UI.php 69 KB

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