UI.php 84 KB

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