UI.php 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248
  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. DisplayDetails($oP, $sClass, $oObj, $id);
  682. }
  683. break;
  684. ///////////////////////////////////////////////////////////////////////////////////////////
  685. case 'search_oql': // OQL query
  686. $sOQLClass = utils::ReadParam('oql_class', '', false, 'class');
  687. $sBaseClass = utils::ReadParam('base_class', $sOQLClass, false, 'class');
  688. $sOQLClause = utils::ReadParam('oql_clause', '', false, 'raw_data');
  689. $sFormat = utils::ReadParam('format', '');
  690. $bSearchForm = utils::ReadParam('search_form', true);
  691. $sTitle = utils::ReadParam('title', 'UI:SearchResultsPageTitle');
  692. if (empty($sOQLClass))
  693. {
  694. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'oql_class'));
  695. }
  696. $oP->set_title(Dict::S($sTitle));
  697. $oP->add('<h1>'.Dict::S($sTitle).'</h1>');
  698. $sOQL = "SELECT $sOQLClass $sOQLClause";
  699. try
  700. {
  701. $oFilter = DBObjectSearch::FromOQL($sOQL);
  702. DisplaySearchSet($oP, $oFilter, $bSearchForm, $sBaseClass, $sFormat);
  703. }
  704. catch(CoreException $e)
  705. {
  706. $oFilter = new DBObjectSearch($sOQLClass);
  707. $oSet = new DBObjectSet($oFilter);
  708. if ($bSearchForm)
  709. {
  710. $oBlock = new DisplayBlock($oFilter, 'search', false);
  711. $oBlock->Display($oP, 0);
  712. }
  713. $oP->P('<b>'.Dict::Format('UI:Error:IncorrectOQLQuery_Message', $e->getHtmlDesc()).'</b>');
  714. }
  715. catch(Exception $e)
  716. {
  717. $oP->P('<b>'.Dict::Format('UI:Error:AnErrorOccuredWhileRunningTheQuery_Message', $e->getMessage()).'</b>');
  718. }
  719. break;
  720. ///////////////////////////////////////////////////////////////////////////////////////////
  721. case 'search_form': // Search form
  722. $sClass = utils::ReadParam('class', '', false, 'class');
  723. $sFormat = utils::ReadParam('format', 'html');
  724. $bSearchForm = utils::ReadParam('search_form', true);
  725. if (empty($sClass))
  726. {
  727. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'class'));
  728. }
  729. $oP->set_title(Dict::S('UI:SearchResultsPageTitle'));
  730. $oFilter = new DBObjectSearch($sClass);
  731. DisplaySearchSet($oP, $oFilter, $bSearchForm, '' /* sBaseClass */, $sFormat);
  732. break;
  733. ///////////////////////////////////////////////////////////////////////////////////////////
  734. case 'search': // Serialized CMDBSearchFilter
  735. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  736. $sFormat = utils::ReadParam('format', '');
  737. $bSearchForm = utils::ReadParam('search_form', true);
  738. if (empty($sFilter))
  739. {
  740. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'filter'));
  741. }
  742. $oP->set_title(Dict::S('UI:SearchResultsPageTitle'));
  743. // TO DO: limit the search filter by the user context
  744. $oFilter = CMDBSearchFilter::unserialize($sFilter); // TO DO : check that the filter is valid
  745. DisplaySearchSet($oP, $oFilter, $bSearchForm, '' /* sBaseClass */, $sFormat);
  746. break;
  747. ///////////////////////////////////////////////////////////////////////////////////////////
  748. case 'full_text': // Global "google-like" search
  749. $sFullText = trim(utils::ReadParam('text', '', false, 'raw_data'));
  750. if (empty($sFullText))
  751. {
  752. $oP->p(Dict::S('UI:Search:NoSearch'));
  753. }
  754. else
  755. {
  756. $oP->set_title(Dict::S('UI:SearchResultsPageTitle'));
  757. $oP->p("<h1>".Dict::Format('UI:FullTextSearchTitle_Text', $sFullText)."</h1>");
  758. $iCount = 0;
  759. $iBlock = 0;
  760. // Search in full text mode in all the classes
  761. $aMatches = array();
  762. $sClassName = '';
  763. // Check if a class name/label is supplied to limit the search
  764. if (preg_match('/^(.+):(.+)$/', $sFullText, $aMatches))
  765. {
  766. $sClassName = $aMatches[1];
  767. if (MetaModel::IsValidClass($sClassName))
  768. {
  769. $sFullText = $aMatches[2];
  770. }
  771. elseif ($sClassName = MetaModel::GetClassFromLabel($sClassName, false /* => not case sensitive */))
  772. {
  773. $sFullText = $aMatches[2];
  774. }
  775. }
  776. if (preg_match('/^"(.*)"$/', $sFullText, $aMatches))
  777. {
  778. // The text is surrounded by double-quotes, remove the quotes and treat it as one single expression
  779. $aFullTextNeedles = array($aMatches[1]);
  780. }
  781. else
  782. {
  783. // Split the text on the blanks and treat this as a search for <word1> AND <word2> AND <word3>
  784. $aFullTextNeedles = explode(' ', $sFullText);
  785. }
  786. // Search is limited ot a given class, or not...
  787. if (empty($sClassName))
  788. {
  789. $aSearchClasses = MetaModel::GetClasses('searchable');
  790. }
  791. else
  792. {
  793. $aSearchClasses = MetaModel::EnumChildClasses($sClassName, ENUM_CHILD_CLASSES_ALL);
  794. }
  795. foreach($aSearchClasses as $sClassName)
  796. {
  797. $oFilter = new DBObjectSearch($sClassName);
  798. foreach($aFullTextNeedles as $sSearchText)
  799. {
  800. $oFilter->AddCondition_FullText($sSearchText);
  801. }
  802. $oSet = new DBObjectSet($oFilter);
  803. if ($oSet->Count() > 0)
  804. {
  805. $aLeafs = array();
  806. while($oObj = $oSet->Fetch())
  807. {
  808. if (get_class($oObj) == $sClassName)
  809. {
  810. $aLeafs[] = $oObj->GetKey();
  811. }
  812. }
  813. $oLeafsFilter = new DBObjectSearch($sClassName);
  814. if (count($aLeafs) > 0)
  815. {
  816. $iCount += count($aLeafs);
  817. $oP->add("<div class=\"page_header\">\n");
  818. $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");
  819. $oP->add("</div>\n");
  820. $oLeafsFilter->AddCondition('id', $aLeafs, 'IN');
  821. $oBlock = new DisplayBlock($oLeafsFilter, 'list', false);
  822. $oBlock->Display($oP, $iBlock++, array('table_id' => 'global_search'));
  823. $oP->P('&nbsp;'); // Some space ?
  824. }
  825. }
  826. }
  827. if ($iCount == 0)
  828. {
  829. $oP->p(Dict::S('UI:Search:NoObjectFound'));
  830. }
  831. }
  832. break;
  833. ///////////////////////////////////////////////////////////////////////////////////////////
  834. case 'modify': // Form to modify an object
  835. $sClass = utils::ReadParam('class', '', false, 'class');
  836. $sClassLabel = MetaModel::GetName($sClass);
  837. $id = utils::ReadParam('id', '');
  838. if ( empty($sClass) || empty($id)) // TO DO: check that the class name is valid !
  839. {
  840. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'id'));
  841. }
  842. // Check if the user can modify this object
  843. $oObj = MetaModel::GetObject($sClass, $id, false /* MustBeFound */);
  844. if (is_null($oObj))
  845. {
  846. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  847. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  848. }
  849. else
  850. {
  851. // The object could be read - check if it is allowed to modify it
  852. $oSet = CMDBObjectSet::FromObject($oObj);
  853. if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet) == UR_ALLOWED_NO)
  854. {
  855. throw new SecurityException('User not allowed to modify this object', array('class' => $sClass, 'id' => $id));
  856. }
  857. // Note: code duplicated to the case 'apply_modify' when a data integrity issue has been found
  858. $oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetRawName(), $sClassLabel)); // Set title will take care of the encoding
  859. $oP->add("<div class=\"page_header\">\n");
  860. $oP->add("<h1>".$oObj->GetIcon()."&nbsp;".Dict::Format('UI:ModificationTitle_Class_Object', $sClassLabel, $oObj->GetName())."</h1>\n");
  861. $oP->add("</div>\n");
  862. $oP->add("<div class=\"wizContainer\">\n");
  863. $oObj->DisplayModifyForm($oP);
  864. $oP->add("</div>\n");
  865. }
  866. break;
  867. ///////////////////////////////////////////////////////////////////////////////////////////
  868. case 'select_for_modify_all': // Select the list of objects to be modified (bulk modify)
  869. $oP->set_title(Dict::S('UI:ModifyAllPageTitle'));
  870. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  871. if (empty($sFilter))
  872. {
  873. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'filter'));
  874. }
  875. // TO DO: limit the search filter by the user context
  876. $oFilter = DBObjectSearch::unserialize($sFilter); // TO DO : check that the filter is valid
  877. $sClass = $oFilter->GetClass();
  878. $oChecker = new ActionChecker($oFilter, UR_ACTION_BULK_MODIFY);
  879. $oP->add("<h1>Modify All...</h1>\n");
  880. DisplayMultipleSelectionForm($oP, $oFilter, 'form_for_modify_all', $oChecker);
  881. break;
  882. ///////////////////////////////////////////////////////////////////////////////////////////
  883. case 'form_for_modify_all': // Form to modify multiple objects (bulk modify)
  884. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  885. $sClass = utils::ReadParam('class', '', false, 'class');
  886. $oFullSetFilter = DBObjectSearch::unserialize($sFilter);
  887. $aSelectedObj = utils::ReadMultipleSelection($oFullSetFilter);
  888. if (count($aSelectedObj) > 0)
  889. {
  890. $iAllowedCount = count($aSelectedObj);
  891. $sSelectedObj = implode(',', $aSelectedObj);
  892. $sOQL = "SELECT $sClass WHERE id IN (".$sSelectedObj.")";
  893. $oSet = new CMDBObjectSet(DBObjectSearch::FromOQL($sOQL));
  894. // Compute the distribution of the values for each field to determine which of the "scalar" fields are homogenous
  895. $aList = MetaModel::ListAttributeDefs($sClass);
  896. $aValues = array();
  897. foreach($aList as $sAttCode => $oAttDef)
  898. {
  899. if ($oAttDef->IsScalar())
  900. {
  901. $aValues[$sAttCode] = array();
  902. }
  903. }
  904. while($oObj = $oSet->Fetch())
  905. {
  906. foreach($aList as $sAttCode => $oAttDef)
  907. {
  908. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  909. {
  910. $currValue = $oObj->Get($sAttCode);
  911. if ($oAttDef instanceof AttributeCaseLog)
  912. {
  913. $currValue = ' '; // Don't put an empty string, in case the field would be considered as mandatory...
  914. }
  915. if (is_object($currValue)) continue; // Skip non scalar values...
  916. if(!array_key_exists($currValue, $aValues[$sAttCode]))
  917. {
  918. $aValues[$sAttCode][$currValue] = array('count' => 1, 'display' => $oObj->GetAsHTML($sAttCode));
  919. }
  920. else
  921. {
  922. $aValues[$sAttCode][$currValue]['count']++;
  923. }
  924. }
  925. }
  926. }
  927. // Now create an object that has values for the homogenous values only
  928. $oDummyObj = new $sClass(); // @@ What if the class is abstract ?
  929. $aComments = array();
  930. function MyComparison($a, $b) // Sort descending
  931. {
  932. if ($a['count'] == $b['count'])
  933. {
  934. return 0;
  935. }
  936. return ($a['count'] > $b['count']) ? -1 : 1;
  937. }
  938. $iFormId = cmdbAbstractObject::GetNextFormId(); // Identifier that prefixes all the form fields
  939. $sReadyScript = '';
  940. $aDependsOn = array();
  941. $sFormPrefix = '2_';
  942. foreach($aList as $sAttCode => $oAttDef)
  943. {
  944. $aPrerequisites = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  945. if (count($aPrerequisites) > 0)
  946. {
  947. // When 'enabling' a field, all its prerequisites must be enabled too
  948. $sFieldList = "['{$sFormPrefix}".implode("','{$sFormPrefix}", $aPrerequisites)."']";
  949. $oP->add_ready_script("$('#enable_{$sFormPrefix}{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, true); } );\n");
  950. }
  951. $aDependents = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  952. if (count($aDependents) > 0)
  953. {
  954. // When 'disabling' a field, all its dependent fields must be disabled too
  955. $sFieldList = "['{$sFormPrefix}".implode("','{$sFormPrefix}", $aDependents)."']";
  956. $oP->add_ready_script("$('#enable_{$sFormPrefix}{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, false); } );\n");
  957. }
  958. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  959. {
  960. if ($oAttDef->GetEditClass() == 'One Way Password')
  961. {
  962. $sTip = "Unknown values";
  963. $sReadyScript .= "$('#multi_values_$sAttCode').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );";
  964. $oDummyObj->Set($sAttCode, null);
  965. $aComments[$sAttCode] = '<input type="checkbox" id="enable_'.$iFormId.'_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$iFormId.'_'.$sAttCode.'\')"/>';
  966. $aComments[$sAttCode] .= '<div class="multi_values" id="multi_values_'.$sAttCode.'"> ? </div>';
  967. $sReadyScript .= 'ToogleField(false, \''.$iFormId.'_'.$sAttCode.'\');'."\n";
  968. }
  969. else
  970. {
  971. $iCount = count($aValues[$sAttCode]);
  972. if ($iCount == 1)
  973. {
  974. // Homogenous value
  975. reset($aValues[$sAttCode]);
  976. $aKeys = array_keys($aValues[$sAttCode]);
  977. $currValue = $aKeys[0]; // The only value is the first key
  978. //echo "<p>current value for $sAttCode : $currValue</p>";
  979. $oDummyObj->Set($sAttCode, $currValue);
  980. $aComments[$sAttCode] = '<input type="checkbox" checked id="enable_'.$iFormId.'_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$iFormId.'_'.$sAttCode.'\')"/>';
  981. $aComments[$sAttCode] .= '<div class="mono_value">1</div>';
  982. }
  983. else
  984. {
  985. // Non-homogenous value
  986. $aMultiValues = $aValues[$sAttCode];
  987. uasort($aMultiValues, 'MyComparison');
  988. $iMaxCount = 5;
  989. $sTip = "<p><b>".Dict::Format('UI:BulkModify_Count_DistinctValues', $iCount)."</b><ul>";
  990. $index = 0;
  991. foreach($aMultiValues as $sCurrValue => $aVal)
  992. {
  993. $sDisplayValue = empty($aVal['display']) ? '<i>'.Dict::S('Enum:Undefined').'</i>' : str_replace(array("\n", "\r"), " ", $aVal['display']);
  994. $sTip .= "<li>".Dict::Format('UI:BulkModify:Value_Exists_N_Times', $sDisplayValue, $aVal['count'])."</li>";
  995. $index++;
  996. if ($iMaxCount == $index)
  997. {
  998. $sTip .= "<li>".Dict::Format('UI:BulkModify:N_MoreValues', count($aMultiValues) - $iMaxCount)."</li>";
  999. break;
  1000. }
  1001. }
  1002. $sTip .= "</ul></p>";
  1003. $sTip = addslashes($sTip);
  1004. $sReadyScript .= "$('#multi_values_$sAttCode').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );";
  1005. $oDummyObj->Set($sAttCode, null);
  1006. $aComments[$sAttCode] = '<input type="checkbox" id="enable_'.$iFormId.'_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$iFormId.'_'.$sAttCode.'\')"/>';
  1007. $aComments[$sAttCode] .= '<div class="multi_values" id="multi_values_'.$sAttCode.'">'.$iCount.'</div>';
  1008. }
  1009. $sReadyScript .= 'ToogleField('.(($iCount == 1) ? 'true': 'false').', \''.$iFormId.'_'.$sAttCode.'\');'."\n";
  1010. }
  1011. }
  1012. }
  1013. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1014. if (($sStateAttCode != '') && ($oDummyObj->GetState() == ''))
  1015. {
  1016. // Hmmm, it's not gonna work like this ! Set a default value for the "state"
  1017. // Maybe we should use the "state" that is the most common among the objects...
  1018. $aMultiValues = $aValues[$sStateAttCode];
  1019. uasort($aMultiValues, 'MyComparison');
  1020. foreach($aMultiValues as $sCurrValue => $aVal)
  1021. {
  1022. $oDummyObj->Set($sStateAttCode, $sCurrValue);
  1023. break;
  1024. }
  1025. //$oStateAtt = MetaModel::GetAttributeDef($sClass, $sStateAttCode);
  1026. //$oDummyObj->Set($sStateAttCode, $oStateAtt->GetDefaultValue());
  1027. }
  1028. $oP->add("<div class=\"page_header\">\n");
  1029. $oP->add("<h1>".$oDummyObj->GetIcon()."&nbsp;".Dict::Format('UI:Modify_M_ObjectsOf_Class_OutOf_N', $iAllowedCount, $sClass, $iAllowedCount)."</h1>\n");
  1030. $oP->add("</div>\n");
  1031. $oP->add("<div class=\"wizContainer\">\n");
  1032. $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));
  1033. $oP->add("</div>\n");
  1034. $oP->add_ready_script($sReadyScript);
  1035. $sURL = "./UI.php?operation=search&filter=".urlencode($sFilter)."&".$oAppContext->GetForLink();
  1036. $oP->add_ready_script(
  1037. <<<EOF
  1038. $('.wizContainer button.cancel').unbind('click');
  1039. $('.wizContainer button.cancel').click( function() { window.location.href = '$sURL'; } );
  1040. EOF
  1041. );
  1042. } // Else no object selected ???
  1043. else
  1044. {
  1045. $oP->p("No object selected !, nothing to do");
  1046. }
  1047. break;
  1048. ///////////////////////////////////////////////////////////////////////////////////////////
  1049. case 'preview_or_modify_all': // Preview or apply bulk modify
  1050. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  1051. // TO DO: limit the search filter by the user context
  1052. $oFilter = DBObjectSearch::unserialize($sFilter); // TO DO : check that the filter is valid
  1053. $oChecker = new ActionChecker($oFilter, UR_ACTION_BULK_MODIFY);
  1054. $sClass = utils::ReadParam('class', '', false, 'class');
  1055. $bPreview = utils::ReadParam('preview_mode', '');
  1056. $sSelectedObj = utils::ReadParam('selectObj', '', false, 'raw_data');
  1057. if ( empty($sClass) || empty($sSelectedObj)) // TO DO: check that the class name is valid !
  1058. {
  1059. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'selectObj'));
  1060. }
  1061. $aSelectedObj = explode(',', $sSelectedObj);
  1062. $aHeaders = array(
  1063. 'form::select' => array('label' => "<input type=\"checkbox\" onClick=\"CheckAll('.selectList:not(:disabled)', this.checked);\"></input>", 'description' => Dict::S('UI:SelectAllToggle+')),
  1064. 'object' => array('label' => MetaModel::GetName($sClass), 'description' => Dict::S('UI:ModifiedObject')),
  1065. 'status' => array('label' => Dict::S('UI:BulkModifyStatus'), 'description' => Dict::S('UI:BulkModifyStatus+')),
  1066. 'errors' => array('label' => Dict::S('UI:BulkModifyErrors'), 'description' => Dict::S('UI:BulkModifyErrors+')),
  1067. );
  1068. $aRows = array();
  1069. $oP->add("<div class=\"page_header\">\n");
  1070. $oP->add("<h1>".MetaModel::GetClassIcon($sClass)."&nbsp;".Dict::Format('UI:Modify_N_ObjectsOf_Class', count($aSelectedObj), $sClass)."</h1>\n");
  1071. $oP->add("</div>\n");
  1072. $oP->set_title(Dict::Format('UI:Modify_N_ObjectsOf_Class', count($aSelectedObj), $sClass));
  1073. if (!$bPreview)
  1074. {
  1075. // Not in preview mode, do the update for real
  1076. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1077. if (!utils::IsTransactionValid($sTransactionId, false))
  1078. {
  1079. throw new Exception(Dict::S('UI:Error:ObjectAlreadyUpdated'));
  1080. }
  1081. utils::RemoveTransaction($sTransactionId);
  1082. }
  1083. foreach($aSelectedObj as $iId)
  1084. {
  1085. $oObj = MetaModel::GetObject($sClass, $iId);
  1086. $aErrors = $oObj->UpdateObjectFromPostedForm('');
  1087. $bResult = (count($aErrors) == 0);
  1088. if ($bResult)
  1089. {
  1090. list($bResult, $aErrors) = $oObj->CheckToWrite(true /* Enforce Read-only fields */);
  1091. }
  1092. if ($bPreview)
  1093. {
  1094. $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusOk') : Dict::S('UI:BulkModifyStatusError');
  1095. }
  1096. else
  1097. {
  1098. $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusModified') : Dict::S('UI:BulkModifyStatusSkipped');
  1099. }
  1100. $sCSSClass = $bResult ? HILIGHT_CLASS_NONE : HILIGHT_CLASS_CRITICAL;
  1101. $sChecked = $bResult ? 'checked' : '';
  1102. $sDisabled = $bResult ? '' : 'disabled';
  1103. $aRows[] = array(
  1104. 'form::select' => "<input type=\"checkbox\" class=\"selectList\" $sChecked $sDisabled\"></input>",
  1105. 'object' => $oObj->GetHyperlink(),
  1106. 'status' => $sStatus,
  1107. 'errors' => '<p>'.($bResult ? '': implode('</p><p>', $aErrors)).'</p>',
  1108. '@class' => $sCSSClass,
  1109. );
  1110. if ($bResult && (!$bPreview))
  1111. {
  1112. $oObj->DBUpdate();
  1113. }
  1114. }
  1115. $oP->Table($aHeaders, $aRows);
  1116. $sURL = "./UI.php?operation=search&filter=".urlencode($sFilter)."&".$oAppContext->GetForLink();
  1117. if ($bPreview)
  1118. {
  1119. // Form to submit:
  1120. $oP->add("<form method=\"post\" action=\"UI.php\" enctype=\"multipart/form-data\">\n");
  1121. $aDefaults = utils::ReadParam('default', array());
  1122. $oP->add($oAppContext->GetForForm());
  1123. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  1124. $oP->add("<input type=\"hidden\" name=\"filter\" value=\"$sFilter\">\n");
  1125. $oP->add("<input type=\"hidden\" name=\"selectObj\" value=\"$sSelectedObj\">\n");
  1126. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"preview_or_modify_all\">\n");
  1127. $oP->add("<input type=\"hidden\" name=\"preview_mode\" value=\"0\">\n");
  1128. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  1129. $oP->add("<button type=\"button\" class=\"action cancel\" onClick=\"window.location.href='$sURL'\">".Dict::S('UI:Button:Cancel')."</button>&nbsp;&nbsp;&nbsp;&nbsp;\n");
  1130. $oP->add("<button type=\"submit\" class=\"action\"><span>".Dict::S('UI:Button:ModifyAll')."</span></button>\n");
  1131. foreach($_POST as $sKey => $value)
  1132. {
  1133. if (preg_match('/attr_(.+)/', $sKey, $aMatches))
  1134. {
  1135. // Beware: some values (like durations) are passed as arrays
  1136. if (is_array($value))
  1137. {
  1138. foreach($value as $vKey => $vValue)
  1139. {
  1140. $oP->add("<input type=\"hidden\" name=\"{$sKey}[$vKey]\" value=\"$vValue\">\n");
  1141. }
  1142. }
  1143. else
  1144. {
  1145. $oP->add("<input type=\"hidden\" name=\"$sKey\" value=\"$value\">\n");
  1146. }
  1147. }
  1148. }
  1149. $oP->add("</form>\n");
  1150. }
  1151. else
  1152. {
  1153. $sURL = "./UI.php?operation=search&filter=".urlencode($sFilter)."&".$oAppContext->GetForLink();
  1154. $oP->add("<button type=\"button\" onClick=\"window.location.href='$sURL'\" class=\"action\"><span>".Dict::S('UI:Button:Done')."</span></button>\n");
  1155. }
  1156. break;
  1157. ///////////////////////////////////////////////////////////////////////////////////////////
  1158. case 'new': // Form to create a new object
  1159. $sClass = utils::ReadParam('class', '', false, 'class');
  1160. $sStateCode = utils::ReadParam('state', '');
  1161. $bCheckSubClass = utils::ReadParam('checkSubclass', true);
  1162. if ( empty($sClass) )
  1163. {
  1164. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'class'));
  1165. }
  1166. $aArgs = utils::ReadParam('default', array(), false, 'raw_data');
  1167. $aContext = $oAppContext->GetAsHash();
  1168. foreach( $oAppContext->GetNames() as $key)
  1169. {
  1170. $aArgs[$key] = $oAppContext->GetCurrentValue($key);
  1171. }
  1172. // If the specified class has subclasses, ask the user an instance of which class to create
  1173. $aSubClasses = MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL); // Including the specified class itself
  1174. $aPossibleClasses = array();
  1175. $sRealClass = '';
  1176. if ($bCheckSubClass)
  1177. {
  1178. foreach($aSubClasses as $sCandidateClass)
  1179. {
  1180. if (!MetaModel::IsAbstract($sCandidateClass) && (UserRights::IsActionAllowed($sCandidateClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES))
  1181. {
  1182. $aPossibleClasses[$sCandidateClass] = MetaModel::GetName($sCandidateClass);
  1183. }
  1184. }
  1185. // Only one of the subclasses can be instantiated...
  1186. if (count($aPossibleClasses) == 1)
  1187. {
  1188. $aKeys = array_keys($aPossibleClasses);
  1189. $sRealClass = $aKeys[0];
  1190. }
  1191. }
  1192. else
  1193. {
  1194. $sRealClass = $sClass;
  1195. }
  1196. if (!empty($sRealClass))
  1197. {
  1198. // Display the creation form
  1199. $sClassLabel = MetaModel::GetName($sRealClass);
  1200. // Note: some code has been duplicated to the case 'apply_new' when a data integrity issue has been found
  1201. $oP->set_title(Dict::Format('UI:CreationPageTitle_Class', $sClassLabel));
  1202. $oP->add("<h1>".MetaModel::GetClassIcon($sRealClass)."&nbsp;".Dict::Format('UI:CreationTitle_Class', $sClassLabel)."</h1>\n");
  1203. $oP->add("<div class=\"wizContainer\">\n");
  1204. // Set all the default values in an object and clone this "default" object
  1205. $oObjToClone = MetaModel::NewObject($sRealClass);
  1206. // 1st - set context values
  1207. $oAppContext->InitObjectFromContext($oObjToClone);
  1208. // 2nd - set values from the page argument 'default'
  1209. $oObjToClone->UpdateObjectFromArg('default');
  1210. cmdbAbstractObject::DisplayCreationForm($oP, $sRealClass, $oObjToClone, array());
  1211. $oP->add("</div>\n");
  1212. }
  1213. else
  1214. {
  1215. // Select the derived class to create
  1216. $sClassLabel = MetaModel::GetName($sClass);
  1217. $oP->add("<h1>".MetaModel::GetClassIcon($sClass)."&nbsp;".Dict::Format('UI:CreationTitle_Class', $sClassLabel)."</h1>\n");
  1218. $oP->add("<div class=\"wizContainer\">\n");
  1219. $oP->add('<form>');
  1220. $oP->add('<p>'.Dict::Format('UI:SelectTheTypeOf_Class_ToCreate', $sClassLabel));
  1221. $aDefaults = utils::ReadParam('default', array(), false, 'raw_data');
  1222. $oP->add($oAppContext->GetForForm());
  1223. $oP->add("<input type=\"hidden\" name=\"checkSubclass\" value=\"0\">\n");
  1224. $oP->add("<input type=\"hidden\" name=\"state\" value=\"$sStateCode\">\n");
  1225. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"new\">\n");
  1226. foreach($aDefaults as $key => $value)
  1227. {
  1228. if (is_array($value))
  1229. {
  1230. foreach($value as $key2 => $value2)
  1231. {
  1232. if (is_array($value2))
  1233. {
  1234. foreach($value2 as $key3 => $value3)
  1235. {
  1236. $oP->add("<input type=\"hidden\" name=\"default[$key][$key2][$key3]\" value=\"$value3\">\n");
  1237. }
  1238. }
  1239. else
  1240. {
  1241. $oP->add("<input type=\"hidden\" name=\"default[$key][$key2]\" value=\"$value2\">\n");
  1242. }
  1243. }
  1244. }
  1245. else
  1246. {
  1247. $oP->add("<input type=\"hidden\" name=\"default[$key]\" value=\"$value\">\n");
  1248. }
  1249. }
  1250. $oP->add('<select name="class">');
  1251. asort($aPossibleClasses);
  1252. foreach($aPossibleClasses as $sClassName => $sClassLabel)
  1253. {
  1254. $sSelected = ($sClassName == $sClass) ? 'selected' : '';
  1255. $oP->add("<option $sSelected value=\"$sClassName\">$sClassLabel</option>");
  1256. }
  1257. $oP->add('</select>');
  1258. $oP->add("&nbsp; <input type=\"submit\" value=\"".Dict::S('UI:Button:Apply')."\"></p>");
  1259. $oP->add('</form>');
  1260. $oP->add("</div>\n");
  1261. }
  1262. break;
  1263. ///////////////////////////////////////////////////////////////////////////////////////////
  1264. case 'apply_modify': // Applying the modifications to an existing object
  1265. $sClass = utils::ReadPostedParam('class', '');
  1266. $sClassLabel = MetaModel::GetName($sClass);
  1267. $id = utils::ReadPostedParam('id', '');
  1268. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1269. if ( empty($sClass) || empty($id)) // TO DO: check that the class name is valid !
  1270. {
  1271. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'id'));
  1272. }
  1273. $bDisplayDetails = true;
  1274. $oObj = MetaModel::GetObject($sClass, $id, false);
  1275. if ($oObj == null)
  1276. {
  1277. $bDisplayDetails = false;
  1278. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  1279. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  1280. }
  1281. elseif (!utils::IsTransactionValid($sTransactionId, false))
  1282. {
  1283. $oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetRawName(), $sClassLabel)); // Set title will take care of the encoding
  1284. $oP->p("<strong>".Dict::S('UI:Error:ObjectAlreadyUpdated')."</strong>\n");
  1285. }
  1286. else
  1287. {
  1288. $oObj->UpdateObjectFromPostedForm();
  1289. $sMessage = '';
  1290. $sSeverity = 'ok';
  1291. if (!$oObj->IsModified())
  1292. {
  1293. $oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetRawName(), $sClassLabel)); // Set title will take care of the encoding
  1294. $sMessage = Dict::Format('UI:Class_Object_NotUpdated', MetaModel::GetName(get_class($oObj)), $oObj->GetName());
  1295. $sSeverity = 'info';
  1296. }
  1297. else
  1298. {
  1299. list($bRes, $aIssues) = $oObj->CheckToWrite();
  1300. if ($bRes)
  1301. {
  1302. $oObj->DBUpdate();
  1303. utils::RemoveTransaction($sTransactionId);
  1304. $sMessage = Dict::Format('UI:Class_Object_Updated', MetaModel::GetName(get_class($oObj)), $oObj->GetName());
  1305. $sSeverity = 'ok';
  1306. }
  1307. else
  1308. {
  1309. $bDisplayDetails = false;
  1310. // Found issues, explain and give the user a second chance
  1311. //
  1312. $oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetRawName(), $sClassLabel)); // Set title will take care of the encoding
  1313. $oP->add("<div class=\"page_header\">\n");
  1314. $oP->add("<h1>".$oObj->GetIcon()."&nbsp;".Dict::Format('UI:ModificationTitle_Class_Object', $sClassLabel, $oObj->GetName())."</h1>\n");
  1315. $oP->add("</div>\n");
  1316. $oP->add("<div class=\"wizContainer\">\n");
  1317. $oObj->DisplayModifyForm($oP);
  1318. $oP->add("</div>\n");
  1319. $sIssueDesc = Dict::Format('UI:ObjectCouldNotBeWritten', implode(', ', $aIssues));
  1320. $oP->add_ready_script("alert('".addslashes($sIssueDesc)."');");
  1321. }
  1322. }
  1323. }
  1324. if ($bDisplayDetails)
  1325. {
  1326. $oObj = MetaModel::GetObject(get_class($oObj), $oObj->GetKey()); //Workaround: reload the object so that the linkedset are displayed properly
  1327. $sNextAction = utils::ReadPostedParam('next_action', '');
  1328. if (!empty($sNextAction))
  1329. {
  1330. ApplyNextAction($oP, $oObj, $sNextAction);
  1331. }
  1332. else
  1333. {
  1334. // Nothing more to do
  1335. ReloadAndDisplay($oP, $oObj, $sMessage, $sSeverity);
  1336. }
  1337. }
  1338. break;
  1339. ///////////////////////////////////////////////////////////////////////////////////////////
  1340. case 'select_for_deletion': // Select multiple objects for deletion
  1341. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  1342. if (empty($sFilter))
  1343. {
  1344. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'filter'));
  1345. }
  1346. $oP->set_title(Dict::S('UI:BulkDeletePageTitle'));
  1347. $oP->add("<h1>".Dict::S('UI:BulkDeleteTitle')."</h1>\n");
  1348. // TO DO: limit the search filter by the user context
  1349. $oFilter = CMDBSearchFilter::unserialize($sFilter); // TO DO : check that the filter is valid
  1350. $oChecker = new ActionChecker($oFilter, UR_ACTION_BULK_DELETE);
  1351. DisplayMultipleSelectionForm($oP, $oFilter, 'bulk_delete', $oChecker);
  1352. break;
  1353. ///////////////////////////////////////////////////////////////////////////////////////////
  1354. case 'bulk_delete_confirmed': // Confirm bulk deletion of objects
  1355. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1356. if (!utils::IsTransactionValid($sTransactionId))
  1357. {
  1358. throw new ApplicationException(Dict::S('UI:Error:ObjectsAlreadyDeleted'));
  1359. }
  1360. // Fall through
  1361. ///////////////////////////////////////////////////////////////////////////////////////////
  1362. case 'bulk_delete': // Actual bulk deletion (if confirmed)
  1363. $sClass = utils::ReadPostedParam('class', '');
  1364. $sClassLabel = MetaModel::GetName($sClass);
  1365. $sFilter = utils::ReadPostedParam('filter', '');
  1366. $oFullSetFilter = DBObjectSearch::unserialize($sFilter);
  1367. $aSelectObject = utils::ReadMultipleSelection($oFullSetFilter);
  1368. $aObjects = array();
  1369. if ( empty($sClass) || empty($aSelectObject)) // TO DO: check that the class name is valid !
  1370. {
  1371. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'selectObject[]'));
  1372. }
  1373. foreach($aSelectObject as $iId)
  1374. {
  1375. $aObjects[] = MetaModel::GetObject($sClass, $iId);
  1376. }
  1377. if (!UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_DELETE, DBObjectSet::FromArray($sClass, $aObjects)))
  1378. {
  1379. throw new SecurityException(Dict::Format('UI:Error:BulkDeleteNotAllowedOn_Class', $sClass));
  1380. }
  1381. $oP->set_title(Dict::S('UI:BulkDeletePageTitle'));
  1382. DeleteObjects($oP, $sClass, $aObjects, ($operation == 'bulk_delete_confirmed'), $oFullSetFilter);
  1383. break;
  1384. ///////////////////////////////////////////////////////////////////////////////////////////
  1385. case 'delete': // Deletion (preview)
  1386. case 'delete_confirmed': // Deletion (confirmed)
  1387. $sClass = utils::ReadParam('class', '', false, 'class');
  1388. $sClassLabel = MetaModel::GetName($sClass);
  1389. $id = utils::ReadParam('id', '');
  1390. $oObj = MetaModel::GetObject($sClass, $id);
  1391. if (!UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, DBObjectSet::FromObject($oObj)))
  1392. {
  1393. throw new SecurityException(Dict::Format('UI:Error:DeleteNotAllowedOn_Class', $sClass));
  1394. }
  1395. DeleteObjects($oP, $sClass, array($oObj), ($operation == 'delete_confirmed'));
  1396. break;
  1397. ///////////////////////////////////////////////////////////////////////////////////////////
  1398. case 'apply_new': // Creation of a new object
  1399. $sClass = utils::ReadPostedParam('class', '', 'class');
  1400. $sClassLabel = MetaModel::GetName($sClass);
  1401. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1402. if ( empty($sClass) ) // TO DO: check that the class name is valid !
  1403. {
  1404. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'class'));
  1405. }
  1406. if (!utils::IsTransactionValid($sTransactionId, false))
  1407. {
  1408. $oP->p("<strong>".Dict::S('UI:Error:ObjectAlreadyCreated')."</strong>\n");
  1409. }
  1410. else
  1411. {
  1412. $oObj = MetaModel::NewObject($sClass);
  1413. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1414. if (!empty($sStateAttCode))
  1415. {
  1416. $sTargetState = utils::ReadPostedParam('obj_state', '');
  1417. if ($sTargetState != '')
  1418. {
  1419. $oObj->Set($sStateAttCode, $sTargetState);
  1420. }
  1421. }
  1422. $oObj->UpdateObjectFromPostedForm();
  1423. }
  1424. if (isset($oObj) && is_object($oObj))
  1425. {
  1426. $sClass = get_class($oObj);
  1427. $sClassLabel = MetaModel::GetName($sClass);
  1428. list($bRes, $aIssues) = $oObj->CheckToWrite();
  1429. if ($bRes)
  1430. {
  1431. $oObj->DBInsert();
  1432. utils::RemoveTransaction($sTransactionId);
  1433. $oP->set_title(Dict::S('UI:PageTitle:ObjectCreated'));
  1434. $sMessage = Dict::Format('UI:Title:Object_Of_Class_Created', $oObj->GetName(), $sClassLabel);
  1435. $oObj = MetaModel::GetObject(get_class($oObj), $oObj->GetKey()); //Workaround: reload the object so that the linkedset are displayed properly
  1436. $sNextAction = utils::ReadPostedParam('next_action', '');
  1437. if (!empty($sNextAction))
  1438. {
  1439. $oP->add("<h1>$sMessage</h1>");
  1440. ApplyNextAction($oP, $oObj, $sNextAction);
  1441. }
  1442. else
  1443. {
  1444. // Nothing more to do
  1445. ReloadAndDisplay($oP, $oObj, $sMessage, 'ok');
  1446. }
  1447. }
  1448. else
  1449. {
  1450. // Found issues, explain and give the user a second chance
  1451. //
  1452. $oP->set_title(Dict::Format('UI:CreationPageTitle_Class', $sClassLabel));
  1453. $oP->add("<h1>".MetaModel::GetClassIcon($sClass)."&nbsp;".Dict::Format('UI:CreationTitle_Class', $sClassLabel)."</h1>\n");
  1454. $oP->add("<div class=\"wizContainer\">\n");
  1455. cmdbAbstractObject::DisplayCreationForm($oP, $sClass, $oObj);
  1456. $oP->add("</div>\n");
  1457. $sIssueDesc = Dict::Format('UI:ObjectCouldNotBeWritten', implode(', ', $aIssues));
  1458. $oP->add_ready_script("alert('".addslashes($sIssueDesc)."');");
  1459. }
  1460. }
  1461. break;
  1462. ///////////////////////////////////////////////////////////////////////////////////////////
  1463. case 'select_bulk_stimulus': // Form displayed when applying a stimulus to many objects
  1464. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  1465. $sStimulus = utils::ReadParam('stimulus', '');
  1466. $sState = utils::ReadParam('state', '');
  1467. if (empty($sFilter) || empty($sStimulus) || empty($sState))
  1468. {
  1469. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state'));
  1470. }
  1471. $oFilter = DBObjectSearch::unserialize($sFilter);
  1472. $sClass = $oFilter->GetClass();
  1473. $aStimuli = MetaModel::EnumStimuli($sClass);
  1474. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1475. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1476. $oP->set_title($sActionLabel);
  1477. $oP->add('<div class="page_header">');
  1478. $oP->add('<h1>'.MetaModel::GetClassIcon($sClass).'&nbsp;'.$sActionLabel.'</h1>');
  1479. $oP->add('</div>');
  1480. $oChecker = new StimulusChecker($oFilter, $sState, $sStimulus);
  1481. $aExtraFormParams = array('stimulus' => $sStimulus, 'state' => $sState);
  1482. DisplayMultipleSelectionForm($oP, $oFilter, 'bulk_stimulus', $oChecker, $aExtraFormParams);
  1483. break;
  1484. case 'bulk_stimulus':
  1485. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  1486. $sStimulus = utils::ReadParam('stimulus', '');
  1487. $sState = utils::ReadParam('state', '');
  1488. if (empty($sFilter) || empty($sStimulus) || empty($sState))
  1489. {
  1490. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state'));
  1491. }
  1492. $oFilter = DBObjectSearch::unserialize($sFilter);
  1493. $sClass = $oFilter->GetClass();
  1494. $aSelectObject = utils::ReadMultipleSelection($oFilter);
  1495. if (count($aSelectObject) == 0)
  1496. {
  1497. // Nothing to do, no object was selected !
  1498. throw new ApplicationException(Dict::S('UI:BulkAction:NoObjectSelected'));
  1499. }
  1500. else
  1501. {
  1502. $aTransitions = MetaModel::EnumTransitions($sClass, $sState);
  1503. $aStimuli = MetaModel::EnumStimuli($sClass);
  1504. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1505. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1506. $aTransition = $aTransitions[$sStimulus];
  1507. $sTargetState = $aTransition['target_state'];
  1508. $aStates = MetaModel::EnumStates($sClass);
  1509. $aTargetStateDef = $aStates[$sTargetState];
  1510. $oP->set_title(Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aSelectObject), $sClass));
  1511. $oP->add('<div class="page_header">');
  1512. $oP->add('<h1>'.MetaModel::GetClassIcon($sClass).'&nbsp;'.Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aSelectObject), $sClass).'</h1>');
  1513. $oP->add('</div>');
  1514. $aExpectedAttributes = $aTargetStateDef['attribute_list'];
  1515. $aDetails = array();
  1516. $iFieldIndex = 0;
  1517. $aFieldsMap = array();
  1518. $aValues = array();
  1519. $aObjects = array();
  1520. foreach($aSelectObject as $iId)
  1521. {
  1522. $aObjects[] = MetaModel::GetObject($sClass, $iId);
  1523. }
  1524. $oSet = DBObjectSet::FromArray($sClass, $aObjects);
  1525. $oObj = $oSet->ComputeCommonObject($aValues);
  1526. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1527. $oObj->Set($sStateAttCode,$sTargetState);
  1528. $sReadyScript = '';
  1529. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  1530. {
  1531. // Prompt for an attribute if
  1532. // - the attribute must be changed or must be displayed to the user for confirmation
  1533. // - or the field is mandatory and currently empty
  1534. if ( ($iExpectCode & (OPT_ATT_MUSTCHANGE | OPT_ATT_MUSTPROMPT)) ||
  1535. (($iExpectCode & OPT_ATT_MANDATORY) && ($oObj->Get($sAttCode) == '')) )
  1536. {
  1537. $aAttributesDef = MetaModel::ListAttributeDefs($sClass);
  1538. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1539. $aPrerequisites = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  1540. if (count($aPrerequisites) > 0)
  1541. {
  1542. // When 'enabling' a field, all its prerequisites must be enabled too
  1543. $sFieldList = "['".implode("','", $aPrerequisites)."']";
  1544. $oP->add_ready_script("$('#enable_{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, true); } );\n");
  1545. }
  1546. $aDependents = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  1547. if (count($aDependents) > 0)
  1548. {
  1549. // When 'disabling' a field, all its dependent fields must be disabled too
  1550. $sFieldList = "['".implode("','", $aDependents)."']";
  1551. $oP->add_ready_script("$('#enable_{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, false); } );\n");
  1552. }
  1553. $aArgs = array('this' => $oObj);
  1554. $sHTMLValue = cmdbAbstractObject::GetFormElementForField($oP, $sClass, $sAttCode, $oAttDef, $oObj->Get($sAttCode), $oObj->GetEditValue($sAttCode), $sAttCode, '', $iExpectCode, $aArgs);
  1555. $sComments = '<input type="checkbox" checked id="enable_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$sAttCode.'\')"/>';
  1556. if (!isset($aValues[$sAttCode]))
  1557. {
  1558. $aValues[$sAttCode] = array();
  1559. }
  1560. if (count($aValues[$sAttCode]) == 1)
  1561. {
  1562. $sComments .= '<div class="mono_value">1</div>';
  1563. }
  1564. else
  1565. {
  1566. // Non-homogenous value
  1567. $iMaxCount = 5;
  1568. $sTip = "<p><b>".Dict::Format('UI:BulkModify_Count_DistinctValues', count($aValues[$sAttCode]))."</b><ul>";
  1569. $index = 0;
  1570. foreach($aValues[$sAttCode] as $sCurrValue => $aVal)
  1571. {
  1572. $sDisplayValue = empty($aVal['display']) ? '<i>'.Dict::S('Enum:Undefined').'</i>' : str_replace(array("\n", "\r"), " ", $aVal['display']);
  1573. $sTip .= "<li>".Dict::Format('UI:BulkModify:Value_Exists_N_Times', $sDisplayValue, $aVal['count'])."</li>";
  1574. $index++;
  1575. if ($iMaxCount == $index)
  1576. {
  1577. $sTip .= "<li>".Dict::Format('UI:BulkModify:N_MoreValues', count($aValues[$sAttCode]) - $iMaxCount)."</li>";
  1578. break;
  1579. }
  1580. }
  1581. $sTip .= "</ul></p>";
  1582. $sTip = addslashes($sTip);
  1583. $sReadyScript .= "$('#multi_values_$sAttCode').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );\n";
  1584. $sComments .= '<div class="multi_values" id="multi_values_'.$sAttCode.'">'.count($aValues[$sAttCode]).'</div>';
  1585. }
  1586. $aDetails[] = array('label' => '<span>'.$oAttDef->GetLabel().'</span>', 'value' => "<span id=\"field_$sAttCode\">$sHTMLValue</span>", 'comments' => $sComments);
  1587. $aFieldsMap[$sAttCode] = $sAttCode;
  1588. $iFieldIndex++;
  1589. }
  1590. }
  1591. $sButtonsPosition = MetaModel::GetConfig()->Get('buttons_position');
  1592. if ($sButtonsPosition == 'bottom')
  1593. {
  1594. // bottom: Displays the ticket details BEFORE the actions
  1595. $oP->add('<div class="ui-widget-content">');
  1596. $oObj->DisplayBareProperties($oP);
  1597. $oP->add('</div>');
  1598. }
  1599. $oP->add("<div class=\"wizContainer\">\n");
  1600. $oP->add("<form id=\"apply_stimulus\" method=\"post\" onSubmit=\"return OnSubmit('apply_stimulus');\">\n");
  1601. $oP->add("<table><tr><td>\n");
  1602. $oP->details($aDetails);
  1603. $oP->add("</td></tr></table>\n");
  1604. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  1605. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"bulk_apply_stimulus\">\n");
  1606. $oP->add("<input type=\"hidden\" name=\"preview_mode\" value=\"1\">\n");
  1607. $oP->add("<input type=\"hidden\" name=\"filter\" value=\"$sFilter\">\n");
  1608. $oP->add("<input type=\"hidden\" name=\"stimulus\" value=\"$sStimulus\">\n");
  1609. $oP->add("<input type=\"hidden\" name=\"state\" value=\"$sState\">\n");
  1610. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  1611. $oP->add($oAppContext->GetForForm());
  1612. $oP->add("<input type=\"hidden\" name=\"selectObject\" value=\"".implode(',',$aSelectObject)."\">\n");
  1613. $sURL = "./UI.php?operation=search&filter=".urlencode($sFilter)."&".$oAppContext->GetForLink();
  1614. $oP->add("<input type=\"button\" value=\"".Dict::S('UI:Button:Cancel')."\" onClick=\"window.location.href='$sURL'\">&nbsp;&nbsp;&nbsp;&nbsp;\n");
  1615. $oP->add("<button type=\"submit\" class=\"action\"><span>$sActionLabel</span></button>\n");
  1616. $oP->add("</form>\n");
  1617. $oP->add("</div>\n");
  1618. if ($sButtonsPosition != 'bottom')
  1619. {
  1620. // top or both: Displays the ticket details AFTER the actions
  1621. $oP->add('<div class="ui-widget-content">');
  1622. $oObj->DisplayBareProperties($oP);
  1623. $oP->add('</div>');
  1624. }
  1625. $iFieldsCount = count($aFieldsMap);
  1626. $sJsonFieldsMap = json_encode($aFieldsMap);
  1627. $oP->add_script(
  1628. <<<EOF
  1629. // Initializes the object once at the beginning of the page...
  1630. var oWizardHelper = new WizardHelper('$sClass', '', '$sTargetState');
  1631. oWizardHelper.SetFieldsMap($sJsonFieldsMap);
  1632. oWizardHelper.SetFieldsCount($iFieldsCount);
  1633. EOF
  1634. );
  1635. $oP->add_ready_script(
  1636. <<<EOF
  1637. // Starts the validation when the page is ready
  1638. CheckFields('apply_stimulus', false);
  1639. $sReadyScript
  1640. EOF
  1641. );
  1642. }
  1643. break;
  1644. case 'bulk_apply_stimulus':
  1645. $bPreviewMode = utils::ReadPostedParam('preview_mode', false);
  1646. $sFilter = utils::ReadPostedParam('filter', '', false, 'raw_data');
  1647. $sStimulus = utils::ReadPostedParam('stimulus', '');
  1648. $sState = utils::ReadPostedParam('state', '');
  1649. $sSelectObject = utils::ReadPostedParam('selectObject', '', false, 'raw_data');
  1650. $aSelectObject = explode(',', $sSelectObject);
  1651. if (empty($sFilter) || empty($sStimulus) || empty($sState))
  1652. {
  1653. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state'));
  1654. }
  1655. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1656. if (!utils::IsTransactionValid($sTransactionId))
  1657. {
  1658. $oP->p(Dict::S('UI:Error:ObjectAlreadyUpdated'));
  1659. }
  1660. else
  1661. {
  1662. // For archiving the modification
  1663. $oFilter = DBObjectSearch::unserialize($sFilter);
  1664. $sClass = $oFilter->GetClass();
  1665. $aObjects = array();
  1666. foreach($aSelectObject as $iId)
  1667. {
  1668. $aObjects[] = MetaModel::GetObject($sClass, $iId);
  1669. }
  1670. $aTransitions = MetaModel::EnumTransitions($sClass, $sState);
  1671. $aStimuli = MetaModel::EnumStimuli($sClass);
  1672. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1673. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1674. $oP->set_title(Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aObjects), $sClass));
  1675. $oP->add('<div class="page_header">');
  1676. $oP->add('<h1>'.MetaModel::GetClassIcon($sClass).'&nbsp;'.Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aObjects), $sClass).'</h1>');
  1677. $oP->add('</div>');
  1678. $oSet = DBObjectSet::FromArray($sClass, $aObjects);
  1679. // For reporting
  1680. $aHeaders = array(
  1681. 'object' => array('label' => MetaModel::GetName($sClass), 'description' => Dict::S('UI:ModifiedObject')),
  1682. 'status' => array('label' => Dict::S('UI:BulkModifyStatus'), 'description' => Dict::S('UI:BulkModifyStatus+')),
  1683. 'errors' => array('label' => Dict::S('UI:BulkModifyErrors'), 'description' => Dict::S('UI:BulkModifyErrors+')),
  1684. );
  1685. $aRows = array();
  1686. while ($oObj = $oSet->Fetch())
  1687. {
  1688. $sError = Dict::S('UI:BulkModifyStatusOk');
  1689. try
  1690. {
  1691. $aTransitions = $oObj->EnumTransitions();
  1692. $aStimuli = MetaModel::EnumStimuli($sClass);
  1693. if (!isset($aTransitions[$sStimulus]))
  1694. {
  1695. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
  1696. }
  1697. else
  1698. {
  1699. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1700. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1701. $aTransition = $aTransitions[$sStimulus];
  1702. $sTargetState = $aTransition['target_state'];
  1703. $aTargetStates = MetaModel::EnumStates($sClass);
  1704. $aTargetState = $aTargetStates[$sTargetState];
  1705. $aExpectedAttributes = $aTargetState['attribute_list'];
  1706. $aDetails = array();
  1707. $aErrors = array();
  1708. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  1709. {
  1710. $iFlags = $oObj->GetAttributeFlags($sAttCode);
  1711. if (($iExpectCode & (OPT_ATT_MUSTCHANGE|OPT_ATT_MUSTPROMPT)) || ($oObj->Get($sAttCode) == '') )
  1712. {
  1713. $paramValue = utils::ReadPostedParam("attr_$sAttCode", '', 'raw_data');
  1714. if ( ($iFlags & OPT_ATT_SLAVE) && ($paramValue != $oObj->Get($sAttCode)) )
  1715. {
  1716. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1717. $aErrors[] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $oAttDef->GetLabel());
  1718. unset($aExpectedAttributes[$sAttCode]);
  1719. }
  1720. }
  1721. }
  1722. $oObj->UpdateObjectFromPostedForm('', array_keys($aExpectedAttributes), $sTargetState);
  1723. if (count($aErrors) == 0)
  1724. {
  1725. if ($oObj->ApplyStimulus($sStimulus))
  1726. {
  1727. list($bResult, $aErrors) = $oObj->CheckToWrite();
  1728. $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusModified') : Dict::S('UI:BulkModifyStatusSkipped');
  1729. if ($bResult)
  1730. {
  1731. $oObj->DBUpdate();
  1732. }
  1733. else
  1734. {
  1735. $sError = '<p>'.implode('</p></p>',$aErrors)."</p>\n";
  1736. }
  1737. }
  1738. else
  1739. {
  1740. $sStatus = Dict::S('UI:BulkModifyStatusSkipped');
  1741. $sError = '<p>'.Dict::S('UI:FailedToApplyStimuli')."<p>\n";
  1742. }
  1743. }
  1744. else
  1745. {
  1746. $sStatus = Dict::S('UI:BulkModifyStatusSkipped');
  1747. $sError = '<p>'.implode('</p></p>',$aErrors)."</p>\n";
  1748. }
  1749. }
  1750. }
  1751. catch(Exception $e)
  1752. {
  1753. $sError = $e->getMessage();
  1754. $sStatus = Dict::S('UI:BulkModifyStatusSkipped');
  1755. }
  1756. $aRows[] = array(
  1757. 'object' => $oObj->GetHyperlink(),
  1758. 'status' => $sStatus,
  1759. 'errors' => $sError,
  1760. );
  1761. }
  1762. $oP->Table($aHeaders, $aRows);
  1763. // Back to the list
  1764. $sURL = "./UI.php?operation=search&filter=".urlencode($sFilter)."&".$oAppContext->GetForLink();
  1765. $oP->add('<input type="button" onClick="window.location.href=\''.$sURL.'\'" value="'.Dict::S('UI:Button:Done').'">');
  1766. }
  1767. break;
  1768. case 'stimulus': // Form displayed when applying a stimulus (state change)
  1769. $sClass = utils::ReadParam('class', '', false, 'class');
  1770. $id = utils::ReadParam('id', '');
  1771. $sStimulus = utils::ReadParam('stimulus', '');
  1772. if ( empty($sClass) || empty($id) || empty($sStimulus) ) // TO DO: check that the class name is valid !
  1773. {
  1774. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'class', 'id', 'stimulus'));
  1775. }
  1776. $oObj = MetaModel::GetObject($sClass, $id, false);
  1777. if ($oObj != null)
  1778. {
  1779. $aTransitions = $oObj->EnumTransitions();
  1780. $aStimuli = MetaModel::EnumStimuli($sClass);
  1781. if (!isset($aTransitions[$sStimulus]))
  1782. {
  1783. // Invalid stimulus
  1784. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
  1785. }
  1786. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1787. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1788. $aTransition = $aTransitions[$sStimulus];
  1789. $sTargetState = $aTransition['target_state'];
  1790. $aTargetStates = MetaModel::EnumStates($sClass);
  1791. $oP->add("<div class=\"page_header\">\n");
  1792. $oP->add("<h1>$sActionLabel - <span class=\"hilite\">{$oObj->GetName()}</span></h1>\n");
  1793. $oP->set_title($sActionLabel);
  1794. $oP->add("</div>\n");
  1795. $aTargetState = $aTargetStates[$sTargetState];
  1796. $aExpectedAttributes = $aTargetState['attribute_list'];
  1797. $oP->add("<h1>$sActionDetails</h1>\n");
  1798. $sButtonsPosition = MetaModel::GetConfig()->Get('buttons_position');
  1799. if ($sButtonsPosition == 'bottom')
  1800. {
  1801. // bottom: Displays the ticket details BEFORE the actions
  1802. $oP->add('<div class="ui-widget-content">');
  1803. $oObj->DisplayBareProperties($oP);
  1804. $oP->add('</div>');
  1805. }
  1806. $oP->add("<div class=\"wizContainer\">\n");
  1807. $oP->add("<form id=\"apply_stimulus\" method=\"post\" onSubmit=\"return OnSubmit('apply_stimulus');\">\n");
  1808. $aDetails = array();
  1809. $iFieldIndex = 0;
  1810. $aFieldsMap = array();
  1811. $aDetailsList = $oObj->FlattenZList(MetaModel::GetZListItems($sClass, 'details'));
  1812. // Order the fields based on their dependencies, set the fields for which there is only one possible value
  1813. // and perform this in the order of dependencies to avoid dead-ends
  1814. $aDeps = array();
  1815. foreach($aDetailsList as $sAttCode)
  1816. {
  1817. $aDeps[$sAttCode] = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode);
  1818. }
  1819. $aList = $oObj->OrderDependentFields($aDeps);
  1820. foreach($aList as $sAttCode)
  1821. {
  1822. // Consider only the "expected" fields for the target state
  1823. if (array_key_exists($sAttCode, $aExpectedAttributes))
  1824. {
  1825. $iExpectCode = $aExpectedAttributes[$sAttCode];
  1826. // Prompt for an attribute if
  1827. // - the attribute must be changed or must be displayed to the user for confirmation
  1828. // - or the field is mandatory and currently empty
  1829. if ( ($iExpectCode & (OPT_ATT_MUSTCHANGE | OPT_ATT_MUSTPROMPT)) ||
  1830. (($iExpectCode & OPT_ATT_MANDATORY) && ($oObj->Get($sAttCode) == '')) )
  1831. {
  1832. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1833. $aArgs = array('this' => $oObj);
  1834. // If the field is mandatory, set it to the only possible value
  1835. if ((!$oAttDef->IsNullAllowed()) || ($iExpectCode & OPT_ATT_MANDATORY))
  1836. {
  1837. if ($oAttDef->IsExternalKey())
  1838. {
  1839. $oAllowedValues = MetaModel::GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs);
  1840. if ($oAllowedValues->Count() == 1)
  1841. {
  1842. $oRemoteObj = $oAllowedValues->Fetch();
  1843. $oObj->Set($sAttCode, $oRemoteObj->GetKey());
  1844. }
  1845. }
  1846. else
  1847. {
  1848. $aAllowedValues = MetaModel::GetAllowedValues_att($sClass, $sAttCode, $aArgs);
  1849. if (count($aAllowedValues) == 1)
  1850. {
  1851. $aValues = array_keys($aAllowedValues);
  1852. $oObj->Set($sAttCode, $aValues[0]);
  1853. }
  1854. }
  1855. }
  1856. $sHTMLValue = cmdbAbstractObject::GetFormElementForField($oP, $sClass, $sAttCode, $oAttDef, $oObj->Get($sAttCode), $oObj->GetEditValue($sAttCode), 'att_'.$iFieldIndex, '', $iExpectCode, $aArgs);
  1857. $aDetails[] = array('label' => '<span>'.$oAttDef->GetLabel().'</span>', 'value' => "<span id=\"field_att_$iFieldIndex\">$sHTMLValue</span>");
  1858. $aFieldsMap[$sAttCode] = 'att_'.$iFieldIndex;
  1859. $iFieldIndex++;
  1860. }
  1861. }
  1862. }
  1863. $oP->add('<table><tr><td>');
  1864. $oP->details($aDetails);
  1865. $oP->add('</td></tr></table>');
  1866. $oP->add("<input type=\"hidden\" name=\"id\" value=\"$id\" id=\"id\">\n");
  1867. $aFieldsMap['id'] = 'id';
  1868. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  1869. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"apply_stimulus\">\n");
  1870. $oP->add("<input type=\"hidden\" name=\"stimulus\" value=\"$sStimulus\">\n");
  1871. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  1872. $oP->add($oAppContext->GetForForm());
  1873. $oP->add("<button type=\"button\" class=\"action\" onClick=\"BackToDetails('$sClass', $id)\"><span>".Dict::S('UI:Button:Cancel')."</span></button>&nbsp;&nbsp;&nbsp;&nbsp;\n");
  1874. $oP->add("<button type=\"submit\" class=\"action\"><span>$sActionLabel</span></button>\n");
  1875. $oP->add("</form>\n");
  1876. $oP->add("</div>\n");
  1877. if ($sButtonsPosition != 'top')
  1878. {
  1879. // bottom or both: Displays the ticket details AFTER the actions
  1880. $oP->add('<div class="ui-widget-content">');
  1881. $oObj->DisplayBareProperties($oP);
  1882. $oP->add('</div>');
  1883. }
  1884. $iFieldsCount = count($aFieldsMap);
  1885. $sJsonFieldsMap = json_encode($aFieldsMap);
  1886. $oP->add_script(
  1887. <<<EOF
  1888. // Initializes the object once at the beginning of the page...
  1889. var oWizardHelper = new WizardHelper('$sClass', '', '$sTargetState');
  1890. oWizardHelper.SetFieldsMap($sJsonFieldsMap);
  1891. oWizardHelper.SetFieldsCount($iFieldsCount);
  1892. EOF
  1893. );
  1894. $oP->add_ready_script(
  1895. <<<EOF
  1896. // Starts the validation when the page is ready
  1897. CheckFields('apply_stimulus', false);
  1898. EOF
  1899. );
  1900. }
  1901. else
  1902. {
  1903. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  1904. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  1905. }
  1906. break;
  1907. ///////////////////////////////////////////////////////////////////////////////////////////
  1908. case 'apply_stimulus': // Actual state change
  1909. $sClass = utils::ReadPostedParam('class', '');
  1910. $id = utils::ReadPostedParam('id', '');
  1911. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1912. $sStimulus = utils::ReadPostedParam('stimulus', '');
  1913. if ( empty($sClass) || empty($id) || empty($sStimulus) ) // TO DO: check that the class name is valid !
  1914. {
  1915. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'class', 'id', 'stimulus'));
  1916. }
  1917. $oObj = MetaModel::GetObject($sClass, $id, false);
  1918. if ($oObj != null)
  1919. {
  1920. $aTransitions = $oObj->EnumTransitions();
  1921. $aStimuli = MetaModel::EnumStimuli($sClass);
  1922. $sMessage = '';
  1923. $sSeverity = 'ok';
  1924. if (!isset($aTransitions[$sStimulus]))
  1925. {
  1926. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
  1927. }
  1928. if (!utils::IsTransactionValid($sTransactionId))
  1929. {
  1930. $sMessage = Dict::S('UI:Error:ObjectAlreadyUpdated');
  1931. $sSeverity = 'info';
  1932. }
  1933. else
  1934. {
  1935. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1936. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1937. $aTransition = $aTransitions[$sStimulus];
  1938. $sTargetState = $aTransition['target_state'];
  1939. $aTargetStates = MetaModel::EnumStates($sClass);
  1940. $aTargetState = $aTargetStates[$sTargetState];
  1941. $aExpectedAttributes = $aTargetState['attribute_list'];
  1942. $aDetails = array();
  1943. $aErrors = array();
  1944. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  1945. {
  1946. $iFlags = $oObj->GetAttributeFlags($sAttCode);
  1947. if (($iExpectCode & (OPT_ATT_MUSTCHANGE|OPT_ATT_MUSTPROMPT)) || ($oObj->Get($sAttCode) == '') )
  1948. {
  1949. $paramValue = utils::ReadPostedParam("attr_$sAttCode", '', 'raw_data');
  1950. if ( ($iFlags & OPT_ATT_SLAVE) && ($paramValue != $oObj->Get($sAttCode)))
  1951. {
  1952. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1953. $aErrors[] = Dict::Format('UI:AttemptingToChangeASlaveAttribute_Name', $oAttDef->GetLabel());
  1954. unset($aExpectedAttributes[$sAttCode]);
  1955. }
  1956. }
  1957. }
  1958. $oObj->UpdateObjectFromPostedForm('', array_keys($aExpectedAttributes), $sTargetState);
  1959. if (count($aErrors) == 0)
  1960. {
  1961. if ($oObj->ApplyStimulus($sStimulus))
  1962. {
  1963. $oObj->DBUpdate();
  1964. $sMessage = Dict::Format('UI:Class_Object_Updated', MetaModel::GetName(get_class($oObj)), $oObj->GetName());
  1965. $sSeverity = 'ok';
  1966. }
  1967. else
  1968. {
  1969. $sMessage = Dict::S('UI:FailedToApplyStimuli');
  1970. $sSeverity = 'error';
  1971. }
  1972. }
  1973. else
  1974. {
  1975. $sMessage = implode('</p><p>', $aErrors);
  1976. $sSeverity = 'error';
  1977. }
  1978. }
  1979. ReloadAndDisplay($oP, $oObj, $sMessage, $sSeverity);
  1980. }
  1981. else
  1982. {
  1983. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  1984. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  1985. }
  1986. break;
  1987. ///////////////////////////////////////////////////////////////////////////////////////////
  1988. case 'swf_navigator': // Graphical display of the relations "impact" / "depends on"
  1989. $sClass = utils::ReadParam('class', '', false, 'class');
  1990. $id = utils::ReadParam('id', 0);
  1991. $sRelation = utils::ReadParam('relation', 'impact');
  1992. $aResults = array();
  1993. $oObj = MetaModel::GetObject($sClass, $id);
  1994. $oObj->GetRelatedObjects($sRelation, 20 /* iMaxDepth */, $aResults);
  1995. $oP->AddTabContainer('Navigator');
  1996. $oP->SetCurrentTabContainer('Navigator');
  1997. $sFirstTab = MetaModel::GetConfig()->Get('impact_analysis_first_tab');
  1998. if ($sFirstTab == 'list')
  1999. {
  2000. DisplayNavigatorListTab($oP, $aResults, $sRelation, $oObj);
  2001. DisplayNavigatorGraphicsTab($oP, $aResults, $sClass, $id, $sRelation, $oAppContext);
  2002. }
  2003. else
  2004. {
  2005. DisplayNavigatorGraphicsTab($oP, $aResults, $sClass, $id, $sRelation, $oAppContext);
  2006. DisplayNavigatorListTab($oP, $aResults, $sRelation, $oObj);
  2007. }
  2008. $oP->SetCurrentTab('');
  2009. break;
  2010. ///////////////////////////////////////////////////////////////////////////////////////////
  2011. case 'cancel': // An action was cancelled
  2012. $oP->set_title(Dict::S('UI:OperationCancelled'));
  2013. $oP->add('<h1>'.Dict::S('UI:OperationCancelled').'</h1>');
  2014. break;
  2015. ///////////////////////////////////////////////////////////////////////////////////////////
  2016. default: // Menu node rendering (templates)
  2017. ApplicationMenu::LoadAdditionalMenus();
  2018. $oMenuNode = ApplicationMenu::GetMenuNode(ApplicationMenu::GetMenuIndexById(ApplicationMenu::GetActiveNodeId()));
  2019. if (is_object($oMenuNode))
  2020. {
  2021. $oMenuNode->RenderContent($oP, $oAppContext->GetAsHash());
  2022. $oP->set_title($oMenuNode->GetLabel());
  2023. }
  2024. ///////////////////////////////////////////////////////////////////////////////////////////
  2025. }
  2026. $oKPI->ComputeAndReport('GUI creation before output');
  2027. ExecutionKPI::ReportStats();
  2028. DisplayWelcomePopup($oP);
  2029. $oP->output();
  2030. }
  2031. catch(CoreException $e)
  2032. {
  2033. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  2034. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  2035. if ($e instanceof SecurityException)
  2036. {
  2037. $oP->add("<h1>".Dict::S('UI:SystemIntrusion')."</h1>\n");
  2038. }
  2039. else
  2040. {
  2041. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  2042. }
  2043. $oP->error(Dict::Format('UI:Error_Details', $e->getHtmlDesc()));
  2044. $oP->output();
  2045. if (MetaModel::IsLogEnabledIssue())
  2046. {
  2047. if (MetaModel::IsValidClass('EventIssue'))
  2048. {
  2049. try
  2050. {
  2051. $oLog = new EventIssue();
  2052. $oLog->Set('message', $e->getMessage());
  2053. $oLog->Set('userinfo', '');
  2054. $oLog->Set('issue', $e->GetIssue());
  2055. $oLog->Set('impact', 'Page could not be displayed');
  2056. $oLog->Set('callstack', $e->getTrace());
  2057. $oLog->Set('data', $e->getContextData());
  2058. $oLog->DBInsertNoReload();
  2059. }
  2060. catch(Exception $e)
  2061. {
  2062. IssueLog::Error("Failed to log issue into the DB");
  2063. }
  2064. }
  2065. IssueLog::Error($e->getMessage());
  2066. }
  2067. // For debugging only
  2068. //throw $e;
  2069. }
  2070. catch(Exception $e)
  2071. {
  2072. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  2073. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  2074. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  2075. $oP->error(Dict::Format('UI:Error_Details', $e->getMessage()));
  2076. $oP->output();
  2077. if (MetaModel::IsLogEnabledIssue())
  2078. {
  2079. if (MetaModel::IsValidClass('EventIssue'))
  2080. {
  2081. try
  2082. {
  2083. $oLog = new EventIssue();
  2084. $oLog->Set('message', $e->getMessage());
  2085. $oLog->Set('userinfo', '');
  2086. $oLog->Set('issue', 'PHP Exception');
  2087. $oLog->Set('impact', 'Page could not be displayed');
  2088. $oLog->Set('callstack', $e->getTrace());
  2089. $oLog->Set('data', array());
  2090. $oLog->DBInsertNoReload();
  2091. }
  2092. catch(Exception $e)
  2093. {
  2094. IssueLog::Error("Failed to log issue into the DB");
  2095. }
  2096. }
  2097. IssueLog::Error($e->getMessage());
  2098. }
  2099. }
  2100. ?>