BxBaseSearchExtended.php 19 KB

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