BxBaseSearchExtended.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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. * Extended Search objects representation.
  11. *
  12. * @see BxDolSearchExtended
  13. */
  14. class BxBaseSearchExtended extends BxDolSearchExtended
  15. {
  16. protected $_sFormClassName;
  17. protected $_sFormClassPath;
  18. protected $_oForm;
  19. protected $_oTemplate;
  20. protected $_bJsMode;
  21. protected $_iAgeMin;
  22. protected $_iAgeMax;
  23. public function __construct ($aObject, $oTemplate = null)
  24. {
  25. parent::__construct ($aObject);
  26. if ($oTemplate)
  27. $this->_oTemplate = $oTemplate;
  28. else if(!empty($this->_aObject['module']))
  29. $this->_oTemplate = BxDolModule::getInstance($this->_aObject['module'])->_oTemplate;
  30. else
  31. $this->_oTemplate = BxDolTemplate::getInstance();
  32. $this->_sFormClassName = '';
  33. $this->_sFormClassPath = '';
  34. $this->_oForm = null;
  35. $this->_bJsMode = false;
  36. $this->_iAgeMin = 1;
  37. $this->_iAgeMax = 75;
  38. }
  39. public function getForm($aParams = array())
  40. {
  41. if(!$this->isEnabled())
  42. return '';
  43. $oForm = $this->prepareForm($aParams);
  44. return bx_is_api() ? bx_api_get_block('form', $oForm->getCodeAPI(), ['id' => 2, 'ext' => ['name' => $this->_aObject['module'] . '_serach', 'request' => ['url' => '/api.php?r=system/get_form/TemplSearchExtendedServices&params[]=' . $this->_aObject['module'], 'immutable' => true]]]) : $oForm->getCode();
  45. }
  46. /**
  47. * Get search results from search form or from custom condition
  48. *
  49. * @param $aParams['cond'] custom condition to pass instead of form submission,
  50. * conditions are key&value pair, where 'key' is form input name and
  51. * 'value' is the term to search for
  52. * @param $aParams['start'] position of first record to display
  53. * @param $aParams['per_page'] number of items per page
  54. * @param $aParams['template'] custom unit templates to use
  55. * @return HTML string with search results
  56. */
  57. public function getResults($aParams = array())
  58. {
  59. if(!$this->isEnabled())
  60. return '';
  61. $bJsMode = isset($aParams['js_mode']) ? (bool)$aParams['js_mode'] : $this->_bJsMode;
  62. $bCondition = !empty($aParams['cond']) && is_array($aParams['cond']);
  63. $iStart = !empty($aParams['start']) ? (int)$aParams['start'] : 0;
  64. $iPerPage = !empty($aParams['per_page']) ? (int)$aParams['per_page'] : (int)getParam('sys_per_page_search_extended');
  65. if(!$iPerPage) {
  66. bx_import('BxDolSearch');
  67. $iPerPage = BX_DOL_SEARCH_RESULTS_PER_PAGE_DEFAULT;
  68. }
  69. unset($aParams['start'], $aParams['per_page']);
  70. $sUnitTemplate = !empty($aParams['template']) ? $aParams['template'] : '';
  71. $oForm = $this->prepareForm($aParams);
  72. if($bCondition) {
  73. $mixedSubmitName = $oForm->aParams['db']['submit_name'];
  74. if(is_array($mixedSubmitName))
  75. $mixedSubmitName = array_pop($mixedSubmitName);
  76. $aParams['cond'][$mixedSubmitName] = 1;
  77. $oForm->aFormAttrs['method'] = BX_DOL_FORM_METHOD_SPECIFIC;
  78. $oForm->aParams['csrf']['disable'] = true;
  79. $oForm->initChecker([], $aParams['cond']);
  80. }
  81. if(!$oForm->isSubmittedAndValid() && !$this->_bFilterMode && (!$this->_bIsApi || !isset($aParams['search_params'])))
  82. return $this->_bIsApi ? [$this->getResultsAPI([], $iStart, $iPerPage)] : '';
  83. $oContentInfo = BxDolContentInfo::getObjectInstance($this->_aObject['object_content_info']);
  84. if(!$oContentInfo)
  85. return $this->_bIsApi ? [$this->getResultsAPI([], $iStart, $iPerPage)] : '';
  86. $aParamsSearch = [];
  87. if(empty($aParams['search_params'])) {
  88. foreach($this->_aObject['fields'] as $aField) {
  89. $mixedValue = $oForm->getCleanValue($aField['name']);
  90. if(empty($mixedValue) || (is_array($mixedValue) && bx_is_empty_array($mixedValue)))
  91. continue;
  92. $aParamsSearch[$aField['name']] = [
  93. 'type' => $aField['search_type'],
  94. 'value' => $mixedValue,
  95. 'operator' => $aField['search_operator']
  96. ];
  97. if(!$bCondition) {
  98. if(!isset($aParams['cond']))
  99. $aParams['cond'] = array();
  100. switch($oForm->aInputs[$aField['name']]['type']) {
  101. case 'location':
  102. case 'location_radius':
  103. $aParams['cond'][$aField['name']] = $mixedValue['string'];
  104. $aLocationComponents = BxDolMetatags::locationsParseComponents($mixedValue['array'], $aField['name']);
  105. if($oForm->aInputs[$aField['name']]['type'] == 'location_radius' && count($mixedValue['array']) > count($aLocationComponents))
  106. $aLocationComponents[$aField['name'] . '_rad'] = array_pop($mixedValue['array']);
  107. $aParams['cond'] = array_merge($aParams['cond'], $aLocationComponents);
  108. break;
  109. default:
  110. $aParams['cond'][$aField['name']] = $mixedValue;
  111. }
  112. }
  113. }
  114. }
  115. else
  116. $aParamsSearch = $aParams['search_params'];
  117. if((empty($aParamsSearch) || !is_array($aParamsSearch)) && !$this->_bFilterMode)
  118. return $this->_bIsApi ? [$this->getResultsAPI([], $iStart, $iPerPage, $aParamsSearch)] : '';
  119. if(($mixedSort = bx_get('sort')) !== false && ($aSort = explode(':', $mixedSort)))
  120. $aParamsSearch['order'] = [['field' => $aSort[0], 'direction' => $aSort[1]]];
  121. $aResults = false;
  122. /**
  123. * @hooks
  124. * @hookdef hook-search-get_data 'search', 'get_data' - hook in get data for serach
  125. * - $unit_name - equals `search`
  126. * - $action - equals `get_data`
  127. * - $object_id - not used
  128. * - $sender_id - not used
  129. * - $extra_params - array of additional params with the following array keys:
  130. * - `object` - [array] by ref, object info for current search, can be overridden in hook processing
  131. * - `search_params` - [string] by ref, search params, can be overridden in hook processing
  132. * - `search_results` - [string] by ref, html for block, can be overridden in hook processing
  133. * @hook @ref hook-search-get_data
  134. */
  135. bx_alert('search', 'get_data', 0, false, [
  136. 'object' => $this->_aObject,
  137. 'search_params' => &$aParamsSearch,
  138. 'search_results' => &$aResults,
  139. 'search_params_ref' => &$aParamsSearch,
  140. 'search_results_ref' => &$aResults,
  141. ]);
  142. if($aResults === false)
  143. $aResults = $oContentInfo->getSearchResultExtended($aParamsSearch, $iStart, $iPerPage + 1, $this->_bFilterMode);
  144. if(empty($aResults) || !is_array($aResults))
  145. return $this->_bIsApi ? [$this->getResultsAPI([], $iStart, $iPerPage, $aParamsSearch)] : _t('Nothing found');
  146. $iResults = count($aResults);
  147. if($iResults > $iPerPage)
  148. array_pop($aResults);
  149. $mixedResults = $this->_bIsApi ? [] : '';
  150. foreach($aResults as $iId) {
  151. $mixedResult = $oContentInfo->getContentSearchResultUnit($iId, $sUnitTemplate);
  152. if($this->_bIsApi)
  153. $mixedResults[] = $mixedResult;
  154. else
  155. $mixedResults .= $mixedResult;
  156. }
  157. if($this->_bIsApi)
  158. return [$this->getResultsAPI($mixedResults, $iStart, $iPerPage, $aParamsSearch)];
  159. //-- Paginate
  160. $bTmplVarsPaginate = false;
  161. $aTmplVarsPaginate = [];
  162. if(($bTmplVarsPaginate = $iStart || $iResults > $iPerPage) !== false) {
  163. if(!empty($aParams['cond']) && is_array($aParams['cond']))
  164. $aParams['cond'] = self::encodeConditions($aParams['cond']);
  165. $aPaginate = ['num' => $iResults, 'start' => $iStart, 'per_page' => $iPerPage];
  166. if(($sKt = 'total') && ($mixedTotal = $aParams[$sKt] ?? false)) {
  167. if(is_numeric($mixedTotal))
  168. $aPaginate[$sKt] = (int)$mixedTotal;
  169. else
  170. $aPaginate[$sKt] = count($oContentInfo->getSearchResultExtended($aParamsSearch, 0, 0, $this->_bFilterMode));
  171. }
  172. if(!$bJsMode) {
  173. $aParams['start'] = '{start}';
  174. $aParams['per_page'] = '{per_page}';
  175. list($sPageLink, $aPageParams) = bx_get_base_url_inline($aParams);
  176. $aPaginate['page_url'] = BxDolPermalinks::getInstance()->permalink(bx_append_url_params($sPageLink, $aPageParams, true, ['{start}', '{per_page}']));
  177. }
  178. else
  179. $aPaginate['on_change_page'] = "return !loadDynamicBlockAutoPaginate(this, '{start}', '{per_page}', " . bx_js_string(json_encode($aParams)) . ");";
  180. $oPaginate = new BxTemplPaginate($aPaginate);
  181. $aTmplVarsPaginate = [
  182. 'paginate' => $oPaginate->getSimplePaginate()
  183. ];
  184. }
  185. return $this->_oTemplate->parseHtmlByName('search_extended_results.html', [
  186. 'class' => str_replace('_', '-', $this->_sObject),
  187. 'sort' => $mixedResults != '' ? $this->getSorting($aParams) : '',
  188. 'code' => $mixedResults,
  189. 'bx_if:show_paginate' => [
  190. 'condition' => $bTmplVarsPaginate,
  191. 'content' => $aTmplVarsPaginate
  192. ]
  193. ]);
  194. }
  195. public function getResultsAPI($aData, $iStart, $iPerPage, $aParamsSearch = '')
  196. {
  197. return bx_api_get_block('browse', [
  198. 'nocache' => true,
  199. 'module' => $this->_aObject['module'],
  200. 'unit' => 'general-content-list',
  201. 'request_url' => '/api.php?r=system/get_results/TemplSearchExtendedServices&params[]=',
  202. 'data' => defined('BX_API_PAGE') ? [] : $aData,
  203. 'params' => ['per_page' => $iPerPage, 'start' => $iStart, 'object' => $this->_aObject['module'], 'search_params' => $aParamsSearch],
  204. ]);
  205. }
  206. public function getSorting($aParams = [])
  207. {
  208. if(!$this->isEnabled())
  209. return '';
  210. $aTxtDirection = [
  211. 'asc' => _t('_order_asc'),
  212. 'desc' => _t('_order_desc')
  213. ];
  214. $bJsMode = isset($aParams['js_mode']) ? (bool)$aParams['js_mode'] : $this->_bJsMode;
  215. $aValues = [];
  216. foreach($this->_aObject['sortable_fields'] as $aField) {
  217. if($aField['active'] == 0)
  218. continue;
  219. $sLangKey = $aField['caption'] . '_' . $aField['direction'];
  220. $sLangVal = _t($sLangKey);
  221. $aValues[] = [
  222. 'key' => $aField['name'] . ':' . $aField['direction'],
  223. 'value' => strcmp($sLangKey, $sLangVal) != 0 ? $sLangVal : _t($aField['caption']) . ' ' . $aTxtDirection[$aField['direction']]
  224. ];
  225. }
  226. if(!empty($aValues))
  227. $aValues = array_merge([['key' => '', 'value' => _t('_sys_txt_search_sort_by_default')]], $aValues);
  228. if($this->_bIsApi)
  229. return $this->getSortingAPI($aValues);
  230. $oForm = new BxTemplFormView([]);
  231. $sOnChange = '';
  232. if(!$bJsMode) {
  233. unset($aParams['start'], $aParams['per_page']);
  234. list($sPageLink, $aPageParams) = bx_get_base_url_inline($aParams);
  235. $sOnChange = "bx_search_extnded_sort(this,'" . BxDolPermalinks::getInstance()->permalink(bx_append_url_params($sPageLink, $aPageParams)) . "')";
  236. }
  237. else
  238. $sOnChange = "return !loadDynamicBlockAutoSort(this, $(this).val()," . bx_js_string(json_encode($aParams)) . ");";
  239. $sSort = '';
  240. if(!empty($aValues)) {
  241. $aInputSort = [
  242. 'type' => 'select',
  243. 'name' => 'sort',
  244. 'value' => bx_get('sort') ? bx_get('sort') : '',
  245. 'values' => $aValues,
  246. 'caption' => _t('_sys_txt_search_sort_by'),
  247. 'attrs' => [
  248. 'onChange' => $sOnChange,
  249. ],
  250. 'tr_attrs' => [
  251. 'class' => 'sort'
  252. ]
  253. ];
  254. $sSort = $oForm->genRow($aInputSort);
  255. }
  256. return $sSort;
  257. }
  258. public function getSortingAPI($aData)
  259. {
  260. return bx_api_get_block('sorting', [
  261. 'nocache' => true,
  262. 'module' => $this->_aObject['module'],
  263. 'data' => $aData
  264. ]);
  265. }
  266. protected function &prepareForm($aParams = array())
  267. {
  268. if(!empty($this->_oForm) && $this->_oForm instanceof BxDolForm)
  269. return $this->_oForm;
  270. $sForm = 'sys_search_extended_' . $this->_sObject;
  271. $sFormSubmit = 'search' . $this->_sObject;
  272. list($sPageLink, $aPageParams) = bx_get_base_url_inline();
  273. $mDefValues = bx_get('filters');
  274. if ($mDefValues){
  275. $mDefValues = json_decode($mDefValues, true);
  276. }
  277. $aForm = array(
  278. 'form_attrs' => array(
  279. 'id' => $sForm,
  280. 'name' => $sForm,
  281. 'action' => !empty($aPageParams['i']) ? BxDolPermalinks::getInstance()->permalink(bx_append_url_params($sPageLink, array('i' => $aPageParams['i']))) : $sPageLink,
  282. 'method' => 'post'
  283. ),
  284. 'params' => array(
  285. 'db' => array(
  286. 'table' => '',
  287. 'key' => '',
  288. 'uri' => '',
  289. 'uri_title' => '',
  290. 'submit_name' => $sFormSubmit
  291. ),
  292. 'checker_helper' => 'BxBaseSearchExtendedFormCheckerHelper',
  293. ),
  294. 'inputs' => array()
  295. );
  296. foreach ($this->_aObject['fields'] as $aField) {
  297. if((int)$aField['active'] == 0)
  298. continue;
  299. if(in_array($aField['search_type'], array('checkbox_set', 'select_multiple'))) {
  300. if(isset($aField['values']['']))
  301. unset($aField['values']['']);
  302. if(isset($aField['values'][0]) && !is_array($aField['values'][0]))
  303. unset($aField['values'][0]);
  304. }
  305. $aAttrs = array();
  306. if(in_array($aField['search_type'], array('datepicker_range_age')) && !empty($aField['search_value'])) {
  307. $aFieldParams = BxDolService::callSerialized($aField['search_value']);
  308. $iMin = isset($aFieldParams['min']) && is_numeric($aFieldParams['min']) ? $aFieldParams['min'] : $this->_iAgeMin;
  309. $iMax = isset($aFieldParams['max']) && is_numeric($aFieldParams['max']) ? $aFieldParams['max'] : $this->_iAgeMax;
  310. $aField['search_value'] = $iMin . '-' . $iMax;
  311. $aAttrs = array('min' => $iMin, 'max' => $iMax, 'step' => 1);
  312. }
  313. if(in_array($aField['search_type'], array('datepicker_range')) && !empty($aField['search_value'])) {
  314. $aField['search_value'] = '';
  315. }
  316. $aForm['inputs'][$aField['name']] = array(
  317. 'type' => $aField['search_type'],
  318. 'name' => $aField['name'],
  319. 'caption' => _t($aField['caption']),
  320. 'info' => _t($aField['info']),
  321. 'values' => $aField['values'],
  322. 'value' => $aField['search_value'] == '' && isset($mDefValues) && isset($mDefValues[$aField['name']]) ? $mDefValues[$aField['name']] : $aField['search_value'],
  323. 'attrs' => $aAttrs,
  324. 'db' => array(
  325. 'pass' => 'datepicker_range_age' === $aField['search_type'] ? 'AgeRange' : (!empty($aField['pass']) ? $aField['pass'] : 'Xss')
  326. )
  327. );
  328. if(in_array($aField['search_type'], array('location', 'location_radius')))
  329. $aForm['inputs'][$aField['name']]['manual_input'] = true;
  330. }
  331. $aForm['inputs']['search'] = array(
  332. 'type' => 'submit',
  333. 'name' => $sFormSubmit,
  334. 'value' => _t($this->_bFilterMode ? '_Apply' : '_Search')
  335. );
  336. $sClass = 'BxTemplSearchExtendedForm';
  337. if(!empty($this->_sFormClassName)) {
  338. $sClass = $this->_sFormClassName;
  339. if(!empty($this->_sFormClassPath))
  340. require_once(BX_DIRECTORY_PATH_ROOT . $this->_sFormClassPath);
  341. }
  342. $bJsMode = isset($aParams['js_mode']) ? (bool)$aParams['js_mode'] : $this->_bJsMode;
  343. $bCondition = !empty($aParams['cond']) && is_array($aParams['cond']);
  344. $aValues = !$bJsMode && $bCondition ? $aParams['cond'] : array();
  345. $this->_oForm = new $sClass($aForm, $this->_oTemplate);
  346. $this->_oForm->initChecker($aValues, $aValues);
  347. return $this->_oForm;
  348. }
  349. }
  350. class BxBaseSearchExtendedFormCheckerHelper extends BxDolFormCheckerHelper
  351. {
  352. static public function passAgeRange ($s)
  353. {
  354. if (is_array($s)) {
  355. $a = array ();
  356. foreach ($s as $k => $v)
  357. $a[$k] = self::_passAgeRange ($v);
  358. return $a;
  359. }
  360. return self::_passAgeRange ($s);
  361. }
  362. static public function _passAgeRange ($s)
  363. {
  364. $a = explode ('-', $s);
  365. if (!$a || count($a) != 2)
  366. return $s;
  367. $i0 = new \DateInterval("P".(int)$a[0]."Y");
  368. $i1 = new \DateInterval("P".(int)$a[1]."Y");
  369. return [
  370. (new DateTime("now", new DateTimeZone('UTC')))->sub($i1)->format("Y-m-d"),
  371. (new DateTime("now", new DateTimeZone('UTC')))->sub($i0)->format("Y-m-d"),
  372. ];
  373. }
  374. }
  375. /** @} */