UI.php 89 KB

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