UI.php 84 KB

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