UI.php 65 KB

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