UI.php 68 KB

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