UI.php 64 KB

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