UI.php 85 KB

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