UI.php 63 KB

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