UI.php 87 KB

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