UI.php 69 KB

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