UI.php 69 KB

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