portalwebpage.class.inc.php 30 KB

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