BxBaseSearchExtended.php 17 KB

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