UI.php 88 KB

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