datatable.class.inc.php 32 KB

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