portalwebpage.class.inc.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  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. * Class PortalWebPage
  20. *
  21. * @copyright Copyright (C) 2010-2013 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. require_once(APPROOT."/application/nicewebpage.class.inc.php");
  25. require_once(APPROOT."/application/applicationcontext.class.inc.php");
  26. require_once(APPROOT."/application/user.preferences.class.inc.php");
  27. define('BUTTON_CANCEL', 1);
  28. define('BUTTON_BACK', 2);
  29. define('BUTTON_NEXT', 4);
  30. define('BUTTON_FINISH', 8);
  31. define('PARAM_ARROW_SEP', '_x_');
  32. class TransactionException extends Exception
  33. {
  34. }
  35. /**
  36. * Web page with some associated CSS and scripts (jquery) for a fancier display
  37. * of the Portal web page
  38. */
  39. class PortalWebPage extends NiceWebPage
  40. {
  41. /**
  42. * Portal menu
  43. */
  44. protected $m_sWelcomeMsg;
  45. protected $m_aMenuButtons;
  46. protected $m_oCtx;
  47. public function __construct($sTitle, $sAlternateStyleSheet = '')
  48. {
  49. $this->m_oCtx = new ContextTag('GUI:Portal');
  50. $this->m_sWelcomeMsg = '';
  51. $this->m_aMenuButtons = array();
  52. parent::__construct($sTitle);
  53. $this->add_header("Content-type: text/html; charset=utf-8");
  54. $this->add_header("Cache-control: no-cache");
  55. $this->add_linked_stylesheet("../css/jquery.treeview.css");
  56. $this->add_linked_stylesheet("../css/jquery.autocomplete.css");
  57. $this->add_linked_stylesheet("../css/jquery.multiselect.css");
  58. $sAbsURLAppRoot = addslashes(utils::GetAbsoluteUrlAppRoot()); // Pass it to Javascript scripts
  59. $sAbsURLModulesRoot = addslashes(utils::GetAbsoluteUrlModulesRoot()); // Pass it to Javascript scripts
  60. $oAppContext = new ApplicationContext();
  61. $sAppContext = addslashes($oAppContext->GetForLink());
  62. $this->add_dict_entry('UI:FillAllMandatoryFields');
  63. if ($sAlternateStyleSheet != '')
  64. {
  65. $this->add_linked_stylesheet("../portal/$sAlternateStyleSheet/portal.css");
  66. }
  67. else
  68. {
  69. $this->add_linked_stylesheet("../portal/portal.css");
  70. }
  71. $this->add_linked_script('../js/jquery.layout.min.js');
  72. $this->add_linked_script('../js/jquery.ba-bbq.min.js');
  73. $this->add_linked_script("../js/jquery.tablehover.js");
  74. $this->add_linked_script("../js/jquery.treeview.js");
  75. $this->add_linked_script("../js/jquery.autocomplete.js");
  76. $this->add_linked_script("../js/jquery.positionBy.js");
  77. $this->add_linked_script("../js/jquery.popupmenu.js");
  78. $this->add_linked_script("../js/date.js");
  79. $this->add_linked_script("../js/jquery.tablesorter.min.js");
  80. $this->add_linked_script("../js/jquery.tablesorter.pager.js");
  81. $this->add_linked_script("../js/jquery.blockUI.js");
  82. $this->add_linked_script("../js/utils.js");
  83. $this->add_linked_script("../js/forms-json-utils.js");
  84. $this->add_linked_script("../js/swfobject.js");
  85. $this->add_linked_script("../js/jquery.qtip-1.0.min.js");
  86. $this->add_linked_script('../js/jquery.multiselect.js');
  87. $this->add_linked_script("../js/ajaxfileupload.js");
  88. $this->add_linked_script("../js/ckeditor/ckeditor.js");
  89. $this->add_linked_script("../js/ckeditor/adapters/jquery.js");
  90. $sJSDisconnectedMessage = json_encode(Dict::S('UI:DisconnectedDlgMessage'));
  91. $sJSTitle = json_encode(Dict::S('UI:DisconnectedDlgTitle'));
  92. $sJSLoginAgain = json_encode(Dict::S('UI:LoginAgain'));
  93. $sJSStayOnThePage = json_encode(Dict::S('UI:StayOnThePage'));
  94. $sJSDaysMin = json_encode(array(Dict::S('DayOfWeek-Sunday-Min'), Dict::S('DayOfWeek-Monday-Min'), Dict::S('DayOfWeek-Tuesday-Min'), Dict::S('DayOfWeek-Wednesday-Min'),
  95. Dict::S('DayOfWeek-Thursday-Min'), Dict::S('DayOfWeek-Friday-Min'), Dict::S('DayOfWeek-Saturday-Min')));
  96. $sJSMonthsShort = json_encode(array(Dict::S('Month-01-Short'), Dict::S('Month-02-Short'), Dict::S('Month-03-Short'), Dict::S('Month-04-Short'), Dict::S('Month-05-Short'), Dict::S('Month-06-Short'),
  97. Dict::S('Month-07-Short'), Dict::S('Month-08-Short'), Dict::S('Month-09-Short'), Dict::S('Month-10-Short'), Dict::S('Month-11-Short'), Dict::S('Month-12-Short')));
  98. $iFirstDayOfWeek = (int) Dict::S('Calendar-FirstDayOfWeek');
  99. $this->add_ready_script(
  100. <<<EOF
  101. try
  102. {
  103. //add new widget called TruncatedList to properly display truncated lists when they are sorted
  104. $.tablesorter.addWidget({
  105. // give the widget a id
  106. id: "truncatedList",
  107. // format is called when the on init and when a sorting has finished
  108. format: function(table)
  109. {
  110. // Check if there is a "truncated" line
  111. this.truncatedList = false;
  112. if ($("tr td.truncated",table).length > 0)
  113. {
  114. this.truncatedList = true;
  115. }
  116. if (this.truncatedList)
  117. {
  118. $("tr td",table).removeClass('truncated');
  119. $("tr:last td",table).addClass('truncated');
  120. }
  121. }
  122. });
  123. $.tablesorter.addWidget({
  124. // give the widget a id
  125. id: "myZebra",
  126. // format is called when the on init and when a sorting has finished
  127. format: function(table)
  128. {
  129. // Replace the 'red even' lines by 'red_even' since most browser do not support 2 classes selector in CSS, etc..
  130. $("tbody tr:even",table).addClass('even');
  131. $("tbody tr.red:even",table).removeClass('red').removeClass('even').addClass('red_even');
  132. $("tbody tr.orange:even",table).removeClass('orange').removeClass('even').addClass('orange_even');
  133. $("tbody tr.green:even",table).removeClass('green').removeClass('even').addClass('green_even');
  134. }
  135. });
  136. $(".date-pick").datepicker({
  137. showOn: 'button',
  138. buttonImage: '../images/calendar.png',
  139. buttonImageOnly: true,
  140. dateFormat: 'yy-mm-dd',
  141. constrainInput: false,
  142. changeMonth: true,
  143. changeYear: true,
  144. dayNamesMin: $sJSDaysMin,
  145. monthNamesShort: $sJSMonthsShort,
  146. firstDay: $iFirstDayOfWeek
  147. });
  148. $(".datetime-pick").datepicker({
  149. showOn: 'button',
  150. buttonImage: '../images/calendar.png',
  151. buttonImageOnly: true,
  152. dateFormat: 'yy-mm-dd 00:00:00',
  153. constrainInput: false,
  154. changeMonth: true,
  155. changeYear: true,
  156. dayNamesMin: $sJSDaysMin,
  157. monthNamesShort: $sJSMonthsShort,
  158. firstDay: $iFirstDayOfWeek
  159. });
  160. //$('.resizable').resizable(); // Make resizable everything that claims to be resizable !
  161. $('.caselog_header').click( function () { $(this).toggleClass('open').next('.caselog_entry_html').toggle(); });
  162. $(document).ajaxSend(function(event, jqxhr, options) {
  163. jqxhr.setRequestHeader('X-Combodo-Ajax', 'true');
  164. });
  165. $(document).ajaxError(function(event, jqxhr, options) {
  166. if (jqxhr.status == 401)
  167. {
  168. $('<div>'+$sJSDisconnectedMessage+'</div>').dialog({
  169. modal:true,
  170. title: $sJSTitle,
  171. close: function() { $(this).remove(); },
  172. minWidth: 400,
  173. buttons: [
  174. { text: $sJSLoginAgain, click: function() { window.location.href= GetAbsoluteUrlAppRoot()+'pages/UI.php' } },
  175. { text: $sJSStayOnThePage, click: function() { $(this).dialog('close'); } }
  176. ]
  177. });
  178. }
  179. });
  180. }
  181. catch(err)
  182. {
  183. // Do something with the error !
  184. alert(err);
  185. }
  186. EOF
  187. );
  188. $this->add_script(
  189. <<<EOF
  190. function CheckSelection(sMessage, sInputId)
  191. {
  192. var bResult;
  193. if (sInputId.length > 0)
  194. {
  195. bResult = ($('input[name='+sInputId+']:checked').length > 0);
  196. }
  197. else
  198. {
  199. // First select found...
  200. bResult = ($('input:checked').length > 0);
  201. }
  202. if (!bResult)
  203. {
  204. alert(sMessage);
  205. }
  206. return bResult;
  207. }
  208. function GetAbsoluteUrlAppRoot()
  209. {
  210. return '$sAbsURLAppRoot';
  211. }
  212. function GetAbsoluteUrlModulesRoot()
  213. {
  214. return '$sAbsURLModulesRoot';
  215. }
  216. function AddAppContext(sURL)
  217. {
  218. var sContext = '$sAppContext';
  219. if (sContext.length > 0)
  220. {
  221. if (sURL.indexOf('?') == -1)
  222. {
  223. return sURL+'?'+sContext;
  224. }
  225. return sURL+'&'+sContext;
  226. }
  227. return sURL;
  228. }
  229. function GoBack(sFormId)
  230. {
  231. var form = $('#'+sFormId);
  232. var step_back = $('input[name=step_back]');
  233. form.unbind('submit'); // De-activate validation
  234. step_back.val(1);
  235. form.submit(); // Go
  236. }
  237. function GoHome()
  238. {
  239. var form = $('FORM');
  240. form.unbind('submit'); // De-activate validation
  241. window.location.href = window.location.href.replace(/operation=[^&]*&?/, '');
  242. return false;
  243. }
  244. function SetWizardNextStep(sStep)
  245. {
  246. var next_step = $('input[id=next_step]');
  247. next_step.val(sStep);
  248. }
  249. // For disabling the CKEditor at init time when the corresponding textarea is disabled !
  250. CKEDITOR.plugins.add( 'disabler',
  251. {
  252. init : function( editor )
  253. {
  254. editor.on( 'instanceReady', function(e)
  255. {
  256. e.removeListener();
  257. $('#'+ editor.name).trigger('update');
  258. });
  259. }
  260. });
  261. EOF
  262. );
  263. // For Wizard helper to process the ajax replies
  264. $this->add('<div id="ajax_content"></div>');
  265. // Customize the logo (unless a customer CSS has been defined)
  266. if ($sAlternateStyleSheet == '')
  267. {
  268. if (file_exists(MODULESROOT.'branding/portal-logo.png'))
  269. {
  270. $sDisplayIcon = utils::GetAbsoluteUrlModulesRoot().'branding/portal-logo.png';
  271. $this->add_style("div#portal #logo {background: url(\"$sDisplayIcon\") no-repeat scroll 0 0 transparent;}");
  272. }
  273. }
  274. }
  275. public function SetCurrentTab($sTabLabel = '')
  276. {
  277. }
  278. /**
  279. * Specify a welcome message (optional)
  280. */
  281. public function SetWelcomeMessage($sMsg)
  282. {
  283. $this->m_sWelcomeMsg = $sMsg;
  284. }
  285. /**
  286. * Add a button to the portal's main menu
  287. */
  288. public function AddMenuButton($sId, $sLabel, $sHyperlink)
  289. {
  290. $this->m_aMenuButtons[] = array('id' => $sId, 'label' => $sLabel, 'hyperlink' => $sHyperlink);
  291. }
  292. var $m_bEnableDisconnectButton = true;
  293. public function EnableDisconnectButton($bEnable)
  294. {
  295. $this->m_bEnableDisconnectButton = $bEnable;
  296. }
  297. public function output()
  298. {
  299. $sApplicationBanner = '';
  300. if (!MetaModel::DBHasAccess(ACCESS_USER_WRITE))
  301. {
  302. $sReadOnly = Dict::S('UI:AccessRO-Users');
  303. $sAdminMessage = trim(MetaModel::GetConfig()->Get('access_message'));
  304. $sApplicationBanner .= '<div id="admin-banner">';
  305. $sApplicationBanner .= '<img src="../images/locked.png" style="vertical-align:middle;">';
  306. $sApplicationBanner .= '&nbsp;<b>'.$sReadOnly.'</b>';
  307. if (strlen($sAdminMessage) > 0)
  308. {
  309. $sApplicationBanner .= '&nbsp;: '.$sAdminMessage.'';
  310. }
  311. $sApplicationBanner .= '</div>';
  312. }
  313. $sMenu = '';
  314. if ($this->m_bEnableDisconnectButton)
  315. {
  316. $this->AddMenuButton('logoff', 'Portal:Disconnect', utils::GetAbsoluteUrlAppRoot().'pages/logoff.php?operation=do_logoff'); // This menu is always present and is the last one
  317. }
  318. foreach($this->m_aMenuButtons as $aMenuItem)
  319. {
  320. $sMenu .= "<a class=\"button\" id=\"{$aMenuItem['id']}\" href=\"{$aMenuItem['hyperlink']}\"><span>".Dict::S($aMenuItem['label'])."</span></a>";
  321. }
  322. $this->s_content = '<div id="portal"><div id="welcome">'.$this->m_sWelcomeMsg.'</div><div id="banner"><div id="logo"></div><div id="menu">'.$sMenu.'</div></div>'.$sApplicationBanner.'<div id="content">'.$this->s_content.'</div></div>';
  323. parent::output();
  324. }
  325. /**
  326. * Displays a list of objects, without any hyperlink (except for the object's details)
  327. * @param DBObjectSet $oSet The set of objects to display
  328. * @param Array $aZList The ZList (list of field codes) to use for the tabular display
  329. * @param String $sEmptyListMessage Message displayed whenever the list is empty
  330. * @return string The HTML text representing the list
  331. */
  332. public function DisplaySet($oSet, $aZList, $sEmptyListMessage = '')
  333. {
  334. if ($oSet->Count() > 0)
  335. {
  336. $sClass = $oSet->GetClass();
  337. if (is_subclass_of($sClass, 'cmdbAbstractObject'))
  338. {
  339. // Home-made and very limited display of an object set
  340. $sUniqueId = $sClass.$this->GetUniqueId();
  341. $this->add("<div id=\"$sUniqueId\">\n"); // The id here MUST be the same as currentId, otherwise the pagination will be broken
  342. cmdbAbstractObject::DisplaySet($this, $oSet, array('currentId' => $sUniqueId, 'menu' => false, 'toolkit_menu' => false, 'zlist' => false, 'extra_fields' => implode(',', $aZList)));
  343. $this->add("</div>\n");
  344. }
  345. else
  346. {
  347. // Home-made and very limited display of an object set
  348. $aAttribs = array();
  349. $aValues = array();
  350. $aAttribs['key'] = array('label' => MetaModel::GetName($sClass), 'description' => '');
  351. foreach($aZList as $sAttCode)
  352. {
  353. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  354. $aAttribs[$sAttCode] = array('label' => $oAttDef->GetLabel(), 'description' => $oAttDef->GetDescription());
  355. }
  356. while($oObj = $oSet->Fetch())
  357. {
  358. $aRow = array();
  359. $aRow['key'] = '<a href="./index.php?operation=details&class='.get_class($oObj).'&id='.$oObj->GetKey().'">'.$oObj->GetName().'</a>';
  360. $sHilightClass = $oObj->GetHilightClass();
  361. if ($sHilightClass != '')
  362. {
  363. $aRow['@class'] = $sHilightClass;
  364. }
  365. foreach($aZList as $sAttCode)
  366. {
  367. $aRow[$sAttCode] = $oObj->GetAsHTML($sAttCode);
  368. }
  369. $aValues[$oObj->GetKey()] = $aRow;
  370. }
  371. $this->table($aAttribs, $aValues);
  372. }
  373. }
  374. elseif (strlen($sEmptyListMessage) > 0)
  375. {
  376. $this->add($sEmptyListMessage);
  377. }
  378. }
  379. /**
  380. * Display the attributes of an object (no title, no form)
  381. * @param Object $oObj Any kind of object
  382. * @param aAttList The list of attributes to display
  383. * @return void
  384. */
  385. public function DisplayObjectDetails($oObj, $aAttList)
  386. {
  387. $sClass = get_class($oObj);
  388. $aDetails = array();
  389. foreach($aAttList as $sAttCode)
  390. {
  391. $iFlags = $oObj->GetAttributeFlags($sAttCode);
  392. $oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
  393. if ( (!$oAttDef->IsLinkSet()) && (($iFlags & OPT_ATT_HIDDEN) == 0) )
  394. {
  395. // Don't display linked set and non-visible attributes (in this state)
  396. $sDisplayValue = $oObj->GetAsHTML($sAttCode);
  397. $aDetails[] = array('label' => '<span title="'.MetaModel::GetDescription($sClass, $sAttCode).'">'.MetaModel::GetLabel($sClass, $sAttCode).'</span>', 'value' => $sDisplayValue);
  398. }
  399. }
  400. $this->details($aDetails);
  401. }
  402. /**
  403. * DisplayObjectLinkset
  404. * @param Object $oObj Any kind of object
  405. * @param $sLinkSetAttCode The attribute code of the link set attribute to display
  406. * @param $sRemoteAttCode The external key on the linked class, pointing to the remote objects
  407. * @param $aZList The list of attribute of the remote object
  408. * @param $sEmptyListMessage The message to display if the list is empty
  409. * @return void
  410. */
  411. public function DisplayObjectLinkset($oObj, $sLinkSetAttCode, $sRemoteAttCode, $aZList, $sEmptyListMessage = '', $oSearchRestriction = null)
  412. {
  413. if (empty($sEmptyListMessage))
  414. {
  415. $sEmptyListMessage = Dict::S('UI:Search:NoObjectFound');
  416. }
  417. $oLinkSet = $oObj->Get($sLinkSetAttCode);
  418. if ($oLinkSet->Count() > 0)
  419. {
  420. $sClass = $oLinkSet->GetClass();
  421. $oExtKeyToRemote = MetaModel::GetAttributeDef($sClass, $sRemoteAttCode);
  422. $sRemoteClass = $oExtKeyToRemote->GetTargetClass();
  423. if (is_null($oSearchRestriction))
  424. {
  425. $oObjSearch = new DBObjectSearch($sRemoteClass);
  426. }
  427. else
  428. {
  429. $oObjSearch = $oSearchRestriction;
  430. }
  431. $oObjSearch->AddCondition_ReferencedBy($oLinkSet->GetFilter(), $sRemoteAttCode);
  432. $aExtraParams = array('menu' => false, 'toolkit_menu' => false, 'zlist' => false, 'extra_fields' => implode(',', $aZList));
  433. $oBlock = new DisplayBlock($oObjSearch, 'list', false);
  434. $oBlock->Display($this, 1, $aExtraParams);
  435. }
  436. elseif (strlen($sEmptyListMessage) > 0)
  437. {
  438. $this->add($sEmptyListMessage);
  439. }
  440. }
  441. protected function DisplaySearchField($sClass, $sAttSpec, $aExtraParams, $sPrefix, $sFieldName = null, $aFilterParams = array())
  442. {
  443. if (is_null($sFieldName))
  444. {
  445. $sFieldName = str_replace('->', PARAM_ARROW_SEP, $sAttSpec);
  446. }
  447. $iPos = strpos($sAttSpec, '->');
  448. if ($iPos !== false)
  449. {
  450. $sAttCode = substr($sAttSpec, 0, $iPos);
  451. $sSubSpec = substr($sAttSpec, $iPos + 2);
  452. if (!MetaModel::IsValidAttCode($sClass, $sAttCode))
  453. {
  454. throw new Exception("Invalid attribute code '$sClass/$sAttCode' in search specification '$sAttSpec'");
  455. }
  456. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  457. if ($oAttDef->IsLinkSet())
  458. {
  459. $sTargetClass = $oAttDef->GetLinkedClass();
  460. }
  461. elseif ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE))
  462. {
  463. $sTargetClass = $oAttDef->GetTargetClass(EXTKEY_ABSOLUTE);
  464. }
  465. else
  466. {
  467. throw new Exception("Attribute specification '$sAttSpec', '$sAttCode' should be either a link set or an external key");
  468. }
  469. $this->DisplaySearchField($sTargetClass, $sSubSpec, $aExtraParams, $sPrefix, $sFieldName, $aFilterParams);
  470. }
  471. else
  472. {
  473. // $sAttSpec is an attribute code
  474. //
  475. $this->add('<span style="white-space: nowrap;padding:5px;display:inline-block;">');
  476. $sFilterValue = '';
  477. $sFilterValue = utils::ReadParam($sPrefix.$sFieldName, '', false, 'raw_data');
  478. $sFilterOpCode = null; // Use the default 'loose' OpCode
  479. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttSpec);
  480. if ($oAttDef->IsExternalKey())
  481. {
  482. $sTargetClass = $oAttDef->GetTargetClass();
  483. $sFilterDefName = 'PORTAL_TICKETS_SEARCH_FILTER_'.$sAttSpec;
  484. if (defined($sFilterDefName))
  485. {
  486. try
  487. {
  488. $oFitlerWithParams = DBObjectSearch::FromOQL(constant($sFilterDefName));
  489. $sFilterOQL = $oFitlerWithParams->ToOQL(true, $aFilterParams);
  490. $oAllowedValues = new DBObjectSet(DBObjectSearch::FromOQL($sFilterOQL), array(), $aFilterParams);
  491. }
  492. catch(OQLException $e)
  493. {
  494. throw new Exception("Incorrect filter '$sFilterDefName' for attribute '$sAttcode': ".$e->getMessage());
  495. }
  496. }
  497. else
  498. {
  499. $oAllowedValues = new DBObjectSet(new DBObjectSearch($sTargetClass));
  500. }
  501. $iFieldSize = $oAttDef->GetMaxSize();
  502. $iMaxComboLength = $oAttDef->GetMaximumComboLength();
  503. $this->add("<label>".MetaModel::GetFilterLabel($sClass, $sAttSpec).":</label>&nbsp;");
  504. //$oWidget = UIExtKeyWidget::DIsplayFromAttCode($sAttSpec, $sClass, $oAttDef->GetLabel(), $oAllowedValues, $sFilterValue, $sPrefix.$sFieldName, false, '', $sPrefix, '');
  505. //$this->add($oWidget->Display($this, $aExtraParams, true /* bSearchMode */));
  506. $aExtKeyParams = $aExtraParams;
  507. $aExtKeyParams['iFieldSize'] = $oAttDef->GetMaxSize();
  508. $aExtKeyParams['iMinChars'] = $oAttDef->GetMinAutoCompleteChars();
  509. // DisplayFromAttCode($this, $sAttCode, $sClass, $sTitle, $oAllowedValues, $value, $iInputId, $bMandatory, $sFieldName = '', $sFormPrefix = '', $aArgs, $bSearchMode = false)
  510. $sHtml = UIExtKeyWidget::DisplayFromAttCode($this, $sAttSpec, $sClass, $oAttDef->GetLabel(), $oAllowedValues, $sFilterValue, $sPrefix.$sFieldName, false, $sPrefix.$sFieldName, $sPrefix, $aExtKeyParams, true);
  511. $this->add($sHtml);
  512. }
  513. else
  514. {
  515. $aAllowedValues = MetaModel::GetAllowedValues_flt($sClass, $sAttSpec, $aExtraParams);
  516. if (is_null($aAllowedValues))
  517. {
  518. // Any value is possible, display an input box
  519. $sSanitizedValue = htmlentities($sFilterValue, ENT_QUOTES, 'UTF-8');
  520. $this->add("<label>".MetaModel::GetFilterLabel($sClass, $sAttSpec).":</label>&nbsp;<input class=\"textSearch\" name=\"$sPrefix$sFieldName\" value=\"$sSanitizedValue\"/>\n");
  521. }
  522. else
  523. {
  524. //Enum field or external key, display a combo
  525. $sValue = "<select name=\"$sPrefix$sFieldName\">\n";
  526. $sValue .= "<option value=\"\">".Dict::S('UI:SearchValue:Any')."</option>\n";
  527. foreach($aAllowedValues as $key => $value)
  528. {
  529. if ($sFilterValue == $key)
  530. {
  531. $sSelected = ' selected';
  532. }
  533. else
  534. {
  535. $sSelected = '';
  536. }
  537. $sValue .= "<option value=\"$key\"$sSelected>$value</option>\n";
  538. }
  539. $sValue .= "</select>\n";
  540. $this->add("<label>".MetaModel::GetFilterLabel($sClass, $sAttSpec).":</label>&nbsp;$sValue\n");
  541. }
  542. }
  543. unset($aExtraParams[$sFieldName]);
  544. $this->add('</span> ');
  545. $sTip = $oAttDef->GetHelpOnSmartSearch();
  546. if (strlen($sTip) > 0)
  547. {
  548. $sTip = addslashes($sTip);
  549. $sTip = str_replace(array("\n", "\r"), " ", $sTip);
  550. // :input does represent in form visible input (INPUT, SELECT, TEXTAREA)
  551. $this->add_ready_script("$(':input[name={$sPrefix}$sFieldName]').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );");
  552. }
  553. }
  554. }
  555. /**
  556. * Get The organization of the current user (i.e. the organization of its contact)
  557. * @throws Exception
  558. */
  559. function GetUserOrg()
  560. {
  561. $oOrg = null;
  562. $iContactId = UserRights::GetContactId();
  563. $oContact = MetaModel::GetObject('Contact', $iContactId, false); // false => Can fail
  564. if (is_object($oContact))
  565. {
  566. $oOrg = MetaModel::GetObject('Organization', $oContact->Get('org_id'), false); // false => can fail
  567. }
  568. else
  569. {
  570. throw new Exception(Dict::S('Portal:ErrorNoContactForThisUser'));
  571. }
  572. return $oOrg;
  573. }
  574. public function DisplaySearchForm($sClass, $aAttList, $aExtraParams, $sPrefix, $bClosed = true)
  575. {
  576. $oUserOrg = $this->GetUserOrg();
  577. $aFilterParams = array('org_id' => $oUserOrg->GetKey(), 'contact_id' => UserRights::GetContactId());
  578. $sCSSClass = ($bClosed) ? 'DrawerClosed' : '';
  579. $this->add("<div id=\"ds_$sPrefix\" class=\"SearchDrawer $sCSSClass\">\n");
  580. $this->add_ready_script(
  581. <<<EOF
  582. $("#dh_$sPrefix").click( function() {
  583. $("#ds_$sPrefix").slideToggle('normal', function() { $("#ds_$sPrefix").parent().resize(); } );
  584. $("#dh_$sPrefix").toggleClass('open');
  585. });
  586. EOF
  587. );
  588. $this->add("<form id=\"search_$sClass\" action=\"\" method=\"post\">\n"); // Don't use $_SERVER['SCRIPT_NAME'] since the form may be called asynchronously (from ajax.php)
  589. // $this->add("<h2>".Dict::Format('UI:SearchFor_Class_Objects', 'xxxxxx')."</h2>\n");
  590. $this->add("<p>\n");
  591. foreach($aAttList as $sAttSpec)
  592. {
  593. //$oAppContext->Reset($sAttSpec); // Make sure the same parameter will not be passed twice
  594. $this->DisplaySearchField($sClass, $sAttSpec, $aExtraParams, $sPrefix, null, $aFilterParams);
  595. }
  596. $this->add("</p>\n");
  597. $this->add("<p align=\"right\"><input type=\"submit\" value=\"".Dict::S('UI:Button:Search')."\"></p>\n");
  598. foreach($aExtraParams as $sName => $sValue)
  599. {
  600. // Note: use DumpHiddenParams() to transmit arrays as hidden params
  601. if (is_scalar($sValue))
  602. {
  603. $this->add("<input type=\"hidden\" name=\"$sName\" value=\"$sValue\" />\n");
  604. }
  605. }
  606. // $this->add($oAppContext->GetForForm());
  607. $this->add("</form>\n");
  608. $this->add("</div>\n");
  609. $this->add("<div class=\"HRDrawer\"></div>\n");
  610. $this->add("<div id=\"dh_$sPrefix\" class=\"DrawerHandle\">".Dict::S('UI:SearchToggle')."</div>\n");
  611. }
  612. /**
  613. * Read parameters from the page
  614. * Parameters that were absent from the page's parameters are not set in the resulting hash array
  615. * @input string $sMethod Either get or post
  616. * @return Hash Array of name => value corresponding to the parameters that were passed to the page
  617. */
  618. public function ReadAllParams($sParamList, $sPrefix = 'attr_')
  619. {
  620. $aParams = explode(',', $sParamList);
  621. $aValues = array();
  622. foreach($aParams as $sName)
  623. {
  624. $sName = trim($sName);
  625. $value = utils::ReadParam($sPrefix.$sName, null, false, 'raw_data');
  626. if (!is_null($value))
  627. {
  628. $aValues[$sName] = $value;
  629. }
  630. }
  631. return $aValues;
  632. }
  633. /**
  634. * Outputs a list of parameters as hidden fields
  635. * Example: attr_dummy[-123][id] = "blah"
  636. * @param Hash $aParameters Array name => value for the parameters
  637. * @param Array $aExclude The list of parameters that must not be handled this way (probably already in the visible part of the form)
  638. * @return void
  639. */
  640. protected function DumpHiddenParamsInternal($sName, $value)
  641. {
  642. if (is_array($value))
  643. {
  644. foreach($value as $sKey => $item)
  645. {
  646. $this->DumpHiddenParamsInternal($sName.'['.$sKey.']', $item);
  647. }
  648. }
  649. else
  650. {
  651. $this->Add("<input type=\"hidden\" name=\"$sName\" value=\"$value\">");
  652. }
  653. }
  654. /**
  655. * Outputs a list of parameters as hidden field into the current page
  656. * (must be called when inside a form)
  657. * @param Hash $aParameters Array name => value for the parameters
  658. * @param Array $aExclude The list of parameters that must not be handled this way (probably already in the visible part of the form)
  659. * @return void
  660. */
  661. public function DumpHiddenParams($aParameters, $aExclude = null, $sPrefix = 'attr_')
  662. {
  663. foreach($aParameters as $sAttCode => $value)
  664. {
  665. if (is_null($aExclude) || !in_array($sAttCode, $aExclude))
  666. {
  667. $this->DumpHiddenParamsInternal($sPrefix.$sAttCode, $value);
  668. }
  669. }
  670. }
  671. public function PostedParamsToFilter($sClass, $aAttList, $sPrefix)
  672. {
  673. $oFilter = new DBObjectSearch($sClass);
  674. $iCountParams = 0;
  675. foreach($aAttList as $sAttSpec)
  676. {
  677. $sFieldName = str_replace('->', PARAM_ARROW_SEP, $sAttSpec);
  678. $value = utils::ReadPostedParam($sPrefix.$sFieldName, null, 'raw_data');
  679. if (!is_null($value) && (is_array($value) ? count($value)>0 : strlen($value)>0))
  680. {
  681. $oFilter->AddConditionAdvanced($sAttSpec, $value);
  682. $iCountParams++;
  683. }
  684. }
  685. if ($iCountParams == 0)
  686. {
  687. return null;
  688. }
  689. else
  690. {
  691. return $oFilter;
  692. }
  693. }
  694. /**
  695. * Updates the object form POSTED arguments, and writes it into the DB (applies a stimuli if requested)
  696. * @param DBObject $oObj The object to update
  697. * $param array $aAttList If set, this will limit the list of updated attributes
  698. * @return void
  699. */
  700. public function DoUpdateObjectFromPostedForm(DBObject $oObj, $aAttList = null)
  701. {
  702. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  703. if (!utils::IsTransactionValid($sTransactionId))
  704. {
  705. throw new TransactionException();
  706. }
  707. $sClass = get_class($oObj);
  708. $sStimulus = trim(utils::ReadPostedParam('apply_stimulus', ''));
  709. $sTargetState = '';
  710. if (!empty($sStimulus))
  711. {
  712. // Compute the target state
  713. $aTransitions = $oObj->EnumTransitions();
  714. if (!isset($aTransitions[$sStimulus]))
  715. {
  716. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
  717. }
  718. $sTargetState = $aTransitions[$sStimulus]['target_state'];
  719. }
  720. $oObj->UpdateObjectFromPostedForm('' /* form prefix */, $aAttList, $sTargetState);
  721. // Optional: apply a stimulus
  722. //
  723. if (!empty($sStimulus))
  724. {
  725. if (!$oObj->ApplyStimulus($sStimulus))
  726. {
  727. throw new Exception("Cannot apply stimulus '$sStimulus' to {$oObj->GetName()}");
  728. }
  729. }
  730. if ($oObj->IsModified())
  731. {
  732. // Record the change
  733. //
  734. $oObj->DBUpdate();
  735. // Trigger ?
  736. //
  737. $aClasses = MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL);
  738. $sClassList = implode(", ", CMDBSource::Quote($aClasses));
  739. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnPortalUpdate AS t WHERE t.target_class IN ($sClassList)"));
  740. while ($oTrigger = $oSet->Fetch())
  741. {
  742. $oTrigger->DoActivate($oObj->ToArgs('this'));
  743. }
  744. $this->p("<h1>".Dict::Format('UI:Class_Object_Updated', MetaModel::GetName(get_class($oObj)), $oObj->GetName())."</h1>\n");
  745. }
  746. $bLockEnabled = MetaModel::GetConfig()->Get('concurrent_lock_enabled');
  747. if ($bLockEnabled)
  748. {
  749. // Release the concurrent lock, if any
  750. $sOwnershipToken = utils::ReadPostedParam('ownership_token', null, false, 'raw_data');
  751. if ($sOwnershipToken !== null)
  752. {
  753. // We're done, let's release the lock
  754. iTopOwnershipLock::ReleaseLock(get_class($oObj), $oObj->GetKey(), $sOwnershipToken);
  755. }
  756. }
  757. }
  758. /**
  759. * Find the object of the specified Class/ID.
  760. * @param WebPage $oP The current page
  761. * @return DBObject The found object, or throws an exception in case of failure
  762. */
  763. public function FindObjectFromArgs($aAllowedClasses = null)
  764. {
  765. $sClass = utils::ReadParam('class', '', true, 'class');
  766. $iId = utils::ReadParam('id', 0, true, 'integer');
  767. if (empty($sClass))
  768. {
  769. throw new Exception("Missing argument 'class'");
  770. }
  771. if (!MetaModel::IsValidClass($sClass))
  772. {
  773. throw new Exception("Wrong value for argument 'class': $sClass");
  774. }
  775. if ($iId == 0)
  776. {
  777. throw new Exception("Missing argument 'id'");
  778. }
  779. if(!is_null($aAllowedClasses))
  780. {
  781. $bAllowed = false;
  782. foreach($aAllowedClasses as $sParentClass)
  783. {
  784. if (MetaModel::IsParentClass($sParentClass, $sClass))
  785. {
  786. $bAllowed = true;
  787. }
  788. }
  789. if (!$bAllowed)
  790. {
  791. throw new Exception("Class '$sClass not allowed in this implementation'");
  792. }
  793. }
  794. $oObj = MetaModel::GetObject($sClass, $iId, false);
  795. if (!is_object($oObj))
  796. {
  797. throw new Exception("Could not find the object $sClass/$iId");
  798. }
  799. return $oObj;
  800. }
  801. var $m_sWizardId = null;
  802. public function WizardFormStart($sId = '', $sNextStep = null, $bAttachment = false, $sMethod = 'post')
  803. {
  804. $this->m_sWizardId = $sId;
  805. // multipart... needed for file upload
  806. $this->add("<form id=\"{$this->m_sWizardId}\" method=\"$sMethod\" enctype=\"multipart/form-data\" onsubmit=\"window.bInSubmit = true;\">\n");
  807. $aPreviousSteps = $this->GetWizardStepHistory();
  808. if (utils::ReadParam('step_back', 0) == 1)
  809. {
  810. // Back into the past history
  811. array_pop($aPreviousSteps);
  812. }
  813. else
  814. {
  815. // Moving forward
  816. array_push($aPreviousSteps, utils::ReadParam('next_step'));
  817. }
  818. $sStepHistory = implode(',', $aPreviousSteps);
  819. $this->add("<input type=\"hidden\" id=\"step_history\" name=\"step_history\" value=\"".htmlentities($sStepHistory, ENT_QUOTES, 'UTF-8')."\">");
  820. if (!is_null($sNextStep))
  821. {
  822. $this->add("<input type=\"hidden\" id=\"next_step\" name=\"next_step\" value=\"$sNextStep\">");
  823. }
  824. $this->add("<input type=\"hidden\" id=\"step_back\" name=\"step_back\" value=\"0\">");
  825. $sTransactionId = utils::GetNewTransactionId();
  826. $this->SetTransactionId($sTransactionId);
  827. $this->add("<input type=\"hidden\" id=\"transaction_id\" name=\"transaction_id\" value=\"$sTransactionId\">\n");
  828. $this->add_ready_script("$(window).unload(function() { OnUnload('$sTransactionId') } );\n");
  829. }
  830. public function WizardFormButtons($iButtonFlags)
  831. {
  832. $aButtons = array();
  833. if ($iButtonFlags & BUTTON_CANCEL)
  834. {
  835. $aButtons[] = "<input id=\"btn_cancel\" type=\"button\" value=\"".Dict::S('UI:Button:Cancel')."\" onClick=\"GoHome();\">";
  836. }
  837. if ($iButtonFlags & BUTTON_BACK)
  838. {
  839. if (utils::ReadParam('step_back', 1) != 1)
  840. {
  841. $aButtons[] = "<input id=\"btn_back\" type=\"submit\" value=\"".Dict::S('UI:Button:Back')."\" onClick=\"GoBack('{$this->m_sWizardId}');\">";
  842. }
  843. }
  844. if ($iButtonFlags & BUTTON_NEXT)
  845. {
  846. $aButtons[] = "<input id=\"btn_next\" type=\"submit\" value=\"".Dict::S('UI:Button:Next')."\">";
  847. }
  848. if ($iButtonFlags & BUTTON_FINISH)
  849. {
  850. $aButtons[] = "<input id=\"btn_finish\" type=\"submit\" value=\"".Dict::S('UI:Button:Finish')."\">";
  851. }
  852. $this->add('<div id="buttons">');
  853. $this->add(implode('', $aButtons));
  854. $this->add('</div>');
  855. }
  856. public function WizardFormEnd()
  857. {
  858. $this->add("</form>\n");
  859. }
  860. public function GetWizardStep()
  861. {
  862. if (utils::ReadParam('step_back', 0) == 1)
  863. {
  864. // Take the value into the history - one level above
  865. $aPreviousSteps = $this->GetWizardStepHistory();
  866. array_pop($aPreviousSteps);
  867. return end($aPreviousSteps);
  868. }
  869. else
  870. {
  871. return utils::ReadParam('next_step');
  872. }
  873. }
  874. protected function GetWizardStepHistory()
  875. {
  876. $sRawHistory = trim(utils::ReadParam('step_history', '', false, 'raw_data'));
  877. if (strlen($sRawHistory) == 0)
  878. {
  879. return array();
  880. }
  881. else
  882. {
  883. return explode(',', $sRawHistory);
  884. }
  885. }
  886. public function WizardCheckSelectionOnSubmit($sMessageIfNoSelection, $sInputName = '')
  887. {
  888. $this->add_ready_script(
  889. <<<EOF
  890. $('#{$this->m_sWizardId}').submit(function() {
  891. return CheckSelection('$sMessageIfNoSelection', '$sInputName');
  892. });
  893. EOF
  894. );
  895. }
  896. }
  897. ?>