UI.php 65 KB

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