BxBaseSearchExtended.php 19 KB

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