UI.php 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749
  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. $sTargetState = $aTransitions[$sStimulus]['target_state'];
  1041. $aStates = MetaModel::EnumStates($sClass);
  1042. $aTargetStateDef = $aStates[$sTargetState];
  1043. $oP->set_title(Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aSelectObject), $sClass));
  1044. $oP->add('<div class="page_header">');
  1045. $oP->add('<h1>'.MetaModel::GetClassIcon($sClass).'&nbsp;'.Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aSelectObject), $sClass).'</h1>');
  1046. $oP->add('</div>');
  1047. $aExpectedAttributes = MetaModel::GetTransitionAttributes($sClass, $sStimulus, $sState);
  1048. $aDetails = array();
  1049. $iFieldIndex = 0;
  1050. $aFieldsMap = array();
  1051. $aValues = array();
  1052. $aObjects = array();
  1053. foreach($aSelectObject as $iId)
  1054. {
  1055. $aObjects[] = MetaModel::GetObject($sClass, $iId);
  1056. }
  1057. $oSet = DBObjectSet::FromArray($sClass, $aObjects);
  1058. $oObj = $oSet->ComputeCommonObject($aValues);
  1059. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1060. $oObj->Set($sStateAttCode,$sTargetState);
  1061. $sReadyScript = '';
  1062. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  1063. {
  1064. // Prompt for an attribute if
  1065. // - the attribute must be changed or must be displayed to the user for confirmation
  1066. // - or the field is mandatory and currently empty
  1067. if ( ($iExpectCode & (OPT_ATT_MUSTCHANGE | OPT_ATT_MUSTPROMPT)) ||
  1068. (($iExpectCode & OPT_ATT_MANDATORY) && ($oObj->Get($sAttCode) == '')) )
  1069. {
  1070. $aAttributesDef = MetaModel::ListAttributeDefs($sClass);
  1071. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1072. $aPrerequisites = MetaModel::GetPrerequisiteAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  1073. if (count($aPrerequisites) > 0)
  1074. {
  1075. // When 'enabling' a field, all its prerequisites must be enabled too
  1076. $sFieldList = "['".implode("','", $aPrerequisites)."']";
  1077. $oP->add_ready_script("$('#enable_{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, true); } );\n");
  1078. }
  1079. $aDependents = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  1080. if (count($aDependents) > 0)
  1081. {
  1082. // When 'disabling' a field, all its dependent fields must be disabled too
  1083. $sFieldList = "['".implode("','", $aDependents)."']";
  1084. $oP->add_ready_script("$('#enable_{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, false); } );\n");
  1085. }
  1086. $aArgs = array('this' => $oObj);
  1087. $sHTMLValue = cmdbAbstractObject::GetFormElementForField($oP, $sClass, $sAttCode, $oAttDef, $oObj->Get($sAttCode), $oObj->GetEditValue($sAttCode), $sAttCode, '', $iExpectCode, $aArgs);
  1088. $sComments = '<input type="checkbox" checked id="enable_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$sAttCode.'\')"/>';
  1089. if (!isset($aValues[$sAttCode]))
  1090. {
  1091. $aValues[$sAttCode] = array();
  1092. }
  1093. if (count($aValues[$sAttCode]) == 1)
  1094. {
  1095. $sComments .= '<div class="mono_value">1</div>';
  1096. }
  1097. else
  1098. {
  1099. // Non-homogenous value
  1100. $iMaxCount = 5;
  1101. $sTip = "<p><b>".Dict::Format('UI:BulkModify_Count_DistinctValues', count($aValues[$sAttCode]))."</b><ul>";
  1102. $index = 0;
  1103. foreach($aValues[$sAttCode] as $sCurrValue => $aVal)
  1104. {
  1105. $sDisplayValue = empty($aVal['display']) ? '<i>'.Dict::S('Enum:Undefined').'</i>' : str_replace(array("\n", "\r"), " ", $aVal['display']);
  1106. $sTip .= "<li>".Dict::Format('UI:BulkModify:Value_Exists_N_Times', $sDisplayValue, $aVal['count'])."</li>";
  1107. $index++;
  1108. if ($iMaxCount == $index)
  1109. {
  1110. $sTip .= "<li>".Dict::Format('UI:BulkModify:N_MoreValues', count($aValues[$sAttCode]) - $iMaxCount)."</li>";
  1111. break;
  1112. }
  1113. }
  1114. $sTip .= "</ul></p>";
  1115. $sTip = addslashes($sTip);
  1116. $sReadyScript .= "$('#multi_values_$sAttCode').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );\n";
  1117. $sComments .= '<div class="multi_values" id="multi_values_'.$sAttCode.'">'.count($aValues[$sAttCode]).'</div>';
  1118. }
  1119. $aDetails[] = array('label' => '<span>'.$oAttDef->GetLabel().'</span>', 'value' => "<span id=\"field_$sAttCode\">$sHTMLValue</span>", 'comments' => $sComments);
  1120. $aFieldsMap[$sAttCode] = $sAttCode;
  1121. $iFieldIndex++;
  1122. }
  1123. }
  1124. $sButtonsPosition = MetaModel::GetConfig()->Get('buttons_position');
  1125. if ($sButtonsPosition == 'bottom')
  1126. {
  1127. // bottom: Displays the ticket details BEFORE the actions
  1128. $oP->add('<div class="ui-widget-content">');
  1129. $oObj->DisplayBareProperties($oP);
  1130. $oP->add('</div>');
  1131. }
  1132. $oP->add("<div class=\"wizContainer\">\n");
  1133. $oP->add("<form id=\"apply_stimulus\" method=\"post\" onSubmit=\"return OnSubmit('apply_stimulus');\">\n");
  1134. $oP->add("<table><tr><td>\n");
  1135. $oP->details($aDetails);
  1136. $oP->add("</td></tr></table>\n");
  1137. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  1138. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"bulk_apply_stimulus\">\n");
  1139. $oP->add("<input type=\"hidden\" name=\"preview_mode\" value=\"1\">\n");
  1140. $oP->add("<input type=\"hidden\" name=\"filter\" value=\"$sFilter\">\n");
  1141. $oP->add("<input type=\"hidden\" name=\"stimulus\" value=\"$sStimulus\">\n");
  1142. $oP->add("<input type=\"hidden\" name=\"state\" value=\"$sState\">\n");
  1143. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  1144. $oP->add($oAppContext->GetForForm());
  1145. $oP->add("<input type=\"hidden\" name=\"selectObject\" value=\"".implode(',',$aSelectObject)."\">\n");
  1146. $sURL = "./UI.php?operation=search&filter=".urlencode($sFilter)."&".$oAppContext->GetForLink();
  1147. $oP->add("<input type=\"button\" value=\"".Dict::S('UI:Button:Cancel')."\" onClick=\"window.location.href='$sURL'\">&nbsp;&nbsp;&nbsp;&nbsp;\n");
  1148. $oP->add("<button type=\"submit\" class=\"action\"><span>$sActionLabel</span></button>\n");
  1149. $oP->add("</form>\n");
  1150. $oP->add("</div>\n");
  1151. if ($sButtonsPosition != 'bottom')
  1152. {
  1153. // top or both: Displays the ticket details AFTER the actions
  1154. $oP->add('<div class="ui-widget-content">');
  1155. $oObj->DisplayBareProperties($oP);
  1156. $oP->add('</div>');
  1157. }
  1158. $iFieldsCount = count($aFieldsMap);
  1159. $sJsonFieldsMap = json_encode($aFieldsMap);
  1160. $oP->add_script(
  1161. <<<EOF
  1162. // Initializes the object once at the beginning of the page...
  1163. var oWizardHelper = new WizardHelper('$sClass', '', '$sTargetState');
  1164. oWizardHelper.SetFieldsMap($sJsonFieldsMap);
  1165. oWizardHelper.SetFieldsCount($iFieldsCount);
  1166. EOF
  1167. );
  1168. $oP->add_ready_script(
  1169. <<<EOF
  1170. // Starts the validation when the page is ready
  1171. CheckFields('apply_stimulus', false);
  1172. $sReadyScript
  1173. EOF
  1174. );
  1175. }
  1176. break;
  1177. case 'bulk_apply_stimulus':
  1178. $oP->DisableBreadCrumb();
  1179. $bPreviewMode = utils::ReadPostedParam('preview_mode', false);
  1180. $sFilter = utils::ReadPostedParam('filter', '', false, 'raw_data');
  1181. $sStimulus = utils::ReadPostedParam('stimulus', '');
  1182. $sState = utils::ReadPostedParam('state', '');
  1183. $sSelectObject = utils::ReadPostedParam('selectObject', '', false, 'raw_data');
  1184. $aSelectObject = explode(',', $sSelectObject);
  1185. if (empty($sFilter) || empty($sStimulus) || empty($sState))
  1186. {
  1187. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state'));
  1188. }
  1189. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1190. if (!utils::IsTransactionValid($sTransactionId))
  1191. {
  1192. $oP->p(Dict::S('UI:Error:ObjectAlreadyUpdated'));
  1193. }
  1194. else
  1195. {
  1196. // For archiving the modification
  1197. $oFilter = DBObjectSearch::unserialize($sFilter);
  1198. $sClass = $oFilter->GetClass();
  1199. $aObjects = array();
  1200. foreach($aSelectObject as $iId)
  1201. {
  1202. $aObjects[] = MetaModel::GetObject($sClass, $iId);
  1203. }
  1204. $aTransitions = MetaModel::EnumTransitions($sClass, $sState);
  1205. $aStimuli = MetaModel::EnumStimuli($sClass);
  1206. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1207. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1208. $oP->set_title(Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aObjects), $sClass));
  1209. $oP->add('<div class="page_header">');
  1210. $oP->add('<h1>'.MetaModel::GetClassIcon($sClass).'&nbsp;'.Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aObjects), $sClass).'</h1>');
  1211. $oP->add('</div>');
  1212. $oSet = DBObjectSet::FromArray($sClass, $aObjects);
  1213. // For reporting
  1214. $aHeaders = array(
  1215. 'object' => array('label' => MetaModel::GetName($sClass), 'description' => Dict::S('UI:ModifiedObject')),
  1216. 'status' => array('label' => Dict::S('UI:BulkModifyStatus'), 'description' => Dict::S('UI:BulkModifyStatus+')),
  1217. 'errors' => array('label' => Dict::S('UI:BulkModifyErrors'), 'description' => Dict::S('UI:BulkModifyErrors+')),
  1218. );
  1219. $aRows = array();
  1220. while ($oObj = $oSet->Fetch())
  1221. {
  1222. $sError = Dict::S('UI:BulkModifyStatusOk');
  1223. try
  1224. {
  1225. $aTransitions = $oObj->EnumTransitions();
  1226. $aStimuli = MetaModel::EnumStimuli($sClass);
  1227. if (!isset($aTransitions[$sStimulus]))
  1228. {
  1229. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
  1230. }
  1231. else
  1232. {
  1233. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1234. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1235. $sTargetState = $aTransitions[$sStimulus]['target_state'];
  1236. $aExpectedAttributes = $oObj->GetTransitionAttributes($sStimulus /* cureent state */);
  1237. $aDetails = array();
  1238. $aErrors = array();
  1239. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  1240. {
  1241. $iFlags = $oObj->GetTransitionFlags($sAttCode, $sStimulus);
  1242. if (($iExpectCode & (OPT_ATT_MUSTCHANGE|OPT_ATT_MUSTPROMPT)) || ($oObj->Get($sAttCode) == '') )
  1243. {
  1244. $paramValue = utils::ReadPostedParam("attr_$sAttCode", '', 'raw_data');
  1245. if ( ($iFlags & OPT_ATT_SLAVE) && ($paramValue != $oObj->Get($sAttCode)) )
  1246. {
  1247. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1248. $aErrors[] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $oAttDef->GetLabel());
  1249. unset($aExpectedAttributes[$sAttCode]);
  1250. }
  1251. }
  1252. }
  1253. $oObj->UpdateObjectFromPostedForm('', array_keys($aExpectedAttributes), $sTargetState);
  1254. if (count($aErrors) == 0)
  1255. {
  1256. if ($oObj->ApplyStimulus($sStimulus))
  1257. {
  1258. list($bResult, $aErrors) = $oObj->CheckToWrite();
  1259. $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusModified') : Dict::S('UI:BulkModifyStatusSkipped');
  1260. if ($bResult)
  1261. {
  1262. $oObj->DBUpdate();
  1263. }
  1264. else
  1265. {
  1266. $sError = '<p>'.implode('</p></p>',$aErrors)."</p>\n";
  1267. }
  1268. }
  1269. else
  1270. {
  1271. $sStatus = Dict::S('UI:BulkModifyStatusSkipped');
  1272. $sError = '<p>'.Dict::S('UI:FailedToApplyStimuli')."<p>\n";
  1273. }
  1274. }
  1275. else
  1276. {
  1277. $sStatus = Dict::S('UI:BulkModifyStatusSkipped');
  1278. $sError = '<p>'.implode('</p></p>',$aErrors)."</p>\n";
  1279. }
  1280. }
  1281. }
  1282. catch(Exception $e)
  1283. {
  1284. $sError = $e->getMessage();
  1285. $sStatus = Dict::S('UI:BulkModifyStatusSkipped');
  1286. }
  1287. $aRows[] = array(
  1288. 'object' => $oObj->GetHyperlink(),
  1289. 'status' => $sStatus,
  1290. 'errors' => $sError,
  1291. );
  1292. }
  1293. $oP->Table($aHeaders, $aRows);
  1294. // Back to the list
  1295. $sURL = "./UI.php?operation=search&filter=".urlencode($sFilter)."&".$oAppContext->GetForLink();
  1296. $oP->add('<input type="button" onClick="window.location.href=\''.$sURL.'\'" value="'.Dict::S('UI:Button:Done').'">');
  1297. }
  1298. break;
  1299. case 'stimulus': // Form displayed when applying a stimulus (state change)
  1300. $oP->DisableBreadCrumb();
  1301. $sClass = utils::ReadParam('class', '', false, 'class');
  1302. $id = utils::ReadParam('id', '');
  1303. $sStimulus = utils::ReadParam('stimulus', '');
  1304. if ( empty($sClass) || empty($id) || empty($sStimulus) ) // TO DO: check that the class name is valid !
  1305. {
  1306. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'class', 'id', 'stimulus'));
  1307. }
  1308. $oObj = MetaModel::GetObject($sClass, $id, false);
  1309. if ($oObj != null)
  1310. {
  1311. $oObj->DisplayStimulusForm($oP, $sStimulus);
  1312. }
  1313. else
  1314. {
  1315. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  1316. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  1317. }
  1318. break;
  1319. ///////////////////////////////////////////////////////////////////////////////////////////
  1320. case 'apply_stimulus': // Actual state change
  1321. $oP->DisableBreadCrumb();
  1322. $sClass = utils::ReadPostedParam('class', '');
  1323. $id = utils::ReadPostedParam('id', '');
  1324. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1325. $sStimulus = utils::ReadPostedParam('stimulus', '');
  1326. if ( empty($sClass) || empty($id) || empty($sStimulus) ) // TO DO: check that the class name is valid !
  1327. {
  1328. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'class', 'id', 'stimulus'));
  1329. }
  1330. $oObj = MetaModel::GetObject($sClass, $id, false);
  1331. if ($oObj != null)
  1332. {
  1333. $aTransitions = $oObj->EnumTransitions();
  1334. $aStimuli = MetaModel::EnumStimuli($sClass);
  1335. $sMessage = '';
  1336. $sSeverity = 'ok';
  1337. $bDisplayDetails = true;
  1338. if (!isset($aTransitions[$sStimulus]))
  1339. {
  1340. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
  1341. }
  1342. if (!utils::IsTransactionValid($sTransactionId))
  1343. {
  1344. $sMessage = Dict::S('UI:Error:ObjectAlreadyUpdated');
  1345. $sSeverity = 'info';
  1346. }
  1347. else
  1348. {
  1349. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1350. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1351. $sTargetState = $aTransitions[$sStimulus]['target_state'];
  1352. $aExpectedAttributes = $oObj->GetTransitionAttributes($sStimulus /*, current state*/);
  1353. $aDetails = array();
  1354. $aErrors = array();
  1355. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  1356. {
  1357. $iFlags = $oObj->GetTransitionFlags($sAttCode, $sStimulus);
  1358. if (($iExpectCode & (OPT_ATT_MUSTCHANGE|OPT_ATT_MUSTPROMPT)) || ($oObj->Get($sAttCode) == '') )
  1359. {
  1360. $paramValue = utils::ReadPostedParam("attr_$sAttCode", '', 'raw_data');
  1361. if ( ($iFlags & OPT_ATT_SLAVE) && ($paramValue != $oObj->Get($sAttCode)))
  1362. {
  1363. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1364. $aErrors[] = Dict::Format('UI:AttemptingToChangeASlaveAttribute_Name', $oAttDef->GetLabel());
  1365. unset($aExpectedAttributes[$sAttCode]);
  1366. }
  1367. }
  1368. }
  1369. $oObj->UpdateObjectFromPostedForm('', array_keys($aExpectedAttributes), $sTargetState);
  1370. if (count($aErrors) == 0)
  1371. {
  1372. $sIssues = '';
  1373. $bApplyStimulus = true;
  1374. list($bRes, $aIssues) = $oObj->CheckToWrite(); // Check before trying to write the object
  1375. if ($bRes)
  1376. {
  1377. try
  1378. {
  1379. $bApplyStimulus = $oObj->ApplyStimulus($sStimulus); // will write the object in the DB
  1380. }
  1381. catch(CoreException $e)
  1382. {
  1383. // Rollback to the previous state... by reloading the object from the database and applying the modifications again
  1384. $oObj = MetaModel::GetObject(get_class($oObj), $oObj->GetKey());
  1385. $oObj->UpdateObjectFromPostedForm('', array_keys($aExpectedAttributes), $sTargetState);
  1386. $sIssues = $e->getMessage();
  1387. }
  1388. }
  1389. else
  1390. {
  1391. $sIssues = implode(' ', $aIssues);
  1392. }
  1393. if (!$bApplyStimulus)
  1394. {
  1395. $sMessage = Dict::S('UI:FailedToApplyStimuli');
  1396. $sSeverity = 'error';
  1397. }
  1398. else if ($sIssues != '')
  1399. {
  1400. $sOwnershipToken = utils::ReadPostedParam('ownership_token', null, false, 'raw_data');
  1401. if ($sOwnershipToken !== null)
  1402. {
  1403. // Release the concurrent lock, if any, a new lock will be re-acquired by DisplayStimulusForm below
  1404. iTopOwnershipLock::ReleaseLock(get_class($oObj), $oObj->GetKey(), $sOwnershipToken);
  1405. }
  1406. $bDisplayDetails = false;
  1407. // Found issues, explain and give the user a second chance
  1408. //
  1409. $oObj->DisplayStimulusForm($oP, $sStimulus);
  1410. $sIssueDesc = Dict::Format('UI:ObjectCouldNotBeWritten',$sIssues);
  1411. $oP->add_ready_script("alert('".addslashes($sIssueDesc)."');");
  1412. }
  1413. else
  1414. {
  1415. $sMessage = Dict::Format('UI:Class_Object_Updated', MetaModel::GetName(get_class($oObj)), $oObj->GetName());
  1416. $sSeverity = 'ok';
  1417. utils::RemoveTransaction($sTransactionId);
  1418. $bLockEnabled = MetaModel::GetConfig()->Get('concurrent_lock_enabled');
  1419. if ($bLockEnabled)
  1420. {
  1421. // Release the concurrent lock, if any
  1422. $sOwnershipToken = utils::ReadPostedParam('ownership_token', null, false, 'raw_data');
  1423. if ($sOwnershipToken !== null)
  1424. {
  1425. // We're done, let's release the lock
  1426. iTopOwnershipLock::ReleaseLock(get_class($oObj), $oObj->GetKey(), $sOwnershipToken);
  1427. }
  1428. }
  1429. }
  1430. }
  1431. else
  1432. {
  1433. $sMessage = implode('</p><p>', $aErrors);
  1434. $sSeverity = 'error';
  1435. }
  1436. }
  1437. if ($bDisplayDetails)
  1438. {
  1439. ReloadAndDisplay($oP, $oObj, 'apply_stimulus', $sMessage, $sSeverity);
  1440. }
  1441. }
  1442. else
  1443. {
  1444. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  1445. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  1446. }
  1447. break;
  1448. ///////////////////////////////////////////////////////////////////////////////////////////
  1449. case 'swf_navigator': // Graphical display of the relations "impact" / "depends on"
  1450. require_once(APPROOT.'core/simplegraph.class.inc.php');
  1451. require_once(APPROOT.'core/relationgraph.class.inc.php');
  1452. require_once(APPROOT.'core/displayablegraph.class.inc.php');
  1453. $sClass = utils::ReadParam('class', '', false, 'class');
  1454. $id = utils::ReadParam('id', 0);
  1455. $sRelation = utils::ReadParam('relation', 'impact');
  1456. $sDirection = utils::ReadParam('direction', 'down');
  1457. $iGroupingThreshold = utils::ReadParam('g', 5);
  1458. $oObj = MetaModel::GetObject($sClass, $id);
  1459. $iMaxRecursionDepth = MetaModel::GetConfig()->Get('relations_max_depth', 20);
  1460. $aSourceObjects = array($oObj);
  1461. $oP->set_title(MetaModel::GetRelationDescription($sRelation).' '.$oObj->GetName());
  1462. $sPageId = "ui-relation-graph-".$sClass.'::'.$id;
  1463. $sLabel = $oObj->GetName().' '.MetaModel::GetRelationLabel($sRelation);
  1464. $sDescription = MetaModel::GetRelationDescription($sRelation).' '.$oObj->GetName();
  1465. $oP->SetBreadCrumbEntry($sPageId, $sLabel, $sDescription);
  1466. if ($sRelation == 'depends on')
  1467. {
  1468. $sRelation = 'impacts';
  1469. $sDirection = 'up';
  1470. }
  1471. if ($sDirection == 'up')
  1472. {
  1473. $oRelGraph = MetaModel::GetRelatedObjectsUp($sRelation, $aSourceObjects, $iMaxRecursionDepth);
  1474. }
  1475. else
  1476. {
  1477. $oRelGraph = MetaModel::GetRelatedObjectsDown($sRelation, $aSourceObjects, $iMaxRecursionDepth);
  1478. }
  1479. $aResults = $oRelGraph->GetObjectsByClass();
  1480. $oDisplayGraph = DisplayableGraph::FromRelationGraph($oRelGraph, $iGroupingThreshold, ($sDirection == 'down'));
  1481. $oP->AddTabContainer('Navigator');
  1482. $oP->SetCurrentTabContainer('Navigator');
  1483. $sFirstTab = MetaModel::GetConfig()->Get('impact_analysis_first_tab');
  1484. $sContextKey = "itop-config-mgmt/relation_context/$sClass/$sRelation/$sDirection";
  1485. // Check if the current object supports Attachments, similar to AttachmentPlugin::IsTargetObject
  1486. $sClassForAttachment = null;
  1487. $iIdForAttachment = null;
  1488. if (class_exists('Attachment'))
  1489. {
  1490. $aAllowedClasses = MetaModel::GetModuleSetting('itop-attachments', 'allowed_classes', array('Ticket'));
  1491. foreach($aAllowedClasses as $sAllowedClass)
  1492. {
  1493. if ($oObj instanceof $sAllowedClass)
  1494. {
  1495. $iIdForAttachment = $id;
  1496. $sClassForAttachment = $sClass;
  1497. }
  1498. }
  1499. }
  1500. $oP->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/tabularfieldsselector.js');
  1501. $oP->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/jquery.dragtable.js');
  1502. $oP->add_linked_stylesheet(utils::GetAbsoluteUrlAppRoot().'css/dragtable.css');
  1503. // Display the tabs
  1504. if ($sFirstTab == 'list')
  1505. {
  1506. DisplayNavigatorListTab($oP, $aResults, $sRelation, $sDirection, $oObj);
  1507. $oP->SetCurrentTab(Dict::S('UI:RelationshipGraph'));
  1508. $oDisplayGraph->Display($oP, $aResults, $sRelation, $oAppContext, array(), $sClassForAttachment, $iIdForAttachment, $sContextKey, array('this' => $oObj));
  1509. DisplayNavigatorGroupTab($oP);
  1510. }
  1511. else
  1512. {
  1513. $oP->SetCurrentTab(Dict::S('UI:RelationshipGraph'));
  1514. $oDisplayGraph->Display($oP, $aResults, $sRelation, $oAppContext, array(), $sClassForAttachment, $iIdForAttachment, $sContextKey, array('this' => $oObj));
  1515. DisplayNavigatorListTab($oP, $aResults, $sRelation, $sDirection, $oObj);
  1516. DisplayNavigatorGroupTab($oP);
  1517. }
  1518. $oP->SetCurrentTab('');
  1519. break;
  1520. ///////////////////////////////////////////////////////////////////////////////////////////
  1521. case 'kill_lock':
  1522. $oP->DisableBreadCrumb();
  1523. $sClass = utils::ReadParam('class', '');
  1524. $id = utils::ReadParam('id', '');
  1525. iTopOwnershipLock::KillLock($sClass, $id);
  1526. $oObj = MetaModel::GetObject($sClass, $id);
  1527. ReloadAndDisplay($oP, $oObj, 'concurrent_lock_killed', Dict::S('UI:ConcurrentLockKilled'), 'info');
  1528. break;
  1529. ///////////////////////////////////////////////////////////////////////////////////////////
  1530. case 'cancel': // An action was cancelled
  1531. $oP->DisableBreadCrumb();
  1532. $oP->set_title(Dict::S('UI:OperationCancelled'));
  1533. $oP->add('<h1>'.Dict::S('UI:OperationCancelled').'</h1>');
  1534. break;
  1535. ///////////////////////////////////////////////////////////////////////////////////////////
  1536. default: // Menu node rendering (templates)
  1537. ApplicationMenu::LoadAdditionalMenus();
  1538. $oMenuNode = ApplicationMenu::GetMenuNode(ApplicationMenu::GetMenuIndexById(ApplicationMenu::GetActiveNodeId()));
  1539. if (is_object($oMenuNode))
  1540. {
  1541. $oMenuNode->RenderContent($oP, $oAppContext->GetAsHash());
  1542. $oP->set_title($oMenuNode->GetLabel());
  1543. }
  1544. ///////////////////////////////////////////////////////////////////////////////////////////
  1545. }
  1546. DisplayWelcomePopup($oP);
  1547. $oP->output();
  1548. }
  1549. catch(CoreException $e)
  1550. {
  1551. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  1552. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  1553. if ($e instanceof SecurityException)
  1554. {
  1555. $oP->add("<h1>".Dict::S('UI:SystemIntrusion')."</h1>\n");
  1556. }
  1557. else
  1558. {
  1559. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  1560. }
  1561. $oP->error(Dict::Format('UI:Error_Details', $e->getHtmlDesc()));
  1562. $oP->output();
  1563. if (MetaModel::IsLogEnabledIssue())
  1564. {
  1565. if (MetaModel::IsValidClass('EventIssue'))
  1566. {
  1567. try
  1568. {
  1569. $oLog = new EventIssue();
  1570. $oLog->Set('message', $e->getMessage());
  1571. $oLog->Set('userinfo', '');
  1572. $oLog->Set('issue', $e->GetIssue());
  1573. $oLog->Set('impact', 'Page could not be displayed');
  1574. $oLog->Set('callstack', $e->getTrace());
  1575. $oLog->Set('data', $e->getContextData());
  1576. $oLog->DBInsertNoReload();
  1577. }
  1578. catch(Exception $e)
  1579. {
  1580. IssueLog::Error("Failed to log issue into the DB");
  1581. }
  1582. }
  1583. IssueLog::Error($e->getMessage());
  1584. }
  1585. // For debugging only
  1586. //throw $e;
  1587. }
  1588. catch(Exception $e)
  1589. {
  1590. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  1591. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  1592. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  1593. $oP->error(Dict::Format('UI:Error_Details', $e->getMessage()));
  1594. $oP->output();
  1595. if (MetaModel::IsLogEnabledIssue())
  1596. {
  1597. if (MetaModel::IsValidClass('EventIssue'))
  1598. {
  1599. try
  1600. {
  1601. $oLog = new EventIssue();
  1602. $oLog->Set('message', $e->getMessage());
  1603. $oLog->Set('userinfo', '');
  1604. $oLog->Set('issue', 'PHP Exception');
  1605. $oLog->Set('impact', 'Page could not be displayed');
  1606. $oLog->Set('callstack', $e->getTrace());
  1607. $oLog->Set('data', array());
  1608. $oLog->DBInsertNoReload();
  1609. }
  1610. catch(Exception $e)
  1611. {
  1612. IssueLog::Error("Failed to log issue into the DB");
  1613. }
  1614. }
  1615. IssueLog::Error($e->getMessage());
  1616. }
  1617. }
  1618. ?>