UI.php 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185
  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. if ($sTargetState != '')
  1290. {
  1291. $oObj->Set($sStateAttCode, $sTargetState);
  1292. }
  1293. }
  1294. $oObj->UpdateObjectFromPostedForm();
  1295. }
  1296. if (isset($oObj) && is_object($oObj))
  1297. {
  1298. $sClass = get_class($oObj);
  1299. $sClassLabel = MetaModel::GetName($sClass);
  1300. list($bRes, $aIssues) = $oObj->CheckToWrite();
  1301. if ($bRes)
  1302. {
  1303. $oMyChange = MetaModel::NewObject("CMDBChange");
  1304. $oMyChange->Set("date", time());
  1305. $sUserString = CMDBChange::GetCurrentUserName();
  1306. $oMyChange->Set("userinfo", $sUserString);
  1307. $iChangeId = $oMyChange->DBInsert();
  1308. $oObj->DBInsertTracked($oMyChange);
  1309. utils::RemoveTransaction($sTransactionId);
  1310. $oP->set_title(Dict::S('UI:PageTitle:ObjectCreated'));
  1311. $oP->add("<h1>".Dict::Format('UI:Title:Object_Of_Class_Created', $oObj->GetName(), $sClassLabel)."</h1>\n");
  1312. $oObj = MetaModel::GetObject(get_class($oObj), $oObj->GetKey()); //Workaround: reload the object so that the linkedset are displayed properly
  1313. $sNextAction = utils::ReadPostedParam('next_action', '');
  1314. if (!empty($sNextAction))
  1315. {
  1316. ApplyNextAction($oP, $oObj, $sNextAction, $oMyChange);
  1317. }
  1318. else
  1319. {
  1320. // Nothing more to do
  1321. $oObj->DisplayDetails($oP);
  1322. }
  1323. }
  1324. else
  1325. {
  1326. // Found issues, explain and give the user a second chance
  1327. //
  1328. $oP->set_title(Dict::Format('UI:CreationPageTitle_Class', $sClassLabel));
  1329. $oP->add("<h1>".MetaModel::GetClassIcon($sClass)."&nbsp;".Dict::Format('UI:CreationTitle_Class', $sClassLabel)."</h1>\n");
  1330. $oP->add("<div class=\"wizContainer\">\n");
  1331. cmdbAbstractObject::DisplayCreationForm($oP, $sClass, $oObj);
  1332. $oP->add("</div>\n");
  1333. $sIssueDesc = Dict::Format('UI:ObjectCouldNotBeWritten', implode(', ', $aIssues));
  1334. $oP->add_ready_script("alert('".addslashes($sIssueDesc)."');");
  1335. }
  1336. }
  1337. break;
  1338. ///////////////////////////////////////////////////////////////////////////////////////////
  1339. case 'wizard_apply_new': // no more used ???
  1340. $sJson = utils::ReadPostedParam('json_obj', '', 'raw_data');
  1341. $oWizardHelper = WizardHelper::FromJSON($sJson);
  1342. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1343. if (!utils::IsTransactionValid($sTransactionId))
  1344. {
  1345. $oP->p(Dict::S('UI:Error:ObjectAlreadyCreated'));
  1346. }
  1347. else
  1348. {
  1349. $oObj = $oWizardHelper->GetTargetObject(true /* read uploaded files */);
  1350. if (is_object($oObj))
  1351. {
  1352. $sClass = get_class($oObj);
  1353. $sClassLabel = MetaModel::GetName($sClass);
  1354. $oMyChange = MetaModel::NewObject("CMDBChange");
  1355. $oMyChange->Set("date", time());
  1356. $sUserString = CMDBChange::GetCurrentUserName();
  1357. $oMyChange->Set("userinfo", $sUserString);
  1358. $iChangeId = $oMyChange->DBInsert();
  1359. $oObj->DBInsertTracked($oMyChange);
  1360. $oP->set_title(Dict::S('UI:PageTitle:ObjectCreated'));
  1361. $oP->add("<h1>".Dict::Format('UI:Title:Object_Of_Class_Created', $oObj->GetName(), $sClassLabel)."</h1>\n");
  1362. $oObj->DisplayDetails($oP);
  1363. }
  1364. }
  1365. break;
  1366. ///////////////////////////////////////////////////////////////////////////////////////////
  1367. case 'select_bulk_stimulus': // Form displayed when applying a stimulus to many objects
  1368. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  1369. $sStimulus = utils::ReadParam('stimulus', '');
  1370. $sState = utils::ReadParam('state', '');
  1371. if (empty($sFilter) || empty($sStimulus) || empty($sState))
  1372. {
  1373. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state'));
  1374. }
  1375. $oFilter = DBObjectSearch::unserialize($sFilter);
  1376. $sClass = $oFilter->GetClass();
  1377. $aStimuli = MetaModel::EnumStimuli($sClass);
  1378. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1379. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1380. $oP->set_title($sActionLabel);
  1381. $oP->add('<div class="page_header">');
  1382. $oP->add('<h1>'.MetaModel::GetClassIcon($sClass).'&nbsp;'.$sActionLabel.'</h1>');
  1383. $oP->add('</div>');
  1384. $oChecker = new StimulusChecker($oFilter, $sState, $sStimulus);
  1385. $aExtraFormParams = array('stimulus' => $sStimulus, 'state' => $sState);
  1386. DisplayMultipleSelectionForm($oP, $oFilter, 'bulk_stimulus', $oChecker, $aExtraFormParams);
  1387. break;
  1388. case 'bulk_stimulus':
  1389. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  1390. $sStimulus = utils::ReadParam('stimulus', '');
  1391. $sState = utils::ReadParam('state', '');
  1392. if (empty($sFilter) || empty($sStimulus) || empty($sState))
  1393. {
  1394. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state'));
  1395. }
  1396. $oFilter = DBObjectSearch::unserialize($sFilter);
  1397. $sClass = $oFilter->GetClass();
  1398. $aSelectObject = utils::ReadMultipleSelection($oFilter);
  1399. if (count($aSelectObject) == 0)
  1400. {
  1401. // Nothing to do, no object was selected !
  1402. throw new ApplicationException(Dict::S('UI:BulkAction:NoObjectSelected'));
  1403. }
  1404. else
  1405. {
  1406. $aTransitions = MetaModel::EnumTransitions($sClass, $sState);
  1407. $aStimuli = MetaModel::EnumStimuli($sClass);
  1408. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1409. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1410. $aTransition = $aTransitions[$sStimulus];
  1411. $sTargetState = $aTransition['target_state'];
  1412. $aStates = MetaModel::EnumStates($sClass);
  1413. $aTargetStateDef = $aStates[$sTargetState];
  1414. $oP->set_title(Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aSelectObject), $sClass));
  1415. $oP->add('<div class="page_header">');
  1416. $oP->add('<h1>'.MetaModel::GetClassIcon($sClass).'&nbsp;'.Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aSelectObject), $sClass).'</h1>');
  1417. $oP->add('</div>');
  1418. $aExpectedAttributes = $aTargetStateDef['attribute_list'];
  1419. $aDetails = array();
  1420. $iFieldIndex = 0;
  1421. $aFieldsMap = array();
  1422. $aValues = array();
  1423. $aObjects = array();
  1424. foreach($aSelectObject as $iId)
  1425. {
  1426. $aObjects[] = MetaModel::GetObject($sClass, $iId);
  1427. }
  1428. $oSet = DBObjectSet::FromArray($sClass, $aObjects);
  1429. $oObj = $oSet->ComputeCommonObject($aValues);
  1430. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1431. $oObj->Set($sStateAttCode,$sTargetState);
  1432. $sReadyScript = '';
  1433. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  1434. {
  1435. // Prompt for an attribute if
  1436. // - the attribute must be changed or must be displayed to the user for confirmation
  1437. // - or the field is mandatory and currently empty
  1438. if ( ($iExpectCode & (OPT_ATT_MUSTCHANGE | OPT_ATT_MUSTPROMPT)) ||
  1439. (($iExpectCode & OPT_ATT_MANDATORY) && ($oObj->Get($sAttCode) == '')) )
  1440. {
  1441. $aAttributesDef = MetaModel::ListAttributeDefs($sClass);
  1442. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1443. $aPrerequisites = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  1444. if (count($aPrerequisites) > 0)
  1445. {
  1446. // When 'enabling' a field, all its prerequisites must be enabled too
  1447. $sFieldList = "['".implode("','", $aPrerequisites)."']";
  1448. $oP->add_ready_script("$('#enable_{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, true); } );\n");
  1449. }
  1450. $aDependents = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  1451. if (count($aDependents) > 0)
  1452. {
  1453. // When 'disabling' a field, all its dependent fields must be disabled too
  1454. $sFieldList = "['".implode("','", $aDependents)."']";
  1455. $oP->add_ready_script("$('#enable_{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, false); } );\n");
  1456. }
  1457. $aArgs = array('this' => $oObj);
  1458. $sHTMLValue = cmdbAbstractObject::GetFormElementForField($oP, $sClass, $sAttCode, $oAttDef, $oObj->Get($sAttCode), $oObj->GetEditValue($sAttCode), $sAttCode, '', $iExpectCode, $aArgs);
  1459. $sComments = '<input type="checkbox" checked id="enable_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$sAttCode.'\')"/>';
  1460. if (!isset($aValues[$sAttCode]))
  1461. {
  1462. $aValues[$sAttCode] = array();
  1463. }
  1464. if (count($aValues[$sAttCode]) == 1)
  1465. {
  1466. $sComments .= '<div class="mono_value">1</div>';
  1467. }
  1468. else
  1469. {
  1470. // Non-homogenous value
  1471. $iMaxCount = 5;
  1472. $sTip = "<p><b>".Dict::Format('UI:BulkModify_Count_DistinctValues', count($aValues[$sAttCode]))."</b><ul>";
  1473. $index = 0;
  1474. foreach($aValues[$sAttCode] as $sCurrValue => $aVal)
  1475. {
  1476. $sDisplayValue = empty($aVal['display']) ? '<i>'.Dict::S('Enum:Undefined').'</i>' : str_replace(array("\n", "\r"), " ", $aVal['display']);
  1477. $sTip .= "<li>".Dict::Format('UI:BulkModify:Value_Exists_N_Times', $sDisplayValue, $aVal['count'])."</li>";
  1478. $index++;
  1479. if ($iMaxCount == $index)
  1480. {
  1481. $sTip .= "<li>".(count($aMultiValues) - $iMaxCount)." more different values...</li>";
  1482. break;
  1483. }
  1484. if ($iMaxCount == $index)
  1485. {
  1486. $sTip .= "<li>".Dict::Format('UI:BulkModify:N_MoreValues', count($aValues[$sAttCode]) - $iMaxCount)."</li>";
  1487. break;
  1488. }
  1489. }
  1490. $sTip .= "</ul></p>";
  1491. $sReadyScript .= "$('#multi_values_$sAttCode').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );\n";
  1492. $sComments .= '<div class="multi_values" id="multi_values_'.$sAttCode.'">'.count($aValues[$sAttCode]).'</div>';
  1493. }
  1494. $aDetails[] = array('label' => '<span>'.$oAttDef->GetLabel().'</span>', 'value' => "<span id=\"field_$sAttCode\">$sHTMLValue</span>", 'comments' => $sComments);
  1495. $aFieldsMap[$sAttCode] = $sAttCode;
  1496. $iFieldIndex++;
  1497. }
  1498. }
  1499. $sButtonsPosition = MetaModel::GetConfig()->Get('buttons_position');
  1500. if ($sButtonsPosition == 'bottom')
  1501. {
  1502. // bottom: Displays the ticket details BEFORE the actions
  1503. $oP->add('<div class="ui-widget-content">');
  1504. $oObj->DisplayBareProperties($oP);
  1505. $oP->add('</div>');
  1506. }
  1507. $oP->add("<div class=\"wizContainer\">\n");
  1508. $oP->add("<form id=\"apply_stimulus\" method=\"post\" onSubmit=\"return OnSubmit('apply_stimulus');\">\n");
  1509. $oP->add("<table><tr><td>\n");
  1510. $oP->details($aDetails);
  1511. $oP->add("</td></tr></table>\n");
  1512. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  1513. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"bulk_apply_stimulus\">\n");
  1514. $oP->add("<input type=\"hidden\" name=\"preview_mode\" value=\"1\">\n");
  1515. $oP->add("<input type=\"hidden\" name=\"filter\" value=\"$sFilter\">\n");
  1516. $oP->add("<input type=\"hidden\" name=\"stimulus\" value=\"$sStimulus\">\n");
  1517. $oP->add("<input type=\"hidden\" name=\"state\" value=\"$sState\">\n");
  1518. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  1519. $oP->add($oAppContext->GetForForm());
  1520. $oP->add("<input type=\"hidden\" name=\"selectObject\" value=\"".implode(',',$aSelectObject)."\">\n");
  1521. $sURL = "./UI.php?operation=search&filter=$sFilter&".$oAppContext->GetForLink();
  1522. $oP->add("<input type=\"button\" value=\"".Dict::S('UI:Button:Cancel')."\" onClick=\"window.location.href='$sURL'\">&nbsp;&nbsp;&nbsp;&nbsp;\n");
  1523. $oP->add("<button type=\"submit\" class=\"action\"><span>$sActionLabel</span></button>\n");
  1524. $oP->add("</form>\n");
  1525. $oP->add("</div>\n");
  1526. if ($sButtonsPosition != 'bottom')
  1527. {
  1528. // top or both: Displays the ticket details AFTER the actions
  1529. $oP->add('<div class="ui-widget-content">');
  1530. $oObj->DisplayBareProperties($oP);
  1531. $oP->add('</div>');
  1532. }
  1533. $iFieldsCount = count($aFieldsMap);
  1534. $sJsonFieldsMap = json_encode($aFieldsMap);
  1535. $oP->add_script(
  1536. <<<EOF
  1537. // Initializes the object once at the beginning of the page...
  1538. var oWizardHelper = new WizardHelper('$sClass', '', '$sTargetState');
  1539. oWizardHelper.SetFieldsMap($sJsonFieldsMap);
  1540. oWizardHelper.SetFieldsCount($iFieldsCount);
  1541. EOF
  1542. );
  1543. $oP->add_ready_script(
  1544. <<<EOF
  1545. // Starts the validation when the page is ready
  1546. CheckFields('apply_stimulus', false);
  1547. $sReadyScript
  1548. EOF
  1549. );
  1550. }
  1551. break;
  1552. case 'bulk_apply_stimulus':
  1553. $bPreviewMode = utils::ReadPostedParam('preview_mode', false);
  1554. $sFilter = utils::ReadPostedParam('filter', '', false, 'raw_data');
  1555. $sStimulus = utils::ReadPostedParam('stimulus', '');
  1556. $sState = utils::ReadPostedParam('state', '');
  1557. $sSelectObject = utils::ReadPostedParam('selectObject', '', false, 'raw_data');
  1558. $aSelectObject = explode(',', $sSelectObject);
  1559. if (empty($sFilter) || empty($sStimulus) || empty($sState))
  1560. {
  1561. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state'));
  1562. }
  1563. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1564. if (!utils::IsTransactionValid($sTransactionId))
  1565. {
  1566. $oP->p(Dict::S('UI:Error:ObjectAlreadyUpdated'));
  1567. }
  1568. else
  1569. {
  1570. // For archiving the modification
  1571. $oFilter = DBObjectSearch::unserialize($sFilter);
  1572. $sClass = $oFilter->GetClass();
  1573. $aObjects = array();
  1574. foreach($aSelectObject as $iId)
  1575. {
  1576. $aObjects[] = MetaModel::GetObject($sClass, $iId);
  1577. }
  1578. $aTransitions = MetaModel::EnumTransitions($sClass, $sState);
  1579. $aStimuli = MetaModel::EnumStimuli($sClass);
  1580. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1581. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1582. $oP->set_title(Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aObjects), $sClass));
  1583. $oP->add('<div class="page_header">');
  1584. $oP->add('<h1>'.MetaModel::GetClassIcon($sClass).'&nbsp;'.Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aObjects), $sClass).'</h1>');
  1585. $oP->add('</div>');
  1586. $oSet = DBObjectSet::FromArray($sClass, $aObjects);
  1587. $oMyChange = MetaModel::NewObject("CMDBChange");
  1588. $oMyChange->Set("date", time());
  1589. $sUserString = CMDBChange::GetCurrentUserName();
  1590. $oMyChange->Set("userinfo", $sUserString);
  1591. $iChangeId = $oMyChange->DBInsert();
  1592. // For reporting
  1593. $aHeaders = array(
  1594. 'object' => array('label' => MetaModel::GetName($sClass), 'description' => Dict::S('UI:ModifiedObject')),
  1595. 'status' => array('label' => Dict::S('UI:BulkModifyStatus'), 'description' => Dict::S('UI:BulkModifyStatus+')),
  1596. 'errors' => array('label' => Dict::S('UI:BulkModifyErrors'), 'description' => Dict::S('UI:BulkModifyErrors+')),
  1597. );
  1598. $aRows = array();
  1599. while ($oObj = $oSet->Fetch())
  1600. {
  1601. $sError = Dict::S('UI:BulkModifyStatusOk');
  1602. try
  1603. {
  1604. $aTransitions = $oObj->EnumTransitions();
  1605. $aStimuli = MetaModel::EnumStimuli($sClass);
  1606. if (!isset($aTransitions[$sStimulus]))
  1607. {
  1608. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
  1609. }
  1610. else
  1611. {
  1612. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1613. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1614. $aTransition = $aTransitions[$sStimulus];
  1615. $sTargetState = $aTransition['target_state'];
  1616. $aTargetStates = MetaModel::EnumStates($sClass);
  1617. $aTargetState = $aTargetStates[$sTargetState];
  1618. $aExpectedAttributes = $aTargetState['attribute_list'];
  1619. $aDetails = array();
  1620. $aErrors = array();
  1621. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  1622. {
  1623. $iFlags = $oObj->GetAttributeFlags($sAttCode);
  1624. if (($iExpectCode & (OPT_ATT_MUSTCHANGE|OPT_ATT_MUSTPROMPT)) || ($oObj->Get($sAttCode) == '') )
  1625. {
  1626. $paramValue = utils::ReadPostedParam("attr_$sAttCode", '', 'raw_data');
  1627. if ( ($iFlags & OPT_ATT_SLAVE) && ($paramValue != $oObj->Get($sAttCode)) )
  1628. {
  1629. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1630. $aErrors[] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $oAttDef->GetLabel());
  1631. }
  1632. else
  1633. {
  1634. $oObj->Set($sAttCode, $paramValue);
  1635. }
  1636. }
  1637. }
  1638. if (count($aErrors) == 0)
  1639. {
  1640. if ($oObj->ApplyStimulus($sStimulus))
  1641. {
  1642. list($bResult, $aErrors) = $oObj->CheckToWrite();
  1643. $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusModified') : Dict::S('UI:BulkModifyStatusSkipped');
  1644. if ($bResult)
  1645. {
  1646. $oObj->DBUpdateTracked($oMyChange);
  1647. }
  1648. else
  1649. {
  1650. $sError = '<p>'.implode('</p></p>',$aErrors)."</p>\n";
  1651. }
  1652. }
  1653. else
  1654. {
  1655. $sStatus = Dict::S('UI:BulkModifyStatusSkipped');
  1656. $sError = '<p>'.Dict::S('UI:FailedToApplyStimuli')."<p>\n";
  1657. }
  1658. }
  1659. else
  1660. {
  1661. $sStatus = Dict::S('UI:BulkModifyStatusSkipped');
  1662. $sError = '<p>'.implode('</p></p>',$aErrors)."</p>\n";
  1663. }
  1664. }
  1665. }
  1666. catch(Exception $e)
  1667. {
  1668. $sError = $e->getMessage();
  1669. $sStatus = Dict::S('UI:BulkModifyStatusSkipped');
  1670. }
  1671. $aRows[] = array(
  1672. 'object' => $oObj->GetHyperlink(),
  1673. 'status' => $sStatus,
  1674. 'errors' => $sError,
  1675. );
  1676. }
  1677. $oP->Table($aHeaders, $aRows);
  1678. // Back to the list
  1679. $sURL = "./UI.php?operation=search&filter=$sFilter&".$oAppContext->GetForLink();
  1680. $oP->add('<input type="button" onClick="window.location.href=\''.$sURL.'\'" value="'.Dict::S('UI:Button:Done').'">');
  1681. }
  1682. break;
  1683. case 'stimulus': // Form displayed when applying a stimulus (state change)
  1684. $sClass = utils::ReadParam('class', '', false, 'class');
  1685. $id = utils::ReadParam('id', '');
  1686. $sStimulus = utils::ReadParam('stimulus', '');
  1687. if ( empty($sClass) || empty($id) || empty($sStimulus) ) // TO DO: check that the class name is valid !
  1688. {
  1689. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'class', 'id', 'stimulus'));
  1690. }
  1691. $oObj = MetaModel::GetObject($sClass, $id, false);
  1692. if ($oObj != null)
  1693. {
  1694. $aTransitions = $oObj->EnumTransitions();
  1695. $aStimuli = MetaModel::EnumStimuli($sClass);
  1696. if (!isset($aTransitions[$sStimulus]))
  1697. {
  1698. // Invalid stimulus
  1699. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
  1700. }
  1701. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1702. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1703. $aTransition = $aTransitions[$sStimulus];
  1704. $sTargetState = $aTransition['target_state'];
  1705. $aTargetStates = MetaModel::EnumStates($sClass);
  1706. $oP->add("<div class=\"page_header\">\n");
  1707. $oP->add("<h1>$sActionLabel - <span class=\"hilite\">{$oObj->GetName()}</span></h1>\n");
  1708. $oP->set_title($sActionLabel);
  1709. $oP->add("</div>\n");
  1710. $aTargetState = $aTargetStates[$sTargetState];
  1711. $aExpectedAttributes = $aTargetState['attribute_list'];
  1712. $oP->add("<h1>$sActionDetails</h1>\n");
  1713. $sButtonsPosition = MetaModel::GetConfig()->Get('buttons_position');
  1714. if ($sButtonsPosition == 'bottom')
  1715. {
  1716. // bottom: Displays the ticket details BEFORE the actions
  1717. $oP->add('<div class="ui-widget-content">');
  1718. $oObj->DisplayBareProperties($oP);
  1719. $oP->add('</div>');
  1720. }
  1721. $oP->add("<div class=\"wizContainer\">\n");
  1722. $oP->add("<form id=\"apply_stimulus\" method=\"post\" onSubmit=\"return OnSubmit('apply_stimulus');\">\n");
  1723. $aDetails = array();
  1724. $iFieldIndex = 0;
  1725. $aFieldsMap = array();
  1726. $aDetailsList = $oObj->FlattenZList(MetaModel::GetZListItems($sClass, 'details'));
  1727. // Order the fields based on their dependencies, set the fields for which there is only one possible value
  1728. // and perform this in the order of dependencies to avoid dead-ends
  1729. $aDeps = array();
  1730. foreach($aDetailsList as $sAttCode)
  1731. {
  1732. $aDeps[$sAttCode] = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode);
  1733. }
  1734. $aList = $oObj->OrderDependentFields($aDeps);
  1735. foreach($aList as $sAttCode)
  1736. {
  1737. // Consider only the "expected" fields for the target state
  1738. if (array_key_exists($sAttCode, $aExpectedAttributes))
  1739. {
  1740. $iExpectCode = $aExpectedAttributes[$sAttCode];
  1741. // Prompt for an attribute if
  1742. // - the attribute must be changed or must be displayed to the user for confirmation
  1743. // - or the field is mandatory and currently empty
  1744. if ( ($iExpectCode & (OPT_ATT_MUSTCHANGE | OPT_ATT_MUSTPROMPT)) ||
  1745. (($iExpectCode & OPT_ATT_MANDATORY) && ($oObj->Get($sAttCode) == '')) )
  1746. {
  1747. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1748. $aArgs = array('this' => $oObj);
  1749. // If the field is mandatory, set it to the only possible value
  1750. if ((!$oAttDef->IsNullAllowed()) || ($iExpectCode & OPT_ATT_MANDATORY))
  1751. {
  1752. if ($oAttDef->IsExternalKey())
  1753. {
  1754. $oAllowedValues = MetaModel::GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs);
  1755. if ($oAllowedValues->Count() == 1)
  1756. {
  1757. $oRemoteObj = $oAllowedValues->Fetch();
  1758. $oObj->Set($sAttCode, $oRemoteObj->GetKey());
  1759. }
  1760. }
  1761. else
  1762. {
  1763. $aAllowedValues = MetaModel::GetAllowedValues_att($sClass, $sAttCode, $aArgs);
  1764. if (count($aAllowedValues) == 1)
  1765. {
  1766. $aValues = array_keys($aAllowedValues);
  1767. $oObj->Set($sAttCode, $aValues[0]);
  1768. }
  1769. }
  1770. }
  1771. $sHTMLValue = cmdbAbstractObject::GetFormElementForField($oP, $sClass, $sAttCode, $oAttDef, $oObj->Get($sAttCode), $oObj->GetEditValue($sAttCode), 'att_'.$iFieldIndex, '', $iExpectCode, $aArgs);
  1772. $aDetails[] = array('label' => '<span>'.$oAttDef->GetLabel().'</span>', 'value' => "<span id=\"field_att_$iFieldIndex\">$sHTMLValue</span>");
  1773. $aFieldsMap[$sAttCode] = 'att_'.$iFieldIndex;
  1774. $iFieldIndex++;
  1775. }
  1776. }
  1777. }
  1778. $oP->add('<table><tr><td>');
  1779. $oP->details($aDetails);
  1780. $oP->add('</td></tr></table>');
  1781. $oP->add("<input type=\"hidden\" name=\"id\" value=\"$id\" id=\"id\">\n");
  1782. $aFieldsMap['id'] = 'id';
  1783. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  1784. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"apply_stimulus\">\n");
  1785. $oP->add("<input type=\"hidden\" name=\"stimulus\" value=\"$sStimulus\">\n");
  1786. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  1787. $oP->add($oAppContext->GetForForm());
  1788. $oP->add("<button type=\"button\" class=\"action\" onClick=\"BackToDetails('$sClass', $id)\"><span>".Dict::S('UI:Button:Cancel')."</span></button>&nbsp;&nbsp;&nbsp;&nbsp;\n");
  1789. $oP->add("<button type=\"submit\" class=\"action\"><span>$sActionLabel</span></button>\n");
  1790. $oP->add("</form>\n");
  1791. $oP->add("</div>\n");
  1792. if ($sButtonsPosition != 'top')
  1793. {
  1794. // bottom or both: Displays the ticket details AFTER the actions
  1795. $oP->add('<div class="ui-widget-content">');
  1796. $oObj->DisplayBareProperties($oP);
  1797. $oP->add('</div>');
  1798. }
  1799. $iFieldsCount = count($aFieldsMap);
  1800. $sJsonFieldsMap = json_encode($aFieldsMap);
  1801. $oP->add_script(
  1802. <<<EOF
  1803. // Initializes the object once at the beginning of the page...
  1804. var oWizardHelper = new WizardHelper('$sClass', '', '$sTargetState');
  1805. oWizardHelper.SetFieldsMap($sJsonFieldsMap);
  1806. oWizardHelper.SetFieldsCount($iFieldsCount);
  1807. EOF
  1808. );
  1809. $oP->add_ready_script(
  1810. <<<EOF
  1811. // Starts the validation when the page is ready
  1812. CheckFields('apply_stimulus', false);
  1813. EOF
  1814. );
  1815. }
  1816. else
  1817. {
  1818. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  1819. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  1820. }
  1821. break;
  1822. ///////////////////////////////////////////////////////////////////////////////////////////
  1823. case 'apply_stimulus': // Actual state change
  1824. $sClass = utils::ReadPostedParam('class', '');
  1825. $id = utils::ReadPostedParam('id', '');
  1826. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1827. $sStimulus = utils::ReadPostedParam('stimulus', '');
  1828. if ( empty($sClass) || empty($id) || empty($sStimulus) ) // TO DO: check that the class name is valid !
  1829. {
  1830. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'class', 'id', 'stimulus'));
  1831. }
  1832. $oObj = MetaModel::GetObject($sClass, $id, false);
  1833. if ($oObj != null)
  1834. {
  1835. $aTransitions = $oObj->EnumTransitions();
  1836. $aStimuli = MetaModel::EnumStimuli($sClass);
  1837. if (!isset($aTransitions[$sStimulus]))
  1838. {
  1839. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
  1840. }
  1841. if (!utils::IsTransactionValid($sTransactionId))
  1842. {
  1843. $oP->p(Dict::S('UI:Error:ObjectAlreadyUpdated'));
  1844. }
  1845. else
  1846. {
  1847. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1848. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1849. $aTransition = $aTransitions[$sStimulus];
  1850. $sTargetState = $aTransition['target_state'];
  1851. $aTargetStates = MetaModel::EnumStates($sClass);
  1852. $aTargetState = $aTargetStates[$sTargetState];
  1853. $aExpectedAttributes = $aTargetState['attribute_list'];
  1854. $aDetails = array();
  1855. $aErrors = array();
  1856. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  1857. {
  1858. $iFlags = $oObj->GetAttributeFlags($sAttCode);
  1859. if (($iExpectCode & (OPT_ATT_MUSTCHANGE|OPT_ATT_MUSTPROMPT)) || ($oObj->Get($sAttCode) == '') )
  1860. {
  1861. $paramValue = utils::ReadPostedParam("attr_$sAttCode", '', 'raw_data');
  1862. if ( ($iFlags & OPT_ATT_SLAVE) && ($paramValue != $oObj->Get($sAttCode)))
  1863. {
  1864. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1865. $aErrors[] = Dict::Format('UI:AttemptingToChangeASlaveAttribute_Name', $oAttDef->GetLabel());
  1866. }
  1867. else
  1868. {
  1869. $oObj->Set($sAttCode, $paramValue);
  1870. }
  1871. }
  1872. }
  1873. if (count($aErrors) == 0)
  1874. {
  1875. if ($oObj->ApplyStimulus($sStimulus))
  1876. {
  1877. $oMyChange = MetaModel::NewObject("CMDBChange");
  1878. $oMyChange->Set("date", time());
  1879. $sUserString = CMDBChange::GetCurrentUserName();
  1880. $oMyChange->Set("userinfo", $sUserString);
  1881. $iChangeId = $oMyChange->DBInsert();
  1882. $oObj->DBUpdateTracked($oMyChange);
  1883. $oP->p(Dict::Format('UI:Class_Object_Updated', MetaModel::GetName(get_class($oObj)), $oObj->GetName()));
  1884. }
  1885. else
  1886. {
  1887. $oP->p(Dict::S('UI:FailedToApplyStimuli'));
  1888. }
  1889. }
  1890. else
  1891. {
  1892. $oP->p(implode('</p><p>', $aErrors));
  1893. }
  1894. }
  1895. $oObj->DisplayDetails($oP);
  1896. }
  1897. else
  1898. {
  1899. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  1900. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  1901. }
  1902. break;
  1903. ///////////////////////////////////////////////////////////////////////////////////////////
  1904. case 'swf_navigator': // Graphical display of the relations "impact" / "depends on"
  1905. $sClass = utils::ReadParam('class', '', false, 'class');
  1906. $id = utils::ReadParam('id', 0);
  1907. $sRelation = utils::ReadParam('relation', 'impact');
  1908. $oP->AddTabContainer('Navigator');
  1909. $oP->SetCurrentTabContainer('Navigator');
  1910. $oP->SetCurrentTab(Dict::S('UI:RelationshipGraph'));
  1911. $width = 1000;
  1912. $height = 700;
  1913. $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";
  1914. $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\">
  1915. <param name=\"allowScriptAccess\" value=\"sameDomain\" />
  1916. <param name=\"allowFullScreen\" value=\"false\" />
  1917. <param name=\"FlashVars\" value=\"$sParams\" />
  1918. <param name=\"wmode\" value=\"transparent\">
  1919. <param name=\"movie\" value=\"../navigator/navigator.swf\" /><param name=\"quality\" value=\"high\" /><param name=\"bgcolor\" value=\"#ffffff\" />
  1920. <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\" />
  1921. </object></div>\n");
  1922. $oP->SetCurrentTab(Dict::S('UI:RelationshipList'));
  1923. $oP->add("<div id=\"impacted_objects\" style=\"width:100%;background-color:#fff;padding:10px;\"><p style=\"height:150px;\">&nbsp;</p></div>");
  1924. $oP->add_ready_script(
  1925. <<<EOF
  1926. var ajax_request = null;
  1927. function UpdateImpactedObjects(sClass, iId, sRelation)
  1928. {
  1929. var class_name = sClass; //$('select[name=class_name]').val();
  1930. if (class_name != '')
  1931. {
  1932. $('#impacted_objects').block();
  1933. // Make sure that we cancel any pending request before issuing another
  1934. // since responses may arrive in arbitrary order
  1935. if (ajax_request != null)
  1936. {
  1937. ajax_request.abort();
  1938. ajax_request = null;
  1939. }
  1940. ajax_request = $.get(GetAbsoluteUrlAppRoot()+'pages/xml.navigator.php', { 'class': sClass, id: iId, relation: sRelation, format: 'html' },
  1941. function(data)
  1942. {
  1943. $('#impacted_objects').empty();
  1944. $('#impacted_objects').append(data);
  1945. $('#impacted_objects').unblock();
  1946. $('#impacted_objects .listResults').tablesorter( { widgets: ['myZebra', 'truncatedList']} ); // sortable and zebra tables
  1947. $('#impacted_objects table.listResults').tableHover(); // hover tables
  1948. }
  1949. );
  1950. }
  1951. }
  1952. UpdateImpactedObjects('$sClass', $id, '$sRelation');
  1953. EOF
  1954. );
  1955. $oP->SetCurrentTab('');
  1956. break;
  1957. ///////////////////////////////////////////////////////////////////////////////////////////
  1958. case 'cancel': // An action was cancelled
  1959. $oP->set_title(Dict::S('UI:OperationCancelled'));
  1960. $oP->add('<h1>'.Dict::S('UI:OperationCancelled').'</h1>');
  1961. break;
  1962. ///////////////////////////////////////////////////////////////////////////////////////////
  1963. default: // Menu node rendering (templates)
  1964. $oMenuNode = ApplicationMenu::GetMenuNode(ApplicationMenu::GetActiveNodeId());
  1965. if (is_object($oMenuNode))
  1966. {
  1967. $oMenuNode->RenderContent($oP, $oAppContext->GetAsHash());
  1968. $oP->set_title($oMenuNode->GetLabel());
  1969. }
  1970. ///////////////////////////////////////////////////////////////////////////////////////////
  1971. }
  1972. $oKPI->ComputeAndReport('GUI creation before output');
  1973. ExecutionKPI::ReportStats();
  1974. MetaModel::ShowQueryTrace();
  1975. DisplayWelcomePopup($oP);
  1976. $oP->output();
  1977. }
  1978. catch(CoreException $e)
  1979. {
  1980. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  1981. $oP = new SetupWebPage(Dict::S('UI:PageTitle:FatalError'));
  1982. if ($e instanceof SecurityException)
  1983. {
  1984. $oP->add("<h1>".Dict::S('UI:SystemIntrusion')."</h1>\n");
  1985. }
  1986. else
  1987. {
  1988. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  1989. }
  1990. $oP->error(Dict::Format('UI:Error_Details', $e->getHtmlDesc()));
  1991. $oP->output();
  1992. if (MetaModel::IsLogEnabledIssue())
  1993. {
  1994. if (MetaModel::IsValidClass('EventIssue'))
  1995. {
  1996. try
  1997. {
  1998. $oLog = new EventIssue();
  1999. $oLog->Set('message', $e->getMessage());
  2000. $oLog->Set('userinfo', '');
  2001. $oLog->Set('issue', $e->GetIssue());
  2002. $oLog->Set('impact', 'Page could not be displayed');
  2003. $oLog->Set('callstack', $e->getTrace());
  2004. $oLog->Set('data', $e->getContextData());
  2005. $oLog->DBInsertNoReload();
  2006. }
  2007. catch(Exception $e)
  2008. {
  2009. IssueLog::Error("Failed to log issue into the DB");
  2010. }
  2011. }
  2012. IssueLog::Error($e->getMessage());
  2013. }
  2014. // For debugging only
  2015. //throw $e;
  2016. }
  2017. catch(Exception $e)
  2018. {
  2019. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  2020. $oP = new SetupWebPage(Dict::S('UI:PageTitle:FatalError'));
  2021. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  2022. $oP->error(Dict::Format('UI:Error_Details', $e->getMessage()));
  2023. $oP->output();
  2024. if (MetaModel::IsLogEnabledIssue())
  2025. {
  2026. if (MetaModel::IsValidClass('EventIssue'))
  2027. {
  2028. try
  2029. {
  2030. $oLog = new EventIssue();
  2031. $oLog->Set('message', $e->getMessage());
  2032. $oLog->Set('userinfo', '');
  2033. $oLog->Set('issue', 'PHP Exception');
  2034. $oLog->Set('impact', 'Page could not be displayed');
  2035. $oLog->Set('callstack', $e->getTrace());
  2036. $oLog->Set('data', array());
  2037. $oLog->DBInsertNoReload();
  2038. }
  2039. catch(Exception $e)
  2040. {
  2041. IssueLog::Error("Failed to log issue into the DB");
  2042. }
  2043. }
  2044. IssueLog::Error($e->getMessage());
  2045. }
  2046. }
  2047. ?>