UI.php 63 KB

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