BxBaseSearchExtended.php 18 KB

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