UI.php 68 KB

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