UI.php 89 KB

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