UI.php 65 KB

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