UI.php 64 KB

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