UI.php 64 KB

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