UI.php 87 KB

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