datatable.class.inc.php 30 KB

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