UI.php 68 KB

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