UI.php 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217
  1. <?php
  2. // Copyright (C) 2010-2012 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Main page of iTop
  20. *
  21. * @copyright Copyright (C) 2010-2012 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. /**
  25. * Perform all the needed checks to delete one (or more) objects
  26. */
  27. function DeleteObjects(WebPage $oP, $sClass, $aObjects, $bDeleteConfirmed, $oFilter = null)
  28. {
  29. $oDeletionPlan = new DeletionPlan();
  30. foreach($aObjects as $oObj)
  31. {
  32. if ($bDeleteConfirmed)
  33. {
  34. $oObj->DBDeleteTracked(CMDBObject::GetCurrentChange(), null, $oDeletionPlan);
  35. }
  36. else
  37. {
  38. $oObj->CheckToDelete($oDeletionPlan);
  39. }
  40. }
  41. if ($bDeleteConfirmed)
  42. {
  43. if (count($aObjects) == 1)
  44. {
  45. $oObj = $aObjects[0];
  46. $oP->add("<h1>".Dict::Format('UI:Title:DeletionOf_Object', $oObj->GetName())."</h1>\n");
  47. }
  48. else
  49. {
  50. $oP->add("<h1>".Dict::Format('UI:Title:BulkDeletionOf_Count_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass))."</h1>\n");
  51. }
  52. // Security - do not allow the user to force a forbidden delete by the mean of page arguments...
  53. if ($oDeletionPlan->FoundSecurityIssue())
  54. {
  55. throw new CoreException(Dict::S('UI:Error:NotEnoughRightsToDelete'));
  56. }
  57. if ($oDeletionPlan->FoundManualOperation())
  58. {
  59. throw new CoreException(Dict::S('UI:Error:CannotDeleteBecauseManualOpNeeded'));
  60. }
  61. if ($oDeletionPlan->FoundManualDelete())
  62. {
  63. throw new CoreException(Dict::S('UI:Error:CannotDeleteBecauseOfDepencies'));
  64. }
  65. // Report deletions
  66. //
  67. $aDisplayData = array();
  68. foreach ($oDeletionPlan->ListDeletes() as $sTargetClass => $aDeletes)
  69. {
  70. foreach ($aDeletes as $iId => $aData)
  71. {
  72. $oToDelete = $aData['to_delete'];
  73. if (isset($aData['requested_explicitely']))
  74. {
  75. $sMessage = Dict::S('UI:Delete:Deleted');
  76. }
  77. else
  78. {
  79. $sMessage = Dict::S('UI:Delete:AutomaticallyDeleted');
  80. }
  81. $aDisplayData[] = array(
  82. 'class' => MetaModel::GetName(get_class($oToDelete)),
  83. 'object' => $oToDelete->GetName(),
  84. 'consequence' => $sMessage,
  85. );
  86. }
  87. }
  88. // Report updates
  89. //
  90. foreach ($oDeletionPlan->ListUpdates() as $sTargetClass => $aToUpdate)
  91. {
  92. foreach ($aToUpdate as $iId => $aData)
  93. {
  94. $oToUpdate = $aData['to_reset'];
  95. $aDisplayData[] = array(
  96. 'class' => MetaModel::GetName(get_class($oToUpdate)),
  97. 'object' => $oToUpdate->GetHyperLink(),
  98. 'consequence' => Dict::Format('UI:Delete:AutomaticResetOf_Fields', $aData['attributes_list']),
  99. );
  100. }
  101. }
  102. // Report automatic jobs
  103. //
  104. if ($oDeletionPlan->GetTargetCount() > 0)
  105. {
  106. if (count($aObjects) == 1)
  107. {
  108. $oObj = $aObjects[0];
  109. $oP->p(Dict::Format('UI:Delete:CleaningUpRefencesTo_Object', $oObj->GetName()));
  110. }
  111. else
  112. {
  113. $oP->p(Dict::Format('UI:Delete:CleaningUpRefencesTo_Several_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass)));
  114. }
  115. $aDisplayConfig = array();
  116. $aDisplayConfig['class'] = array('label' => 'Class', 'description' => '');
  117. $aDisplayConfig['object'] = array('label' => 'Object', 'description' => '');
  118. $aDisplayConfig['consequence'] = array('label' => 'Done', 'description' => Dict::S('UI:Delete:Done+'));
  119. $oP->table($aDisplayConfig, $aDisplayData);
  120. }
  121. }
  122. else
  123. {
  124. if (count($aObjects) == 1)
  125. {
  126. $oObj = $aObjects[0];
  127. $oP->add("<h1>".Dict::Format('UI:Delete:ConfirmDeletionOf_Name', $oObj->GetName())."</h1>\n");
  128. }
  129. else
  130. {
  131. $oP->add("<h1>".Dict::Format('UI:Delete:ConfirmDeletionOf_Count_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass))."</h1>\n");
  132. }
  133. // Explain what should be done
  134. //
  135. $aDisplayData = array();
  136. foreach ($oDeletionPlan->ListDeletes() as $sTargetClass => $aDeletes)
  137. {
  138. foreach ($aDeletes as $iId => $aData)
  139. {
  140. $oToDelete = $aData['to_delete'];
  141. $bAutoDel = (($aData['mode'] == DEL_SILENT) || ($aData['mode'] == DEL_AUTO));
  142. if (array_key_exists('issue', $aData))
  143. {
  144. if ($bAutoDel)
  145. {
  146. if (isset($aData['requested_explicitely']))
  147. {
  148. $sConsequence = Dict::Format('UI:Delete:CannotDeleteBecause', $aData['issue']);
  149. }
  150. else
  151. {
  152. $sConsequence = Dict::Format('UI:Delete:ShouldBeDeletedAtomaticallyButNotPossible', $aData['issue']);
  153. }
  154. }
  155. else
  156. {
  157. $sConsequence = Dict::Format('UI:Delete:MustBeDeletedManuallyButNotPossible', $aData['issue']);
  158. }
  159. }
  160. else
  161. {
  162. if ($bAutoDel)
  163. {
  164. if (isset($aData['requested_explicitely']))
  165. {
  166. $sConsequence = ''; // not applicable
  167. }
  168. else
  169. {
  170. $sConsequence = Dict::S('UI:Delete:WillBeDeletedAutomatically');
  171. }
  172. }
  173. else
  174. {
  175. $sConsequence = Dict::S('UI:Delete:MustBeDeletedManually');
  176. }
  177. }
  178. $aDisplayData[] = array(
  179. 'class' => MetaModel::GetName(get_class($oToDelete)),
  180. 'object' => $oToDelete->GetHyperLink(),
  181. 'consequence' => $sConsequence,
  182. );
  183. }
  184. }
  185. foreach ($oDeletionPlan->ListUpdates() as $sRemoteClass => $aToUpdate)
  186. {
  187. foreach ($aToUpdate as $iId => $aData)
  188. {
  189. $oToUpdate = $aData['to_reset'];
  190. if (array_key_exists('issue', $aData))
  191. {
  192. $sConsequence = Dict::Format('UI:Delete:CannotUpdateBecause_Issue', $aData['issue']);
  193. }
  194. else
  195. {
  196. $sConsequence = Dict::Format('UI:Delete:WillAutomaticallyUpdate_Fields', $aData['attributes_list']);
  197. }
  198. $aDisplayData[] = array(
  199. 'class' => MetaModel::GetName(get_class($oToUpdate)),
  200. 'object' => $oToUpdate->GetHyperLink(),
  201. 'consequence' => $sConsequence,
  202. );
  203. }
  204. }
  205. $iImpactedIndirectly = $oDeletionPlan->GetTargetCount() - count($aObjects);
  206. if ($iImpactedIndirectly > 0)
  207. {
  208. if (count($aObjects) == 1)
  209. {
  210. $oObj = $aObjects[0];
  211. $oP->p(Dict::Format('UI:Delete:Count_Objects/LinksReferencing_Object', $iImpactedIndirectly, $oObj->GetName()));
  212. }
  213. else
  214. {
  215. $oP->p(Dict::Format('UI:Delete:Count_Objects/LinksReferencingTheObjects', $iImpactedIndirectly));
  216. }
  217. $oP->p(Dict::S('UI:Delete:ReferencesMustBeDeletedToEnsureIntegrity'));
  218. }
  219. if (($iImpactedIndirectly > 0) || $oDeletionPlan->FoundStopper())
  220. {
  221. $aDisplayConfig = array();
  222. $aDisplayConfig['class'] = array('label' => 'Class', 'description' => '');
  223. $aDisplayConfig['object'] = array('label' => 'Object', 'description' => '');
  224. $aDisplayConfig['consequence'] = array('label' => 'Consequence', 'description' => Dict::S('UI:Delete:Consequence+'));
  225. $oP->table($aDisplayConfig, $aDisplayData);
  226. }
  227. if ($oDeletionPlan->FoundStopper())
  228. {
  229. if ($oDeletionPlan->FoundSecurityIssue())
  230. {
  231. $oP->p(Dict::S('UI:Delete:SorryDeletionNotAllowed'));
  232. }
  233. elseif ($oDeletionPlan->FoundManualOperation())
  234. {
  235. $oP->p(Dict::S('UI:Delete:PleaseDoTheManualOperations'));
  236. }
  237. else // $bFoundManualOp
  238. {
  239. $oP->p(Dict::S('UI:Delete:PleaseDoTheManualOperations'));
  240. }
  241. $oAppContext = new ApplicationContext();
  242. $oP->add("<form method=\"post\">\n");
  243. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::ReadParam('transaction_id')."\">\n");
  244. $oP->add("<input type=\"button\" onclick=\"window.history.back();\" value=\"".Dict::S('UI:Button:Back')."\">\n");
  245. $oP->add("<input DISABLED type=\"submit\" name=\"\" value=\"".Dict::S('UI:Button:Delete')."\">\n");
  246. $oP->add($oAppContext->GetForForm());
  247. $oP->add("</form>\n");
  248. }
  249. else
  250. {
  251. $oAppContext = new ApplicationContext();
  252. if (count($aObjects) == 1)
  253. {
  254. $oObj = $aObjects[0];
  255. $id = $oObj->GetKey();
  256. $oP->p('<h1>'.Dict::Format('UI:Delect:Confirm_Object', $oObj->GetHyperLink()).'</h1>');
  257. $oP->add("<form method=\"post\">\n");
  258. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::ReadParam('transaction_id')."\">\n");
  259. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"delete_confirmed\">\n");
  260. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  261. $oP->add("<input type=\"hidden\" name=\"id\" value=\"$id\">\n");
  262. $oP->add("<input type=\"button\" onclick=\"window.history.back();\" value=\"".Dict::S('UI:Button:Back')."\">\n");
  263. $oP->add("<input type=\"submit\" name=\"\" value=\"".Dict::S('UI:Button:Delete')."\">\n");
  264. $oP->add($oAppContext->GetForForm());
  265. $oP->add("</form>\n");
  266. }
  267. else
  268. {
  269. $oP->p('<h1>'.Dict::Format('UI:Delect:Confirm_Count_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass)).'</h1>');
  270. foreach($aObjects as $oObj)
  271. {
  272. $aKeys[] = $oObj->GetKey();
  273. }
  274. $oFilter = new DBObjectSearch($sClass);
  275. $oFilter->AddCondition('id', $aKeys, 'IN');
  276. $oSet = new CMDBobjectSet($oFilter);
  277. $oP->add('<div id="0">');
  278. CMDBAbstractObject::DisplaySet($oP, $oSet, array('display_limit' => false, 'menu' => false));
  279. $oP->add("</div>\n");
  280. $oP->add("<form method=\"post\">\n");
  281. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::ReadParam('transaction_id')."\">\n");
  282. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"bulk_delete_confirmed\">\n");
  283. $oP->add("<input type=\"hidden\" name=\"filter\" value=\"".$oFilter->Serialize()."\">\n");
  284. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  285. foreach($aObjects as $oObj)
  286. {
  287. $oP->add("<input type=\"hidden\" name=\"selectObject[]\" value=\"".$oObj->GetKey()."\">\n");
  288. }
  289. $oP->add("<input type=\"button\" onclick=\"window.history.back();\" value=\"".Dict::S('UI:Button:Back')."\">\n");
  290. $oP->add("<input type=\"submit\" name=\"\" value=\"".Dict::S('UI:Button:Delete')."\">\n");
  291. $oP->add($oAppContext->GetForForm());
  292. $oP->add("</form>\n");
  293. }
  294. }
  295. }
  296. }
  297. /**
  298. * Displays a popup welcome message, once per session at maximum
  299. * until the user unchecks the "Display welcome at startup"
  300. * @param WebPage $oP The current web page for the display
  301. * @return void
  302. */
  303. function DisplayWelcomePopup(WebPage $oP)
  304. {
  305. if (!isset($_SESSION['welcome']))
  306. {
  307. // Check, only once per session, if the popup should be displayed...
  308. // If the user did not already ask for hiding it forever
  309. $bPopup = appUserPreferences::GetPref('welcome_popup', true);
  310. if ($bPopup)
  311. {
  312. $sTemplate = @file_get_contents('../application/templates/welcome_popup.html');
  313. if ($sTemplate !== false)
  314. {
  315. $oTemplate = new DisplayTemplate($sTemplate);
  316. $oP->add("<div id=\"welcome_popup\">");
  317. $oTemplate->Render($oP, array());
  318. $oP->add("<p style=\"float:left\"><input type=\"checkbox\" checked id=\"display_welcome_popup\"/><label for=\"display_welcome_popup\">&nbsp;".Dict::S('UI:DisplayThisMessageAtStartup')."</label></p>\n");
  319. $oP->add("<p style=\"float:right\"><input type=\"button\" value=\"".Dict::S('UI:Button:Ok')."\" onClick=\"$('#welcome_popup').dialog('close');\"/>\n");
  320. $oP->add("</div>\n");
  321. $sTitle = addslashes(Dict::S('UI:WelcomeMenu:Title'));
  322. $oP->add_ready_script(
  323. <<<EOF
  324. $('#welcome_popup').dialog( { width:'80%', height: 'auto', title: '$sTitle', autoOpen: true, modal:true,
  325. close: function() {
  326. var bDisplay = $('#display_welcome_popup:checked').length;
  327. SetUserPreference('welcome_popup', bDisplay, true);
  328. }
  329. });
  330. if ($('#welcome_popup').height() > ($(window).height()-70))
  331. {
  332. $('#welcome_popup').height($(window).height()-70);
  333. }
  334. EOF
  335. );
  336. $_SESSION['welcome'] = 'ok';
  337. }
  338. }
  339. }
  340. }
  341. /**
  342. * Apply the 'next-action' to the given object or redirect to the page that prompts for additional information if needed
  343. * @param $oP WebPage The page for the output
  344. * @param $oObj CMDBObject The object to process
  345. * @param $sNextAction string The code of the stimulus for the 'action' (i.e. Transition) to apply
  346. */
  347. function ApplyNextAction(Webpage $oP, CMDBObject $oObj, $sNextAction)
  348. {
  349. // Here handle the apply stimulus
  350. $aTransitions = $oObj->EnumTransitions();
  351. $aStimuli = MetaModel::EnumStimuli(get_class($oObj));
  352. if (!isset($aTransitions[$sNextAction]))
  353. {
  354. // Invalid stimulus
  355. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sNextAction, $oObj->GetName(), $oObj->GetStateLabel()));
  356. }
  357. // Get the list of missing mandatory fields for the target state, considering only the changes from the previous form (i.e don't prompt twice)
  358. $aExpectedAttributes = $oObj->GetExpectedAttributes($oObj->GetState(), $sNextAction, true /* $bOnlyNewOnes */);
  359. if (count($aExpectedAttributes) == 0)
  360. {
  361. // If all the mandatory fields are already present, just apply the transition silently...
  362. if ($oObj->ApplyStimulus($sNextAction))
  363. {
  364. $oObj->DBUpdate();
  365. }
  366. ReloadAndDisplay($oP, $oObj);
  367. }
  368. else
  369. {
  370. // redirect to the 'stimulus' action
  371. $oAppContext = new ApplicationContext();
  372. //echo "<p>Missing Attributes <pre>".print_r($aExpectedAttributes, true)."</pre></p>\n";
  373. $oP->add_header('Location: '.utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=stimulus&class='.get_class($oObj).'&stimulus='.$sNextAction.'&id='.$oObj->getKey().'&'.$oAppContext->GetForLink());
  374. }
  375. }
  376. function ReloadAndDisplay($oPage, $oObj, $sMessage = '', $sSeverity)
  377. {
  378. $oAppContext = new ApplicationContext();
  379. $sMessageKey = get_class($oObj).'::'.$oObj->GetKey();
  380. if ($sMessage != '')
  381. {
  382. $_SESSION['obj_messages'][$sMessageKey] = array('severity' => $sSeverity, 'message' => $sMessage);
  383. }
  384. $oPage->add_header('Location: '.utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=details&class='.get_class($oObj).'&id='.$oObj->getKey().'&'.$oAppContext->GetForLink());
  385. }
  386. /**
  387. * Displays the details of an object
  388. * @param $oP WebPage Page for the output
  389. * @param $sClass string The name of the class of the object
  390. * @param $oObj DBObject The object to display
  391. * @param $id mixed Identifier of the object (name or ID)
  392. */
  393. function DisplayDetails($oP, $sClass, $oObj, $id)
  394. {
  395. $sClassLabel = MetaModel::GetName($sClass);
  396. $oSearch = new DBObjectSearch($sClass);
  397. $oBlock = new DisplayBlock($oSearch, 'search', false);
  398. $oBlock->Display($oP, 0);
  399. // The object could be listed, check if it is actually allowed to view it
  400. $oSet = CMDBObjectSet::FromObject($oObj);
  401. if (UserRights::IsActionAllowed($sClass, UR_ACTION_READ, $oSet) == UR_ALLOWED_NO)
  402. {
  403. throw new SecurityException('User not allowed to view this object', array('class' => $sClass, 'id' => $id));
  404. }
  405. $oP->set_title(Dict::Format('UI:DetailsPageTitle', $oObj->GetRawName(), $sClassLabel)); // Set title will take care of the encoding
  406. $oObj->DisplayDetails($oP);
  407. }
  408. /**
  409. * Displays the result of a search request
  410. * @param $oP WebPage Web page for the output
  411. * @param $oFilter DBObjectSearch The search of objects to display
  412. * @param $bSearchForm boolean Whether or not to display the search form at the top the page
  413. * @param $sBaseClass string The base class for the search (can be different from the actual class of the results)
  414. * @param $sFormat string The format to use for the output: csv or html
  415. */
  416. function DisplaySearchSet($oP, $oFilter, $bSearchForm = true, $sBaseClass = '', $sFormat = '')
  417. {
  418. if ($bSearchForm)
  419. {
  420. $aParams = array('open' => true);
  421. if (!empty($sBaseClass))
  422. {
  423. $aParams['baseClass'] = $sBaseClass;
  424. }
  425. $oBlock = new DisplayBlock($oFilter, 'search', false /* Asynchronous */, $aParams);
  426. $oBlock->Display($oP, 0);
  427. }
  428. if (strtolower($sFormat) == 'csv')
  429. {
  430. $oBlock = new DisplayBlock($oFilter, 'csv', false);
  431. $oBlock->Display($oP, 1);
  432. // Adjust the size of the Textarea containing the CSV to fit almost all the remaining space
  433. $oP->add_ready_script(" $('#1>textarea').height($('#1').parent().height() - $('#0').outerHeight() - 30).width( $('#1').parent().width() - 20);"); // adjust the size of the block
  434. }
  435. else
  436. {
  437. $oBlock = new DisplayBlock($oFilter, 'list', false);
  438. $oBlock->Display($oP, 1);
  439. }
  440. }
  441. /**
  442. * Displays a form (checkboxes) to select the objects for which to apply a given action
  443. * Only the objects for which the action is valid can be checked. By default all valid objects are checked
  444. * @param $oP WebPage The page for output
  445. * @param $oFilter DBObjectSearch The filter that defines the list of objects
  446. * @param $sNextOperation string The next operation (code) to be executed when the form is submitted
  447. * @param $oChecker ActionChecker The helper class/instance used to check for which object the action is valid
  448. * @return none
  449. */
  450. function DisplayMultipleSelectionForm($oP, $oFilter, $sNextOperation, $oChecker, $aExtraFormParams = array())
  451. {
  452. $oAppContext = new ApplicationContext();
  453. $iBulkActionAllowed = $oChecker->IsAllowed();
  454. $sClass = $oFilter->GetClass();
  455. $aExtraParams = array('selection_type' => 'multiple', 'selection_mode' => true, 'display_limit' => false, 'menu' => false);
  456. if ($iBulkActionAllowed == UR_ALLOWED_DEPENDS)
  457. {
  458. $aAllowed = array();
  459. $aExtraParams['selection_enabled'] = $oChecker->GetAllowedIDs();
  460. }
  461. else if(UR_ALLOWED_NO)
  462. {
  463. throw new ApplicationException(Dict::Format('UI:ActionNotAllowed'));
  464. }
  465. $oBlock = new DisplayBlock($oFilter, 'list', false);
  466. $oP->add("<form method=\"post\" action=\"./UI.php\">\n");
  467. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  468. $oP->add("<input type=\"hidden\" name=\"class\" value=\"".$oFilter->GetClass()."\">\n");
  469. $oP->add("<input type=\"hidden\" name=\"filter\" value=\"".$oFilter->Serialize()."\">\n");
  470. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  471. foreach($aExtraFormParams as $sName => $sValue)
  472. {
  473. $oP->add("<input type=\"hidden\" name=\"$sName\" value=\"$sValue\">\n");
  474. }
  475. $oP->add($oAppContext->GetForForm());
  476. $oBlock->Display($oP, 1, $aExtraParams);
  477. $oP->add("<input type=\"button\" value=\"".Dict::S('UI:Button:Cancel')."\" onClick=\"window.history.back()\">&nbsp;&nbsp;<input type=\"submit\" value=\"".Dict::S('UI:Button:Next')."\">\n");
  478. $oP->add("</form>\n");
  479. $oP->add_ready_script("$('#1 table.listResults').trigger('check_all');");
  480. }
  481. /***********************************************************************************
  482. *
  483. * Main user interface page, starts here
  484. *
  485. * ***********************************************************************************/
  486. try
  487. {
  488. require_once('../approot.inc.php');
  489. require_once(APPROOT.'/application/application.inc.php');
  490. require_once(APPROOT.'/application/itopwebpage.class.inc.php');
  491. require_once(APPROOT.'/application/wizardhelper.class.inc.php');
  492. require_once(APPROOT.'/application/startup.inc.php');
  493. $operation = utils::ReadParam('operation', '');
  494. $oKPI = new ApplicationStartupKPI();
  495. $oKPI->ComputeAndReport('Load of data model and all includes');
  496. $oKPI = new ExecutionKPI();
  497. require_once(APPROOT.'/application/loginwebpage.class.inc.php');
  498. $sLoginMessage = LoginWebPage::DoLogin(); // Check user rights and prompt if needed
  499. $oAppContext = new ApplicationContext();
  500. $oKPI->ComputeAndReport('User login');
  501. $oP = new iTopWebPage(Dict::S('UI:WelcomeToITop'));
  502. $oP->SetMessage($sLoginMessage);
  503. // All the following actions use advanced forms that require more javascript to be loaded
  504. switch($operation)
  505. {
  506. case 'new': // Form to create a new object
  507. case 'modify': // Form to modify an object
  508. case 'apply_new': // Creation of a new object
  509. case 'apply_modify': // Applying the modifications to an existing object
  510. case 'form_for_modify_all': // Form to modify multiple objects (bulk modify)
  511. case 'bulk_stimulus': // For to apply a stimulus to multiple objects
  512. case 'stimulus': // Form displayed when applying a stimulus (state change)
  513. $oP->add_linked_script("../js/json.js");
  514. $oP->add_linked_script("../js/forms-json-utils.js");
  515. $oP->add_linked_script("../js/wizardhelper.js");
  516. $oP->add_linked_script("../js/wizard.utils.js");
  517. $oP->add_linked_script("../js/linkswidget.js");
  518. $oP->add_linked_script("../js/linksdirectwidget.js");
  519. $oP->add_linked_script("../js/extkeywidget.js");
  520. $oP->add_linked_script("../js/jquery.blockUI.js");
  521. break;
  522. }
  523. switch($operation)
  524. {
  525. ///////////////////////////////////////////////////////////////////////////////////////////
  526. case 'details': // Details of an object
  527. $sClass = utils::ReadParam('class', '');
  528. $id = utils::ReadParam('id', '');
  529. if ( empty($sClass) || empty($id))
  530. {
  531. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'id'));
  532. }
  533. if (is_numeric($id))
  534. {
  535. $oObj = MetaModel::GetObject($sClass, $id, false /* MustBeFound */);
  536. }
  537. else
  538. {
  539. $oObj = MetaModel::GetObjectByName($sClass, $id, false /* MustBeFound */);
  540. }
  541. if (is_null($oObj))
  542. {
  543. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  544. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  545. }
  546. else
  547. {
  548. DisplayDetails($oP, $sClass, $oObj, $id);
  549. }
  550. break;
  551. ///////////////////////////////////////////////////////////////////////////////////////////
  552. case 'search_oql': // OQL query
  553. $sOQLClass = utils::ReadParam('oql_class', '', false, 'class');
  554. $sBaseClass = utils::ReadParam('base_class', $sOQLClass, false, 'class');
  555. $sOQLClause = utils::ReadParam('oql_clause', '', false, 'raw_data');
  556. $sFormat = utils::ReadParam('format', '');
  557. $bSearchForm = utils::ReadParam('search_form', true);
  558. $sTitle = utils::ReadParam('title', 'UI:SearchResultsPageTitle');
  559. if (empty($sOQLClass))
  560. {
  561. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'oql_class'));
  562. }
  563. $oP->set_title(Dict::S($sTitle));
  564. $oP->add('<h1>'.Dict::S($sTitle).'</h1>');
  565. $sOQL = "SELECT $sOQLClass $sOQLClause";
  566. try
  567. {
  568. $oFilter = DBObjectSearch::FromOQL($sOQL);
  569. DisplaySearchSet($oP, $oFilter, $bSearchForm, $sBaseClass, $sFormat);
  570. }
  571. catch(CoreException $e)
  572. {
  573. $oFilter = new DBObjectSearch($sOQLClass);
  574. $oSet = new DBObjectSet($oFilter);
  575. if ($bSearchForm)
  576. {
  577. $oBlock = new DisplayBlock($oFilter, 'search', false);
  578. $oBlock->Display($oP, 0);
  579. }
  580. $oP->P('<b>'.Dict::Format('UI:Error:IncorrectOQLQuery_Message', $e->getHtmlDesc()).'</b>');
  581. }
  582. catch(Exception $e)
  583. {
  584. $oP->P('<b>'.Dict::Format('UI:Error:AnErrorOccuredWhileRunningTheQuery_Message', $e->getMessage()).'</b>');
  585. }
  586. break;
  587. ///////////////////////////////////////////////////////////////////////////////////////////
  588. case 'search_form': // Search form
  589. $sClass = utils::ReadParam('class', '', false, 'class');
  590. $sFormat = utils::ReadParam('format', 'html');
  591. $bSearchForm = utils::ReadParam('search_form', true);
  592. if (empty($sClass))
  593. {
  594. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'class'));
  595. }
  596. $oP->set_title(Dict::S('UI:SearchResultsPageTitle'));
  597. $oFilter = new DBObjectSearch($sClass);
  598. DisplaySearchSet($oP, $oFilter, $bSearchForm, '' /* sBaseClass */, $sFormat);
  599. break;
  600. ///////////////////////////////////////////////////////////////////////////////////////////
  601. case 'search': // Serialized CMDBSearchFilter
  602. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  603. $sFormat = utils::ReadParam('format', '');
  604. $bSearchForm = utils::ReadParam('search_form', true);
  605. if (empty($sFilter))
  606. {
  607. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'filter'));
  608. }
  609. $oP->set_title(Dict::S('UI:SearchResultsPageTitle'));
  610. // TO DO: limit the search filter by the user context
  611. $oFilter = CMDBSearchFilter::unserialize($sFilter); // TO DO : check that the filter is valid
  612. DisplaySearchSet($oP, $oFilter, $bSearchForm, '' /* sBaseClass */, $sFormat);
  613. break;
  614. ///////////////////////////////////////////////////////////////////////////////////////////
  615. case 'full_text': // Global "google-like" search
  616. $sFullText = trim(utils::ReadParam('text', '', false, 'raw_data'));
  617. if (empty($sFullText))
  618. {
  619. $oP->p(Dict::S('UI:Search:NoSearch'));
  620. }
  621. else
  622. {
  623. $oP->set_title(Dict::S('UI:SearchResultsPageTitle'));
  624. $oP->p("<h1>".Dict::Format('UI:FullTextSearchTitle_Text', $sFullText)."</h1>");
  625. $iCount = 0;
  626. $iBlock = 0;
  627. // Search in full text mode in all the classes
  628. $aMatches = array();
  629. $sClassName = '';
  630. // Check if a class name/label is supplied to limit the search
  631. if (preg_match('/^(.+):(.+)$/', $sFullText, $aMatches))
  632. {
  633. $sClassName = $aMatches[1];
  634. if (MetaModel::IsValidClass($sClassName))
  635. {
  636. $sFullText = $aMatches[2];
  637. }
  638. elseif ($sClassName = MetaModel::GetClassFromLabel($sClassName, false /* => not case sensitive */))
  639. {
  640. $sFullText = $aMatches[2];
  641. }
  642. }
  643. if (preg_match('/^"(.*)"$/', $sFullText, $aMatches))
  644. {
  645. // The text is surrounded by double-quotes, remove the quotes and treat it as one single expression
  646. $aFullTextNeedles = array($aMatches[1]);
  647. }
  648. else
  649. {
  650. // Split the text on the blanks and treat this as a search for <word1> AND <word2> AND <word3>
  651. $aFullTextNeedles = explode(' ', $sFullText);
  652. }
  653. // Search is limited ot a given class, or not...
  654. if (empty($sClassName))
  655. {
  656. $aSearchClasses = MetaModel::GetClasses('searchable');
  657. }
  658. else
  659. {
  660. $aSearchClasses = MetaModel::EnumChildClasses($sClassName, ENUM_CHILD_CLASSES_ALL);
  661. }
  662. foreach($aSearchClasses as $sClassName)
  663. {
  664. $oFilter = new DBObjectSearch($sClassName);
  665. foreach($aFullTextNeedles as $sSearchText)
  666. {
  667. $oFilter->AddCondition_FullText($sSearchText);
  668. }
  669. $oSet = new DBObjectSet($oFilter);
  670. if ($oSet->Count() > 0)
  671. {
  672. $aLeafs = array();
  673. while($oObj = $oSet->Fetch())
  674. {
  675. if (get_class($oObj) == $sClassName)
  676. {
  677. $aLeafs[] = $oObj->GetKey();
  678. }
  679. }
  680. $oLeafsFilter = new DBObjectSearch($sClassName);
  681. if (count($aLeafs) > 0)
  682. {
  683. $iCount += count($aLeafs);
  684. $oP->add("<div class=\"page_header\">\n");
  685. $oP->add("<h2>".MetaModel::GetClassIcon($sClassName)."&nbsp;<span class=\"hilite\">".Dict::Format('UI:Search:Count_ObjectsOf_Class_Found', count($aLeafs), Metamodel::GetName($sClassName))."</h2>\n");
  686. $oP->add("</div>\n");
  687. $oLeafsFilter->AddCondition('id', $aLeafs, 'IN');
  688. $oBlock = new DisplayBlock($oLeafsFilter, 'list', false);
  689. $oBlock->Display($oP, $iBlock++, array('table_id' => 'global_search'));
  690. $oP->P('&nbsp;'); // Some space ?
  691. }
  692. }
  693. }
  694. if ($iCount == 0)
  695. {
  696. $oP->p(Dict::S('UI:Search:NoObjectFound'));
  697. }
  698. }
  699. break;
  700. ///////////////////////////////////////////////////////////////////////////////////////////
  701. case 'modify': // Form to modify an object
  702. $sClass = utils::ReadParam('class', '', false, 'class');
  703. $sClassLabel = MetaModel::GetName($sClass);
  704. $id = utils::ReadParam('id', '');
  705. if ( empty($sClass) || empty($id)) // TO DO: check that the class name is valid !
  706. {
  707. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'id'));
  708. }
  709. // Check if the user can modify this object
  710. $oObj = MetaModel::GetObject($sClass, $id, false /* MustBeFound */);
  711. if (is_null($oObj))
  712. {
  713. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  714. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  715. }
  716. else
  717. {
  718. // The object could be read - check if it is allowed to modify it
  719. $oSet = CMDBObjectSet::FromObject($oObj);
  720. if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet) == UR_ALLOWED_NO)
  721. {
  722. throw new SecurityException('User not allowed to modify this object', array('class' => $sClass, 'id' => $id));
  723. }
  724. // Note: code duplicated to the case 'apply_modify' when a data integrity issue has been found
  725. $oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetRawName(), $sClassLabel)); // Set title will take care of the encoding
  726. $oP->add("<div class=\"page_header\">\n");
  727. $oP->add("<h1>".$oObj->GetIcon()."&nbsp;".Dict::Format('UI:ModificationTitle_Class_Object', $sClassLabel, $oObj->GetName())."</h1>\n");
  728. $oP->add("</div>\n");
  729. $oP->add("<div class=\"wizContainer\">\n");
  730. $oObj->DisplayModifyForm($oP);
  731. $oP->add("</div>\n");
  732. }
  733. break;
  734. ///////////////////////////////////////////////////////////////////////////////////////////
  735. case 'select_for_modify_all': // Select the list of objects to be modified (bulk modify)
  736. $oP->set_title(Dict::S('UI:ModifyAllPageTitle'));
  737. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  738. if (empty($sFilter))
  739. {
  740. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'filter'));
  741. }
  742. // TO DO: limit the search filter by the user context
  743. $oFilter = DBObjectSearch::unserialize($sFilter); // TO DO : check that the filter is valid
  744. $sClass = $oFilter->GetClass();
  745. $oChecker = new ActionChecker($oFilter, UR_ACTION_BULK_MODIFY);
  746. $oP->add("<h1>Modify All...</h1>\n");
  747. DisplayMultipleSelectionForm($oP, $oFilter, 'form_for_modify_all', $oChecker);
  748. break;
  749. ///////////////////////////////////////////////////////////////////////////////////////////
  750. case 'form_for_modify_all': // Form to modify multiple objects (bulk modify)
  751. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  752. $sClass = utils::ReadParam('class', '', false, 'class');
  753. $oFullSetFilter = DBObjectSearch::unserialize($sFilter);
  754. $aSelectedObj = utils::ReadMultipleSelection($oFullSetFilter);
  755. if (count($aSelectedObj) > 0)
  756. {
  757. $iAllowedCount = count($aSelectedObj);
  758. $sSelectedObj = implode(',', $aSelectedObj);
  759. $sOQL = "SELECT $sClass WHERE id IN (".$sSelectedObj.")";
  760. $oSet = new CMDBObjectSet(DBObjectSearch::FromOQL($sOQL));
  761. // Compute the distribution of the values for each field to determine which of the "scalar" fields are homogenous
  762. $aList = MetaModel::ListAttributeDefs($sClass);
  763. $aValues = array();
  764. foreach($aList as $sAttCode => $oAttDef)
  765. {
  766. if ($oAttDef->IsScalar())
  767. {
  768. $aValues[$sAttCode] = array();
  769. }
  770. }
  771. while($oObj = $oSet->Fetch())
  772. {
  773. foreach($aList as $sAttCode => $oAttDef)
  774. {
  775. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  776. {
  777. $currValue = $oObj->Get($sAttCode);
  778. if ($oAttDef instanceof AttributeCaseLog)
  779. {
  780. $currValue = ' '; // Don't put an empty string, in case the field would be considered as mandatory...
  781. }
  782. if (is_object($currValue)) continue; // Skip non scalar values...
  783. if(!array_key_exists($currValue, $aValues[$sAttCode]))
  784. {
  785. $aValues[$sAttCode][$currValue] = array('count' => 1, 'display' => $oObj->GetAsHTML($sAttCode));
  786. }
  787. else
  788. {
  789. $aValues[$sAttCode][$currValue]['count']++;
  790. }
  791. }
  792. }
  793. }
  794. // Now create an object that has values for the homogenous values only
  795. $oDummyObj = new $sClass(); // @@ What if the class is abstract ?
  796. $aComments = array();
  797. function MyComparison($a, $b) // Sort descending
  798. {
  799. if ($a['count'] == $b['count'])
  800. {
  801. return 0;
  802. }
  803. return ($a['count'] > $b['count']) ? -1 : 1;
  804. }
  805. $iFormId = cmdbAbstractObject::GetNextFormId(); // Identifier that prefixes all the form fields
  806. $sReadyScript = '';
  807. $aDependsOn = array();
  808. $sFormPrefix = '2_';
  809. foreach($aList as $sAttCode => $oAttDef)
  810. {
  811. $aPrerequisites = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  812. if (count($aPrerequisites) > 0)
  813. {
  814. // When 'enabling' a field, all its prerequisites must be enabled too
  815. $sFieldList = "['{$sFormPrefix}".implode("','{$sFormPrefix}", $aPrerequisites)."']";
  816. $oP->add_ready_script("$('#enable_{$sFormPrefix}{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, true); } );\n");
  817. }
  818. $aDependents = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  819. if (count($aDependents) > 0)
  820. {
  821. // When 'disabling' a field, all its dependent fields must be disabled too
  822. $sFieldList = "['{$sFormPrefix}".implode("','{$sFormPrefix}", $aDependents)."']";
  823. $oP->add_ready_script("$('#enable_{$sFormPrefix}{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, false); } );\n");
  824. }
  825. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  826. {
  827. if ($oAttDef->GetEditClass() == 'One Way Password')
  828. {
  829. $sTip = "Unknown values";
  830. $sReadyScript .= "$('#multi_values_$sAttCode').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );";
  831. $oDummyObj->Set($sAttCode, null);
  832. $aComments[$sAttCode] = '<input type="checkbox" id="enable_'.$iFormId.'_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$iFormId.'_'.$sAttCode.'\')"/>';
  833. $aComments[$sAttCode] .= '<div class="multi_values" id="multi_values_'.$sAttCode.'"> ? </div>';
  834. $sReadyScript .= 'ToogleField(false, \''.$iFormId.'_'.$sAttCode.'\');'."\n";
  835. }
  836. else
  837. {
  838. $iCount = count($aValues[$sAttCode]);
  839. if ($iCount == 1)
  840. {
  841. // Homogenous value
  842. reset($aValues[$sAttCode]);
  843. $aKeys = array_keys($aValues[$sAttCode]);
  844. $currValue = $aKeys[0]; // The only value is the first key
  845. //echo "<p>current value for $sAttCode : $currValue</p>";
  846. $oDummyObj->Set($sAttCode, $currValue);
  847. $aComments[$sAttCode] = '<input type="checkbox" checked id="enable_'.$iFormId.'_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$iFormId.'_'.$sAttCode.'\')"/>';
  848. $aComments[$sAttCode] .= '<div class="mono_value">1</div>';
  849. }
  850. else
  851. {
  852. // Non-homogenous value
  853. $aMultiValues = $aValues[$sAttCode];
  854. uasort($aMultiValues, 'MyComparison');
  855. $iMaxCount = 5;
  856. $sTip = "<p><b>".Dict::Format('UI:BulkModify_Count_DistinctValues', $iCount)."</b><ul>";
  857. $index = 0;
  858. foreach($aMultiValues as $sCurrValue => $aVal)
  859. {
  860. $sDisplayValue = empty($aVal['display']) ? '<i>'.Dict::S('Enum:Undefined').'</i>' : str_replace(array("\n", "\r"), " ", $aVal['display']);
  861. $sTip .= "<li>".Dict::Format('UI:BulkModify:Value_Exists_N_Times', $sDisplayValue, $aVal['count'])."</li>";
  862. $index++;
  863. if ($iMaxCount == $index)
  864. {
  865. $sTip .= "<li>".Dict::Format('UI:BulkModify:N_MoreValues', count($aMultiValues) - $iMaxCount)."</li>";
  866. break;
  867. }
  868. }
  869. $sTip .= "</ul></p>";
  870. $sTip = addslashes($sTip);
  871. $sReadyScript .= "$('#multi_values_$sAttCode').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );";
  872. $oDummyObj->Set($sAttCode, null);
  873. $aComments[$sAttCode] = '<input type="checkbox" id="enable_'.$iFormId.'_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$iFormId.'_'.$sAttCode.'\')"/>';
  874. $aComments[$sAttCode] .= '<div class="multi_values" id="multi_values_'.$sAttCode.'">'.$iCount.'</div>';
  875. }
  876. $sReadyScript .= 'ToogleField('.(($iCount == 1) ? 'true': 'false').', \''.$iFormId.'_'.$sAttCode.'\');'."\n";
  877. }
  878. }
  879. }
  880. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  881. if (($sStateAttCode != '') && ($oDummyObj->GetState() == ''))
  882. {
  883. // Hmmm, it's not gonna work like this ! Set a default value for the "state"
  884. // Maybe we should use the "state" that is the most common among the objects...
  885. $aMultiValues = $aValues[$sStateAttCode];
  886. uasort($aMultiValues, 'MyComparison');
  887. foreach($aMultiValues as $sCurrValue => $aVal)
  888. {
  889. $oDummyObj->Set($sStateAttCode, $sCurrValue);
  890. break;
  891. }
  892. //$oStateAtt = MetaModel::GetAttributeDef($sClass, $sStateAttCode);
  893. //$oDummyObj->Set($sStateAttCode, $oStateAtt->GetDefaultValue());
  894. }
  895. $oP->add("<div class=\"page_header\">\n");
  896. $oP->add("<h1>".$oDummyObj->GetIcon()."&nbsp;".Dict::Format('UI:Modify_M_ObjectsOf_Class_OutOf_N', $iAllowedCount, $sClass, $iAllowedCount)."</h1>\n");
  897. $oP->add("</div>\n");
  898. $oP->add("<div class=\"wizContainer\">\n");
  899. $oDummyObj->DisplayModifyForm($oP, array('fieldsComments' => $aComments, 'noRelations' => true, 'custom_operation' => 'preview_or_modify_all', 'custom_button' => Dict::S('UI:Button:PreviewModifications'), 'selectObj' => $sSelectedObj, 'filter' => $sFilter, 'preview_mode' => true, 'disabled_fields' => '{}', 'disable_plugins' => true));
  900. $oP->add("</div>\n");
  901. $oP->add_ready_script($sReadyScript);
  902. $sURL = "./UI.php?operation=search&filter=".urlencode($sFilter)."&".$oAppContext->GetForLink();
  903. $oP->add_ready_script(
  904. <<<EOF
  905. $('.wizContainer button.cancel').unbind('click');
  906. $('.wizContainer button.cancel').click( function() { window.location.href = '$sURL'; } );
  907. EOF
  908. );
  909. } // Else no object selected ???
  910. else
  911. {
  912. $oP->p("No object selected !, nothing to do");
  913. }
  914. break;
  915. ///////////////////////////////////////////////////////////////////////////////////////////
  916. case 'preview_or_modify_all': // Preview or apply bulk modify
  917. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  918. // TO DO: limit the search filter by the user context
  919. $oFilter = DBObjectSearch::unserialize($sFilter); // TO DO : check that the filter is valid
  920. $oChecker = new ActionChecker($oFilter, UR_ACTION_BULK_MODIFY);
  921. $sClass = utils::ReadParam('class', '', false, 'class');
  922. $bPreview = utils::ReadParam('preview_mode', '');
  923. $sSelectedObj = utils::ReadParam('selectObj', '', false, 'raw_data');
  924. if ( empty($sClass) || empty($sSelectedObj)) // TO DO: check that the class name is valid !
  925. {
  926. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'selectObj'));
  927. }
  928. $aSelectedObj = explode(',', $sSelectedObj);
  929. $aHeaders = array(
  930. 'form::select' => array('label' => "<input type=\"checkbox\" onClick=\"CheckAll('.selectList:not(:disabled)', this.checked);\"></input>", 'description' => Dict::S('UI:SelectAllToggle+')),
  931. 'object' => array('label' => MetaModel::GetName($sClass), 'description' => Dict::S('UI:ModifiedObject')),
  932. 'status' => array('label' => Dict::S('UI:BulkModifyStatus'), 'description' => Dict::S('UI:BulkModifyStatus+')),
  933. 'errors' => array('label' => Dict::S('UI:BulkModifyErrors'), 'description' => Dict::S('UI:BulkModifyErrors+')),
  934. );
  935. $aRows = array();
  936. $oP->add("<div class=\"page_header\">\n");
  937. $oP->add("<h1>".MetaModel::GetClassIcon($sClass)."&nbsp;".Dict::Format('UI:Modify_N_ObjectsOf_Class', count($aSelectedObj), $sClass)."</h1>\n");
  938. $oP->add("</div>\n");
  939. $oP->set_title(Dict::Format('UI:Modify_N_ObjectsOf_Class', count($aSelectedObj), $sClass));
  940. if (!$bPreview)
  941. {
  942. // Not in preview mode, do the update for real
  943. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  944. if (!utils::IsTransactionValid($sTransactionId, false))
  945. {
  946. throw new Exception(Dict::S('UI:Error:ObjectAlreadyUpdated'));
  947. }
  948. utils::RemoveTransaction($sTransactionId);
  949. }
  950. foreach($aSelectedObj as $iId)
  951. {
  952. $oObj = MetaModel::GetObject($sClass, $iId);
  953. $aErrors = $oObj->UpdateObjectFromPostedForm('');
  954. $bResult = (count($aErrors) == 0);
  955. if ($bResult)
  956. {
  957. list($bResult, $aErrors) = $oObj->CheckToWrite(true /* Enforce Read-only fields */);
  958. }
  959. if ($bPreview)
  960. {
  961. $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusOk') : Dict::S('UI:BulkModifyStatusError');
  962. }
  963. else
  964. {
  965. $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusModified') : Dict::S('UI:BulkModifyStatusSkipped');
  966. }
  967. $sCSSClass = $bResult ? HILIGHT_CLASS_NONE : HILIGHT_CLASS_CRITICAL;
  968. $sChecked = $bResult ? 'checked' : '';
  969. $sDisabled = $bResult ? '' : 'disabled';
  970. $aRows[] = array(
  971. 'form::select' => "<input type=\"checkbox\" class=\"selectList\" $sChecked $sDisabled\"></input>",
  972. 'object' => $oObj->GetHyperlink(),
  973. 'status' => $sStatus,
  974. 'errors' => '<p>'.($bResult ? '': implode('</p><p>', $aErrors)).'</p>',
  975. '@class' => $sCSSClass,
  976. );
  977. if ($bResult && (!$bPreview))
  978. {
  979. $oObj->DBUpdate();
  980. }
  981. }
  982. $oP->Table($aHeaders, $aRows);
  983. $sURL = "./UI.php?operation=search&filter=".urlencode($sFilter)."&".$oAppContext->GetForLink();
  984. if ($bPreview)
  985. {
  986. // Form to submit:
  987. $oP->add("<form method=\"post\" action=\"UI.php\" enctype=\"multipart/form-data\">\n");
  988. $aDefaults = utils::ReadParam('default', array());
  989. $oP->add($oAppContext->GetForForm());
  990. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  991. $oP->add("<input type=\"hidden\" name=\"filter\" value=\"$sFilter\">\n");
  992. $oP->add("<input type=\"hidden\" name=\"selectObj\" value=\"$sSelectedObj\">\n");
  993. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"preview_or_modify_all\">\n");
  994. $oP->add("<input type=\"hidden\" name=\"preview_mode\" value=\"0\">\n");
  995. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  996. $oP->add("<button type=\"button\" class=\"action cancel\" onClick=\"window.location.href='$sURL'\">".Dict::S('UI:Button:Cancel')."</button>&nbsp;&nbsp;&nbsp;&nbsp;\n");
  997. $oP->add("<button type=\"submit\" class=\"action\"><span>".Dict::S('UI:Button:ModifyAll')."</span></button>\n");
  998. foreach($_POST as $sKey => $value)
  999. {
  1000. if (preg_match('/attr_(.+)/', $sKey, $aMatches))
  1001. {
  1002. // Beware: some values (like durations) are passed as arrays
  1003. if (is_array($value))
  1004. {
  1005. foreach($value as $vKey => $vValue)
  1006. {
  1007. $oP->add("<input type=\"hidden\" name=\"{$sKey}[$vKey]\" value=\"$vValue\">\n");
  1008. }
  1009. }
  1010. else
  1011. {
  1012. $oP->add("<input type=\"hidden\" name=\"$sKey\" value=\"$value\">\n");
  1013. }
  1014. }
  1015. }
  1016. $oP->add("</form>\n");
  1017. }
  1018. else
  1019. {
  1020. $sURL = "./UI.php?operation=search&filter=".urlencode($sFilter)."&".$oAppContext->GetForLink();
  1021. $oP->add("<button type=\"button\" onClick=\"window.location.href='$sURL'\" class=\"action\"><span>".Dict::S('UI:Button:Done')."</span></button>\n");
  1022. }
  1023. break;
  1024. ///////////////////////////////////////////////////////////////////////////////////////////
  1025. case 'new': // Form to create a new object
  1026. $sClass = utils::ReadParam('class', '', false, 'class');
  1027. $sStateCode = utils::ReadParam('state', '');
  1028. $bCheckSubClass = utils::ReadParam('checkSubclass', true);
  1029. if ( empty($sClass) )
  1030. {
  1031. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'class'));
  1032. }
  1033. $aArgs = utils::ReadParam('default', array(), false, 'raw_data');
  1034. $aContext = $oAppContext->GetAsHash();
  1035. foreach( $oAppContext->GetNames() as $key)
  1036. {
  1037. $aArgs[$key] = $oAppContext->GetCurrentValue($key);
  1038. }
  1039. // If the specified class has subclasses, ask the user an instance of which class to create
  1040. $aSubClasses = MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL); // Including the specified class itself
  1041. $aPossibleClasses = array();
  1042. $sRealClass = '';
  1043. if ($bCheckSubClass)
  1044. {
  1045. foreach($aSubClasses as $sCandidateClass)
  1046. {
  1047. if (!MetaModel::IsAbstract($sCandidateClass) && (UserRights::IsActionAllowed($sCandidateClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES))
  1048. {
  1049. $aPossibleClasses[$sCandidateClass] = MetaModel::GetName($sCandidateClass);
  1050. }
  1051. }
  1052. // Only one of the subclasses can be instantiated...
  1053. if (count($aPossibleClasses) == 1)
  1054. {
  1055. $aKeys = array_keys($aPossibleClasses);
  1056. $sRealClass = $aKeys[0];
  1057. }
  1058. }
  1059. else
  1060. {
  1061. $sRealClass = $sClass;
  1062. }
  1063. if (!empty($sRealClass))
  1064. {
  1065. // Display the creation form
  1066. $sClassLabel = MetaModel::GetName($sRealClass);
  1067. // Note: some code has been duplicated to the case 'apply_new' when a data integrity issue has been found
  1068. $oP->set_title(Dict::Format('UI:CreationPageTitle_Class', $sClassLabel));
  1069. $oP->add("<h1>".MetaModel::GetClassIcon($sRealClass)."&nbsp;".Dict::Format('UI:CreationTitle_Class', $sClassLabel)."</h1>\n");
  1070. $oP->add("<div class=\"wizContainer\">\n");
  1071. // Set all the default values in an object and clone this "default" object
  1072. $oObjToClone = MetaModel::NewObject($sRealClass);
  1073. // 1st - set context values
  1074. $oAppContext->InitObjectFromContext($oObjToClone);
  1075. // 2nd - set values from the page argument 'default'
  1076. $oObjToClone->UpdateObjectFromArg('default');
  1077. cmdbAbstractObject::DisplayCreationForm($oP, $sRealClass, $oObjToClone, array());
  1078. $oP->add("</div>\n");
  1079. }
  1080. else
  1081. {
  1082. // Select the derived class to create
  1083. $sClassLabel = MetaModel::GetName($sClass);
  1084. $oP->add("<h1>".MetaModel::GetClassIcon($sClass)."&nbsp;".Dict::Format('UI:CreationTitle_Class', $sClassLabel)."</h1>\n");
  1085. $oP->add("<div class=\"wizContainer\">\n");
  1086. $oP->add('<form>');
  1087. $oP->add('<p>'.Dict::Format('UI:SelectTheTypeOf_Class_ToCreate', $sClassLabel));
  1088. $aDefaults = utils::ReadParam('default', array(), false, 'raw_data');
  1089. $oP->add($oAppContext->GetForForm());
  1090. $oP->add("<input type=\"hidden\" name=\"checkSubclass\" value=\"0\">\n");
  1091. $oP->add("<input type=\"hidden\" name=\"state\" value=\"$sStateCode\">\n");
  1092. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"new\">\n");
  1093. foreach($aDefaults as $key => $value)
  1094. {
  1095. if (is_array($value))
  1096. {
  1097. foreach($value as $key2 => $value2)
  1098. {
  1099. if (is_array($value2))
  1100. {
  1101. foreach($value2 as $key3 => $value3)
  1102. {
  1103. $oP->add("<input type=\"hidden\" name=\"default[$key][$key2][$key3]\" value=\"$value3\">\n");
  1104. }
  1105. }
  1106. else
  1107. {
  1108. $oP->add("<input type=\"hidden\" name=\"default[$key][$key2]\" value=\"$value2\">\n");
  1109. }
  1110. }
  1111. }
  1112. else
  1113. {
  1114. $oP->add("<input type=\"hidden\" name=\"default[$key]\" value=\"$value\">\n");
  1115. }
  1116. }
  1117. $oP->add('<select name="class">');
  1118. asort($aPossibleClasses);
  1119. foreach($aPossibleClasses as $sClassName => $sClassLabel)
  1120. {
  1121. $sSelected = ($sClassName == $sClass) ? 'selected' : '';
  1122. $oP->add("<option $sSelected value=\"$sClassName\">$sClassLabel</option>");
  1123. }
  1124. $oP->add('</select>');
  1125. $oP->add("&nbsp; <input type=\"submit\" value=\"".Dict::S('UI:Button:Apply')."\"></p>");
  1126. $oP->add('</form>');
  1127. $oP->add("</div>\n");
  1128. }
  1129. break;
  1130. ///////////////////////////////////////////////////////////////////////////////////////////
  1131. case 'apply_modify': // Applying the modifications to an existing object
  1132. $sClass = utils::ReadPostedParam('class', '');
  1133. $sClassLabel = MetaModel::GetName($sClass);
  1134. $id = utils::ReadPostedParam('id', '');
  1135. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1136. if ( empty($sClass) || empty($id)) // TO DO: check that the class name is valid !
  1137. {
  1138. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'id'));
  1139. }
  1140. $bDisplayDetails = true;
  1141. $oObj = MetaModel::GetObject($sClass, $id, false);
  1142. if ($oObj == null)
  1143. {
  1144. $bDisplayDetails = false;
  1145. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  1146. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  1147. }
  1148. elseif (!utils::IsTransactionValid($sTransactionId, false))
  1149. {
  1150. $oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetRawName(), $sClassLabel)); // Set title will take care of the encoding
  1151. $oP->p("<strong>".Dict::S('UI:Error:ObjectAlreadyUpdated')."</strong>\n");
  1152. }
  1153. else
  1154. {
  1155. $oObj->UpdateObjectFromPostedForm();
  1156. $sMessage = '';
  1157. $sSeverity = 'ok';
  1158. if (!$oObj->IsModified())
  1159. {
  1160. $oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetRawName(), $sClassLabel)); // Set title will take care of the encoding
  1161. $sMessage = Dict::Format('UI:Class_Object_NotUpdated', MetaModel::GetName(get_class($oObj)), $oObj->GetName());
  1162. $sSeverity = 'info';
  1163. }
  1164. else
  1165. {
  1166. list($bRes, $aIssues) = $oObj->CheckToWrite();
  1167. if ($bRes)
  1168. {
  1169. $oObj->DBUpdate();
  1170. utils::RemoveTransaction($sTransactionId);
  1171. $sMessage = Dict::Format('UI:Class_Object_Updated', MetaModel::GetName(get_class($oObj)), $oObj->GetName());
  1172. $sSeverity = 'ok';
  1173. }
  1174. else
  1175. {
  1176. $bDisplayDetails = false;
  1177. // Found issues, explain and give the user a second chance
  1178. //
  1179. $oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetRawName(), $sClassLabel)); // Set title will take care of the encoding
  1180. $oP->add("<div class=\"page_header\">\n");
  1181. $oP->add("<h1>".$oObj->GetIcon()."&nbsp;".Dict::Format('UI:ModificationTitle_Class_Object', $sClassLabel, $oObj->GetName())."</h1>\n");
  1182. $oP->add("</div>\n");
  1183. $oP->add("<div class=\"wizContainer\">\n");
  1184. $oObj->DisplayModifyForm($oP);
  1185. $oP->add("</div>\n");
  1186. $sIssueDesc = Dict::Format('UI:ObjectCouldNotBeWritten', implode(', ', $aIssues));
  1187. $oP->add_ready_script("alert('".addslashes($sIssueDesc)."');");
  1188. }
  1189. }
  1190. }
  1191. if ($bDisplayDetails)
  1192. {
  1193. $oObj = MetaModel::GetObject(get_class($oObj), $oObj->GetKey()); //Workaround: reload the object so that the linkedset are displayed properly
  1194. $sNextAction = utils::ReadPostedParam('next_action', '');
  1195. if (!empty($sNextAction))
  1196. {
  1197. ApplyNextAction($oP, $oObj, $sNextAction);
  1198. }
  1199. else
  1200. {
  1201. // Nothing more to do
  1202. ReloadAndDisplay($oP, $oObj, $sMessage, $sSeverity);
  1203. }
  1204. }
  1205. break;
  1206. ///////////////////////////////////////////////////////////////////////////////////////////
  1207. case 'select_for_deletion': // Select multiple objects for deletion
  1208. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  1209. if (empty($sFilter))
  1210. {
  1211. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'filter'));
  1212. }
  1213. $oP->set_title(Dict::S('UI:BulkDeletePageTitle'));
  1214. $oP->add("<h1>".Dict::S('UI:BulkDeleteTitle')."</h1>\n");
  1215. // TO DO: limit the search filter by the user context
  1216. $oFilter = CMDBSearchFilter::unserialize($sFilter); // TO DO : check that the filter is valid
  1217. $oChecker = new ActionChecker($oFilter, UR_ACTION_BULK_DELETE);
  1218. DisplayMultipleSelectionForm($oP, $oFilter, 'bulk_delete', $oChecker);
  1219. break;
  1220. ///////////////////////////////////////////////////////////////////////////////////////////
  1221. case 'bulk_delete_confirmed': // Confirm bulk deletion of objects
  1222. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1223. if (!utils::IsTransactionValid($sTransactionId))
  1224. {
  1225. throw new ApplicationException(Dict::S('UI:Error:ObjectsAlreadyDeleted'));
  1226. }
  1227. // Fall through
  1228. ///////////////////////////////////////////////////////////////////////////////////////////
  1229. case 'bulk_delete': // Actual bulk deletion (if confirmed)
  1230. $sClass = utils::ReadPostedParam('class', '');
  1231. $sClassLabel = MetaModel::GetName($sClass);
  1232. $sFilter = utils::ReadPostedParam('filter', '');
  1233. $oFullSetFilter = DBObjectSearch::unserialize($sFilter);
  1234. $aSelectObject = utils::ReadMultipleSelection($oFullSetFilter);
  1235. $aObjects = array();
  1236. if ( empty($sClass) || empty($aSelectObject)) // TO DO: check that the class name is valid !
  1237. {
  1238. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'selectObject[]'));
  1239. }
  1240. foreach($aSelectObject as $iId)
  1241. {
  1242. $aObjects[] = MetaModel::GetObject($sClass, $iId);
  1243. }
  1244. if (!UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_DELETE, DBObjectSet::FromArray($sClass, $aObjects)))
  1245. {
  1246. throw new SecurityException(Dict::Format('UI:Error:BulkDeleteNotAllowedOn_Class', $sClass));
  1247. }
  1248. $oP->set_title(Dict::S('UI:BulkDeletePageTitle'));
  1249. DeleteObjects($oP, $sClass, $aObjects, ($operation == 'bulk_delete_confirmed'), $oFullSetFilter);
  1250. break;
  1251. ///////////////////////////////////////////////////////////////////////////////////////////
  1252. case 'delete': // Deletion (preview)
  1253. case 'delete_confirmed': // Deletion (confirmed)
  1254. $sClass = utils::ReadParam('class', '', false, 'class');
  1255. $sClassLabel = MetaModel::GetName($sClass);
  1256. $id = utils::ReadParam('id', '');
  1257. $oObj = MetaModel::GetObject($sClass, $id);
  1258. if (!UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, DBObjectSet::FromObject($oObj)))
  1259. {
  1260. throw new SecurityException(Dict::Format('UI:Error:DeleteNotAllowedOn_Class', $sClass));
  1261. }
  1262. DeleteObjects($oP, $sClass, array($oObj), ($operation == 'delete_confirmed'));
  1263. break;
  1264. ///////////////////////////////////////////////////////////////////////////////////////////
  1265. case 'apply_new': // Creation of a new object
  1266. $sClass = utils::ReadPostedParam('class', '', 'class');
  1267. $sClassLabel = MetaModel::GetName($sClass);
  1268. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1269. if ( empty($sClass) ) // TO DO: check that the class name is valid !
  1270. {
  1271. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'class'));
  1272. }
  1273. if (!utils::IsTransactionValid($sTransactionId, false))
  1274. {
  1275. $oP->p("<strong>".Dict::S('UI:Error:ObjectAlreadyCreated')."</strong>\n");
  1276. }
  1277. else
  1278. {
  1279. $oObj = MetaModel::NewObject($sClass);
  1280. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1281. if (!empty($sStateAttCode))
  1282. {
  1283. $sTargetState = utils::ReadPostedParam('obj_state', '');
  1284. if ($sTargetState != '')
  1285. {
  1286. $oObj->Set($sStateAttCode, $sTargetState);
  1287. }
  1288. }
  1289. $oObj->UpdateObjectFromPostedForm();
  1290. }
  1291. if (isset($oObj) && is_object($oObj))
  1292. {
  1293. $sClass = get_class($oObj);
  1294. $sClassLabel = MetaModel::GetName($sClass);
  1295. list($bRes, $aIssues) = $oObj->CheckToWrite();
  1296. if ($bRes)
  1297. {
  1298. $oObj->DBInsert();
  1299. utils::RemoveTransaction($sTransactionId);
  1300. $oP->set_title(Dict::S('UI:PageTitle:ObjectCreated'));
  1301. $sMessage = Dict::Format('UI:Title:Object_Of_Class_Created', $oObj->GetName(), $sClassLabel);
  1302. $oObj = MetaModel::GetObject(get_class($oObj), $oObj->GetKey()); //Workaround: reload the object so that the linkedset are displayed properly
  1303. $sNextAction = utils::ReadPostedParam('next_action', '');
  1304. if (!empty($sNextAction))
  1305. {
  1306. $oP->add("<h1>$sMessage</h1>");
  1307. ApplyNextAction($oP, $oObj, $sNextAction);
  1308. }
  1309. else
  1310. {
  1311. // Nothing more to do
  1312. ReloadAndDisplay($oP, $oObj, $sMessage, 'ok');
  1313. }
  1314. }
  1315. else
  1316. {
  1317. // Found issues, explain and give the user a second chance
  1318. //
  1319. $oP->set_title(Dict::Format('UI:CreationPageTitle_Class', $sClassLabel));
  1320. $oP->add("<h1>".MetaModel::GetClassIcon($sClass)."&nbsp;".Dict::Format('UI:CreationTitle_Class', $sClassLabel)."</h1>\n");
  1321. $oP->add("<div class=\"wizContainer\">\n");
  1322. cmdbAbstractObject::DisplayCreationForm($oP, $sClass, $oObj);
  1323. $oP->add("</div>\n");
  1324. $sIssueDesc = Dict::Format('UI:ObjectCouldNotBeWritten', implode(', ', $aIssues));
  1325. $oP->add_ready_script("alert('".addslashes($sIssueDesc)."');");
  1326. }
  1327. }
  1328. break;
  1329. ///////////////////////////////////////////////////////////////////////////////////////////
  1330. case 'select_bulk_stimulus': // Form displayed when applying a stimulus to many objects
  1331. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  1332. $sStimulus = utils::ReadParam('stimulus', '');
  1333. $sState = utils::ReadParam('state', '');
  1334. if (empty($sFilter) || empty($sStimulus) || empty($sState))
  1335. {
  1336. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state'));
  1337. }
  1338. $oFilter = DBObjectSearch::unserialize($sFilter);
  1339. $sClass = $oFilter->GetClass();
  1340. $aStimuli = MetaModel::EnumStimuli($sClass);
  1341. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1342. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1343. $oP->set_title($sActionLabel);
  1344. $oP->add('<div class="page_header">');
  1345. $oP->add('<h1>'.MetaModel::GetClassIcon($sClass).'&nbsp;'.$sActionLabel.'</h1>');
  1346. $oP->add('</div>');
  1347. $oChecker = new StimulusChecker($oFilter, $sState, $sStimulus);
  1348. $aExtraFormParams = array('stimulus' => $sStimulus, 'state' => $sState);
  1349. DisplayMultipleSelectionForm($oP, $oFilter, 'bulk_stimulus', $oChecker, $aExtraFormParams);
  1350. break;
  1351. case 'bulk_stimulus':
  1352. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  1353. $sStimulus = utils::ReadParam('stimulus', '');
  1354. $sState = utils::ReadParam('state', '');
  1355. if (empty($sFilter) || empty($sStimulus) || empty($sState))
  1356. {
  1357. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state'));
  1358. }
  1359. $oFilter = DBObjectSearch::unserialize($sFilter);
  1360. $sClass = $oFilter->GetClass();
  1361. $aSelectObject = utils::ReadMultipleSelection($oFilter);
  1362. if (count($aSelectObject) == 0)
  1363. {
  1364. // Nothing to do, no object was selected !
  1365. throw new ApplicationException(Dict::S('UI:BulkAction:NoObjectSelected'));
  1366. }
  1367. else
  1368. {
  1369. $aTransitions = MetaModel::EnumTransitions($sClass, $sState);
  1370. $aStimuli = MetaModel::EnumStimuli($sClass);
  1371. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1372. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1373. $aTransition = $aTransitions[$sStimulus];
  1374. $sTargetState = $aTransition['target_state'];
  1375. $aStates = MetaModel::EnumStates($sClass);
  1376. $aTargetStateDef = $aStates[$sTargetState];
  1377. $oP->set_title(Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aSelectObject), $sClass));
  1378. $oP->add('<div class="page_header">');
  1379. $oP->add('<h1>'.MetaModel::GetClassIcon($sClass).'&nbsp;'.Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aSelectObject), $sClass).'</h1>');
  1380. $oP->add('</div>');
  1381. $aExpectedAttributes = $aTargetStateDef['attribute_list'];
  1382. $aDetails = array();
  1383. $iFieldIndex = 0;
  1384. $aFieldsMap = array();
  1385. $aValues = array();
  1386. $aObjects = array();
  1387. foreach($aSelectObject as $iId)
  1388. {
  1389. $aObjects[] = MetaModel::GetObject($sClass, $iId);
  1390. }
  1391. $oSet = DBObjectSet::FromArray($sClass, $aObjects);
  1392. $oObj = $oSet->ComputeCommonObject($aValues);
  1393. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1394. $oObj->Set($sStateAttCode,$sTargetState);
  1395. $sReadyScript = '';
  1396. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  1397. {
  1398. // Prompt for an attribute if
  1399. // - the attribute must be changed or must be displayed to the user for confirmation
  1400. // - or the field is mandatory and currently empty
  1401. if ( ($iExpectCode & (OPT_ATT_MUSTCHANGE | OPT_ATT_MUSTPROMPT)) ||
  1402. (($iExpectCode & OPT_ATT_MANDATORY) && ($oObj->Get($sAttCode) == '')) )
  1403. {
  1404. $aAttributesDef = MetaModel::ListAttributeDefs($sClass);
  1405. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1406. $aPrerequisites = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  1407. if (count($aPrerequisites) > 0)
  1408. {
  1409. // When 'enabling' a field, all its prerequisites must be enabled too
  1410. $sFieldList = "['".implode("','", $aPrerequisites)."']";
  1411. $oP->add_ready_script("$('#enable_{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, true); } );\n");
  1412. }
  1413. $aDependents = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  1414. if (count($aDependents) > 0)
  1415. {
  1416. // When 'disabling' a field, all its dependent fields must be disabled too
  1417. $sFieldList = "['".implode("','", $aDependents)."']";
  1418. $oP->add_ready_script("$('#enable_{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, false); } );\n");
  1419. }
  1420. $aArgs = array('this' => $oObj);
  1421. $sHTMLValue = cmdbAbstractObject::GetFormElementForField($oP, $sClass, $sAttCode, $oAttDef, $oObj->Get($sAttCode), $oObj->GetEditValue($sAttCode), $sAttCode, '', $iExpectCode, $aArgs);
  1422. $sComments = '<input type="checkbox" checked id="enable_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$sAttCode.'\')"/>';
  1423. if (!isset($aValues[$sAttCode]))
  1424. {
  1425. $aValues[$sAttCode] = array();
  1426. }
  1427. if (count($aValues[$sAttCode]) == 1)
  1428. {
  1429. $sComments .= '<div class="mono_value">1</div>';
  1430. }
  1431. else
  1432. {
  1433. // Non-homogenous value
  1434. $iMaxCount = 5;
  1435. $sTip = "<p><b>".Dict::Format('UI:BulkModify_Count_DistinctValues', count($aValues[$sAttCode]))."</b><ul>";
  1436. $index = 0;
  1437. foreach($aValues[$sAttCode] as $sCurrValue => $aVal)
  1438. {
  1439. $sDisplayValue = empty($aVal['display']) ? '<i>'.Dict::S('Enum:Undefined').'</i>' : str_replace(array("\n", "\r"), " ", $aVal['display']);
  1440. $sTip .= "<li>".Dict::Format('UI:BulkModify:Value_Exists_N_Times', $sDisplayValue, $aVal['count'])."</li>";
  1441. $index++;
  1442. if ($iMaxCount == $index)
  1443. {
  1444. $sTip .= "<li>".Dict::Format('UI:BulkModify:N_MoreValues', count($aValues[$sAttCode]) - $iMaxCount)."</li>";
  1445. break;
  1446. }
  1447. }
  1448. $sTip .= "</ul></p>";
  1449. $sTip = addslashes($sTip);
  1450. $sReadyScript .= "$('#multi_values_$sAttCode').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );\n";
  1451. $sComments .= '<div class="multi_values" id="multi_values_'.$sAttCode.'">'.count($aValues[$sAttCode]).'</div>';
  1452. }
  1453. $aDetails[] = array('label' => '<span>'.$oAttDef->GetLabel().'</span>', 'value' => "<span id=\"field_$sAttCode\">$sHTMLValue</span>", 'comments' => $sComments);
  1454. $aFieldsMap[$sAttCode] = $sAttCode;
  1455. $iFieldIndex++;
  1456. }
  1457. }
  1458. $sButtonsPosition = MetaModel::GetConfig()->Get('buttons_position');
  1459. if ($sButtonsPosition == 'bottom')
  1460. {
  1461. // bottom: Displays the ticket details BEFORE the actions
  1462. $oP->add('<div class="ui-widget-content">');
  1463. $oObj->DisplayBareProperties($oP);
  1464. $oP->add('</div>');
  1465. }
  1466. $oP->add("<div class=\"wizContainer\">\n");
  1467. $oP->add("<form id=\"apply_stimulus\" method=\"post\" onSubmit=\"return OnSubmit('apply_stimulus');\">\n");
  1468. $oP->add("<table><tr><td>\n");
  1469. $oP->details($aDetails);
  1470. $oP->add("</td></tr></table>\n");
  1471. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  1472. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"bulk_apply_stimulus\">\n");
  1473. $oP->add("<input type=\"hidden\" name=\"preview_mode\" value=\"1\">\n");
  1474. $oP->add("<input type=\"hidden\" name=\"filter\" value=\"$sFilter\">\n");
  1475. $oP->add("<input type=\"hidden\" name=\"stimulus\" value=\"$sStimulus\">\n");
  1476. $oP->add("<input type=\"hidden\" name=\"state\" value=\"$sState\">\n");
  1477. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  1478. $oP->add($oAppContext->GetForForm());
  1479. $oP->add("<input type=\"hidden\" name=\"selectObject\" value=\"".implode(',',$aSelectObject)."\">\n");
  1480. $sURL = "./UI.php?operation=search&filter=".urlencode($sFilter)."&".$oAppContext->GetForLink();
  1481. $oP->add("<input type=\"button\" value=\"".Dict::S('UI:Button:Cancel')."\" onClick=\"window.location.href='$sURL'\">&nbsp;&nbsp;&nbsp;&nbsp;\n");
  1482. $oP->add("<button type=\"submit\" class=\"action\"><span>$sActionLabel</span></button>\n");
  1483. $oP->add("</form>\n");
  1484. $oP->add("</div>\n");
  1485. if ($sButtonsPosition != 'bottom')
  1486. {
  1487. // top or both: Displays the ticket details AFTER the actions
  1488. $oP->add('<div class="ui-widget-content">');
  1489. $oObj->DisplayBareProperties($oP);
  1490. $oP->add('</div>');
  1491. }
  1492. $iFieldsCount = count($aFieldsMap);
  1493. $sJsonFieldsMap = json_encode($aFieldsMap);
  1494. $oP->add_script(
  1495. <<<EOF
  1496. // Initializes the object once at the beginning of the page...
  1497. var oWizardHelper = new WizardHelper('$sClass', '', '$sTargetState');
  1498. oWizardHelper.SetFieldsMap($sJsonFieldsMap);
  1499. oWizardHelper.SetFieldsCount($iFieldsCount);
  1500. EOF
  1501. );
  1502. $oP->add_ready_script(
  1503. <<<EOF
  1504. // Starts the validation when the page is ready
  1505. CheckFields('apply_stimulus', false);
  1506. $sReadyScript
  1507. EOF
  1508. );
  1509. }
  1510. break;
  1511. case 'bulk_apply_stimulus':
  1512. $bPreviewMode = utils::ReadPostedParam('preview_mode', false);
  1513. $sFilter = utils::ReadPostedParam('filter', '', false, 'raw_data');
  1514. $sStimulus = utils::ReadPostedParam('stimulus', '');
  1515. $sState = utils::ReadPostedParam('state', '');
  1516. $sSelectObject = utils::ReadPostedParam('selectObject', '', false, 'raw_data');
  1517. $aSelectObject = explode(',', $sSelectObject);
  1518. if (empty($sFilter) || empty($sStimulus) || empty($sState))
  1519. {
  1520. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state'));
  1521. }
  1522. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1523. if (!utils::IsTransactionValid($sTransactionId))
  1524. {
  1525. $oP->p(Dict::S('UI:Error:ObjectAlreadyUpdated'));
  1526. }
  1527. else
  1528. {
  1529. // For archiving the modification
  1530. $oFilter = DBObjectSearch::unserialize($sFilter);
  1531. $sClass = $oFilter->GetClass();
  1532. $aObjects = array();
  1533. foreach($aSelectObject as $iId)
  1534. {
  1535. $aObjects[] = MetaModel::GetObject($sClass, $iId);
  1536. }
  1537. $aTransitions = MetaModel::EnumTransitions($sClass, $sState);
  1538. $aStimuli = MetaModel::EnumStimuli($sClass);
  1539. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1540. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1541. $oP->set_title(Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aObjects), $sClass));
  1542. $oP->add('<div class="page_header">');
  1543. $oP->add('<h1>'.MetaModel::GetClassIcon($sClass).'&nbsp;'.Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aObjects), $sClass).'</h1>');
  1544. $oP->add('</div>');
  1545. $oSet = DBObjectSet::FromArray($sClass, $aObjects);
  1546. // For reporting
  1547. $aHeaders = array(
  1548. 'object' => array('label' => MetaModel::GetName($sClass), 'description' => Dict::S('UI:ModifiedObject')),
  1549. 'status' => array('label' => Dict::S('UI:BulkModifyStatus'), 'description' => Dict::S('UI:BulkModifyStatus+')),
  1550. 'errors' => array('label' => Dict::S('UI:BulkModifyErrors'), 'description' => Dict::S('UI:BulkModifyErrors+')),
  1551. );
  1552. $aRows = array();
  1553. while ($oObj = $oSet->Fetch())
  1554. {
  1555. $sError = Dict::S('UI:BulkModifyStatusOk');
  1556. try
  1557. {
  1558. $aTransitions = $oObj->EnumTransitions();
  1559. $aStimuli = MetaModel::EnumStimuli($sClass);
  1560. if (!isset($aTransitions[$sStimulus]))
  1561. {
  1562. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
  1563. }
  1564. else
  1565. {
  1566. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1567. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1568. $aTransition = $aTransitions[$sStimulus];
  1569. $sTargetState = $aTransition['target_state'];
  1570. $aTargetStates = MetaModel::EnumStates($sClass);
  1571. $aTargetState = $aTargetStates[$sTargetState];
  1572. $aExpectedAttributes = $aTargetState['attribute_list'];
  1573. $aDetails = array();
  1574. $aErrors = array();
  1575. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  1576. {
  1577. $iFlags = $oObj->GetAttributeFlags($sAttCode);
  1578. if (($iExpectCode & (OPT_ATT_MUSTCHANGE|OPT_ATT_MUSTPROMPT)) || ($oObj->Get($sAttCode) == '') )
  1579. {
  1580. $paramValue = utils::ReadPostedParam("attr_$sAttCode", '', 'raw_data');
  1581. if ( ($iFlags & OPT_ATT_SLAVE) && ($paramValue != $oObj->Get($sAttCode)) )
  1582. {
  1583. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1584. $aErrors[] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $oAttDef->GetLabel());
  1585. unset($aExpectedAttributes[$sAttCode]);
  1586. }
  1587. }
  1588. }
  1589. $oObj->UpdateObjectFromPostedForm('', array_keys($aExpectedAttributes), $sTargetState);
  1590. if (count($aErrors) == 0)
  1591. {
  1592. if ($oObj->ApplyStimulus($sStimulus))
  1593. {
  1594. list($bResult, $aErrors) = $oObj->CheckToWrite();
  1595. $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusModified') : Dict::S('UI:BulkModifyStatusSkipped');
  1596. if ($bResult)
  1597. {
  1598. $oObj->DBUpdate();
  1599. }
  1600. else
  1601. {
  1602. $sError = '<p>'.implode('</p></p>',$aErrors)."</p>\n";
  1603. }
  1604. }
  1605. else
  1606. {
  1607. $sStatus = Dict::S('UI:BulkModifyStatusSkipped');
  1608. $sError = '<p>'.Dict::S('UI:FailedToApplyStimuli')."<p>\n";
  1609. }
  1610. }
  1611. else
  1612. {
  1613. $sStatus = Dict::S('UI:BulkModifyStatusSkipped');
  1614. $sError = '<p>'.implode('</p></p>',$aErrors)."</p>\n";
  1615. }
  1616. }
  1617. }
  1618. catch(Exception $e)
  1619. {
  1620. $sError = $e->getMessage();
  1621. $sStatus = Dict::S('UI:BulkModifyStatusSkipped');
  1622. }
  1623. $aRows[] = array(
  1624. 'object' => $oObj->GetHyperlink(),
  1625. 'status' => $sStatus,
  1626. 'errors' => $sError,
  1627. );
  1628. }
  1629. $oP->Table($aHeaders, $aRows);
  1630. // Back to the list
  1631. $sURL = "./UI.php?operation=search&filter=".urlencode($sFilter)."&".$oAppContext->GetForLink();
  1632. $oP->add('<input type="button" onClick="window.location.href=\''.$sURL.'\'" value="'.Dict::S('UI:Button:Done').'">');
  1633. }
  1634. break;
  1635. case 'stimulus': // Form displayed when applying a stimulus (state change)
  1636. $sClass = utils::ReadParam('class', '', false, 'class');
  1637. $id = utils::ReadParam('id', '');
  1638. $sStimulus = utils::ReadParam('stimulus', '');
  1639. if ( empty($sClass) || empty($id) || empty($sStimulus) ) // TO DO: check that the class name is valid !
  1640. {
  1641. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'class', 'id', 'stimulus'));
  1642. }
  1643. $oObj = MetaModel::GetObject($sClass, $id, false);
  1644. if ($oObj != null)
  1645. {
  1646. $aTransitions = $oObj->EnumTransitions();
  1647. $aStimuli = MetaModel::EnumStimuli($sClass);
  1648. if (!isset($aTransitions[$sStimulus]))
  1649. {
  1650. // Invalid stimulus
  1651. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
  1652. }
  1653. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1654. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1655. $aTransition = $aTransitions[$sStimulus];
  1656. $sTargetState = $aTransition['target_state'];
  1657. $aTargetStates = MetaModel::EnumStates($sClass);
  1658. $oP->add("<div class=\"page_header\">\n");
  1659. $oP->add("<h1>$sActionLabel - <span class=\"hilite\">{$oObj->GetName()}</span></h1>\n");
  1660. $oP->set_title($sActionLabel);
  1661. $oP->add("</div>\n");
  1662. $aTargetState = $aTargetStates[$sTargetState];
  1663. $aExpectedAttributes = $aTargetState['attribute_list'];
  1664. $oP->add("<h1>$sActionDetails</h1>\n");
  1665. $sButtonsPosition = MetaModel::GetConfig()->Get('buttons_position');
  1666. if ($sButtonsPosition == 'bottom')
  1667. {
  1668. // bottom: Displays the ticket details BEFORE the actions
  1669. $oP->add('<div class="ui-widget-content">');
  1670. $oObj->DisplayBareProperties($oP);
  1671. $oP->add('</div>');
  1672. }
  1673. $oP->add("<div class=\"wizContainer\">\n");
  1674. $oP->add("<form id=\"apply_stimulus\" method=\"post\" onSubmit=\"return OnSubmit('apply_stimulus');\">\n");
  1675. $aDetails = array();
  1676. $iFieldIndex = 0;
  1677. $aFieldsMap = array();
  1678. $aDetailsList = $oObj->FlattenZList(MetaModel::GetZListItems($sClass, 'details'));
  1679. // Order the fields based on their dependencies, set the fields for which there is only one possible value
  1680. // and perform this in the order of dependencies to avoid dead-ends
  1681. $aDeps = array();
  1682. foreach($aDetailsList as $sAttCode)
  1683. {
  1684. $aDeps[$sAttCode] = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode);
  1685. }
  1686. $aList = $oObj->OrderDependentFields($aDeps);
  1687. foreach($aList as $sAttCode)
  1688. {
  1689. // Consider only the "expected" fields for the target state
  1690. if (array_key_exists($sAttCode, $aExpectedAttributes))
  1691. {
  1692. $iExpectCode = $aExpectedAttributes[$sAttCode];
  1693. // Prompt for an attribute if
  1694. // - the attribute must be changed or must be displayed to the user for confirmation
  1695. // - or the field is mandatory and currently empty
  1696. if ( ($iExpectCode & (OPT_ATT_MUSTCHANGE | OPT_ATT_MUSTPROMPT)) ||
  1697. (($iExpectCode & OPT_ATT_MANDATORY) && ($oObj->Get($sAttCode) == '')) )
  1698. {
  1699. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1700. $aArgs = array('this' => $oObj);
  1701. // If the field is mandatory, set it to the only possible value
  1702. if ((!$oAttDef->IsNullAllowed()) || ($iExpectCode & OPT_ATT_MANDATORY))
  1703. {
  1704. if ($oAttDef->IsExternalKey())
  1705. {
  1706. $oAllowedValues = MetaModel::GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs);
  1707. if ($oAllowedValues->Count() == 1)
  1708. {
  1709. $oRemoteObj = $oAllowedValues->Fetch();
  1710. $oObj->Set($sAttCode, $oRemoteObj->GetKey());
  1711. }
  1712. }
  1713. else
  1714. {
  1715. $aAllowedValues = MetaModel::GetAllowedValues_att($sClass, $sAttCode, $aArgs);
  1716. if (count($aAllowedValues) == 1)
  1717. {
  1718. $aValues = array_keys($aAllowedValues);
  1719. $oObj->Set($sAttCode, $aValues[0]);
  1720. }
  1721. }
  1722. }
  1723. $sHTMLValue = cmdbAbstractObject::GetFormElementForField($oP, $sClass, $sAttCode, $oAttDef, $oObj->Get($sAttCode), $oObj->GetEditValue($sAttCode), 'att_'.$iFieldIndex, '', $iExpectCode, $aArgs);
  1724. $aDetails[] = array('label' => '<span>'.$oAttDef->GetLabel().'</span>', 'value' => "<span id=\"field_att_$iFieldIndex\">$sHTMLValue</span>");
  1725. $aFieldsMap[$sAttCode] = 'att_'.$iFieldIndex;
  1726. $iFieldIndex++;
  1727. }
  1728. }
  1729. }
  1730. $oP->add('<table><tr><td>');
  1731. $oP->details($aDetails);
  1732. $oP->add('</td></tr></table>');
  1733. $oP->add("<input type=\"hidden\" name=\"id\" value=\"$id\" id=\"id\">\n");
  1734. $aFieldsMap['id'] = 'id';
  1735. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  1736. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"apply_stimulus\">\n");
  1737. $oP->add("<input type=\"hidden\" name=\"stimulus\" value=\"$sStimulus\">\n");
  1738. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  1739. $oP->add($oAppContext->GetForForm());
  1740. $oP->add("<button type=\"button\" class=\"action\" onClick=\"BackToDetails('$sClass', $id)\"><span>".Dict::S('UI:Button:Cancel')."</span></button>&nbsp;&nbsp;&nbsp;&nbsp;\n");
  1741. $oP->add("<button type=\"submit\" class=\"action\"><span>$sActionLabel</span></button>\n");
  1742. $oP->add("</form>\n");
  1743. $oP->add("</div>\n");
  1744. if ($sButtonsPosition != 'top')
  1745. {
  1746. // bottom or both: Displays the ticket details AFTER the actions
  1747. $oP->add('<div class="ui-widget-content">');
  1748. $oObj->DisplayBareProperties($oP);
  1749. $oP->add('</div>');
  1750. }
  1751. $iFieldsCount = count($aFieldsMap);
  1752. $sJsonFieldsMap = json_encode($aFieldsMap);
  1753. $oP->add_script(
  1754. <<<EOF
  1755. // Initializes the object once at the beginning of the page...
  1756. var oWizardHelper = new WizardHelper('$sClass', '', '$sTargetState');
  1757. oWizardHelper.SetFieldsMap($sJsonFieldsMap);
  1758. oWizardHelper.SetFieldsCount($iFieldsCount);
  1759. EOF
  1760. );
  1761. $oP->add_ready_script(
  1762. <<<EOF
  1763. // Starts the validation when the page is ready
  1764. CheckFields('apply_stimulus', false);
  1765. EOF
  1766. );
  1767. }
  1768. else
  1769. {
  1770. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  1771. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  1772. }
  1773. break;
  1774. ///////////////////////////////////////////////////////////////////////////////////////////
  1775. case 'apply_stimulus': // Actual state change
  1776. $sClass = utils::ReadPostedParam('class', '');
  1777. $id = utils::ReadPostedParam('id', '');
  1778. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1779. $sStimulus = utils::ReadPostedParam('stimulus', '');
  1780. if ( empty($sClass) || empty($id) || empty($sStimulus) ) // TO DO: check that the class name is valid !
  1781. {
  1782. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'class', 'id', 'stimulus'));
  1783. }
  1784. $oObj = MetaModel::GetObject($sClass, $id, false);
  1785. if ($oObj != null)
  1786. {
  1787. $aTransitions = $oObj->EnumTransitions();
  1788. $aStimuli = MetaModel::EnumStimuli($sClass);
  1789. $sMessage = '';
  1790. $sSeverity = 'ok';
  1791. if (!isset($aTransitions[$sStimulus]))
  1792. {
  1793. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
  1794. }
  1795. if (!utils::IsTransactionValid($sTransactionId))
  1796. {
  1797. $sMessage = Dict::S('UI:Error:ObjectAlreadyUpdated');
  1798. $sSeverity = 'info';
  1799. }
  1800. else
  1801. {
  1802. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1803. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1804. $aTransition = $aTransitions[$sStimulus];
  1805. $sTargetState = $aTransition['target_state'];
  1806. $aTargetStates = MetaModel::EnumStates($sClass);
  1807. $aTargetState = $aTargetStates[$sTargetState];
  1808. $aExpectedAttributes = $aTargetState['attribute_list'];
  1809. $aDetails = array();
  1810. $aErrors = array();
  1811. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  1812. {
  1813. $iFlags = $oObj->GetAttributeFlags($sAttCode);
  1814. if (($iExpectCode & (OPT_ATT_MUSTCHANGE|OPT_ATT_MUSTPROMPT)) || ($oObj->Get($sAttCode) == '') )
  1815. {
  1816. $paramValue = utils::ReadPostedParam("attr_$sAttCode", '', 'raw_data');
  1817. if ( ($iFlags & OPT_ATT_SLAVE) && ($paramValue != $oObj->Get($sAttCode)))
  1818. {
  1819. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1820. $aErrors[] = Dict::Format('UI:AttemptingToChangeASlaveAttribute_Name', $oAttDef->GetLabel());
  1821. unset($aExpectedAttributes[$sAttCode]);
  1822. }
  1823. }
  1824. }
  1825. $oObj->UpdateObjectFromPostedForm('', array_keys($aExpectedAttributes), $sTargetState);
  1826. if (count($aErrors) == 0)
  1827. {
  1828. if ($oObj->ApplyStimulus($sStimulus))
  1829. {
  1830. $oObj->DBUpdate();
  1831. $sMessage = Dict::Format('UI:Class_Object_Updated', MetaModel::GetName(get_class($oObj)), $oObj->GetName());
  1832. $sSeverity = 'ok';
  1833. }
  1834. else
  1835. {
  1836. $sMessage = Dict::S('UI:FailedToApplyStimuli');
  1837. $sSeverity = 'error';
  1838. }
  1839. }
  1840. else
  1841. {
  1842. $sMessage = implode('</p><p>', $aErrors);
  1843. $sSeverity = 'error';
  1844. }
  1845. }
  1846. ReloadAndDisplay($oP, $oObj, $sMessage, $sSeverity);
  1847. }
  1848. else
  1849. {
  1850. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  1851. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  1852. }
  1853. break;
  1854. ///////////////////////////////////////////////////////////////////////////////////////////
  1855. case 'swf_navigator': // Graphical display of the relations "impact" / "depends on"
  1856. $sClass = utils::ReadParam('class', '', false, 'class');
  1857. $id = utils::ReadParam('id', 0);
  1858. $sRelation = utils::ReadParam('relation', 'impact');
  1859. $oP->AddTabContainer('Navigator');
  1860. $oP->SetCurrentTabContainer('Navigator');
  1861. $oP->SetCurrentTab(Dict::S('UI:RelationshipGraph'));
  1862. $oP->add("<div id=\"ds_flash\" class=\"SearchDrawer\">\n");
  1863. $oP->add_ready_script(
  1864. <<<EOF
  1865. $("#dh_flash").click( function() {
  1866. $("#ds_flash").slideToggle('normal', function() { $("#ds_flash").parent().resize(); } );
  1867. $("#dh_flash").toggleClass('open');
  1868. });
  1869. EOF
  1870. );
  1871. $aResults = array();
  1872. $aSortedElements = array();
  1873. $oObj = MetaModel::GetObject($sClass, $id);
  1874. $oObj->GetRelatedObjects($sRelation, 20 /* iMaxDepth */, $aResults);
  1875. foreach($aResults as $sClassIdx => $aObjects)
  1876. {
  1877. foreach($aObjects as $oCurrObj)
  1878. {
  1879. $sSubClass = get_class($oCurrObj);
  1880. $aSortedElements[$sSubClass] = MetaModel::GetName($sSubClass);
  1881. }
  1882. }
  1883. asort($aSortedElements);
  1884. $idx = 0;
  1885. foreach($aSortedElements as $sSubClass => $sClassName)
  1886. {
  1887. $oP->add("<span style=\"padding-right:2em; white-space:nowrap;\"><input type=\"checkbox\" id=\"exclude_$idx\" name=\"excluded[]\" value=\"$sSubClass\" checked onChange=\"$('#ReloadMovieBtn').button('enable')\"><label for=\"exclude_$idx\">&nbsp;".MetaModel::GetClassIcon($sSubClass)."&nbsp;$sClassName</label></span> ");
  1888. $idx++;
  1889. }
  1890. $oP->add("<p style=\"text-align:right\"><button type=\"button\" id=\"ReloadMovieBtn\" onClick=\"DoReload()\">".Dict::S('UI:Button:Refresh')."</button></p>");
  1891. $oP->add("</div>\n");
  1892. $oP->add("<div class=\"HRDrawer\"></div>\n");
  1893. $oP->add("<div id=\"dh_flash\" class=\"DrawerHandle\">".Dict::S('UI:ElementsDisplayed')."</div>\n");
  1894. $width = 1000;
  1895. $height = 700;
  1896. $sDrillUrl = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=details&'.$oAppContext->GetForLink();
  1897. $sParams = "pWidth=$width&pHeight=$height&drillUrl=".urlencode($sDrillUrl)."&displayController=false&xmlUrl=".urlencode("./xml.navigator.php")."&obj_class=$sClass&obj_id=$id&relation=$sRelation";
  1898. $oP->add("<div style=\"z-index:1;background:white;width:100%;height:{$height}px\"><object style=\"z-index:2\" classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0\" width=\"100%\" height=\"$height\" id=\"navigator\" align=\"middle\">
  1899. <param name=\"allowScriptAccess\" value=\"always\" />
  1900. <param name=\"allowFullScreen\" value=\"false\" />
  1901. <param name=\"FlashVars\" value=\"$sParams\" />
  1902. <param name=\"wmode\" value=\"transparent\">
  1903. <param name=\"movie\" value=\"../navigator/navigator.swf\" /><param name=\"quality\" value=\"high\" /><param name=\"bgcolor\" value=\"#ffffff\" />
  1904. <embed src=\"../navigator/navigator.swf\" wmode=\"transparent\" flashVars=\"$sParams\" quality=\"high\" bgcolor=\"#ffffff\" width=\"100%\" height=\"$height\" name=\"navigator\" align=\"middle\" swliveconnect=\"true\" allowScriptAccess=\"always\" allowFullScreen=\"false\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.adobe.com/go/getflashplayer\" />
  1905. </object></div>\n");
  1906. $oP->SetCurrentTab(Dict::S('UI:RelationshipList'));
  1907. $oP->add("<div id=\"impacted_objects\" style=\"width:100%;background-color:#fff;padding:10px;\"><p style=\"height:150px;\">&nbsp;</p></div>");
  1908. $oP->add_script(
  1909. <<<EOF
  1910. function getFlashMovieObject(movieName)
  1911. {
  1912. if (window.document[movieName])
  1913. {
  1914. return window.document[movieName];
  1915. }
  1916. if (navigator.appName.indexOf("Microsoft Internet")==-1)
  1917. {
  1918. if (document.embeds && document.embeds[movieName])
  1919. return document.embeds[movieName];
  1920. }
  1921. else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
  1922. {
  1923. return document.getElementById(movieName);
  1924. }
  1925. }
  1926. function DoReload()
  1927. {
  1928. $('#ReloadMovieBtn').button('disable');
  1929. var oMovie = getFlashMovieObject('navigator');
  1930. try
  1931. {
  1932. var aExcluded = [];
  1933. $('input[name^=excluded]').each( function() {
  1934. if (!$(this).attr('checked'))
  1935. {
  1936. aExcluded.push($(this).val());
  1937. }
  1938. } );
  1939. oMovie.Filter(aExcluded.join(','));
  1940. //oMovie.SetVariable("/:message", "foo");
  1941. }
  1942. catch(err)
  1943. {
  1944. alert(err);
  1945. }
  1946. }
  1947. EOF
  1948. );
  1949. $oP->add_ready_script(
  1950. <<<EOF
  1951. var ajax_request = null;
  1952. $('#ReloadMovieBtn').button().button('disable');
  1953. function UpdateImpactedObjects(sClass, iId, sRelation)
  1954. {
  1955. var class_name = sClass; //$('select[name=class_name]').val();
  1956. if (class_name != '')
  1957. {
  1958. $('#impacted_objects').block();
  1959. // Make sure that we cancel any pending request before issuing another
  1960. // since responses may arrive in arbitrary order
  1961. if (ajax_request != null)
  1962. {
  1963. ajax_request.abort();
  1964. ajax_request = null;
  1965. }
  1966. ajax_request = $.get(GetAbsoluteUrlAppRoot()+'pages/xml.navigator.php', { 'class': sClass, id: iId, relation: sRelation, format: 'html' },
  1967. function(data)
  1968. {
  1969. $('#impacted_objects').empty();
  1970. $('#impacted_objects').append(data);
  1971. $('#impacted_objects').unblock();
  1972. }
  1973. );
  1974. }
  1975. }
  1976. UpdateImpactedObjects('$sClass', $id, '$sRelation');
  1977. EOF
  1978. );
  1979. $oP->SetCurrentTab('');
  1980. break;
  1981. ///////////////////////////////////////////////////////////////////////////////////////////
  1982. case 'cancel': // An action was cancelled
  1983. $oP->set_title(Dict::S('UI:OperationCancelled'));
  1984. $oP->add('<h1>'.Dict::S('UI:OperationCancelled').'</h1>');
  1985. break;
  1986. ///////////////////////////////////////////////////////////////////////////////////////////
  1987. default: // Menu node rendering (templates)
  1988. ApplicationMenu::LoadAdditionalMenus();
  1989. $oMenuNode = ApplicationMenu::GetMenuNode(ApplicationMenu::GetMenuIndexById(ApplicationMenu::GetActiveNodeId()));
  1990. if (is_object($oMenuNode))
  1991. {
  1992. $oMenuNode->RenderContent($oP, $oAppContext->GetAsHash());
  1993. $oP->set_title($oMenuNode->GetLabel());
  1994. }
  1995. ///////////////////////////////////////////////////////////////////////////////////////////
  1996. }
  1997. $oKPI->ComputeAndReport('GUI creation before output');
  1998. ExecutionKPI::ReportStats();
  1999. MetaModel::RecordQueryTrace();
  2000. DisplayWelcomePopup($oP);
  2001. $oP->output();
  2002. }
  2003. catch(CoreException $e)
  2004. {
  2005. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  2006. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  2007. if ($e instanceof SecurityException)
  2008. {
  2009. $oP->add("<h1>".Dict::S('UI:SystemIntrusion')."</h1>\n");
  2010. }
  2011. else
  2012. {
  2013. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  2014. }
  2015. $oP->error(Dict::Format('UI:Error_Details', $e->getHtmlDesc()));
  2016. $oP->output();
  2017. if (MetaModel::IsLogEnabledIssue())
  2018. {
  2019. if (MetaModel::IsValidClass('EventIssue'))
  2020. {
  2021. try
  2022. {
  2023. $oLog = new EventIssue();
  2024. $oLog->Set('message', $e->getMessage());
  2025. $oLog->Set('userinfo', '');
  2026. $oLog->Set('issue', $e->GetIssue());
  2027. $oLog->Set('impact', 'Page could not be displayed');
  2028. $oLog->Set('callstack', $e->getTrace());
  2029. $oLog->Set('data', $e->getContextData());
  2030. $oLog->DBInsertNoReload();
  2031. }
  2032. catch(Exception $e)
  2033. {
  2034. IssueLog::Error("Failed to log issue into the DB");
  2035. }
  2036. }
  2037. IssueLog::Error($e->getMessage());
  2038. }
  2039. // For debugging only
  2040. //throw $e;
  2041. }
  2042. catch(Exception $e)
  2043. {
  2044. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  2045. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  2046. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  2047. $oP->error(Dict::Format('UI:Error_Details', $e->getMessage()));
  2048. $oP->output();
  2049. if (MetaModel::IsLogEnabledIssue())
  2050. {
  2051. if (MetaModel::IsValidClass('EventIssue'))
  2052. {
  2053. try
  2054. {
  2055. $oLog = new EventIssue();
  2056. $oLog->Set('message', $e->getMessage());
  2057. $oLog->Set('userinfo', '');
  2058. $oLog->Set('issue', 'PHP Exception');
  2059. $oLog->Set('impact', 'Page could not be displayed');
  2060. $oLog->Set('callstack', $e->getTrace());
  2061. $oLog->Set('data', array());
  2062. $oLog->DBInsertNoReload();
  2063. }
  2064. catch(Exception $e)
  2065. {
  2066. IssueLog::Error("Failed to log issue into the DB");
  2067. }
  2068. }
  2069. IssueLog::Error($e->getMessage());
  2070. }
  2071. }
  2072. ?>