BxBaseGrid.php 51 KB

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