portalwebpage.class.inc.php 34 KB

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