UI.php 64 KB

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