UI.php 85 KB

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