datatable.class.inc.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  1. <?php
  2. // Copyright (C) 2010-2012 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. * Data Table to display a set of objects in a tabular manner in HTML
  20. *
  21. * @copyright Copyright (C) 2010-2012 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. class DataTable
  25. {
  26. protected $iListId; // Unique ID inside the web page
  27. protected $sTableId; // identifier for saving the settings (combined with the class aliases)
  28. protected $oSet; // The set of objects to display
  29. protected $aClassAliases; // The aliases (alias => class) inside the set
  30. protected $iNbObjects; // Total number of objects inthe set
  31. protected $bUseCustomSettings; // Whether or not the current display uses custom settings
  32. protected $oDefaultSettings; // the default settings for displaying such a list
  33. /**
  34. * @param $iListId mixed Unique ID for this div/table in the page
  35. * @param $oSet DBObjectSet The set of data to display
  36. * @param $aClassAliases Hash The list of classes/aliases to be displayed in this set $sAlias => $sClassName
  37. * @param $sTableId mixed A string (or null) identifying this table in order to persist its settings
  38. */
  39. public function __construct($iListId, $oSet, $aClassAliases, $sTableId = null)
  40. {
  41. $this->iListId = utils::GetSafeId($iListId); // Make a "safe" ID for jQuery
  42. $this->oSet = $oSet;
  43. $this->aClassAliases = $aClassAliases;
  44. $this->sTableId = $sTableId;
  45. $this->iNbObjects = $oSet->Count();
  46. $this->bUseCustomSettings = false;
  47. $this->oDefaultSettings = null;
  48. }
  49. public function Display(WebPage $oPage, DataTableSettings $oSettings, $bActionsMenu, $sSelectMode, $bViewLink, $aExtraParams)
  50. {
  51. $this->oDefaultSettings = $oSettings;
  52. // Identified tables can have their own specific settings
  53. $oCustomSettings = DataTableSettings::GetTableSettings($this->aClassAliases, $this->sTableId);
  54. if ($oCustomSettings != null)
  55. {
  56. // Custom settings overload the default ones
  57. $this->bUseCustomSettings = true;
  58. }
  59. else
  60. {
  61. $oCustomSettings = $oSettings;
  62. }
  63. if ($oCustomSettings->iDefaultPageSize > 0)
  64. {
  65. $this->oSet->SetLimit($oCustomSettings->iDefaultPageSize);
  66. }
  67. $this->oSet->SetOrderBy($oCustomSettings->GetSortOrder());
  68. $bToolkitMenu = true;
  69. if (isset($aExtraParams['toolkit_menu']))
  70. {
  71. $bToolkitMenu = (bool) $aExtraParams['toolkit_menu'];
  72. }
  73. if (UserRights::IsPortalUser())
  74. {
  75. // Portal users have a limited access to data, for now they can only see what's configured for them
  76. $bToolkitMenu = false;
  77. }
  78. return $this->GetAsHTML($oPage, $oCustomSettings->iDefaultPageSize, $oCustomSettings->iDefaultPageSize, 0, $oCustomSettings->aColumns, $bActionsMenu, $bToolkitMenu, $sSelectMode, $bViewLink, $aExtraParams);
  79. }
  80. public function GetAsHTML(WebPage $oPage, $iPageSize, $iDefaultPageSize, $iPageIndex, $aColumns, $bActionsMenu, $bToolkitMenu, $sSelectMode, $bViewLink, $aExtraParams)
  81. {
  82. $sObjectsCount = $this->GetObjectCount($oPage, $sSelectMode);
  83. $sPager = $this->GetPager($oPage, $iPageSize, $iDefaultPageSize, $iPageIndex);
  84. $sActionsMenu = '';
  85. $sToolkitMenu = '';
  86. if ($bActionsMenu)
  87. {
  88. $sActionsMenu = $this->GetActionsMenu($oPage, $aExtraParams);
  89. }
  90. if ($bToolkitMenu)
  91. {
  92. $sToolkitMenu = $this->GetToolkitMenu($oPage, $aExtraParams);
  93. }
  94. $sDataTable = $this->GetHTMLTable($oPage, $aColumns, $sSelectMode, $iPageSize, $bViewLink, $aExtraParams);
  95. $sConfigDlg = $this->GetTableConfigDlg($oPage, $aColumns, $bViewLink, $iDefaultPageSize);
  96. $sHtml = "<table id=\"datatable_{$this->iListId}\" class=\"datatable\">";
  97. $sHtml .= "<tr><td>";
  98. $sHtml .= "<table style=\"width:100%;\">";
  99. $sHtml .= "<tr><td class=\"pagination_container\">$sObjectsCount</td><td class=\"menucontainer\">$sToolkitMenu $sActionsMenu</td></tr>";
  100. $sHtml .= "<tr>$sPager</tr>";
  101. $sHtml .= "</table>";
  102. $sHtml .= "</td></tr>";
  103. $sHtml .= "<tr><td class=\"datacontents\">$sDataTable</td></tr>";
  104. $sHtml .= "</table>\n";
  105. $oPage->add_at_the_end($sConfigDlg);
  106. $aOptions = array(
  107. 'sPersistentId' => '',
  108. 'sFilter' => $this->oSet->GetFilter()->serialize(),
  109. 'oColumns' => $aColumns,
  110. 'sSelectMode' => $sSelectMode,
  111. 'sViewLink' => ($bViewLink ? 'true' : 'false'),
  112. 'iNbObjects' => $this->iNbObjects,
  113. 'iDefaultPageSize' => $iDefaultPageSize,
  114. 'iPageSize' => $iPageSize,
  115. 'iPageIndex' => $iPageIndex,
  116. 'oClassAliases' => $this->aClassAliases,
  117. 'sTableId' => $this->sTableId,
  118. 'oExtraParams' => $aExtraParams,
  119. 'sRenderUrl' => utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php',
  120. 'oRenderParameters' => array('str' => ''), // Forces JSON to encode this as a object...
  121. 'oDefaultSettings' => array('str' => ''), // Forces JSON to encode this as a object...
  122. 'oLabels' => array('moveup' => Dict::S('UI:Button:MoveUp'), 'movedown' => Dict::S('UI:Button:MoveDown')),
  123. );
  124. if($this->oDefaultSettings != null)
  125. {
  126. $aOptions['oDefaultSettings'] = $this->GetAsHash($this->oDefaultSettings);
  127. }
  128. $sJSOptions = json_encode($aOptions);
  129. $oPage->add_ready_script("$('#datatable_{$this->iListId}').datatable($sJSOptions);");
  130. return $sHtml;
  131. }
  132. /**
  133. * When refreshing the body of a paginated table, get the rows of the table (inside the TBODY)
  134. * return string The HTML rows to insert inside the <tbody> node
  135. */
  136. public function GetAsHTMLTableRows(WebPage $oPage, $iPageSize, $aColumns, $sSelectMode, $bViewLink, $aExtraParams)
  137. {
  138. $aAttribs = $this->GetHTMLTableConfig($aColumns, $sSelectMode, $bViewLink);
  139. $aValues = $this->GetHTMLTableValues($aColumns, $sSelectMode, $iPageSize, $bViewLink, $aExtraParams);
  140. $sHtml = '';
  141. foreach($aValues as $aRow)
  142. {
  143. $sHtml .= $oPage->GetTableRow($aRow, $aAttribs);
  144. }
  145. return $sHtml;
  146. }
  147. protected function GetObjectCount(WebPage $oPage, $sSelectMode)
  148. {
  149. if (($sSelectMode == 'single') || ($sSelectMode == 'multiple'))
  150. {
  151. $sHtml = '<div class="pagination_objcount">'.Dict::Format('UI:Pagination:HeaderSelection', '<span id="total">'.$this->iNbObjects.'</span>', '<span class="selectedCount">0</span>').'</div>';
  152. }
  153. else
  154. {
  155. $sHtml = '<div class="pagination_objcount">'.Dict::Format('UI:Pagination:HeaderNoSelection', '<span id="total">'.$this->iNbObjects.'</span>').'</div>';
  156. }
  157. return $sHtml;
  158. }
  159. protected function GetPager(WebPage $oPage, $iPageSize, $iDefaultPageSize, $iPageIndex)
  160. {
  161. $sHtml = '';
  162. if ($iPageSize < 1) // Display all
  163. {
  164. $sPagerStyle = 'style="display:none"'; // no limit: display the full table, so hide the "pager" UI
  165. }
  166. else
  167. {
  168. $sPagerStyle = '';
  169. }
  170. $sCombo = '<select class="pagesize">';
  171. for($iPage = 1; $iPage < 5; $iPage++)
  172. {
  173. $iNbItems = $iPage * $iDefaultPageSize;
  174. $sSelected = ($iNbItems == $iPageSize) ? 'selected="selected"' : '';
  175. $sCombo .= "<option $sSelected value=\"$iNbItems\">$iNbItems</option>";
  176. }
  177. $sSelected = ($iPageSize < 1) ? 'selected="selected"' : '';
  178. $sCombo .= "<option $sSelected value=\"-1\">".Dict::S('UI:Pagination:All')."</option>";
  179. $sCombo .= '</select>';
  180. $sPages = Dict::S('UI:Pagination:PagesLabel');
  181. $sPageSizeCombo = Dict::Format('UI:Pagination:PageSize', $sCombo);
  182. $iNbPages = ($iPageSize < 1) ? 1 : ceil($this->iNbObjects / $iPageSize);
  183. if ($iNbPages == 1)
  184. {
  185. // No need to display the pager
  186. $sPagerStyle = 'style="display:none"';
  187. }
  188. $aPagesToDisplay = array();
  189. for($idx = 0; $idx <= min(4, $iNbPages-1); $idx++)
  190. {
  191. if ($idx == 0)
  192. {
  193. $aPagesToDisplay[$idx] = '<span page="0" class="curr_page">1</span>';
  194. }
  195. else
  196. {
  197. $aPagesToDisplay[$idx] = "<span id=\"gotopage_$idx\" class=\"gotopage\" page=\"$idx\">".(1+$idx)."</span>";
  198. }
  199. }
  200. $iLastPageIdx = $iNbPages - 1;
  201. if (!isset($aPagesToDisplay[$iLastPageIdx]))
  202. {
  203. unset($aPagesToDisplay[$idx - 1]); // remove the last page added to make room for the very last page
  204. $aPagesToDisplay[$iLastPageIdx] = "<span id=\"gotopage_$iLastPageIdx\" class=\"gotopage\" page=\"$iLastPageIdx\">... $iNbPages</span>";
  205. }
  206. $sPagesLinks = implode('', $aPagesToDisplay);
  207. $sPagesList = '['.implode(',', array_keys($aPagesToDisplay)).']';
  208. $sSelectionMode = ($iNbPages == 1) ? '' : 'positive';
  209. $sHtml =
  210. <<<EOF
  211. <td $sPagerStyle colspan="2">
  212. <table id="pager{$this->iListId}" class="pager"><tr>
  213. <td>$sPages</td>
  214. <td><img src="../images/first.png" class="first"/></td>
  215. <td><img src="../images/prev.png" class="prev"/></td>
  216. <td><span id="index">$sPagesLinks</span></td>
  217. <td><img src="../images/next.png" class="next"/></td>
  218. <td><img src="../images/last.png" class="last"/></td>
  219. <td>$sPageSizeCombo</td>
  220. <td><span id="loading">&nbsp;</span><input type="hidden" name="selectionMode" value="$sSelectionMode"></input>
  221. </td>
  222. </tr>
  223. </table>
  224. </td>
  225. EOF;
  226. return $sHtml;
  227. }
  228. protected function GetActionsMenu(WebPage $oPage, $aExtraParams)
  229. {
  230. $oMenuBlock = new MenuBlock($this->oSet->GetFilter(), 'list');
  231. $sHtml = $oMenuBlock->GetRenderContent($oPage, $aExtraParams, $this->iListId);
  232. return $sHtml;
  233. }
  234. protected function GetToolkitMenu(WebPage $oPage, $aExtraParams)
  235. {
  236. $sMenuTitle = Dict::S('UI:ConfigureThisList');
  237. $sHtml = '<div class="itop_popup toolkit_menu" id="tk_'.$this->iListId.'"><ul><li><img src="../images/toolkit_menu.png"><ul>';
  238. $oMenuItem1 = new JSPopupMenuItem('iTop::ConfigureList', $sMenuTitle, "$('#datatable_dlg_".$this->iListId."').dialog('open');");
  239. $aActions = array(
  240. $oMenuItem1->GetUID() => $oMenuItem1->GetMenuItem(),
  241. );
  242. $this->oSet->Rewind();
  243. utils::GetPopupMenuItems($oPage, iPopupMenuExtension::MENU_OBJLIST_TOOLKIT, $this->oSet, $aActions);
  244. $this->oSet->Rewind();
  245. $sHtml .= $oPage->RenderPopupMenuItems($aActions);
  246. return $sHtml;
  247. }
  248. protected function GetTableConfigDlg(WebPage $oPage, $aColumns, $bViewLink, $iDefaultPageSize)
  249. {
  250. $sHtml = "<div id=\"datatable_dlg_{$this->iListId}\" style=\"display: none;\">";
  251. $sHtml .= "<form onsubmit=\"return false\">";
  252. $sChecked = ($this->bUseCustomSettings) ? '' : 'checked';
  253. $sHtml .= "<p><input id=\"dtbl_dlg_settings_{$this->iListId}\" type=\"radio\" name=\"settings\" $sChecked value=\"defaults\"><label for=\"dtbl_dlg_settings_{$this->iListId}\">&nbsp;".Dict::S('UI:UseDefaultSettings').'</label></p>';
  254. $sHtml .= "<fieldset>";
  255. $sChecked = ($this->bUseCustomSettings) ? 'checked': '';
  256. $sHtml .= "<legend class=\"transparent\"><input id=\"dtbl_dlg_specific_{$this->iListId}\" type=\"radio\" class=\"specific_settings\" name=\"settings\" $sChecked value=\"specific\"><label for=\"dtbl_dlg_specific_{$this->iListId}\">&nbsp;".Dict::S('UI:UseSpecificSettings')."</label></legend>";
  257. $sHtml .= Dict::S('UI:ColumnsAndSortOrder').'<br/><ul class="sortable_field_list" id="sfl_'.$this->iListId.'"></ul>';
  258. $sHtml .= '<p>'.Dict::Format('UI:Display_X_ItemsPerPage', '<input type="text" size="4" name="page_size" value="'.$iDefaultPageSize.'">').'</p>';
  259. $sHtml .= "</fieldset>";
  260. $sHtml .= "<fieldset>";
  261. $sSaveChecked = ($this->sTableId != null) ? 'checked' : '';
  262. $sCustomDisabled = ($this->sTableId == null) ? 'disabled="disabled" stay-disabled="true" ' : '';
  263. $sCustomChecked = ($this->sTableId != null) ? 'checked' : '';
  264. $sGenericChecked = ($this->sTableId == null) ? 'checked' : '';
  265. $sHtml .= "<legend class=\"transparent\"><input id=\"dtbl_dlg_save_{$this->iListId}\" type=\"checkbox\" $sSaveChecked name=\"save_settings\"><label for=\"dtbl_dlg_save_{$this->iListId}\">&nbsp;".Dict::S('UI:UseSavetheSettings')."</label></legend>";
  266. $sHtml .= "<p><input id=\"dtbl_dlg_this_list_{$this->iListId}\" type=\"radio\" name=\"scope\" $sCustomChecked $sCustomDisabled value=\"this_list\"><label for=\"dtbl_dlg_this_list_{$this->iListId}\">&nbsp;".Dict::S('UI:OnlyForThisList').'</label>&nbsp;&nbsp;&nbsp;&nbsp;';
  267. $sHtml .= "<input id=\"dtbl_dlg_all_{$this->iListId}\" type=\"radio\" name=\"scope\" $sGenericChecked value=\"defaults\"><label for=\"dtbl_dlg_all_{$this->iListId}\">&nbsp;".Dict::S('UI:ForAllLists').'</label></p>';
  268. $sHtml .= "</fieldset>";
  269. $sHtml .= '<table style="width:100%"><tr><td style="text-align:center;">';
  270. $sHtml .= '<button type="button" onclick="$(\'#datatable_'.$this->iListId.'\').datatable(\'onDlgCancel\'); $(\'#datatable_dlg_'.$this->iListId.'\').dialog(\'close\')">'.Dict::S('UI:Button:Cancel').'</button>';
  271. $sHtml .= '</td><td style="text-align:center;">';
  272. $sHtml .= '<button type="submit" onclick="$(\'#datatable_'.$this->iListId.'\').datatable(\'onDlgOk\');$(\'#datatable_dlg_'.$this->iListId.'\').dialog(\'close\');">'.Dict::S('UI:Button:Ok').'</button>';
  273. $sHtml .= '</td></tr></table>';
  274. $sHtml .= "</form>";
  275. $sHtml .= "</div>";
  276. $sDlgTitle = addslashes(Dict::S('UI:ListConfigurationTitle'));
  277. $oPage->add_ready_script("$('#datatable_dlg_{$this->iListId}').dialog({autoOpen: false, title: '$sDlgTitle', width: 500, close: function() { $('#datatable_{$this->iListId}').datatable('onDlgCancel'); } });");
  278. return $sHtml;
  279. }
  280. public function GetAsHash($oSetting)
  281. {
  282. $aSettings = array('iDefaultPageSize' => $oSetting->iDefaultPageSize, 'oColumns' => $oSetting->aColumns);
  283. return $aSettings;
  284. }
  285. protected function GetHTMLTableConfig($aColumns, $sSelectMode, $bViewLink)
  286. {
  287. $aAttribs = array();
  288. if ($sSelectMode == 'multiple')
  289. {
  290. $aAttribs['form::select'] = array('label' => "<input type=\"checkbox\" onClick=\"CheckAll('.selectList{$this->iListId}:not(:disabled)', this.checked);\" class=\"checkAll\"></input>", 'description' => Dict::S('UI:SelectAllToggle+'));
  291. }
  292. else if ($sSelectMode == 'single')
  293. {
  294. $aAttribs['form::select'] = array('label' => "", 'description' => '');
  295. }
  296. foreach($this->aClassAliases as $sAlias => $sClassName)
  297. {
  298. foreach($aColumns[$sAlias] as $sAttCode => $aData)
  299. {
  300. if ($aData['checked'])
  301. {
  302. if ($sAttCode == '_key_')
  303. {
  304. $aAttribs['key_'.$sAlias] = array('label' => MetaModel::GetName($sClassName), 'description' => '');
  305. }
  306. else
  307. {
  308. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
  309. $aAttribs[$sAttCode.'_'.$sAlias] = array('label' => MetaModel::GetLabel($sClassName, $sAttCode), 'description' => $oAttDef->GetOrderByHint());
  310. }
  311. }
  312. }
  313. }
  314. return $aAttribs;
  315. }
  316. protected function GetHTMLTableValues($aColumns, $sSelectMode, $iPageSize, $bViewLink, $aExtraParams)
  317. {
  318. $bLocalize = true;
  319. if (isset($aExtraParams['localize_values']))
  320. {
  321. $bLocalize = (bool) $aExtraParams['localize_values'];
  322. }
  323. $aValues = array();
  324. $this->oSet->Seek(0);
  325. $iMaxObjects = $iPageSize;
  326. while (($aObjects = $this->oSet->FetchAssoc()) && ($iMaxObjects != 0))
  327. {
  328. $bFirstObject = true;
  329. $aRow = array();
  330. foreach($this->aClassAliases as $sAlias => $sClassName)
  331. {
  332. if (is_object($aObjects[$sAlias]))
  333. {
  334. $sHilightClass = $aObjects[$sAlias]->GetHilightClass();
  335. if ($sHilightClass != '')
  336. {
  337. $aRow['@class'] = $sHilightClass;
  338. }
  339. if ((($sSelectMode == 'single') || ($sSelectMode == 'multiple')) && $bFirstObject)
  340. {
  341. if (array_key_exists('selection_enabled', $aExtraParams) && isset($aExtraParams['selection_enabled'][$aObjects[$sAlias]->GetKey()]))
  342. {
  343. $sDisabled = ($aExtraParams['selection_enabled'][$aObjects[$sAlias]->GetKey()]) ? '' : ' disabled="disabled"';
  344. }
  345. else
  346. {
  347. $sDisabled = '';
  348. }
  349. if ($sSelectMode == 'single')
  350. {
  351. $aRow['form::select'] = "<input type=\"radio\" $sDisabled class=\"selectList{$this->iListId}\" name=\"selectObject\" value=\"".$aObjects[$sAlias]->GetKey()."\"></input>";
  352. }
  353. else
  354. {
  355. $aRow['form::select'] = "<input type=\"checkBox\" $sDisabled class=\"selectList{$this->iListId}\" name=\"selectObject[]\" value=\"".$aObjects[$sAlias]->GetKey()."\"></input>";
  356. }
  357. }
  358. foreach($aColumns[$sAlias] as $sAttCode => $aData)
  359. {
  360. if ($aData['checked'])
  361. {
  362. if ($sAttCode == '_key_')
  363. {
  364. $aRow['key_'.$sAlias] = $aObjects[$sAlias]->GetHyperLink();
  365. }
  366. else
  367. {
  368. $aRow[$sAttCode.'_'.$sAlias] = $aObjects[$sAlias]->GetAsHTML($sAttCode, $bLocalize);
  369. }
  370. }
  371. }
  372. }
  373. else
  374. {
  375. foreach($aColumns[$sAlias] as $sAttCode => $aData)
  376. {
  377. if ($aData['checked'])
  378. {
  379. if ($sAttCode == '_key_')
  380. {
  381. $aRow['key_'.$sAlias] = '';
  382. }
  383. else
  384. {
  385. $aRow[$sAttCode.'_'.$sAlias] = '';
  386. }
  387. }
  388. }
  389. }
  390. $bFirstObject = false;
  391. }
  392. $aValues[] = $aRow;
  393. $iMaxObjects--;
  394. }
  395. return $aValues;
  396. }
  397. public function GetHTMLTable(WebPage $oPage, $aColumns, $sSelectMode, $iPageSize, $bViewLink, $aExtraParams)
  398. {
  399. $iNbPages = ($iPageSize < 1) ? 1 : ceil($this->iNbObjects / $iPageSize);
  400. if ($iPageSize < 1)
  401. {
  402. $iPageSize = -1; // convention: no pagination
  403. }
  404. $aAttribs = $this->GetHTMLTableConfig($aColumns, $sSelectMode, $bViewLink);
  405. $aValues = $this->GetHTMLTableValues($aColumns, $sSelectMode, $iPageSize, $bViewLink, $aExtraParams);
  406. $sHtml = '<table class="listContainer">';
  407. foreach($this->oSet->GetFilter()->GetInternalParams() as $sName => $sValue)
  408. {
  409. $aExtraParams['query_params'][$sName] = $sValue;
  410. }
  411. $sHtml .= "<tr><td>";
  412. $sHtml .= $oPage->GetTable($aAttribs, $aValues);
  413. $sHtml .= '</td></tr>';
  414. $sHtml .= '</table>';
  415. $iCount = $this->iNbObjects;
  416. $aArgs = $this->oSet->GetArgs();
  417. $sExtraParams = addslashes(str_replace('"', "'", json_encode(array_merge($aExtraParams, $aArgs)))); // JSON encode, change the style of the quotes and escape them
  418. $sSelectModeJS = '';
  419. $sHeaders = '';
  420. if (($sSelectMode == 'single') || ($sSelectMode == 'multiple'))
  421. {
  422. $sSelectModeJS = $sSelectMode;
  423. $sHeaders = 'headers: { 0: {sorter: false}},';
  424. }
  425. $sDisplayKey = ($bViewLink) ? 'true' : 'false';
  426. // Protect against duplicate elements in the Zlist
  427. $aUniqueOrderedList = array();
  428. foreach($this->aClassAliases as $sAlias => $sClassName)
  429. {
  430. foreach($aColumns[$sAlias] as $sAttCode => $aData)
  431. {
  432. if ($aData['checked'])
  433. {
  434. $aUniqueOrderedList[$sAttCode] = true;
  435. }
  436. }
  437. }
  438. $aUniqueOrderedList = array_keys($aUniqueOrderedList);
  439. $sJSColumns = json_encode($aColumns);
  440. $sJSClassAliases = json_encode($this->aClassAliases);
  441. $sCssCount = isset($aExtraParams['cssCount']) ? ", cssCount: '{$aExtraParams['cssCount']}'" : '';
  442. $this->oSet->ApplyParameters();
  443. // Display the actual sort order of the table
  444. $aRealSortOrder = $this->oSet->GetRealSortOrder();
  445. $aDefaultSort = array();
  446. $iColOffset = 0;
  447. if (($sSelectMode == 'single') || ($sSelectMode == 'multiple'))
  448. {
  449. $iColOffset += 1;
  450. }
  451. if ($bViewLink)
  452. {
  453. // $iColOffset += 1;
  454. }
  455. foreach($aRealSortOrder as $sColCode => $bAscending)
  456. {
  457. $iPos = array_search($sColCode, $aUniqueOrderedList);
  458. if ($iPos !== false)
  459. {
  460. $aDefaultSort[] = "[".($iColOffset+$iPos).",".($bAscending ? '0' : '1')."]";
  461. }
  462. else if (($iPos = array_search(preg_replace('/_friendlyname$/', '', $sColCode), $aUniqueOrderedList)) !== false)
  463. {
  464. // if sorted on the friendly name of an external key, then consider it sorted on the column that shows the links
  465. $aDefaultSort[] = "[".($iColOffset+$iPos).",".($bAscending ? '0' : '1')."]";
  466. }
  467. else if($sColCode == 'friendlyname' && $bViewLink)
  468. {
  469. $aDefaultSort[] = "[".($iColOffset).",".($bAscending ? '0' : '1')."]";
  470. }
  471. }
  472. $sFakeSortList = '';
  473. if (count($aDefaultSort) > 0)
  474. {
  475. $sFakeSortList = '['.implode(',', $aDefaultSort).']';
  476. }
  477. $sOQL = addslashes($this->oSet->GetFilter()->serialize());
  478. $oPage->add_ready_script(
  479. <<<EOF
  480. var oTable = $('#{$this->iListId} table.listResults');
  481. oTable.tablesorter( { $sHeaders widgets: ['myZebra', 'truncatedList']} ).tablesorterPager({container: $('#pager{$this->iListId}'), totalRows:$iCount, size: $iPageSize, filter: '$sOQL', extra_params: '$sExtraParams', select_mode: '$sSelectModeJS', displayKey: $sDisplayKey, columns: $sJSColumns, class_aliases: $sJSClassAliases $sCssCount});
  482. EOF
  483. );
  484. if ($sFakeSortList != '')
  485. {
  486. $oPage->add_ready_script("oTable.trigger(\"fakesorton\", [$sFakeSortList]);");
  487. }
  488. //if ($iNbPages == 1)
  489. if (false)
  490. {
  491. if (isset($aExtraParams['cssCount']))
  492. {
  493. $sCssCount = $aExtraParams['cssCount'];
  494. if ($sSelectMode == 'single')
  495. {
  496. $sSelectSelector = ":radio[name^=selectObj]";
  497. }
  498. else if ($sSelectMode == 'multiple')
  499. {
  500. $sSelectSelector = ":checkbox[name^=selectObj]";
  501. }
  502. $oPage->add_ready_script(
  503. <<<EOF
  504. $('#{$this->iListId} table.listResults $sSelectSelector').change(function() {
  505. var c = $('{$sCssCount}');
  506. var v = $('#{$this->iListId} table.listResults $sSelectSelector:checked').length;
  507. c.val(v);
  508. $('#{$this->iListId} .selectedCount').text(v);
  509. c.trigger('change');
  510. });
  511. EOF
  512. );
  513. }
  514. }
  515. return $sHtml;
  516. }
  517. public function UpdatePager(WebPage $oPage, $iDefaultPageSize, $iStart)
  518. {
  519. $iPageSize = ($iDefaultPageSize < 1) ? 1 : $iDefaultPageSize;
  520. $iPageIndex = 1 + floor($iStart / $iPageSize);
  521. $sHtml = $this->GetPager($oPage, $iPageSize, $iDefaultPageSize, $iPageIndex);
  522. $oPage->add_ready_script("$('#pager{$this->iListId}').html('".str_replace("\n", ' ', addslashes($sHtml))."');");
  523. if ($iDefaultPageSize < 1)
  524. {
  525. $oPage->add_ready_script("$('#pager{$this->iListId}').parent().hide()");
  526. }
  527. else
  528. {
  529. $oPage->add_ready_script("$('#pager{$this->iListId}').parent().show()");
  530. }
  531. }
  532. }
  533. class DataTableSettings implements Serializable
  534. {
  535. public $aClassAliases;
  536. public $sTableId;
  537. public $iDefaultPageSize;
  538. public $aColumns;
  539. public function __construct($aClassAliases, $sTableId = null)
  540. {
  541. $this->aClassAliases = $aClassAliases;
  542. $this->sTableId = $sTableId;
  543. $this->iDefaultPageSize = 10;
  544. $this->aColumns = array();
  545. }
  546. protected function Init($iDefaultPageSize, $aSortOrder, $aColumns)
  547. {
  548. $this->iDefaultPageSize = $iDefaultPageSize;
  549. $this->aColumns = $aColumns;
  550. $this->FixVisibleColumns();
  551. }
  552. public function serialize()
  553. {
  554. // Save only the 'visible' columns
  555. $aColumns = array();
  556. foreach($this->aClassAliases as $sAlias => $sClass)
  557. {
  558. $aColumns[$sAlias] = array();
  559. foreach($this->aColumns[$sAlias] as $sAttCode => $aData)
  560. {
  561. unset($aData['label']); // Don't save the display name
  562. unset($aData['alias']); // Don't save the alias (redundant)
  563. unset($aData['code']); // Don't save the code (redundant)
  564. if ($aData['checked'])
  565. {
  566. $aColumns[$sAlias][$sAttCode] = $aData;
  567. }
  568. }
  569. }
  570. return serialize(
  571. array(
  572. 'iDefaultPageSize' => $this->iDefaultPageSize,
  573. 'aColumns' => $aColumns,
  574. )
  575. );
  576. }
  577. public function unserialize($sData)
  578. {
  579. $aData = unserialize($sData);
  580. $this->iDefaultPageSize = $aData['iDefaultPageSize'];
  581. $this->aColumns = $aData['aColumns'];
  582. foreach($this->aClassAliases as $sAlias => $sClass)
  583. {
  584. foreach($this->aColumns[$sAlias] as $sAttCode => $aData)
  585. {
  586. $aFieldData = false;
  587. if ($sAttCode == '_key_')
  588. {
  589. $aFieldData = $this->GetFieldData($sAlias, $sAttCode, null, true /* bChecked */, $aData['sort']);
  590. }
  591. else if (MetaModel::isValidAttCode($sClass, $sAttCode))
  592. {
  593. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  594. $aFieldData = $this->GetFieldData($sAlias, $sAttCode, $oAttDef, true /* bChecked */, $aData['sort']);
  595. }
  596. if ($aFieldData)
  597. {
  598. $this->aColumns[$sAlias][$sAttCode] = $aFieldData;
  599. }
  600. else
  601. {
  602. unset($this->aColumns[$sAlias][$sAttCode]);
  603. }
  604. }
  605. }
  606. $this->FixVisibleColumns();
  607. }
  608. static public function GetDataModelSettings($aClassAliases, $bViewLink, $aDefaultLists)
  609. {
  610. $oSettings = new DataTableSettings($aClassAliases);
  611. // Retrieve the class specific settings for each class/alias based on the 'list' ZList
  612. //TODO let the caller pass some other default settings (another Zlist, extre fields...)
  613. $aColumns = array();
  614. foreach($aClassAliases as $sAlias => $sClass)
  615. {
  616. if ($aDefaultLists == null)
  617. {
  618. $aList = cmdbAbstract::FlattenZList(MetaModel::GetZListItems($sClass, 'list'));
  619. }
  620. else
  621. {
  622. $aList = $aDefaultLists[$sAlias];
  623. }
  624. $aSortOrder = MetaModel::GetOrderByDefault($sClass);
  625. if ($bViewLink)
  626. {
  627. $sSort = 'none';
  628. if(array_key_exists('friendlyname', $aSortOrder))
  629. {
  630. $sSort = $aSortOrder['friendlyname'] ? 'asc' : 'desc';
  631. }
  632. $aColumns[$sAlias]['_key_'] = $oSettings->GetFieldData($sAlias, '_key_', null, true /* bChecked */, $sSort);
  633. }
  634. foreach($aList as $sAttCode)
  635. {
  636. $sSort = 'none';
  637. if(array_key_exists($sAttCode, $aSortOrder))
  638. {
  639. $sSort = $aSortOrder[$sAttCode] ? 'asc' : 'desc';
  640. }
  641. $oAttDef = Metamodel::GetAttributeDef($sClass, $sAttCode);
  642. $aFieldData = $oSettings->GetFieldData($sAlias, $sAttCode, $oAttDef, true /* bChecked */, $sSort);
  643. if ($aFieldData) $aColumns[$sAlias][$sAttCode] = $aFieldData;
  644. }
  645. }
  646. $iDefaultPageSize = appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit());
  647. $oSettings->Init($iDefaultPageSize, $aSortOrder, $aColumns);
  648. return $oSettings;
  649. }
  650. protected function FixVisibleColumns()
  651. {
  652. foreach($this->aClassAliases as $sAlias => $sClass)
  653. {
  654. foreach($this->aColumns[$sAlias] as $sAttCode => $aData)
  655. {
  656. // Remove non-existent columns
  657. // TODO: check if the existing ones are still valid (in case their type changed)
  658. if (($sAttCode != '_key_') && (!MetaModel::IsValidAttCode($sClass, $sAttCode)))
  659. {
  660. unset($this->aColumns[$sAlias][$sAttCode]);
  661. }
  662. }
  663. $aList = MetaModel::ListAttributeDefs($sClass);
  664. // Add the other (non visible ones), sorted in alphabetical order
  665. $aTempData = array();
  666. foreach($aList as $sAttCode => $oAttDef)
  667. {
  668. if ( (!array_key_exists($sAttCode, $this->aColumns[$sAlias])) && (!$oAttDef instanceof AttributeLinkSet))
  669. {
  670. $aFieldData = $this->GetFieldData($sAlias, $sAttCode, $oAttDef, false /* bChecked */, 'none');
  671. if ($aFieldData) $aTempData[$aFieldData['label']] = $aFieldData;
  672. }
  673. }
  674. ksort($aTempData);
  675. foreach($aTempData as $sLabel => $aFieldData)
  676. {
  677. $this->aColumns[$sAlias][$aFieldData['code']] = $aFieldData;
  678. }
  679. }
  680. }
  681. static public function GetTableSettings($aClassAliases, $sTableId = null)
  682. {
  683. $pref = null;
  684. $oSettings = new DataTableSettings($aClassAliases, $sTableId);
  685. if ($sTableId != null)
  686. {
  687. // An identified table, let's fetch its own settings (if any)
  688. $pref = appUserPreferences::GetPref($oSettings->GetPrefsKey($sTableId), null);
  689. }
  690. if ($pref == null)
  691. {
  692. // Try the global preferred values for this class / set of classes
  693. $pref = appUserPreferences::GetPref($oSettings->GetPrefsKey(null), null);
  694. if ($pref == null)
  695. {
  696. // no such settings, use the default values provided by the data model
  697. return null;
  698. }
  699. }
  700. $oSettings->unserialize($pref);
  701. return $oSettings;
  702. }
  703. public function GetSortOrder()
  704. {
  705. $aSortOrder = array();
  706. foreach($this->aColumns as $sAlias => $aColumns)
  707. {
  708. foreach($aColumns as $aColumn)
  709. {
  710. if ($aColumn['sort'] != 'none')
  711. {
  712. $sCode = ($aColumn['code'] == '_key_') ? 'friendlyname' : $aColumn['code'];
  713. $aSortOrder[$sCode] = ($aColumn['sort']=='asc'); // true for ascending, false for descending
  714. }
  715. }
  716. break; // TODO: For now the Set object supports only sorting on the first class of the set
  717. }
  718. return $aSortOrder;
  719. }
  720. public function Save()
  721. {
  722. if ($this->sTableId == null) return false; // Cannot save, the table is not identified, use SaveAsDefault instead
  723. $sSettings = $this->serialize();
  724. appUserPreferences::SetPref($this->GetPrefsKey($this->sTableId), $sSettings);
  725. return true;
  726. }
  727. public function SaveAsDefault()
  728. {
  729. $sSettings = $this->serialize();
  730. appUserPreferences::SetPref($this->GetPrefsKey(null), $sSettings);
  731. return true;
  732. }
  733. /**
  734. * Clear the preferences for this particular table
  735. * @param $bResetAll boolean If true,the settings for all tables of the same class(es)/alias(es) are reset
  736. */
  737. public function ResetToDefault($bResetAll)
  738. {
  739. if (($this->sTableId == null) && (!$bResetAll)) return false; // Cannot reset, the table is not identified, use force $bResetAll instead
  740. if ($bResetAll)
  741. {
  742. // Turn the key into a suitable PCRE pattern
  743. $sKey = $this->GetPrefsKey(null);
  744. $sPattern = str_replace(array('|'), array('\\|'), $sKey); // escape the | character
  745. $sPattern = '#^'.str_replace(array('*'), array('.*'), $sPattern).'$#'; // Don't use slash as the delimiter since it's used in our key to delimit aliases
  746. appUserPreferences::UnsetPref($sPattern, true);
  747. }
  748. else
  749. {
  750. appUserPreferences::UnsetPref($this->GetPrefsKey($this->sTableId), false);
  751. }
  752. return true;
  753. }
  754. protected function GetPrefsKey($sTableId = null)
  755. {
  756. if ($sTableId == null) $sTableId = '*';
  757. $aKeys = array();
  758. foreach($this->aClassAliases as $sAlias => $sClass)
  759. {
  760. $aKeys[] = $sAlias.'-'.$sClass;
  761. }
  762. return implode('/', $aKeys).'|'.$sTableId;
  763. }
  764. protected function GetFieldData($sAlias, $sAttCode, $oAttDef, $bChecked, $sSort)
  765. {
  766. $ret = false;
  767. if ($sAttCode == '_key_')
  768. {
  769. $sLabel = Dict::Format('UI:ExtKey_AsLink', MetaModel::GetName($this->aClassAliases[$sAlias]));
  770. $ret = array(
  771. 'label' => $sLabel,
  772. 'checked' => true,
  773. 'disabled' => true,
  774. 'alias' => $sAlias,
  775. 'code' => $sAttCode,
  776. 'sort' => $sSort,
  777. );
  778. }
  779. else if (!$oAttDef->IsLinkSet())
  780. {
  781. $sLabel = $oAttDef->GetLabel();
  782. if ($oAttDef->IsExternalKey())
  783. {
  784. $sLabel = Dict::Format('UI:ExtKey_AsLink', $oAttDef->GetLabel());
  785. }
  786. else if ($oAttDef->IsExternalField())
  787. {
  788. $oExtAttDef = $oAttDef->GetExtAttDef();
  789. $sLabel = Dict::Format('UI:ExtField_AsRemoteField', $oAttDef->GetLabel(), $oExtAttDef->GetLabel());
  790. }
  791. elseif ($oAttDef instanceof AttributeFriendlyName)
  792. {
  793. $sLabel = Dict::Format('UI:ExtKey_AsFriendlyName', $oAttDef->GetLabel());
  794. }
  795. $ret = array(
  796. 'label' => $sLabel,
  797. 'checked' => $bChecked,
  798. 'disabled' => false,
  799. 'alias' => $sAlias,
  800. 'code' => $sAttCode,
  801. 'sort' => $sSort,
  802. );
  803. }
  804. return $ret;
  805. }
  806. }