UI.php 65 KB

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