UI.php 85 KB

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