UI.php 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * Main page of iTop
  18. *
  19. * @author Erwan Taloc <erwan.taloc@combodo.com>
  20. * @author Romain Quetiez <romain.quetiez@combodo.com>
  21. * @author Denis Flaven <denis.flaven@combodo.com>
  22. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  23. */
  24. /**
  25. * Perform all the needed checks to delete one (or more) objects
  26. */
  27. function DeleteObjects(WebPage $oP, $sClass, $aObjects, $bDeleteConfirmed)
  28. {
  29. $oDeletionPlan = new DeletionPlan();
  30. foreach($aObjects as $oObj)
  31. {
  32. if ($bDeleteConfirmed)
  33. {
  34. // Prepare the change reporting
  35. //
  36. $oMyChange = MetaModel::NewObject("CMDBChange");
  37. $oMyChange->Set("date", time());
  38. $sUserString = CMDBChange::GetCurrentUserName();
  39. $oMyChange->Set("userinfo", $sUserString);
  40. $oMyChange->DBInsert();
  41. $oObj->DBDeleteTracked($oMyChange, null, $oDeletionPlan);
  42. }
  43. else
  44. {
  45. $oObj->CheckToDelete($oDeletionPlan);
  46. }
  47. }
  48. if ($bDeleteConfirmed)
  49. {
  50. if (count($aObjects) == 1)
  51. {
  52. $oObj = $aObjects[0];
  53. $oP->add("<h1>".Dict::Format('UI:Title:DeletionOf_Object', $oObj->GetName())."</h1>\n");
  54. }
  55. else
  56. {
  57. $oP->add("<h1>".Dict::Format('UI:Title:BulkDeletionOf_Count_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass))."</h1>\n");
  58. }
  59. // Security - do not allow the user to force a forbidden delete by the mean of page arguments...
  60. if ($oDeletionPlan->FoundSecurityIssue())
  61. {
  62. throw new CoreException(Dict::S('UI:Error:NotEnoughRightsToDelete'));
  63. }
  64. if ($oDeletionPlan->FoundManualOperation())
  65. {
  66. throw new CoreException(Dict::S('UI:Error:CannotDeleteBecauseManualOpNeeded'));
  67. }
  68. if ($oDeletionPlan->FoundManualDelete())
  69. {
  70. throw new CoreException(Dict::S('UI:Error:CannotDeleteBecauseOfDepencies'));
  71. }
  72. // Report deletions
  73. //
  74. $aDisplayData = array();
  75. foreach ($oDeletionPlan->ListDeletes() as $sTargetClass => $aDeletes)
  76. {
  77. foreach ($aDeletes as $iId => $aData)
  78. {
  79. $oToDelete = $aData['to_delete'];
  80. if (isset($aData['requested_explicitely']))
  81. {
  82. $sMessage = Dict::S('UI:Delete:Deleted');
  83. }
  84. else
  85. {
  86. $sMessage = Dict::S('UI:Delete:AutomaticallyDeleted');
  87. }
  88. $aDisplayData[] = array(
  89. 'class' => MetaModel::GetName(get_class($oToDelete)),
  90. 'object' => $oToDelete->GetName(),
  91. 'consequence' => $sMessage,
  92. );
  93. }
  94. }
  95. // Report updates
  96. //
  97. foreach ($oDeletionPlan->ListUpdates() as $sTargetClass => $aToUpdate)
  98. {
  99. foreach ($aToUpdate as $iId => $aData)
  100. {
  101. $oToUpdate = $aData['to_reset'];
  102. $aDisplayData[] = array(
  103. 'class' => MetaModel::GetName(get_class($oToUpdate)),
  104. 'object' => $oToUpdate->GetHyperLink(),
  105. 'consequence' => Dict::Format('UI:Delete:AutomaticResetOf_Fields', $aData['attributes_list']),
  106. );
  107. }
  108. }
  109. // Report automatic jobs
  110. //
  111. if ($oDeletionPlan->GetTargetCount() > 0)
  112. {
  113. if (count($aObjects) == 1)
  114. {
  115. $oObj = $aObjects[0];
  116. $oP->p(Dict::Format('UI:Delete:CleaningUpRefencesTo_Object', $oObj->GetName()));
  117. }
  118. else
  119. {
  120. $oP->p(Dict::Format('UI:Delete:CleaningUpRefencesTo_Several_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass)));
  121. }
  122. $aDisplayConfig = array();
  123. $aDisplayConfig['class'] = array('label' => 'Class', 'description' => '');
  124. $aDisplayConfig['object'] = array('label' => 'Object', 'description' => '');
  125. $aDisplayConfig['consequence'] = array('label' => 'Done', 'description' => Dict::S('UI:Delete:Done+'));
  126. $oP->table($aDisplayConfig, $aDisplayData);
  127. }
  128. }
  129. else
  130. {
  131. if (count($aObjects) == 1)
  132. {
  133. $oObj = $aObjects[0];
  134. $oP->add("<h1>".Dict::Format('UI:Delete:ConfirmDeletionOf_Name', $oObj->GetName())."</h1>\n");
  135. }
  136. else
  137. {
  138. $oP->add("<h1>".Dict::Format('UI:Delete:ConfirmDeletionOf_Count_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass))."</h1>\n");
  139. }
  140. // Explain what should be done
  141. //
  142. $aDisplayData = array();
  143. foreach ($oDeletionPlan->ListDeletes() as $sTargetClass => $aDeletes)
  144. {
  145. foreach ($aDeletes as $iId => $aData)
  146. {
  147. $oToDelete = $aData['to_delete'];
  148. $bAutoDel = (($aData['mode'] == DEL_SILENT) || ($aData['mode'] == DEL_AUTO));
  149. if (array_key_exists('issue', $aData))
  150. {
  151. if ($bAutoDel)
  152. {
  153. if (isset($aData['requested_explicitely']))
  154. {
  155. $sConsequence = Dict::Format('UI:Delete:CannotDeleteBecause', $aData['issue']);
  156. }
  157. else
  158. {
  159. $sConsequence = Dict::Format('UI:Delete:ShouldBeDeletedAtomaticallyButNotPossible', $aData['issue']);
  160. }
  161. }
  162. else
  163. {
  164. $sConsequence = Dict::Format('UI:Delete:MustBeDeletedManuallyButNotPossible', $aData['issue']);
  165. }
  166. }
  167. else
  168. {
  169. if ($bAutoDel)
  170. {
  171. if (isset($aData['requested_explicitely']))
  172. {
  173. $sConsequence = ''; // not applicable
  174. }
  175. else
  176. {
  177. $sConsequence = Dict::S('UI:Delete:WillBeDeletedAutomatically');
  178. }
  179. }
  180. else
  181. {
  182. $sConsequence = Dict::S('UI:Delete:MustBeDeletedManually');
  183. }
  184. }
  185. $aDisplayData[] = array(
  186. 'class' => MetaModel::GetName(get_class($oToDelete)),
  187. 'object' => $oToDelete->GetHyperLink(),
  188. 'consequence' => $sConsequence,
  189. );
  190. }
  191. }
  192. foreach ($oDeletionPlan->ListUpdates() as $sRemoteClass => $aToUpdate)
  193. {
  194. foreach ($aToUpdate as $iId => $aData)
  195. {
  196. $oToUpdate = $aData['to_reset'];
  197. if (array_key_exists('issue', $aData))
  198. {
  199. $sConsequence = Dict::Format('UI:Delete:CannotUpdateBecause_Issue', $aData['issue']);
  200. }
  201. else
  202. {
  203. $sConsequence = Dict::Format('UI:Delete:WillAutomaticallyUpdate_Fields', $aData['attributes_list']);
  204. }
  205. $aDisplayData[] = array(
  206. 'class' => MetaModel::GetName(get_class($oToUpdate)),
  207. 'object' => $oToUpdate->GetHyperLink(),
  208. 'consequence' => $sConsequence,
  209. );
  210. }
  211. }
  212. $iImpactedIndirectly = $oDeletionPlan->GetTargetCount() - count($aObjects);
  213. if ($iImpactedIndirectly > 0)
  214. {
  215. if (count($aObjects) == 1)
  216. {
  217. $oObj = $aObjects[0];
  218. $oP->p(Dict::Format('UI:Delete:Count_Objects/LinksReferencing_Object', $iImpactedIndirectly, $oObj->GetName()));
  219. }
  220. else
  221. {
  222. $oP->p(Dict::Format('UI:Delete:Count_Objects/LinksReferencingTheObjects', $iImpactedIndirectly));
  223. }
  224. $oP->p(Dict::S('UI:Delete:ReferencesMustBeDeletedToEnsureIntegrity'));
  225. }
  226. if (($iImpactedIndirectly > 0) || $oDeletionPlan->FoundStopper())
  227. {
  228. $aDisplayConfig = array();
  229. $aDisplayConfig['class'] = array('label' => 'Class', 'description' => '');
  230. $aDisplayConfig['object'] = array('label' => 'Object', 'description' => '');
  231. $aDisplayConfig['consequence'] = array('label' => 'Consequence', 'description' => Dict::S('UI:Delete:Consequence+'));
  232. $oP->table($aDisplayConfig, $aDisplayData);
  233. }
  234. if ($oDeletionPlan->FoundStopper())
  235. {
  236. if ($oDeletionPlan->FoundSecurityIssue())
  237. {
  238. $oP->p(Dict::S('UI:Delete:SorryDeletionNotAllowed'));
  239. }
  240. elseif ($oDeletionPlan->FoundManualOperation())
  241. {
  242. $oP->p(Dict::S('UI:Delete:PleaseDoTheManualOperations'));
  243. }
  244. else // $bFoundManualOp
  245. {
  246. $oP->p(Dict::S('UI:Delete:PleaseDoTheManualOperations'));
  247. }
  248. $oAppContext = new ApplicationContext();
  249. $oP->add("<form method=\"post\">\n");
  250. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::ReadParam('transaction_id')."\">\n");
  251. $oP->add("<input type=\"button\" onclick=\"window.history.back();\" value=\"".Dict::S('UI:Button:Back')."\">\n");
  252. $oP->add("<input DISABLED type=\"submit\" name=\"\" value=\"".Dict::S('UI:Button:Delete')."\">\n");
  253. $oP->add($oAppContext->GetForForm());
  254. $oP->add("</form>\n");
  255. }
  256. else
  257. {
  258. $oAppContext = new ApplicationContext();
  259. if (count($aObjects) == 1)
  260. {
  261. $oObj = $aObjects[0];
  262. $id = $oObj->GetKey();
  263. $oP->p('<h1>'.Dict::Format('UI:Delect:Confirm_Object', $oObj->GetHyperLink()).'</h1>');
  264. $oP->add("<form method=\"post\">\n");
  265. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::ReadParam('transaction_id')."\">\n");
  266. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"delete_confirmed\">\n");
  267. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  268. $oP->add("<input type=\"hidden\" name=\"id\" value=\"$id\">\n");
  269. $oP->add("<input type=\"button\" onclick=\"window.history.back();\" value=\"".Dict::S('UI:Button:Back')."\">\n");
  270. $oP->add("<input type=\"submit\" name=\"\" value=\"".Dict::S('UI:Button:Delete')."\">\n");
  271. $oP->add($oAppContext->GetForForm());
  272. $oP->add("</form>\n");
  273. }
  274. else
  275. {
  276. $oP->p('<h1>'.Dict::Format('UI:Delect:Confirm_Count_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass)).'</h1>');
  277. foreach($aObjects as $oObj)
  278. {
  279. $aKeys[] = $oObj->GetKey();
  280. }
  281. $oFilter = new DBObjectSearch($sClass);
  282. $oFilter->AddCondition('id', $aKeys, 'IN');
  283. $oSet = new CMDBobjectSet($oFilter);
  284. $oP->add('<div id="0">');
  285. CMDBAbstractObject::DisplaySet($oP, $oSet, array('display_limit' => false, 'menu' => false));
  286. $oP->add("</div>\n");
  287. $oP->add("<form method=\"post\">\n");
  288. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::ReadParam('transaction_id')."\">\n");
  289. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"bulk_delete_confirmed\">\n");
  290. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  291. foreach($aObjects as $oObj)
  292. {
  293. $oP->add("<input type=\"hidden\" name=\"selectObject[]\" value=\"".$oObj->GetKey()."\">\n");
  294. }
  295. $oP->add("<input type=\"button\" onclick=\"window.history.back();\" value=\"".Dict::S('UI:Button:Back')."\">\n");
  296. $oP->add("<input type=\"submit\" name=\"\" value=\"".Dict::S('UI:Button:Delete')."\">\n");
  297. $oP->add($oAppContext->GetForForm());
  298. $oP->add("</form>\n");
  299. }
  300. }
  301. }
  302. }
  303. /**
  304. * Displays a popup welcome message, once per session at maximum
  305. * until the user unchecks the "Display welcome at startup"
  306. * @param WebPage $oP The current web page for the display
  307. * @return void
  308. */
  309. function DisplayWelcomePopup(WebPage $oP)
  310. {
  311. if (!isset($_SESSION['welcome']))
  312. {
  313. // Check, only once per session, if the popup should be displayed...
  314. // If the user did not already ask for hiding it forever
  315. $bPopup = appUserPreferences::GetPref('welcome_popup', true);
  316. if ($bPopup)
  317. {
  318. $sTemplate = @file_get_contents('../application/templates/welcome_popup.html');
  319. if ($sTemplate !== false)
  320. {
  321. $oTemplate = new DisplayTemplate($sTemplate);
  322. $oP->add("<div id=\"welcome_popup\">");
  323. $oTemplate->Render($oP, array());
  324. $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");
  325. $oP->add("<p style=\"float:right\"><input type=\"button\" value=\"".Dict::S('UI:Button:Ok')."\" onClick=\"$('#welcome_popup').dialog('close');\"/>\n");
  326. $oP->add("</div>\n");
  327. $sTitle = addslashes(Dict::S('UI:WelcomeMenu:Title'));
  328. $oP->add_ready_script(
  329. <<<EOF
  330. $('#welcome_popup').dialog( { width:'80%', height: 'auto', title: '$sTitle', autoOpen: true, modal:true,
  331. close: function() {
  332. var bDisplay = $('#display_welcome_popup:checked').length;
  333. SetUserPreference('welcome_popup', bDisplay, true);
  334. }
  335. });
  336. if ($('#welcome_popup').height() > ($(window).height()-70))
  337. {
  338. $('#welcome_popup').height($(window).height()-70);
  339. }
  340. EOF
  341. );
  342. $_SESSION['welcome'] = 'ok';
  343. }
  344. }
  345. }
  346. }
  347. /**
  348. * Apply the 'next-action' to the given object or redirect to the page that prompts for additional information if needed
  349. * @param $oP WebPage The page for the output
  350. * @param $oObj CMDBObject The object to process
  351. * @param $sNextAction string The code of the stimulus for the 'action' (i.e. Transition) to apply
  352. * @param $oMyChange CMDBChange The change used to log the modifications or null is none is available (a new one will be created)
  353. */
  354. function ApplyNextAction(Webpage $oP, CMDBObject $oObj, $sNextAction, $oMyChange)
  355. {
  356. // Here handle the apply stimulus
  357. $aTransitions = $oObj->EnumTransitions();
  358. $aStimuli = MetaModel::EnumStimuli(get_class($oObj));
  359. if (!isset($aTransitions[$sNextAction]))
  360. {
  361. // Invalid stimulus
  362. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sNextAction, $oObj->GetName(), $oObj->GetStateLabel()));
  363. }
  364. // 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)
  365. $aExpectedAttributes = $oObj->GetExpectedAttributes($oObj->GetState(), $sNextAction, true /* $bOnlyNewOnes */);
  366. if (count($aExpectedAttributes) == 0)
  367. {
  368. // If all the mandatory fields are already present, just apply the transition silently...
  369. if ($oObj->ApplyStimulus($sNextAction))
  370. {
  371. if ($oMyChange == null)
  372. {
  373. $oMyChange = MetaModel::NewObject("CMDBChange");
  374. $oMyChange->Set("date", time());
  375. $sUserString = CMDBChange::GetCurrentUserName();
  376. $oMyChange->Set("userinfo", $sUserString);
  377. $iChangeId = $oMyChange->DBInsert();
  378. }
  379. $oObj->DBUpdateTracked($oMyChange);
  380. }
  381. $oObj->DisplayDetails($oP);
  382. }
  383. else
  384. {
  385. // redirect to the 'stimulus' action
  386. $oAppContext = new ApplicationContext();
  387. //echo "<p>Missing Attributes <pre>".print_r($aExpectedAttributes, true)."</pre></p>\n";
  388. $oP->add_header('Location: '.utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=stimulus&class='.get_class($oObj).'&stimulus='.$sNextAction.'&id='.$oObj->getKey().'&'.$oAppContext->GetForLink());
  389. }
  390. }
  391. /**
  392. * Displays the details of an object
  393. * @param $oP WebPage Page for the output
  394. * @param $sClass string The name of the class of the object
  395. * @param $oObj DBObject The object to display
  396. * @param $id mixed Identifier of the object (name or ID)
  397. */
  398. function DisplayDetails($oP, $sClass, $oObj, $id)
  399. {
  400. $sClassLabel = MetaModel::GetName($sClass);
  401. $oSearch = new DBObjectSearch($sClass);
  402. $oBlock = new DisplayBlock($oSearch, 'search', false);
  403. $oBlock->Display($oP, 0);
  404. // The object could be listed, check if it is actually allowed to view it
  405. $oSet = CMDBObjectSet::FromObject($oObj);
  406. if (UserRights::IsActionAllowed($sClass, UR_ACTION_READ, $oSet) == UR_ALLOWED_NO)
  407. {
  408. throw new SecurityException('User not allowed to view this object', array('class' => $sClass, 'id' => $id));
  409. }
  410. $oP->set_title(Dict::Format('UI:DetailsPageTitle', $oObj->GetName(), $sClassLabel));
  411. $oObj->DisplayDetails($oP);
  412. }
  413. /**
  414. * Displays the result of a search request
  415. * @param $oP WebPage Web page for the output
  416. * @param $oFilter DBObjectSearch The search of objects to display
  417. * @param $bSearchForm boolean Whether or not to display the search form at the top the page
  418. * @param $sBaseClass string The base class for the search (can be different from the actual class of the results)
  419. * @param $sFormat string The format to use for the output: csv or html
  420. */
  421. function DisplaySearchSet($oP, $oFilter, $bSearchForm = true, $sBaseClass = '', $sFormat = '')
  422. {
  423. $oSet = new DBObjectSet($oFilter);
  424. if ($bSearchForm)
  425. {
  426. $aParams = array('open' => true);
  427. if (!empty($sBaseClass))
  428. {
  429. $aParams['baseClass'] = $sBaseClass;
  430. }
  431. $oBlock = new DisplayBlock($oFilter, 'search', false /* Asynchronous */, $aParams);
  432. $oBlock->Display($oP, 0);
  433. }
  434. if (strtolower($sFormat) == 'csv')
  435. {
  436. $oBlock = new DisplayBlock($oFilter, 'csv', false);
  437. $oBlock->Display($oP, 1);
  438. // Adjust the size of the Textarea containing the CSV to fit almost all the remaining space
  439. $oP->add_ready_script(" $('#1>textarea').height($('#1').parent().height() - $('#0').outerHeight() - 30).width( $('#1').parent().width() - 20);"); // adjust the size of the block
  440. }
  441. else
  442. {
  443. $oBlock = new DisplayBlock($oFilter, 'list', false);
  444. $oBlock->Display($oP, 1);
  445. }
  446. }
  447. /**
  448. * Displays a form (checkboxes) to select the objects for which to apply a given action
  449. * Only the objects for which the action is valid can be checked. By default all valid objects are checked
  450. * @param $oP WebPage The page for output
  451. * @param $oFilter DBObjectSearch The filter that defines the list of objects
  452. * @param $sNextOperation string The next operation (code) to be executed when the form is submitted
  453. * @param $oChecker ActionChecker The helper class/instance used to check for which object the action is valid
  454. * @return none
  455. */
  456. function DisplayMultipleSelectionForm($oP, $oFilter, $sNextOperation, $oChecker, $aExtraFormParams = array())
  457. {
  458. $oAppContext = new ApplicationContext();
  459. $iBulkActionAllowed = $oChecker->IsAllowed();
  460. $sClass = $oFilter->GetClass();
  461. $aExtraParams = array('selection_type' => 'multiple', 'selection_mode' => true, 'display_limit' => false, 'menu' => false);
  462. if ($iBulkActionAllowed == UR_ALLOWED_DEPENDS)
  463. {
  464. $aAllowed = array();
  465. $aExtraParams['selection_enabled'] = $oChecker->GetAllowedIDs();
  466. }
  467. else if(UR_ALLOWED_NO)
  468. {
  469. throw new ApplicationException(Dict::Format('UI:ActionNotAllowed'));
  470. }
  471. $oBlock = new DisplayBlock($oFilter, 'list', false);
  472. $oP->add("<form method=\"post\" action=\"./UI.php\">\n");
  473. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  474. $oP->add("<input type=\"hidden\" name=\"class\" value=\"".$oFilter->GetClass()."\">\n");
  475. $oP->add("<input type=\"hidden\" name=\"filter\" value=\"".$oFilter->Serialize()."\">\n");
  476. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  477. foreach($aExtraFormParams as $sName => $sValue)
  478. {
  479. $oP->add("<input type=\"hidden\" name=\"$sName\" value=\"$sValue\">\n");
  480. }
  481. $oP->add($oAppContext->GetForForm());
  482. $oBlock->Display($oP, 1, $aExtraParams);
  483. $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");
  484. $oP->add("</form>\n");
  485. $oP->add_ready_script(
  486. <<<EOF
  487. $(':checkbox[name^=selectObject]').change(function() {
  488. var v = $('#1 table.listResults :checkbox[name^=selectObject]:checked').length;
  489. $('#1 .selectedCount').text(v);
  490. });
  491. CheckAll('.selectList1:not(:disabled)', true);
  492. EOF
  493. );
  494. }
  495. /***********************************************************************************
  496. *
  497. * Main user interface page, starts here
  498. *
  499. * ***********************************************************************************/
  500. try
  501. {
  502. require_once('../approot.inc.php');
  503. require_once(APPROOT.'/application/application.inc.php');
  504. require_once(APPROOT.'/application/itopwebpage.class.inc.php');
  505. require_once(APPROOT.'/application/wizardhelper.class.inc.php');
  506. require_once(APPROOT.'/application/startup.inc.php');
  507. $operation = utils::ReadParam('operation', '');
  508. $oKPI = new ApplicationStartupKPI();
  509. $oKPI->ComputeAndReport('Load of data model and all includes');
  510. $oKPI = new ExecutionKPI();
  511. require_once(APPROOT.'/application/loginwebpage.class.inc.php');
  512. $sLoginMessage = LoginWebPage::DoLogin(); // Check user rights and prompt if needed
  513. $oAppContext = new ApplicationContext();
  514. $oKPI->ComputeAndReport('User login');
  515. $oP = new iTopWebPage(Dict::S('UI:WelcomeToITop'));
  516. $oP->SetMessage($sLoginMessage);
  517. // All the following actions use advanced forms that require more javascript to be loaded
  518. switch($operation)
  519. {
  520. case 'new': // Form to create a new object
  521. case 'modify': // Form to modify an object
  522. case 'apply_new': // Creation of a new object
  523. case 'apply_modify': // Applying the modifications to an existing object
  524. case 'form_for_modify_all': // Form to modify multiple objects (bulk modify)
  525. case 'bulk_stimulus': // For to apply a stimulus to multiple objects
  526. case 'stimulus': // Form displayed when applying a stimulus (state change)
  527. $oP->add_linked_script("../js/json.js");
  528. $oP->add_linked_script("../js/forms-json-utils.js");
  529. $oP->add_linked_script("../js/wizardhelper.js");
  530. $oP->add_linked_script("../js/wizard.utils.js");
  531. $oP->add_linked_script("../js/linkswidget.js");
  532. $oP->add_linked_script("../js/extkeywidget.js");
  533. $oP->add_linked_script("../js/jquery.blockUI.js");
  534. break;
  535. }
  536. switch($operation)
  537. {
  538. ///////////////////////////////////////////////////////////////////////////////////////////
  539. case 'details': // Details of an object
  540. $sClass = utils::ReadParam('class', '');
  541. $id = utils::ReadParam('id', '');
  542. if ( empty($sClass) || empty($id))
  543. {
  544. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'id'));
  545. }
  546. if (is_numeric($id))
  547. {
  548. $oObj = MetaModel::GetObject($sClass, $id, false /* MustBeFound */);
  549. }
  550. else
  551. {
  552. $oObj = MetaModel::GetObjectByName($sClass, $id, false /* MustBeFound */);
  553. }
  554. if (is_null($oObj))
  555. {
  556. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  557. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  558. }
  559. else
  560. {
  561. DisplayDetails($oP, $sClass, $oObj, $id);
  562. }
  563. break;
  564. ///////////////////////////////////////////////////////////////////////////////////////////
  565. case 'search_oql': // OQL query
  566. $sOQLClass = utils::ReadParam('oql_class', '', false, 'class');
  567. $sBaseClass = utils::ReadParam('base_class', $sOQLClass, false, 'class');
  568. $sOQLClause = utils::ReadParam('oql_clause', '', false, 'raw_data');
  569. $sFormat = utils::ReadParam('format', '');
  570. $bSearchForm = utils::ReadParam('search_form', true);
  571. $sTitle = utils::ReadParam('title', 'UI:SearchResultsPageTitle');
  572. if (empty($sOQLClass))
  573. {
  574. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'oql_class'));
  575. }
  576. $oP->set_title(Dict::S($sTitle));
  577. $oP->add('<h1>'.Dict::S($sTitle).'</h1>');
  578. $sOQL = "SELECT $sOQLClass $sOQLClause";
  579. try
  580. {
  581. $oFilter = DBObjectSearch::FromOQL($sOQL);
  582. DisplaySearchSet($oP, $oFilter, $bSearchForm, $sBaseClass, $sFormat);
  583. }
  584. catch(CoreException $e)
  585. {
  586. $oFilter = new DBObjectSearch($sOQLClass);
  587. $oSet = new DBObjectSet($oFilter);
  588. if ($bSearchForm)
  589. {
  590. $oBlock = new DisplayBlock($oFilter, 'search', false);
  591. $oBlock->Display($oP, 0);
  592. }
  593. $oP->P('<b>'.Dict::Format('UI:Error:IncorrectOQLQuery_Message', $e->getHtmlDesc()).'</b>');
  594. }
  595. catch(Exception $e)
  596. {
  597. $oP->P('<b>'.Dict::Format('UI:Error:AnErrorOccuredWhileRunningTheQuery_Message', $e->getMessage()).'</b>');
  598. }
  599. break;
  600. ///////////////////////////////////////////////////////////////////////////////////////////
  601. case 'search_form': // Search form
  602. $sClass = utils::ReadParam('class', '', false, 'class');
  603. $sFormat = utils::ReadParam('format', 'html');
  604. $bSearchForm = utils::ReadParam('search_form', true);
  605. if (empty($sClass))
  606. {
  607. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'class'));
  608. }
  609. $oP->set_title(Dict::S('UI:SearchResultsPageTitle'));
  610. $oFilter = new DBObjectSearch($sClass);
  611. DisplaySearchSet($oP, $oFilter, $bSearchForm, '' /* sBaseClass */, $sFormat);
  612. break;
  613. ///////////////////////////////////////////////////////////////////////////////////////////
  614. case 'search': // Serialized CMDBSearchFilter
  615. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  616. $sFormat = utils::ReadParam('format', '');
  617. $bSearchForm = utils::ReadParam('search_form', true);
  618. if (empty($sFilter))
  619. {
  620. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'filter'));
  621. }
  622. $oP->set_title(Dict::S('UI:SearchResultsPageTitle'));
  623. // TO DO: limit the search filter by the user context
  624. $oFilter = CMDBSearchFilter::unserialize($sFilter); // TO DO : check that the filter is valid
  625. DisplaySearchSet($oP, $oFilter, $bSearchForm, '' /* sBaseClass */, $sFormat);
  626. break;
  627. ///////////////////////////////////////////////////////////////////////////////////////////
  628. case 'full_text': // Global "google-like" search
  629. $sFullText = trim(utils::ReadParam('text', '', false, 'raw_data'));
  630. if (empty($sFullText))
  631. {
  632. $oP->p(Dict::S('UI:Search:NoSearch'));
  633. }
  634. else
  635. {
  636. $oP->set_title(Dict::S('UI:SearchResultsPageTitle'));
  637. $oP->p("<h1>".Dict::Format('UI:FullTextSearchTitle_Text', $sFullText)."</h1>");
  638. $iCount = 0;
  639. $iBlock = 0;
  640. // Search in full text mode in all the classes
  641. $aMatches = array();
  642. $sClassName = '';
  643. // Check if a class name/label is supplied to limit the search
  644. if (preg_match('/^(.+):(.+)$/', $sFullText, $aMatches))
  645. {
  646. $sClassName = $aMatches[1];
  647. if (MetaModel::IsValidClass($sClassName))
  648. {
  649. $sFullText = $aMatches[2];
  650. }
  651. elseif ($sClassName = MetaModel::GetClassFromLabel($sClassName, false /* => not case sensitive */))
  652. {
  653. $sFullText = $aMatches[2];
  654. }
  655. }
  656. if (preg_match('/^"(.*)"$/', $sFullText, $aMatches))
  657. {
  658. // The text is surrounded by double-quotes, remove the quotes and treat it as one single expression
  659. $aFullTextNeedles = array($aMatches[1]);
  660. }
  661. else
  662. {
  663. // Split the text on the blanks and treat this as a search for <word1> AND <word2> AND <word3>
  664. $aFullTextNeedles = explode(' ', $sFullText);
  665. }
  666. // Search is limited ot a given class, or not...
  667. if (empty($sClassName))
  668. {
  669. $aSearchClasses = MetaModel::GetClasses('searchable');
  670. }
  671. else
  672. {
  673. $aSearchClasses = MetaModel::EnumChildClasses($sClassName, ENUM_CHILD_CLASSES_ALL);
  674. }
  675. foreach($aSearchClasses as $sClassName)
  676. {
  677. $oFilter = new DBObjectSearch($sClassName);
  678. foreach($aFullTextNeedles as $sSearchText)
  679. {
  680. $oFilter->AddCondition_FullText($sSearchText);
  681. }
  682. $oSet = new DBObjectSet($oFilter);
  683. if ($oSet->Count() > 0)
  684. {
  685. $aLeafs = array();
  686. while($oObj = $oSet->Fetch())
  687. {
  688. if (get_class($oObj) == $sClassName)
  689. {
  690. $aLeafs[] = $oObj->GetKey();
  691. }
  692. }
  693. $oLeafsFilter = new DBObjectSearch($sClassName);
  694. if (count($aLeafs) > 0)
  695. {
  696. $iCount += count($aLeafs);
  697. $oP->add("<div class=\"page_header\">\n");
  698. $oP->add("<h2>".MetaModel::GetClassIcon($sClassName)."&nbsp;<span class=\"hilite\">".Dict::Format('UI:Search:Count_ObjectsOf_Class_Found', count($aLeafs), Metamodel::GetName($sClassName))."</h2>\n");
  699. $oP->add("</div>\n");
  700. $oLeafsFilter->AddCondition('id', $aLeafs, 'IN');
  701. $oBlock = new DisplayBlock($oLeafsFilter, 'list', false);
  702. $oBlock->Display($oP, $iBlock++);
  703. $oP->P('&nbsp;'); // Some space ?
  704. }
  705. }
  706. }
  707. if ($iCount == 0)
  708. {
  709. $oP->p(Dict::S('UI:Search:NoObjectFound'));
  710. }
  711. }
  712. break;
  713. ///////////////////////////////////////////////////////////////////////////////////////////
  714. case 'modify': // Form to modify an object
  715. $sClass = utils::ReadParam('class', '', false, 'class');
  716. $sClassLabel = MetaModel::GetName($sClass);
  717. $id = utils::ReadParam('id', '');
  718. if ( empty($sClass) || empty($id)) // TO DO: check that the class name is valid !
  719. {
  720. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'id'));
  721. }
  722. // Check if the user can modify this object
  723. $oObj = MetaModel::GetObject($sClass, $id, false /* MustBeFound */);
  724. if (is_null($oObj))
  725. {
  726. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  727. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  728. }
  729. else
  730. {
  731. // The object could be read - check if it is allowed to modify it
  732. $oSet = CMDBObjectSet::FromObject($oObj);
  733. if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet) == UR_ALLOWED_NO)
  734. {
  735. throw new SecurityException('User not allowed to modify this object', array('class' => $sClass, 'id' => $id));
  736. }
  737. // Note: code duplicated to the case 'apply_modify' when a data integrity issue has been found
  738. $oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetName(), $sClassLabel));
  739. $oP->add("<div class=\"page_header\">\n");
  740. $oP->add("<h1>".$oObj->GetIcon()."&nbsp;".Dict::Format('UI:ModificationTitle_Class_Object', $sClassLabel, $oObj->GetName())."</h1>\n");
  741. $oP->add("</div>\n");
  742. $oP->add("<div class=\"wizContainer\">\n");
  743. $oObj->DisplayModifyForm($oP);
  744. $oP->add("</div>\n");
  745. }
  746. break;
  747. ///////////////////////////////////////////////////////////////////////////////////////////
  748. case 'select_for_modify_all': // Select the list of objects to be modified (bulk modify)
  749. $oP->set_title(Dict::S('UI:ModifyAllPageTitle'));
  750. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  751. if (empty($sFilter))
  752. {
  753. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'filter'));
  754. }
  755. // TO DO: limit the search filter by the user context
  756. $oFilter = DBObjectSearch::unserialize($sFilter); // TO DO : check that the filter is valid
  757. $sClass = $oFilter->GetClass();
  758. $oChecker = new ActionChecker($oFilter, UR_ACTION_BULK_MODIFY);
  759. $oP->add("<h1>Modify All...</h1>\n");
  760. DisplayMultipleSelectionForm($oP, $oFilter, 'form_for_modify_all', $oChecker);
  761. break;
  762. ///////////////////////////////////////////////////////////////////////////////////////////
  763. case 'form_for_modify_all': // Form to modify multiple objects (bulk modify)
  764. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  765. $sClass = utils::ReadParam('class', '', false, 'class');
  766. $oFullSetFilter = DBObjectSearch::unserialize($sFilter);
  767. $aSelectedObj = utils::ReadMultipleSelection($oFullSetFilter);
  768. if (count($aSelectedObj) > 0)
  769. {
  770. $iAllowedCount = count($aSelectedObj);
  771. $sSelectedObj = implode(',', $aSelectedObj);
  772. $sOQL = "SELECT $sClass WHERE id IN (".$sSelectedObj.")";
  773. $oSet = new CMDBObjectSet(DBObjectSearch::FromOQL($sOQL));
  774. // Compute the distribution of the values for each field to determine which of the "scalar" fields are homogenous
  775. $aList = MetaModel::ListAttributeDefs($sClass);
  776. $aValues = array();
  777. foreach($aList as $sAttCode => $oAttDef)
  778. {
  779. if ($oAttDef->IsScalar())
  780. {
  781. $aValues[$sAttCode] = array();
  782. }
  783. }
  784. while($oObj = $oSet->Fetch())
  785. {
  786. foreach($aList as $sAttCode => $oAttDef)
  787. {
  788. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  789. {
  790. $currValue = $oObj->Get($sAttCode);
  791. if ($oAttDef instanceof AttributeCaseLog)
  792. {
  793. $currValue = '';
  794. }
  795. if (is_object($currValue)) continue; // Skip non scalar values...
  796. if(!array_key_exists($currValue, $aValues[$sAttCode]))
  797. {
  798. $aValues[$sAttCode][$currValue] = array('count' => 1, 'display' => $oObj->GetAsHTML($sAttCode));
  799. }
  800. else
  801. {
  802. $aValues[$sAttCode][$currValue]['count']++;
  803. }
  804. }
  805. }
  806. }
  807. // Now create an object that has values for the homogenous values only
  808. $oDummyObj = new $sClass(); // @@ What if the class is abstract ?
  809. $aComments = array();
  810. function MyComparison($a, $b) // Sort descending
  811. {
  812. if ($a['count'] == $b['count'])
  813. {
  814. return 0;
  815. }
  816. return ($a['count'] > $b['count']) ? -1 : 1;
  817. }
  818. $iFormId = cmdbAbstractObject::GetNextFormId(); // Identifier that prefixes all the form fields
  819. $sReadyScript = '';
  820. $aDependsOn = array();
  821. $sFormPrefix = '2_';
  822. foreach($aList as $sAttCode => $oAttDef)
  823. {
  824. $aPrerequisites = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  825. if (count($aPrerequisites) > 0)
  826. {
  827. // When 'enabling' a field, all its prerequisites must be enabled too
  828. $sFieldList = "['{$sFormPrefix}".implode("','{$sFormPrefix}", $aPrerequisites)."']";
  829. $oP->add_ready_script("$('#enable_{$sFormPrefix}{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, true); } );\n");
  830. }
  831. $aDependents = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  832. if (count($aDependents) > 0)
  833. {
  834. // When 'disabling' a field, all its dependent fields must be disabled too
  835. $sFieldList = "['{$sFormPrefix}".implode("','{$sFormPrefix}", $aDependents)."']";
  836. $oP->add_ready_script("$('#enable_{$sFormPrefix}{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, false); } );\n");
  837. }
  838. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  839. {
  840. if ($oAttDef->GetEditClass() == 'One Way Password')
  841. {
  842. $sTip = "Unknown values";
  843. $sReadyScript .= "$('#multi_values_$sAttCode').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );";
  844. $oDummyObj->Set($sAttCode, null);
  845. $aComments[$sAttCode] = '<input type="checkbox" id="enable_'.$iFormId.'_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$iFormId.'_'.$sAttCode.'\')"/>';
  846. $aComments[$sAttCode] .= '<div class="multi_values" id="multi_values_'.$sAttCode.'"> ? </div>';
  847. $sReadyScript .= 'ToogleField(false, \''.$iFormId.'_'.$sAttCode.'\');'."\n";
  848. }
  849. else
  850. {
  851. $iCount = count($aValues[$sAttCode]);
  852. if ($iCount == 1)
  853. {
  854. // Homogenous value
  855. reset($aValues[$sAttCode]);
  856. $aKeys = array_keys($aValues[$sAttCode]);
  857. $currValue = $aKeys[0]; // The only value is the first key
  858. //echo "<p>current value for $sAttCode : $currValue</p>";
  859. $oDummyObj->Set($sAttCode, $currValue);
  860. $aComments[$sAttCode] = '<input type="checkbox" checked id="enable_'.$iFormId.'_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$iFormId.'_'.$sAttCode.'\')"/>';
  861. $aComments[$sAttCode] .= '<div class="mono_value">1</div>';
  862. }
  863. else
  864. {
  865. // Non-homogenous value
  866. $aMultiValues = $aValues[$sAttCode];
  867. uasort($aMultiValues, 'MyComparison');
  868. $iMaxCount = 5;
  869. $sTip = "<p><b>".Dict::Format('UI:BulkModify_Count_DistinctValues', $iCount)."</b><ul>";
  870. $index = 0;
  871. foreach($aMultiValues as $sCurrValue => $aVal)
  872. {
  873. $sDisplayValue = empty($aVal['display']) ? '<i>'.Dict::S('Enum:Undefined').'</i>' : str_replace(array("\n", "\r"), " ", $aVal['display']);
  874. $sTip .= "<li>".Dict::Format('UI:BulkModify:Value_Exists_N_Times', $sDisplayValue, $aVal['count'])."</li>";
  875. $index++;
  876. if ($iMaxCount == $index)
  877. {
  878. $sTip .= "<li>".Dict::Format('UI:BulkModify:N_MoreValues', count($aMultiValues) - $iMaxCount)."</li>";
  879. break;
  880. }
  881. }
  882. $sTip .= "</ul></p>";
  883. $sReadyScript .= "$('#multi_values_$sAttCode').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );";
  884. $oDummyObj->Set($sAttCode, null);
  885. $aComments[$sAttCode] = '<input type="checkbox" id="enable_'.$iFormId.'_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$iFormId.'_'.$sAttCode.'\')"/>';
  886. $aComments[$sAttCode] .= '<div class="multi_values" id="multi_values_'.$sAttCode.'">'.$iCount.'</div>';
  887. }
  888. $sReadyScript .= 'ToogleField('.(($iCount == 1) ? 'true': 'false').', \''.$iFormId.'_'.$sAttCode.'\');'."\n";
  889. }
  890. }
  891. }
  892. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  893. if (($sStateAttCode != '') && ($oDummyObj->GetState() == ''))
  894. {
  895. // Hmmm, it's not gonna work like this ! Set a default value for the "state"
  896. // Maybe we should use the "state" that is the most common among the objects...
  897. $aMultiValues = $aValues[$sStateAttCode];
  898. uasort($aMultiValues, 'MyComparison');
  899. foreach($aMultiValues as $sCurrValue => $aVal)
  900. {
  901. $oDummyObj->Set($sStateAttCode, $sCurrValue);
  902. break;
  903. }
  904. //$oStateAtt = MetaModel::GetAttributeDef($sClass, $sStateAttCode);
  905. //$oDummyObj->Set($sStateAttCode, $oStateAtt->GetDefaultValue());
  906. }
  907. $oP->add("<div class=\"page_header\">\n");
  908. $oP->add("<h1>".$oDummyObj->GetIcon()."&nbsp;".Dict::Format('UI:Modify_M_ObjectsOf_Class_OutOf_N', $iAllowedCount, $sClass, $iAllowedCount)."</h1>\n");
  909. $oP->add("</div>\n");
  910. $oP->add("<div class=\"wizContainer\">\n");
  911. $oDummyObj->DisplayModifyForm($oP, array('fieldsComments' => $aComments, 'noRelations' => true, 'custom_operation' => 'preview_or_modify_all', 'custom_button' => Dict::S('UI:Button:PreviewModifications'), 'selectObj' => $sSelectedObj, 'filter' => $sFilter, 'preview_mode' => true, 'disabled_fields' => '{}'));
  912. $oP->add("</div>\n");
  913. $oP->add_ready_script($sReadyScript);
  914. $sURL = "./UI.php?operation=search&filter=$sFilter&".$oAppContext->GetForLink();
  915. $oP->add_ready_script(
  916. <<<EOF
  917. $('.wizContainer button.cancel').unbind('click');
  918. $('.wizContainer button.cancel').click( function() { window.location.href = '$sURL'; } );
  919. EOF
  920. );
  921. } // Else no object selected ???
  922. else
  923. {
  924. $oP->p("No object selected !, nothing to do");
  925. }
  926. break;
  927. ///////////////////////////////////////////////////////////////////////////////////////////
  928. case 'preview_or_modify_all': // Preview or apply bulk modify
  929. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  930. // TO DO: limit the search filter by the user context
  931. $oFilter = DBObjectSearch::unserialize($sFilter); // TO DO : check that the filter is valid
  932. $oChecker = new ActionChecker($oFilter, UR_ACTION_BULK_MODIFY);
  933. $sClass = utils::ReadParam('class', '', false, 'class');
  934. $bPreview = utils::ReadParam('preview_mode', '');
  935. $sSelectedObj = utils::ReadParam('selectObj', '', false, 'raw_data');
  936. if ( empty($sClass) || empty($sSelectedObj)) // TO DO: check that the class name is valid !
  937. {
  938. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'selectObj'));
  939. }
  940. $aSelectedObj = explode(',', $sSelectedObj);
  941. $aHeaders = array(
  942. 'form::select' => array('label' => "<input type=\"checkbox\" onClick=\"CheckAll('.selectList:not(:disabled)', this.checked);\"></input>", 'description' => Dict::S('UI:SelectAllToggle+')),
  943. 'object' => array('label' => MetaModel::GetName($sClass), 'description' => Dict::S('UI:ModifiedObject')),
  944. 'status' => array('label' => Dict::S('UI:BulkModifyStatus'), 'description' => Dict::S('UI:BulkModifyStatus+')),
  945. 'errors' => array('label' => Dict::S('UI:BulkModifyErrors'), 'description' => Dict::S('UI:BulkModifyErrors+')),
  946. );
  947. $aRows = array();
  948. $oP->add("<div class=\"page_header\">\n");
  949. $oP->add("<h1>".MetaModel::GetClassIcon($sClass)."&nbsp;".Dict::Format('UI:Modify_N_ObjectsOf_Class', count($aSelectedObj), $sClass)."</h1>\n");
  950. $oP->add("</div>\n");
  951. $oP->set_title(Dict::Format('UI:Modify_N_ObjectsOf_Class', count($aSelectedObj), $sClass));
  952. if (!$bPreview)
  953. {
  954. // Not in preview mode, do the update for real
  955. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  956. if (!utils::IsTransactionValid($sTransactionId, false))
  957. {
  958. throw new Exception(Dict::S('UI:Error:ObjectAlreadyUpdated'));
  959. }
  960. $oMyChange = MetaModel::NewObject("CMDBChange");
  961. $oMyChange->Set("date", time());
  962. $sUserString = CMDBChange::GetCurrentUserName();
  963. $oMyChange->Set("userinfo", $sUserString);
  964. $iChangeId = $oMyChange->DBInsert();
  965. utils::RemoveTransaction($sTransactionId);
  966. }
  967. foreach($aSelectedObj as $iId)
  968. {
  969. $oObj = MetaModel::GetObject($sClass, $iId);
  970. $aErrors = $oObj->UpdateObjectFromPostedForm('');
  971. $bResult = (count($aErrors) == 0);
  972. if ($bResult)
  973. {
  974. list($bResult, $aErrors) = $oObj->CheckToWrite(true /* Enforce Read-only fields */);
  975. }
  976. if ($bPreview)
  977. {
  978. $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusOk') : Dict::S('UI:BulkModifyStatusError');
  979. }
  980. else
  981. {
  982. $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusModified') : Dict::S('UI:BulkModifyStatusSkipped');
  983. }
  984. $sCSSClass = $bResult ? HILIGHT_CLASS_NONE : HILIGHT_CLASS_CRITICAL;
  985. $sChecked = $bResult ? 'checked' : '';
  986. $sDisabled = $bResult ? '' : 'disabled';
  987. $aRows[] = array(
  988. 'form::select' => "<input type=\"checkbox\" class=\"selectList\" $sChecked $sDisabled\"></input>",
  989. 'object' => $oObj->GetHyperlink(),
  990. 'status' => $sStatus,
  991. 'errors' => '<p>'.($bResult ? '': implode('</p><p>', $aErrors)).'</p>',
  992. '@class' => $sCSSClass,
  993. );
  994. if ($bResult && (!$bPreview))
  995. {
  996. $oObj->DBUpdateTracked($oMyChange);
  997. }
  998. }
  999. $oP->Table($aHeaders, $aRows);
  1000. $sURL = "./UI.php?operation=search&filter=$sFilter&".$oAppContext->GetForLink();
  1001. if ($bPreview)
  1002. {
  1003. // Form to submit:
  1004. $oP->add("<form method=\"post\" action=\"UI.php\" enctype=\"multipart/form-data\">\n");
  1005. $aDefaults = utils::ReadParam('default', array());
  1006. $oP->add($oAppContext->GetForForm());
  1007. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  1008. $oP->add("<input type=\"hidden\" name=\"filter\" value=\"$sFilter\">\n");
  1009. $oP->add("<input type=\"hidden\" name=\"selectObj\" value=\"$sSelectedObj\">\n");
  1010. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"preview_or_modify_all\">\n");
  1011. $oP->add("<input type=\"hidden\" name=\"preview_mode\" value=\"0\">\n");
  1012. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  1013. $oP->add("<button type=\"button\" class=\"action cancel\" onClick=\"window.location.href='$sURL'\">".Dict::S('UI:Button:Cancel')."</button>&nbsp;&nbsp;&nbsp;&nbsp;\n");
  1014. $oP->add("<button type=\"submit\" class=\"action\"><span>".Dict::S('UI:Button:ModifyAll')."</span></button>\n");
  1015. foreach($_POST as $sKey => $value)
  1016. {
  1017. if (preg_match('/attr_(.+)/', $sKey, $aMatches))
  1018. {
  1019. $oP->add("<input type=\"hidden\" name=\"$sKey\" value=\"$value\">\n");
  1020. }
  1021. }
  1022. $oP->add("</form>\n");
  1023. }
  1024. else
  1025. {
  1026. $sURL = "./UI.php?operation=search&filter=$sFilter&".$oAppContext->GetForLink();
  1027. $oP->add("<button type=\"button\" onClick=\"window.location.href='$sURL'\" class=\"action\"><span>".Dict::S('UI:Button:Done')."</span></button>\n");
  1028. }
  1029. break;
  1030. ///////////////////////////////////////////////////////////////////////////////////////////
  1031. case 'new': // Form to create a new object
  1032. $sClass = utils::ReadParam('class', '', false, 'class');
  1033. $sStateCode = utils::ReadParam('state', '');
  1034. $bCheckSubClass = utils::ReadParam('checkSubclass', true);
  1035. if ( empty($sClass) )
  1036. {
  1037. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'class'));
  1038. }
  1039. $aArgs = utils::ReadParam('default', array(), false, 'raw_data');
  1040. $aContext = $oAppContext->GetAsHash();
  1041. foreach( $oAppContext->GetNames() as $key)
  1042. {
  1043. $aArgs[$key] = $oAppContext->GetCurrentValue($key);
  1044. }
  1045. // If the specified class has subclasses, ask the user an instance of which class to create
  1046. $aSubClasses = MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL); // Including the specified class itself
  1047. $aPossibleClasses = array();
  1048. $sRealClass = '';
  1049. if ($bCheckSubClass)
  1050. {
  1051. foreach($aSubClasses as $sCandidateClass)
  1052. {
  1053. if (!MetaModel::IsAbstract($sCandidateClass) && (UserRights::IsActionAllowed($sCandidateClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES))
  1054. {
  1055. $aPossibleClasses[$sCandidateClass] = MetaModel::GetName($sCandidateClass);
  1056. }
  1057. }
  1058. // Only one of the subclasses can be instantiated...
  1059. if (count($aPossibleClasses) == 1)
  1060. {
  1061. $aKeys = array_keys($aPossibleClasses);
  1062. $sRealClass = $aKeys[0];
  1063. }
  1064. }
  1065. else
  1066. {
  1067. $sRealClass = $sClass;
  1068. }
  1069. if (!empty($sRealClass))
  1070. {
  1071. // Display the creation form
  1072. $sClassLabel = MetaModel::GetName($sRealClass);
  1073. // Note: some code has been duplicated to the case 'apply_new' when a data integrity issue has been found
  1074. $oP->set_title(Dict::Format('UI:CreationPageTitle_Class', $sClassLabel));
  1075. $oP->add("<h1>".MetaModel::GetClassIcon($sRealClass)."&nbsp;".Dict::Format('UI:CreationTitle_Class', $sClassLabel)."</h1>\n");
  1076. $oP->add("<div class=\"wizContainer\">\n");
  1077. // Set all the default values in an object and clone this "default" object
  1078. $oObjToClone = MetaModel::NewObject($sRealClass);
  1079. // 1st - set context values
  1080. $oAppContext->InitObjectFromContext($oObjToClone);
  1081. // 2nd - set values from the page argument 'default'
  1082. $oObjToClone->UpdateObjectFromArg('default');
  1083. cmdbAbstractObject::DisplayCreationForm($oP, $sRealClass, $oObjToClone, array());
  1084. $oP->add("</div>\n");
  1085. }
  1086. else
  1087. {
  1088. // Select the derived class to create
  1089. $sClassLabel = MetaModel::GetName($sClass);
  1090. $oP->add("<h1>".MetaModel::GetClassIcon($sClass)."&nbsp;".Dict::Format('UI:CreationTitle_Class', $sClassLabel)."</h1>\n");
  1091. $oP->add("<div class=\"wizContainer\">\n");
  1092. $oP->add('<form>');
  1093. $oP->add('<p>'.Dict::Format('UI:SelectTheTypeOf_Class_ToCreate', $sClassLabel));
  1094. $aDefaults = utils::ReadParam('default', array(), false, 'raw_data');
  1095. $oP->add($oAppContext->GetForForm());
  1096. $oP->add("<input type=\"hidden\" name=\"checkSubclass\" value=\"0\">\n");
  1097. $oP->add("<input type=\"hidden\" name=\"state\" value=\"$sStateCode\">\n");
  1098. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"new\">\n");
  1099. foreach($aDefaults as $key => $value)
  1100. {
  1101. if (is_array($value))
  1102. {
  1103. foreach($value as $key2 => $value2)
  1104. {
  1105. if (is_array($value2))
  1106. {
  1107. foreach($value2 as $key3 => $value3)
  1108. {
  1109. $oP->add("<input type=\"hidden\" name=\"default[$key][$key2][$key3]\" value=\"$value3\">\n");
  1110. }
  1111. }
  1112. else
  1113. {
  1114. $oP->add("<input type=\"hidden\" name=\"default[$key][$key2]\" value=\"$value2\">\n");
  1115. }
  1116. }
  1117. }
  1118. else
  1119. {
  1120. $oP->add("<input type=\"hidden\" name=\"default[$key]\" value=\"$value\">\n");
  1121. }
  1122. }
  1123. $oP->add('<select name="class">');
  1124. asort($aPossibleClasses);
  1125. foreach($aPossibleClasses as $sClassName => $sClassLabel)
  1126. {
  1127. $sSelected = ($sClassName == $sClass) ? 'selected' : '';
  1128. $oP->add("<option $sSelected value=\"$sClassName\">$sClassLabel</option>");
  1129. }
  1130. $oP->add('</select>');
  1131. $oP->add("&nbsp; <input type=\"submit\" value=\"".Dict::S('UI:Button:Apply')."\"></p>");
  1132. $oP->add('</form>');
  1133. $oP->add("</div>\n");
  1134. }
  1135. break;
  1136. ///////////////////////////////////////////////////////////////////////////////////////////
  1137. case 'apply_modify': // Applying the modifications to an existing object
  1138. $sClass = utils::ReadPostedParam('class', '');
  1139. $sClassLabel = MetaModel::GetName($sClass);
  1140. $id = utils::ReadPostedParam('id', '');
  1141. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1142. if ( empty($sClass) || empty($id)) // TO DO: check that the class name is valid !
  1143. {
  1144. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'id'));
  1145. }
  1146. $bDisplayDetails = true;
  1147. $oObj = MetaModel::GetObject($sClass, $id, false);
  1148. if ($oObj == null)
  1149. {
  1150. $bDisplayDetails = false;
  1151. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  1152. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  1153. }
  1154. elseif (!utils::IsTransactionValid($sTransactionId, false))
  1155. {
  1156. $oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetName(), $sClassLabel));
  1157. $oP->p("<strong>".Dict::S('UI:Error:ObjectAlreadyUpdated')."</strong>\n");
  1158. }
  1159. else
  1160. {
  1161. $oMyChange = null;
  1162. $oObj->UpdateObjectFromPostedForm();
  1163. if (!$oObj->IsModified())
  1164. {
  1165. $oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetName(), $sClassLabel));
  1166. $oP->p(Dict::Format('UI:Class_Object_NotUpdated', MetaModel::GetName(get_class($oObj)), $oObj->GetName()));
  1167. }
  1168. else
  1169. {
  1170. list($bRes, $aIssues) = $oObj->CheckToWrite();
  1171. if ($bRes)
  1172. {
  1173. $oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetName(), $sClassLabel));
  1174. $oP->add("<h1>".Dict::Format('UI:ModificationTitle_Class_Object', $sClassLabel, $oObj->GetName())."</h1>\n");
  1175. $oMyChange = MetaModel::NewObject("CMDBChange");
  1176. $oMyChange->Set("date", time());
  1177. $sUserString = CMDBChange::GetCurrentUserName();
  1178. $oMyChange->Set("userinfo", $sUserString);
  1179. $iChangeId = $oMyChange->DBInsert();
  1180. $oObj->DBUpdateTracked($oMyChange);
  1181. utils::RemoveTransaction($sTransactionId);
  1182. $oP->p(Dict::Format('UI:Class_Object_Updated', MetaModel::GetName(get_class($oObj)), $oObj->GetName()));
  1183. }
  1184. else
  1185. {
  1186. $bDisplayDetails = false;
  1187. // Found issues, explain and give the user a second chance
  1188. //
  1189. $oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetName(), $sClassLabel));
  1190. $oP->add("<div class=\"page_header\">\n");
  1191. $oP->add("<h1>".$oObj->GetIcon()."&nbsp;".Dict::Format('UI:ModificationTitle_Class_Object', $sClassLabel, $oObj->GetName())."</h1>\n");
  1192. $oP->add("</div>\n");
  1193. $oP->add("<div class=\"wizContainer\">\n");
  1194. $oObj->DisplayModifyForm($oP);
  1195. $oP->add("</div>\n");
  1196. $sIssueDesc = Dict::Format('UI:ObjectCouldNotBeWritten', implode(', ', $aIssues));
  1197. $oP->add_ready_script("alert('".addslashes($sIssueDesc)."');");
  1198. }
  1199. }
  1200. }
  1201. if ($bDisplayDetails)
  1202. {
  1203. $oObj = MetaModel::GetObject(get_class($oObj), $oObj->GetKey()); //Workaround: reload the object so that the linkedset are displayed properly
  1204. $sNextAction = utils::ReadPostedParam('next_action', '');
  1205. if (!empty($sNextAction))
  1206. {
  1207. ApplyNextAction($oP, $oObj, $sNextAction, $oMyChange);
  1208. }
  1209. else
  1210. {
  1211. // Nothing more to do
  1212. $oObj->DisplayDetails($oP);
  1213. }
  1214. }
  1215. break;
  1216. ///////////////////////////////////////////////////////////////////////////////////////////
  1217. case 'select_for_deletion': // Select multiple objects for deletion
  1218. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  1219. if (empty($sFilter))
  1220. {
  1221. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'filter'));
  1222. }
  1223. $oP->set_title(Dict::S('UI:BulkDeletePageTitle'));
  1224. $oP->add("<h1>".Dict::S('UI:BulkDeleteTitle')."</h1>\n");
  1225. // TO DO: limit the search filter by the user context
  1226. $oFilter = CMDBSearchFilter::unserialize($sFilter); // TO DO : check that the filter is valid
  1227. $oChecker = new ActionChecker($oFilter, UR_ACTION_BULK_DELETE);
  1228. DisplayMultipleSelectionForm($oP, $oFilter, 'bulk_delete', $oChecker);
  1229. break;
  1230. ///////////////////////////////////////////////////////////////////////////////////////////
  1231. case 'bulk_delete_confirmed': // Confirm bulk deletion of objects
  1232. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1233. if (!utils::IsTransactionValid($sTransactionId))
  1234. {
  1235. throw new ApplicationException(Dict::S('UI:Error:ObjectsAlreadyDeleted'));
  1236. }
  1237. // Fall through
  1238. ///////////////////////////////////////////////////////////////////////////////////////////
  1239. case 'bulk_delete': // Actual bulk deletion (if confirmed)
  1240. $sClass = utils::ReadPostedParam('class', '');
  1241. $sClassLabel = MetaModel::GetName($sClass);
  1242. $sFilter = utils::ReadPostedParam('filter', '');
  1243. $oFullSetFilter = DBObjectSearch::unserialize($sFilter);
  1244. $aSelectObject = utils::ReadMultipleSelection($oFullSetFilter);
  1245. $aObjects = array();
  1246. if ( empty($sClass) || empty($aSelectObject)) // TO DO: check that the class name is valid !
  1247. {
  1248. throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'selectObject[]'));
  1249. }
  1250. foreach($aSelectObject as $iId)
  1251. {
  1252. $aObjects[] = MetaModel::GetObject($sClass, $iId);
  1253. }
  1254. if (!UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_DELETE, DBObjectSet::FromArray($sClass, $aObjects)))
  1255. {
  1256. throw new SecurityException(Dict::Format('UI:Error:BulkDeleteNotAllowedOn_Class', $sClass));
  1257. }
  1258. $oP->set_title(Dict::S('UI:BulkDeletePageTitle'));
  1259. DeleteObjects($oP, $sClass, $aObjects, ($operation == 'bulk_delete_confirmed'));
  1260. break;
  1261. ///////////////////////////////////////////////////////////////////////////////////////////
  1262. case 'delete': // Deletion (preview)
  1263. case 'delete_confirmed': // Deletion (confirmed)
  1264. $sClass = utils::ReadParam('class', '', false, 'class');
  1265. $sClassLabel = MetaModel::GetName($sClass);
  1266. $id = utils::ReadParam('id', '');
  1267. $oObj = MetaModel::GetObject($sClass, $id);
  1268. if (!UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, DBObjectSet::FromObject($oObj)))
  1269. {
  1270. throw new SecurityException(Dict::Format('UI:Error:DeleteNotAllowedOn_Class', $sClass));
  1271. }
  1272. DeleteObjects($oP, $sClass, array($oObj), ($operation == 'delete_confirmed'));
  1273. break;
  1274. ///////////////////////////////////////////////////////////////////////////////////////////
  1275. case 'apply_new': // Creation of a new object
  1276. $sClass = utils::ReadPostedParam('class', '', 'class');
  1277. $sClassLabel = MetaModel::GetName($sClass);
  1278. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1279. if ( empty($sClass) ) // TO DO: check that the class name is valid !
  1280. {
  1281. throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'class'));
  1282. }
  1283. if (!utils::IsTransactionValid($sTransactionId, false))
  1284. {
  1285. $oP->p("<strong>".Dict::S('UI:Error:ObjectAlreadyCreated')."</strong>\n");
  1286. }
  1287. else
  1288. {
  1289. $oObj = MetaModel::NewObject($sClass);
  1290. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1291. if (!empty($sStateAttCode))
  1292. {
  1293. $sTargetState = utils::ReadPostedParam('obj_state', '');
  1294. if ($sTargetState != '')
  1295. {
  1296. $oObj->Set($sStateAttCode, $sTargetState);
  1297. }
  1298. }
  1299. $oObj->UpdateObjectFromPostedForm();
  1300. }
  1301. if (isset($oObj) && is_object($oObj))
  1302. {
  1303. $sClass = get_class($oObj);
  1304. $sClassLabel = MetaModel::GetName($sClass);
  1305. list($bRes, $aIssues) = $oObj->CheckToWrite();
  1306. if ($bRes)
  1307. {
  1308. $oMyChange = MetaModel::NewObject("CMDBChange");
  1309. $oMyChange->Set("date", time());
  1310. $sUserString = CMDBChange::GetCurrentUserName();
  1311. $oMyChange->Set("userinfo", $sUserString);
  1312. $iChangeId = $oMyChange->DBInsert();
  1313. $oObj->DBInsertTracked($oMyChange);
  1314. utils::RemoveTransaction($sTransactionId);
  1315. $oP->set_title(Dict::S('UI:PageTitle:ObjectCreated'));
  1316. $oP->add("<h1>".Dict::Format('UI:Title:Object_Of_Class_Created', $oObj->GetName(), $sClassLabel)."</h1>\n");
  1317. $oObj = MetaModel::GetObject(get_class($oObj), $oObj->GetKey()); //Workaround: reload the object so that the linkedset are displayed properly
  1318. $sNextAction = utils::ReadPostedParam('next_action', '');
  1319. if (!empty($sNextAction))
  1320. {
  1321. ApplyNextAction($oP, $oObj, $sNextAction, $oMyChange);
  1322. }
  1323. else
  1324. {
  1325. // Nothing more to do
  1326. $oObj->DisplayDetails($oP);
  1327. }
  1328. }
  1329. else
  1330. {
  1331. // Found issues, explain and give the user a second chance
  1332. //
  1333. $oP->set_title(Dict::Format('UI:CreationPageTitle_Class', $sClassLabel));
  1334. $oP->add("<h1>".MetaModel::GetClassIcon($sClass)."&nbsp;".Dict::Format('UI:CreationTitle_Class', $sClassLabel)."</h1>\n");
  1335. $oP->add("<div class=\"wizContainer\">\n");
  1336. cmdbAbstractObject::DisplayCreationForm($oP, $sClass, $oObj);
  1337. $oP->add("</div>\n");
  1338. $sIssueDesc = Dict::Format('UI:ObjectCouldNotBeWritten', implode(', ', $aIssues));
  1339. $oP->add_ready_script("alert('".addslashes($sIssueDesc)."');");
  1340. }
  1341. }
  1342. break;
  1343. ///////////////////////////////////////////////////////////////////////////////////////////
  1344. case 'wizard_apply_new': // no more used ???
  1345. $sJson = utils::ReadPostedParam('json_obj', '', 'raw_data');
  1346. $oWizardHelper = WizardHelper::FromJSON($sJson);
  1347. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1348. if (!utils::IsTransactionValid($sTransactionId))
  1349. {
  1350. $oP->p(Dict::S('UI:Error:ObjectAlreadyCreated'));
  1351. }
  1352. else
  1353. {
  1354. $oObj = $oWizardHelper->GetTargetObject(true /* read uploaded files */);
  1355. if (is_object($oObj))
  1356. {
  1357. $sClass = get_class($oObj);
  1358. $sClassLabel = MetaModel::GetName($sClass);
  1359. $oMyChange = MetaModel::NewObject("CMDBChange");
  1360. $oMyChange->Set("date", time());
  1361. $sUserString = CMDBChange::GetCurrentUserName();
  1362. $oMyChange->Set("userinfo", $sUserString);
  1363. $iChangeId = $oMyChange->DBInsert();
  1364. $oObj->DBInsertTracked($oMyChange);
  1365. $oP->set_title(Dict::S('UI:PageTitle:ObjectCreated'));
  1366. $oP->add("<h1>".Dict::Format('UI:Title:Object_Of_Class_Created', $oObj->GetName(), $sClassLabel)."</h1>\n");
  1367. $oObj->DisplayDetails($oP);
  1368. }
  1369. }
  1370. break;
  1371. ///////////////////////////////////////////////////////////////////////////////////////////
  1372. case 'select_bulk_stimulus': // Form displayed when applying a stimulus to many objects
  1373. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  1374. $sStimulus = utils::ReadParam('stimulus', '');
  1375. $sState = utils::ReadParam('state', '');
  1376. if (empty($sFilter) || empty($sStimulus) || empty($sState))
  1377. {
  1378. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state'));
  1379. }
  1380. $oFilter = DBObjectSearch::unserialize($sFilter);
  1381. $sClass = $oFilter->GetClass();
  1382. $aStimuli = MetaModel::EnumStimuli($sClass);
  1383. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1384. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1385. $oP->set_title($sActionLabel);
  1386. $oP->add('<div class="page_header">');
  1387. $oP->add('<h1>'.MetaModel::GetClassIcon($sClass).'&nbsp;'.$sActionLabel.'</h1>');
  1388. $oP->add('</div>');
  1389. $oChecker = new StimulusChecker($oFilter, $sState, $sStimulus);
  1390. $aExtraFormParams = array('stimulus' => $sStimulus, 'state' => $sState);
  1391. DisplayMultipleSelectionForm($oP, $oFilter, 'bulk_stimulus', $oChecker, $aExtraFormParams);
  1392. break;
  1393. case 'bulk_stimulus':
  1394. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  1395. $sStimulus = utils::ReadParam('stimulus', '');
  1396. $sState = utils::ReadParam('state', '');
  1397. if (empty($sFilter) || empty($sStimulus) || empty($sState))
  1398. {
  1399. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state'));
  1400. }
  1401. $oFilter = DBObjectSearch::unserialize($sFilter);
  1402. $sClass = $oFilter->GetClass();
  1403. $aSelectObject = utils::ReadMultipleSelection($oFilter);
  1404. if (count($aSelectObject) == 0)
  1405. {
  1406. // Nothing to do, no object was selected !
  1407. throw new ApplicationException(Dict::S('UI:BulkAction:NoObjectSelected'));
  1408. }
  1409. else
  1410. {
  1411. $aTransitions = MetaModel::EnumTransitions($sClass, $sState);
  1412. $aStimuli = MetaModel::EnumStimuli($sClass);
  1413. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1414. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1415. $aTransition = $aTransitions[$sStimulus];
  1416. $sTargetState = $aTransition['target_state'];
  1417. $aStates = MetaModel::EnumStates($sClass);
  1418. $aTargetStateDef = $aStates[$sTargetState];
  1419. $oP->set_title(Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aSelectObject), $sClass));
  1420. $oP->add('<div class="page_header">');
  1421. $oP->add('<h1>'.MetaModel::GetClassIcon($sClass).'&nbsp;'.Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aSelectObject), $sClass).'</h1>');
  1422. $oP->add('</div>');
  1423. $aExpectedAttributes = $aTargetStateDef['attribute_list'];
  1424. $aDetails = array();
  1425. $iFieldIndex = 0;
  1426. $aFieldsMap = array();
  1427. $aValues = array();
  1428. $aObjects = array();
  1429. foreach($aSelectObject as $iId)
  1430. {
  1431. $aObjects[] = MetaModel::GetObject($sClass, $iId);
  1432. }
  1433. $oSet = DBObjectSet::FromArray($sClass, $aObjects);
  1434. $oObj = $oSet->ComputeCommonObject($aValues);
  1435. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1436. $oObj->Set($sStateAttCode,$sTargetState);
  1437. $sReadyScript = '';
  1438. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  1439. {
  1440. // Prompt for an attribute if
  1441. // - the attribute must be changed or must be displayed to the user for confirmation
  1442. // - or the field is mandatory and currently empty
  1443. if ( ($iExpectCode & (OPT_ATT_MUSTCHANGE | OPT_ATT_MUSTPROMPT)) ||
  1444. (($iExpectCode & OPT_ATT_MANDATORY) && ($oObj->Get($sAttCode) == '')) )
  1445. {
  1446. $aAttributesDef = MetaModel::ListAttributeDefs($sClass);
  1447. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1448. $aPrerequisites = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  1449. if (count($aPrerequisites) > 0)
  1450. {
  1451. // When 'enabling' a field, all its prerequisites must be enabled too
  1452. $sFieldList = "['".implode("','", $aPrerequisites)."']";
  1453. $oP->add_ready_script("$('#enable_{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, true); } );\n");
  1454. }
  1455. $aDependents = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  1456. if (count($aDependents) > 0)
  1457. {
  1458. // When 'disabling' a field, all its dependent fields must be disabled too
  1459. $sFieldList = "['".implode("','", $aDependents)."']";
  1460. $oP->add_ready_script("$('#enable_{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, false); } );\n");
  1461. }
  1462. $aArgs = array('this' => $oObj);
  1463. $sHTMLValue = cmdbAbstractObject::GetFormElementForField($oP, $sClass, $sAttCode, $oAttDef, $oObj->Get($sAttCode), $oObj->GetEditValue($sAttCode), $sAttCode, '', $iExpectCode, $aArgs);
  1464. $sComments = '<input type="checkbox" checked id="enable_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$sAttCode.'\')"/>';
  1465. if (!isset($aValues[$sAttCode]))
  1466. {
  1467. $aValues[$sAttCode] = array();
  1468. }
  1469. if (count($aValues[$sAttCode]) == 1)
  1470. {
  1471. $sComments .= '<div class="mono_value">1</div>';
  1472. }
  1473. else
  1474. {
  1475. // Non-homogenous value
  1476. $iMaxCount = 5;
  1477. $sTip = "<p><b>".Dict::Format('UI:BulkModify_Count_DistinctValues', count($aValues[$sAttCode]))."</b><ul>";
  1478. $index = 0;
  1479. foreach($aValues[$sAttCode] as $sCurrValue => $aVal)
  1480. {
  1481. $sDisplayValue = empty($aVal['display']) ? '<i>'.Dict::S('Enum:Undefined').'</i>' : str_replace(array("\n", "\r"), " ", $aVal['display']);
  1482. $sTip .= "<li>".Dict::Format('UI:BulkModify:Value_Exists_N_Times', $sDisplayValue, $aVal['count'])."</li>";
  1483. $index++;
  1484. if ($iMaxCount == $index)
  1485. {
  1486. $sTip .= "<li>".(count($aMultiValues) - $iMaxCount)." more different values...</li>";
  1487. break;
  1488. }
  1489. if ($iMaxCount == $index)
  1490. {
  1491. $sTip .= "<li>".Dict::Format('UI:BulkModify:N_MoreValues', count($aValues[$sAttCode]) - $iMaxCount)."</li>";
  1492. break;
  1493. }
  1494. }
  1495. $sTip .= "</ul></p>";
  1496. $sReadyScript .= "$('#multi_values_$sAttCode').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );\n";
  1497. $sComments .= '<div class="multi_values" id="multi_values_'.$sAttCode.'">'.count($aValues[$sAttCode]).'</div>';
  1498. }
  1499. $aDetails[] = array('label' => '<span>'.$oAttDef->GetLabel().'</span>', 'value' => "<span id=\"field_$sAttCode\">$sHTMLValue</span>", 'comments' => $sComments);
  1500. $aFieldsMap[$sAttCode] = $sAttCode;
  1501. $iFieldIndex++;
  1502. }
  1503. }
  1504. $sButtonsPosition = MetaModel::GetConfig()->Get('buttons_position');
  1505. if ($sButtonsPosition == 'bottom')
  1506. {
  1507. // bottom: Displays the ticket details BEFORE the actions
  1508. $oP->add('<div class="ui-widget-content">');
  1509. $oObj->DisplayBareProperties($oP);
  1510. $oP->add('</div>');
  1511. }
  1512. $oP->add("<div class=\"wizContainer\">\n");
  1513. $oP->add("<form id=\"apply_stimulus\" method=\"post\" onSubmit=\"return OnSubmit('apply_stimulus');\">\n");
  1514. $oP->add("<table><tr><td>\n");
  1515. $oP->details($aDetails);
  1516. $oP->add("</td></tr></table>\n");
  1517. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  1518. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"bulk_apply_stimulus\">\n");
  1519. $oP->add("<input type=\"hidden\" name=\"preview_mode\" value=\"1\">\n");
  1520. $oP->add("<input type=\"hidden\" name=\"filter\" value=\"$sFilter\">\n");
  1521. $oP->add("<input type=\"hidden\" name=\"stimulus\" value=\"$sStimulus\">\n");
  1522. $oP->add("<input type=\"hidden\" name=\"state\" value=\"$sState\">\n");
  1523. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  1524. $oP->add($oAppContext->GetForForm());
  1525. $oP->add("<input type=\"hidden\" name=\"selectObject\" value=\"".implode(',',$aSelectObject)."\">\n");
  1526. $sURL = "./UI.php?operation=search&filter=$sFilter&".$oAppContext->GetForLink();
  1527. $oP->add("<input type=\"button\" value=\"".Dict::S('UI:Button:Cancel')."\" onClick=\"window.location.href='$sURL'\">&nbsp;&nbsp;&nbsp;&nbsp;\n");
  1528. $oP->add("<button type=\"submit\" class=\"action\"><span>$sActionLabel</span></button>\n");
  1529. $oP->add("</form>\n");
  1530. $oP->add("</div>\n");
  1531. if ($sButtonsPosition != 'bottom')
  1532. {
  1533. // top or both: Displays the ticket details AFTER the actions
  1534. $oP->add('<div class="ui-widget-content">');
  1535. $oObj->DisplayBareProperties($oP);
  1536. $oP->add('</div>');
  1537. }
  1538. $iFieldsCount = count($aFieldsMap);
  1539. $sJsonFieldsMap = json_encode($aFieldsMap);
  1540. $oP->add_script(
  1541. <<<EOF
  1542. // Initializes the object once at the beginning of the page...
  1543. var oWizardHelper = new WizardHelper('$sClass', '', '$sTargetState');
  1544. oWizardHelper.SetFieldsMap($sJsonFieldsMap);
  1545. oWizardHelper.SetFieldsCount($iFieldsCount);
  1546. EOF
  1547. );
  1548. $oP->add_ready_script(
  1549. <<<EOF
  1550. // Starts the validation when the page is ready
  1551. CheckFields('apply_stimulus', false);
  1552. $sReadyScript
  1553. EOF
  1554. );
  1555. }
  1556. break;
  1557. case 'bulk_apply_stimulus':
  1558. $bPreviewMode = utils::ReadPostedParam('preview_mode', false);
  1559. $sFilter = utils::ReadPostedParam('filter', '', false, 'raw_data');
  1560. $sStimulus = utils::ReadPostedParam('stimulus', '');
  1561. $sState = utils::ReadPostedParam('state', '');
  1562. $sSelectObject = utils::ReadPostedParam('selectObject', '', false, 'raw_data');
  1563. $aSelectObject = explode(',', $sSelectObject);
  1564. if (empty($sFilter) || empty($sStimulus) || empty($sState))
  1565. {
  1566. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state'));
  1567. }
  1568. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1569. if (!utils::IsTransactionValid($sTransactionId))
  1570. {
  1571. $oP->p(Dict::S('UI:Error:ObjectAlreadyUpdated'));
  1572. }
  1573. else
  1574. {
  1575. // For archiving the modification
  1576. $oFilter = DBObjectSearch::unserialize($sFilter);
  1577. $sClass = $oFilter->GetClass();
  1578. $aObjects = array();
  1579. foreach($aSelectObject as $iId)
  1580. {
  1581. $aObjects[] = MetaModel::GetObject($sClass, $iId);
  1582. }
  1583. $aTransitions = MetaModel::EnumTransitions($sClass, $sState);
  1584. $aStimuli = MetaModel::EnumStimuli($sClass);
  1585. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1586. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1587. $oP->set_title(Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aObjects), $sClass));
  1588. $oP->add('<div class="page_header">');
  1589. $oP->add('<h1>'.MetaModel::GetClassIcon($sClass).'&nbsp;'.Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aObjects), $sClass).'</h1>');
  1590. $oP->add('</div>');
  1591. $oSet = DBObjectSet::FromArray($sClass, $aObjects);
  1592. $oMyChange = MetaModel::NewObject("CMDBChange");
  1593. $oMyChange->Set("date", time());
  1594. $sUserString = CMDBChange::GetCurrentUserName();
  1595. $oMyChange->Set("userinfo", $sUserString);
  1596. $iChangeId = $oMyChange->DBInsert();
  1597. // For reporting
  1598. $aHeaders = array(
  1599. 'object' => array('label' => MetaModel::GetName($sClass), 'description' => Dict::S('UI:ModifiedObject')),
  1600. 'status' => array('label' => Dict::S('UI:BulkModifyStatus'), 'description' => Dict::S('UI:BulkModifyStatus+')),
  1601. 'errors' => array('label' => Dict::S('UI:BulkModifyErrors'), 'description' => Dict::S('UI:BulkModifyErrors+')),
  1602. );
  1603. $aRows = array();
  1604. while ($oObj = $oSet->Fetch())
  1605. {
  1606. $sError = Dict::S('UI:BulkModifyStatusOk');
  1607. try
  1608. {
  1609. $aTransitions = $oObj->EnumTransitions();
  1610. $aStimuli = MetaModel::EnumStimuli($sClass);
  1611. if (!isset($aTransitions[$sStimulus]))
  1612. {
  1613. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
  1614. }
  1615. else
  1616. {
  1617. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1618. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1619. $aTransition = $aTransitions[$sStimulus];
  1620. $sTargetState = $aTransition['target_state'];
  1621. $aTargetStates = MetaModel::EnumStates($sClass);
  1622. $aTargetState = $aTargetStates[$sTargetState];
  1623. $aExpectedAttributes = $aTargetState['attribute_list'];
  1624. $aDetails = array();
  1625. $aErrors = array();
  1626. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  1627. {
  1628. $iFlags = $oObj->GetAttributeFlags($sAttCode);
  1629. if (($iExpectCode & (OPT_ATT_MUSTCHANGE|OPT_ATT_MUSTPROMPT)) || ($oObj->Get($sAttCode) == '') )
  1630. {
  1631. $paramValue = utils::ReadPostedParam("attr_$sAttCode", '', 'raw_data');
  1632. if ( ($iFlags & OPT_ATT_SLAVE) && ($paramValue != $oObj->Get($sAttCode)) )
  1633. {
  1634. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1635. $aErrors[] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $oAttDef->GetLabel());
  1636. }
  1637. else
  1638. {
  1639. $oObj->Set($sAttCode, $paramValue);
  1640. }
  1641. }
  1642. }
  1643. if (count($aErrors) == 0)
  1644. {
  1645. if ($oObj->ApplyStimulus($sStimulus))
  1646. {
  1647. list($bResult, $aErrors) = $oObj->CheckToWrite();
  1648. $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusModified') : Dict::S('UI:BulkModifyStatusSkipped');
  1649. if ($bResult)
  1650. {
  1651. $oObj->DBUpdateTracked($oMyChange);
  1652. }
  1653. else
  1654. {
  1655. $sError = '<p>'.implode('</p></p>',$aErrors)."</p>\n";
  1656. }
  1657. }
  1658. else
  1659. {
  1660. $sStatus = Dict::S('UI:BulkModifyStatusSkipped');
  1661. $sError = '<p>'.Dict::S('UI:FailedToApplyStimuli')."<p>\n";
  1662. }
  1663. }
  1664. else
  1665. {
  1666. $sStatus = Dict::S('UI:BulkModifyStatusSkipped');
  1667. $sError = '<p>'.implode('</p></p>',$aErrors)."</p>\n";
  1668. }
  1669. }
  1670. }
  1671. catch(Exception $e)
  1672. {
  1673. $sError = $e->getMessage();
  1674. $sStatus = Dict::S('UI:BulkModifyStatusSkipped');
  1675. }
  1676. $aRows[] = array(
  1677. 'object' => $oObj->GetHyperlink(),
  1678. 'status' => $sStatus,
  1679. 'errors' => $sError,
  1680. );
  1681. }
  1682. $oP->Table($aHeaders, $aRows);
  1683. // Back to the list
  1684. $sURL = "./UI.php?operation=search&filter=$sFilter&".$oAppContext->GetForLink();
  1685. $oP->add('<input type="button" onClick="window.location.href=\''.$sURL.'\'" value="'.Dict::S('UI:Button:Done').'">');
  1686. }
  1687. break;
  1688. case 'stimulus': // Form displayed when applying a stimulus (state change)
  1689. $sClass = utils::ReadParam('class', '', false, 'class');
  1690. $id = utils::ReadParam('id', '');
  1691. $sStimulus = utils::ReadParam('stimulus', '');
  1692. if ( empty($sClass) || empty($id) || empty($sStimulus) ) // TO DO: check that the class name is valid !
  1693. {
  1694. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'class', 'id', 'stimulus'));
  1695. }
  1696. $oObj = MetaModel::GetObject($sClass, $id, false);
  1697. if ($oObj != null)
  1698. {
  1699. $aTransitions = $oObj->EnumTransitions();
  1700. $aStimuli = MetaModel::EnumStimuli($sClass);
  1701. if (!isset($aTransitions[$sStimulus]))
  1702. {
  1703. // Invalid stimulus
  1704. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
  1705. }
  1706. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1707. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1708. $aTransition = $aTransitions[$sStimulus];
  1709. $sTargetState = $aTransition['target_state'];
  1710. $aTargetStates = MetaModel::EnumStates($sClass);
  1711. $oP->add("<div class=\"page_header\">\n");
  1712. $oP->add("<h1>$sActionLabel - <span class=\"hilite\">{$oObj->GetName()}</span></h1>\n");
  1713. $oP->set_title($sActionLabel);
  1714. $oP->add("</div>\n");
  1715. $aTargetState = $aTargetStates[$sTargetState];
  1716. $aExpectedAttributes = $aTargetState['attribute_list'];
  1717. $oP->add("<h1>$sActionDetails</h1>\n");
  1718. $sButtonsPosition = MetaModel::GetConfig()->Get('buttons_position');
  1719. if ($sButtonsPosition == 'bottom')
  1720. {
  1721. // bottom: Displays the ticket details BEFORE the actions
  1722. $oP->add('<div class="ui-widget-content">');
  1723. $oObj->DisplayBareProperties($oP);
  1724. $oP->add('</div>');
  1725. }
  1726. $oP->add("<div class=\"wizContainer\">\n");
  1727. $oP->add("<form id=\"apply_stimulus\" method=\"post\" onSubmit=\"return OnSubmit('apply_stimulus');\">\n");
  1728. $aDetails = array();
  1729. $iFieldIndex = 0;
  1730. $aFieldsMap = array();
  1731. $aDetailsList = $oObj->FlattenZList(MetaModel::GetZListItems($sClass, 'details'));
  1732. // Order the fields based on their dependencies, set the fields for which there is only one possible value
  1733. // and perform this in the order of dependencies to avoid dead-ends
  1734. $aDeps = array();
  1735. foreach($aDetailsList as $sAttCode)
  1736. {
  1737. $aDeps[$sAttCode] = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode);
  1738. }
  1739. $aList = $oObj->OrderDependentFields($aDeps);
  1740. foreach($aList as $sAttCode)
  1741. {
  1742. // Consider only the "expected" fields for the target state
  1743. if (array_key_exists($sAttCode, $aExpectedAttributes))
  1744. {
  1745. $iExpectCode = $aExpectedAttributes[$sAttCode];
  1746. // Prompt for an attribute if
  1747. // - the attribute must be changed or must be displayed to the user for confirmation
  1748. // - or the field is mandatory and currently empty
  1749. if ( ($iExpectCode & (OPT_ATT_MUSTCHANGE | OPT_ATT_MUSTPROMPT)) ||
  1750. (($iExpectCode & OPT_ATT_MANDATORY) && ($oObj->Get($sAttCode) == '')) )
  1751. {
  1752. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1753. $aArgs = array('this' => $oObj);
  1754. // If the field is mandatory, set it to the only possible value
  1755. if ((!$oAttDef->IsNullAllowed()) || ($iExpectCode & OPT_ATT_MANDATORY))
  1756. {
  1757. if ($oAttDef->IsExternalKey())
  1758. {
  1759. $oAllowedValues = MetaModel::GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs);
  1760. if ($oAllowedValues->Count() == 1)
  1761. {
  1762. $oRemoteObj = $oAllowedValues->Fetch();
  1763. $oObj->Set($sAttCode, $oRemoteObj->GetKey());
  1764. }
  1765. }
  1766. else
  1767. {
  1768. $aAllowedValues = MetaModel::GetAllowedValues_att($sClass, $sAttCode, $aArgs);
  1769. if (count($aAllowedValues) == 1)
  1770. {
  1771. $aValues = array_keys($aAllowedValues);
  1772. $oObj->Set($sAttCode, $aValues[0]);
  1773. }
  1774. }
  1775. }
  1776. $sHTMLValue = cmdbAbstractObject::GetFormElementForField($oP, $sClass, $sAttCode, $oAttDef, $oObj->Get($sAttCode), $oObj->GetEditValue($sAttCode), 'att_'.$iFieldIndex, '', $iExpectCode, $aArgs);
  1777. $aDetails[] = array('label' => '<span>'.$oAttDef->GetLabel().'</span>', 'value' => "<span id=\"field_att_$iFieldIndex\">$sHTMLValue</span>");
  1778. $aFieldsMap[$sAttCode] = 'att_'.$iFieldIndex;
  1779. $iFieldIndex++;
  1780. }
  1781. }
  1782. }
  1783. $oP->add('<table><tr><td>');
  1784. $oP->details($aDetails);
  1785. $oP->add('</td></tr></table>');
  1786. $oP->add("<input type=\"hidden\" name=\"id\" value=\"$id\" id=\"id\">\n");
  1787. $aFieldsMap['id'] = 'id';
  1788. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  1789. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"apply_stimulus\">\n");
  1790. $oP->add("<input type=\"hidden\" name=\"stimulus\" value=\"$sStimulus\">\n");
  1791. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  1792. $oP->add($oAppContext->GetForForm());
  1793. $oP->add("<button type=\"button\" class=\"action\" onClick=\"BackToDetails('$sClass', $id)\"><span>".Dict::S('UI:Button:Cancel')."</span></button>&nbsp;&nbsp;&nbsp;&nbsp;\n");
  1794. $oP->add("<button type=\"submit\" class=\"action\"><span>$sActionLabel</span></button>\n");
  1795. $oP->add("</form>\n");
  1796. $oP->add("</div>\n");
  1797. if ($sButtonsPosition != 'top')
  1798. {
  1799. // bottom or both: Displays the ticket details AFTER the actions
  1800. $oP->add('<div class="ui-widget-content">');
  1801. $oObj->DisplayBareProperties($oP);
  1802. $oP->add('</div>');
  1803. }
  1804. $iFieldsCount = count($aFieldsMap);
  1805. $sJsonFieldsMap = json_encode($aFieldsMap);
  1806. $oP->add_script(
  1807. <<<EOF
  1808. // Initializes the object once at the beginning of the page...
  1809. var oWizardHelper = new WizardHelper('$sClass', '', '$sTargetState');
  1810. oWizardHelper.SetFieldsMap($sJsonFieldsMap);
  1811. oWizardHelper.SetFieldsCount($iFieldsCount);
  1812. EOF
  1813. );
  1814. $oP->add_ready_script(
  1815. <<<EOF
  1816. // Starts the validation when the page is ready
  1817. CheckFields('apply_stimulus', false);
  1818. EOF
  1819. );
  1820. }
  1821. else
  1822. {
  1823. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  1824. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  1825. }
  1826. break;
  1827. ///////////////////////////////////////////////////////////////////////////////////////////
  1828. case 'apply_stimulus': // Actual state change
  1829. $sClass = utils::ReadPostedParam('class', '');
  1830. $id = utils::ReadPostedParam('id', '');
  1831. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  1832. $sStimulus = utils::ReadPostedParam('stimulus', '');
  1833. if ( empty($sClass) || empty($id) || empty($sStimulus) ) // TO DO: check that the class name is valid !
  1834. {
  1835. throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'class', 'id', 'stimulus'));
  1836. }
  1837. $oObj = MetaModel::GetObject($sClass, $id, false);
  1838. if ($oObj != null)
  1839. {
  1840. $aTransitions = $oObj->EnumTransitions();
  1841. $aStimuli = MetaModel::EnumStimuli($sClass);
  1842. if (!isset($aTransitions[$sStimulus]))
  1843. {
  1844. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
  1845. }
  1846. if (!utils::IsTransactionValid($sTransactionId))
  1847. {
  1848. $oP->p(Dict::S('UI:Error:ObjectAlreadyUpdated'));
  1849. }
  1850. else
  1851. {
  1852. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1853. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1854. $aTransition = $aTransitions[$sStimulus];
  1855. $sTargetState = $aTransition['target_state'];
  1856. $aTargetStates = MetaModel::EnumStates($sClass);
  1857. $aTargetState = $aTargetStates[$sTargetState];
  1858. $aExpectedAttributes = $aTargetState['attribute_list'];
  1859. $aDetails = array();
  1860. $aErrors = array();
  1861. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  1862. {
  1863. $iFlags = $oObj->GetAttributeFlags($sAttCode);
  1864. if (($iExpectCode & (OPT_ATT_MUSTCHANGE|OPT_ATT_MUSTPROMPT)) || ($oObj->Get($sAttCode) == '') )
  1865. {
  1866. $paramValue = utils::ReadPostedParam("attr_$sAttCode", '', 'raw_data');
  1867. if ( ($iFlags & OPT_ATT_SLAVE) && ($paramValue != $oObj->Get($sAttCode)))
  1868. {
  1869. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1870. $aErrors[] = Dict::Format('UI:AttemptingToChangeASlaveAttribute_Name', $oAttDef->GetLabel());
  1871. }
  1872. else
  1873. {
  1874. $oObj->Set($sAttCode, $paramValue);
  1875. }
  1876. }
  1877. }
  1878. if (count($aErrors) == 0)
  1879. {
  1880. if ($oObj->ApplyStimulus($sStimulus))
  1881. {
  1882. $oMyChange = MetaModel::NewObject("CMDBChange");
  1883. $oMyChange->Set("date", time());
  1884. $sUserString = CMDBChange::GetCurrentUserName();
  1885. $oMyChange->Set("userinfo", $sUserString);
  1886. $iChangeId = $oMyChange->DBInsert();
  1887. $oObj->DBUpdateTracked($oMyChange);
  1888. $oP->p(Dict::Format('UI:Class_Object_Updated', MetaModel::GetName(get_class($oObj)), $oObj->GetName()));
  1889. }
  1890. else
  1891. {
  1892. $oP->p(Dict::S('UI:FailedToApplyStimuli'));
  1893. }
  1894. }
  1895. else
  1896. {
  1897. $oP->p(implode('</p><p>', $aErrors));
  1898. }
  1899. }
  1900. $oObj->DisplayDetails($oP);
  1901. }
  1902. else
  1903. {
  1904. $oP->set_title(Dict::S('UI:ErrorPageTitle'));
  1905. $oP->P(Dict::S('UI:ObjectDoesNotExist'));
  1906. }
  1907. break;
  1908. ///////////////////////////////////////////////////////////////////////////////////////////
  1909. case 'swf_navigator': // Graphical display of the relations "impact" / "depends on"
  1910. $sClass = utils::ReadParam('class', '', false, 'class');
  1911. $id = utils::ReadParam('id', 0);
  1912. $sRelation = utils::ReadParam('relation', 'impact');
  1913. $oP->AddTabContainer('Navigator');
  1914. $oP->SetCurrentTabContainer('Navigator');
  1915. $oP->SetCurrentTab(Dict::S('UI:RelationshipGraph'));
  1916. $width = 1000;
  1917. $height = 700;
  1918. $sParams = "pWidth=$width&pHeight=$height&drillUrl=".urlencode(utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=details')."&displayController=false&xmlUrl=".urlencode("./xml.navigator.php")."&obj_class=$sClass&obj_id=$id&relation=$sRelation";
  1919. $oP->add("<div style=\"z-index:1;background:white\"><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=\"$width\" height=\"$height\" id=\"navigator\" align=\"middle\">
  1920. <param name=\"allowScriptAccess\" value=\"sameDomain\" />
  1921. <param name=\"allowFullScreen\" value=\"false\" />
  1922. <param name=\"FlashVars\" value=\"$sParams\" />
  1923. <param name=\"wmode\" value=\"transparent\">
  1924. <param name=\"movie\" value=\"../navigator/navigator.swf\" /><param name=\"quality\" value=\"high\" /><param name=\"bgcolor\" value=\"#ffffff\" />
  1925. <embed src=\"../navigator/navigator.swf\" wmode=\"transparent\" flashVars=\"$sParams\" quality=\"high\" bgcolor=\"#ffffff\" width=\"$width\" height=\"$height\" name=\"navigator\" align=\"middle\" allowScriptAccess=\"sameDomain\" allowFullScreen=\"false\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.adobe.com/go/getflashplayer\" />
  1926. </object></div>\n");
  1927. $oP->SetCurrentTab(Dict::S('UI:RelationshipList'));
  1928. $oP->add("<div id=\"impacted_objects\" style=\"width:100%;background-color:#fff;padding:10px;\"><p style=\"height:150px;\">&nbsp;</p></div>");
  1929. $oP->add_ready_script(
  1930. <<<EOF
  1931. var ajax_request = null;
  1932. function UpdateImpactedObjects(sClass, iId, sRelation)
  1933. {
  1934. var class_name = sClass; //$('select[name=class_name]').val();
  1935. if (class_name != '')
  1936. {
  1937. $('#impacted_objects').block();
  1938. // Make sure that we cancel any pending request before issuing another
  1939. // since responses may arrive in arbitrary order
  1940. if (ajax_request != null)
  1941. {
  1942. ajax_request.abort();
  1943. ajax_request = null;
  1944. }
  1945. ajax_request = $.get(GetAbsoluteUrlAppRoot()+'pages/xml.navigator.php', { 'class': sClass, id: iId, relation: sRelation, format: 'html' },
  1946. function(data)
  1947. {
  1948. $('#impacted_objects').empty();
  1949. $('#impacted_objects').append(data);
  1950. $('#impacted_objects').unblock();
  1951. $('#impacted_objects .listResults').tablesorter( { widgets: ['myZebra', 'truncatedList']} ); // sortable and zebra tables
  1952. $('#impacted_objects table.listResults').tableHover(); // hover tables
  1953. }
  1954. );
  1955. }
  1956. }
  1957. UpdateImpactedObjects('$sClass', $id, '$sRelation');
  1958. EOF
  1959. );
  1960. $oP->SetCurrentTab('');
  1961. break;
  1962. ///////////////////////////////////////////////////////////////////////////////////////////
  1963. case 'cancel': // An action was cancelled
  1964. $oP->set_title(Dict::S('UI:OperationCancelled'));
  1965. $oP->add('<h1>'.Dict::S('UI:OperationCancelled').'</h1>');
  1966. break;
  1967. ///////////////////////////////////////////////////////////////////////////////////////////
  1968. default: // Menu node rendering (templates)
  1969. $oMenuNode = ApplicationMenu::GetMenuNode(ApplicationMenu::GetActiveNodeId());
  1970. if (is_object($oMenuNode))
  1971. {
  1972. $oMenuNode->RenderContent($oP, $oAppContext->GetAsHash());
  1973. $oP->set_title($oMenuNode->GetLabel());
  1974. }
  1975. ///////////////////////////////////////////////////////////////////////////////////////////
  1976. }
  1977. $oKPI->ComputeAndReport('GUI creation before output');
  1978. ExecutionKPI::ReportStats();
  1979. MetaModel::ShowQueryTrace();
  1980. DisplayWelcomePopup($oP);
  1981. $oP->output();
  1982. }
  1983. catch(CoreException $e)
  1984. {
  1985. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  1986. $oP = new SetupWebPage(Dict::S('UI:PageTitle:FatalError'));
  1987. if ($e instanceof SecurityException)
  1988. {
  1989. $oP->add("<h1>".Dict::S('UI:SystemIntrusion')."</h1>\n");
  1990. }
  1991. else
  1992. {
  1993. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  1994. }
  1995. $oP->error(Dict::Format('UI:Error_Details', $e->getHtmlDesc()));
  1996. $oP->output();
  1997. if (MetaModel::IsLogEnabledIssue())
  1998. {
  1999. if (MetaModel::IsValidClass('EventIssue'))
  2000. {
  2001. try
  2002. {
  2003. $oLog = new EventIssue();
  2004. $oLog->Set('message', $e->getMessage());
  2005. $oLog->Set('userinfo', '');
  2006. $oLog->Set('issue', $e->GetIssue());
  2007. $oLog->Set('impact', 'Page could not be displayed');
  2008. $oLog->Set('callstack', $e->getTrace());
  2009. $oLog->Set('data', $e->getContextData());
  2010. $oLog->DBInsertNoReload();
  2011. }
  2012. catch(Exception $e)
  2013. {
  2014. IssueLog::Error("Failed to log issue into the DB");
  2015. }
  2016. }
  2017. IssueLog::Error($e->getMessage());
  2018. }
  2019. // For debugging only
  2020. //throw $e;
  2021. }
  2022. catch(Exception $e)
  2023. {
  2024. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  2025. $oP = new SetupWebPage(Dict::S('UI:PageTitle:FatalError'));
  2026. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  2027. $oP->error(Dict::Format('UI:Error_Details', $e->getMessage()));
  2028. $oP->output();
  2029. if (MetaModel::IsLogEnabledIssue())
  2030. {
  2031. if (MetaModel::IsValidClass('EventIssue'))
  2032. {
  2033. try
  2034. {
  2035. $oLog = new EventIssue();
  2036. $oLog->Set('message', $e->getMessage());
  2037. $oLog->Set('userinfo', '');
  2038. $oLog->Set('issue', 'PHP Exception');
  2039. $oLog->Set('impact', 'Page could not be displayed');
  2040. $oLog->Set('callstack', $e->getTrace());
  2041. $oLog->Set('data', array());
  2042. $oLog->DBInsertNoReload();
  2043. }
  2044. catch(Exception $e)
  2045. {
  2046. IssueLog::Error("Failed to log issue into the DB");
  2047. }
  2048. }
  2049. IssueLog::Error($e->getMessage());
  2050. }
  2051. }
  2052. ?>