UI.php 69 KB

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