UI.php 85 KB

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