UI.php 87 KB

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