UI.php 64 KB

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