UI.php 86 KB

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