BxBaseSearchExtended.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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. ]);
  140. if($aResults === false)
  141. $aResults = $oContentInfo->getSearchResultExtended($aParamsSearch, $iStart, $iPerPage + 1, $this->_bFilterMode);
  142. if(empty($aResults) || !is_array($aResults))
  143. return $this->_bIsApi ? [$this->getResultsAPI([], $iStart, $iPerPage, $aParamsSearch)] : _t('Nothing found');
  144. $iResults = count($aResults);
  145. if($iResults > $iPerPage)
  146. array_pop($aResults);
  147. $mixedResults = $this->_bIsApi ? [] : '';
  148. foreach($aResults as $iId) {
  149. $mixedResult = $oContentInfo->getContentSearchResultUnit($iId, $sUnitTemplate);
  150. if($this->_bIsApi)
  151. $mixedResults[] = $mixedResult;
  152. else
  153. $mixedResults .= $mixedResult;
  154. }
  155. if($this->_bIsApi)
  156. return [$this->getResultsAPI($mixedResults, $iStart, $iPerPage, $aParamsSearch)];
  157. //-- Paginate
  158. $bTmplVarsPaginate = false;
  159. $aTmplVarsPaginate = [];
  160. if(($bTmplVarsPaginate = $iStart || $iResults > $iPerPage) !== false) {
  161. if(!empty($aParams['cond']) && is_array($aParams['cond']))
  162. $aParams['cond'] = self::encodeConditions($aParams['cond']);
  163. $aPaginate = ['num' => $iResults, 'start' => $iStart, 'per_page' => $iPerPage];
  164. if(($sKt = 'total') && ($mixedTotal = $aParams[$sKt] ?? false)) {
  165. if(is_numeric($mixedTotal))
  166. $aPaginate[$sKt] = (int)$mixedTotal;
  167. else
  168. $aPaginate[$sKt] = count($oContentInfo->getSearchResultExtended($aParamsSearch, 0, 0, $this->_bFilterMode));
  169. }
  170. if(!$bJsMode) {
  171. $aParams['start'] = '{start}';
  172. $aParams['per_page'] = '{per_page}';
  173. list($sPageLink, $aPageParams) = bx_get_base_url_inline($aParams);
  174. $aPaginate['page_url'] = BxDolPermalinks::getInstance()->permalink(bx_append_url_params($sPageLink, $aPageParams, true, ['{start}', '{per_page}']));
  175. }
  176. else
  177. $aPaginate['on_change_page'] = "return !loadDynamicBlockAutoPaginate(this, '{start}', '{per_page}', " . bx_js_string(json_encode($aParams)) . ");";
  178. $oPaginate = new BxTemplPaginate($aPaginate);
  179. $aTmplVarsPaginate = [
  180. 'paginate' => $oPaginate->getSimplePaginate()
  181. ];
  182. }
  183. return $this->_oTemplate->parseHtmlByName('search_extended_results.html', [
  184. 'class' => str_replace('_', '-', $this->_sObject),
  185. 'sort' => $mixedResults != '' ? $this->getSorting($aParams) : '',
  186. 'code' => $mixedResults,
  187. 'bx_if:show_paginate' => [
  188. 'condition' => $bTmplVarsPaginate,
  189. 'content' => $aTmplVarsPaginate
  190. ]
  191. ]);
  192. }
  193. public function getResultsAPI($aData, $iStart, $iPerPage, $aParamsSearch = '')
  194. {
  195. return bx_api_get_block('browse', [
  196. 'nocache' => true,
  197. 'module' => $this->_aObject['module'],
  198. 'unit' => 'general-content-list',
  199. 'request_url' => '/api.php?r=system/get_results/TemplSearchExtendedServices&params[]=',
  200. 'data' => defined('BX_API_PAGE') ? [] : $aData,
  201. 'params' => ['per_page' => $iPerPage, 'start' => $iStart, 'object' => $this->_aObject['module'], 'search_params' => $aParamsSearch],
  202. ]);
  203. }
  204. public function getSorting($aParams = [])
  205. {
  206. if(!$this->isEnabled())
  207. return '';
  208. $aTxtDirection = [
  209. 'asc' => _t('_order_asc'),
  210. 'desc' => _t('_order_desc')
  211. ];
  212. $bJsMode = isset($aParams['js_mode']) ? (bool)$aParams['js_mode'] : $this->_bJsMode;
  213. $aValues = [];
  214. foreach($this->_aObject['sortable_fields'] as $aField) {
  215. if($aField['active'] == 0)
  216. continue;
  217. $sLangKey = $aField['caption'] . '_' . $aField['direction'];
  218. $sLangVal = _t($sLangKey);
  219. $aValues[] = [
  220. 'key' => $aField['name'] . ':' . $aField['direction'],
  221. 'value' => strcmp($sLangKey, $sLangVal) != 0 ? $sLangVal : _t($aField['caption']) . ' ' . $aTxtDirection[$aField['direction']]
  222. ];
  223. }
  224. if(!empty($aValues))
  225. $aValues = array_merge([['key' => '', 'value' => _t('_sys_txt_search_sort_by_default')]], $aValues);
  226. if($this->_bIsApi)
  227. return $this->getSortingAPI($aValues);
  228. $oForm = new BxTemplFormView([]);
  229. $sOnChange = '';
  230. if(!$bJsMode) {
  231. unset($aParams['start'], $aParams['per_page']);
  232. list($sPageLink, $aPageParams) = bx_get_base_url_inline($aParams);
  233. $sOnChange = "bx_search_extnded_sort(this,'" . BxDolPermalinks::getInstance()->permalink(bx_append_url_params($sPageLink, $aPageParams)) . "')";
  234. }
  235. else
  236. $sOnChange = "return !loadDynamicBlockAutoSort(this, $(this).val()," . bx_js_string(json_encode($aParams)) . ");";
  237. $sSort = '';
  238. if(!empty($aValues)) {
  239. $aInputSort = [
  240. 'type' => 'select',
  241. 'name' => 'sort',
  242. 'value' => bx_get('sort') ? bx_get('sort') : '',
  243. 'values' => $aValues,
  244. 'caption' => _t('_sys_txt_search_sort_by'),
  245. 'attrs' => [
  246. 'onChange' => $sOnChange,
  247. ],
  248. 'tr_attrs' => [
  249. 'class' => 'sort'
  250. ]
  251. ];
  252. $sSort = $oForm->genRow($aInputSort);
  253. }
  254. return $sSort;
  255. }
  256. public function getSortingAPI($aData)
  257. {
  258. return bx_api_get_block('sorting', [
  259. 'nocache' => true,
  260. 'module' => $this->_aObject['module'],
  261. 'data' => $aData
  262. ]);
  263. }
  264. protected function &prepareForm($aParams = array())
  265. {
  266. if(!empty($this->_oForm) && $this->_oForm instanceof BxDolForm)
  267. return $this->_oForm;
  268. $sForm = 'sys_search_extended_' . $this->_sObject;
  269. $sFormSubmit = 'search' . $this->_sObject;
  270. list($sPageLink, $aPageParams) = bx_get_base_url_inline();
  271. $mDefValues = bx_get('filters');
  272. if ($mDefValues){
  273. $mDefValues = json_decode($mDefValues, true);
  274. }
  275. $aForm = array(
  276. 'form_attrs' => array(
  277. 'id' => $sForm,
  278. 'name' => $sForm,
  279. 'action' => !empty($aPageParams['i']) ? BxDolPermalinks::getInstance()->permalink(bx_append_url_params($sPageLink, array('i' => $aPageParams['i']))) : $sPageLink,
  280. 'method' => 'post'
  281. ),
  282. 'params' => array(
  283. 'db' => array(
  284. 'table' => '',
  285. 'key' => '',
  286. 'uri' => '',
  287. 'uri_title' => '',
  288. 'submit_name' => $sFormSubmit
  289. ),
  290. 'checker_helper' => 'BxBaseSearchExtendedFormCheckerHelper',
  291. ),
  292. 'inputs' => array()
  293. );
  294. foreach ($this->_aObject['fields'] as $aField) {
  295. if((int)$aField['active'] == 0)
  296. continue;
  297. if(in_array($aField['search_type'], array('checkbox_set', 'select_multiple'))) {
  298. if(isset($aField['values']['']))
  299. unset($aField['values']['']);
  300. if(isset($aField['values'][0]) && !is_array($aField['values'][0]))
  301. unset($aField['values'][0]);
  302. }
  303. $aAttrs = array();
  304. if(in_array($aField['search_type'], array('datepicker_range_age')) && !empty($aField['search_value'])) {
  305. $aFieldParams = BxDolService::callSerialized($aField['search_value']);
  306. $iMin = isset($aFieldParams['min']) && is_numeric($aFieldParams['min']) ? $aFieldParams['min'] : $this->_iAgeMin;
  307. $iMax = isset($aFieldParams['max']) && is_numeric($aFieldParams['max']) ? $aFieldParams['max'] : $this->_iAgeMax;
  308. $aField['search_value'] = $iMin . '-' . $iMax;
  309. $aAttrs = array('min' => $iMin, 'max' => $iMax, 'step' => 1);
  310. }
  311. if(in_array($aField['search_type'], array('datepicker_range')) && !empty($aField['search_value'])) {
  312. $aField['search_value'] = '';
  313. }
  314. $aForm['inputs'][$aField['name']] = array(
  315. 'type' => $aField['search_type'],
  316. 'name' => $aField['name'],
  317. 'caption' => _t($aField['caption']),
  318. 'info' => _t($aField['info']),
  319. 'values' => $aField['values'],
  320. 'value' => $aField['search_value'] == '' && isset($mDefValues) && isset($mDefValues[$aField['name']]) ? $mDefValues[$aField['name']] : $aField['search_value'],
  321. 'attrs' => $aAttrs,
  322. 'db' => array(
  323. 'pass' => 'datepicker_range_age' === $aField['search_type'] ? 'AgeRange' : (!empty($aField['pass']) ? $aField['pass'] : 'Xss')
  324. )
  325. );
  326. if(in_array($aField['search_type'], array('location', 'location_radius')))
  327. $aForm['inputs'][$aField['name']]['manual_input'] = true;
  328. }
  329. $aForm['inputs']['search'] = array(
  330. 'type' => 'submit',
  331. 'name' => $sFormSubmit,
  332. 'value' => _t($this->_bFilterMode ? '_Apply' : '_Search')
  333. );
  334. $sClass = 'BxTemplSearchExtendedForm';
  335. if(!empty($this->_sFormClassName)) {
  336. $sClass = $this->_sFormClassName;
  337. if(!empty($this->_sFormClassPath))
  338. require_once(BX_DIRECTORY_PATH_ROOT . $this->_sFormClassPath);
  339. }
  340. $bJsMode = isset($aParams['js_mode']) ? (bool)$aParams['js_mode'] : $this->_bJsMode;
  341. $bCondition = !empty($aParams['cond']) && is_array($aParams['cond']);
  342. $aValues = !$bJsMode && $bCondition ? $aParams['cond'] : array();
  343. $this->_oForm = new $sClass($aForm, $this->_oTemplate);
  344. $this->_oForm->initChecker($aValues, $aValues);
  345. return $this->_oForm;
  346. }
  347. }
  348. class BxBaseSearchExtendedFormCheckerHelper extends BxDolFormCheckerHelper
  349. {
  350. static public function passAgeRange ($s)
  351. {
  352. if (is_array($s)) {
  353. $a = array ();
  354. foreach ($s as $k => $v)
  355. $a[$k] = self::_passAgeRange ($v);
  356. return $a;
  357. }
  358. return self::_passAgeRange ($s);
  359. }
  360. static public function _passAgeRange ($s)
  361. {
  362. $a = explode ('-', $s);
  363. if (!$a || count($a) != 2)
  364. return $s;
  365. $i0 = new \DateInterval("P".(int)$a[0]."Y");
  366. $i1 = new \DateInterval("P".(int)$a[1]."Y");
  367. return [
  368. (new DateTime("now", new DateTimeZone('UTC')))->sub($i1)->format("Y-m-d"),
  369. (new DateTime("now", new DateTimeZone('UTC')))->sub($i0)->format("Y-m-d"),
  370. ];
  371. }
  372. }
  373. /** @} */