UI.php 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657
  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. $iErrors = 0;
  499. // Check if a class name/label is supplied to limit the search
  500. $sClassName = '';
  501. if (preg_match('/^([^\"]+):(.+)$/', $sFullText, $aMatches))
  502. {
  503. $sClassName = $aMatches[1];
  504. if (MetaModel::IsValidClass($sClassName))
  505. {
  506. $sFullText = trim($aMatches[2]);
  507. }
  508. elseif ($sClassName = MetaModel::GetClassFromLabel($sClassName, false /* => not case sensitive */))
  509. {
  510. $sFullText = trim($aMatches[2]);
  511. }
  512. }
  513. if (preg_match('/^"(.*)"$/', $sFullText, $aMatches))
  514. {
  515. // The text is surrounded by double-quotes, remove the quotes and treat it as one single expression
  516. $aFullTextNeedles = array($aMatches[1]);
  517. }
  518. else
  519. {
  520. // Split the text on the blanks and treat this as a search for <word1> AND <word2> AND <word3>
  521. $aFullTextNeedles = explode(' ', $sFullText);
  522. }
  523. // Check the needle length
  524. $iMinLenth = MetaModel::GetConfig()->Get('full_text_needle_min');
  525. foreach ($aFullTextNeedles as $sNeedle)
  526. {
  527. if (strlen($sNeedle) < $iMinLenth)
  528. {
  529. $oP->p(Dict::Format('UI:Search:NeedleTooShort', $sNeedle, $iMinLenth));
  530. $iErrors++;
  531. }
  532. }
  533. // Sanity check of the accelerators
  534. $aAccelerators = MetaModel::GetConfig()->Get('full_text_accelerators');
  535. foreach ($aAccelerators as $sClass => $aAccelerator)
  536. {
  537. try
  538. {
  539. $bSkip = array_key_exists('skip', $aAccelerator) ? $aAccelerator['skip'] : false;
  540. if (!$bSkip)
  541. {
  542. $oSearch = DBObjectSearch::FromOQL($aAccelerator['query']);
  543. if ($sClass != $oSearch->GetClass())
  544. {
  545. $oP->p("Full text accelerator for class '$sClass': searched class mismatch (".$oSearch->GetClass().")");
  546. $iErrors++;
  547. }
  548. }
  549. }
  550. catch (OqlException $e)
  551. {
  552. $oP->p("Full text accelerator for class '$sClass': ".$e->getHtmlDesc());
  553. $iErrors++;
  554. }
  555. }
  556. if ($iErrors == 0)
  557. {
  558. $oP->set_title(Dict::S('UI:SearchResultsPageTitle'));
  559. $oP->add("<div style=\"padding: 10px;\">\n");
  560. $oP->add("<div class=\"header_message\" id=\"full_text_progress\" style=\"position: fixed; background-color: #cccccc; opacity: 0.7; padding: 1.5em;\">\n");
  561. $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>');
  562. $oP->add("</div>\n");
  563. $oP->add("<div id=\"full_text_results\">\n");
  564. $oP->add("<div id=\"full_text_progress_placeholder\" style=\"padding: 1.5em;\">&nbsp;</div>\n");
  565. $oP->add("<h2>".Dict::Format('UI:FullTextSearchTitle_Text', htmlentities($sFullText, ENT_QUOTES, 'UTF-8'))."</h2>");
  566. $oP->add("</div>\n");
  567. $oP->add("</div>\n");
  568. $sJSClass = addslashes($sClassName);
  569. $sJSNeedles = json_encode($aFullTextNeedles);
  570. $oP->add_ready_script(
  571. <<<EOF
  572. var oParams = {operation: 'full_text_search', position: 0, 'class': '$sJSClass', needles: $sJSNeedles, tune: $iTune};
  573. $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php', oParams, function(data) {
  574. $('#full_text_results').append(data);
  575. });
  576. EOF
  577. );
  578. if ($iTune > 0)
  579. {
  580. $oP->add_script("var oTimeStatistics = {};");
  581. }
  582. }
  583. }
  584. break;
  585. ///////////////////////////////////////////////////////////////////////////////////////////
  586. case 'modify': // Form to modify an object
  587. $sClass = utils::ReadParam('class', '', false, 'class');
  588. $sClassLabel = MetaModel::GetName($sClass);
  589. $id = utils::ReadParam('id', '');
  590. if ( empty($sClass) || empty($id)) // TO DO: check that the class name is valid !
  591. {
  592. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'id'));
  593. }
  594. // Check if the user can modify this object
  595. $oObj = MetaModel::GetObject($sClass, $id, false /* MustBeFound */);
  596. if (is_null($oObj))
  597. {
  598. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  599. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  600. }
  601. else
  602. {
  603. // The object could be read - check if it is allowed to modify it
  604. $oSet = CMDBObjectSet::FromObject($oObj);
  605. if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet) == UR_ALLOWED_NO)
  606. {
  607. throw new SecurityException('User not allowed to modify this object', array('class' => $sClass, 'id' => $id));
  608. }
  609. // Note: code duplicated to the case 'apply_modify' when a data integrity issue has been found
  610. $oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetRawName(), $sClassLabel)); // Set title will take care of the encoding
  611. $oP->add("<div class=\"page_header\">\n");
  612. $oP->add("<h1>".$oObj->GetIcon()."&nbsp;".Dict::Format('UI:ModificationTitle_Class_Object', $sClassLabel, $oObj->GetName())."</h1>\n");
  613. $oP->add("</div>\n");
  614. $oP->add("<div class=\"wizContainer\">\n");
  615. $oObj->DisplayModifyForm($oP);
  616. $oP->add("</div>\n");
  617. }
  618. break;
  619. ///////////////////////////////////////////////////////////////////////////////////////////
  620. case 'select_for_modify_all': // Select the list of objects to be modified (bulk modify)
  621. $oP->set_title(Dict::S('UI:ModifyAllPageTitle'));
  622. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  623. if (empty($sFilter))
  624. {
  625. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'filter'));
  626. }
  627. // TO DO: limit the search filter by the user context
  628. $oFilter = DBObjectSearch::unserialize($sFilter); // TO DO : check that the filter is valid
  629. $sClass = $oFilter->GetClass();
  630. $oChecker = new ActionChecker($oFilter, UR_ACTION_BULK_MODIFY);
  631. $oP->add("<h1>".Dict::S('UI:ModifyAllPageTitle')."</h1>\n");
  632. DisplayMultipleSelectionForm($oP, $oFilter, 'form_for_modify_all', $oChecker);
  633. break;
  634. ///////////////////////////////////////////////////////////////////////////////////////////
  635. case 'form_for_modify_all': // Form to modify multiple objects (bulk modify)
  636. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  637. $sClass = utils::ReadParam('class', '', false, 'class');
  638. $oFullSetFilter = DBObjectSearch::unserialize($sFilter);
  639. $aSelectedObj = utils::ReadMultipleSelection($oFullSetFilter);
  640. $sCancelUrl = "./UI.php?operation=search&filter=".urlencode($sFilter)."&".$oAppContext->GetForLink();
  641. $aContext = array('filter' => $sFilter);
  642. cmdbAbstractObject::DisplayBulkModifyForm($oP, $sClass, $aSelectedObj, 'preview_or_modify_all', $sCancelUrl, array(), $aContext);
  643. break;
  644. ///////////////////////////////////////////////////////////////////////////////////////////
  645. case 'preview_or_modify_all': // Preview or apply bulk modify
  646. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  647. // TO DO: limit the search filter by the user context
  648. $oFilter = DBObjectSearch::unserialize($sFilter); // TO DO : check that the filter is valid
  649. $oChecker = new ActionChecker($oFilter, UR_ACTION_BULK_MODIFY);
  650. $sClass = utils::ReadParam('class', '', false, 'class');
  651. $bPreview = utils::ReadParam('preview_mode', '');
  652. $sSelectedObj = utils::ReadParam('selectObj', '', false, 'raw_data');
  653. if ( empty($sClass) || empty($sSelectedObj)) // TO DO: check that the class name is valid !
  654. {
  655. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'selectObj'));
  656. }
  657. $aSelectedObj = explode(',', $sSelectedObj);
  658. $sCancelUrl = "./UI.php?operation=search&filter=".urlencode($sFilter)."&".$oAppContext->GetForLink();
  659. $aContext = array(
  660. 'filter' => $sFilter,
  661. 'selectObj' => $sSelectedObj,
  662. );
  663. cmdbAbstractObject::DoBulkModify($oP, $sClass, $aSelectedObj, 'preview_or_modify_all', $bPreview, $sCancelUrl, $aContext);
  664. break;
  665. ///////////////////////////////////////////////////////////////////////////////////////////
  666. case 'new': // Form to create a new object
  667. $sClass = utils::ReadParam('class', '', false, 'class');
  668. $sStateCode = utils::ReadParam('state', '');
  669. $bCheckSubClass = utils::ReadParam('checkSubclass', true);
  670. if ( empty($sClass) )
  671. {
  672. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'class'));
  673. }
  674. $aArgs = utils::ReadParam('default', array(), false, 'raw_data');
  675. $aContext = $oAppContext->GetAsHash();
  676. foreach( $oAppContext->GetNames() as $key)
  677. {
  678. $aArgs[$key] = $oAppContext->GetCurrentValue($key);
  679. }
  680. // If the specified class has subclasses, ask the user an instance of which class to create
  681. $aSubClasses = MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL); // Including the specified class itself
  682. $aPossibleClasses = array();
  683. $sRealClass = '';
  684. if ($bCheckSubClass)
  685. {
  686. foreach($aSubClasses as $sCandidateClass)
  687. {
  688. if (!MetaModel::IsAbstract($sCandidateClass) && (UserRights::IsActionAllowed($sCandidateClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES))
  689. {
  690. $aPossibleClasses[$sCandidateClass] = MetaModel::GetName($sCandidateClass);
  691. }
  692. }
  693. // Only one of the subclasses can be instantiated...
  694. if (count($aPossibleClasses) == 1)
  695. {
  696. $aKeys = array_keys($aPossibleClasses);
  697. $sRealClass = $aKeys[0];
  698. }
  699. }
  700. else
  701. {
  702. $sRealClass = $sClass;
  703. }
  704. if (!empty($sRealClass))
  705. {
  706. // Display the creation form
  707. $sClassLabel = MetaModel::GetName($sRealClass);
  708. // Note: some code has been duplicated to the case 'apply_new' when a data integrity issue has been found
  709. $oP->set_title(Dict::Format('UI:CreationPageTitle_Class', $sClassLabel));
  710. $oP->add("<h1>".MetaModel::GetClassIcon($sRealClass)."&nbsp;".Dict::Format('UI:CreationTitle_Class', $sClassLabel)."</h1>\n");
  711. $oP->add("<div class=\"wizContainer\">\n");
  712. // Set all the default values in an object and clone this "default" object
  713. $oObjToClone = MetaModel::NewObject($sRealClass);
  714. // 1st - set context values
  715. $oAppContext->InitObjectFromContext($oObjToClone);
  716. // 2nd - set values from the page argument 'default'
  717. $oObjToClone->UpdateObjectFromArg('default');
  718. cmdbAbstractObject::DisplayCreationForm($oP, $sRealClass, $oObjToClone, array());
  719. $oP->add("</div>\n");
  720. }
  721. else
  722. {
  723. // Select the derived class to create
  724. $sClassLabel = MetaModel::GetName($sClass);
  725. $oP->add("<h1>".MetaModel::GetClassIcon($sClass)."&nbsp;".Dict::Format('UI:CreationTitle_Class', $sClassLabel)."</h1>\n");
  726. $oP->add("<div class=\"wizContainer\">\n");
  727. $oP->add('<form>');
  728. $oP->add('<p>'.Dict::Format('UI:SelectTheTypeOf_Class_ToCreate', $sClassLabel));
  729. $aDefaults = utils::ReadParam('default', array(), false, 'raw_data');
  730. $oP->add($oAppContext->GetForForm());
  731. $oP->add("<input type=\"hidden\" name=\"checkSubclass\" value=\"0\">\n");
  732. $oP->add("<input type=\"hidden\" name=\"state\" value=\"$sStateCode\">\n");
  733. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"new\">\n");
  734. foreach($aDefaults as $key => $value)
  735. {
  736. if (is_array($value))
  737. {
  738. foreach($value as $key2 => $value2)
  739. {
  740. if (is_array($value2))
  741. {
  742. foreach($value2 as $key3 => $value3)
  743. {
  744. $oP->add("<input type=\"hidden\" name=\"default[$key][$key2][$key3]\" value=\"$value3\">\n");
  745. }
  746. }
  747. else
  748. {
  749. $oP->add("<input type=\"hidden\" name=\"default[$key][$key2]\" value=\"$value2\">\n");
  750. }
  751. }
  752. }
  753. else
  754. {
  755. $oP->add("<input type=\"hidden\" name=\"default[$key]\" value=\"$value\">\n");
  756. }
  757. }
  758. $oP->add('<select name="class">');
  759. asort($aPossibleClasses);
  760. foreach($aPossibleClasses as $sClassName => $sClassLabel)
  761. {
  762. $sSelected = ($sClassName == $sClass) ? 'selected' : '';
  763. $oP->add("<option $sSelected value=\"$sClassName\">$sClassLabel</option>");
  764. }
  765. $oP->add('</select>');
  766. $oP->add("&nbsp; <input type=\"submit\" value=\"".Dict::S('UI:Button:Apply')."\"></p>");
  767. $oP->add('</form>');
  768. $oP->add("</div>\n");
  769. }
  770. break;
  771. ///////////////////////////////////////////////////////////////////////////////////////////
  772. case 'apply_modify': // Applying the modifications to an existing object
  773. $sClass = utils::ReadPostedParam('class', '');
  774. $sClassLabel = MetaModel::GetName($sClass);
  775. $id = utils::ReadPostedParam('id', '');
  776. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  777. if ( empty($sClass) || empty($id)) // TO DO: check that the class name is valid !
  778. {
  779. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'id'));
  780. }
  781. $bDisplayDetails = true;
  782. $oObj = MetaModel::GetObject($sClass, $id, false);
  783. if ($oObj == null)
  784. {
  785. $bDisplayDetails = false;
  786. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  787. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  788. }
  789. elseif (!utils::IsTransactionValid($sTransactionId, false))
  790. {
  791. $oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetRawName(), $sClassLabel)); // Set title will take care of the encoding
  792. $oP->p("<strong>".Dict::S('UI:Error:ObjectAlreadyUpdated')."</strong>\n");
  793. }
  794. else
  795. {
  796. $oObj->UpdateObjectFromPostedForm();
  797. $sMessage = '';
  798. $sSeverity = 'ok';
  799. if (!$oObj->IsModified())
  800. {
  801. $oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetRawName(), $sClassLabel)); // Set title will take care of the encoding
  802. $sMessage = Dict::Format('UI:Class_Object_NotUpdated', MetaModel::GetName(get_class($oObj)), $oObj->GetName());
  803. $sSeverity = 'info';
  804. }
  805. else
  806. {
  807. list($bRes, $aIssues) = $oObj->CheckToWrite();
  808. if ($bRes)
  809. {
  810. $oObj->DBUpdate();
  811. utils::RemoveTransaction($sTransactionId);
  812. $sMessage = Dict::Format('UI:Class_Object_Updated', MetaModel::GetName(get_class($oObj)), $oObj->GetName());
  813. $sSeverity = 'ok';
  814. }
  815. else
  816. {
  817. $bDisplayDetails = false;
  818. // Found issues, explain and give the user a second chance
  819. //
  820. $oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetRawName(), $sClassLabel)); // Set title will take care of the encoding
  821. $oP->add("<div class=\"page_header\">\n");
  822. $oP->add("<h1>".$oObj->GetIcon()."&nbsp;".Dict::Format('UI:ModificationTitle_Class_Object', $sClassLabel, $oObj->GetName())."</h1>\n");
  823. $oP->add("</div>\n");
  824. $oP->add("<div class=\"wizContainer\">\n");
  825. $oObj->DisplayModifyForm($oP);
  826. $oP->add("</div>\n");
  827. $sIssueDesc = Dict::Format('UI:ObjectCouldNotBeWritten', implode(', ', $aIssues));
  828. $oP->add_ready_script("alert('".addslashes($sIssueDesc)."');");
  829. }
  830. }
  831. }
  832. if ($bDisplayDetails)
  833. {
  834. $oObj = MetaModel::GetObject(get_class($oObj), $oObj->GetKey()); //Workaround: reload the object so that the linkedset are displayed properly
  835. $sNextAction = utils::ReadPostedParam('next_action', '');
  836. if (!empty($sNextAction))
  837. {
  838. ApplyNextAction($oP, $oObj, $sNextAction);
  839. }
  840. else
  841. {
  842. // Nothing more to do
  843. ReloadAndDisplay($oP, $oObj, 'update', $sMessage, $sSeverity);
  844. }
  845. }
  846. break;
  847. ///////////////////////////////////////////////////////////////////////////////////////////
  848. case 'select_for_deletion': // Select multiple objects for deletion
  849. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  850. if (empty($sFilter))
  851. {
  852. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'filter'));
  853. }
  854. $oP->set_title(Dict::S('UI:BulkDeletePageTitle'));
  855. $oP->add("<h1>".Dict::S('UI:BulkDeleteTitle')."</h1>\n");
  856. // TO DO: limit the search filter by the user context
  857. $oFilter = CMDBSearchFilter::unserialize($sFilter); // TO DO : check that the filter is valid
  858. $oChecker = new ActionChecker($oFilter, UR_ACTION_BULK_DELETE);
  859. DisplayMultipleSelectionForm($oP, $oFilter, 'bulk_delete', $oChecker);
  860. break;
  861. ///////////////////////////////////////////////////////////////////////////////////////////
  862. case 'bulk_delete_confirmed': // Confirm bulk deletion of objects
  863. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  864. if (!utils::IsTransactionValid($sTransactionId))
  865. {
  866. throw new ApplicationException(Dict::S('UI:Error:ObjectsAlreadyDeleted'));
  867. }
  868. // Fall through
  869. ///////////////////////////////////////////////////////////////////////////////////////////
  870. case 'delete':
  871. case 'bulk_delete': // Actual bulk deletion (if confirmed)
  872. $sClass = utils::ReadParam('class', '', false, 'class');
  873. $sClassLabel = MetaModel::GetName($sClass);
  874. $aObjects = array();
  875. if ($operation == 'delete')
  876. {
  877. // Single object
  878. $id = utils::ReadParam('id', '');
  879. $oObj = MetaModel::GetObject($sClass, $id);
  880. $aObjects[] = $oObj;
  881. if (!UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, DBObjectSet::FromObject($oObj)))
  882. {
  883. throw new SecurityException(Dict::Format('UI:Error:DeleteNotAllowedOn_Class', $sClassLabel));
  884. }
  885. }
  886. else
  887. {
  888. // Several objects
  889. $sFilter = utils::ReadPostedParam('filter', '');
  890. $oFullSetFilter = DBObjectSearch::unserialize($sFilter);
  891. $aSelectObject = utils::ReadMultipleSelection($oFullSetFilter);
  892. if ( empty($sClass) || empty($aSelectObject)) // TO DO: check that the class name is valid !
  893. {
  894. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'selectObject[]'));
  895. }
  896. foreach($aSelectObject as $iId)
  897. {
  898. $aObjects[] = MetaModel::GetObject($sClass, $iId);
  899. }
  900. if (count($aObjects) == 1)
  901. {
  902. if (!UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, DBObjectSet::FromArray($sClass, $aObjects)))
  903. {
  904. throw new SecurityException(Dict::Format('UI:Error:BulkDeleteNotAllowedOn_Class', $sClassLabel));
  905. }
  906. }
  907. else
  908. {
  909. if (!UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_DELETE, DBObjectSet::FromArray($sClass, $aObjects)))
  910. {
  911. throw new SecurityException(Dict::Format('UI:Error:BulkDeleteNotAllowedOn_Class', $sClassLabel));
  912. }
  913. $oP->set_title(Dict::S('UI:BulkDeletePageTitle'));
  914. }
  915. }
  916. // Go for the common part... (delete single, delete bulk, delete confirmed)
  917. cmdbAbstractObject::DeleteObjects($oP, $sClass, $aObjects, ($operation != 'bulk_delete_confirmed'), 'bulk_delete_confirmed');
  918. break;
  919. ///////////////////////////////////////////////////////////////////////////////////////////
  920. case 'apply_new': // Creation of a new object
  921. $sClass = utils::ReadPostedParam('class', '', 'class');
  922. $sClassLabel = MetaModel::GetName($sClass);
  923. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  924. if ( empty($sClass) ) // TO DO: check that the class name is valid !
  925. {
  926. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'class'));
  927. }
  928. if (!utils::IsTransactionValid($sTransactionId, false))
  929. {
  930. $oP->p("<strong>".Dict::S('UI:Error:ObjectAlreadyCreated')."</strong>\n");
  931. }
  932. else
  933. {
  934. $oObj = MetaModel::NewObject($sClass);
  935. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  936. if (!empty($sStateAttCode))
  937. {
  938. $sTargetState = utils::ReadPostedParam('obj_state', '');
  939. if ($sTargetState != '')
  940. {
  941. $oObj->Set($sStateAttCode, $sTargetState);
  942. }
  943. }
  944. $oObj->UpdateObjectFromPostedForm();
  945. }
  946. if (isset($oObj) && is_object($oObj))
  947. {
  948. $sClass = get_class($oObj);
  949. $sClassLabel = MetaModel::GetName($sClass);
  950. list($bRes, $aIssues) = $oObj->CheckToWrite();
  951. if ($bRes)
  952. {
  953. $oObj->DBInsert();
  954. utils::RemoveTransaction($sTransactionId);
  955. $oP->set_title(Dict::S('UI:PageTitle:ObjectCreated'));
  956. $sMessage = Dict::Format('UI:Title:Object_Of_Class_Created', $oObj->GetName(), $sClassLabel);
  957. $oObj = MetaModel::GetObject(get_class($oObj), $oObj->GetKey()); //Workaround: reload the object so that the linkedset are displayed properly
  958. $sNextAction = utils::ReadPostedParam('next_action', '');
  959. if (!empty($sNextAction))
  960. {
  961. $oP->add("<h1>$sMessage</h1>");
  962. ApplyNextAction($oP, $oObj, $sNextAction);
  963. }
  964. else
  965. {
  966. // Nothing more to do
  967. ReloadAndDisplay($oP, $oObj, 'create', $sMessage, 'ok');
  968. }
  969. }
  970. else
  971. {
  972. // Found issues, explain and give the user a second chance
  973. //
  974. $oP->set_title(Dict::Format('UI:CreationPageTitle_Class', $sClassLabel));
  975. $oP->add("<h1>".MetaModel::GetClassIcon($sClass)."&nbsp;".Dict::Format('UI:CreationTitle_Class', $sClassLabel)."</h1>\n");
  976. $oP->add("<div class=\"wizContainer\">\n");
  977. cmdbAbstractObject::DisplayCreationForm($oP, $sClass, $oObj);
  978. $oP->add("</div>\n");
  979. $sIssueDesc = Dict::Format('UI:ObjectCouldNotBeWritten', implode(', ', $aIssues));
  980. $oP->add_ready_script("alert('".addslashes($sIssueDesc)."');");
  981. }
  982. }
  983. break;
  984. ///////////////////////////////////////////////////////////////////////////////////////////
  985. case 'select_bulk_stimulus': // Form displayed when applying a stimulus to many objects
  986. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  987. $sStimulus = utils::ReadParam('stimulus', '');
  988. $sState = utils::ReadParam('state', '');
  989. if (empty($sFilter) || empty($sStimulus) || empty($sState))
  990. {
  991. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state'));
  992. }
  993. $oFilter = DBObjectSearch::unserialize($sFilter);
  994. $sClass = $oFilter->GetClass();
  995. $aStimuli = MetaModel::EnumStimuli($sClass);
  996. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  997. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  998. $oP->set_title($sActionLabel);
  999. $oP->add('<div class="page_header">');
  1000. $oP->add('<h1>'.MetaModel::GetClassIcon($sClass).'&nbsp;'.$sActionLabel.'</h1>');
  1001. $oP->add('</div>');
  1002. $oChecker = new StimulusChecker($oFilter, $sState, $sStimulus);
  1003. $aExtraFormParams = array('stimulus' => $sStimulus, 'state' => $sState);
  1004. DisplayMultipleSelectionForm($oP, $oFilter, 'bulk_stimulus', $oChecker, $aExtraFormParams);
  1005. break;
  1006. case 'bulk_stimulus':
  1007. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  1008. $sStimulus = utils::ReadParam('stimulus', '');
  1009. $sState = utils::ReadParam('state', '');
  1010. if (empty($sFilter) || empty($sStimulus) || empty($sState))
  1011. {
  1012. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state'));
  1013. }
  1014. $oFilter = DBObjectSearch::unserialize($sFilter);
  1015. $sClass = $oFilter->GetClass();
  1016. $aSelectObject = utils::ReadMultipleSelection($oFilter);
  1017. if (count($aSelectObject) == 0)
  1018. {
  1019. // Nothing to do, no object was selected !
  1020. throw new ApplicationException(Dict::S('UI:BulkAction:NoObjectSelected'));
  1021. }
  1022. else
  1023. {
  1024. $aTransitions = MetaModel::EnumTransitions($sClass, $sState);
  1025. $aStimuli = MetaModel::EnumStimuli($sClass);
  1026. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1027. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1028. $aTransition = $aTransitions[$sStimulus];
  1029. $sTargetState = $aTransition['target_state'];
  1030. $aStates = MetaModel::EnumStates($sClass);
  1031. $aTargetStateDef = $aStates[$sTargetState];
  1032. $oP->set_title(Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aSelectObject), $sClass));
  1033. $oP->add('<div class="page_header">');
  1034. $oP->add('<h1>'.MetaModel::GetClassIcon($sClass).'&nbsp;'.Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aSelectObject), $sClass).'</h1>');
  1035. $oP->add('</div>');
  1036. $aExpectedAttributes = $aTargetStateDef['attribute_list'];
  1037. $aDetails = array();
  1038. $iFieldIndex = 0;
  1039. $aFieldsMap = array();
  1040. $aValues = array();
  1041. $aObjects = array();
  1042. foreach($aSelectObject as $iId)
  1043. {
  1044. $aObjects[] = MetaModel::GetObject($sClass, $iId);
  1045. }
  1046. $oSet = DBObjectSet::FromArray($sClass, $aObjects);
  1047. $oObj = $oSet->ComputeCommonObject($aValues);
  1048. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1049. $oObj->Set($sStateAttCode,$sTargetState);
  1050. $sReadyScript = '';
  1051. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  1052. {
  1053. // Prompt for an attribute if
  1054. // - the attribute must be changed or must be displayed to the user for confirmation
  1055. // - or the field is mandatory and currently empty
  1056. if ( ($iExpectCode & (OPT_ATT_MUSTCHANGE | OPT_ATT_MUSTPROMPT)) ||
  1057. (($iExpectCode & OPT_ATT_MANDATORY) && ($oObj->Get($sAttCode) == '')) )
  1058. {
  1059. $aAttributesDef = MetaModel::ListAttributeDefs($sClass);
  1060. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1061. $aPrerequisites = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  1062. if (count($aPrerequisites) > 0)
  1063. {
  1064. // When 'enabling' a field, all its prerequisites must be enabled too
  1065. $sFieldList = "['".implode("','", $aPrerequisites)."']";
  1066. $oP->add_ready_script("$('#enable_{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, true); } );\n");
  1067. }
  1068. $aDependents = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  1069. if (count($aDependents) > 0)
  1070. {
  1071. // When 'disabling' a field, all its dependent fields must be disabled too
  1072. $sFieldList = "['".implode("','", $aDependents)."']";
  1073. $oP->add_ready_script("$('#enable_{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, false); } );\n");
  1074. }
  1075. $aArgs = array('this' => $oObj);
  1076. $sHTMLValue = cmdbAbstractObject::GetFormElementForField($oP, $sClass, $sAttCode, $oAttDef, $oObj->Get($sAttCode), $oObj->GetEditValue($sAttCode), $sAttCode, '', $iExpectCode, $aArgs);
  1077. $sComments = '<input type="checkbox" checked id="enable_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$sAttCode.'\')"/>';
  1078. if (!isset($aValues[$sAttCode]))
  1079. {
  1080. $aValues[$sAttCode] = array();
  1081. }
  1082. if (count($aValues[$sAttCode]) == 1)
  1083. {
  1084. $sComments .= '<div class="mono_value">1</div>';
  1085. }
  1086. else
  1087. {
  1088. // Non-homogenous value
  1089. $iMaxCount = 5;
  1090. $sTip = "<p><b>".Dict::Format('UI:BulkModify_Count_DistinctValues', count($aValues[$sAttCode]))."</b><ul>";
  1091. $index = 0;
  1092. foreach($aValues[$sAttCode] as $sCurrValue => $aVal)
  1093. {
  1094. $sDisplayValue = empty($aVal['display']) ? '<i>'.Dict::S('Enum:Undefined').'</i>' : str_replace(array("\n", "\r"), " ", $aVal['display']);
  1095. $sTip .= "<li>".Dict::Format('UI:BulkModify:Value_Exists_N_Times', $sDisplayValue, $aVal['count'])."</li>";
  1096. $index++;
  1097. if ($iMaxCount == $index)
  1098. {
  1099. $sTip .= "<li>".Dict::Format('UI:BulkModify:N_MoreValues', count($aValues[$sAttCode]) - $iMaxCount)."</li>";
  1100. break;
  1101. }
  1102. }
  1103. $sTip .= "</ul></p>";
  1104. $sTip = addslashes($sTip);
  1105. $sReadyScript .= "$('#multi_values_$sAttCode').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );\n";
  1106. $sComments .= '<div class="multi_values" id="multi_values_'.$sAttCode.'">'.count($aValues[$sAttCode]).'</div>';
  1107. }
  1108. $aDetails[] = array('label' => '<span>'.$oAttDef->GetLabel().'</span>', 'value' => "<span id=\"field_$sAttCode\">$sHTMLValue</span>", 'comments' => $sComments);
  1109. $aFieldsMap[$sAttCode] = $sAttCode;
  1110. $iFieldIndex++;
  1111. }
  1112. }
  1113. $sButtonsPosition = MetaModel::GetConfig()->Get('buttons_position');
  1114. if ($sButtonsPosition == 'bottom')
  1115. {
  1116. // bottom: Displays the ticket details BEFORE the actions
  1117. $oP->add('<div class="ui-widget-content">');
  1118. $oObj->DisplayBareProperties($oP);
  1119. $oP->add('</div>');
  1120. }
  1121. $oP->add("<div class=\"wizContainer\">\n");
  1122. $oP->add("<form id=\"apply_stimulus\" method=\"post\" onSubmit=\"return OnSubmit('apply_stimulus');\">\n");
  1123. $oP->add("<table><tr><td>\n");
  1124. $oP->details($aDetails);
  1125. $oP->add("</td></tr></table>\n");
  1126. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  1127. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"bulk_apply_stimulus\">\n");
  1128. $oP->add("<input type=\"hidden\" name=\"preview_mode\" value=\"1\">\n");
  1129. $oP->add("<input type=\"hidden\" name=\"filter\" value=\"$sFilter\">\n");
  1130. $oP->add("<input type=\"hidden\" name=\"stimulus\" value=\"$sStimulus\">\n");
  1131. $oP->add("<input type=\"hidden\" name=\"state\" value=\"$sState\">\n");
  1132. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  1133. $oP->add($oAppContext->GetForForm());
  1134. $oP->add("<input type=\"hidden\" name=\"selectObject\" value=\"".implode(',',$aSelectObject)."\">\n");
  1135. $sURL = "./UI.php?operation=search&filter=".urlencode($sFilter)."&".$oAppContext->GetForLink();
  1136. $oP->add("<input type=\"button\" value=\"".Dict::S('UI:Button:Cancel')."\" onClick=\"window.location.href='$sURL'\">&nbsp;&nbsp;&nbsp;&nbsp;\n");
  1137. $oP->add("<button type=\"submit\" class=\"action\"><span>$sActionLabel</span></button>\n");
  1138. $oP->add("</form>\n");
  1139. $oP->add("</div>\n");
  1140. if ($sButtonsPosition != 'bottom')
  1141. {
  1142. // top or both: Displays the ticket details AFTER the actions
  1143. $oP->add('<div class="ui-widget-content">');
  1144. $oObj->DisplayBareProperties($oP);
  1145. $oP->add('</div>');
  1146. }
  1147. $iFieldsCount = count($aFieldsMap);
  1148. $sJsonFieldsMap = json_encode($aFieldsMap);
  1149. $oP->add_script(
  1150. <<<EOF
  1151. // Initializes the object once at the beginning of the page...
  1152. var oWizardHelper = new WizardHelper('$sClass', '', '$sTargetState');
  1153. oWizardHelper.SetFieldsMap($sJsonFieldsMap);
  1154. oWizardHelper.SetFieldsCount($iFieldsCount);
  1155. EOF
  1156. );
  1157. $oP->add_ready_script(
  1158. <<<EOF
  1159. // Starts the validation when the page is ready
  1160. CheckFields('apply_stimulus', false);
  1161. $sReadyScript
  1162. EOF
  1163. );
  1164. }
  1165. break;
  1166. case 'bulk_apply_stimulus':
  1167. $bPreviewMode = utils::ReadPostedParam('preview_mode', false);
  1168. $sFilter = utils::ReadPostedParam('filter', '', false, 'raw_data');
  1169. $sStimulus = utils::ReadPostedParam('stimulus', '');
  1170. $sState = utils::ReadPostedParam('state', '');
  1171. $sSelectObject = utils::ReadPostedParam('selectObject', '', false, 'raw_data');
  1172. $aSelectObject = explode(',', $sSelectObject);
  1173. if (empty($sFilter) || empty($sStimulus) || empty($sState))
  1174. {
  1175. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state'));
  1176. }
  1177. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1178. if (!utils::IsTransactionValid($sTransactionId))
  1179. {
  1180. $oP->p(Dict::S('UI:Error:ObjectAlreadyUpdated'));
  1181. }
  1182. else
  1183. {
  1184. // For archiving the modification
  1185. $oFilter = DBObjectSearch::unserialize($sFilter);
  1186. $sClass = $oFilter->GetClass();
  1187. $aObjects = array();
  1188. foreach($aSelectObject as $iId)
  1189. {
  1190. $aObjects[] = MetaModel::GetObject($sClass, $iId);
  1191. }
  1192. $aTransitions = MetaModel::EnumTransitions($sClass, $sState);
  1193. $aStimuli = MetaModel::EnumStimuli($sClass);
  1194. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1195. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1196. $oP->set_title(Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aObjects), $sClass));
  1197. $oP->add('<div class="page_header">');
  1198. $oP->add('<h1>'.MetaModel::GetClassIcon($sClass).'&nbsp;'.Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aObjects), $sClass).'</h1>');
  1199. $oP->add('</div>');
  1200. $oSet = DBObjectSet::FromArray($sClass, $aObjects);
  1201. // For reporting
  1202. $aHeaders = array(
  1203. 'object' => array('label' => MetaModel::GetName($sClass), 'description' => Dict::S('UI:ModifiedObject')),
  1204. 'status' => array('label' => Dict::S('UI:BulkModifyStatus'), 'description' => Dict::S('UI:BulkModifyStatus+')),
  1205. 'errors' => array('label' => Dict::S('UI:BulkModifyErrors'), 'description' => Dict::S('UI:BulkModifyErrors+')),
  1206. );
  1207. $aRows = array();
  1208. while ($oObj = $oSet->Fetch())
  1209. {
  1210. $sError = Dict::S('UI:BulkModifyStatusOk');
  1211. try
  1212. {
  1213. $aTransitions = $oObj->EnumTransitions();
  1214. $aStimuli = MetaModel::EnumStimuli($sClass);
  1215. if (!isset($aTransitions[$sStimulus]))
  1216. {
  1217. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
  1218. }
  1219. else
  1220. {
  1221. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1222. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1223. $aTransition = $aTransitions[$sStimulus];
  1224. $sTargetState = $aTransition['target_state'];
  1225. $aTargetStates = MetaModel::EnumStates($sClass);
  1226. $aTargetState = $aTargetStates[$sTargetState];
  1227. $aExpectedAttributes = $aTargetState['attribute_list'];
  1228. $aDetails = array();
  1229. $aErrors = array();
  1230. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  1231. {
  1232. $iFlags = $oObj->GetAttributeFlags($sAttCode);
  1233. if (($iExpectCode & (OPT_ATT_MUSTCHANGE|OPT_ATT_MUSTPROMPT)) || ($oObj->Get($sAttCode) == '') )
  1234. {
  1235. $paramValue = utils::ReadPostedParam("attr_$sAttCode", '', 'raw_data');
  1236. if ( ($iFlags & OPT_ATT_SLAVE) && ($paramValue != $oObj->Get($sAttCode)) )
  1237. {
  1238. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1239. $aErrors[] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $oAttDef->GetLabel());
  1240. unset($aExpectedAttributes[$sAttCode]);
  1241. }
  1242. }
  1243. }
  1244. $oObj->UpdateObjectFromPostedForm('', array_keys($aExpectedAttributes), $sTargetState);
  1245. if (count($aErrors) == 0)
  1246. {
  1247. if ($oObj->ApplyStimulus($sStimulus))
  1248. {
  1249. list($bResult, $aErrors) = $oObj->CheckToWrite();
  1250. $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusModified') : Dict::S('UI:BulkModifyStatusSkipped');
  1251. if ($bResult)
  1252. {
  1253. $oObj->DBUpdate();
  1254. }
  1255. else
  1256. {
  1257. $sError = '<p>'.implode('</p></p>',$aErrors)."</p>\n";
  1258. }
  1259. }
  1260. else
  1261. {
  1262. $sStatus = Dict::S('UI:BulkModifyStatusSkipped');
  1263. $sError = '<p>'.Dict::S('UI:FailedToApplyStimuli')."<p>\n";
  1264. }
  1265. }
  1266. else
  1267. {
  1268. $sStatus = Dict::S('UI:BulkModifyStatusSkipped');
  1269. $sError = '<p>'.implode('</p></p>',$aErrors)."</p>\n";
  1270. }
  1271. }
  1272. }
  1273. catch(Exception $e)
  1274. {
  1275. $sError = $e->getMessage();
  1276. $sStatus = Dict::S('UI:BulkModifyStatusSkipped');
  1277. }
  1278. $aRows[] = array(
  1279. 'object' => $oObj->GetHyperlink(),
  1280. 'status' => $sStatus,
  1281. 'errors' => $sError,
  1282. );
  1283. }
  1284. $oP->Table($aHeaders, $aRows);
  1285. // Back to the list
  1286. $sURL = "./UI.php?operation=search&filter=".urlencode($sFilter)."&".$oAppContext->GetForLink();
  1287. $oP->add('<input type="button" onClick="window.location.href=\''.$sURL.'\'" value="'.Dict::S('UI:Button:Done').'">');
  1288. }
  1289. break;
  1290. case 'stimulus': // Form displayed when applying a stimulus (state change)
  1291. $sClass = utils::ReadParam('class', '', false, 'class');
  1292. $id = utils::ReadParam('id', '');
  1293. $sStimulus = utils::ReadParam('stimulus', '');
  1294. if ( empty($sClass) || empty($id) || empty($sStimulus) ) // TO DO: check that the class name is valid !
  1295. {
  1296. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'class', 'id', 'stimulus'));
  1297. }
  1298. $oObj = MetaModel::GetObject($sClass, $id, false);
  1299. if ($oObj != null)
  1300. {
  1301. $oObj->DisplayStimulusForm($oP, $sStimulus);
  1302. }
  1303. else
  1304. {
  1305. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  1306. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  1307. }
  1308. break;
  1309. ///////////////////////////////////////////////////////////////////////////////////////////
  1310. case 'apply_stimulus': // Actual state change
  1311. $sClass = utils::ReadPostedParam('class', '');
  1312. $id = utils::ReadPostedParam('id', '');
  1313. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1314. $sStimulus = utils::ReadPostedParam('stimulus', '');
  1315. if ( empty($sClass) || empty($id) || empty($sStimulus) ) // TO DO: check that the class name is valid !
  1316. {
  1317. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'class', 'id', 'stimulus'));
  1318. }
  1319. $oObj = MetaModel::GetObject($sClass, $id, false);
  1320. if ($oObj != null)
  1321. {
  1322. $aTransitions = $oObj->EnumTransitions();
  1323. $aStimuli = MetaModel::EnumStimuli($sClass);
  1324. $sMessage = '';
  1325. $sSeverity = 'ok';
  1326. $bDisplayDetails = true;
  1327. if (!isset($aTransitions[$sStimulus]))
  1328. {
  1329. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
  1330. }
  1331. if (!utils::IsTransactionValid($sTransactionId))
  1332. {
  1333. $sMessage = Dict::S('UI:Error:ObjectAlreadyUpdated');
  1334. $sSeverity = 'info';
  1335. }
  1336. else
  1337. {
  1338. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1339. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1340. $aTransition = $aTransitions[$sStimulus];
  1341. $sTargetState = $aTransition['target_state'];
  1342. $aTargetStates = MetaModel::EnumStates($sClass);
  1343. $aTargetState = $aTargetStates[$sTargetState];
  1344. $aExpectedAttributes = $aTargetState['attribute_list'];
  1345. $aDetails = array();
  1346. $aErrors = array();
  1347. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  1348. {
  1349. $iFlags = $oObj->GetAttributeFlags($sAttCode);
  1350. if (($iExpectCode & (OPT_ATT_MUSTCHANGE|OPT_ATT_MUSTPROMPT)) || ($oObj->Get($sAttCode) == '') )
  1351. {
  1352. $paramValue = utils::ReadPostedParam("attr_$sAttCode", '', 'raw_data');
  1353. if ( ($iFlags & OPT_ATT_SLAVE) && ($paramValue != $oObj->Get($sAttCode)))
  1354. {
  1355. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1356. $aErrors[] = Dict::Format('UI:AttemptingToChangeASlaveAttribute_Name', $oAttDef->GetLabel());
  1357. unset($aExpectedAttributes[$sAttCode]);
  1358. }
  1359. }
  1360. }
  1361. $oObj->UpdateObjectFromPostedForm('', array_keys($aExpectedAttributes), $sTargetState);
  1362. if (count($aErrors) == 0)
  1363. {
  1364. $sIssues = '';
  1365. $bApplyStimulus = true;
  1366. list($bRes, $aIssues) = $oObj->CheckToWrite(); // Check before trying to write the object
  1367. if ($bRes)
  1368. {
  1369. try
  1370. {
  1371. $bApplyStimulus = $oObj->ApplyStimulus($sStimulus); // will write the object in the DB
  1372. }
  1373. catch(CoreException $e)
  1374. {
  1375. // Rollback to the previous state... by reloading the object from the database and applying the modifications again
  1376. $oObj = MetaModel::GetObject(get_class($oObj), $oObj->GetKey());
  1377. $oObj->UpdateObjectFromPostedForm('', array_keys($aExpectedAttributes), $sTargetState);
  1378. $aData = $e->getContextData();
  1379. $sIssues = (array_key_exists('issues', $aData)) ? $aData['issues'] : 'Unknown error...';
  1380. }
  1381. }
  1382. else
  1383. {
  1384. $sIssues = implode(' ', $aIssues);
  1385. }
  1386. if (!$bApplyStimulus)
  1387. {
  1388. $sMessage = Dict::S('UI:FailedToApplyStimuli');
  1389. $sSeverity = 'error';
  1390. }
  1391. else if ($sIssues != '')
  1392. {
  1393. $bDisplayDetails = false;
  1394. // Found issues, explain and give the user a second chance
  1395. //
  1396. $oObj->DisplayStimulusForm($oP, $sStimulus);
  1397. $sIssueDesc = Dict::Format('UI:ObjectCouldNotBeWritten',$sIssues);
  1398. $oP->add_ready_script("alert('".addslashes($sIssueDesc)."');");
  1399. }
  1400. else
  1401. {
  1402. $sMessage = Dict::Format('UI:Class_Object_Updated', MetaModel::GetName(get_class($oObj)), $oObj->GetName());
  1403. $sSeverity = 'ok';
  1404. utils::RemoveTransaction($sTransactionId);
  1405. }
  1406. }
  1407. else
  1408. {
  1409. $sMessage = implode('</p><p>', $aErrors);
  1410. $sSeverity = 'error';
  1411. }
  1412. }
  1413. if ($bDisplayDetails)
  1414. {
  1415. ReloadAndDisplay($oP, $oObj, 'apply_stimulus', $sMessage, $sSeverity);
  1416. }
  1417. }
  1418. else
  1419. {
  1420. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  1421. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  1422. }
  1423. break;
  1424. ///////////////////////////////////////////////////////////////////////////////////////////
  1425. case 'swf_navigator': // Graphical display of the relations "impact" / "depends on"
  1426. $sClass = utils::ReadParam('class', '', false, 'class');
  1427. $id = utils::ReadParam('id', 0);
  1428. $sRelation = utils::ReadParam('relation', 'impact');
  1429. $aResults = array();
  1430. $oObj = MetaModel::GetObject($sClass, $id);
  1431. $iMaxRecursionDepth = MetaModel::GetConfig()->Get('relations_max_depth', 20);
  1432. $oObj->GetRelatedObjects($sRelation, $iMaxRecursionDepth /* iMaxDepth */, $aResults);
  1433. $oP->AddTabContainer('Navigator');
  1434. $oP->SetCurrentTabContainer('Navigator');
  1435. $sFirstTab = MetaModel::GetConfig()->Get('impact_analysis_first_tab');
  1436. if ($sFirstTab == 'list')
  1437. {
  1438. DisplayNavigatorListTab($oP, $aResults, $sRelation, $oObj);
  1439. DisplayNavigatorGraphicsTab($oP, $aResults, $sClass, $id, $sRelation, $oAppContext);
  1440. }
  1441. else
  1442. {
  1443. DisplayNavigatorGraphicsTab($oP, $aResults, $sClass, $id, $sRelation, $oAppContext);
  1444. DisplayNavigatorListTab($oP, $aResults, $sRelation, $oObj);
  1445. }
  1446. $oP->SetCurrentTab('');
  1447. break;
  1448. ///////////////////////////////////////////////////////////////////////////////////////////
  1449. case 'cancel': // An action was cancelled
  1450. $oP->set_title(Dict::S('UI:OperationCancelled'));
  1451. $oP->add('<h1>'.Dict::S('UI:OperationCancelled').'</h1>');
  1452. break;
  1453. ///////////////////////////////////////////////////////////////////////////////////////////
  1454. default: // Menu node rendering (templates)
  1455. ApplicationMenu::LoadAdditionalMenus();
  1456. $oMenuNode = ApplicationMenu::GetMenuNode(ApplicationMenu::GetMenuIndexById(ApplicationMenu::GetActiveNodeId()));
  1457. if (is_object($oMenuNode))
  1458. {
  1459. $oMenuNode->RenderContent($oP, $oAppContext->GetAsHash());
  1460. $oP->set_title($oMenuNode->GetLabel());
  1461. }
  1462. ///////////////////////////////////////////////////////////////////////////////////////////
  1463. }
  1464. DisplayWelcomePopup($oP);
  1465. $oP->output();
  1466. }
  1467. catch(CoreException $e)
  1468. {
  1469. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  1470. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  1471. if ($e instanceof SecurityException)
  1472. {
  1473. $oP->add("<h1>".Dict::S('UI:SystemIntrusion')."</h1>\n");
  1474. }
  1475. else
  1476. {
  1477. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  1478. }
  1479. $oP->error(Dict::Format('UI:Error_Details', $e->getHtmlDesc()));
  1480. $oP->output();
  1481. if (MetaModel::IsLogEnabledIssue())
  1482. {
  1483. if (MetaModel::IsValidClass('EventIssue'))
  1484. {
  1485. try
  1486. {
  1487. $oLog = new EventIssue();
  1488. $oLog->Set('message', $e->getMessage());
  1489. $oLog->Set('userinfo', '');
  1490. $oLog->Set('issue', $e->GetIssue());
  1491. $oLog->Set('impact', 'Page could not be displayed');
  1492. $oLog->Set('callstack', $e->getTrace());
  1493. $oLog->Set('data', $e->getContextData());
  1494. $oLog->DBInsertNoReload();
  1495. }
  1496. catch(Exception $e)
  1497. {
  1498. IssueLog::Error("Failed to log issue into the DB");
  1499. }
  1500. }
  1501. IssueLog::Error($e->getMessage());
  1502. }
  1503. // For debugging only
  1504. //throw $e;
  1505. }
  1506. catch(Exception $e)
  1507. {
  1508. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  1509. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  1510. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  1511. $oP->error(Dict::Format('UI:Error_Details', $e->getMessage()));
  1512. $oP->output();
  1513. if (MetaModel::IsLogEnabledIssue())
  1514. {
  1515. if (MetaModel::IsValidClass('EventIssue'))
  1516. {
  1517. try
  1518. {
  1519. $oLog = new EventIssue();
  1520. $oLog->Set('message', $e->getMessage());
  1521. $oLog->Set('userinfo', '');
  1522. $oLog->Set('issue', 'PHP Exception');
  1523. $oLog->Set('impact', 'Page could not be displayed');
  1524. $oLog->Set('callstack', $e->getTrace());
  1525. $oLog->Set('data', array());
  1526. $oLog->DBInsertNoReload();
  1527. }
  1528. catch(Exception $e)
  1529. {
  1530. IssueLog::Error("Failed to log issue into the DB");
  1531. }
  1532. }
  1533. IssueLog::Error($e->getMessage());
  1534. }
  1535. }
  1536. ?>