BxBaseSearchExtended.php 17 KB

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