BxBaseSearchExtended.php 17 KB

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