UI.php 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689
  1. <?php
  2. // Copyright (C) 2010-2012 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Main page of iTop
  20. *
  21. * @copyright Copyright (C) 2010-2012 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. /**
  25. * Displays a popup welcome message, once per session at maximum
  26. * until the user unchecks the "Display welcome at startup"
  27. * @param WebPage $oP The current web page for the display
  28. * @return void
  29. */
  30. function DisplayWelcomePopup(WebPage $oP)
  31. {
  32. if (!isset($_SESSION['welcome']))
  33. {
  34. // Check, only once per session, if the popup should be displayed...
  35. // If the user did not already ask for hiding it forever
  36. $bPopup = appUserPreferences::GetPref('welcome_popup', true);
  37. if ($bPopup)
  38. {
  39. $sTemplate = @file_get_contents('../application/templates/welcome_popup.html');
  40. if ($sTemplate !== false)
  41. {
  42. $oTemplate = new DisplayTemplate($sTemplate);
  43. $oP->add("<div id=\"welcome_popup\">");
  44. $oTemplate->Render($oP, array());
  45. $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");
  46. $oP->add("<p style=\"float:right\"><input type=\"button\" value=\"".Dict::S('UI:Button:Ok')."\" onClick=\"$('#welcome_popup').dialog('close');\"/>\n");
  47. $oP->add("</div>\n");
  48. $sTitle = addslashes(Dict::S('UI:WelcomeMenu:Title'));
  49. $oP->add_ready_script(
  50. <<<EOF
  51. $('#welcome_popup').dialog( { width:'80%', height: 'auto', title: '$sTitle', autoOpen: true, modal:true,
  52. close: function() {
  53. var bDisplay = $('#display_welcome_popup:checked').length;
  54. SetUserPreference('welcome_popup', bDisplay, true);
  55. }
  56. });
  57. if ($('#welcome_popup').height() > ($(window).height()-70))
  58. {
  59. $('#welcome_popup').height($(window).height()-70);
  60. }
  61. EOF
  62. );
  63. $_SESSION['welcome'] = 'ok';
  64. }
  65. }
  66. }
  67. }
  68. /**
  69. * Apply the 'next-action' to the given object or redirect to the page that prompts for additional information if needed
  70. * @param $oP WebPage The page for the output
  71. * @param $oObj CMDBObject The object to process
  72. * @param $sNextAction string The code of the stimulus for the 'action' (i.e. Transition) to apply
  73. */
  74. function ApplyNextAction(Webpage $oP, CMDBObject $oObj, $sNextAction)
  75. {
  76. // Here handle the apply stimulus
  77. $aTransitions = $oObj->EnumTransitions();
  78. $aStimuli = MetaModel::EnumStimuli(get_class($oObj));
  79. if (!isset($aTransitions[$sNextAction]))
  80. {
  81. // Invalid stimulus
  82. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sNextAction, $oObj->GetName(), $oObj->GetStateLabel()));
  83. }
  84. // Get the list of missing mandatory fields for the target state, considering only the changes from the previous form (i.e don't prompt twice)
  85. $aExpectedAttributes = $oObj->GetExpectedAttributes($oObj->GetState(), $sNextAction, true /* $bOnlyNewOnes */);
  86. if (count($aExpectedAttributes) == 0)
  87. {
  88. // If all the mandatory fields are already present, just apply the transition silently...
  89. if ($oObj->ApplyStimulus($sNextAction))
  90. {
  91. $oObj->DBUpdate();
  92. }
  93. ReloadAndDisplay($oP, $oObj);
  94. }
  95. else
  96. {
  97. // redirect to the 'stimulus' action
  98. $oAppContext = new ApplicationContext();
  99. //echo "<p>Missing Attributes <pre>".print_r($aExpectedAttributes, true)."</pre></p>\n";
  100. $oP->add_header('Location: '.utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=stimulus&class='.get_class($oObj).'&stimulus='.$sNextAction.'&id='.$oObj->getKey().'&'.$oAppContext->GetForLink());
  101. }
  102. }
  103. function ReloadAndDisplay($oPage, $oObj, $sMessageId = '', $sMessage = '', $sSeverity = null)
  104. {
  105. $oAppContext = new ApplicationContext();
  106. if ($sMessageId != '')
  107. {
  108. cmdbAbstractObject::SetSessionMessage(get_class($oObj), $oObj->GetKey(), $sMessageId, $sMessage, $sSeverity, 0, true /* must not exist */);
  109. }
  110. $oPage->add_header('Location: '.utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=details&class='.get_class($oObj).'&id='.$oObj->getKey().'&'.$oAppContext->GetForLink());
  111. }
  112. /**
  113. * Displays the details of an object
  114. * @param $oP WebPage Page for the output
  115. * @param $sClass string The name of the class of the object
  116. * @param $oObj DBObject The object to display
  117. * @param $id mixed Identifier of the object (name or ID)
  118. */
  119. function DisplayDetails($oP, $sClass, $oObj, $id)
  120. {
  121. $sClassLabel = MetaModel::GetName($sClass);
  122. $oSearch = new DBObjectSearch($sClass);
  123. $oBlock = new DisplayBlock($oSearch, 'search', false);
  124. $oBlock->Display($oP, 0);
  125. // The object could be listed, check if it is actually allowed to view it
  126. $oSet = CMDBObjectSet::FromObject($oObj);
  127. if (UserRights::IsActionAllowed($sClass, UR_ACTION_READ, $oSet) == UR_ALLOWED_NO)
  128. {
  129. throw new SecurityException('User not allowed to view this object', array('class' => $sClass, 'id' => $id));
  130. }
  131. $oP->set_title(Dict::Format('UI:DetailsPageTitle', $oObj->GetRawName(), $sClassLabel)); // Set title will take care of the encoding
  132. $oObj->DisplayDetails($oP);
  133. }
  134. /**
  135. * Displays the result of a search request
  136. * @param $oP WebPage Web page for the output
  137. * @param $oFilter DBObjectSearch The search of objects to display
  138. * @param $bSearchForm boolean Whether or not to display the search form at the top the page
  139. * @param $sBaseClass string The base class for the search (can be different from the actual class of the results)
  140. * @param $sFormat string The format to use for the output: csv or html
  141. */
  142. function DisplaySearchSet($oP, $oFilter, $bSearchForm = true, $sBaseClass = '', $sFormat = '', $bDoSearch = true)
  143. {
  144. if ($bSearchForm)
  145. {
  146. $aParams = array('open' => true);
  147. if (!empty($sBaseClass))
  148. {
  149. $aParams['baseClass'] = $sBaseClass;
  150. }
  151. $oBlock = new DisplayBlock($oFilter, 'search', false /* Asynchronous */, $aParams);
  152. $oBlock->Display($oP, 0);
  153. }
  154. if ($bDoSearch)
  155. {
  156. if (strtolower($sFormat) == 'csv')
  157. {
  158. $oBlock = new DisplayBlock($oFilter, 'csv', false);
  159. $oBlock->Display($oP, 1);
  160. // Adjust the size of the Textarea containing the CSV to fit almost all the remaining space
  161. $oP->add_ready_script(" $('#1>textarea').height($('#1').parent().height() - $('#0').outerHeight() - 30).width( $('#1').parent().width() - 20);"); // adjust the size of the block
  162. }
  163. else
  164. {
  165. $oBlock = new DisplayBlock($oFilter, 'list', false);
  166. $oBlock->Display($oP, 1);
  167. }
  168. }
  169. }
  170. /**
  171. * Displays a form (checkboxes) to select the objects for which to apply a given action
  172. * Only the objects for which the action is valid can be checked. By default all valid objects are checked
  173. * @param $oP WebPage The page for output
  174. * @param $oFilter DBObjectSearch The filter that defines the list of objects
  175. * @param $sNextOperation string The next operation (code) to be executed when the form is submitted
  176. * @param $oChecker ActionChecker The helper class/instance used to check for which object the action is valid
  177. * @return none
  178. */
  179. function DisplayMultipleSelectionForm($oP, $oFilter, $sNextOperation, $oChecker, $aExtraFormParams = array())
  180. {
  181. $oAppContext = new ApplicationContext();
  182. $iBulkActionAllowed = $oChecker->IsAllowed();
  183. $sClass = $oFilter->GetClass();
  184. $aExtraParams = array('selection_type' => 'multiple', 'selection_mode' => true, 'display_limit' => false, 'menu' => false);
  185. if ($iBulkActionAllowed == UR_ALLOWED_DEPENDS)
  186. {
  187. $aAllowed = array();
  188. $aExtraParams['selection_enabled'] = $oChecker->GetAllowedIDs();
  189. }
  190. else if(UR_ALLOWED_NO)
  191. {
  192. throw new ApplicationException(Dict::Format('UI:ActionNotAllowed'));
  193. }
  194. $oBlock = new DisplayBlock($oFilter, 'list', false);
  195. $oP->add("<form method=\"post\" action=\"./UI.php\">\n");
  196. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  197. $oP->add("<input type=\"hidden\" name=\"class\" value=\"".$oFilter->GetClass()."\">\n");
  198. $oP->add("<input type=\"hidden\" name=\"filter\" value=\"".$oFilter->Serialize()."\">\n");
  199. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  200. foreach($aExtraFormParams as $sName => $sValue)
  201. {
  202. $oP->add("<input type=\"hidden\" name=\"$sName\" value=\"$sValue\">\n");
  203. }
  204. $oP->add($oAppContext->GetForForm());
  205. $oBlock->Display($oP, 1, $aExtraParams);
  206. $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");
  207. $oP->add("</form>\n");
  208. $oP->add_ready_script("$('#1 table.listResults').trigger('check_all');");
  209. }
  210. function DisplayNavigatorListTab($oP, $aResults, $sRelation, $oObj)
  211. {
  212. $oP->SetCurrentTab(Dict::S('UI:RelationshipList'));
  213. $oP->add("<div id=\"impacted_objects\" style=\"width:100%;background-color:#fff;padding:10px;\">");
  214. $iBlock = 1; // Zero is not a valid blockid
  215. foreach($aResults as $sListClass => $aObjects)
  216. {
  217. $oSet = CMDBObjectSet::FromArray($sListClass, $aObjects);
  218. $oP->add("<h1>".MetaModel::GetRelationDescription($sRelation).' '.$oObj->GetName()."</h1>\n");
  219. $oP->add("<div class=\"page_header\">\n");
  220. $oP->add("<h2>".MetaModel::GetClassIcon($sListClass)."&nbsp;<span class=\"hilite\">".Dict::Format('UI:Search:Count_ObjectsOf_Class_Found', count($aObjects), Metamodel::GetName($sListClass))."</h2>\n");
  221. $oP->add("</div>\n");
  222. $oBlock = DisplayBlock::FromObjectSet($oSet, 'list');
  223. $oBlock->Display($oP, $iBlock++);
  224. $oP->P('&nbsp;'); // Some space ?
  225. }
  226. $oP->add("</div>");
  227. }
  228. function DisplayNavigatorGraphicsTab($oP, $aResults, $oRelGraph, $sClass, $id, $sRelation, $oAppContext, $bDirectionDown)
  229. {
  230. $oP->SetCurrentTab(Dict::S('UI:RelationshipGraph'));
  231. $oP->add("<div id=\"ds_flash\" class=\"SearchDrawer\" style=\"display:none;\">\n");
  232. $oP->add_ready_script(
  233. <<<EOF
  234. $( "#tabbedContent_0" ).tabs({ heightStyle: "fill" });
  235. $("#dh_flash").click( function() {
  236. $("#ds_flash").slideToggle('normal', function() { $("#ds_flash").parent().resize(); } );
  237. $("#dh_flash").toggleClass('open');
  238. });
  239. EOF
  240. );
  241. $aSortedElements = array();
  242. foreach($aResults as $sClassIdx => $aObjects)
  243. {
  244. foreach($aObjects as $oCurrObj)
  245. {
  246. $sSubClass = get_class($oCurrObj);
  247. $aSortedElements[$sSubClass] = MetaModel::GetName($sSubClass);
  248. }
  249. }
  250. asort($aSortedElements);
  251. $idx = 0;
  252. foreach($aSortedElements as $sSubClass => $sClassName)
  253. {
  254. $oP->add("<span style=\"padding-right:2em; white-space:nowrap;\"><input type=\"checkbox\" id=\"exclude_$idx\" name=\"excluded[]\" value=\"$sSubClass\" checked onChange=\"$('#ReloadMovieBtn').button('enable')\"><label for=\"exclude_$idx\">&nbsp;".MetaModel::GetClassIcon($sSubClass)."&nbsp;$sClassName</label></span> ");
  255. $idx++;
  256. }
  257. $oP->add("<p style=\"text-align:right\"><button type=\"button\" id=\"ReloadMovieBtn\" onClick=\"DoReload()\">".Dict::S('UI:Button:Refresh')."</button></p>");
  258. $oP->add("</div>\n");
  259. $oP->add("<div class=\"HRDrawer\"></div>\n");
  260. $oP->add("<div id=\"dh_flash\" class=\"DrawerHandle\">".Dict::S('UI:ElementsDisplayed')."</div>\n");
  261. $sDirection = utils::ReadParam('d', 'horizontal');
  262. $iGroupingThreshold = utils::ReadParam('g', 5);
  263. $oP->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/fraphael.js');
  264. $oP->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/simple_graph.js');
  265. $oGraph = DisplayableGraph::FromRelationGraph($oRelGraph, $iGroupingThreshold, $bDirectionDown);
  266. try
  267. {
  268. $oGraph->InitFromGraphviz();
  269. if (extension_loaded('gd'))
  270. {
  271. $sExportAsPdfURL = utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php?operation=relation_pdf&relation='.$sRelation.'&direction='.($bDirectionDown ? 'down' : 'up').'&class='.$sClass.'&id='.$id;
  272. }
  273. $oAppcontext = new ApplicationContext();
  274. $sContext = $oAppContext->GetForLink();
  275. $sDrillDownURL = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=details&class=%1$s&id=%2$s&'.$sContext;
  276. $sExportAsDocumentURL = '';
  277. $oGraph->RenderAsRaphael($oP, null, $sExportAsPdfURL, $sExportAsDocumentURL, $sDrillDownURL);
  278. }
  279. catch(Exception $e)
  280. {
  281. $oP->add('<div>'.$e->getMessage().'</div>');
  282. }
  283. $oP->add_script(
  284. <<<EOF
  285. function DoReload()
  286. {
  287. $('#ReloadMovieBtn').button('disable');
  288. try
  289. {
  290. var aExcluded = [];
  291. $('input[name^=excluded]').each( function() {
  292. if (!$(this).attr('checked'))
  293. {
  294. aExcluded.push($(this).val());
  295. }
  296. } );
  297. alert('Not yet implemented');
  298. }
  299. catch(err)
  300. {
  301. alert(err);
  302. }
  303. }
  304. EOF
  305. );
  306. $oP->add_ready_script(
  307. <<<EOF
  308. var ajax_request = null;
  309. $('#ReloadMovieBtn').button().button('disable');
  310. function UpdateImpactedObjects(sClass, iId, sRelation)
  311. {
  312. var class_name = sClass; //$('select[name=class_name]').val();
  313. if (class_name != '')
  314. {
  315. $('#impacted_objects').block();
  316. // Make sure that we cancel any pending request before issuing another
  317. // since responses may arrive in arbitrary order
  318. if (ajax_request != null)
  319. {
  320. ajax_request.abort();
  321. ajax_request = null;
  322. }
  323. ajax_request = $.get(GetAbsoluteUrlAppRoot()+'pages/xml.navigator.php', { 'class': sClass, id: iId, relation: sRelation, format: 'html' },
  324. function(data)
  325. {
  326. alert('Not yet implemented');
  327. $('#impacted_objects').unblock();
  328. }
  329. );
  330. }
  331. }
  332. EOF
  333. );
  334. }
  335. /***********************************************************************************
  336. *
  337. * Main user interface page, starts here
  338. *
  339. * ***********************************************************************************/
  340. try
  341. {
  342. require_once('../approot.inc.php');
  343. require_once(APPROOT.'/application/application.inc.php');
  344. require_once(APPROOT.'/application/itopwebpage.class.inc.php');
  345. require_once(APPROOT.'/application/wizardhelper.class.inc.php');
  346. require_once(APPROOT.'/application/startup.inc.php');
  347. $operation = utils::ReadParam('operation', '');
  348. $oKPI = new ExecutionKPI();
  349. $oKPI->ComputeAndReport('Data model loaded');
  350. $oKPI = new ExecutionKPI();
  351. require_once(APPROOT.'/application/loginwebpage.class.inc.php');
  352. $sLoginMessage = LoginWebPage::DoLogin(); // Check user rights and prompt if needed
  353. $oAppContext = new ApplicationContext();
  354. $oKPI->ComputeAndReport('User login');
  355. $oP = new iTopWebPage(Dict::S('UI:WelcomeToITop'));
  356. $oP->SetMessage($sLoginMessage);
  357. // All the following actions use advanced forms that require more javascript to be loaded
  358. switch($operation)
  359. {
  360. case 'new': // Form to create a new object
  361. case 'modify': // Form to modify an object
  362. case 'apply_new': // Creation of a new object
  363. case 'apply_modify': // Applying the modifications to an existing object
  364. case 'form_for_modify_all': // Form to modify multiple objects (bulk modify)
  365. case 'bulk_stimulus': // For to apply a stimulus to multiple objects
  366. case 'stimulus': // Form displayed when applying a stimulus (state change)
  367. case 'apply_stimulus': // Form displayed when applying a stimulus (state change)
  368. $oP->add_linked_script("../js/json.js");
  369. $oP->add_linked_script("../js/forms-json-utils.js");
  370. $oP->add_linked_script("../js/wizardhelper.js");
  371. $oP->add_linked_script("../js/wizard.utils.js");
  372. $oP->add_linked_script("../js/linkswidget.js");
  373. $oP->add_linked_script("../js/linksdirectwidget.js");
  374. $oP->add_linked_script("../js/extkeywidget.js");
  375. $oP->add_linked_script("../js/jquery.blockUI.js");
  376. break;
  377. }
  378. switch($operation)
  379. {
  380. ///////////////////////////////////////////////////////////////////////////////////////////
  381. case 'details': // Details of an object
  382. $sClass = utils::ReadParam('class', '');
  383. $id = utils::ReadParam('id', '');
  384. if ( empty($sClass) || empty($id))
  385. {
  386. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'id'));
  387. }
  388. if (is_numeric($id))
  389. {
  390. $oObj = MetaModel::GetObject($sClass, $id, false /* MustBeFound */);
  391. }
  392. else
  393. {
  394. $oObj = MetaModel::GetObjectByName($sClass, $id, false /* MustBeFound */);
  395. }
  396. if (is_null($oObj))
  397. {
  398. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  399. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  400. }
  401. else
  402. {
  403. try
  404. {
  405. $oObj->Reload();
  406. }
  407. catch(Exception $e)
  408. {
  409. // Probably not allowed to see this instance of a derived class
  410. $oObj = null;
  411. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  412. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  413. }
  414. if (!is_null($oObj))
  415. {
  416. DisplayDetails($oP, $sClass, $oObj, $id);
  417. }
  418. }
  419. break;
  420. ///////////////////////////////////////////////////////////////////////////////////////////
  421. case 'search_oql': // OQL query
  422. $sOQLClass = utils::ReadParam('oql_class', '', false, 'class');
  423. $sBaseClass = utils::ReadParam('base_class', $sOQLClass, false, 'class');
  424. $sOQLClause = utils::ReadParam('oql_clause', '', false, 'raw_data');
  425. $sFormat = utils::ReadParam('format', '');
  426. $bSearchForm = utils::ReadParam('search_form', true);
  427. $sTitle = utils::ReadParam('title', 'UI:SearchResultsPageTitle');
  428. if (empty($sOQLClass))
  429. {
  430. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'oql_class'));
  431. }
  432. $oP->set_title(Dict::S($sTitle));
  433. $oP->add('<h1>'.Dict::S($sTitle).'</h1>');
  434. $sOQL = "SELECT $sOQLClass $sOQLClause";
  435. try
  436. {
  437. $oFilter = DBObjectSearch::FromOQL($sOQL);
  438. DisplaySearchSet($oP, $oFilter, $bSearchForm, $sBaseClass, $sFormat);
  439. }
  440. catch(CoreException $e)
  441. {
  442. $oFilter = new DBObjectSearch($sOQLClass);
  443. $oSet = new DBObjectSet($oFilter);
  444. if ($bSearchForm)
  445. {
  446. $oBlock = new DisplayBlock($oFilter, 'search', false);
  447. $oBlock->Display($oP, 0);
  448. }
  449. $oP->P('<b>'.Dict::Format('UI:Error:IncorrectOQLQuery_Message', $e->getHtmlDesc()).'</b>');
  450. }
  451. catch(Exception $e)
  452. {
  453. $oP->P('<b>'.Dict::Format('UI:Error:AnErrorOccuredWhileRunningTheQuery_Message', $e->getMessage()).'</b>');
  454. }
  455. break;
  456. ///////////////////////////////////////////////////////////////////////////////////////////
  457. case 'search_form': // Search form
  458. $sClass = utils::ReadParam('class', '', false, 'class');
  459. $sFormat = utils::ReadParam('format', 'html');
  460. $bSearchForm = utils::ReadParam('search_form', true);
  461. $bDoSearch = utils::ReadParam('do_search', true);
  462. if (empty($sClass))
  463. {
  464. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'class'));
  465. }
  466. $oP->set_title(Dict::S('UI:SearchResultsPageTitle'));
  467. $oFilter = new DBObjectSearch($sClass);
  468. DisplaySearchSet($oP, $oFilter, $bSearchForm, '' /* sBaseClass */, $sFormat, $bDoSearch);
  469. break;
  470. ///////////////////////////////////////////////////////////////////////////////////////////
  471. case 'search': // Serialized CMDBSearchFilter
  472. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  473. $sFormat = utils::ReadParam('format', '');
  474. $bSearchForm = utils::ReadParam('search_form', true);
  475. if (empty($sFilter))
  476. {
  477. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'filter'));
  478. }
  479. $oP->set_title(Dict::S('UI:SearchResultsPageTitle'));
  480. // TO DO: limit the search filter by the user context
  481. $oFilter = CMDBSearchFilter::unserialize($sFilter); // TO DO : check that the filter is valid
  482. DisplaySearchSet($oP, $oFilter, $bSearchForm, '' /* sBaseClass */, $sFormat);
  483. break;
  484. ///////////////////////////////////////////////////////////////////////////////////////////
  485. case 'full_text': // Global "google-like" search
  486. $sFullText = trim(utils::ReadParam('text', '', false, 'raw_data'));
  487. $iTune = utils::ReadParam('tune', 0);
  488. if (empty($sFullText))
  489. {
  490. $oP->p(Dict::S('UI:Search:NoSearch'));
  491. }
  492. else
  493. {
  494. $iErrors = 0;
  495. // Check if a class name/label is supplied to limit the search
  496. $sClassName = '';
  497. if (preg_match('/^([^\"]+):(.+)$/', $sFullText, $aMatches))
  498. {
  499. $sClassName = $aMatches[1];
  500. if (MetaModel::IsValidClass($sClassName))
  501. {
  502. $sFullText = trim($aMatches[2]);
  503. }
  504. elseif ($sClassName = MetaModel::GetClassFromLabel($sClassName, false /* => not case sensitive */))
  505. {
  506. $sFullText = trim($aMatches[2]);
  507. }
  508. }
  509. if (preg_match('/^"(.*)"$/', $sFullText, $aMatches))
  510. {
  511. // The text is surrounded by double-quotes, remove the quotes and treat it as one single expression
  512. $aFullTextNeedles = array($aMatches[1]);
  513. }
  514. else
  515. {
  516. // Split the text on the blanks and treat this as a search for <word1> AND <word2> AND <word3>
  517. $aFullTextNeedles = explode(' ', $sFullText);
  518. }
  519. // Check the needle length
  520. $iMinLenth = MetaModel::GetConfig()->Get('full_text_needle_min');
  521. foreach ($aFullTextNeedles as $sNeedle)
  522. {
  523. if (strlen($sNeedle) < $iMinLenth)
  524. {
  525. $oP->p(Dict::Format('UI:Search:NeedleTooShort', $sNeedle, $iMinLenth));
  526. $iErrors++;
  527. }
  528. }
  529. // Sanity check of the accelerators
  530. $aAccelerators = MetaModel::GetConfig()->Get('full_text_accelerators');
  531. foreach ($aAccelerators as $sClass => $aAccelerator)
  532. {
  533. try
  534. {
  535. $bSkip = array_key_exists('skip', $aAccelerator) ? $aAccelerator['skip'] : false;
  536. if (!$bSkip)
  537. {
  538. $oSearch = DBObjectSearch::FromOQL($aAccelerator['query']);
  539. if ($sClass != $oSearch->GetClass())
  540. {
  541. $oP->p("Full text accelerator for class '$sClass': searched class mismatch (".$oSearch->GetClass().")");
  542. $iErrors++;
  543. }
  544. }
  545. }
  546. catch (OqlException $e)
  547. {
  548. $oP->p("Full text accelerator for class '$sClass': ".$e->getHtmlDesc());
  549. $iErrors++;
  550. }
  551. }
  552. if ($iErrors == 0)
  553. {
  554. $oP->set_title(Dict::S('UI:SearchResultsPageTitle'));
  555. $oP->add("<div style=\"padding: 10px;\">\n");
  556. $oP->add("<div class=\"header_message\" id=\"full_text_progress\" style=\"position: fixed; background-color: #cccccc; opacity: 0.7; padding: 1.5em;\">\n");
  557. $oP->add('<img id="full_text_indicator" src="../images/indicator.gif">&nbsp;<span style="padding: 1.5em;">'.Dict::Format('UI:Search:Ongoing', htmlentities($sFullText, ENT_QUOTES, 'UTF-8')).'</span>');
  558. $oP->add("</div>\n");
  559. $oP->add("<div id=\"full_text_results\">\n");
  560. $oP->add("<div id=\"full_text_progress_placeholder\" style=\"padding: 1.5em;\">&nbsp;</div>\n");
  561. $oP->add("<h2>".Dict::Format('UI:FullTextSearchTitle_Text', htmlentities($sFullText, ENT_QUOTES, 'UTF-8'))."</h2>");
  562. $oP->add("</div>\n");
  563. $oP->add("</div>\n");
  564. $sJSClass = addslashes($sClassName);
  565. $sJSNeedles = json_encode($aFullTextNeedles);
  566. $oP->add_ready_script(
  567. <<<EOF
  568. var oParams = {operation: 'full_text_search', position: 0, 'class': '$sJSClass', needles: $sJSNeedles, tune: $iTune};
  569. $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php', oParams, function(data) {
  570. $('#full_text_results').append(data);
  571. });
  572. EOF
  573. );
  574. if ($iTune > 0)
  575. {
  576. $oP->add_script("var oTimeStatistics = {};");
  577. }
  578. }
  579. }
  580. break;
  581. ///////////////////////////////////////////////////////////////////////////////////////////
  582. case 'modify': // Form to modify an object
  583. $sClass = utils::ReadParam('class', '', false, 'class');
  584. $sClassLabel = MetaModel::GetName($sClass);
  585. $id = utils::ReadParam('id', '');
  586. if ( empty($sClass) || empty($id)) // TO DO: check that the class name is valid !
  587. {
  588. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'id'));
  589. }
  590. // Check if the user can modify this object
  591. $oObj = MetaModel::GetObject($sClass, $id, false /* MustBeFound */);
  592. if (is_null($oObj))
  593. {
  594. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  595. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  596. }
  597. else
  598. {
  599. // The object could be read - check if it is allowed to modify it
  600. $oSet = CMDBObjectSet::FromObject($oObj);
  601. if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet) == UR_ALLOWED_NO)
  602. {
  603. throw new SecurityException('User not allowed to modify this object', array('class' => $sClass, 'id' => $id));
  604. }
  605. // Note: code duplicated to the case 'apply_modify' when a data integrity issue has been found
  606. $oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetRawName(), $sClassLabel)); // Set title will take care of the encoding
  607. $oP->add("<div class=\"page_header\">\n");
  608. $oP->add("<h1>".$oObj->GetIcon()."&nbsp;".Dict::Format('UI:ModificationTitle_Class_Object', $sClassLabel, $oObj->GetName())."</h1>\n");
  609. $oP->add("</div>\n");
  610. $oP->add("<div class=\"wizContainer\">\n");
  611. $oObj->DisplayModifyForm($oP);
  612. $oP->add("</div>\n");
  613. }
  614. break;
  615. ///////////////////////////////////////////////////////////////////////////////////////////
  616. case 'select_for_modify_all': // Select the list of objects to be modified (bulk modify)
  617. $oP->set_title(Dict::S('UI:ModifyAllPageTitle'));
  618. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  619. if (empty($sFilter))
  620. {
  621. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'filter'));
  622. }
  623. // TO DO: limit the search filter by the user context
  624. $oFilter = DBObjectSearch::unserialize($sFilter); // TO DO : check that the filter is valid
  625. $sClass = $oFilter->GetClass();
  626. $oChecker = new ActionChecker($oFilter, UR_ACTION_BULK_MODIFY);
  627. $oP->add("<h1>".Dict::S('UI:ModifyAllPageTitle')."</h1>\n");
  628. DisplayMultipleSelectionForm($oP, $oFilter, 'form_for_modify_all', $oChecker);
  629. break;
  630. ///////////////////////////////////////////////////////////////////////////////////////////
  631. case 'form_for_modify_all': // Form to modify multiple objects (bulk modify)
  632. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  633. $sClass = utils::ReadParam('class', '', false, 'class');
  634. $oFullSetFilter = DBObjectSearch::unserialize($sFilter);
  635. $aSelectedObj = utils::ReadMultipleSelection($oFullSetFilter);
  636. $sCancelUrl = "./UI.php?operation=search&filter=".urlencode($sFilter)."&".$oAppContext->GetForLink();
  637. $aContext = array('filter' => $sFilter);
  638. cmdbAbstractObject::DisplayBulkModifyForm($oP, $sClass, $aSelectedObj, 'preview_or_modify_all', $sCancelUrl, array(), $aContext);
  639. break;
  640. ///////////////////////////////////////////////////////////////////////////////////////////
  641. case 'preview_or_modify_all': // Preview or apply bulk modify
  642. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  643. // TO DO: limit the search filter by the user context
  644. $oFilter = DBObjectSearch::unserialize($sFilter); // TO DO : check that the filter is valid
  645. $oChecker = new ActionChecker($oFilter, UR_ACTION_BULK_MODIFY);
  646. $sClass = utils::ReadParam('class', '', false, 'class');
  647. $bPreview = utils::ReadParam('preview_mode', '');
  648. $sSelectedObj = utils::ReadParam('selectObj', '', false, 'raw_data');
  649. if ( empty($sClass) || empty($sSelectedObj)) // TO DO: check that the class name is valid !
  650. {
  651. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'selectObj'));
  652. }
  653. $aSelectedObj = explode(',', $sSelectedObj);
  654. $sCancelUrl = "./UI.php?operation=search&filter=".urlencode($sFilter)."&".$oAppContext->GetForLink();
  655. $aContext = array(
  656. 'filter' => $sFilter,
  657. 'selectObj' => $sSelectedObj,
  658. );
  659. cmdbAbstractObject::DoBulkModify($oP, $sClass, $aSelectedObj, 'preview_or_modify_all', $bPreview, $sCancelUrl, $aContext);
  660. break;
  661. ///////////////////////////////////////////////////////////////////////////////////////////
  662. case 'new': // Form to create a new object
  663. $sClass = utils::ReadParam('class', '', false, 'class');
  664. $sStateCode = utils::ReadParam('state', '');
  665. $bCheckSubClass = utils::ReadParam('checkSubclass', true);
  666. if ( empty($sClass) )
  667. {
  668. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'class'));
  669. }
  670. $aArgs = utils::ReadParam('default', array(), false, 'raw_data');
  671. $aContext = $oAppContext->GetAsHash();
  672. foreach( $oAppContext->GetNames() as $key)
  673. {
  674. $aArgs[$key] = $oAppContext->GetCurrentValue($key);
  675. }
  676. // If the specified class has subclasses, ask the user an instance of which class to create
  677. $aSubClasses = MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL); // Including the specified class itself
  678. $aPossibleClasses = array();
  679. $sRealClass = '';
  680. if ($bCheckSubClass)
  681. {
  682. foreach($aSubClasses as $sCandidateClass)
  683. {
  684. if (!MetaModel::IsAbstract($sCandidateClass) && (UserRights::IsActionAllowed($sCandidateClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES))
  685. {
  686. $aPossibleClasses[$sCandidateClass] = MetaModel::GetName($sCandidateClass);
  687. }
  688. }
  689. // Only one of the subclasses can be instantiated...
  690. if (count($aPossibleClasses) == 1)
  691. {
  692. $aKeys = array_keys($aPossibleClasses);
  693. $sRealClass = $aKeys[0];
  694. }
  695. }
  696. else
  697. {
  698. $sRealClass = $sClass;
  699. }
  700. if (!empty($sRealClass))
  701. {
  702. // Display the creation form
  703. $sClassLabel = MetaModel::GetName($sRealClass);
  704. // Note: some code has been duplicated to the case 'apply_new' when a data integrity issue has been found
  705. $oP->set_title(Dict::Format('UI:CreationPageTitle_Class', $sClassLabel));
  706. $oP->add("<h1>".MetaModel::GetClassIcon($sRealClass)."&nbsp;".Dict::Format('UI:CreationTitle_Class', $sClassLabel)."</h1>\n");
  707. $oP->add("<div class=\"wizContainer\">\n");
  708. // Set all the default values in an object and clone this "default" object
  709. $oObjToClone = MetaModel::NewObject($sRealClass);
  710. // 1st - set context values
  711. $oAppContext->InitObjectFromContext($oObjToClone);
  712. // 2nd - set values from the page argument 'default'
  713. $oObjToClone->UpdateObjectFromArg('default');
  714. cmdbAbstractObject::DisplayCreationForm($oP, $sRealClass, $oObjToClone, array());
  715. $oP->add("</div>\n");
  716. }
  717. else
  718. {
  719. // Select the derived class to create
  720. $sClassLabel = MetaModel::GetName($sClass);
  721. $oP->add("<h1>".MetaModel::GetClassIcon($sClass)."&nbsp;".Dict::Format('UI:CreationTitle_Class', $sClassLabel)."</h1>\n");
  722. $oP->add("<div class=\"wizContainer\">\n");
  723. $oP->add('<form>');
  724. $oP->add('<p>'.Dict::Format('UI:SelectTheTypeOf_Class_ToCreate', $sClassLabel));
  725. $aDefaults = utils::ReadParam('default', array(), false, 'raw_data');
  726. $oP->add($oAppContext->GetForForm());
  727. $oP->add("<input type=\"hidden\" name=\"checkSubclass\" value=\"0\">\n");
  728. $oP->add("<input type=\"hidden\" name=\"state\" value=\"$sStateCode\">\n");
  729. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"new\">\n");
  730. foreach($aDefaults as $key => $value)
  731. {
  732. if (is_array($value))
  733. {
  734. foreach($value as $key2 => $value2)
  735. {
  736. if (is_array($value2))
  737. {
  738. foreach($value2 as $key3 => $value3)
  739. {
  740. $oP->add("<input type=\"hidden\" name=\"default[$key][$key2][$key3]\" value=\"$value3\">\n");
  741. }
  742. }
  743. else
  744. {
  745. $oP->add("<input type=\"hidden\" name=\"default[$key][$key2]\" value=\"$value2\">\n");
  746. }
  747. }
  748. }
  749. else
  750. {
  751. $oP->add("<input type=\"hidden\" name=\"default[$key]\" value=\"$value\">\n");
  752. }
  753. }
  754. $oP->add('<select name="class">');
  755. asort($aPossibleClasses);
  756. foreach($aPossibleClasses as $sClassName => $sClassLabel)
  757. {
  758. $sSelected = ($sClassName == $sClass) ? 'selected' : '';
  759. $oP->add("<option $sSelected value=\"$sClassName\">$sClassLabel</option>");
  760. }
  761. $oP->add('</select>');
  762. $oP->add("&nbsp; <input type=\"submit\" value=\"".Dict::S('UI:Button:Apply')."\"></p>");
  763. $oP->add('</form>');
  764. $oP->add("</div>\n");
  765. }
  766. break;
  767. ///////////////////////////////////////////////////////////////////////////////////////////
  768. case 'apply_modify': // Applying the modifications to an existing object
  769. $sClass = utils::ReadPostedParam('class', '');
  770. $sClassLabel = MetaModel::GetName($sClass);
  771. $id = utils::ReadPostedParam('id', '');
  772. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  773. if ( empty($sClass) || empty($id)) // TO DO: check that the class name is valid !
  774. {
  775. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'id'));
  776. }
  777. $bDisplayDetails = true;
  778. $oObj = MetaModel::GetObject($sClass, $id, false);
  779. if ($oObj == null)
  780. {
  781. $bDisplayDetails = false;
  782. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  783. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  784. }
  785. elseif (!utils::IsTransactionValid($sTransactionId, false))
  786. {
  787. $oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetRawName(), $sClassLabel)); // Set title will take care of the encoding
  788. $oP->p("<strong>".Dict::S('UI:Error:ObjectAlreadyUpdated')."</strong>\n");
  789. }
  790. else
  791. {
  792. $oObj->UpdateObjectFromPostedForm();
  793. $sMessage = '';
  794. $sSeverity = 'ok';
  795. if (!$oObj->IsModified())
  796. {
  797. $oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetRawName(), $sClassLabel)); // Set title will take care of the encoding
  798. $sMessage = Dict::Format('UI:Class_Object_NotUpdated', MetaModel::GetName(get_class($oObj)), $oObj->GetName());
  799. $sSeverity = 'info';
  800. }
  801. else
  802. {
  803. list($bRes, $aIssues) = $oObj->CheckToWrite();
  804. if ($bRes)
  805. {
  806. $oObj->DBUpdate();
  807. utils::RemoveTransaction($sTransactionId);
  808. $sMessage = Dict::Format('UI:Class_Object_Updated', MetaModel::GetName(get_class($oObj)), $oObj->GetName());
  809. $sSeverity = 'ok';
  810. }
  811. else
  812. {
  813. $bDisplayDetails = false;
  814. // Found issues, explain and give the user a second chance
  815. //
  816. $oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetRawName(), $sClassLabel)); // Set title will take care of the encoding
  817. $oP->add("<div class=\"page_header\">\n");
  818. $oP->add("<h1>".$oObj->GetIcon()."&nbsp;".Dict::Format('UI:ModificationTitle_Class_Object', $sClassLabel, $oObj->GetName())."</h1>\n");
  819. $oP->add("</div>\n");
  820. $oP->add("<div class=\"wizContainer\">\n");
  821. $oObj->DisplayModifyForm($oP);
  822. $oP->add("</div>\n");
  823. $sIssueDesc = Dict::Format('UI:ObjectCouldNotBeWritten', implode(', ', $aIssues));
  824. $oP->add_ready_script("alert('".addslashes($sIssueDesc)."');");
  825. }
  826. }
  827. }
  828. if ($bDisplayDetails)
  829. {
  830. $oObj = MetaModel::GetObject(get_class($oObj), $oObj->GetKey()); //Workaround: reload the object so that the linkedset are displayed properly
  831. $sNextAction = utils::ReadPostedParam('next_action', '');
  832. if (!empty($sNextAction))
  833. {
  834. ApplyNextAction($oP, $oObj, $sNextAction);
  835. }
  836. else
  837. {
  838. // Nothing more to do
  839. ReloadAndDisplay($oP, $oObj, 'update', $sMessage, $sSeverity);
  840. }
  841. }
  842. break;
  843. ///////////////////////////////////////////////////////////////////////////////////////////
  844. case 'select_for_deletion': // Select multiple objects for deletion
  845. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  846. if (empty($sFilter))
  847. {
  848. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'filter'));
  849. }
  850. $oP->set_title(Dict::S('UI:BulkDeletePageTitle'));
  851. $oP->add("<h1>".Dict::S('UI:BulkDeleteTitle')."</h1>\n");
  852. // TO DO: limit the search filter by the user context
  853. $oFilter = CMDBSearchFilter::unserialize($sFilter); // TO DO : check that the filter is valid
  854. $oChecker = new ActionChecker($oFilter, UR_ACTION_BULK_DELETE);
  855. DisplayMultipleSelectionForm($oP, $oFilter, 'bulk_delete', $oChecker);
  856. break;
  857. ///////////////////////////////////////////////////////////////////////////////////////////
  858. case 'bulk_delete_confirmed': // Confirm bulk deletion of objects
  859. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  860. if (!utils::IsTransactionValid($sTransactionId))
  861. {
  862. throw new ApplicationException(Dict::S('UI:Error:ObjectsAlreadyDeleted'));
  863. }
  864. // Fall through
  865. ///////////////////////////////////////////////////////////////////////////////////////////
  866. case 'delete':
  867. case 'bulk_delete': // Actual bulk deletion (if confirmed)
  868. $sClass = utils::ReadParam('class', '', false, 'class');
  869. $sClassLabel = MetaModel::GetName($sClass);
  870. $aObjects = array();
  871. if ($operation == 'delete')
  872. {
  873. // Single object
  874. $id = utils::ReadParam('id', '');
  875. $oObj = MetaModel::GetObject($sClass, $id);
  876. $aObjects[] = $oObj;
  877. if (!UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, DBObjectSet::FromObject($oObj)))
  878. {
  879. throw new SecurityException(Dict::Format('UI:Error:DeleteNotAllowedOn_Class', $sClassLabel));
  880. }
  881. }
  882. else
  883. {
  884. // Several objects
  885. $sFilter = utils::ReadPostedParam('filter', '');
  886. $oFullSetFilter = DBObjectSearch::unserialize($sFilter);
  887. $aSelectObject = utils::ReadMultipleSelection($oFullSetFilter);
  888. if ( empty($sClass) || empty($aSelectObject)) // TO DO: check that the class name is valid !
  889. {
  890. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'selectObject[]'));
  891. }
  892. foreach($aSelectObject as $iId)
  893. {
  894. $aObjects[] = MetaModel::GetObject($sClass, $iId);
  895. }
  896. if (count($aObjects) == 1)
  897. {
  898. if (!UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, DBObjectSet::FromArray($sClass, $aObjects)))
  899. {
  900. throw new SecurityException(Dict::Format('UI:Error:BulkDeleteNotAllowedOn_Class', $sClassLabel));
  901. }
  902. }
  903. else
  904. {
  905. if (!UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_DELETE, DBObjectSet::FromArray($sClass, $aObjects)))
  906. {
  907. throw new SecurityException(Dict::Format('UI:Error:BulkDeleteNotAllowedOn_Class', $sClassLabel));
  908. }
  909. $oP->set_title(Dict::S('UI:BulkDeletePageTitle'));
  910. }
  911. }
  912. // Go for the common part... (delete single, delete bulk, delete confirmed)
  913. cmdbAbstractObject::DeleteObjects($oP, $sClass, $aObjects, ($operation != 'bulk_delete_confirmed'), 'bulk_delete_confirmed');
  914. break;
  915. ///////////////////////////////////////////////////////////////////////////////////////////
  916. case 'apply_new': // Creation of a new object
  917. $sClass = utils::ReadPostedParam('class', '', 'class');
  918. $sClassLabel = MetaModel::GetName($sClass);
  919. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  920. if ( empty($sClass) ) // TO DO: check that the class name is valid !
  921. {
  922. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'class'));
  923. }
  924. if (!utils::IsTransactionValid($sTransactionId, false))
  925. {
  926. $oP->p("<strong>".Dict::S('UI:Error:ObjectAlreadyCreated')."</strong>\n");
  927. }
  928. else
  929. {
  930. $oObj = MetaModel::NewObject($sClass);
  931. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  932. if (!empty($sStateAttCode))
  933. {
  934. $sTargetState = utils::ReadPostedParam('obj_state', '');
  935. if ($sTargetState != '')
  936. {
  937. $oObj->Set($sStateAttCode, $sTargetState);
  938. }
  939. }
  940. $oObj->UpdateObjectFromPostedForm();
  941. }
  942. if (isset($oObj) && is_object($oObj))
  943. {
  944. $sClass = get_class($oObj);
  945. $sClassLabel = MetaModel::GetName($sClass);
  946. list($bRes, $aIssues) = $oObj->CheckToWrite();
  947. if ($bRes)
  948. {
  949. $oObj->DBInsert();
  950. utils::RemoveTransaction($sTransactionId);
  951. $oP->set_title(Dict::S('UI:PageTitle:ObjectCreated'));
  952. $sMessage = Dict::Format('UI:Title:Object_Of_Class_Created', $oObj->GetName(), $sClassLabel);
  953. $oObj = MetaModel::GetObject(get_class($oObj), $oObj->GetKey()); //Workaround: reload the object so that the linkedset are displayed properly
  954. $sNextAction = utils::ReadPostedParam('next_action', '');
  955. if (!empty($sNextAction))
  956. {
  957. $oP->add("<h1>$sMessage</h1>");
  958. ApplyNextAction($oP, $oObj, $sNextAction);
  959. }
  960. else
  961. {
  962. // Nothing more to do
  963. ReloadAndDisplay($oP, $oObj, 'create', $sMessage, 'ok');
  964. }
  965. }
  966. else
  967. {
  968. // Found issues, explain and give the user a second chance
  969. //
  970. $oP->set_title(Dict::Format('UI:CreationPageTitle_Class', $sClassLabel));
  971. $oP->add("<h1>".MetaModel::GetClassIcon($sClass)."&nbsp;".Dict::Format('UI:CreationTitle_Class', $sClassLabel)."</h1>\n");
  972. $oP->add("<div class=\"wizContainer\">\n");
  973. cmdbAbstractObject::DisplayCreationForm($oP, $sClass, $oObj);
  974. $oP->add("</div>\n");
  975. $sIssueDesc = Dict::Format('UI:ObjectCouldNotBeWritten', implode(', ', $aIssues));
  976. $oP->add_ready_script("alert('".addslashes($sIssueDesc)."');");
  977. }
  978. }
  979. break;
  980. ///////////////////////////////////////////////////////////////////////////////////////////
  981. case 'select_bulk_stimulus': // Form displayed when applying a stimulus to many objects
  982. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  983. $sStimulus = utils::ReadParam('stimulus', '');
  984. $sState = utils::ReadParam('state', '');
  985. if (empty($sFilter) || empty($sStimulus) || empty($sState))
  986. {
  987. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state'));
  988. }
  989. $oFilter = DBObjectSearch::unserialize($sFilter);
  990. $sClass = $oFilter->GetClass();
  991. $aStimuli = MetaModel::EnumStimuli($sClass);
  992. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  993. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  994. $oP->set_title($sActionLabel);
  995. $oP->add('<div class="page_header">');
  996. $oP->add('<h1>'.MetaModel::GetClassIcon($sClass).'&nbsp;'.$sActionLabel.'</h1>');
  997. $oP->add('</div>');
  998. $oChecker = new StimulusChecker($oFilter, $sState, $sStimulus);
  999. $aExtraFormParams = array('stimulus' => $sStimulus, 'state' => $sState);
  1000. DisplayMultipleSelectionForm($oP, $oFilter, 'bulk_stimulus', $oChecker, $aExtraFormParams);
  1001. break;
  1002. case 'bulk_stimulus':
  1003. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  1004. $sStimulus = utils::ReadParam('stimulus', '');
  1005. $sState = utils::ReadParam('state', '');
  1006. if (empty($sFilter) || empty($sStimulus) || empty($sState))
  1007. {
  1008. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state'));
  1009. }
  1010. $oFilter = DBObjectSearch::unserialize($sFilter);
  1011. $sClass = $oFilter->GetClass();
  1012. $aSelectObject = utils::ReadMultipleSelection($oFilter);
  1013. if (count($aSelectObject) == 0)
  1014. {
  1015. // Nothing to do, no object was selected !
  1016. throw new ApplicationException(Dict::S('UI:BulkAction:NoObjectSelected'));
  1017. }
  1018. else
  1019. {
  1020. $aTransitions = MetaModel::EnumTransitions($sClass, $sState);
  1021. $aStimuli = MetaModel::EnumStimuli($sClass);
  1022. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1023. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1024. $aTransition = $aTransitions[$sStimulus];
  1025. $sTargetState = $aTransition['target_state'];
  1026. $aStates = MetaModel::EnumStates($sClass);
  1027. $aTargetStateDef = $aStates[$sTargetState];
  1028. $oP->set_title(Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aSelectObject), $sClass));
  1029. $oP->add('<div class="page_header">');
  1030. $oP->add('<h1>'.MetaModel::GetClassIcon($sClass).'&nbsp;'.Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aSelectObject), $sClass).'</h1>');
  1031. $oP->add('</div>');
  1032. $aExpectedAttributes = $aTargetStateDef['attribute_list'];
  1033. $aDetails = array();
  1034. $iFieldIndex = 0;
  1035. $aFieldsMap = array();
  1036. $aValues = array();
  1037. $aObjects = array();
  1038. foreach($aSelectObject as $iId)
  1039. {
  1040. $aObjects[] = MetaModel::GetObject($sClass, $iId);
  1041. }
  1042. $oSet = DBObjectSet::FromArray($sClass, $aObjects);
  1043. $oObj = $oSet->ComputeCommonObject($aValues);
  1044. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1045. $oObj->Set($sStateAttCode,$sTargetState);
  1046. $sReadyScript = '';
  1047. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  1048. {
  1049. // Prompt for an attribute if
  1050. // - the attribute must be changed or must be displayed to the user for confirmation
  1051. // - or the field is mandatory and currently empty
  1052. if ( ($iExpectCode & (OPT_ATT_MUSTCHANGE | OPT_ATT_MUSTPROMPT)) ||
  1053. (($iExpectCode & OPT_ATT_MANDATORY) && ($oObj->Get($sAttCode) == '')) )
  1054. {
  1055. $aAttributesDef = MetaModel::ListAttributeDefs($sClass);
  1056. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1057. $aPrerequisites = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  1058. if (count($aPrerequisites) > 0)
  1059. {
  1060. // When 'enabling' a field, all its prerequisites must be enabled too
  1061. $sFieldList = "['".implode("','", $aPrerequisites)."']";
  1062. $oP->add_ready_script("$('#enable_{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, true); } );\n");
  1063. }
  1064. $aDependents = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  1065. if (count($aDependents) > 0)
  1066. {
  1067. // When 'disabling' a field, all its dependent fields must be disabled too
  1068. $sFieldList = "['".implode("','", $aDependents)."']";
  1069. $oP->add_ready_script("$('#enable_{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, false); } );\n");
  1070. }
  1071. $aArgs = array('this' => $oObj);
  1072. $sHTMLValue = cmdbAbstractObject::GetFormElementForField($oP, $sClass, $sAttCode, $oAttDef, $oObj->Get($sAttCode), $oObj->GetEditValue($sAttCode), $sAttCode, '', $iExpectCode, $aArgs);
  1073. $sComments = '<input type="checkbox" checked id="enable_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$sAttCode.'\')"/>';
  1074. if (!isset($aValues[$sAttCode]))
  1075. {
  1076. $aValues[$sAttCode] = array();
  1077. }
  1078. if (count($aValues[$sAttCode]) == 1)
  1079. {
  1080. $sComments .= '<div class="mono_value">1</div>';
  1081. }
  1082. else
  1083. {
  1084. // Non-homogenous value
  1085. $iMaxCount = 5;
  1086. $sTip = "<p><b>".Dict::Format('UI:BulkModify_Count_DistinctValues', count($aValues[$sAttCode]))."</b><ul>";
  1087. $index = 0;
  1088. foreach($aValues[$sAttCode] as $sCurrValue => $aVal)
  1089. {
  1090. $sDisplayValue = empty($aVal['display']) ? '<i>'.Dict::S('Enum:Undefined').'</i>' : str_replace(array("\n", "\r"), " ", $aVal['display']);
  1091. $sTip .= "<li>".Dict::Format('UI:BulkModify:Value_Exists_N_Times', $sDisplayValue, $aVal['count'])."</li>";
  1092. $index++;
  1093. if ($iMaxCount == $index)
  1094. {
  1095. $sTip .= "<li>".Dict::Format('UI:BulkModify:N_MoreValues', count($aValues[$sAttCode]) - $iMaxCount)."</li>";
  1096. break;
  1097. }
  1098. }
  1099. $sTip .= "</ul></p>";
  1100. $sTip = addslashes($sTip);
  1101. $sReadyScript .= "$('#multi_values_$sAttCode').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );\n";
  1102. $sComments .= '<div class="multi_values" id="multi_values_'.$sAttCode.'">'.count($aValues[$sAttCode]).'</div>';
  1103. }
  1104. $aDetails[] = array('label' => '<span>'.$oAttDef->GetLabel().'</span>', 'value' => "<span id=\"field_$sAttCode\">$sHTMLValue</span>", 'comments' => $sComments);
  1105. $aFieldsMap[$sAttCode] = $sAttCode;
  1106. $iFieldIndex++;
  1107. }
  1108. }
  1109. $sButtonsPosition = MetaModel::GetConfig()->Get('buttons_position');
  1110. if ($sButtonsPosition == 'bottom')
  1111. {
  1112. // bottom: Displays the ticket details BEFORE the actions
  1113. $oP->add('<div class="ui-widget-content">');
  1114. $oObj->DisplayBareProperties($oP);
  1115. $oP->add('</div>');
  1116. }
  1117. $oP->add("<div class=\"wizContainer\">\n");
  1118. $oP->add("<form id=\"apply_stimulus\" method=\"post\" onSubmit=\"return OnSubmit('apply_stimulus');\">\n");
  1119. $oP->add("<table><tr><td>\n");
  1120. $oP->details($aDetails);
  1121. $oP->add("</td></tr></table>\n");
  1122. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  1123. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"bulk_apply_stimulus\">\n");
  1124. $oP->add("<input type=\"hidden\" name=\"preview_mode\" value=\"1\">\n");
  1125. $oP->add("<input type=\"hidden\" name=\"filter\" value=\"$sFilter\">\n");
  1126. $oP->add("<input type=\"hidden\" name=\"stimulus\" value=\"$sStimulus\">\n");
  1127. $oP->add("<input type=\"hidden\" name=\"state\" value=\"$sState\">\n");
  1128. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  1129. $oP->add($oAppContext->GetForForm());
  1130. $oP->add("<input type=\"hidden\" name=\"selectObject\" value=\"".implode(',',$aSelectObject)."\">\n");
  1131. $sURL = "./UI.php?operation=search&filter=".urlencode($sFilter)."&".$oAppContext->GetForLink();
  1132. $oP->add("<input type=\"button\" value=\"".Dict::S('UI:Button:Cancel')."\" onClick=\"window.location.href='$sURL'\">&nbsp;&nbsp;&nbsp;&nbsp;\n");
  1133. $oP->add("<button type=\"submit\" class=\"action\"><span>$sActionLabel</span></button>\n");
  1134. $oP->add("</form>\n");
  1135. $oP->add("</div>\n");
  1136. if ($sButtonsPosition != 'bottom')
  1137. {
  1138. // top or both: Displays the ticket details AFTER the actions
  1139. $oP->add('<div class="ui-widget-content">');
  1140. $oObj->DisplayBareProperties($oP);
  1141. $oP->add('</div>');
  1142. }
  1143. $iFieldsCount = count($aFieldsMap);
  1144. $sJsonFieldsMap = json_encode($aFieldsMap);
  1145. $oP->add_script(
  1146. <<<EOF
  1147. // Initializes the object once at the beginning of the page...
  1148. var oWizardHelper = new WizardHelper('$sClass', '', '$sTargetState');
  1149. oWizardHelper.SetFieldsMap($sJsonFieldsMap);
  1150. oWizardHelper.SetFieldsCount($iFieldsCount);
  1151. EOF
  1152. );
  1153. $oP->add_ready_script(
  1154. <<<EOF
  1155. // Starts the validation when the page is ready
  1156. CheckFields('apply_stimulus', false);
  1157. $sReadyScript
  1158. EOF
  1159. );
  1160. }
  1161. break;
  1162. case 'bulk_apply_stimulus':
  1163. $bPreviewMode = utils::ReadPostedParam('preview_mode', false);
  1164. $sFilter = utils::ReadPostedParam('filter', '', false, 'raw_data');
  1165. $sStimulus = utils::ReadPostedParam('stimulus', '');
  1166. $sState = utils::ReadPostedParam('state', '');
  1167. $sSelectObject = utils::ReadPostedParam('selectObject', '', false, 'raw_data');
  1168. $aSelectObject = explode(',', $sSelectObject);
  1169. if (empty($sFilter) || empty($sStimulus) || empty($sState))
  1170. {
  1171. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state'));
  1172. }
  1173. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1174. if (!utils::IsTransactionValid($sTransactionId))
  1175. {
  1176. $oP->p(Dict::S('UI:Error:ObjectAlreadyUpdated'));
  1177. }
  1178. else
  1179. {
  1180. // For archiving the modification
  1181. $oFilter = DBObjectSearch::unserialize($sFilter);
  1182. $sClass = $oFilter->GetClass();
  1183. $aObjects = array();
  1184. foreach($aSelectObject as $iId)
  1185. {
  1186. $aObjects[] = MetaModel::GetObject($sClass, $iId);
  1187. }
  1188. $aTransitions = MetaModel::EnumTransitions($sClass, $sState);
  1189. $aStimuli = MetaModel::EnumStimuli($sClass);
  1190. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1191. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1192. $oP->set_title(Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aObjects), $sClass));
  1193. $oP->add('<div class="page_header">');
  1194. $oP->add('<h1>'.MetaModel::GetClassIcon($sClass).'&nbsp;'.Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aObjects), $sClass).'</h1>');
  1195. $oP->add('</div>');
  1196. $oSet = DBObjectSet::FromArray($sClass, $aObjects);
  1197. // For reporting
  1198. $aHeaders = array(
  1199. 'object' => array('label' => MetaModel::GetName($sClass), 'description' => Dict::S('UI:ModifiedObject')),
  1200. 'status' => array('label' => Dict::S('UI:BulkModifyStatus'), 'description' => Dict::S('UI:BulkModifyStatus+')),
  1201. 'errors' => array('label' => Dict::S('UI:BulkModifyErrors'), 'description' => Dict::S('UI:BulkModifyErrors+')),
  1202. );
  1203. $aRows = array();
  1204. while ($oObj = $oSet->Fetch())
  1205. {
  1206. $sError = Dict::S('UI:BulkModifyStatusOk');
  1207. try
  1208. {
  1209. $aTransitions = $oObj->EnumTransitions();
  1210. $aStimuli = MetaModel::EnumStimuli($sClass);
  1211. if (!isset($aTransitions[$sStimulus]))
  1212. {
  1213. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
  1214. }
  1215. else
  1216. {
  1217. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1218. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1219. $aTransition = $aTransitions[$sStimulus];
  1220. $sTargetState = $aTransition['target_state'];
  1221. $aTargetStates = MetaModel::EnumStates($sClass);
  1222. $aTargetState = $aTargetStates[$sTargetState];
  1223. $aExpectedAttributes = $aTargetState['attribute_list'];
  1224. $aDetails = array();
  1225. $aErrors = array();
  1226. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  1227. {
  1228. $iFlags = $oObj->GetAttributeFlags($sAttCode);
  1229. if (($iExpectCode & (OPT_ATT_MUSTCHANGE|OPT_ATT_MUSTPROMPT)) || ($oObj->Get($sAttCode) == '') )
  1230. {
  1231. $paramValue = utils::ReadPostedParam("attr_$sAttCode", '', 'raw_data');
  1232. if ( ($iFlags & OPT_ATT_SLAVE) && ($paramValue != $oObj->Get($sAttCode)) )
  1233. {
  1234. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1235. $aErrors[] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $oAttDef->GetLabel());
  1236. unset($aExpectedAttributes[$sAttCode]);
  1237. }
  1238. }
  1239. }
  1240. $oObj->UpdateObjectFromPostedForm('', array_keys($aExpectedAttributes), $sTargetState);
  1241. if (count($aErrors) == 0)
  1242. {
  1243. if ($oObj->ApplyStimulus($sStimulus))
  1244. {
  1245. list($bResult, $aErrors) = $oObj->CheckToWrite();
  1246. $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusModified') : Dict::S('UI:BulkModifyStatusSkipped');
  1247. if ($bResult)
  1248. {
  1249. $oObj->DBUpdate();
  1250. }
  1251. else
  1252. {
  1253. $sError = '<p>'.implode('</p></p>',$aErrors)."</p>\n";
  1254. }
  1255. }
  1256. else
  1257. {
  1258. $sStatus = Dict::S('UI:BulkModifyStatusSkipped');
  1259. $sError = '<p>'.Dict::S('UI:FailedToApplyStimuli')."<p>\n";
  1260. }
  1261. }
  1262. else
  1263. {
  1264. $sStatus = Dict::S('UI:BulkModifyStatusSkipped');
  1265. $sError = '<p>'.implode('</p></p>',$aErrors)."</p>\n";
  1266. }
  1267. }
  1268. }
  1269. catch(Exception $e)
  1270. {
  1271. $sError = $e->getMessage();
  1272. $sStatus = Dict::S('UI:BulkModifyStatusSkipped');
  1273. }
  1274. $aRows[] = array(
  1275. 'object' => $oObj->GetHyperlink(),
  1276. 'status' => $sStatus,
  1277. 'errors' => $sError,
  1278. );
  1279. }
  1280. $oP->Table($aHeaders, $aRows);
  1281. // Back to the list
  1282. $sURL = "./UI.php?operation=search&filter=".urlencode($sFilter)."&".$oAppContext->GetForLink();
  1283. $oP->add('<input type="button" onClick="window.location.href=\''.$sURL.'\'" value="'.Dict::S('UI:Button:Done').'">');
  1284. }
  1285. break;
  1286. case 'stimulus': // Form displayed when applying a stimulus (state change)
  1287. $sClass = utils::ReadParam('class', '', false, 'class');
  1288. $id = utils::ReadParam('id', '');
  1289. $sStimulus = utils::ReadParam('stimulus', '');
  1290. if ( empty($sClass) || empty($id) || empty($sStimulus) ) // TO DO: check that the class name is valid !
  1291. {
  1292. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'class', 'id', 'stimulus'));
  1293. }
  1294. $oObj = MetaModel::GetObject($sClass, $id, false);
  1295. if ($oObj != null)
  1296. {
  1297. $oObj->DisplayStimulusForm($oP, $sStimulus);
  1298. }
  1299. else
  1300. {
  1301. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  1302. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  1303. }
  1304. break;
  1305. ///////////////////////////////////////////////////////////////////////////////////////////
  1306. case 'apply_stimulus': // Actual state change
  1307. $sClass = utils::ReadPostedParam('class', '');
  1308. $id = utils::ReadPostedParam('id', '');
  1309. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1310. $sStimulus = utils::ReadPostedParam('stimulus', '');
  1311. if ( empty($sClass) || empty($id) || empty($sStimulus) ) // TO DO: check that the class name is valid !
  1312. {
  1313. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'class', 'id', 'stimulus'));
  1314. }
  1315. $oObj = MetaModel::GetObject($sClass, $id, false);
  1316. if ($oObj != null)
  1317. {
  1318. $aTransitions = $oObj->EnumTransitions();
  1319. $aStimuli = MetaModel::EnumStimuli($sClass);
  1320. $sMessage = '';
  1321. $sSeverity = 'ok';
  1322. $bDisplayDetails = true;
  1323. if (!isset($aTransitions[$sStimulus]))
  1324. {
  1325. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
  1326. }
  1327. if (!utils::IsTransactionValid($sTransactionId))
  1328. {
  1329. $sMessage = Dict::S('UI:Error:ObjectAlreadyUpdated');
  1330. $sSeverity = 'info';
  1331. }
  1332. else
  1333. {
  1334. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1335. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1336. $aTransition = $aTransitions[$sStimulus];
  1337. $sTargetState = $aTransition['target_state'];
  1338. $aTargetStates = MetaModel::EnumStates($sClass);
  1339. $aTargetState = $aTargetStates[$sTargetState];
  1340. $aExpectedAttributes = $aTargetState['attribute_list'];
  1341. $aDetails = array();
  1342. $aErrors = array();
  1343. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  1344. {
  1345. $iFlags = $oObj->GetAttributeFlags($sAttCode);
  1346. if (($iExpectCode & (OPT_ATT_MUSTCHANGE|OPT_ATT_MUSTPROMPT)) || ($oObj->Get($sAttCode) == '') )
  1347. {
  1348. $paramValue = utils::ReadPostedParam("attr_$sAttCode", '', 'raw_data');
  1349. if ( ($iFlags & OPT_ATT_SLAVE) && ($paramValue != $oObj->Get($sAttCode)))
  1350. {
  1351. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1352. $aErrors[] = Dict::Format('UI:AttemptingToChangeASlaveAttribute_Name', $oAttDef->GetLabel());
  1353. unset($aExpectedAttributes[$sAttCode]);
  1354. }
  1355. }
  1356. }
  1357. $oObj->UpdateObjectFromPostedForm('', array_keys($aExpectedAttributes), $sTargetState);
  1358. if (count($aErrors) == 0)
  1359. {
  1360. $sIssues = '';
  1361. $bApplyStimulus = true;
  1362. list($bRes, $aIssues) = $oObj->CheckToWrite(); // Check before trying to write the object
  1363. if ($bRes)
  1364. {
  1365. try
  1366. {
  1367. $bApplyStimulus = $oObj->ApplyStimulus($sStimulus); // will write the object in the DB
  1368. }
  1369. catch(CoreException $e)
  1370. {
  1371. // Rollback to the previous state... by reloading the object from the database and applying the modifications again
  1372. $oObj = MetaModel::GetObject(get_class($oObj), $oObj->GetKey());
  1373. $oObj->UpdateObjectFromPostedForm('', array_keys($aExpectedAttributes), $sTargetState);
  1374. $aData = $e->getContextData();
  1375. $sIssues = (array_key_exists('issues', $aData)) ? $aData['issues'] : 'Unknown error...';
  1376. }
  1377. }
  1378. else
  1379. {
  1380. $sIssues = implode(' ', $aIssues);
  1381. }
  1382. if (!$bApplyStimulus)
  1383. {
  1384. $sMessage = Dict::S('UI:FailedToApplyStimuli');
  1385. $sSeverity = 'error';
  1386. }
  1387. else if ($sIssues != '')
  1388. {
  1389. $bDisplayDetails = false;
  1390. // Found issues, explain and give the user a second chance
  1391. //
  1392. $oObj->DisplayStimulusForm($oP, $sStimulus);
  1393. $sIssueDesc = Dict::Format('UI:ObjectCouldNotBeWritten',$sIssues);
  1394. $oP->add_ready_script("alert('".addslashes($sIssueDesc)."');");
  1395. }
  1396. else
  1397. {
  1398. $sMessage = Dict::Format('UI:Class_Object_Updated', MetaModel::GetName(get_class($oObj)), $oObj->GetName());
  1399. $sSeverity = 'ok';
  1400. utils::RemoveTransaction($sTransactionId);
  1401. }
  1402. }
  1403. else
  1404. {
  1405. $sMessage = implode('</p><p>', $aErrors);
  1406. $sSeverity = 'error';
  1407. }
  1408. }
  1409. if ($bDisplayDetails)
  1410. {
  1411. ReloadAndDisplay($oP, $oObj, 'apply_stimulus', $sMessage, $sSeverity);
  1412. }
  1413. }
  1414. else
  1415. {
  1416. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  1417. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  1418. }
  1419. break;
  1420. ///////////////////////////////////////////////////////////////////////////////////////////
  1421. case 'swf_navigator': // Graphical display of the relations "impact" / "depends on"
  1422. require_once(APPROOT.'core/simplegraph.class.inc.php');
  1423. require_once(APPROOT.'core/relationgraph.class.inc.php');
  1424. require_once(APPROOT.'core/displayablegraph.class.inc.php');
  1425. $sClass = utils::ReadParam('class', '', false, 'class');
  1426. $id = utils::ReadParam('id', 0);
  1427. $sRelation = utils::ReadParam('relation', 'impact');
  1428. $sDirection = utils::ReadParam('direction', 'down');
  1429. $oObj = MetaModel::GetObject($sClass, $id);
  1430. $iMaxRecursionDepth = MetaModel::GetConfig()->Get('relations_max_depth', 20);
  1431. $aSourceObjects = array($oObj);
  1432. if ($sRelation == 'depends on')
  1433. {
  1434. $sRelation = 'impacts';
  1435. $sDirection = 'up';
  1436. }
  1437. if ($sDirection == 'up')
  1438. {
  1439. $oRelGraph = MetaModel::GetRelatedObjectsUp($sRelation, $aSourceObjects, $iMaxRecursionDepth);
  1440. }
  1441. else
  1442. {
  1443. $oRelGraph = MetaModel::GetRelatedObjectsDown($sRelation, $aSourceObjects, $iMaxRecursionDepth);
  1444. }
  1445. $aResults = array();
  1446. $oIterator = new RelationTypeIterator($oRelGraph, 'Node');
  1447. foreach($oIterator as $oNode)
  1448. {
  1449. $oObj = $oNode->GetProperty('object'); // Some nodes (Redundancy Nodes) do not contain an object
  1450. if ($oObj)
  1451. {
  1452. $sObjClass = get_class($oObj);
  1453. if (!array_key_exists($sClass, $aResults))
  1454. {
  1455. $aResults[$sObjClass] = array();
  1456. }
  1457. $aResults[$sObjClass][] = $oObj;
  1458. }
  1459. }
  1460. $oP->AddTabContainer('Navigator');
  1461. $oP->SetCurrentTabContainer('Navigator');
  1462. $sFirstTab = MetaModel::GetConfig()->Get('impact_analysis_first_tab');
  1463. if ($sFirstTab == 'list')
  1464. {
  1465. DisplayNavigatorListTab($oP, $aResults, $sRelation, $oObj);
  1466. DisplayNavigatorGraphicsTab($oP, $aResults, $oRelGraph, $sClass, $id, $sRelation, $oAppContext, ($sDirection == 'down'));
  1467. }
  1468. else
  1469. {
  1470. DisplayNavigatorGraphicsTab($oP, $aResults, $oRelGraph, $sClass, $id, $sRelation, $oAppContext, ($sDirection == 'down'));
  1471. DisplayNavigatorListTab($oP, $aResults, $sRelation, $oObj);
  1472. }
  1473. $oP->SetCurrentTab('');
  1474. break;
  1475. ///////////////////////////////////////////////////////////////////////////////////////////
  1476. case 'cancel': // An action was cancelled
  1477. $oP->set_title(Dict::S('UI:OperationCancelled'));
  1478. $oP->add('<h1>'.Dict::S('UI:OperationCancelled').'</h1>');
  1479. break;
  1480. ///////////////////////////////////////////////////////////////////////////////////////////
  1481. default: // Menu node rendering (templates)
  1482. ApplicationMenu::LoadAdditionalMenus();
  1483. $oMenuNode = ApplicationMenu::GetMenuNode(ApplicationMenu::GetMenuIndexById(ApplicationMenu::GetActiveNodeId()));
  1484. if (is_object($oMenuNode))
  1485. {
  1486. $oMenuNode->RenderContent($oP, $oAppContext->GetAsHash());
  1487. $oP->set_title($oMenuNode->GetLabel());
  1488. }
  1489. ///////////////////////////////////////////////////////////////////////////////////////////
  1490. }
  1491. DisplayWelcomePopup($oP);
  1492. $oP->output();
  1493. }
  1494. catch(CoreException $e)
  1495. {
  1496. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  1497. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  1498. if ($e instanceof SecurityException)
  1499. {
  1500. $oP->add("<h1>".Dict::S('UI:SystemIntrusion')."</h1>\n");
  1501. }
  1502. else
  1503. {
  1504. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  1505. }
  1506. $oP->error(Dict::Format('UI:Error_Details', $e->getHtmlDesc()));
  1507. $oP->output();
  1508. if (MetaModel::IsLogEnabledIssue())
  1509. {
  1510. if (MetaModel::IsValidClass('EventIssue'))
  1511. {
  1512. try
  1513. {
  1514. $oLog = new EventIssue();
  1515. $oLog->Set('message', $e->getMessage());
  1516. $oLog->Set('userinfo', '');
  1517. $oLog->Set('issue', $e->GetIssue());
  1518. $oLog->Set('impact', 'Page could not be displayed');
  1519. $oLog->Set('callstack', $e->getTrace());
  1520. $oLog->Set('data', $e->getContextData());
  1521. $oLog->DBInsertNoReload();
  1522. }
  1523. catch(Exception $e)
  1524. {
  1525. IssueLog::Error("Failed to log issue into the DB");
  1526. }
  1527. }
  1528. IssueLog::Error($e->getMessage());
  1529. }
  1530. // For debugging only
  1531. //throw $e;
  1532. }
  1533. catch(Exception $e)
  1534. {
  1535. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  1536. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  1537. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  1538. $oP->error(Dict::Format('UI:Error_Details', $e->getMessage()));
  1539. $oP->output();
  1540. if (MetaModel::IsLogEnabledIssue())
  1541. {
  1542. if (MetaModel::IsValidClass('EventIssue'))
  1543. {
  1544. try
  1545. {
  1546. $oLog = new EventIssue();
  1547. $oLog->Set('message', $e->getMessage());
  1548. $oLog->Set('userinfo', '');
  1549. $oLog->Set('issue', 'PHP Exception');
  1550. $oLog->Set('impact', 'Page could not be displayed');
  1551. $oLog->Set('callstack', $e->getTrace());
  1552. $oLog->Set('data', array());
  1553. $oLog->DBInsertNoReload();
  1554. }
  1555. catch(Exception $e)
  1556. {
  1557. IssueLog::Error("Failed to log issue into the DB");
  1558. }
  1559. }
  1560. IssueLog::Error($e->getMessage());
  1561. }
  1562. }
  1563. ?>