BxBaseGrid.php 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup UnaBaseView UNA Base Representation Classes
  7. * @{
  8. */
  9. /**
  10. * Grid representation.
  11. * @see BxDolGrid
  12. */
  13. class BxBaseGrid extends BxDolGrid
  14. {
  15. protected $_oTemplate;
  16. protected $_oFunctions;
  17. protected $_aPopupOptions = false;
  18. protected $_sPaginateType; // default (empty value), simple, load_more
  19. protected $_aQueryAppend = [];
  20. protected $_aQueryAppendExclude = false; // an array of keys which shouldn't be pathed in http requests, but can be stored (used) in 'Query Append' array.
  21. protected $_aQueryAppendExcludeApi = false;
  22. protected $_aQueryReset = false;
  23. protected $_aConfirmMessages = false;
  24. protected $_bSelectAll = false;
  25. protected $_isDisplayPopupOnTextOverflow = true;
  26. protected $_aFilterAreaLabels = []; // filter name => accessible name (lang key or plain text); filter controls are rendered without a visible caption
  27. public function __construct ($aOptions, $oTemplate)
  28. {
  29. parent::__construct ($aOptions);
  30. if ($oTemplate)
  31. $this->_oTemplate = $oTemplate;
  32. else
  33. $this->_oTemplate = BxDolTemplate::getInstance();
  34. $this->_oFunctions = BxTemplFunctions::getInstanceWithTemplate($this->_oTemplate);
  35. $this->_aPopupOptions = [];
  36. $this->_sPaginateType = '';
  37. $this->_aQueryAppend = [
  38. $this->_oTemplate->getCodeKey() => $this->_oTemplate->getCode()
  39. ];
  40. $this->_aQueryAppendExclude = [];
  41. $this->_aQueryAppendExcludeApi = [$this->_oTemplate->getCodeKey()];
  42. $this->_aQueryReset = [
  43. $this->_aOptions['filter_get'],
  44. $this->_aOptions['order_get_field'],
  45. $this->_aOptions['order_get_dir'],
  46. $this->_aOptions['paginate_get_start'],
  47. $this->_aOptions['paginate_get_per_page']
  48. ];
  49. $this->_aConfirmMessages = [];
  50. }
  51. public function performActionDisplay()
  52. {
  53. if($this->_bIsApi)
  54. return $this->getCodeAPI();
  55. require_once(BX_DIRECTORY_PATH_INC . "design.inc.php");
  56. echoJson([
  57. 'grid' => $this->getCode(false),
  58. 'total_count' => $this->_iTotalCount,
  59. 'total_count_f' => $this->_getCounter()
  60. ]);
  61. }
  62. public function performActionLoadMore()
  63. {
  64. $this->performActionDisplay();
  65. }
  66. public function performActionReorder()
  67. {
  68. $this->_replaceMarkers ();
  69. $aOrder = bx_get($this->_sObject . '_row');
  70. $iOrder = 0;
  71. foreach ($aOrder as $mixedId)
  72. $this->_updateOrder($mixedId, ++$iOrder);
  73. return $this->_getActionResult([]);
  74. }
  75. public function performActionDelete()
  76. {
  77. $this->_replaceMarkers ();
  78. $aResult = [];
  79. $iAffected = 0;
  80. $aIds = bx_get('ids');
  81. if (!$aIds || !is_array($aIds))
  82. return $this->_getActionResult($aResult);
  83. foreach ($aIds as $mixedId)
  84. $iAffected += $this->_delete($mixedId) ? 1 : 0;
  85. if($iAffected)
  86. $aResult = !$this->_bIsApi ? ['grid' => $this->getCode(false)] : [];
  87. else
  88. $aResult = ['msg' => _t("_sys_grid_delete_failed")];
  89. return $this->_getActionResult($aResult);
  90. }
  91. public function performActionEnable($mixedChecked = null)
  92. {
  93. $this->_replaceMarkers ();
  94. $aIds = bx_get('ids');
  95. if (!$aIds || !is_array($aIds)) {
  96. echoJson(array());
  97. exit;
  98. }
  99. $iChecked = (int)($mixedChecked !== null ? $mixedChecked : bx_get('checked'));
  100. $aAffectedIds = array ();
  101. foreach ($aIds as $mixedId)
  102. if ($this->_enable($mixedId, $iChecked))
  103. $aAffectedIds[] = preg_match("/^[\d\w]+$/", $mixedId) ? $mixedId : (int)$mixedId;
  104. $sAction = $iChecked ? 'enable' : 'disable';
  105. if($this->_bIsApi)
  106. return $aAffectedIds;
  107. echo echoJson(array($sAction => $aAffectedIds));
  108. }
  109. public function performActionRevealSecret()
  110. {
  111. $this->_replaceMarkers();
  112. if (!isLogged())
  113. return $this->_getActionResult(['msg' => _t('_Access denied')]);
  114. if (!$this->_isCurrentPasswordValid(bx_get('password')))
  115. return $this->_getActionResult(['msg' => _t('_sys_form_account_input_password_current_error')]);
  116. $aIds = bx_get('ids');
  117. $sKey = bx_process_input(bx_get('field'));
  118. $mixedId = is_array($aIds) && $aIds ? reset($aIds) : false;
  119. if ($mixedId === false || $sKey === false || $sKey === '' || empty($this->_aOptions['fields'][$sKey]))
  120. return $this->_getActionResult(['msg' => _t('_sys_txt_error_occured')]);
  121. $aRow = $this->_getSecretRow($mixedId);
  122. if (!$aRow)
  123. return $this->_getActionResult(['msg' => _t('_sys_txt_error_occured')]);
  124. return $this->_getActionResult([
  125. 'secret' => [
  126. 'id' => $mixedId,
  127. 'field' => $sKey,
  128. 'value' => $this->_getSecretValue($mixedId, $sKey, $aRow),
  129. ]
  130. ]);
  131. }
  132. public function getCode ($isDisplayHeader = true)
  133. {
  134. $this->_replaceMarkers ();
  135. if ($isDisplayHeader && empty($this->_aOptions['paginate_url'])) {
  136. // reset page query params if grid is just initialized and it uses AJAX paginate
  137. $this->resetQueryParams();
  138. }
  139. $sPaginate = '';
  140. $aData = array();
  141. $sIdWrapper = 'bx-grid-wrap-' . $this->_sObject;
  142. $sIdContainer = 'bx-grid-cont-' . $this->_sObject;
  143. $sIdTable = 'bx-grid-table-' . $this->_sObject;
  144. $sFilter = $this->_getFilterValue();
  145. $sOrderField = $this->_getOrderValue();
  146. $sOrderDir = 0 === strcasecmp('desc', bx_get($this->_aOptions['order_get_dir'])) ? 'DESC' : 'ASC';
  147. $iStart = 0;
  148. if($this->_aOptions['paginate_get_start'] && ($iStartGet = (int)bx_get($this->_aOptions['paginate_get_start'])) >= 0)
  149. $iStart = $iStartGet;
  150. $iPerPage = 10;
  151. if($this->_aOptions['paginate_get_per_page'] && ($iPerPageGet = (int)bx_get($this->_aOptions['paginate_get_per_page'])) > 0)
  152. $iPerPage = $iPerPageGet;
  153. else if($this->_aOptions['paginate_per_page'])
  154. $iPerPage = (int)$this->_aOptions['paginate_per_page'];
  155. if ($this->_aOptions['paginate_get_start']) {
  156. $aData = $this->_getData ($sFilter, $sOrderField, $sOrderDir, $iStart, $iPerPage + 1);
  157. $sPageUrl = false;
  158. if (!empty($this->_aOptions['paginate_url'])) {
  159. $sPageUrl = $this->_aOptions['paginate_url'];
  160. $aParamsAppend = array();
  161. if ($sFilter) {
  162. $aParamsAppend['filter'] = bx_process_input(bx_get($this->_aOptions['filter_get']));
  163. }
  164. if ($sOrderField) {
  165. $aParamsAppend['order_field'] = bx_process_input(bx_get($this->_aOptions['order_get_field']));
  166. $aParamsAppend['order_dir'] = bx_process_input(bx_get($this->_aOptions['order_get_dir']));
  167. }
  168. if ($aParamsAppend)
  169. $sPageUrl = bx_append_url_params($sPageUrl, $aParamsAppend);
  170. }
  171. $aPaginateParams = [
  172. 'start' => $iStart,
  173. 'per_page' => $iPerPage,
  174. 'page_url' => $sPageUrl ? $sPageUrl : "javascript:glGrids." . $this->_sObject . "." . ($this->_sPaginateType == 'load_more' ? 'loadMore' : 'reload') . "('{start}'); void(0);",
  175. ];
  176. $oPaginate = new BxTemplPaginate($aPaginateParams, $this->_oTemplate);
  177. $oPaginate->setNumFromDataArray($aData);
  178. if (isset($this->_aOptions['paginate_simple']) && false !== $this->_aOptions['paginate_simple'])
  179. $sPaginate = $oPaginate->getSimplePaginate($this->_aOptions['paginate_simple']);
  180. else
  181. $sPaginate = $oPaginate->{'get' . bx_gen_method_name($this->_sPaginateType) . 'Paginate'}();
  182. } else {
  183. $aData = $this->_getData ($sFilter, $sOrderField, $sOrderDir, $iStart, $iPerPage);
  184. }
  185. if((empty($aData) || !is_array($aData)) && isset($this->_aBrowseParams['empty_message']) && !(bool)$this->_aBrowseParams['empty_message'])
  186. return '';
  187. $sPopupOptions = '{}';
  188. if (!empty($this->_aPopupOptions) && is_array($this->_aPopupOptions))
  189. $sPopupOptions = json_encode($this->_aPopupOptions);
  190. $aQueryAppend = array_merge(is_array($this->_aQueryAppend) ? $this->_aQueryAppend : array(), is_array($this->_aMarkers) ? $this->_aMarkers : array());
  191. if(!empty($this->_aQueryAppendExclude) && is_array($this->_aQueryAppendExclude))
  192. $aQueryAppend = array_diff_key($aQueryAppend, array_flip($this->_aQueryAppendExclude));
  193. $sQueryAppend = '{}';
  194. if (!empty($aQueryAppend) && is_array($aQueryAppend))
  195. $sQueryAppend = json_encode($aQueryAppend);
  196. $sConfirmMessages = '{}';
  197. if (!empty($this->_aConfirmMessages) && is_array($this->_aConfirmMessages))
  198. $sConfirmMessages = json_encode($this->_aConfirmMessages);
  199. $iColumns = count($this->_aOptions['fields']);
  200. $aVarsHead = $this->_getRowHead();
  201. $sClassHeader = '';
  202. if($this->_aOptions['show_total_count'] == 0)
  203. $sClassHeader .= ' bx-gh-no-counter';
  204. $aVars = array (
  205. 'object' => $this->_sObject,
  206. 'csrf_token' => BxDolForm::getCsrfToken(),
  207. 'id_table' => $sIdTable,
  208. 'id_cont' => $sIdContainer,
  209. 'id_wrap' => $sIdWrapper,
  210. 'class_table_wrapper' => $this->_aOptions['responsive'] ? 'bx-grid-table-wrapper-responsive' : '',
  211. 'sortable' => empty($this->_aOptions['field_order']) ? 0 : 1,
  212. 'sorting' => empty($this->_getOrderFields()) ? 0 : 1,
  213. 'sorting_field' => $sOrderField,
  214. 'sorting_dir' => $sOrderDir,
  215. 'bx_if:display_head' => array(
  216. 'condition' => !empty($aVarsHead),
  217. 'content' => array(
  218. 'bx_repeat:row_header' => $aVarsHead,
  219. 'columns' => $iColumns,
  220. )
  221. ),
  222. 'bx_repeat:rows_data' => $this->_getRowsDataDesign ($aData),
  223. 'paginate_get_start' => $this->_aOptions['paginate_get_start'],
  224. 'paginate_get_per_page' => $this->_aOptions['paginate_get_per_page'],
  225. 'start' => $iStart,
  226. 'per_page' => $iPerPage,
  227. 'filter' => bx_js_string($sFilter, BX_ESCAPE_STR_APOS),
  228. 'filter_get' => bx_js_string($this->_aOptions['filter_get']),
  229. 'order_field' => bx_js_string($sOrderField, BX_ESCAPE_STR_APOS),
  230. 'order_dir' => bx_js_string($sOrderDir, BX_ESCAPE_STR_APOS),
  231. 'order_get_field' => bx_js_string($this->_aOptions['order_get_field']),
  232. 'order_get_dir' => bx_js_string($this->_aOptions['order_get_dir']),
  233. 'popup_options' => $sPopupOptions,
  234. 'query_append' => $sQueryAppend,
  235. 'confirm_messages' => $sConfirmMessages,
  236. 'columns' => $iColumns,
  237. 'bx_if:display_footer' => array(
  238. 'condition' => !empty($this->_aOptions['actions_bulk']) || !empty($sPaginate),
  239. 'content' => array(
  240. 'bx_if:actions_bulk' => array (
  241. 'condition' => !empty($this->_aOptions['actions_bulk']),
  242. 'content' => array(
  243. 'actions_bulk' => $this->_getActions ('bulk'),
  244. ),
  245. ),
  246. 'paginate' => $sPaginate,
  247. )
  248. ),
  249. 'bx_if:display_header' => array (
  250. 'condition' => $isDisplayHeader,
  251. 'content' => array (
  252. 'class' => $sClassHeader,
  253. 'bx_if:actions_independent' => array (
  254. 'condition' => !empty($this->_aOptions['actions_independent']),
  255. 'content' => array(
  256. 'actions_independent' => $this->_getActions ('independent'),
  257. ),
  258. ),
  259. 'bx_if:filter' => array (
  260. 'condition' => !empty($this->_aOptions['filter_fields']) || !empty($this->_aOptions['filter_fields_translatable']),
  261. 'content' => array(
  262. 'controls' => $this->_getFilterControls(),
  263. ),
  264. ),
  265. 'bx_if:counter' => array (
  266. 'condition' => $this->_aOptions['show_total_count'] == 1,
  267. 'content' => array(
  268. 'counter' => $this->_getCounter(),
  269. ),
  270. ),
  271. ),
  272. ),
  273. );
  274. $this->_addJsCss();
  275. return $this->_oTemplate->parseHtmlByName('grid.html', $aVars);
  276. }
  277. protected function _getJsCodeVars()
  278. {
  279. $sFilter = $this->_getFilterValue();
  280. $sOrderField = $this->_getOrderValue();
  281. $sOrderDir = 0 === strcasecmp('desc', bx_get($this->_aOptions['order_get_dir'])) ? 'DESC' : 'ASC';
  282. $iStart = 0;
  283. if($this->_aOptions['paginate_get_start'] && ($iStartGet = (int)bx_get($this->_aOptions['paginate_get_start'])) >= 0)
  284. $iStart = $iStartGet;
  285. $iPerPage = 10;
  286. if($this->_aOptions['paginate_get_per_page'] && ($iPerPageGet = (int)bx_get($this->_aOptions['paginate_get_per_page'])) > 0)
  287. $iPerPage = $iPerPageGet;
  288. else if($this->_aOptions['paginate_per_page'])
  289. $iPerPage = (int)$this->_aOptions['paginate_per_page'];
  290. $sPopupOptions = '{}';
  291. if (!empty($this->_aPopupOptions) && is_array($this->_aPopupOptions))
  292. $sPopupOptions = json_encode($this->_aPopupOptions);
  293. $aQueryAppend = array_merge(is_array($this->_aQueryAppend) ? $this->_aQueryAppend : array(), is_array($this->_aMarkers) ? $this->_aMarkers : array());
  294. if(!empty($this->_aQueryAppendExclude) && is_array($this->_aQueryAppendExclude))
  295. $aQueryAppend = array_diff_key($aQueryAppend, array_flip($this->_aQueryAppendExclude));
  296. $sQueryAppend = '{}';
  297. if (!empty($aQueryAppend) && is_array($aQueryAppend))
  298. $sQueryAppend = json_encode($aQueryAppend);
  299. $sConfirmMessages = '{}';
  300. if (!empty($this->_aConfirmMessages) && is_array($this->_aConfirmMessages))
  301. $sConfirmMessages = json_encode($this->_aConfirmMessages);
  302. return [
  303. 'object' => $this->_sObject,
  304. 'csrf_token' => BxDolForm::getCsrfToken(),
  305. 'sortable' => empty($this->_aOptions['field_order']) ? 0 : 1,
  306. 'sorting' => empty($this->_getOrderFields()) ? 0 : 1,
  307. 'paginate_get_start' => $this->_aOptions['paginate_get_start'],
  308. 'paginate_get_per_page' => $this->_aOptions['paginate_get_per_page'],
  309. 'start' => $iStart,
  310. 'per_page' => $iPerPage,
  311. 'filter' => bx_js_string($sFilter, BX_ESCAPE_STR_APOS),
  312. 'filter_get' => bx_js_string($this->_aOptions['filter_get']),
  313. 'order_field' => bx_js_string($sOrderField, BX_ESCAPE_STR_APOS),
  314. 'order_dir' => bx_js_string($sOrderDir, BX_ESCAPE_STR_APOS),
  315. 'order_get_field' => bx_js_string($this->_aOptions['order_get_field']),
  316. 'order_get_dir' => bx_js_string($this->_aOptions['order_get_dir']),
  317. 'popup_options' => $sPopupOptions,
  318. 'query_append' => $sQueryAppend,
  319. 'confirm_messages' => $sConfirmMessages,
  320. 'columns' => count($this->_aOptions['fields']),
  321. ];
  322. }
  323. /**
  324. * Init grid JS class without rendering grid HTML.
  325. * @return string
  326. */
  327. public function getCodeJs()
  328. {
  329. $this->_replaceMarkers();
  330. $this->_addJsCss();
  331. return $this->_oTemplate->parseHtmlByName('grid_js.html', $this->_getJsCodeVars());
  332. }
  333. /**
  334. * Get raw actions list (name, title, icon, confirm) without HTML.
  335. * Custom `_getAction[Name]` methods that return empty hide the action, same as in the grid.
  336. * @param string $sType action type: single, bulk, independent
  337. * @param mixed $sActionData row id for single actions
  338. * @param array $aRow row data, used by custom action methods
  339. * @return array
  340. */
  341. public function getActionsRaw($sType, $sActionData = false, $aRow = [])
  342. {
  343. $sActionsType = 'actions_' . $sType;
  344. if (empty($this->_aOptions[$sActionsType]) || !is_array($this->_aOptions[$sActionsType]))
  345. return [];
  346. $aResult = [];
  347. foreach ($this->_aOptions[$sActionsType] as $sKey => $a) {
  348. if(!$a['active'] || (!$a['title'] && !$a['icon']))
  349. continue;
  350. $sFunc = '_getAction' . $this->_genMethodName($sKey);
  351. if (method_exists($this, $sFunc)) {
  352. if (!isset($a['attr']))
  353. $a['attr'] = [];
  354. $mixed = $this->$sFunc($sType, $sKey, $a, false, false, $aRow);
  355. if ($mixed === '' || $mixed === false)
  356. continue;
  357. }
  358. $aResult[] = [
  359. 'name' => $sKey,
  360. 'title' => $a['title'],
  361. 'icon' => !empty($a['icon']) ? $a['icon'] : '',
  362. 'confirm' => !empty($a['confirm']) ? 1 : 0,
  363. 'reset_paginate' => false === strpos($sKey, 'delete') ? 0 : 1,
  364. ];
  365. }
  366. return $aResult;
  367. }
  368. /**
  369. * Get grid code API.
  370. * @return array
  371. */
  372. public function getCodeAPI($bForceReturn = false)
  373. {
  374. $this->_replaceMarkers();
  375. $sFilter = bx_unicode_urldecode(bx_process_input(bx_get($this->_aOptions['filter_get'])));
  376. $sOrderField = bx_unicode_urldecode(bx_process_input(bx_get($this->_aOptions['order_get_field'])));
  377. $sOrderDir = 0 === strcasecmp('desc', bx_get($this->_aOptions['order_get_dir'])) ? 'DESC' : 'ASC';
  378. $iStart = 0;
  379. if($this->_aOptions['paginate_get_start'] && ($iStartGet = (int)bx_get($this->_aOptions['paginate_get_start'])) >= 0)
  380. $iStart = $iStartGet;
  381. $iPerPage = 10;
  382. if($this->_aOptions['paginate_get_per_page'] && ($iPerPageGet = (int)bx_get($this->_aOptions['paginate_get_per_page'])) > 0)
  383. $iPerPage = $iPerPageGet;
  384. else if($this->_aOptions['paginate_per_page'])
  385. $iPerPage = (int)$this->_aOptions['paginate_per_page'];
  386. $aData = $this->_getData($sFilter, $sOrderField, $sOrderDir, $iStart, $iPerPage);
  387. if(!empty($aData) && is_array($aData))
  388. $aData = $this->decodeDataAPI($aData);
  389. $aQueryAppend = [];
  390. if(!empty($this->_aQueryAppend) && is_array($this->_aQueryAppend))
  391. $aQueryAppend = array_merge($aQueryAppend, $this->_aQueryAppend);
  392. if(!empty($this->_aMarkers) && is_array($this->_aMarkers))
  393. $aQueryAppend = array_merge($aQueryAppend, $this->_aMarkers);
  394. if(!empty($this->_aQueryAppendExclude) && is_array($this->_aQueryAppendExclude))
  395. $aQueryAppend = array_diff_key($aQueryAppend, array_flip($this->_aQueryAppendExclude));
  396. if(!empty($this->_aQueryAppendExcludeApi) && is_array($this->_aQueryAppendExcludeApi))
  397. $aQueryAppend = array_diff_key($aQueryAppend, array_flip($this->_aQueryAppendExcludeApi));
  398. return [
  399. 'settings' => [
  400. 'object' => $this->_aOptions['object'],
  401. 'field_id' => $this->_aOptions['field_id'],
  402. 'start' => $iStart,
  403. 'per_page' => $iPerPage,
  404. 'filters' => $this->_getFilterControlsAPI(),
  405. 'query_append' => $aQueryAppend
  406. ],
  407. 'header' => $this->_getRowHeadAPI(),
  408. 'data' => defined('BX_API_PAGE') && !$bForceReturn ? [] : $aData,
  409. 'actions' => [
  410. 'independent' => $this->_getActionsAPI('independent'),
  411. 'bulk' => $this->_getActionsAPI('bulk')
  412. ]
  413. ];
  414. }
  415. public function decodeDataAPI($aData)
  416. {
  417. $sKeyId = $this->_aOptions['field_id'];
  418. $sMethodDefault = '_getCellDefault';
  419. $aDataRv = [];
  420. foreach($aData as $iKey => $aRow) {
  421. $aDataRv[$iKey] = [$sKeyId => $aData[$iKey][$sKeyId]];
  422. foreach($this->_aOptions['fields'] as $sKey => $aField) {
  423. $sMethod = '_getCell' . $this->_genMethodName($sKey);
  424. if(!method_exists($this, $sMethod))
  425. $sMethod = !empty($aField['secret']) ? '_getCellSecret' : $sMethodDefault;
  426. if(($aCell = $this->$sMethod(isset($aData[$iKey][$sKey]) ? $aData[$iKey][$sKey] : _t('_undefined'), $sKey, $aField, $aRow)))
  427. $aDataRv[$iKey][$sKey] = $aCell;
  428. }
  429. }
  430. return $aDataRv;
  431. }
  432. public function getFormBlockAPI($oForm, $sAction, $iId = 0)
  433. {
  434. return [
  435. bx_api_get_block('form', $oForm->getCodeAPI(), [
  436. 'ext' => [
  437. 'name' => $this->_oModule->getName(),
  438. 'title' => $this->getFormBlockTitleAPI($sAction, $iId),
  439. 'request' => ['url' => $this->getFormCallBackUrlAPI($sAction, $iId), 'immutable' => true]]
  440. ]
  441. )
  442. ];
  443. }
  444. public function getFormBlockTitleAPI($sAction, $iId)
  445. {
  446. return '';
  447. }
  448. public function getFormCallBackUrlAPI($sAction, $iId)
  449. {
  450. return '';
  451. }
  452. /**
  453. * Reset query params, like filter and page number
  454. */
  455. public function resetQueryParams()
  456. {
  457. foreach ($this->_aQueryReset as $sKey) {
  458. unset($_GET[$sKey]);
  459. unset($_POST[$sKey]);
  460. }
  461. }
  462. protected function _getRowHead()
  463. {
  464. $aRet = array();
  465. foreach ($this->_aOptions['fields'] as $sKey => $a) {
  466. $sMethod = '_getCellHeaderDefault';
  467. $sCustomMethod = '_getCellHeader' . $this->_genMethodName($sKey);
  468. if (method_exists($this, $sCustomMethod))
  469. $sMethod = $sCustomMethod;
  470. $aRet[] = array('header_cell' => $this->$sMethod($sKey, $a));
  471. }
  472. return $aRet;
  473. }
  474. protected function _getRowHeadAPI()
  475. {
  476. $bResize = false;
  477. $aHeader = [];
  478. foreach($this->_aOptions['fields'] as $sKey => $aField) {
  479. if($sKey == 'checkbox' && (int)$aField['width'] < 8)
  480. $bResize = true;
  481. $sMethod = '_getCellHeader' . $this->_genMethodName($sKey);
  482. if(($aHeaderItem = $this->{method_exists($this, $sMethod) ? $sMethod : '_getCellHeaderDefault'}($sKey, $aField)))
  483. $aHeader[] = $aHeaderItem;
  484. }
  485. if(($sKey = 'checkbox') && $bResize)
  486. $this->_resizeCellAPI($sKey, $this->_aOptions['fields'][$sKey], $aHeader);
  487. return $aHeader;
  488. }
  489. protected function _resizeCellAPI($sKey, $aField, &$aHeader)
  490. {
  491. $iMin = 8;
  492. $iAdd = $iMin - (int)$aField['width'];
  493. $iThreshold = $iMin + $iAdd;
  494. $iReduce = 0;
  495. array_walk($aHeader, function($aItem) use ($iThreshold, &$iReduce) {
  496. if((int)$aItem['width'] >= $iThreshold)
  497. $iReduce += 1;
  498. });
  499. $fSub = round($iAdd / $iReduce, 2);
  500. array_walk($aHeader, function(&$aItem) use ($sKey, $iThreshold, $iAdd, $fSub) {
  501. if($aItem['name'] == $sKey)
  502. $aItem['width'] = (float)$aItem['width'] + $iAdd;
  503. else if((int)$aItem['width'] >= $iThreshold)
  504. $aItem['width'] = (float)$aItem['width'] - $fSub;
  505. else
  506. return;
  507. $aItem['width'] .= '%';
  508. });
  509. }
  510. protected function _getCellHeaderDefault ($sKey, $aField)
  511. {
  512. if($this->_bIsApi)
  513. return [
  514. 'name' => bx_process_output($aField['name']),
  515. 'title' => bx_process_output($aField['title']),
  516. 'width' => $aField['width']
  517. ];
  518. $sHeader = bx_process_output($aField['title']);
  519. if ($sHeader === '') // a column with no visible title (switcher, actions, order) still needs one for assistive tech
  520. $sHeader = '<span class="sr-only">' . bx_process_output($this->_getCellHeaderFallbackTitle($sKey)) . '</span>';
  521. if (($aSortingFields = $this->_getOrderFields()) && in_array($sKey, $aSortingFields)) {
  522. $sHeader = '<a href="javascript:void(0);" class="bx-grid-sort-handle">' . $sHeader . '</a><span class="bx-grid-sort-indi"></span>';
  523. $aField['attr_head']['bx_grid_sort_head'] = $sKey;
  524. }
  525. $sAttr = $this->_convertAttrs(
  526. $aField, 'attr_head',
  527. 'bx-def-padding-sec-bottom bx-def-padding-sec-top bx-grid-header-' . $sKey, // add default classes
  528. isset($aField['width']) ? 'width:' . $aField['width'] : false // add default styles
  529. );
  530. return $this->_getCellHeaderWrapper ($sKey, $aField, $sHeader, $sAttr);
  531. }
  532. protected function _getCellHeaderCheckbox ($sKey, $aField)
  533. {
  534. if($this->_bIsApi)
  535. return $this->_getCellHeaderDefault($sKey, $aField);
  536. $aAttr = array(
  537. 'type' => 'checkbox',
  538. 'id' => $this->_sObject . '_check_all',
  539. 'name' => $this->_sObject . '_check_all',
  540. 'aria-label' => _t('_sys_grid_lbl_select_all'),
  541. 'onclick' => "$('input[name=" . $this->_sObject . "_check]:not([disabled])').attr('checked', this.checked)"
  542. );
  543. if($this->_bSelectAll)
  544. $aAttr['checked'] = 'checked';
  545. $aField['attr'] = isset($aField['attr']) && is_array($aField['attr']) ? array_merge($aAttr, $aField['attr']) : $aAttr;
  546. $sAttrHead = $this->_convertAttrs(
  547. $aField, 'attr_head',
  548. 'bx-def-padding-sec-bottom bx-def-padding-sec-top bx-grid-header-' . $sKey, // add default classes
  549. isset($aField['width']) ? 'width:' . $aField['width'] : false // add default styles
  550. );
  551. return $this->_getCellHeaderWrapper ($sKey, $aField, ' <input ' . $this->_convertAttrs($aField, 'attr') . ' /> ', $sAttrHead);
  552. }
  553. protected function _getCellHeaderWrapper ($sKey, $aField, $sHeader, $sAttr)
  554. {
  555. return '<th scope="col" ' . $sAttr . '>' . $sHeader . '</th>';
  556. }
  557. /**
  558. * The title read out for a column whose header is empty: the conventional columns by name, the key as words otherwise.
  559. */
  560. protected function _getCellHeaderFallbackTitle ($sKey)
  561. {
  562. $aTitles = array('switcher' => '_sys_active', 'actions' => '_sys_grid_lbl_actions', 'order' => '_sys_grid_lbl_order', 'checkbox' => '_sys_grid_lbl_select');
  563. if (isset($aTitles[$sKey]))
  564. return _t($aTitles[$sKey]);
  565. return ucfirst(str_replace('_', ' ', $sKey));
  566. }
  567. /**
  568. * Check if the whole row is disabled.
  569. * When row is disabled - checkbox is not selectable, actions aren't clickable and text is grayed out.
  570. * By default all rows aren't disabled.
  571. * @param $aRow row array
  572. * @return boolean
  573. */
  574. protected function _isRowDisabled($aRow)
  575. {
  576. if (isset($aRow[$this->_aOptions['field_active']]) && !$this->_switcherState2Checked($aRow[$this->_aOptions['field_active']]))
  577. return true;
  578. return false;
  579. }
  580. /**
  581. * Determine how actions are disabled when whole row is disabled.
  582. * @param $aRow row array
  583. * @return null - disable/enable actions when row is disabled/enabled, true - actions are always disabled, false - actions are always enabled
  584. */
  585. protected function _getActionsDisabledBehavior($aRow)
  586. {
  587. return null;
  588. }
  589. /**
  590. * Check if the checkbox is disabled.
  591. * @param $aRow row array
  592. * @return boolean
  593. */
  594. protected function _isCheckboxDisabled($aRow)
  595. {
  596. return $this->_isRowDisabled($aRow);
  597. }
  598. /**
  599. * Is checkbox checked by default ?
  600. * By default no one checkbox is selected.
  601. * @return boolean
  602. */
  603. protected function _isCheckboxSelected($mixedValue, $sKey, $aField, $aRow)
  604. {
  605. return $this->_bSelectAll;
  606. }
  607. /**
  608. * Is switcher on by default ?
  609. * By default no one switcher is on.
  610. * @return boolean
  611. */
  612. protected function _isSwitcherOn($mixedValue, $sKey, $aField, $aRow)
  613. {
  614. return $this->_switcherState2Checked($mixedValue);
  615. }
  616. /**
  617. * Convert switcher checked status to the actual value ?
  618. * @return boolean
  619. */
  620. protected function _switcherChecked2State($isChecked)
  621. {
  622. return $isChecked ? 1 : 0;
  623. }
  624. /**
  625. * Convert switcher value to checked(boolean) value ?
  626. * @return boolean
  627. */
  628. protected function _switcherState2Checked($mixedState)
  629. {
  630. return $mixedState ? true : false;
  631. }
  632. protected function _getRowsDataDesign (&$aData)
  633. {
  634. $aGrid = array();
  635. if(empty($aData))
  636. $aGrid[] = array(
  637. 'id_row' => 0,
  638. 'row_class' => 'bx-grid-table-row-empty',
  639. 'row' => '<td class="bx-def-padding-sec-topbottom" colspan="' . count($this->_aOptions['fields']) . '">' . MsgBox(_t('_Empty')) . '</td>'
  640. );
  641. else
  642. foreach ($aData as $aRow)
  643. $aGrid[] = array(
  644. 'id_row' => $this->_getRowId($aRow),
  645. 'row_class' => $this->_isRowDisabled($aRow) ? 'bx-grid-table-row-disabled bx-def-font-grayed' : '',
  646. 'row' => $this->_getRowDesign($aRow)
  647. );
  648. return $aGrid;
  649. }
  650. protected function _getRowId($mixedRow)
  651. {
  652. if(is_string($mixedRow))
  653. $sId = rand(1, getrandmax());
  654. else
  655. $sId = $mixedRow[$this->_aOptions['field_id']];
  656. return $this->_sObject . '_row_' . $sId;
  657. }
  658. protected function _getRowDesign($mixedRow)
  659. {
  660. $sRow = '';
  661. if(is_string($mixedRow))
  662. $sRow = '<td class="bx-grid-cell bx-gc-string bx-def-padding-sec-topbottom bx-def-font-bold" colspan="' . count($this->_aOptions['fields']) . '">' . $mixedRow . '</td>';
  663. else
  664. foreach($this->_aOptions['fields'] as $sKey => $aField)
  665. $sRow .= $this->_getCellDesign($sKey, $aField, $mixedRow);
  666. return $sRow;
  667. }
  668. protected function _getCellDesign($sKey, $aField, $aRow)
  669. {
  670. $sMethod = '_getCellDefault';
  671. if ($this->_aOptions['field_order'] == $sKey)
  672. $sMethod = '_getCellOrder';
  673. $sCustomMethod = '_getCell' . $this->_genMethodName($sKey);
  674. if (method_exists($this, $sCustomMethod))
  675. $sMethod = $sCustomMethod;
  676. else if (!empty($aField['secret']))
  677. $sMethod = '_getCellSecret';
  678. $mixedValue = $this->_getCellData($sKey, $aField, $aRow);
  679. if ($aField['translatable'])
  680. $mixedValue = _t($mixedValue);
  681. if ($sMethod != '_getCellSecret')
  682. $mixedValue = $this->_limitMaxLength($mixedValue, $sKey, $aField, $aRow, $this->_isDisplayPopupOnTextOverflow);
  683. return $this->$sMethod($mixedValue, $sKey, $aField, $aRow);
  684. }
  685. protected function _getCellCheckbox ($mixedValue, $sKey, $aField, $aRow)
  686. {
  687. if($this->_bIsApi)
  688. return ['type' => 'checkbox', 'data' => $aRow[$this->_aOptions['field_id']]];
  689. $sAttr = $this->_convertAttrs(
  690. $aField, 'attr_cell',
  691. 'bx-def-padding-sec-bottom bx-def-padding-sec-top', // add default classes
  692. isset($aField['width']) ? 'width:' . $aField['width'] : false // add default styles
  693. );
  694. $sDisabled = ($this->_isCheckboxDisabled($aRow) ? 'disabled="disabled"' : '');
  695. $sSelected = ($this->_isCheckboxSelected($mixedValue, $sKey, $aField, $aRow) ? 'checked="checked"' : '');
  696. $sVal = $aRow[$this->_aOptions['field_id']];
  697. return '<td ' . $sAttr . '><input type="checkbox" name="'. $this->_sObject . '_check" value="' . $sVal . '" ' . $sDisabled . ' ' . $sSelected . '/></td>';
  698. }
  699. protected function _getCellSwitcher ($mixedValue, $sKey, $aField, $aRow)
  700. {
  701. if($this->_bIsApi)
  702. return ['type' => 'switcher', 'data' => $aRow[$this->_aOptions['field_active']], 'fld' => $this->_aOptions['field_active']];
  703. $sAttr = $this->_convertAttrs(
  704. $aField, 'attr_cell',
  705. 'bx-def-padding-sec-bottom bx-def-padding-sec-top', // add default classes
  706. isset($aField['width']) ? 'width:' . $aField['width'] : false // add default styles
  707. );
  708. $oForm = new BxTemplFormView(array(), $this->_oTemplate);
  709. $oForm->addCssJs();
  710. // the switch's name for assistive tech: the column title (Active when the column has none) and the row's title
  711. $sLabel = !empty($aField['title']) ? _t($aField['title']) : _t('_sys_active');
  712. foreach (array('title', 'name', 'caption') as $sTitleKey)
  713. if (!empty($aRow[$sTitleKey]) && is_string($aRow[$sTitleKey])) {
  714. $sLabel .= ': ' . strip_tags(_t($aRow[$sTitleKey]));
  715. break;
  716. }
  717. $aInput = array(
  718. 'type' => 'switcher',
  719. 'name' => $this->_sObject . '_switch_' . $aRow[$this->_aOptions['field_id']],
  720. 'caption' => '',
  721. 'attrs' => array (
  722. 'aria-label' => $sLabel,
  723. 'bx_grid_action_single' => 'enable',
  724. 'bx_grid_action_confirm' => '',
  725. 'bx_grid_action_data' => $aRow[$this->_aOptions['field_id']],
  726. ),
  727. 'value' => $aRow[$this->_aOptions['field_id']],
  728. 'checked' => $this->_isSwitcherOn(isset($aRow[$this->_aOptions['field_active']]) ? $aRow[$this->_aOptions['field_active']] : false, $sKey, $aField, $aRow),
  729. );
  730. $sSwitcher = $oForm->genInput($aInput);
  731. return '<td ' . $sAttr . '>' . $sSwitcher . '</td>';
  732. }
  733. protected function _getCellOrder ($mixedValue, $sKey, $aField, $aRow)
  734. {
  735. if($this->_bIsApi)
  736. return ['type' => 'order', 'data'=> $mixedValue];
  737. $sAttr = $this->_convertAttrs(
  738. $aField, 'attr_cell',
  739. 'bx-def-padding-sec-bottom bx-def-padding-sec-top', // add default classes
  740. isset($aField['width']) ? 'width:' . $aField['width'] : false // add default styles
  741. );
  742. return '<td ' . $sAttr . '><div id="' . $this->_sObject . '_cell_' . $aRow[$this->_aOptions['field_id']] . '" class="bx-grid-drag-handle"><i class="sys-icon grip-vertical"></i></div></td>';
  743. }
  744. protected function _getCellActions ($mixedValue, $sKey, $aField, $aRow)
  745. {
  746. $sAttr = $this->_convertAttrs(
  747. $aField, 'attr_cell',
  748. 'bx-def-padding-sec-bottom bx-def-padding-sec-top', // add default classes
  749. isset($aField['width']) ? 'width:' . $aField['width'] : false // add default styles
  750. );
  751. $mixedDisabledBehavior = $this->_getActionsDisabledBehavior($aRow);
  752. $mixedActions = $this->_getActions('single', $aRow[$this->_aOptions['field_id']], false, null === $mixedDisabledBehavior ? $this->_isRowDisabled($aRow) : $mixedDisabledBehavior, null !== $mixedDisabledBehavior, $aRow);
  753. if($this->_bIsApi)
  754. return ['type' => 'actions', 'data' => $mixedActions];
  755. return '<td ' . $sAttr . '><div class="bx-grid-cell-single-actions-wrapper bx-def-margin-thd-neg">' . $mixedActions . '</div></td>';
  756. }
  757. protected function _getCellDefault ($mixedValue, $sKey, $aField, $aRow)
  758. {
  759. if($this->_bIsApi) {
  760. $sType = $mixedValue['type'] ?? 'text';
  761. if(isset($mixedValue['type']))
  762. unset($mixedValue['type']);
  763. return [
  764. 'type' => $sType,
  765. 'value'=> (int)$aField['translatable'] ? _t($mixedValue) : $mixedValue
  766. ];
  767. }
  768. $sAttr = $this->_convertAttrs(
  769. $aField, 'attr_cell',
  770. 'bx-grid-cell' . (!empty($aField['name']) ? ' bx-gc-' . $aField['name'] : '') . ' bx-def-padding-sec-bottom bx-def-padding-sec-top', // add default classes
  771. isset($aField['width']) ? 'width:' . $aField['width'] : false // add default styles
  772. );
  773. return '<td ' . $sAttr . '>' . $mixedValue . '</td>';
  774. }
  775. /**
  776. * Display a cell as a masked secret with an eye icon to reveal it after password confirmation.
  777. * @see BxDolGrid grid_display_secret_cell
  778. */
  779. protected function _getCellSecret ($mixedValue, $sKey, $aField, $aRow)
  780. {
  781. $sRaw = '';
  782. if (isset($aRow[$sKey]) && $aRow[$sKey] !== '' && $aRow[$sKey] !== null)
  783. $sRaw = (string)$aRow[$sKey];
  784. else if ($mixedValue !== '' && $mixedValue !== null && $mixedValue !== false)
  785. $sRaw = (string)$mixedValue;
  786. $sMasked = $sRaw !== '' ? bx_gen_secret($sRaw) : '';
  787. if ($this->_bIsApi)
  788. return ['type' => 'secret', 'value' => $sMasked];
  789. $sAttr = $this->_convertAttrs(
  790. $aField, 'attr_cell',
  791. 'bx-grid-cell' . (!empty($aField['name']) ? ' bx-gc-' . $aField['name'] : '') . ' bx-def-padding-sec-bottom bx-def-padding-sec-top',
  792. isset($aField['width']) ? 'width:' . $aField['width'] : false
  793. );
  794. $sToggle = '';
  795. if ($sRaw !== '' && isLogged()) {
  796. $mixedId = $aRow[$this->_aOptions['field_id']];
  797. $sToggle = '<a href="javascript:void(0);" class="bx-grid-secret-toggle" title="' . bx_html_attribute(_t('_sys_grid_secret_reveal')) . '" bx_grid_secret_id="' . bx_html_attribute($mixedId) . '" bx_grid_secret_field="' . bx_html_attribute($sKey) . '"><i class="sys-icon eye"></i></a>';
  798. }
  799. return '<td ' . $sAttr . '><div class="bx-grid-secret"><span class="bx-grid-secret-value" data-masked="' . bx_html_attribute($sMasked) . '">' . bx_process_output($sMasked) . '</span>' . $sToggle . '</div></td>';
  800. }
  801. protected function _getSecretRow($mixedId)
  802. {
  803. $aRows = $this->_getDataUpdated([$mixedId]);
  804. if (!$aRows || !is_array($aRows))
  805. return false;
  806. $sFieldId = $this->_aOptions['field_id'];
  807. foreach ($aRows as $aRow) {
  808. if (isset($aRow[$sFieldId]) && (string)$aRow[$sFieldId] === (string)$mixedId)
  809. return $aRow;
  810. }
  811. return reset($aRows);
  812. }
  813. /**
  814. * Return the secret value for a revealed cell. Override when the value is encrypted or computed.
  815. */
  816. protected function _getSecretValue($mixedId, $sKey, $aRow)
  817. {
  818. return isset($aRow[$sKey]) ? $aRow[$sKey] : '';
  819. }
  820. protected function _isCurrentPasswordValid($sPassword)
  821. {
  822. if ($sPassword === false || $sPassword === '')
  823. return false;
  824. if (!class_exists('BxFormAccountCheckerHelper'))
  825. bx_import('BxBaseFormAccount');
  826. $oChecker = new BxFormAccountCheckerHelper();
  827. return true === $oChecker->checkPasswordCurrent($sPassword);
  828. }
  829. protected function _getActions ($sType, $sActionData = false, $isSmall = false, $isDisabled = false, $isPermanentState = false, $aRow = array())
  830. {
  831. $sActionsType = 'actions_' . $sType;
  832. if (empty($this->_aOptions[$sActionsType]) || !is_array($this->_aOptions[$sActionsType]))
  833. return '';
  834. $mixedResult = $this->_bIsApi ? [] : '';
  835. foreach ($this->_aOptions[$sActionsType] as $sKey => $a) {
  836. if(!$a['active'] || (!$a['title'] && !$a['icon']))
  837. continue;
  838. $sFunc = '_getAction' . $this->_genMethodName($sKey);
  839. if (!method_exists($this, $sFunc))
  840. $sFunc = empty($a) ? '_getActionDivider' : '_getActionDefault';
  841. if (!isset($a['attr']['bx_grid_action'])) {
  842. $a['attr']['bx_grid_action_' . $sType] = $sKey;
  843. if (!empty($sActionData))
  844. $a['attr']['bx_grid_action_data'] = $sActionData;
  845. if (isset($a['confirm']))
  846. $a['attr']['bx_grid_action_confirm'] = $a['confirm'] ? 1 : 0;
  847. $a['attr']['bx_grid_action_reset_paginate'] = false === strpos($sKey, 'delete') ? 0 : 1; // reset paginate after deleting row
  848. }
  849. if ($isPermanentState && !isset($a['attr']['bx_grid_permanent_state']))
  850. $a['attr']['bx_grid_permanent_state'] = 1;
  851. if ($this->_bIsApi)
  852. $mixedResult[] = $this->$sFunc($sType, $sKey, $a, $isSmall, $isDisabled, $aRow);
  853. else
  854. $mixedResult .= $this->$sFunc($sType, $sKey, $a, $isSmall, $isDisabled, $aRow);
  855. }
  856. return $mixedResult;
  857. }
  858. protected function _getActionsAPI ($sType)
  859. {
  860. $sActionsType = 'actions_' . $sType;
  861. if(empty($this->_aOptions[$sActionsType]) || !is_array($this->_aOptions[$sActionsType]))
  862. return [];
  863. foreach ($this->_aOptions[$sActionsType] as $sKey => $aAction) {
  864. $sMethod = '_getAction' . $this->_genMethodName($sKey);
  865. if(!method_exists($this, $sMethod))
  866. $sMethod = '_getActionDefault';
  867. if(!isset($aAction['attr']))
  868. $aAction['attr'] = [];
  869. if(($_aAction = $this->$sMethod($sType, $sKey, $aAction)))
  870. $this->_aOptions[$sActionsType][$sKey] = $_aAction;
  871. }
  872. return $this->_aOptions[$sActionsType];
  873. }
  874. protected function _getActionDelete($sType, $sKey, $a, $isSmall = false, $isDisabled = false, $aRow = array())
  875. {
  876. if($this->_bIsApi)
  877. return array_merge($a, ['name' => $sKey, 'type' => 'callback', 'on_callback' => 'hide_row']);
  878. return $this->_getActionDefault($sType, $sKey, $a, $isSmall, $isDisabled, $aRow);
  879. }
  880. protected function _getActionDefault ($sType, $sKey, $a, $isSmall = false, $isDisabled = false, $aRow = array())
  881. {
  882. if ($a['icon_only'] && empty($a['attr']['title']) && !empty($a['title']))
  883. $a['attr']['title'] = $a['title'];
  884. if ($a['icon_only'] && empty($a['attr']['aria-label']) && !empty($a['title']))
  885. $a['attr']['aria-label'] = $a['title'];
  886. if ($this->_bIsApi) {
  887. $sParams = '';
  888. if($sType == 'single' && ($sFieldId = $this->_aOptions['field_id']) && isset($aRow[$sFieldId]))
  889. $sParams = '&id=' . $aRow[$sFieldId];
  890. return array_merge($a, ['name' => $sKey, 'type' => 'modal', 'action' => $sKey, 'params' => $sParams]);
  891. }
  892. $sAttr = $this->_convertAttrs(
  893. $a, 'attr',
  894. 'bx-btn bx-def-margin-thd' . ($isSmall ? ' bx-btn-small' : '') . ($isDisabled ? ' bx-btn-disabled' : '') // add default classes
  895. );
  896. $sIcon = '';
  897. $sImage = '';
  898. if (!empty($a['icon'])) {
  899. list($sIconFont, $sIconUrl, $sIconA, $sIconHtml) = $this->_oFunctions->getIcon($a['icon']);
  900. if ($sIconFont)
  901. $sIcon = '<i class="sys-icon ' . $sIconFont . '"></i>';
  902. else if($sIconUrl)
  903. $sImage = '<img style="background-image:url(' . $sIconUrl . ');" src="' . $this->_oTemplate->getIconUrl('spacer.gif') .'" />';
  904. else if($sIconHtml)
  905. $sImage = $sIconHtml;
  906. }
  907. return '<button ' . $sAttr . '>' . $sIcon . $sImage . ($a['icon_only'] || empty($a['title']) ? '' : '<u>' . $a['title'] . '</u>') . '</button>';
  908. }
  909. protected function _getActionDivider ($sType, $sKey, $a, $isSmall = false, $isDisabled = false, $aRow = array())
  910. {
  911. return '<div class="bx-grid-actions-divider bx-def-margin-sec-left"> | </div>';
  912. }
  913. protected function _getActionResult($aResult)
  914. {
  915. return $this->_bIsApi ? $aResult : echoJson($aResult);
  916. }
  917. protected function _getFilterControls ()
  918. {
  919. $oForm = new BxTemplFormView([]);
  920. $aInput = array(
  921. 'type' => 'text',
  922. 'name' => 'keyword',
  923. 'attrs' => array(
  924. 'id' => 'bx-grid-search-' . $this->_sObject,
  925. 'aria-label' => _t('_Search')
  926. )
  927. );
  928. $this->_oTemplate->addCss('forms.css');
  929. return $oForm->genRow($aInput);
  930. }
  931. protected function _getFilterControlsAPI($aFilters = [])
  932. {
  933. if(!empty($this->_aOptions['filter_fields']) || !empty($this->_aOptions['filter_fields_translatable']))
  934. $aFilters['search'] = [];
  935. return $aFilters;
  936. }
  937. protected function _getFilterOnChange()
  938. {
  939. return '';
  940. }
  941. /**
  942. * Grid filter controls are rendered without a visible caption, so each one needs its own accessible name:
  943. * the name the grid declares in $_aFilterAreaLabels, else the "unfiltered" option the filter starts with
  944. * ("All", "Any status", "Select one..."), else the generic "Filters".
  945. */
  946. protected function _getFilterAreaLabel($sFilterName, $aInputValues = [])
  947. {
  948. if(!empty($this->_aFilterAreaLabels[$sFilterName]))
  949. return $this->_aFilterAreaLabels[$sFilterName];
  950. if(!empty($aInputValues['']) && is_string($aInputValues['']))
  951. return $aInputValues[''];
  952. return '_Filters';
  953. }
  954. protected function _getFilterSelectOne($sFilterName, $sFilterValue, $aFilterValues, $mixedAddSelectOne = true, $bAsArray = false)
  955. {
  956. if(empty($sFilterName))
  957. return '';
  958. $aInputValues = [];
  959. if(($mixedAddSelectOne === true && ($sKey = '_Select_one')) || (is_string($mixedAddSelectOne) && ($sKey = $mixedAddSelectOne)))
  960. $aInputValues[''] = _t($sKey);
  961. foreach($aFilterValues as $mixedKey => $mixedValue)
  962. if(is_array($mixedValue) && isset($mixedValue['key'], $mixedValue['value']))
  963. $aInputValues[$mixedValue['key']] = _t($mixedValue['value']);
  964. else
  965. $aInputValues[$mixedKey] = _t($mixedValue);
  966. $aInputSelect = [
  967. 'type' => 'select',
  968. 'name' => $sFilterName,
  969. 'attrs' => [
  970. 'id' => 'bx-grid-' . $sFilterName . '-' . $this->_sObject,
  971. 'onChange' => ($sOnChange = $this->_getFilterOnChange()) ? 'javascript:' . $sOnChange : '',
  972. ],
  973. 'area_label' => $this->_getFilterAreaLabel($sFilterName, $aInputValues),
  974. 'value' => $sFilterValue,
  975. 'values' => $aInputValues
  976. ];
  977. if($bAsArray)
  978. return $aInputSelect;
  979. $oForm = new BxTemplFormView([]);
  980. return $oForm->genRow($aInputSelect);
  981. }
  982. protected function _getFilterDatePicker($sFilterName, $sFilterValue, $bAsArray = false)
  983. {
  984. if(empty($sFilterName))
  985. return '';
  986. $aInputDatePicker = [
  987. 'type' => 'datepicker',
  988. 'name' => $sFilterName,
  989. 'attrs' => [
  990. 'id' => 'bx-grid-' . $sFilterName . '-' . $this->_sObject,
  991. 'onChange' => ($sOnChange = $this->_getFilterOnChange()) ? 'javascript:' . $sOnChange : '',
  992. ],
  993. 'area_label' => $this->_getFilterAreaLabel($sFilterName),
  994. 'value' => $sFilterValue,
  995. ];
  996. if($bAsArray)
  997. return $aInputDatePicker;
  998. $oForm = new BxTemplFormView([]);
  999. return $oForm->genRow($aInputDatePicker);
  1000. }
  1001. protected function _getFilterButton($bAsArray = false)
  1002. {
  1003. $sOnChange = $this->_getFilterOnChange();
  1004. $aInputButton = [
  1005. 'type' => 'button',
  1006. 'name' => 'button',
  1007. 'attrs' => [
  1008. 'id' => 'bx-grid-button-' . $this->_sObject,
  1009. 'onClick' => 'javascript:' . $sOnChange,
  1010. ],
  1011. 'value' => _t('_Search'),
  1012. ];
  1013. if($bAsArray)
  1014. return $aInputButton;
  1015. $oForm = new BxTemplFormView([]);
  1016. return $oForm->genRow($aInputButton);
  1017. }
  1018. protected function _getFilterLabel($sFilterValue, $bAsArray = false)
  1019. {
  1020. $aInputLabel = [
  1021. 'type' => 'value',
  1022. 'value' => $sFilterValue,
  1023. 'tr_attrs' => ['class' => 'bx-grid-controls-filter-label'],
  1024. ];
  1025. if($bAsArray)
  1026. return $aInputLabel;
  1027. $oForm = new BxTemplFormView([]);
  1028. return $oForm->genRow($aInputLabel);
  1029. }
  1030. protected function _getSearchInput($bAsArray = false)
  1031. {
  1032. $sOnChange = $this->_getFilterOnChange();
  1033. $aInputSearch = [
  1034. 'type' => 'text',
  1035. 'name' => 'search',
  1036. 'attrs' => [
  1037. 'id' => 'bx-grid-search-' . $this->_sObject,
  1038. 'aria-label' => _t('_Search'),
  1039. 'onKeyup' => 'javascript:$(this).off(\'keyup focusout\'); ' . $sOnChange,
  1040. 'onBlur' => 'javascript:' . $sOnChange,
  1041. ]
  1042. ];
  1043. if($bAsArray)
  1044. return $aInputSearch;
  1045. $oForm = new BxTemplFormView([]);
  1046. return $oForm->genRow($aInputSearch);
  1047. }
  1048. protected function _getCounter()
  1049. {
  1050. return _t('_sys_grid_total_count', $this->_iTotalCount);
  1051. }
  1052. protected function _limitMaxLength ($mixedValue, $sKey, $aField, $aRow, $isDisplayPopupOnTextOverflow, $bReturnString = true)
  1053. {
  1054. if((int)$aField['chars_limit'] <= 0)
  1055. return $mixedValue;
  1056. return $this->_oFunctions->getStringWithLimitedLength([strip_tags($mixedValue), $mixedValue], $aField['chars_limit'], $isDisplayPopupOnTextOverflow, $bReturnString);
  1057. }
  1058. protected function _convertAttrs ($aField, $sAttrName, $sClasses = false, $sStyles = false)
  1059. {
  1060. if (!empty($aField['hidden_on'])) {
  1061. $aHiddenOn = array(
  1062. pow(2, BX_DB_HIDDEN_PHONE - 1) => 'bx-def-media-phone-hide',
  1063. pow(2, BX_DB_HIDDEN_TABLET - 1) => 'bx-def-media-tablet-hide',
  1064. pow(2, BX_DB_HIDDEN_DESKTOP - 1) => 'bx-def-media-desktop-hide',
  1065. pow(2, BX_DB_HIDDEN_MOBILE - 1) => 'bx-def-mobile-app-hide'
  1066. );
  1067. foreach ($aHiddenOn as $iHiddenOn => $sClass)
  1068. if ((int)$aField['hidden_on'] & $iHiddenOn)
  1069. $sClasses .= ' ' . $sClass;
  1070. }
  1071. return bx_convert_array2attrs(
  1072. isset($aField[$sAttrName]) && is_array($aField[$sAttrName]) ? $aField[$sAttrName] : array(),
  1073. $sClasses,
  1074. $sStyles
  1075. );
  1076. }
  1077. protected function _updateOrder($mixedId, $iOrder)
  1078. {
  1079. $oDb = BxDolDb::getInstance();
  1080. $sTable = $this->_aOptions['table'];
  1081. $sFieldId = $this->_aOptions['field_id'];
  1082. $sFieldOrder = $this->_aOptions['field_order'];
  1083. $sQuery = $oDb->prepare("UPDATE `{$sTable}` SET `{$sFieldOrder}` = ? WHERE `{$sFieldId}` = ?", $iOrder, $mixedId);
  1084. return $oDb->query($sQuery);
  1085. }
  1086. protected function _delete ($mixedId)
  1087. {
  1088. $oDb = BxDolDb::getInstance();
  1089. $sTable = $this->_aOptions['table'];
  1090. $sFieldId = $this->_aOptions['field_id'];
  1091. $sQuery = $oDb->prepare("DELETE FROM `{$sTable}` WHERE `{$sFieldId}` = ?", $mixedId);
  1092. return $oDb->query($sQuery);
  1093. }
  1094. protected function _enable ($mixedId, $isChecked)
  1095. {
  1096. $oDb = BxDolDb::getInstance();
  1097. $sTable = $this->_aOptions['table'];
  1098. $sFieldId = $this->_aOptions['field_id'];
  1099. $sFieldActive = $this->_aOptions['field_active'];
  1100. $sQuery = $oDb->prepare("UPDATE `{$sTable}` SET `$sFieldActive` = ? WHERE `{$sFieldId}` = ?", $this->_switcherChecked2State($isChecked), $mixedId);
  1101. return $oDb->query($sQuery);
  1102. }
  1103. protected function _addJsCss()
  1104. {
  1105. if ($this->_aOptions['field_order']) {
  1106. $this->_oTemplate->addJs(array(
  1107. 'jquery-ui/jquery-ui.custom.min.js',
  1108. 'URI.min.js',
  1109. ));
  1110. }
  1111. $this->_oTemplate->addJs('BxDolGrid.js');
  1112. $this->_oTemplate->addCss('grid.css');
  1113. $this->_oTemplate->addJsTranslation([
  1114. '_sys_grid_confirmation',
  1115. '_sys_grid_secret_reveal',
  1116. '_sys_grid_secret_hide',
  1117. '_sys_grid_secret_password_prompt',
  1118. ]);
  1119. }
  1120. }
  1121. /** @} */