UI.php 83 KB

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