index.php 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522
  1. <?php
  2. // Copyright (C) 2010-2013 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * iTop User Portal main page
  20. *
  21. * @copyright Copyright (C) 2010-2013 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. require_once('../approot.inc.php');
  25. require_once(APPROOT.'/application/application.inc.php');
  26. require_once(APPROOT.'/application/nicewebpage.class.inc.php');
  27. require_once(APPROOT.'/application/wizardhelper.class.inc.php');
  28. /**
  29. * Helper to determine the supported types of tickets
  30. */
  31. function GetTicketClasses()
  32. {
  33. $aClasses = array();
  34. foreach (explode(',', MetaModel::GetConfig()->Get('portal_tickets')) as $sRawClass)
  35. {
  36. $sRawClass = trim($sRawClass);
  37. if (!MetaModel::IsValidClass($sRawClass))
  38. {
  39. throw new Exception("Class '$sRawClass' is not a valid class, please review your configuration (portal_tickets)");
  40. }
  41. if (!MetaModel::IsParentClass('Ticket', $sRawClass))
  42. {
  43. throw new Exception("Class '$sRawClass' does not inherit from Ticket, please review your configuration (portal_tickets)");
  44. }
  45. $aClasses[] = $sRawClass;
  46. }
  47. return $aClasses;
  48. }
  49. /**
  50. * Helper to protect the portal against malicious usages
  51. * Throws an exception if the current user is not allowed to view the object details
  52. */
  53. function ValidateObject($oObject)
  54. {
  55. if (IsPowerUser())
  56. {
  57. $sValidationDefine = 'PORTAL_'.strtoupper(get_class($oObject)).'_DISPLAY_POWERUSER_QUERY';
  58. } else
  59. {
  60. $sValidationDefine = 'PORTAL_'.strtoupper(get_class($oObject)).'_DISPLAY_QUERY';
  61. }
  62. if (defined($sValidationDefine))
  63. {
  64. $sValidationOql = constant($sValidationDefine);
  65. $oSearch = DBObjectSearch::FromOQL($sValidationOql);
  66. $oSearch->AddCondition('id', $oObject->GetKey());
  67. if ($iUser = UserRights::GetContactId())
  68. {
  69. $oContact = MetaModel::GetObject('Contact', $iUser);
  70. $aArgs = $oContact->ToArgs('contact');
  71. }
  72. else
  73. {
  74. $aArgs = array();
  75. }
  76. $oSet = new DBObjectSet($oSearch, array(), $aArgs);
  77. if ($oSet->Count() == 0)
  78. {
  79. throw new SecurityException('You are not allowed to access the object '.get_class($oObject).'::'.$oObject->GetKey());
  80. }
  81. }
  82. }
  83. /**
  84. * Helper to get the relevant constant
  85. */
  86. function GetConstant($sClass, $sName)
  87. {
  88. $sConstName = 'PORTAL_'.strtoupper($sClass).'_'.$sName;
  89. if (defined($sConstName))
  90. {
  91. return constant($sConstName);
  92. }
  93. else
  94. {
  95. throw new Exception("Missing portal constant '$sConstName'");
  96. }
  97. }
  98. /**
  99. * Helper to determine the ticket class given the service subcategory
  100. */
  101. function ComputeClass($iSubSvcId)
  102. {
  103. $aClasses = GetTicketClasses();
  104. if ((PORTAL_SET_TYPE_FROM == '') || (PORTAL_TYPE_TO_CLASS == ''))
  105. {
  106. // return the first enabled class
  107. $sClass = reset($aClasses);
  108. }
  109. else
  110. {
  111. $oServiceSubcat = MetaModel::GetObject('ServiceSubcategory', $iSubSvcId, true, true /* allow all data*/);
  112. $sTicketType = $oServiceSubcat->Get(PORTAL_SET_TYPE_FROM);
  113. $aMapping = json_decode(PORTAL_TYPE_TO_CLASS, true);
  114. if (!array_key_exists($sTicketType, $aMapping))
  115. {
  116. throw new Exception("Ticket type '$sTicketType' not found in the mapping (".implode(', ', array_keys($aMapping))."). Please contact your administrator.");
  117. }
  118. $sClass = $aMapping[$sTicketType];
  119. if (!in_array($sClass, $aClasses))
  120. {
  121. throw new Exception("Service subcategory #$iSubSvcId has a ticket type ($sClass) that is not known by the portal, please contact your administrator.");
  122. }
  123. }
  124. return $sClass;
  125. }
  126. /**
  127. * Helper to limit the service categories depending on the current settings
  128. */
  129. function RestrictSubcategories(&$oSearch)
  130. {
  131. $aMapping = (PORTAL_TYPE_TO_CLASS == '') ? array() : json_decode(PORTAL_TYPE_TO_CLASS, true);
  132. foreach($aMapping as $sTicketType => $sClass)
  133. {
  134. if (!in_array($sClass, GetTicketClasses()))
  135. {
  136. // Exclude this value for the result set
  137. $oSearch->AddCondition(PORTAL_SET_TYPE_FROM, $sTicketType, '!=');
  138. }
  139. }
  140. }
  141. /**
  142. * Displays the portal main menu
  143. * @param WebPage $oP The current web page
  144. * @return void
  145. */
  146. function DisplayMainMenu(WebPage $oP)
  147. {
  148. $oP->AddMenuButton('showongoing', 'Portal:ShowOngoing', '../portal/index.php?operation=show_ongoing');
  149. $oP->AddMenuButton('newrequest', 'Portal:CreateNewRequest', '../portal/index.php?operation=create_request');
  150. $oP->AddMenuButton('showclosed', 'Portal:ShowClosed', '../portal/index.php?operation=show_closed');
  151. $oP->AddMenuButton('showtoapprove', 'Portal:ShowToApprove', '../portal/index.php?operation=show_toapprove');
  152. if (isKeyUser()) {
  153. $oP->AddMenuButton('showtoresolve', 'Portal:ShowToResolve', '../portal/index.php?operation=show_toresolve');
  154. }
  155. /* THEBEN
  156. if (UserRights::CanChangePassword())
  157. {
  158. $oP->AddMenuButton('change_pwd', 'Portal:ChangeMyPassword', '../portal/index.php?loginop=change_pwd');
  159. } */
  160. }
  161. /**
  162. * Displays the current tickets
  163. * @param WebPage $oP The current web page
  164. * @return void
  165. */
  166. function ShowOngoingTickets(WebPage $oP)
  167. {
  168. $oP->add("<div id=\"open_requests\">\n");
  169. $oP->add("<h1 id=\"title_open_requests\">".Dict::S('Portal:OpenRequests')."</h1>\n");
  170. ListOpenRequests($oP);
  171. $oP->add("</div>\n");
  172. $oP->add("<div id=\"#div_resolved_requests\">\n");
  173. $oP->add("<h1 id=\"#resolved_requests\">".Dict::S('Portal:ResolvedRequests')."</h1>\n");
  174. ListResolvedRequests($oP);
  175. $oP->add("</div>\n");
  176. $oP->add("<div id=\"#requests_to_approve\">\n");
  177. $oP->add("<h1 id=\"#title_requests_to_approve\">".Dict::S('Portal:RequestsToApprove')."</h1>\n");
  178. ListRequestsToApprove($oP);
  179. $oP->add("</div>\n");
  180. if (isKeyUser()) {
  181. $oP->add("<div id=\"open_requests\">\n");
  182. $oP->add("<h1 id=\"title_requests_to_resolve\">".Dict::S('Portal:RequestsToResolve')."</h1>\n");
  183. ListRequestsToResolve($oP);
  184. $oP->add("</div>\n");
  185. }
  186. }
  187. /**
  188. * Displays the tickets which need approval by mysel
  189. * @param WebPage $oP The current web page
  190. * @return void
  191. */
  192. // =========================== THEBEN ==================================
  193. function ShowTicketsToApprove(WebPage $oP)
  194. {
  195. $oP->add("<div id=\"open_requests\">\n");
  196. $oP->add("<h1 id=\"title_open_requests\">".Dict::S('Portal:RequestsToApprove')."</h1>\n");
  197. ListRequestsToApprove($oP);
  198. $oP->add("</div>\n");
  199. }
  200. /**
  201. * Displays the tickets which need approval by mysel
  202. * @param WebPage $oP The current web page
  203. * @return void
  204. */
  205. // =========================== THEBEN ==================================
  206. function ShowTicketsToResolve(WebPage $oP)
  207. {
  208. $oP->add("<div id=\"open_requests\">\n");
  209. $oP->add("<h1 id=\"title_requests_to_resolve\">".Dict::S('Portal:RequestsToResolve')."</h1>\n");
  210. ListRequestsToResolve($oP);
  211. $oP->add("</div>\n");
  212. }
  213. /**
  214. * Displays the closed tickets
  215. * @param WebPage $oP The current web page
  216. * @return void
  217. */
  218. function ShowClosedTickets(WebPage $oP)
  219. {
  220. $oP->add("<div id=\"#closed_tickets\">\n");
  221. //$oP->add("<h1 id=\"#closed_tickets\">".Dict::S('Portal:ListClosedTickets')."</h1>\n");
  222. ListClosedTickets($oP);
  223. $oP->add("</div>\n");
  224. }
  225. /**
  226. * Displays the form to select a Template
  227. * @param WebPage $oP Web page for the form output
  228. * @param Organization $oUserOrg The organization of the current user
  229. * @param $iSvcId Id of the selected service in case of pass-through (when there is only one service)
  230. * @param integer $iSubSvcId The identifier of the sub-service (fall through when there is only one sub-service)
  231. * @return void
  232. */
  233. function SelectRequestTemplate($oP, $oUserOrg, $iSvcId = null, $iSubSvcId = null)
  234. {
  235. $aParameters = $oP->ReadAllParams(PORTAL_ALL_PARAMS.',template_id');
  236. if (!is_null($iSvcId))
  237. {
  238. $aParameters['service_id'] = $iSvcId;
  239. }
  240. if (!is_null($iSubSvcId))
  241. {
  242. $aParameters['servicesubcategory_id'] = $iSubSvcId;
  243. }
  244. $iDefaultTemplate = isset($aParameters['template_id']) ? $aParameters['template_id'] : 0;
  245. if (MetaModel::IsValidClass('Template'))
  246. {
  247. $sClass = ComputeClass($aParameters['servicesubcategory_id']);
  248. try
  249. {
  250. $sOql = GetConstant($sClass, 'TEMPLATE_QUERY');
  251. }
  252. catch(Exception $e)
  253. {
  254. // Backward compatibility
  255. $sOql = REQUEST_TEMPLATE_QUERY;
  256. }
  257. $oSearch = DBObjectSearch::FromOQL($sOql);
  258. $oSearch->AllowAllData();
  259. $oSet = new CMDBObjectSet($oSearch, array(), array(
  260. 'service_id' => $aParameters['service_id'],
  261. 'servicesubcategory_id' => $aParameters['servicesubcategory_id']
  262. ));
  263. if ($oSet->Count() == 0)
  264. {
  265. RequestCreationForm($oP, $oUserOrg, $aParameters['service_id'], $aParameters['servicesubcategory_id'], 0);
  266. return;
  267. }
  268. elseif ($oSet->Count() == 1)
  269. {
  270. $oTemplate = $oSet->Fetch();
  271. $iTemplateId = $oTemplate->GetKey();
  272. RequestCreationForm($oP, $oUserOrg, $aParameters['service_id'], $aParameters['servicesubcategory_id'], $iTemplateId);
  273. return;
  274. }
  275. $oServiceSubCategory = MetaModel::GetObject('ServiceSubcategory', $aParameters['servicesubcategory_id'], false);
  276. if (is_object($oServiceSubCategory))
  277. {
  278. $oP->add("<div class=\"wizContainer\" id=\"form_select_servicesubcategory\">\n");
  279. $oP->add("<h1 id=\"select_template\">".Dict::Format('Portal:SelectRequestTemplate', $oServiceSubCategory->GetName())."</h1>\n");
  280. $oP->WizardFormStart('request_wizard', 3);
  281. $oP->add("<table>\n");
  282. while($oTemplate = $oSet->Fetch())
  283. {
  284. $id = $oTemplate->GetKey();
  285. $sChecked = "";
  286. if ($id == $iDefaultTemplate)
  287. {
  288. $sChecked = "checked";
  289. }
  290. $oP->add("<tr>");
  291. $oP->add("<td style=\"vertical-align:top\">");
  292. $oP->p("<input name=\"attr_template_id\" $sChecked type=\"radio\" id=\"template_$id\" value=\"$id\">");
  293. $oP->add("</td>");
  294. $oP->add("<td style=\"vertical-align:top\">");
  295. $oP->p("<b><label for=\"template_$id\">".$oTemplate->GetAsHTML('label')."</label></b>");
  296. $oP->p($oTemplate->GetAsHTML('description'));
  297. $oP->add("</td>");
  298. $oP->add("</tr>");
  299. }
  300. $oP->add("</table>\n");
  301. $oP->DumpHiddenParams($aParameters, array('template_id'));
  302. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"create_request\">");
  303. $oP->WizardFormButtons(BUTTON_BACK | BUTTON_NEXT | BUTTON_CANCEL); //Back button automatically discarded if on the first page
  304. $oP->WizardCheckSelectionOnSubmit(Dict::S('Portal:PleaseSelectATemplate'));
  305. $oP->WizardFormEnd();
  306. $oP->add("</div>\n");
  307. }
  308. else
  309. {
  310. $oP->p("Error: Invalid servicesubcategory_id = ".$aParameters['servicesubcategory_id']);
  311. }
  312. }
  313. else
  314. {
  315. RequestCreationForm($oP, $oUserOrg, $aParameters['service_id'], $aParameters['servicesubcategory_id']);
  316. return;
  317. }
  318. }
  319. /**
  320. * Displays the form for the final step of the ticket creation
  321. * @param WebPage $oP The current web page for the form output
  322. * @param Organization $oUserOrg The organization of the current user
  323. * @param integer $iSvcId The identifier of the service (fall through when there is only one service)
  324. * @param integer $iSubSvcId The identifier of the sub-service (fall through when there is only one sub-service)
  325. * @param integer $iTemplateId The identifier of the template (fall through when there is only one template)
  326. * @return void
  327. */
  328. function RequestCreationForm($oP, $oUserOrg)
  329. {
  330. $aParameters = $oP->ReadAllParams(PORTAL_ALL_PARAMS.',template_id');
  331. $sDescription = '';
  332. if (isset($aParameters['template_id']) && ($aParameters['template_id'] != 0))
  333. {
  334. $aTemplateFields = array();
  335. $oTemplate = MetaModel::GetObject('Template', $aParameters['template_id'], false);
  336. if (is_object($oTemplate))
  337. {
  338. $oFieldSearch = DBObjectSearch::FromOQL('SELECT TemplateField WHERE template_id = :template_id');
  339. $oFieldSearch->AllowAllData();
  340. $oFieldSet = new DBObjectSet($oFieldSearch, array('order' => true), array('template_id' => $oTemplate->GetKey()));
  341. while($oField = $oFieldSet->Fetch())
  342. {
  343. $sAttCode = $oField->Get('code');
  344. if (isset($aParameters[$sAttCode]))
  345. {
  346. $oField->Set('initial_value', $aParameters[$sAttCode]);
  347. }
  348. $aTemplateFields[$sAttCode] = $oField;
  349. }
  350. }
  351. }
  352. //$oServiceCategory = MetaModel::GetObject('Service', $aParameters['service_id'], false, true /* allow all data*/);
  353. //$oServiceSubCategory = MetaModel::GetObject('ServiceSubcategory', $aParameters['servicesubcategory_id'], false, true /* allow all data*/);
  354. //if (is_object($oServiceCategory) && is_object($oServiceSubCategory))
  355. {
  356. $sClass = "UserRequest"; // ComputeClass($oServiceSubCategory->GetKey());
  357. $oRequest = MetaModel::NewObject($sClass);
  358. $oRequest->Set('org_id', $oUserOrg->GetKey());
  359. $oRequest->Set('caller_id', UserRights::GetContactId());
  360. // $oRequest->Set('service_id', $aParameters['service_id']);
  361. // $oRequest->Set('servicesubcategory_id', $aParameters['servicesubcategory_id']);
  362. /* $oAttDef = MetaModel::GetAttributeDef($sClass, 'service_id');
  363. $aDetails[] = array('label' => $oAttDef->GetLabel(), 'value' => $oServiceCategory->GetName());
  364. $oAttDef = MetaModel::GetAttributeDef($sClass, 'servicesubcategory_id');
  365. $aDetails[] = array('label' => $oAttDef->GetLabel(), 'value' => $oServiceSubCategory->GetName());
  366. */
  367. $aList = explode(',', GetConstant($sClass, 'FORM_ATTRIBUTES'));
  368. IssueLog::info("aList, FORM_ATTRIBUTES=".print_r($aList,true));
  369. // TODO
  370. /* echo "<select name='userCharacters' id='userCharacter'>";
  371. echo "<option value='1'>Kid Wonder</option>";
  372. echo "<option value='3'>Oriel</option>";
  373. echo "</select>"; */
  374. $iFlags = 0;
  375. foreach($aList as $sAttCode)
  376. {
  377. $value = '';
  378. if (isset($aParameters[$sAttCode]))
  379. {
  380. $value = $aParameters[$sAttCode];
  381. $oRequest->Set($sAttCode, $value);
  382. }
  383. }
  384. $aFieldsMap = array();
  385. foreach($aList as $sAttCode)
  386. {
  387. IssueLog::Info("sAttCode=".$sAttCode);
  388. $value = '';
  389. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  390. IssueLog::Info("oAttDef=".print_r($oAttDef,true));
  391. $iFlags = $oRequest->GetAttributeFlags($sAttCode);
  392. if (isset($aParameters[$sAttCode]))
  393. {
  394. $value = $aParameters[$sAttCode];
  395. }
  396. $aArgs = array('this' => $oRequest);
  397. $sInputId = 'attr_'.$sAttCode;
  398. IssueLog::Info("sInputId=".$sInputId);
  399. $aFieldsMap[$sAttCode] = $sInputId;
  400. $sValue = "<span id=\"field_{$sInputId}\">".$oRequest->GetFormElementForField($oP, $sClass, $sAttCode, $oAttDef, $value, '', 'attr_'.$sAttCode, '', $iFlags, $aArgs).'</span>';
  401. IssueLog::Info("sValue=".$sValue);
  402. $aDetails[] = array('label' => $oAttDef->GetLabel(), 'value' => $sValue);
  403. }
  404. $aHidden = array();
  405. if (!empty($aTemplateFields))
  406. {
  407. foreach ($aTemplateFields as $sAttCode => $oField)
  408. {
  409. $sValue = $oField->GetFormElement($oP, $sClass);
  410. if ($oField->Get('input_type') == 'hidden')
  411. {
  412. $aHidden[] = $sValue;
  413. }
  414. else
  415. {
  416. $aDetails[] = array('label' => $oField->GetAsHTML('label'), 'value' => $sValue);
  417. }
  418. }
  419. }
  420. $oP->add_script(
  421. <<<EOF
  422. // Create the object once at the beginning of the page...
  423. var oWizardHelper = new WizardHelper('$sClass', '');
  424. EOF
  425. );
  426. $oP->add_linked_script("../js/json.js");
  427. $oP->add_linked_script("../js/forms-json-utils.js");
  428. $oP->add_linked_script("../js/wizardhelper.js");
  429. $oP->add_linked_script("../js/wizard.utils.js");
  430. $oP->add_linked_script("../js/linkswidget.js");
  431. $oP->add_linked_script("../js/extkeywidget.js");
  432. $oP->add_linked_script("../js/jquery.blockUI.js");
  433. $oP->add("<div class=\"wizContainer\" id=\"form_request_description\">\n");
  434. $oP->add("<h1 id=\"title_request_form\">".Dict::S('Portal:DescriptionOfTheRequest')."</h1>\n");
  435. $oP->WizardFormStart('request_form', 1);
  436. $oP->details($aDetails);
  437. // Add hidden fields for known values, enabling dependant attributes to be computed correctly
  438. //
  439. foreach($oRequest->ListChanges() as $sAttCode => $value)
  440. {
  441. if (!in_array($sAttCode, $aList))
  442. {
  443. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  444. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  445. {
  446. $sValue = htmlentities($oRequest->Get($sAttCode), ENT_QUOTES, 'UTF-8');
  447. $oP->add("<input type=\"hidden\" id=\"attr_$sAttCode\" name=\"attr_$sAttCode\" value=\"$sValue\">");
  448. $aFieldsMap[$sAttCode] = 'attr_'.$sAttCode;
  449. }
  450. }
  451. }
  452. if (isset($aParameters['template_id']) && ($aParameters['template_id'] != 0))
  453. {
  454. $oP->add("<input type=\"hidden\" name=\"attr_template_id\" value=\"{$aParameters['template_id']}\">");
  455. }
  456. $oP->add(implode("\n", $aHidden));
  457. $oAttPlugin = new AttachmentPlugIn();
  458. $oAttPlugin->OnDisplayRelations($oRequest, $oP, true /* edit */);
  459. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"create_request\">");
  460. $oP->WizardFormButtons(BUTTON_BACK | BUTTON_FINISH | BUTTON_CANCEL); //Back button automatically discarded if on the first page
  461. $oP->WizardFormEnd();
  462. $oP->add("</div>\n");
  463. $iFieldsCount = count($aFieldsMap);
  464. $sJsonFieldsMap = json_encode($aFieldsMap);
  465. // IssueLog::Info("sJsonFieldsMap=".$sJsonFieldsMap);
  466. $oP->add_ready_script(
  467. <<<EOF
  468. oWizardHelper.SetFieldsMap($sJsonFieldsMap);
  469. oWizardHelper.SetFieldsCount($iFieldsCount);
  470. // Starts the validation when the page is ready
  471. CheckFields('request_form', false);
  472. $('#request_form').submit( function() {
  473. return OnSubmit('request_form');
  474. });
  475. EOF
  476. );
  477. }
  478. // else
  479. // {
  480. // User not authorized to use this service ?
  481. //ShowOngoingTickets($oP);
  482. // }
  483. }
  484. /**
  485. * Validate the parameters and create the ticket object (based on the page's POSTed parameters)
  486. * @param WebPage $oP The current web page for the output
  487. * @param Organization $oUserOrg The organization of the current user
  488. * @return void
  489. */
  490. function DoCreateRequest($oP, $oUserOrg)
  491. { IssueLog::Info("DoCreateRequest");
  492. $aParameters = $oP->ReadAllParams(PORTAL_ALL_PARAMS.',template_id');
  493. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  494. if (!utils::IsTransactionValid($sTransactionId))
  495. {
  496. $oP->add("<h1>".Dict::S('UI:Error:ObjectAlreadyCreated')."</h1>\n");
  497. //ShowOngoingTickets($oP);
  498. return;
  499. }
  500. // Validate the parameters
  501. // 1) ServiceCategory
  502. $oSearch = DBObjectSearch::FromOQL(PORTAL_VALIDATE_SERVICECATEGORY_QUERY);
  503. $oSearch->AllowAllData(); // In case the user has the rights on his org only
  504. $oSet = new CMDBObjectSet($oSearch, array(), array('id' => $aParameters['service_id'], 'org_id' => $oUserOrg->GetKey()));
  505. if ($oSet->Count() != 1)
  506. {
  507. // Invalid service for the current user !
  508. throw new Exception("Invalid Service Category: id={$aParameters['service_id']} - count: ".$oSet->Count());
  509. }
  510. $oServiceCategory = $oSet->Fetch();
  511. // 2) Service Subcategory
  512. $oSearch = DBObjectSearch::FromOQL(PORTAL_VALIDATE_SERVICESUBCATEGORY_QUERY);
  513. RestrictSubcategories($oSearch);
  514. $oSearch->AllowAllData(); // In case the user has the rights on his org only
  515. $oSet = new CMDBObjectSet($oSearch, array(), array('service_id' => $aParameters['service_id'], 'id' =>$aParameters['servicesubcategory_id'],'org_id' => $oUserOrg->GetKey() ));
  516. if ($oSet->Count() != 1)
  517. {
  518. // Invalid subcategory
  519. throw new Exception("Invalid ServiceSubcategory: id={$aParameters['servicesubcategory_id']} for service category ".$oServiceCategory->GetName()."({$aParameters['service_id']}) - count: ".$oSet->Count());
  520. }
  521. $oServiceSubCategory = $oSet->Fetch();
  522. $sClass = ComputeClass($oServiceSubCategory->GetKey());
  523. $oRequest = MetaModel::NewObject($sClass);
  524. $aAttList = array_merge(explode(',', GetConstant($sClass, 'FORM_ATTRIBUTES')), array('service_id', 'servicesubcategory_id'));
  525. $oRequest->UpdateObjectFromPostedForm('' /* form prefix */, $aAttList);
  526. $oRequest->Set('org_id', $oUserOrg->GetKey());
  527. $oRequest->Set('caller_id', UserRights::GetContactId());
  528. if (isset($aParameters['moreinfo']))
  529. {
  530. // There is a template, insert it into the description
  531. $sLogAttCode = GetConstant($sClass, 'PUBLIC_LOG');
  532. $oRequest->Set($sLogAttCode, $aParameters['moreinfo']);
  533. }
  534. $sTypeAttCode = GetConstant($sClass, 'TYPE');
  535. if (($sTypeAttCode != '') && (PORTAL_SET_TYPE_FROM != ''))
  536. {
  537. $oRequest->Set($sTypeAttCode, $oServiceSubCategory->Get(PORTAL_SET_TYPE_FROM));
  538. }
  539. if (MetaModel::IsValidAttCode($sClass, 'origin'))
  540. {
  541. $oRequest->Set('origin', 'portal');
  542. }
  543. $oAttPlugin = new AttachmentPlugIn();
  544. $oAttPlugin->OnFormSubmit($oRequest);
  545. list($bRes, $aIssues) = $oRequest->CheckToWrite();
  546. if ($bRes)
  547. {
  548. if (isset($aParameters['template_id']))
  549. {
  550. $oTemplate = MetaModel::GetObject('Template', $aParameters['template_id']);
  551. $sLogAttCode = GetConstant($sClass, 'PUBLIC_LOG');
  552. $oRequest->Set($sLogAttCode, $oTemplate->GetPostedValuesAsText($oRequest)."\n");
  553. $oRequest->DBInsertNoReload();
  554. $oTemplate->RecordExtraDataFromPostedForm($oRequest);
  555. }
  556. else
  557. {
  558. $oRequest->DBInsertNoReload();
  559. }
  560. $oP->add("<h1>".Dict::Format('UI:Title:Object_Of_Class_Created', $oRequest->GetName(), MetaModel::GetName($sClass))."</h1>\n");
  561. //DisplayObject($oP, $oRequest, $oUserOrg);
  562. ShowOngoingTickets($oP);
  563. }
  564. else
  565. {
  566. RequestCreationForm($oP, $oUserOrg);
  567. $sIssueDesc = Dict::Format('UI:ObjectCouldNotBeWritten', implode(', ', $aIssues));
  568. $oP->add_ready_script("alert('".addslashes($sIssueDesc)."');");
  569. }
  570. }
  571. /**
  572. * Prompts the user for creating a new request
  573. * @param WebPage $oP The current web page
  574. * @return void
  575. */
  576. function CreateRequest(WebPage $oP, Organization $oUserOrg)
  577. {
  578. switch($oP->GetWizardStep())
  579. {
  580. // case 0:
  581. /* default:
  582. SelectServiceCategory($oP, $oUserOrg);
  583. break;
  584. case 1:
  585. SelectServiceSubCategory($oP, $oUserOrg);
  586. break;
  587. case 2:
  588. SelectRequestTemplate($oP, $oUserOrg);
  589. break; */
  590. case 0:
  591. RequestCreationForm($oP, $oUserOrg);
  592. break;
  593. case 1:
  594. DoCreateRequest($oP, $oUserOrg);
  595. break;
  596. }
  597. }
  598. /**
  599. * Helper to display lists (UserRequest, Incident, etc.)
  600. * Adjust the presentation depending on the following cases:
  601. * - no item at all
  602. * - items of one class only
  603. * - items of several classes
  604. */
  605. function DisplayRequestLists(WebPage $oP, $aClassToSet)
  606. {
  607. $iNotEmpty = 0; // Count of types for which there are some items to display
  608. foreach ($aClassToSet as $sClass => $oSet)
  609. {
  610. if ($oSet->Count() > 0)
  611. {
  612. $iNotEmpty++;
  613. }
  614. }
  615. if ($iNotEmpty == 0)
  616. {
  617. $oP->p(Dict::S('Portal:NoOpenRequest'));
  618. }
  619. else
  620. {
  621. foreach ($aClassToSet as $sClass => $oSet)
  622. {
  623. if ($iNotEmpty > 1)
  624. {
  625. // Differentiate the sublists
  626. $oP->add("<h2>".MetaModel::GetName($sClass)."</h2>\n");
  627. }
  628. if ($oSet->Count() > 0)
  629. {
  630. $sZList = GetConstant($sClass, 'LIST_ZLIST');
  631. $aZList = explode(',', $sZList);
  632. $oP->DisplaySet($oSet, $aZList, Dict::S('Portal:NoOpenRequest'));
  633. }
  634. }
  635. }
  636. }
  637. /**
  638. * Lists all the currently opened User Requests for the current user
  639. * @param WebPage $oP The current web page
  640. * @return void
  641. */
  642. function ListOpenRequests(WebPage $oP)
  643. {
  644. $oUserOrg = GetUserOrg();
  645. $aClassToSet = array();
  646. foreach (GetTicketClasses() as $sClass)
  647. {
  648. $sOQL = "SELECT $sClass WHERE org_id = :org_id AND status NOT IN ('closed', 'resolved')";
  649. $oSearch = DBObjectSearch::FromOQL($sOQL);
  650. $iUser = UserRights::GetContactId();
  651. if ($iUser > 0 && !IsPowerUser())
  652. {
  653. $oSearch->AddCondition('caller_id', $iUser);
  654. }
  655. $aClassToSet[$sClass] = new CMDBObjectSet($oSearch, array(), array('org_id' => $oUserOrg->GetKey()));
  656. }
  657. DisplayRequestLists($oP, $aClassToSet);
  658. }
  659. /**
  660. * Lists all the currently resolved (not yet closed) User Requests for the current user
  661. * @param WebPage $oP The current web page
  662. * @return void
  663. */
  664. function ListResolvedRequests(WebPage $oP)
  665. {
  666. $oUserOrg = GetUserOrg();
  667. $aClassToSet = array();
  668. foreach (GetTicketClasses() as $sClass)
  669. {
  670. $sOQL = "SELECT $sClass WHERE org_id = :org_id AND status = 'resolved'";
  671. $oSearch = DBObjectSearch::FromOQL($sOQL);
  672. $iUser = UserRights::GetContactId();
  673. if ($iUser > 0 && !IsPowerUser())
  674. {
  675. $oSearch->AddCondition('caller_id', $iUser);
  676. }
  677. $aClassToSet[$sClass] = new CMDBObjectSet($oSearch, array(), array('org_id' => $oUserOrg->GetKey()));
  678. }
  679. DisplayRequestLists($oP, $aClassToSet);
  680. }
  681. /**
  682. * Lists all the currently resolved (not yet closed) User Requests for the current user
  683. * @param WebPage $oP The current web page
  684. * @return void
  685. */
  686. // ========================= THEBEN ===================================
  687. function ListRequestsToApprove(WebPage $oP)
  688. {
  689. $oUserOrg = GetUserOrg();
  690. $aClassToSet = array();
  691. foreach (GetTicketClasses() as $sClass)
  692. {
  693. $sOQL = "SELECT $sClass WHERE org_id = :org_id AND status = 'waiting_for_approval'";
  694. $oSearch = DBObjectSearch::FromOQL($sOQL);
  695. $iUser = UserRights::GetContactId();
  696. $oSearch->AddCondition('approver_id', $iUser);
  697. $aClassToSet[$sClass] = new CMDBObjectSet($oSearch, array(), array('org_id' => $oUserOrg->GetKey()));
  698. }
  699. DisplayRequestLists($oP, $aClassToSet);
  700. }
  701. /**
  702. * Lists all the currently resolved (not yet closed) User Requests for the current user
  703. * @param WebPage $oP The current web page
  704. * @return void
  705. */
  706. // ========================= THEBEN ===================================
  707. function ListRequestsToResolve(WebPage $oP)
  708. {
  709. $oUserOrg = GetUserOrg();
  710. $aClassToSet = array();
  711. foreach (GetTicketClasses() as $sClass)
  712. {
  713. $sOQL = "SELECT $sClass WHERE org_id = :org_id AND status = 'assigned'";
  714. $oSearch = DBObjectSearch::FromOQL($sOQL);
  715. $iUser = UserRights::GetContactId();
  716. $oSearch->AddCondition('agent_id', $iUser);
  717. $aClassToSet[$sClass] = new CMDBObjectSet($oSearch, array(), array('org_id' => $oUserOrg->GetKey()));
  718. }
  719. DisplayRequestLists($oP, $aClassToSet);
  720. }
  721. /**
  722. * Lists all the currently closed tickets
  723. * @param WebPage $oP The current web page
  724. * @return void
  725. */
  726. function ListClosedTickets(WebPage $oP)
  727. {
  728. $aAttSpecs = explode(',', PORTAL_TICKETS_SEARCH_CRITERIA);
  729. // Remove the caller_id form the search criteria if the user is not a Portal Power User
  730. // since the user is only allowed to see her/his own tickets
  731. foreach($aAttSpecs as $idx => $sAttCode)
  732. {
  733. if (($sAttCode == 'caller_id') && !IsPowerUser())
  734. {
  735. unset($aAttSpecs[$idx]);
  736. }
  737. }
  738. $aClasses = GetTicketClasses();
  739. $sMainClass = reset($aClasses);
  740. $oP->DisplaySearchForm($sMainClass, $aAttSpecs, array('operation' => 'show_closed'), 'search_', false /* => not closed */);
  741. $oUserOrg = GetUserOrg();
  742. $oP->add("<h1>".Dict::S('Portal:ClosedRequests')."</h1>\n");
  743. $aClassToSet = array();
  744. foreach (GetTicketClasses() as $sClass)
  745. {
  746. $oSearch = $oP->PostedParamsToFilter($sClass, $aAttSpecs, 'search_');
  747. if(is_null($oSearch))
  748. {
  749. $oSearch = new DBObjectSearch($sClass);
  750. }
  751. $oSearch->AddCondition('org_id', $oUserOrg->GetKey());
  752. $oSearch->AddCondition('status', 'closed');
  753. $iUser = UserRights::GetContactId();
  754. if ($iUser > 0 && !IsPowerUser())
  755. {
  756. $oSearch->AddCondition('caller_id', $iUser);
  757. }
  758. $aClassToSet[$sClass] = new CMDBObjectSet($oSearch);
  759. }
  760. DisplayRequestLists($oP, $aClassToSet);
  761. }
  762. /**
  763. * Display an object - to be customized
  764. * @param WebPage $oP The current web page
  765. * @param Object $oObj Any kind of object
  766. * @param Object $oUserOrg The organization of the logged in user
  767. * @return void
  768. */
  769. function DisplayObject($oP, $oObj, $oUserOrg)
  770. {
  771. if (in_array(get_class($oObj), GetTicketClasses()))
  772. {
  773. ShowDetailsRequest($oP, $oObj);
  774. }
  775. else
  776. {
  777. throw new Exception("The class ".get_class($oObj)." is not handled through the portal");
  778. }
  779. }
  780. /**
  781. * Displays the details of a request
  782. * @param WebPage $oP The current web page
  783. * @param Object $oObj The target object
  784. * @return void
  785. */
  786. //============= THEBEN ============= ApproveButton === ResolveButton ===============
  787. function ShowDetailsRequest(WebPage $oP, $oObj)
  788. {
  789. $sClass = get_class($oObj);
  790. $sLogAttCode = GetConstant($sClass, 'PUBLIC_LOG');
  791. $sUserCommentAttCode = GetConstant($sClass, 'USER_COMMENT');
  792. $bIsReopenButton = false;
  793. $bIsCloseButton = false;
  794. $bIsEscalateButton = false;
  795. $bIsApproveButton = false;
  796. $bIsRejectButton = false;
  797. $bIsResolveButton = false;
  798. $bEditAttachments = false;
  799. $aEditAtt = array(); // List of attributes editable in the main form
  800. if (!MetaModel::DBIsReadOnly())
  801. {
  802. switch($oObj->GetState())
  803. {
  804. case 'resolved':
  805. $aEditAtt = array();
  806. $aTransitions = $oObj->EnumTransitions();
  807. $oSet = DBObjectSet::FromObject($oObj);
  808. // Add the "Reopen" button if this is valid action
  809. if (array_key_exists('ev_reopen', $aTransitions) && UserRights::IsStimulusAllowed($sClass, 'ev_reopen', $oSet))
  810. {
  811. $bIsReopenButton = true;
  812. MakeStimulusForm($oP, $oObj, 'ev_reopen', array($sLogAttCode));
  813. }
  814. // Add the "Close" button if this is valid action
  815. if (array_key_exists('ev_close', $aTransitions) && UserRights::IsStimulusAllowed($sClass, 'ev_close', $oSet))
  816. { if (($oObj->Get('caller_id') == UserRights::GetContactId())
  817. || IsPowerUSer()) {
  818. // I can only close a ticket if I'm the caller or a power user
  819. $bIsCloseButton = true;
  820. MakeStimulusForm($oP, $oObj, 'ev_close', array('user_satisfaction', $sUserCommentAttCode));
  821. }
  822. IssueLog::Info('caller_id='.$oObj->Get('caller_id')." user-id=".UserRights::GetContactId());
  823. }
  824. break;
  825. case 'waiting_for_approval':
  826. $aEditAtt = array();
  827. $aTransitions = $oObj->EnumTransitions();
  828. $oSet = DBObjectSet::FromObject($oObj);
  829. // Add the "Approve" button if this is valid action
  830. if (array_key_exists('ev_approve', $aTransitions)) //TODO check if current user is approver && UserRights::IsStimulusAllowed($sClass, 'ev_reopen', $oSet))
  831. {
  832. $bIsApproveButton = true;
  833. MakeStimulusForm($oP, $oObj, 'ev_approve', array($sLogAttCode));
  834. }
  835. // Add the "Reject" button if this is valid action
  836. if (array_key_exists('ev_reject', $aTransitions)) // TODO check if current user is approve && UserRights::IsStimulusAllowed($sClass, 'ev_close', $oSet))
  837. {
  838. $bIsRejectButton = true;
  839. MakeStimulusForm($oP, $oObj, 'ev_reject', array($sLogAttCode) ); //array('user_satisfaction', $sUserCommentAttCode));
  840. }
  841. break;
  842. case 'closed':
  843. // By convention 'closed' is the final state of a ticket and nothing can be done in such a state
  844. break;
  845. case 'assigned':
  846. $iFlags = $oObj->GetAttributeFlags($sLogAttCode);
  847. $bReadOnly = (($iFlags & (OPT_ATT_READONLY | OPT_ATT_HIDDEN)) != 0);
  848. if ($bReadOnly)
  849. {
  850. $aEditAtt = array();
  851. $bEditAttachments = false;
  852. }
  853. else
  854. {
  855. $aEditAtt = array(
  856. $sLogAttCode => '????'
  857. );
  858. $bEditAttachments = true;
  859. }
  860. if (isKeyUser()) {
  861. $aTransitions = $oObj->EnumTransitions();
  862. $oSet = DBObjectSet::FromObject($oObj);
  863. // Add the "Resolver" button if this is valid action
  864. if (array_key_exists('ev_resolve', $aTransitions)) //TODO check if current user is approver && UserRights::IsStimulusAllowed($sClass, 'ev_reopen', $oSet))
  865. {
  866. $bIsResolveButton = true;
  867. MakeStimulusForm($oP, $oObj, 'ev_resolve', array($sLogAttCode));
  868. }
  869. }
  870. break;
  871. default:
  872. // In all other states, the only possible action is to update the ticket (both the case log and the attachments)
  873. // This update is possible only if the case log field is not read-only or hidden in the current state
  874. $iFlags = $oObj->GetAttributeFlags($sLogAttCode);
  875. $bReadOnly = (($iFlags & (OPT_ATT_READONLY | OPT_ATT_HIDDEN)) != 0);
  876. if ($bReadOnly)
  877. {
  878. $aEditAtt = array();
  879. $bEditAttachments = false;
  880. }
  881. else
  882. {
  883. $aEditAtt = array(
  884. $sLogAttCode => '????'
  885. );
  886. $bEditAttachments = true;
  887. }
  888. break;
  889. }
  890. }
  891. // REFACTORISER LA MISE EN FORME
  892. $oP->add("<h1 id=\"title_request_details\">".$oObj->GetIcon()."&nbsp;".Dict::Format('Portal:TitleRequestDetailsFor_Request', $oObj->GetName())."</h1>\n");
  893. $aAttList = json_decode(GetConstant($sClass, 'DETAILS_ZLIST'), true);
  894. switch($oObj->GetState())
  895. {
  896. case 'closed':
  897. $aAttList['centered'][] = 'user_satisfaction';
  898. $aAttList['centered'][] = $sUserCommentAttCode;
  899. }
  900. // Remove the edited attribute from the shown attributes
  901. //
  902. foreach($aEditAtt as $sAttCode => $foo)
  903. {
  904. foreach($aAttList as $col => $aColumn)
  905. {
  906. if (in_array($sAttCode, $aColumn))
  907. {
  908. if(($index = array_search($sAttCode, $aColumn)) !== false)
  909. {
  910. unset($aAttList[$col][$index]);
  911. }
  912. }
  913. }
  914. }
  915. $oP->add("<div class=\"wizContainer\" id=\"form_commment_request\">\n");
  916. $oP->WizardFormStart('request_form', null);
  917. $oP->add('<div id="request_details">');
  918. $oP->add('<table id="request_details_table">');
  919. $oP->add('<tr>');
  920. $oP->add('<td style="vertical-align:top;">');
  921. $oP->DisplayObjectDetails($oObj, $aAttList['col:left']);
  922. $oP->add('</td>');
  923. $oP->add('<td style="vertical-align:top;">');
  924. $oP->DisplayObjectDetails($oObj, $aAttList['col:right']);
  925. $oP->add('</td>');
  926. $oP->add('</tr>');
  927. if (array_key_exists('centered', $aAttList))
  928. {
  929. $oP->add('<tr>');
  930. $oP->add('<td style="vertical-align:top;" colspan="2">');
  931. $oP->DisplayObjectDetails($oObj, $aAttList['centered']);
  932. $oP->add('</td>');
  933. $oP->add('</tr>');
  934. }
  935. // REFACTORISER
  936. $oP->add('<tr>');
  937. $oP->add('<td colspan="2" style="vertical-align:top;">');
  938. $oAttPlugin = new AttachmentPlugIn();
  939. if ($bEditAttachments)
  940. {
  941. $oAttPlugin->EnableDelete(false);
  942. $oAttPlugin->OnDisplayRelations($oObj, $oP, true /* edit */);
  943. }
  944. else
  945. {
  946. $oAttPlugin->OnDisplayRelations($oObj, $oP, false /* read */);
  947. }
  948. $oP->add('</td>');
  949. $oP->add('</tr>');
  950. $oP->add('<tr>');
  951. $oP->add('<td colspan="2" style="vertical-align:top;">');
  952. //$oP->add("<form action=\"../portal/index.php\" id=\"request_form\" method=\"post\">\n");
  953. //$oP->add('<table id=""><tr><td style="vertical-align:top;">');
  954. //$oP->add("<h1 id=\"title_request_details\">".Dict::Format('Portal:CommentsFor_Request', $oObj->GetName())."</h1>\n");
  955. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">");
  956. $oP->add("<input type=\"hidden\" name=\"id\" value=\"".$oObj->GetKey()."\">");
  957. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"update_request\">");
  958. $oP->add("<input type=\"hidden\" id=\"stimulus_to_apply\" name=\"apply_stimulus\" value=\"\">\n");
  959. $oP->add_script(
  960. <<<EOF
  961. function SetStimulusToApply(sStimulusCode)
  962. {
  963. $('#stimulus_to_apply').val(sStimulusCode);
  964. }
  965. EOF
  966. );
  967. $aEditFields = array(); // Intermediate array to avoid code duplication while splitting btw ticket_log and the rest
  968. foreach($aEditAtt as $sAttCode => $foo)
  969. {
  970. $sValue = $oObj->Get($sAttCode);
  971. $sDisplayValue = $oObj->GetEditValue($sAttCode);
  972. $aArgs = array('this' => $oObj, 'formPrefix' => '');
  973. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  974. $sInputId = 'input_'.$sAttCode;
  975. $sHTMLValue = "<span id=\"field_{$sInputId}\">".cmdbAbstractObject::GetFormElementForField($oP, $sClass, $sAttCode, $oAttDef, $sValue, $sDisplayValue, $sInputId, '', 0 /*$iFlags*/, $aArgs).'</span>';
  976. $aEditFields[$sAttCode] = array(
  977. 'label' => MetaModel::GetLabel($sClass, $sAttCode),
  978. 'value' => $sHTMLValue
  979. );
  980. }
  981. foreach($aEditFields as $sAttCode => $aFieldSpec)
  982. {
  983. if ($sAttCode == $sLogAttCode)
  984. {
  985. // Skip, the public log will be displayed below the buttons
  986. continue;
  987. }
  988. $oP->add("<div class=\"edit_item\">");
  989. $oP->add('<h1>'.$aFieldSpec['label'].'</h1>');
  990. $oP->add($aFieldSpec['value']);
  991. $oP->add('</div>');
  992. }
  993. if($bIsReopenButton)
  994. {
  995. $sStimulusCode = 'ev_reopen';
  996. $sTitle = addslashes(Dict::S('Portal:Button:ReopenTicket'));
  997. $sOk = addslashes(Dict::S('UI:Button:Ok'));
  998. $oP->p('<input type="button" onClick="RunStimulusDialog(\''.$sStimulusCode.'\', \''.$sTitle.'\', \''.$sOk.'\');" value="'.$sTitle.'...">');
  999. }
  1000. if($bIsApproveButton)
  1001. {
  1002. $sStimulusCode = 'ev_approve';
  1003. $sTitle = addslashes(Dict::S('Portal:Button:ApproveTicket'));
  1004. $sOk = addslashes(Dict::S('UI:Button:Ok'));
  1005. $oP->p('<input type="button" onClick="RunStimulusDialog(\''.$sStimulusCode.'\', \''.$sTitle.'\', \''.$sOk.'\');" value="'.$sTitle.'...">');
  1006. }
  1007. if($bIsRejectButton)
  1008. {
  1009. $sStimulusCode = 'ev_reject';
  1010. $sTitle = addslashes(Dict::S('Portal:Button:RejectTicket'));
  1011. $sOk = addslashes(Dict::S('UI:Button:Ok'));
  1012. $oP->p('<input type="button" onClick="RunStimulusDialog(\''.$sStimulusCode.'\', \''.$sTitle.'\', \''.$sOk.'\');" value="'.$sTitle.'...">');
  1013. }
  1014. if($bIsResolveButton)
  1015. {
  1016. $sStimulusCode = 'ev_resolve';
  1017. $sTitle = addslashes(Dict::S('Portal:Button:ResolveTicket'));
  1018. $sOk = addslashes(Dict::S('UI:Button:Ok'));
  1019. $oP->p('<input type="button" onClick="RunStimulusDialog(\''.$sStimulusCode.'\', \''.$sTitle.'\', \''.$sOk.'\');" value="'.$sTitle.'...">');
  1020. }
  1021. if($bIsCloseButton)
  1022. {
  1023. $sStimulusCode = 'ev_close';
  1024. $sTitle = addslashes(Dict::S('Portal:Button:CloseTicket'));
  1025. $sOk = addslashes(Dict::S('UI:Button:Ok'));
  1026. $oP->p('<input type="button" onClick="RunStimulusDialog(\''.$sStimulusCode.'\', \''.$sTitle.'\', \''.$sOk.'\');" value="'.$sTitle.'...">');
  1027. }
  1028. elseif (count($aEditAtt) > 0)
  1029. {
  1030. $oP->p('<input type="submit" value="'.Dict::S('Portal:Button:UpdateRequest').'">');
  1031. }
  1032. if ($bIsEscalateButton)
  1033. {
  1034. $sStimulusCode = 'ev_timeout';
  1035. $oP->p('<input type="submit" onClick="SetStimulusToApply(\''.$sStimulusCode.'\');" value="'.Dict::S('Portal:ButtonEscalate').'">');
  1036. }
  1037. $oP->add('</td>');
  1038. $oP->add('</tr>');
  1039. $oP->add('<tr>');
  1040. $oP->add('<td colspan="2" style="vertical-align:top;">');
  1041. if (isset($aEditFields[$sLogAttCode]))
  1042. {
  1043. $oP->add("<div class=\"edit_item\">");
  1044. $oP->add('<h1>'.$aEditFields[$sLogAttCode]['label'].'</h1>');
  1045. $oP->add($aEditFields[$sLogAttCode]['value']);
  1046. $oP->add('</div>');
  1047. }
  1048. else
  1049. {
  1050. $oP->add('<h1>'.MetaModel::GetLabel($sClass, $sLogAttCode).'</h1>');
  1051. $oP->add($oObj->GetAsHTML($sLogAttCode));
  1052. }
  1053. $oP->add('</td>');
  1054. $oP->add('</tr>');
  1055. $oP->add('</table>');
  1056. $oP->add('</div>');
  1057. $oP->WizardFormEnd();
  1058. $oP->add('</div>');
  1059. }
  1060. /**
  1061. * Create form to apply a stimulus
  1062. * @param WebPage $oP The current web page
  1063. * @param Object $oObj The target object
  1064. * @param String $sStimulusCode Stimulus that will be applied
  1065. * @param Array $aEditAtt List of attributes to edit
  1066. * @return void
  1067. */
  1068. function MakeStimulusForm(WebPage $oP, $oObj, $sStimulusCode, $aEditAtt)
  1069. {
  1070. static $bHasStimulusForm = false;
  1071. $sDialogId = $sStimulusCode."_dialog";
  1072. $sFormId = $sStimulusCode."_form";
  1073. $sCancelButtonLabel = Dict::S('UI:Button:Cancel');
  1074. $oP->add('<div id="'.$sDialogId.'" style="display: none;">');
  1075. $sClass = get_class($oObj);
  1076. $oP->add('<form id="'.$sFormId.'" method="post">');
  1077. $sTransactionId = utils::GetNewTransactionId();
  1078. $oP->add("<input type=\"hidden\" id=\"transaction_id\" name=\"transaction_id\" value=\"$sTransactionId\">\n");
  1079. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">");
  1080. $oP->add("<input type=\"hidden\" name=\"id\" value=\"".$oObj->GetKey()."\">");
  1081. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"update_request\">");
  1082. $oP->add("<input type=\"hidden\" id=\"stimulus_to_apply\" name=\"apply_stimulus\" value=\"$sStimulusCode\">\n");
  1083. $aTransitions = $oObj->EnumTransitions();
  1084. $aStimuli = MetaModel::EnumStimuli($sClass);
  1085. if (!isset($aTransitions[$sStimulusCode]))
  1086. {
  1087. // Invalid stimulus
  1088. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulusCode, $oObj->GetName(), $oObj->GetStateLabel()));
  1089. }
  1090. // Compute the attribute flags in the target state
  1091. $aTransition = $aTransitions[$sStimulusCode];
  1092. $sTargetState = $aTransition['target_state'];
  1093. $aTargetStates = MetaModel::EnumStates($sClass);
  1094. $aTargetState = $aTargetStates[$sTargetState];
  1095. $aExpectedAttributes = $aTargetState['attribute_list'];
  1096. foreach($aEditAtt as $sAttCode)
  1097. {
  1098. $sValue = $oObj->Get($sAttCode);
  1099. $sDisplayValue = $oObj->GetEditValue($sAttCode);
  1100. $aArgs = array('this' => $oObj, 'formPrefix' => '');
  1101. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1102. $sInputId = 'input_'.$sAttCode;
  1103. $iFlags = array_key_exists($sAttCode, $aExpectedAttributes) ? $aExpectedAttributes[$sAttCode] : 0;
  1104. $sHTMLValue = "<span id=\"field_{$sStimulusCode}_{$sInputId}\">".cmdbAbstractObject::GetFormElementForField($oP, $sClass, $sAttCode, $oAttDef, $sValue, $sDisplayValue, $sInputId, '', $iFlags, $aArgs).'</span>';
  1105. $oP->add('<h1>'.MetaModel::GetLabel($sClass, $sAttCode).'</h1>');
  1106. $oP->add($sHTMLValue);
  1107. }
  1108. $oP->add('</form>');
  1109. $oP->add('</div>');
  1110. if (!$bHasStimulusForm)
  1111. {
  1112. $bHasStimulusForm = true;
  1113. $oP->add_script(
  1114. <<<EOF
  1115. function RunStimulusDialog(sStimulusCode, sTitle, sOkButtonLabel)
  1116. {
  1117. var sWidth = 'auto';
  1118. if (sStimulusCode == 'ev_reopen')
  1119. {
  1120. // Avoid having a dialog spanning the complete width of the window
  1121. // just because it contains a CaseLog entry
  1122. sWidth = '80%';
  1123. }
  1124. $('#'+sStimulusCode+'_dialog').dialog({
  1125. height: 'auto',
  1126. width: sWidth,
  1127. modal: true,
  1128. title: sTitle,
  1129. buttons: [
  1130. { text: sOkButtonLabel, click: function() {
  1131. $(this).find('#'+sStimulusCode+'_form').submit();
  1132. } },
  1133. { text: "$sCancelButtonLabel", click: function() {
  1134. $(this).dialog( "close" );
  1135. } }
  1136. ]
  1137. });
  1138. // Start the validation
  1139. CheckFields(sStimulusCode+'_form', false);
  1140. $('#'+sStimulusCode+'_form').submit( function() {
  1141. return OnSubmit(sStimulusCode+'_form');
  1142. });
  1143. }
  1144. EOF
  1145. );
  1146. }
  1147. }
  1148. /**
  1149. * Get The organization of the current user (i.e. the organization of its contact)
  1150. * @param WebPage $oP The current page, for errors output
  1151. * @return Organization The user's org or null in case of problem...
  1152. */
  1153. function GetUserOrg()
  1154. {
  1155. $oOrg = null;
  1156. $iContactId = UserRights::GetContactId();
  1157. $oContact = MetaModel::GetObject('Contact', $iContactId, false); // false => Can fail
  1158. if (is_object($oContact))
  1159. {
  1160. $oOrg = MetaModel::GetObject('Organization', $oContact->Get('org_id'), false); // false => can fail
  1161. }
  1162. else
  1163. {
  1164. throw new Exception(Dict::S('Portal:ErrorNoContactForThisUser'));
  1165. }
  1166. return $oOrg;
  1167. }
  1168. /**
  1169. * Determine if the current user can be considered as being a portal power user
  1170. */
  1171. function IsPowerUSer()
  1172. {
  1173. $iUserID = UserRights::GetUserId();
  1174. $sOQLprofile = "SELECT URP_Profiles AS p JOIN URP_UserProfile AS up ON up.profileid=p.id WHERE up.userid = :user AND p.name = :profile";
  1175. $oProfileSet = new DBObjectSet(
  1176. DBObjectSearch::FromOQL($sOQLprofile),
  1177. array(),
  1178. array(
  1179. 'user' => $iUserID,
  1180. 'profile' => PORTAL_POWER_USER_PROFILE,
  1181. )
  1182. );
  1183. $bRes = ($oProfileSet->count() > 0);
  1184. return $bRes;
  1185. }
  1186. /**
  1187. * Determine if the current user can be considered as being a portal key user
  1188. * (can update tickets where he is agent and can resolve them)
  1189. */
  1190. function IsKeyUSer()
  1191. {
  1192. $iUserID = UserRights::GetUserId();
  1193. $sOQLprofile = "SELECT URP_Profiles AS p JOIN URP_UserProfile AS up ON up.profileid=p.id WHERE up.userid = :user AND p.name = :profile";
  1194. $oProfileSet = new DBObjectSet(
  1195. DBObjectSearch::FromOQL($sOQLprofile),
  1196. array(),
  1197. array(
  1198. 'user' => $iUserID,
  1199. 'profile' => 'PORTAL_KEY_USER_PROFILE',
  1200. )
  1201. );
  1202. $bRes = ($oProfileSet->count() > 0);
  1203. return $bRes;
  1204. }
  1205. ///////////////////////////////////////////////////////////////////////////////
  1206. //
  1207. // Main program
  1208. //
  1209. ///////////////////////////////////////////////////////////////////////////////
  1210. try
  1211. {
  1212. require_once(APPROOT.'/application/startup.inc.php');
  1213. require_once(APPROOT.'/application/portalwebpage.class.inc.php');
  1214. $oAppContext = new ApplicationContext();
  1215. $sOperation = utils::ReadParam('operation', '');
  1216. require_once(APPROOT.'/application/loginwebpage.class.inc.php');
  1217. LoginWebPage::DoLogin(false /* bMustBeAdmin */, true /* IsAllowedToPortalUsers */); // Check user rights and prompt if needed
  1218. ApplicationContext::SetUrlMakerClass('MyPortalURLMaker');
  1219. $aClasses = explode(',', MetaModel::GetConfig()->Get('portal_tickets'));
  1220. $sMainClass = trim(reset($aClasses));
  1221. if (!class_exists($sMainClass))
  1222. {
  1223. $oP = new WebPage(Dict::S('Portal:Title'));
  1224. $oP->p(dict::Format('Portal:NoRequestMgmt', UserRights::GetUserFriendlyName()));
  1225. }
  1226. else
  1227. {
  1228. $oUserOrg = GetUserOrg();
  1229. $sCode = $oUserOrg->Get('code');
  1230. $sAlternateStylesheet = '';
  1231. //IssueLog::Info("org code of user=".$sCode);
  1232. if (@file_exists("./$sCode/portal.css"))
  1233. {
  1234. $sAlternateStylesheet = "$sCode";
  1235. IssueLog::Info("using Alt Stylesheet: ".$sAlternateStylesheet);
  1236. }
  1237. $oP = new PortalWebPage(Dict::S('Portal:Title'), $sAlternateStylesheet);
  1238. $oP->EnableDisconnectButton(utils::CanLogOff());
  1239. $oP->SetWelcomeMessage(Dict::Format('Portal:WelcomeUserOrg', UserRights::GetUserFriendlyName(), $oUserOrg->GetName()));
  1240. if (is_object($oUserOrg))
  1241. {
  1242. switch($sOperation)
  1243. {
  1244. case 'show_closed':
  1245. $oP->set_title(Dict::S('Portal:ShowClosed'));
  1246. DisplayMainMenu($oP);
  1247. ShowClosedTickets($oP);
  1248. break;
  1249. case 'create_request':
  1250. $oP->set_title(Dict::S('Portal:CreateNewRequest'));
  1251. DisplayMainMenu($oP);
  1252. if (!MetaModel::DBIsReadOnly())
  1253. {
  1254. CreateRequest($oP, $oUserOrg);
  1255. }
  1256. break;
  1257. case 'details':
  1258. $oP->set_title(Dict::S('Portal:TitleDetailsFor_Request'));
  1259. DisplayMainMenu($oP);
  1260. $oObj = $oP->FindObjectFromArgs(GetTicketClasses());
  1261. ValidateObject($oObj);
  1262. DisplayObject($oP, $oObj, $oUserOrg);
  1263. break;
  1264. case 'update_request':
  1265. $oP->set_title(Dict::S('Portal:TitleDetailsFor_Request'));
  1266. DisplayMainMenu($oP);
  1267. if (!MetaModel::DBIsReadOnly())
  1268. {
  1269. $oObj = $oP->FindObjectFromArgs(GetTicketClasses());
  1270. ValidateObject($oObj);
  1271. $aAttList = array(
  1272. GetConstant(get_class($oObj), 'PUBLIC_LOG'),
  1273. 'user_satisfaction',
  1274. GetConstant(get_class($oObj), 'USER_COMMENT')
  1275. );
  1276. try
  1277. {
  1278. $oP->DoUpdateObjectFromPostedForm($oObj, $aAttList);
  1279. $oObj->Reload(); // Make sure the object is in good shape to be displayed
  1280. }
  1281. catch(TransactionException $e)
  1282. {
  1283. $oP->add("<h1>".Dict::S('UI:Error:ObjectAlreadyUpdated')."</h1>\n");
  1284. }
  1285. DisplayObject($oP, $oObj, $oUserOrg);
  1286. }
  1287. break;
  1288. // =================== THEBEN ===========================
  1289. case 'show_toapprove':
  1290. $oP->set_title(Dict::S('Portal:ShowToApprove'));
  1291. DisplayMainMenu($oP);
  1292. ShowTicketsToApprove($oP);
  1293. break;
  1294. // =================== THEBEN ===========================
  1295. case 'show_toresolve':
  1296. $oP->set_title(Dict::S('Portal:ShowToResolve'));
  1297. DisplayMainMenu($oP);
  1298. ShowTicketsToResolve($oP);
  1299. break;
  1300. case 'show_ongoing':
  1301. default:
  1302. $oP->set_title(Dict::S('Portal:ShowOngoing'));
  1303. DisplayMainMenu($oP);
  1304. ShowOngoingTickets($oP);
  1305. break;
  1306. }
  1307. }
  1308. }
  1309. $oP->output();
  1310. }
  1311. catch(CoreException $e)
  1312. {
  1313. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  1314. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  1315. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  1316. $oP->error(Dict::Format('UI:Error_Details', $e->getHtmlDesc()));
  1317. //$oP->p($e->getTraceAsString());
  1318. $oP->output();
  1319. if (MetaModel::IsLogEnabledIssue())
  1320. {
  1321. if (MetaModel::IsValidClass('EventIssue'))
  1322. {
  1323. try
  1324. {
  1325. $oLog = new EventIssue();
  1326. $oLog->Set('message', $e->getMessage());
  1327. $oLog->Set('userinfo', '');
  1328. $oLog->Set('issue', $e->GetIssue());
  1329. $oLog->Set('impact', 'Page could not be displayed');
  1330. $oLog->Set('callstack', $e->getTrace());
  1331. $oLog->Set('data', $e->getContextData());
  1332. $oLog->DBInsertNoReload();
  1333. }
  1334. catch(Exception $e)
  1335. {
  1336. IssueLog::Error("Failed to log issue into the DB");
  1337. }
  1338. }
  1339. IssueLog::Error($e->getMessage());
  1340. }
  1341. // For debugging only
  1342. //throw $e;
  1343. }
  1344. catch(Exception $e)
  1345. {
  1346. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  1347. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  1348. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  1349. $oP->error(Dict::Format('UI:Error_Details', $e->getMessage()));
  1350. //$oP->p($e->getTraceAsString());
  1351. $oP->output();
  1352. if (MetaModel::IsLogEnabledIssue())
  1353. {
  1354. if (MetaModel::IsValidClass('EventIssue'))
  1355. {
  1356. try
  1357. {
  1358. $oLog = new EventIssue();
  1359. $oLog->Set('message', $e->getMessage());
  1360. $oLog->Set('userinfo', '');
  1361. $oLog->Set('issue', 'PHP Exception');
  1362. $oLog->Set('impact', 'Page could not be displayed');
  1363. $oLog->Set('callstack', $e->getTrace());
  1364. $oLog->Set('data', array());
  1365. $oLog->DBInsertNoReload();
  1366. }
  1367. catch(Exception $e)
  1368. {
  1369. IssueLog::Error("Failed to log issue into the DB");
  1370. }
  1371. }
  1372. IssueLog::Error($e->getMessage());
  1373. }
  1374. }
  1375. ?>