UI.php 87 KB

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