UI.php 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620
  1. <?php
  2. // Copyright (C) 2010-2015 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. $oP->add("<h1>".MetaModel::GetRelationDescription($sRelation).' '.$oObj->GetName()."</h1>\n");
  215. $iBlock = 1; // Zero is not a valid blockid
  216. foreach($aResults as $sListClass => $aObjects)
  217. {
  218. $oSet = CMDBObjectSet::FromArray($sListClass, $aObjects);
  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 DisplayNavigatorGroupTab($oP, $aGroups, $sRelation, $oObj)
  229. {
  230. if (count($aGroups) > 0)
  231. {
  232. $oP->SetCurrentTab(Dict::S('UI:RelationGroups'));
  233. $oP->add("<div id=\"impacted_groupss\" style=\"width:100%;background-color:#fff;padding:10px;\">");
  234. $iBlock = 1; // Zero is not a valid blockid
  235. foreach($aGroups as $idx => $aObjects)
  236. {
  237. $sListClass = get_class(current($aObjects));
  238. $oSet = CMDBObjectSet::FromArray($sListClass, $aObjects);
  239. $oP->add("<h1>".Dict::Format('UI:RelationGroupNumber_N', (1+$idx))."</h1>\n");
  240. $oP->add("<div id=\"relation_group_$idx\" class=\"page_header\">\n");
  241. $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");
  242. $oP->add("</div>\n");
  243. $oBlock = DisplayBlock::FromObjectSet($oSet, 'list');
  244. $oBlock->Display($oP, 'group_'.$iBlock++);
  245. $oP->p('&nbsp;'); // Some space ?
  246. }
  247. $oP->add("</div>");
  248. }
  249. }
  250. /***********************************************************************************
  251. *
  252. * Main user interface page starts here
  253. *
  254. ***********************************************************************************/
  255. try
  256. {
  257. require_once('../approot.inc.php');
  258. require_once(APPROOT.'/application/application.inc.php');
  259. require_once(APPROOT.'/application/itopwebpage.class.inc.php');
  260. require_once(APPROOT.'/application/wizardhelper.class.inc.php');
  261. require_once(APPROOT.'/application/startup.inc.php');
  262. $operation = utils::ReadParam('operation', '');
  263. $oKPI = new ExecutionKPI();
  264. $oKPI->ComputeAndReport('Data model loaded');
  265. $oKPI = new ExecutionKPI();
  266. require_once(APPROOT.'/application/loginwebpage.class.inc.php');
  267. $sLoginMessage = LoginWebPage::DoLogin(); // Check user rights and prompt if needed
  268. $oAppContext = new ApplicationContext();
  269. $oKPI->ComputeAndReport('User login');
  270. $oP = new iTopWebPage(Dict::S('UI:WelcomeToITop'));
  271. $oP->SetMessage($sLoginMessage);
  272. // All the following actions use advanced forms that require more javascript to be loaded
  273. switch($operation)
  274. {
  275. case 'new': // Form to create a new object
  276. case 'modify': // Form to modify an object
  277. case 'apply_new': // Creation of a new object
  278. case 'apply_modify': // Applying the modifications to an existing object
  279. case 'form_for_modify_all': // Form to modify multiple objects (bulk modify)
  280. case 'bulk_stimulus': // For to apply a stimulus to multiple objects
  281. case 'stimulus': // Form displayed when applying a stimulus (state change)
  282. case 'apply_stimulus': // Form displayed when applying a stimulus (state change)
  283. $oP->add_linked_script("../js/json.js");
  284. $oP->add_linked_script("../js/forms-json-utils.js");
  285. $oP->add_linked_script("../js/wizardhelper.js");
  286. $oP->add_linked_script("../js/wizard.utils.js");
  287. $oP->add_linked_script("../js/linkswidget.js");
  288. $oP->add_linked_script("../js/linksdirectwidget.js");
  289. $oP->add_linked_script("../js/extkeywidget.js");
  290. $oP->add_linked_script("../js/jquery.blockUI.js");
  291. break;
  292. }
  293. switch($operation)
  294. {
  295. ///////////////////////////////////////////////////////////////////////////////////////////
  296. case 'details': // Details of an object
  297. $sClass = utils::ReadParam('class', '');
  298. $id = utils::ReadParam('id', '');
  299. if ( empty($sClass) || empty($id))
  300. {
  301. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'id'));
  302. }
  303. if (is_numeric($id))
  304. {
  305. $oObj = MetaModel::GetObject($sClass, $id, false /* MustBeFound */);
  306. }
  307. else
  308. {
  309. $oObj = MetaModel::GetObjectByName($sClass, $id, false /* MustBeFound */);
  310. }
  311. if (is_null($oObj))
  312. {
  313. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  314. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  315. }
  316. else
  317. {
  318. try
  319. {
  320. $oObj->Reload();
  321. }
  322. catch(Exception $e)
  323. {
  324. // Probably not allowed to see this instance of a derived class
  325. $oObj = null;
  326. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  327. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  328. }
  329. if (!is_null($oObj))
  330. {
  331. DisplayDetails($oP, $sClass, $oObj, $id);
  332. }
  333. }
  334. break;
  335. ///////////////////////////////////////////////////////////////////////////////////////////
  336. case 'search_oql': // OQL query
  337. $sOQLClass = utils::ReadParam('oql_class', '', false, 'class');
  338. $sBaseClass = utils::ReadParam('base_class', $sOQLClass, false, 'class');
  339. $sOQLClause = utils::ReadParam('oql_clause', '', false, 'raw_data');
  340. $sFormat = utils::ReadParam('format', '');
  341. $bSearchForm = utils::ReadParam('search_form', true);
  342. $sTitle = utils::ReadParam('title', 'UI:SearchResultsPageTitle');
  343. if (empty($sOQLClass))
  344. {
  345. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'oql_class'));
  346. }
  347. $oP->set_title(Dict::S($sTitle));
  348. $oP->add('<h1>'.Dict::S($sTitle).'</h1>');
  349. $sOQL = "SELECT $sOQLClass $sOQLClause";
  350. try
  351. {
  352. $oFilter = DBObjectSearch::FromOQL($sOQL);
  353. DisplaySearchSet($oP, $oFilter, $bSearchForm, $sBaseClass, $sFormat);
  354. }
  355. catch(CoreException $e)
  356. {
  357. $oFilter = new DBObjectSearch($sOQLClass);
  358. $oSet = new DBObjectSet($oFilter);
  359. if ($bSearchForm)
  360. {
  361. $oBlock = new DisplayBlock($oFilter, 'search', false);
  362. $oBlock->Display($oP, 0);
  363. }
  364. $oP->P('<b>'.Dict::Format('UI:Error:IncorrectOQLQuery_Message', $e->getHtmlDesc()).'</b>');
  365. }
  366. catch(Exception $e)
  367. {
  368. $oP->P('<b>'.Dict::Format('UI:Error:AnErrorOccuredWhileRunningTheQuery_Message', $e->getMessage()).'</b>');
  369. }
  370. break;
  371. ///////////////////////////////////////////////////////////////////////////////////////////
  372. case 'search_form': // Search form
  373. $sClass = utils::ReadParam('class', '', false, 'class');
  374. $sFormat = utils::ReadParam('format', 'html');
  375. $bSearchForm = utils::ReadParam('search_form', true);
  376. $bDoSearch = utils::ReadParam('do_search', true);
  377. if (empty($sClass))
  378. {
  379. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'class'));
  380. }
  381. $oP->set_title(Dict::S('UI:SearchResultsPageTitle'));
  382. $oFilter = new DBObjectSearch($sClass);
  383. DisplaySearchSet($oP, $oFilter, $bSearchForm, '' /* sBaseClass */, $sFormat, $bDoSearch);
  384. break;
  385. ///////////////////////////////////////////////////////////////////////////////////////////
  386. case 'search': // Serialized CMDBSearchFilter
  387. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  388. $sFormat = utils::ReadParam('format', '');
  389. $bSearchForm = utils::ReadParam('search_form', true);
  390. if (empty($sFilter))
  391. {
  392. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'filter'));
  393. }
  394. $oP->set_title(Dict::S('UI:SearchResultsPageTitle'));
  395. // TO DO: limit the search filter by the user context
  396. $oFilter = CMDBSearchFilter::unserialize($sFilter); // TO DO : check that the filter is valid
  397. DisplaySearchSet($oP, $oFilter, $bSearchForm, '' /* sBaseClass */, $sFormat);
  398. break;
  399. ///////////////////////////////////////////////////////////////////////////////////////////
  400. case 'full_text': // Global "google-like" search
  401. $sFullText = trim(utils::ReadParam('text', '', false, 'raw_data'));
  402. $iTune = utils::ReadParam('tune', 0);
  403. if (empty($sFullText))
  404. {
  405. $oP->p(Dict::S('UI:Search:NoSearch'));
  406. }
  407. else
  408. {
  409. $iErrors = 0;
  410. // Check if a class name/label is supplied to limit the search
  411. $sClassName = '';
  412. if (preg_match('/^([^\"]+):(.+)$/', $sFullText, $aMatches))
  413. {
  414. $sClassName = $aMatches[1];
  415. if (MetaModel::IsValidClass($sClassName))
  416. {
  417. $sFullText = trim($aMatches[2]);
  418. }
  419. elseif ($sClassName = MetaModel::GetClassFromLabel($sClassName, false /* => not case sensitive */))
  420. {
  421. $sFullText = trim($aMatches[2]);
  422. }
  423. }
  424. if (preg_match('/^"(.*)"$/', $sFullText, $aMatches))
  425. {
  426. // The text is surrounded by double-quotes, remove the quotes and treat it as one single expression
  427. $aFullTextNeedles = array($aMatches[1]);
  428. }
  429. else
  430. {
  431. // Split the text on the blanks and treat this as a search for <word1> AND <word2> AND <word3>
  432. $aFullTextNeedles = explode(' ', $sFullText);
  433. }
  434. // Check the needle length
  435. $iMinLenth = MetaModel::GetConfig()->Get('full_text_needle_min');
  436. foreach ($aFullTextNeedles as $sNeedle)
  437. {
  438. if (strlen($sNeedle) < $iMinLenth)
  439. {
  440. $oP->p(Dict::Format('UI:Search:NeedleTooShort', $sNeedle, $iMinLenth));
  441. $iErrors++;
  442. }
  443. }
  444. // Sanity check of the accelerators
  445. $aAccelerators = MetaModel::GetConfig()->Get('full_text_accelerators');
  446. foreach ($aAccelerators as $sClass => $aAccelerator)
  447. {
  448. try
  449. {
  450. $bSkip = array_key_exists('skip', $aAccelerator) ? $aAccelerator['skip'] : false;
  451. if (!$bSkip)
  452. {
  453. $oSearch = DBObjectSearch::FromOQL($aAccelerator['query']);
  454. if ($sClass != $oSearch->GetClass())
  455. {
  456. $oP->p("Full text accelerator for class '$sClass': searched class mismatch (".$oSearch->GetClass().")");
  457. $iErrors++;
  458. }
  459. }
  460. }
  461. catch (OqlException $e)
  462. {
  463. $oP->p("Full text accelerator for class '$sClass': ".$e->getHtmlDesc());
  464. $iErrors++;
  465. }
  466. }
  467. if ($iErrors == 0)
  468. {
  469. $oP->set_title(Dict::S('UI:SearchResultsPageTitle'));
  470. $oP->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/xlsx-export.js');
  471. $oP->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/tabularfieldsselector.js');
  472. $oP->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/jquery.dragtable.js');
  473. $oP->add_linked_stylesheet(utils::GetAbsoluteUrlAppRoot().'css/dragtable.css');
  474. $oP->add("<div style=\"padding: 10px;\">\n");
  475. $oP->add("<div class=\"header_message\" id=\"full_text_progress\" style=\"position: fixed; background-color: #cccccc; opacity: 0.7; padding: 1.5em;\">\n");
  476. $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>');
  477. $oP->add("</div>\n");
  478. $oP->add("<div id=\"full_text_results\">\n");
  479. $oP->add("<div id=\"full_text_progress_placeholder\" style=\"padding: 1.5em;\">&nbsp;</div>\n");
  480. $oP->add("<h2>".Dict::Format('UI:FullTextSearchTitle_Text', htmlentities($sFullText, ENT_QUOTES, 'UTF-8'))."</h2>");
  481. $oP->add("</div>\n");
  482. $oP->add("</div>\n");
  483. $sJSClass = addslashes($sClassName);
  484. $sJSNeedles = json_encode($aFullTextNeedles);
  485. $oP->add_ready_script(
  486. <<<EOF
  487. var oParams = {operation: 'full_text_search', position: 0, 'class': '$sJSClass', needles: $sJSNeedles, tune: $iTune};
  488. $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php', oParams, function(data) {
  489. $('#full_text_results').append(data);
  490. });
  491. EOF
  492. );
  493. if ($iTune > 0)
  494. {
  495. $oP->add_script("var oTimeStatistics = {};");
  496. }
  497. }
  498. }
  499. break;
  500. ///////////////////////////////////////////////////////////////////////////////////////////
  501. case 'modify': // Form to modify an object
  502. $sClass = utils::ReadParam('class', '', false, 'class');
  503. $sClassLabel = MetaModel::GetName($sClass);
  504. $id = utils::ReadParam('id', '');
  505. if ( empty($sClass) || empty($id)) // TO DO: check that the class name is valid !
  506. {
  507. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'id'));
  508. }
  509. // Check if the user can modify this object
  510. $oObj = MetaModel::GetObject($sClass, $id, false /* MustBeFound */);
  511. if (is_null($oObj))
  512. {
  513. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  514. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  515. }
  516. else
  517. {
  518. // The object could be read - check if it is allowed to modify it
  519. $oSet = CMDBObjectSet::FromObject($oObj);
  520. if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet) == UR_ALLOWED_NO)
  521. {
  522. throw new SecurityException('User not allowed to modify this object', array('class' => $sClass, 'id' => $id));
  523. }
  524. // Note: code duplicated to the case 'apply_modify' when a data integrity issue has been found
  525. $oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetRawName(), $sClassLabel)); // Set title will take care of the encoding
  526. $oP->add("<div class=\"page_header\">\n");
  527. $oP->add("<h1>".$oObj->GetIcon()."&nbsp;".Dict::Format('UI:ModificationTitle_Class_Object', $sClassLabel, $oObj->GetName())."</h1>\n");
  528. $oP->add("</div>\n");
  529. $oP->add("<div class=\"wizContainer\">\n");
  530. $oObj->DisplayModifyForm($oP);
  531. $oP->add("</div>\n");
  532. }
  533. break;
  534. ///////////////////////////////////////////////////////////////////////////////////////////
  535. case 'select_for_modify_all': // Select the list of objects to be modified (bulk modify)
  536. $oP->set_title(Dict::S('UI:ModifyAllPageTitle'));
  537. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  538. if (empty($sFilter))
  539. {
  540. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'filter'));
  541. }
  542. // TO DO: limit the search filter by the user context
  543. $oFilter = DBObjectSearch::unserialize($sFilter); // TO DO : check that the filter is valid
  544. $sClass = $oFilter->GetClass();
  545. $oChecker = new ActionChecker($oFilter, UR_ACTION_BULK_MODIFY);
  546. $oP->add("<h1>".Dict::S('UI:ModifyAllPageTitle')."</h1>\n");
  547. DisplayMultipleSelectionForm($oP, $oFilter, 'form_for_modify_all', $oChecker);
  548. break;
  549. ///////////////////////////////////////////////////////////////////////////////////////////
  550. case 'form_for_modify_all': // Form to modify multiple objects (bulk modify)
  551. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  552. $sClass = utils::ReadParam('class', '', false, 'class');
  553. $oFullSetFilter = DBObjectSearch::unserialize($sFilter);
  554. $aSelectedObj = utils::ReadMultipleSelection($oFullSetFilter);
  555. $sCancelUrl = "./UI.php?operation=search&filter=".urlencode($sFilter)."&".$oAppContext->GetForLink();
  556. $aContext = array('filter' => $sFilter);
  557. cmdbAbstractObject::DisplayBulkModifyForm($oP, $sClass, $aSelectedObj, 'preview_or_modify_all', $sCancelUrl, array(), $aContext);
  558. break;
  559. ///////////////////////////////////////////////////////////////////////////////////////////
  560. case 'preview_or_modify_all': // Preview or apply bulk modify
  561. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  562. // TO DO: limit the search filter by the user context
  563. $oFilter = DBObjectSearch::unserialize($sFilter); // TO DO : check that the filter is valid
  564. $oChecker = new ActionChecker($oFilter, UR_ACTION_BULK_MODIFY);
  565. $sClass = utils::ReadParam('class', '', false, 'class');
  566. $bPreview = utils::ReadParam('preview_mode', '');
  567. $sSelectedObj = utils::ReadParam('selectObj', '', false, 'raw_data');
  568. if ( empty($sClass) || empty($sSelectedObj)) // TO DO: check that the class name is valid !
  569. {
  570. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'selectObj'));
  571. }
  572. $aSelectedObj = explode(',', $sSelectedObj);
  573. $sCancelUrl = "./UI.php?operation=search&filter=".urlencode($sFilter)."&".$oAppContext->GetForLink();
  574. $aContext = array(
  575. 'filter' => $sFilter,
  576. 'selectObj' => $sSelectedObj,
  577. );
  578. cmdbAbstractObject::DoBulkModify($oP, $sClass, $aSelectedObj, 'preview_or_modify_all', $bPreview, $sCancelUrl, $aContext);
  579. break;
  580. ///////////////////////////////////////////////////////////////////////////////////////////
  581. case 'new': // Form to create a new object
  582. $sClass = utils::ReadParam('class', '', false, 'class');
  583. $sStateCode = utils::ReadParam('state', '');
  584. $bCheckSubClass = utils::ReadParam('checkSubclass', true);
  585. if ( empty($sClass) )
  586. {
  587. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'class'));
  588. }
  589. $aArgs = utils::ReadParam('default', array(), false, 'raw_data');
  590. $aContext = $oAppContext->GetAsHash();
  591. foreach( $oAppContext->GetNames() as $key)
  592. {
  593. $aArgs[$key] = $oAppContext->GetCurrentValue($key);
  594. }
  595. // If the specified class has subclasses, ask the user an instance of which class to create
  596. $aSubClasses = MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL); // Including the specified class itself
  597. $aPossibleClasses = array();
  598. $sRealClass = '';
  599. if ($bCheckSubClass)
  600. {
  601. foreach($aSubClasses as $sCandidateClass)
  602. {
  603. if (!MetaModel::IsAbstract($sCandidateClass) && (UserRights::IsActionAllowed($sCandidateClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES))
  604. {
  605. $aPossibleClasses[$sCandidateClass] = MetaModel::GetName($sCandidateClass);
  606. }
  607. }
  608. // Only one of the subclasses can be instantiated...
  609. if (count($aPossibleClasses) == 1)
  610. {
  611. $aKeys = array_keys($aPossibleClasses);
  612. $sRealClass = $aKeys[0];
  613. }
  614. }
  615. else
  616. {
  617. $sRealClass = $sClass;
  618. }
  619. if (!empty($sRealClass))
  620. {
  621. // Display the creation form
  622. $sClassLabel = MetaModel::GetName($sRealClass);
  623. // Note: some code has been duplicated to the case 'apply_new' when a data integrity issue has been found
  624. $oP->set_title(Dict::Format('UI:CreationPageTitle_Class', $sClassLabel));
  625. $oP->add("<h1>".MetaModel::GetClassIcon($sRealClass)."&nbsp;".Dict::Format('UI:CreationTitle_Class', $sClassLabel)."</h1>\n");
  626. $oP->add("<div class=\"wizContainer\">\n");
  627. // Set all the default values in an object and clone this "default" object
  628. $oObjToClone = MetaModel::NewObject($sRealClass);
  629. // 1st - set context values
  630. $oAppContext->InitObjectFromContext($oObjToClone);
  631. // 2nd - set values from the page argument 'default'
  632. $oObjToClone->UpdateObjectFromArg('default');
  633. cmdbAbstractObject::DisplayCreationForm($oP, $sRealClass, $oObjToClone, array());
  634. $oP->add("</div>\n");
  635. }
  636. else
  637. {
  638. // Select the derived class to create
  639. $sClassLabel = MetaModel::GetName($sClass);
  640. $oP->add("<h1>".MetaModel::GetClassIcon($sClass)."&nbsp;".Dict::Format('UI:CreationTitle_Class', $sClassLabel)."</h1>\n");
  641. $oP->add("<div class=\"wizContainer\">\n");
  642. $oP->add('<form>');
  643. $oP->add('<p>'.Dict::Format('UI:SelectTheTypeOf_Class_ToCreate', $sClassLabel));
  644. $aDefaults = utils::ReadParam('default', array(), false, 'raw_data');
  645. $oP->add($oAppContext->GetForForm());
  646. $oP->add("<input type=\"hidden\" name=\"checkSubclass\" value=\"0\">\n");
  647. $oP->add("<input type=\"hidden\" name=\"state\" value=\"$sStateCode\">\n");
  648. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"new\">\n");
  649. foreach($aDefaults as $key => $value)
  650. {
  651. if (is_array($value))
  652. {
  653. foreach($value as $key2 => $value2)
  654. {
  655. if (is_array($value2))
  656. {
  657. foreach($value2 as $key3 => $value3)
  658. {
  659. $oP->add("<input type=\"hidden\" name=\"default[$key][$key2][$key3]\" value=\"$value3\">\n");
  660. }
  661. }
  662. else
  663. {
  664. $oP->add("<input type=\"hidden\" name=\"default[$key][$key2]\" value=\"$value2\">\n");
  665. }
  666. }
  667. }
  668. else
  669. {
  670. $oP->add("<input type=\"hidden\" name=\"default[$key]\" value=\"$value\">\n");
  671. }
  672. }
  673. $oP->add('<select name="class">');
  674. asort($aPossibleClasses);
  675. foreach($aPossibleClasses as $sClassName => $sClassLabel)
  676. {
  677. $sSelected = ($sClassName == $sClass) ? 'selected' : '';
  678. $oP->add("<option $sSelected value=\"$sClassName\">$sClassLabel</option>");
  679. }
  680. $oP->add('</select>');
  681. $oP->add("&nbsp; <input type=\"submit\" value=\"".Dict::S('UI:Button:Apply')."\"></p>");
  682. $oP->add('</form>');
  683. $oP->add("</div>\n");
  684. }
  685. break;
  686. ///////////////////////////////////////////////////////////////////////////////////////////
  687. case 'apply_modify': // Applying the modifications to an existing object
  688. $sClass = utils::ReadPostedParam('class', '');
  689. $sClassLabel = MetaModel::GetName($sClass);
  690. $id = utils::ReadPostedParam('id', '');
  691. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  692. if ( empty($sClass) || empty($id)) // TO DO: check that the class name is valid !
  693. {
  694. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'id'));
  695. }
  696. $bDisplayDetails = true;
  697. $oObj = MetaModel::GetObject($sClass, $id, false);
  698. if ($oObj == null)
  699. {
  700. $bDisplayDetails = false;
  701. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  702. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  703. }
  704. elseif (!utils::IsTransactionValid($sTransactionId, false))
  705. {
  706. $oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetRawName(), $sClassLabel)); // Set title will take care of the encoding
  707. $oP->p("<strong>".Dict::S('UI:Error:ObjectAlreadyUpdated')."</strong>\n");
  708. }
  709. else
  710. {
  711. $oObj->UpdateObjectFromPostedForm();
  712. $sMessage = '';
  713. $sSeverity = 'ok';
  714. if (!$oObj->IsModified())
  715. {
  716. $oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetRawName(), $sClassLabel)); // Set title will take care of the encoding
  717. $sMessage = Dict::Format('UI:Class_Object_NotUpdated', MetaModel::GetName(get_class($oObj)), $oObj->GetName());
  718. $sSeverity = 'info';
  719. }
  720. else
  721. {
  722. list($bRes, $aIssues) = $oObj->CheckToWrite();
  723. if ($bRes)
  724. {
  725. $oObj->DBUpdate();
  726. utils::RemoveTransaction($sTransactionId);
  727. $sMessage = Dict::Format('UI:Class_Object_Updated', MetaModel::GetName(get_class($oObj)), $oObj->GetName());
  728. $sSeverity = 'ok';
  729. }
  730. else
  731. {
  732. $bDisplayDetails = false;
  733. // Found issues, explain and give the user a second chance
  734. //
  735. $oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetRawName(), $sClassLabel)); // Set title will take care of the encoding
  736. $oP->add("<div class=\"page_header\">\n");
  737. $oP->add("<h1>".$oObj->GetIcon()."&nbsp;".Dict::Format('UI:ModificationTitle_Class_Object', $sClassLabel, $oObj->GetName())."</h1>\n");
  738. $oP->add("</div>\n");
  739. $oP->add("<div class=\"wizContainer\">\n");
  740. $oObj->DisplayModifyForm($oP);
  741. $oP->add("</div>\n");
  742. $sIssueDesc = Dict::Format('UI:ObjectCouldNotBeWritten', implode(', ', $aIssues));
  743. $oP->add_ready_script("alert('".addslashes($sIssueDesc)."');");
  744. }
  745. }
  746. }
  747. if ($bDisplayDetails)
  748. {
  749. $oObj = MetaModel::GetObject(get_class($oObj), $oObj->GetKey()); //Workaround: reload the object so that the linkedset are displayed properly
  750. $sNextAction = utils::ReadPostedParam('next_action', '');
  751. if (!empty($sNextAction))
  752. {
  753. ApplyNextAction($oP, $oObj, $sNextAction);
  754. }
  755. else
  756. {
  757. // Nothing more to do
  758. ReloadAndDisplay($oP, $oObj, 'update', $sMessage, $sSeverity);
  759. }
  760. }
  761. break;
  762. ///////////////////////////////////////////////////////////////////////////////////////////
  763. case 'select_for_deletion': // Select multiple objects for deletion
  764. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  765. if (empty($sFilter))
  766. {
  767. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'filter'));
  768. }
  769. $oP->set_title(Dict::S('UI:BulkDeletePageTitle'));
  770. $oP->add("<h1>".Dict::S('UI:BulkDeleteTitle')."</h1>\n");
  771. // TO DO: limit the search filter by the user context
  772. $oFilter = CMDBSearchFilter::unserialize($sFilter); // TO DO : check that the filter is valid
  773. $oChecker = new ActionChecker($oFilter, UR_ACTION_BULK_DELETE);
  774. DisplayMultipleSelectionForm($oP, $oFilter, 'bulk_delete', $oChecker);
  775. break;
  776. ///////////////////////////////////////////////////////////////////////////////////////////
  777. case 'bulk_delete_confirmed': // Confirm bulk deletion of objects
  778. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  779. if (!utils::IsTransactionValid($sTransactionId))
  780. {
  781. throw new ApplicationException(Dict::S('UI:Error:ObjectsAlreadyDeleted'));
  782. }
  783. // Fall through
  784. ///////////////////////////////////////////////////////////////////////////////////////////
  785. case 'delete':
  786. case 'bulk_delete': // Actual bulk deletion (if confirmed)
  787. $sClass = utils::ReadParam('class', '', false, 'class');
  788. $sClassLabel = MetaModel::GetName($sClass);
  789. $aObjects = array();
  790. if ($operation == 'delete')
  791. {
  792. // Single object
  793. $id = utils::ReadParam('id', '');
  794. $oObj = MetaModel::GetObject($sClass, $id);
  795. $aObjects[] = $oObj;
  796. if (!UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, DBObjectSet::FromObject($oObj)))
  797. {
  798. throw new SecurityException(Dict::Format('UI:Error:DeleteNotAllowedOn_Class', $sClassLabel));
  799. }
  800. }
  801. else
  802. {
  803. // Several objects
  804. $sFilter = utils::ReadPostedParam('filter', '');
  805. $oFullSetFilter = DBObjectSearch::unserialize($sFilter);
  806. $aSelectObject = utils::ReadMultipleSelection($oFullSetFilter);
  807. if ( empty($sClass) || empty($aSelectObject)) // TO DO: check that the class name is valid !
  808. {
  809. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'selectObject[]'));
  810. }
  811. foreach($aSelectObject as $iId)
  812. {
  813. $aObjects[] = MetaModel::GetObject($sClass, $iId);
  814. }
  815. if (count($aObjects) == 1)
  816. {
  817. if (!UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, DBObjectSet::FromArray($sClass, $aObjects)))
  818. {
  819. throw new SecurityException(Dict::Format('UI:Error:BulkDeleteNotAllowedOn_Class', $sClassLabel));
  820. }
  821. }
  822. else
  823. {
  824. if (!UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_DELETE, DBObjectSet::FromArray($sClass, $aObjects)))
  825. {
  826. throw new SecurityException(Dict::Format('UI:Error:BulkDeleteNotAllowedOn_Class', $sClassLabel));
  827. }
  828. $oP->set_title(Dict::S('UI:BulkDeletePageTitle'));
  829. }
  830. }
  831. // Go for the common part... (delete single, delete bulk, delete confirmed)
  832. cmdbAbstractObject::DeleteObjects($oP, $sClass, $aObjects, ($operation != 'bulk_delete_confirmed'), 'bulk_delete_confirmed');
  833. break;
  834. ///////////////////////////////////////////////////////////////////////////////////////////
  835. case 'apply_new': // Creation of a new object
  836. $sClass = utils::ReadPostedParam('class', '', 'class');
  837. $sClassLabel = MetaModel::GetName($sClass);
  838. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  839. if ( empty($sClass) ) // TO DO: check that the class name is valid !
  840. {
  841. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'class'));
  842. }
  843. if (!utils::IsTransactionValid($sTransactionId, false))
  844. {
  845. $oP->p("<strong>".Dict::S('UI:Error:ObjectAlreadyCreated')."</strong>\n");
  846. }
  847. else
  848. {
  849. $oObj = MetaModel::NewObject($sClass);
  850. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  851. if (!empty($sStateAttCode))
  852. {
  853. $sTargetState = utils::ReadPostedParam('obj_state', '');
  854. if ($sTargetState != '')
  855. {
  856. $oObj->Set($sStateAttCode, $sTargetState);
  857. }
  858. }
  859. $oObj->UpdateObjectFromPostedForm();
  860. }
  861. if (isset($oObj) && is_object($oObj))
  862. {
  863. $sClass = get_class($oObj);
  864. $sClassLabel = MetaModel::GetName($sClass);
  865. list($bRes, $aIssues) = $oObj->CheckToWrite();
  866. if ($bRes)
  867. {
  868. $oObj->DBInsert();
  869. utils::RemoveTransaction($sTransactionId);
  870. $oP->set_title(Dict::S('UI:PageTitle:ObjectCreated'));
  871. $sMessage = Dict::Format('UI:Title:Object_Of_Class_Created', $oObj->GetName(), $sClassLabel);
  872. $oObj = MetaModel::GetObject(get_class($oObj), $oObj->GetKey()); //Workaround: reload the object so that the linkedset are displayed properly
  873. $sNextAction = utils::ReadPostedParam('next_action', '');
  874. if (!empty($sNextAction))
  875. {
  876. $oP->add("<h1>$sMessage</h1>");
  877. ApplyNextAction($oP, $oObj, $sNextAction);
  878. }
  879. else
  880. {
  881. // Nothing more to do
  882. ReloadAndDisplay($oP, $oObj, 'create', $sMessage, 'ok');
  883. }
  884. }
  885. else
  886. {
  887. // Found issues, explain and give the user a second chance
  888. //
  889. $oP->set_title(Dict::Format('UI:CreationPageTitle_Class', $sClassLabel));
  890. $oP->add("<h1>".MetaModel::GetClassIcon($sClass)."&nbsp;".Dict::Format('UI:CreationTitle_Class', $sClassLabel)."</h1>\n");
  891. $oP->add("<div class=\"wizContainer\">\n");
  892. cmdbAbstractObject::DisplayCreationForm($oP, $sClass, $oObj);
  893. $oP->add("</div>\n");
  894. $sIssueDesc = Dict::Format('UI:ObjectCouldNotBeWritten', implode(', ', $aIssues));
  895. $oP->add_ready_script("alert('".addslashes($sIssueDesc)."');");
  896. }
  897. }
  898. break;
  899. ///////////////////////////////////////////////////////////////////////////////////////////
  900. case 'select_bulk_stimulus': // Form displayed when applying a stimulus to many objects
  901. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  902. $sStimulus = utils::ReadParam('stimulus', '');
  903. $sState = utils::ReadParam('state', '');
  904. if (empty($sFilter) || empty($sStimulus) || empty($sState))
  905. {
  906. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state'));
  907. }
  908. $oFilter = DBObjectSearch::unserialize($sFilter);
  909. $sClass = $oFilter->GetClass();
  910. $aStimuli = MetaModel::EnumStimuli($sClass);
  911. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  912. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  913. $oP->set_title($sActionLabel);
  914. $oP->add('<div class="page_header">');
  915. $oP->add('<h1>'.MetaModel::GetClassIcon($sClass).'&nbsp;'.$sActionLabel.'</h1>');
  916. $oP->add('</div>');
  917. $oChecker = new StimulusChecker($oFilter, $sState, $sStimulus);
  918. $aExtraFormParams = array('stimulus' => $sStimulus, 'state' => $sState);
  919. DisplayMultipleSelectionForm($oP, $oFilter, 'bulk_stimulus', $oChecker, $aExtraFormParams);
  920. break;
  921. case 'bulk_stimulus':
  922. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  923. $sStimulus = utils::ReadParam('stimulus', '');
  924. $sState = utils::ReadParam('state', '');
  925. if (empty($sFilter) || empty($sStimulus) || empty($sState))
  926. {
  927. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state'));
  928. }
  929. $oFilter = DBObjectSearch::unserialize($sFilter);
  930. $sClass = $oFilter->GetClass();
  931. $aSelectObject = utils::ReadMultipleSelection($oFilter);
  932. if (count($aSelectObject) == 0)
  933. {
  934. // Nothing to do, no object was selected !
  935. throw new ApplicationException(Dict::S('UI:BulkAction:NoObjectSelected'));
  936. }
  937. else
  938. {
  939. $aTransitions = MetaModel::EnumTransitions($sClass, $sState);
  940. $aStimuli = MetaModel::EnumStimuli($sClass);
  941. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  942. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  943. $aTransition = $aTransitions[$sStimulus];
  944. $sTargetState = $aTransition['target_state'];
  945. $aStates = MetaModel::EnumStates($sClass);
  946. $aTargetStateDef = $aStates[$sTargetState];
  947. $oP->set_title(Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aSelectObject), $sClass));
  948. $oP->add('<div class="page_header">');
  949. $oP->add('<h1>'.MetaModel::GetClassIcon($sClass).'&nbsp;'.Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aSelectObject), $sClass).'</h1>');
  950. $oP->add('</div>');
  951. $aExpectedAttributes = $aTargetStateDef['attribute_list'];
  952. $aDetails = array();
  953. $iFieldIndex = 0;
  954. $aFieldsMap = array();
  955. $aValues = array();
  956. $aObjects = array();
  957. foreach($aSelectObject as $iId)
  958. {
  959. $aObjects[] = MetaModel::GetObject($sClass, $iId);
  960. }
  961. $oSet = DBObjectSet::FromArray($sClass, $aObjects);
  962. $oObj = $oSet->ComputeCommonObject($aValues);
  963. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  964. $oObj->Set($sStateAttCode,$sTargetState);
  965. $sReadyScript = '';
  966. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  967. {
  968. // Prompt for an attribute if
  969. // - the attribute must be changed or must be displayed to the user for confirmation
  970. // - or the field is mandatory and currently empty
  971. if ( ($iExpectCode & (OPT_ATT_MUSTCHANGE | OPT_ATT_MUSTPROMPT)) ||
  972. (($iExpectCode & OPT_ATT_MANDATORY) && ($oObj->Get($sAttCode) == '')) )
  973. {
  974. $aAttributesDef = MetaModel::ListAttributeDefs($sClass);
  975. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  976. $aPrerequisites = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  977. if (count($aPrerequisites) > 0)
  978. {
  979. // When 'enabling' a field, all its prerequisites must be enabled too
  980. $sFieldList = "['".implode("','", $aPrerequisites)."']";
  981. $oP->add_ready_script("$('#enable_{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, true); } );\n");
  982. }
  983. $aDependents = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  984. if (count($aDependents) > 0)
  985. {
  986. // When 'disabling' a field, all its dependent fields must be disabled too
  987. $sFieldList = "['".implode("','", $aDependents)."']";
  988. $oP->add_ready_script("$('#enable_{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, false); } );\n");
  989. }
  990. $aArgs = array('this' => $oObj);
  991. $sHTMLValue = cmdbAbstractObject::GetFormElementForField($oP, $sClass, $sAttCode, $oAttDef, $oObj->Get($sAttCode), $oObj->GetEditValue($sAttCode), $sAttCode, '', $iExpectCode, $aArgs);
  992. $sComments = '<input type="checkbox" checked id="enable_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$sAttCode.'\')"/>';
  993. if (!isset($aValues[$sAttCode]))
  994. {
  995. $aValues[$sAttCode] = array();
  996. }
  997. if (count($aValues[$sAttCode]) == 1)
  998. {
  999. $sComments .= '<div class="mono_value">1</div>';
  1000. }
  1001. else
  1002. {
  1003. // Non-homogenous value
  1004. $iMaxCount = 5;
  1005. $sTip = "<p><b>".Dict::Format('UI:BulkModify_Count_DistinctValues', count($aValues[$sAttCode]))."</b><ul>";
  1006. $index = 0;
  1007. foreach($aValues[$sAttCode] as $sCurrValue => $aVal)
  1008. {
  1009. $sDisplayValue = empty($aVal['display']) ? '<i>'.Dict::S('Enum:Undefined').'</i>' : str_replace(array("\n", "\r"), " ", $aVal['display']);
  1010. $sTip .= "<li>".Dict::Format('UI:BulkModify:Value_Exists_N_Times', $sDisplayValue, $aVal['count'])."</li>";
  1011. $index++;
  1012. if ($iMaxCount == $index)
  1013. {
  1014. $sTip .= "<li>".Dict::Format('UI:BulkModify:N_MoreValues', count($aValues[$sAttCode]) - $iMaxCount)."</li>";
  1015. break;
  1016. }
  1017. }
  1018. $sTip .= "</ul></p>";
  1019. $sTip = addslashes($sTip);
  1020. $sReadyScript .= "$('#multi_values_$sAttCode').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );\n";
  1021. $sComments .= '<div class="multi_values" id="multi_values_'.$sAttCode.'">'.count($aValues[$sAttCode]).'</div>';
  1022. }
  1023. $aDetails[] = array('label' => '<span>'.$oAttDef->GetLabel().'</span>', 'value' => "<span id=\"field_$sAttCode\">$sHTMLValue</span>", 'comments' => $sComments);
  1024. $aFieldsMap[$sAttCode] = $sAttCode;
  1025. $iFieldIndex++;
  1026. }
  1027. }
  1028. $sButtonsPosition = MetaModel::GetConfig()->Get('buttons_position');
  1029. if ($sButtonsPosition == 'bottom')
  1030. {
  1031. // bottom: Displays the ticket details BEFORE the actions
  1032. $oP->add('<div class="ui-widget-content">');
  1033. $oObj->DisplayBareProperties($oP);
  1034. $oP->add('</div>');
  1035. }
  1036. $oP->add("<div class=\"wizContainer\">\n");
  1037. $oP->add("<form id=\"apply_stimulus\" method=\"post\" onSubmit=\"return OnSubmit('apply_stimulus');\">\n");
  1038. $oP->add("<table><tr><td>\n");
  1039. $oP->details($aDetails);
  1040. $oP->add("</td></tr></table>\n");
  1041. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  1042. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"bulk_apply_stimulus\">\n");
  1043. $oP->add("<input type=\"hidden\" name=\"preview_mode\" value=\"1\">\n");
  1044. $oP->add("<input type=\"hidden\" name=\"filter\" value=\"$sFilter\">\n");
  1045. $oP->add("<input type=\"hidden\" name=\"stimulus\" value=\"$sStimulus\">\n");
  1046. $oP->add("<input type=\"hidden\" name=\"state\" value=\"$sState\">\n");
  1047. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  1048. $oP->add($oAppContext->GetForForm());
  1049. $oP->add("<input type=\"hidden\" name=\"selectObject\" value=\"".implode(',',$aSelectObject)."\">\n");
  1050. $sURL = "./UI.php?operation=search&filter=".urlencode($sFilter)."&".$oAppContext->GetForLink();
  1051. $oP->add("<input type=\"button\" value=\"".Dict::S('UI:Button:Cancel')."\" onClick=\"window.location.href='$sURL'\">&nbsp;&nbsp;&nbsp;&nbsp;\n");
  1052. $oP->add("<button type=\"submit\" class=\"action\"><span>$sActionLabel</span></button>\n");
  1053. $oP->add("</form>\n");
  1054. $oP->add("</div>\n");
  1055. if ($sButtonsPosition != 'bottom')
  1056. {
  1057. // top or both: Displays the ticket details AFTER the actions
  1058. $oP->add('<div class="ui-widget-content">');
  1059. $oObj->DisplayBareProperties($oP);
  1060. $oP->add('</div>');
  1061. }
  1062. $iFieldsCount = count($aFieldsMap);
  1063. $sJsonFieldsMap = json_encode($aFieldsMap);
  1064. $oP->add_script(
  1065. <<<EOF
  1066. // Initializes the object once at the beginning of the page...
  1067. var oWizardHelper = new WizardHelper('$sClass', '', '$sTargetState');
  1068. oWizardHelper.SetFieldsMap($sJsonFieldsMap);
  1069. oWizardHelper.SetFieldsCount($iFieldsCount);
  1070. EOF
  1071. );
  1072. $oP->add_ready_script(
  1073. <<<EOF
  1074. // Starts the validation when the page is ready
  1075. CheckFields('apply_stimulus', false);
  1076. $sReadyScript
  1077. EOF
  1078. );
  1079. }
  1080. break;
  1081. case 'bulk_apply_stimulus':
  1082. $bPreviewMode = utils::ReadPostedParam('preview_mode', false);
  1083. $sFilter = utils::ReadPostedParam('filter', '', false, 'raw_data');
  1084. $sStimulus = utils::ReadPostedParam('stimulus', '');
  1085. $sState = utils::ReadPostedParam('state', '');
  1086. $sSelectObject = utils::ReadPostedParam('selectObject', '', false, 'raw_data');
  1087. $aSelectObject = explode(',', $sSelectObject);
  1088. if (empty($sFilter) || empty($sStimulus) || empty($sState))
  1089. {
  1090. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state'));
  1091. }
  1092. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1093. if (!utils::IsTransactionValid($sTransactionId))
  1094. {
  1095. $oP->p(Dict::S('UI:Error:ObjectAlreadyUpdated'));
  1096. }
  1097. else
  1098. {
  1099. // For archiving the modification
  1100. $oFilter = DBObjectSearch::unserialize($sFilter);
  1101. $sClass = $oFilter->GetClass();
  1102. $aObjects = array();
  1103. foreach($aSelectObject as $iId)
  1104. {
  1105. $aObjects[] = MetaModel::GetObject($sClass, $iId);
  1106. }
  1107. $aTransitions = MetaModel::EnumTransitions($sClass, $sState);
  1108. $aStimuli = MetaModel::EnumStimuli($sClass);
  1109. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1110. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1111. $oP->set_title(Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aObjects), $sClass));
  1112. $oP->add('<div class="page_header">');
  1113. $oP->add('<h1>'.MetaModel::GetClassIcon($sClass).'&nbsp;'.Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aObjects), $sClass).'</h1>');
  1114. $oP->add('</div>');
  1115. $oSet = DBObjectSet::FromArray($sClass, $aObjects);
  1116. // For reporting
  1117. $aHeaders = array(
  1118. 'object' => array('label' => MetaModel::GetName($sClass), 'description' => Dict::S('UI:ModifiedObject')),
  1119. 'status' => array('label' => Dict::S('UI:BulkModifyStatus'), 'description' => Dict::S('UI:BulkModifyStatus+')),
  1120. 'errors' => array('label' => Dict::S('UI:BulkModifyErrors'), 'description' => Dict::S('UI:BulkModifyErrors+')),
  1121. );
  1122. $aRows = array();
  1123. while ($oObj = $oSet->Fetch())
  1124. {
  1125. $sError = Dict::S('UI:BulkModifyStatusOk');
  1126. try
  1127. {
  1128. $aTransitions = $oObj->EnumTransitions();
  1129. $aStimuli = MetaModel::EnumStimuli($sClass);
  1130. if (!isset($aTransitions[$sStimulus]))
  1131. {
  1132. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
  1133. }
  1134. else
  1135. {
  1136. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1137. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1138. $aTransition = $aTransitions[$sStimulus];
  1139. $sTargetState = $aTransition['target_state'];
  1140. $aTargetStates = MetaModel::EnumStates($sClass);
  1141. $aTargetState = $aTargetStates[$sTargetState];
  1142. $aExpectedAttributes = $aTargetState['attribute_list'];
  1143. $aDetails = array();
  1144. $aErrors = array();
  1145. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  1146. {
  1147. $iFlags = $oObj->GetAttributeFlags($sAttCode);
  1148. if (($iExpectCode & (OPT_ATT_MUSTCHANGE|OPT_ATT_MUSTPROMPT)) || ($oObj->Get($sAttCode) == '') )
  1149. {
  1150. $paramValue = utils::ReadPostedParam("attr_$sAttCode", '', 'raw_data');
  1151. if ( ($iFlags & OPT_ATT_SLAVE) && ($paramValue != $oObj->Get($sAttCode)) )
  1152. {
  1153. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1154. $aErrors[] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $oAttDef->GetLabel());
  1155. unset($aExpectedAttributes[$sAttCode]);
  1156. }
  1157. }
  1158. }
  1159. $oObj->UpdateObjectFromPostedForm('', array_keys($aExpectedAttributes), $sTargetState);
  1160. if (count($aErrors) == 0)
  1161. {
  1162. if ($oObj->ApplyStimulus($sStimulus))
  1163. {
  1164. list($bResult, $aErrors) = $oObj->CheckToWrite();
  1165. $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusModified') : Dict::S('UI:BulkModifyStatusSkipped');
  1166. if ($bResult)
  1167. {
  1168. $oObj->DBUpdate();
  1169. }
  1170. else
  1171. {
  1172. $sError = '<p>'.implode('</p></p>',$aErrors)."</p>\n";
  1173. }
  1174. }
  1175. else
  1176. {
  1177. $sStatus = Dict::S('UI:BulkModifyStatusSkipped');
  1178. $sError = '<p>'.Dict::S('UI:FailedToApplyStimuli')."<p>\n";
  1179. }
  1180. }
  1181. else
  1182. {
  1183. $sStatus = Dict::S('UI:BulkModifyStatusSkipped');
  1184. $sError = '<p>'.implode('</p></p>',$aErrors)."</p>\n";
  1185. }
  1186. }
  1187. }
  1188. catch(Exception $e)
  1189. {
  1190. $sError = $e->getMessage();
  1191. $sStatus = Dict::S('UI:BulkModifyStatusSkipped');
  1192. }
  1193. $aRows[] = array(
  1194. 'object' => $oObj->GetHyperlink(),
  1195. 'status' => $sStatus,
  1196. 'errors' => $sError,
  1197. );
  1198. }
  1199. $oP->Table($aHeaders, $aRows);
  1200. // Back to the list
  1201. $sURL = "./UI.php?operation=search&filter=".urlencode($sFilter)."&".$oAppContext->GetForLink();
  1202. $oP->add('<input type="button" onClick="window.location.href=\''.$sURL.'\'" value="'.Dict::S('UI:Button:Done').'">');
  1203. }
  1204. break;
  1205. case 'stimulus': // Form displayed when applying a stimulus (state change)
  1206. $sClass = utils::ReadParam('class', '', false, 'class');
  1207. $id = utils::ReadParam('id', '');
  1208. $sStimulus = utils::ReadParam('stimulus', '');
  1209. if ( empty($sClass) || empty($id) || empty($sStimulus) ) // TO DO: check that the class name is valid !
  1210. {
  1211. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'class', 'id', 'stimulus'));
  1212. }
  1213. $oObj = MetaModel::GetObject($sClass, $id, false);
  1214. if ($oObj != null)
  1215. {
  1216. $oObj->DisplayStimulusForm($oP, $sStimulus);
  1217. }
  1218. else
  1219. {
  1220. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  1221. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  1222. }
  1223. break;
  1224. ///////////////////////////////////////////////////////////////////////////////////////////
  1225. case 'apply_stimulus': // Actual state change
  1226. $sClass = utils::ReadPostedParam('class', '');
  1227. $id = utils::ReadPostedParam('id', '');
  1228. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1229. $sStimulus = utils::ReadPostedParam('stimulus', '');
  1230. if ( empty($sClass) || empty($id) || empty($sStimulus) ) // TO DO: check that the class name is valid !
  1231. {
  1232. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'class', 'id', 'stimulus'));
  1233. }
  1234. $oObj = MetaModel::GetObject($sClass, $id, false);
  1235. if ($oObj != null)
  1236. {
  1237. $aTransitions = $oObj->EnumTransitions();
  1238. $aStimuli = MetaModel::EnumStimuli($sClass);
  1239. $sMessage = '';
  1240. $sSeverity = 'ok';
  1241. $bDisplayDetails = true;
  1242. if (!isset($aTransitions[$sStimulus]))
  1243. {
  1244. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
  1245. }
  1246. if (!utils::IsTransactionValid($sTransactionId))
  1247. {
  1248. $sMessage = Dict::S('UI:Error:ObjectAlreadyUpdated');
  1249. $sSeverity = 'info';
  1250. }
  1251. else
  1252. {
  1253. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1254. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1255. $aTransition = $aTransitions[$sStimulus];
  1256. $sTargetState = $aTransition['target_state'];
  1257. $aTargetStates = MetaModel::EnumStates($sClass);
  1258. $aTargetState = $aTargetStates[$sTargetState];
  1259. $aExpectedAttributes = $aTargetState['attribute_list'];
  1260. $aDetails = array();
  1261. $aErrors = array();
  1262. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  1263. {
  1264. $iFlags = $oObj->GetAttributeFlags($sAttCode);
  1265. if (($iExpectCode & (OPT_ATT_MUSTCHANGE|OPT_ATT_MUSTPROMPT)) || ($oObj->Get($sAttCode) == '') )
  1266. {
  1267. $paramValue = utils::ReadPostedParam("attr_$sAttCode", '', 'raw_data');
  1268. if ( ($iFlags & OPT_ATT_SLAVE) && ($paramValue != $oObj->Get($sAttCode)))
  1269. {
  1270. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1271. $aErrors[] = Dict::Format('UI:AttemptingToChangeASlaveAttribute_Name', $oAttDef->GetLabel());
  1272. unset($aExpectedAttributes[$sAttCode]);
  1273. }
  1274. }
  1275. }
  1276. $oObj->UpdateObjectFromPostedForm('', array_keys($aExpectedAttributes), $sTargetState);
  1277. if (count($aErrors) == 0)
  1278. {
  1279. $sIssues = '';
  1280. $bApplyStimulus = true;
  1281. list($bRes, $aIssues) = $oObj->CheckToWrite(); // Check before trying to write the object
  1282. if ($bRes)
  1283. {
  1284. try
  1285. {
  1286. $bApplyStimulus = $oObj->ApplyStimulus($sStimulus); // will write the object in the DB
  1287. }
  1288. catch(CoreException $e)
  1289. {
  1290. // Rollback to the previous state... by reloading the object from the database and applying the modifications again
  1291. $oObj = MetaModel::GetObject(get_class($oObj), $oObj->GetKey());
  1292. $oObj->UpdateObjectFromPostedForm('', array_keys($aExpectedAttributes), $sTargetState);
  1293. $sIssues = $e->getMessage();
  1294. }
  1295. }
  1296. else
  1297. {
  1298. $sIssues = implode(' ', $aIssues);
  1299. }
  1300. if (!$bApplyStimulus)
  1301. {
  1302. $sMessage = Dict::S('UI:FailedToApplyStimuli');
  1303. $sSeverity = 'error';
  1304. }
  1305. else if ($sIssues != '')
  1306. {
  1307. $bDisplayDetails = false;
  1308. // Found issues, explain and give the user a second chance
  1309. //
  1310. $oObj->DisplayStimulusForm($oP, $sStimulus);
  1311. $sIssueDesc = Dict::Format('UI:ObjectCouldNotBeWritten',$sIssues);
  1312. $oP->add_ready_script("alert('".addslashes($sIssueDesc)."');");
  1313. }
  1314. else
  1315. {
  1316. $sMessage = Dict::Format('UI:Class_Object_Updated', MetaModel::GetName(get_class($oObj)), $oObj->GetName());
  1317. $sSeverity = 'ok';
  1318. utils::RemoveTransaction($sTransactionId);
  1319. }
  1320. }
  1321. else
  1322. {
  1323. $sMessage = implode('</p><p>', $aErrors);
  1324. $sSeverity = 'error';
  1325. }
  1326. }
  1327. if ($bDisplayDetails)
  1328. {
  1329. ReloadAndDisplay($oP, $oObj, 'apply_stimulus', $sMessage, $sSeverity);
  1330. }
  1331. }
  1332. else
  1333. {
  1334. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  1335. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  1336. }
  1337. break;
  1338. ///////////////////////////////////////////////////////////////////////////////////////////
  1339. case 'swf_navigator': // Graphical display of the relations "impact" / "depends on"
  1340. require_once(APPROOT.'core/simplegraph.class.inc.php');
  1341. require_once(APPROOT.'core/relationgraph.class.inc.php');
  1342. require_once(APPROOT.'core/displayablegraph.class.inc.php');
  1343. $sClass = utils::ReadParam('class', '', false, 'class');
  1344. $id = utils::ReadParam('id', 0);
  1345. $sRelation = utils::ReadParam('relation', 'impact');
  1346. $sDirection = utils::ReadParam('direction', 'down');
  1347. $iGroupingThreshold = utils::ReadParam('g', 5);
  1348. $oObj = MetaModel::GetObject($sClass, $id);
  1349. $iMaxRecursionDepth = MetaModel::GetConfig()->Get('relations_max_depth', 20);
  1350. $aSourceObjects = array($oObj);
  1351. if ($sRelation == 'depends on')
  1352. {
  1353. $sRelation = 'impacts';
  1354. $sDirection = 'up';
  1355. }
  1356. if ($sDirection == 'up')
  1357. {
  1358. $oRelGraph = MetaModel::GetRelatedObjectsUp($sRelation, $aSourceObjects, $iMaxRecursionDepth);
  1359. }
  1360. else
  1361. {
  1362. $oRelGraph = MetaModel::GetRelatedObjectsDown($sRelation, $aSourceObjects, $iMaxRecursionDepth);
  1363. }
  1364. $aResults = $oRelGraph->GetObjectsByClass();
  1365. $oDisplayGraph = DisplayableGraph::FromRelationGraph($oRelGraph, $iGroupingThreshold, ($sDirection == 'down'));
  1366. $aGroups = array();
  1367. $iGroupIdx = 0;
  1368. $oIterator = new RelationTypeIterator($oDisplayGraph, 'Node');
  1369. foreach($oIterator as $oNode)
  1370. {
  1371. if ($oNode instanceof DisplayableGroupNode)
  1372. {
  1373. $aGroups[] = $oNode->GetObjects();
  1374. $oNode->SetProperty('group_index', $iGroupIdx);
  1375. $iGroupIdx++;
  1376. }
  1377. }
  1378. $oP->AddTabContainer('Navigator');
  1379. $oP->SetCurrentTabContainer('Navigator');
  1380. $sFirstTab = MetaModel::GetConfig()->Get('impact_analysis_first_tab');
  1381. $sContextKey = "itop-config-mgmt/relation_context/$sClass/$sRelation/$sDirection";
  1382. // Check if the current object supports Attachments, similar to AttachmentPlugin::IsTargetObject
  1383. $sClassForAttachment = null;
  1384. $iIdForAttachment = null;
  1385. if (class_exists('Attachment'))
  1386. {
  1387. $aAllowedClasses = MetaModel::GetModuleSetting('itop-attachments', 'allowed_classes', array('Ticket'));
  1388. foreach($aAllowedClasses as $sAllowedClass)
  1389. {
  1390. if ($oObj instanceof $sAllowedClass)
  1391. {
  1392. $iIdForAttachment = $id;
  1393. $sClassForAttachment = $sClass;
  1394. }
  1395. }
  1396. }
  1397. // Display the tabs
  1398. if ($sFirstTab == 'list')
  1399. {
  1400. DisplayNavigatorListTab($oP, $aResults, $sRelation, $oObj);
  1401. $oP->SetCurrentTab(Dict::S('UI:RelationshipGraph'));
  1402. $oDisplayGraph->Display($oP, $aResults, $sRelation, $oAppContext, array(), $sClassForAttachment, $iIdForAttachment, $sContextKey, array('this' => $oObj));
  1403. DisplayNavigatorGroupTab($oP, $aGroups, $sRelation, $oObj);
  1404. }
  1405. else
  1406. {
  1407. $oP->SetCurrentTab(Dict::S('UI:RelationshipGraph'));
  1408. $oDisplayGraph->Display($oP, $aResults, $sRelation, $oAppContext, array(), $sClassForAttachment, $iIdForAttachment, $sContextKey, array('this' => $oObj));
  1409. DisplayNavigatorListTab($oP, $aResults, $sRelation, $oObj);
  1410. DisplayNavigatorGroupTab($oP, $aGroups, $sRelation, $oObj);
  1411. }
  1412. $oP->SetCurrentTab('');
  1413. break;
  1414. ///////////////////////////////////////////////////////////////////////////////////////////
  1415. case 'cancel': // An action was cancelled
  1416. $oP->set_title(Dict::S('UI:OperationCancelled'));
  1417. $oP->add('<h1>'.Dict::S('UI:OperationCancelled').'</h1>');
  1418. break;
  1419. ///////////////////////////////////////////////////////////////////////////////////////////
  1420. default: // Menu node rendering (templates)
  1421. ApplicationMenu::LoadAdditionalMenus();
  1422. $oMenuNode = ApplicationMenu::GetMenuNode(ApplicationMenu::GetMenuIndexById(ApplicationMenu::GetActiveNodeId()));
  1423. if (is_object($oMenuNode))
  1424. {
  1425. $oMenuNode->RenderContent($oP, $oAppContext->GetAsHash());
  1426. $oP->set_title($oMenuNode->GetLabel());
  1427. }
  1428. ///////////////////////////////////////////////////////////////////////////////////////////
  1429. }
  1430. DisplayWelcomePopup($oP);
  1431. $oP->output();
  1432. }
  1433. catch(CoreException $e)
  1434. {
  1435. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  1436. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  1437. if ($e instanceof SecurityException)
  1438. {
  1439. $oP->add("<h1>".Dict::S('UI:SystemIntrusion')."</h1>\n");
  1440. }
  1441. else
  1442. {
  1443. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  1444. }
  1445. $oP->error(Dict::Format('UI:Error_Details', $e->getHtmlDesc()));
  1446. $oP->output();
  1447. if (MetaModel::IsLogEnabledIssue())
  1448. {
  1449. if (MetaModel::IsValidClass('EventIssue'))
  1450. {
  1451. try
  1452. {
  1453. $oLog = new EventIssue();
  1454. $oLog->Set('message', $e->getMessage());
  1455. $oLog->Set('userinfo', '');
  1456. $oLog->Set('issue', $e->GetIssue());
  1457. $oLog->Set('impact', 'Page could not be displayed');
  1458. $oLog->Set('callstack', $e->getTrace());
  1459. $oLog->Set('data', $e->getContextData());
  1460. $oLog->DBInsertNoReload();
  1461. }
  1462. catch(Exception $e)
  1463. {
  1464. IssueLog::Error("Failed to log issue into the DB");
  1465. }
  1466. }
  1467. IssueLog::Error($e->getMessage());
  1468. }
  1469. // For debugging only
  1470. //throw $e;
  1471. }
  1472. catch(Exception $e)
  1473. {
  1474. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  1475. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  1476. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  1477. $oP->error(Dict::Format('UI:Error_Details', $e->getMessage()));
  1478. $oP->output();
  1479. if (MetaModel::IsLogEnabledIssue())
  1480. {
  1481. if (MetaModel::IsValidClass('EventIssue'))
  1482. {
  1483. try
  1484. {
  1485. $oLog = new EventIssue();
  1486. $oLog->Set('message', $e->getMessage());
  1487. $oLog->Set('userinfo', '');
  1488. $oLog->Set('issue', 'PHP Exception');
  1489. $oLog->Set('impact', 'Page could not be displayed');
  1490. $oLog->Set('callstack', $e->getTrace());
  1491. $oLog->Set('data', array());
  1492. $oLog->DBInsertNoReload();
  1493. }
  1494. catch(Exception $e)
  1495. {
  1496. IssueLog::Error("Failed to log issue into the DB");
  1497. }
  1498. }
  1499. IssueLog::Error($e->getMessage());
  1500. }
  1501. }
  1502. ?>