UI.php 87 KB

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