BxBaseSearchExtended.php 19 KB

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