datatable.class.inc.php 29 KB

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