UI.php 87 KB

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