portalwebpage.class.inc.php 28 KB

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