UI.php 80 KB

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