UI.php 89 KB

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