UI.php 67 KB

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