UI.php 86 KB

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