UI.php 69 KB

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