BxBaseSearchExtended.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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, '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(!$this->_bIsApi || !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. bx_alert('search', 'get_data', 0, false, array('object' => $this->_aObject, 'search_params' => &$aParamsSearch, 'search_results' => &$aResults));
  140. if($aResults === false)
  141. $aResults = $oContentInfo->getSearchResultExtended($aParamsSearch, $iStart, $iPerPage + 1, $this->_bFilterMode);
  142. if(empty($aResults) || !is_array($aResults))
  143. return $this->_bIsApi ? bx_api_get_msg(_t('Nothing found'), ['ext' => ['msg_type' => 'result']]) : _t('Nothing found');
  144. if(!empty($aParams['cond']) && is_array($aParams['cond']))
  145. $aParams['cond'] = self::encodeConditions($aParams['cond']);
  146. $aPaginate = ['start' => $iStart, 'per_page' => $iPerPage];
  147. if(!empty($aParams['total'])) {
  148. if(is_numeric($aParams['total']))
  149. $aPaginate['total'] = (int)$aParams['total'];
  150. else
  151. $aPaginate['total'] = count($oContentInfo->getSearchResultExtended($aParamsSearch, 0, 0, $this->_bFilterMode));
  152. }
  153. if(!$bJsMode) {
  154. $aParams['start'] = '{start}';
  155. $aParams['per_page'] = '{per_page}';
  156. list($sPageLink, $aPageParams) = bx_get_base_url_inline($aParams);
  157. if(!$this->_bIsApi)
  158. $aPaginate['page_url'] = BxDolPermalinks::getInstance()->permalink(bx_append_url_params($sPageLink, $aPageParams, true, ['{start}', '{per_page}']));
  159. }
  160. else
  161. $aPaginate['on_change_page'] = "return !loadDynamicBlockAutoPaginate(this, '{start}', '{per_page}', " . bx_js_string(json_encode($aParams)) . ");";
  162. $oPaginate = new BxTemplPaginate($aPaginate);
  163. $oPaginate->setNumFromDataArray($aResults);
  164. $bTmplVarsPaginate = $iStart || $oPaginate->getNum() > $iPerPage;
  165. $aTmplVarsPaginate = $bTmplVarsPaginate ? array('paginate' => $oPaginate->getSimplePaginate()) : array();
  166. $mixedResults = $this->_bIsApi ? [] : '';
  167. foreach($aResults as $iId) {
  168. $mixedResult = $oContentInfo->getContentSearchResultUnit($iId, $sUnitTemplate);
  169. if($this->_bIsApi)
  170. $mixedResults[] = $mixedResult;
  171. else
  172. $mixedResults .= $mixedResult;
  173. }
  174. if($this->_bIsApi) {
  175. if(isset($aParams['search_params']))
  176. return [$this->getResultsAPI($aRes, $iPerPage, $iStart, $aParamsSearch)];
  177. else
  178. return $this->getResultsAPI([], $iPerPage, $iStart, $aParamsSearch);
  179. }
  180. $aTxtDirection = [
  181. 'asc' => _t('_order_asc'),
  182. 'desc' => _t('_order_desc')
  183. ];
  184. $sSort = '';
  185. if($mixedResults != '') {
  186. $aData = $this->_aObject['sortable_fields'];
  187. $aValues = [];
  188. foreach($aData as $aField) {
  189. if ($aField['active'] == 0)
  190. continue;
  191. $sLangKey = $aField['caption'] . '_' . $aField['direction'];
  192. $sLangVal = _t($sLangKey);
  193. $aValues[$aField['name'] . ':' . $aField['direction']] = strcmp($sLangKey, $sLangVal) != 0 ? $sLangVal : _t($aField['caption']) . ' ' . $aTxtDirection[$aField['direction']];
  194. }
  195. if (!empty($aValues)){
  196. $aValues = array_merge(['' => _t('_sys_txt_search_sort_by_default')], $aValues);
  197. }
  198. $oForm = new BxTemplFormView(array());
  199. $sOnChange = '';
  200. if(!$bJsMode) {
  201. unset($aParams['start']);
  202. unset($aParams['per_page']);
  203. list($sPageLink, $aPageParams) = bx_get_base_url_inline($aParams);
  204. $sOnChange = "bx_search_extnded_sort(this,'" . BxDolPermalinks::getInstance()->permalink(bx_append_url_params($sPageLink, $aPageParams)) . "')";
  205. }
  206. else{
  207. $sOnChange = "return !loadDynamicBlockAutoSort(this, $(this).val()," . bx_js_string(json_encode($aParams)) . ");";
  208. }
  209. $sSort = '';
  210. if (!empty($aValues)){
  211. $aInputSort = array(
  212. 'type' => 'select',
  213. 'name' => 'sort',
  214. 'value' => bx_get('sort') ? bx_get('sort') : '',
  215. 'values' => $aValues,
  216. 'caption' => _t('_sys_txt_search_sort_by'),
  217. 'attrs' => array(
  218. 'onChange' => $sOnChange,
  219. ),
  220. 'tr_attrs' => array(
  221. 'class' => 'sort'
  222. )
  223. );
  224. $sSort = $oForm->genRow($aInputSort);
  225. }
  226. }
  227. return $this->_oTemplate->parseHtmlByName('search_extended_results.html', array(
  228. 'sort' => $sSort,
  229. 'code' => $mixedResults,
  230. 'bx_if:show_paginate' => array(
  231. 'condition' => $bTmplVarsPaginate,
  232. 'content' => $aTmplVarsPaginate
  233. )
  234. ));
  235. }
  236. protected function &prepareForm($aParams = array())
  237. {
  238. if(!empty($this->_oForm) && $this->_oForm instanceof BxDolForm)
  239. return $this->_oForm;
  240. $sForm = 'sys_search_extended_' . $this->_sObject;
  241. $sFormSubmit = 'search' . $this->_sObject;
  242. list($sPageLink, $aPageParams) = bx_get_base_url_inline();
  243. $aForm = array(
  244. 'form_attrs' => array(
  245. 'id' => $sForm,
  246. 'name' => $sForm,
  247. 'action' => BxDolPermalinks::getInstance()->permalink(bx_append_url_params($sPageLink, array('i' => $aPageParams['i']))),
  248. 'method' => 'post'
  249. ),
  250. 'params' => array(
  251. 'db' => array(
  252. 'table' => '',
  253. 'key' => '',
  254. 'uri' => '',
  255. 'uri_title' => '',
  256. 'submit_name' => $sFormSubmit
  257. ),
  258. 'checker_helper' => 'BxBaseSearchExtendedFormCheckerHelper',
  259. ),
  260. 'inputs' => array()
  261. );
  262. foreach ($this->_aObject['fields'] as $aField) {
  263. if((int)$aField['active'] == 0)
  264. continue;
  265. if(in_array($aField['search_type'], array('checkbox_set', 'select_multiple'))) {
  266. if(isset($aField['values']['']))
  267. unset($aField['values']['']);
  268. if(isset($aField['values'][0]) && !is_array($aField['values'][0]))
  269. unset($aField['values'][0]);
  270. }
  271. $aAttrs = array();
  272. if(in_array($aField['search_type'], array('datepicker_range_age')) && !empty($aField['search_value'])) {
  273. $aFieldParams = BxDolService::callSerialized($aField['search_value']);
  274. $iMin = isset($aFieldParams['min']) && is_numeric($aFieldParams['min']) ? $aFieldParams['min'] : $this->_iAgeMin;
  275. $iMax = isset($aFieldParams['max']) && is_numeric($aFieldParams['max']) ? $aFieldParams['max'] : $this->_iAgeMax;
  276. $aField['search_value'] = $iMin . '-' . $iMax;
  277. $aAttrs = array('min' => $iMin, 'max' => $iMax, 'step' => 1);
  278. }
  279. if(in_array($aField['search_type'], array('datepicker_range')) && !empty($aField['search_value'])) {
  280. $aField['search_value'] = '';
  281. }
  282. $aForm['inputs'][$aField['name']] = array(
  283. 'type' => $aField['search_type'],
  284. 'name' => $aField['name'],
  285. 'caption' => _t($aField['caption']),
  286. 'info' => _t($aField['info']),
  287. 'values' => $aField['values'],
  288. 'value' => $aField['search_value'],
  289. 'attrs' => $aAttrs,
  290. 'db' => array(
  291. 'pass' => 'datepicker_range_age' === $aField['search_type'] ? 'AgeRange' : (!empty($aField['pass']) ? $aField['pass'] : 'Xss')
  292. )
  293. );
  294. if(in_array($aField['search_type'], array('location', 'location_radius')))
  295. $aForm['inputs'][$aField['name']]['manual_input'] = true;
  296. }
  297. $aForm['inputs']['search'] = array(
  298. 'type' => 'submit',
  299. 'name' => $sFormSubmit,
  300. 'value' => _t($this->_bFilterMode ? '_Apply' : '_Search')
  301. );
  302. $sClass = 'BxTemplSearchExtendedForm';
  303. if(!empty($this->_sFormClassName)) {
  304. $sClass = $this->_sFormClassName;
  305. if(!empty($this->_sFormClassPath))
  306. require_once(BX_DIRECTORY_PATH_ROOT . $this->_sFormClassPath);
  307. }
  308. $bJsMode = isset($aParams['js_mode']) ? (bool)$aParams['js_mode'] : $this->_bJsMode;
  309. $bCondition = !empty($aParams['cond']) && is_array($aParams['cond']);
  310. $aValues = !$bJsMode && $bCondition ? $aParams['cond'] : array();
  311. $this->_oForm = new $sClass($aForm, $this->_oTemplate);
  312. $this->_oForm->initChecker($aValues, $aValues);
  313. return $this->_oForm;
  314. }
  315. }
  316. class BxBaseSearchExtendedFormCheckerHelper extends BxDolFormCheckerHelper
  317. {
  318. static public function passAgeRange ($s)
  319. {
  320. if (is_array($s)) {
  321. $a = array ();
  322. foreach ($s as $k => $v)
  323. $a[$k] = self::_passAgeRange ($v);
  324. return $a;
  325. }
  326. return self::_passAgeRange ($s);
  327. }
  328. static public function _passAgeRange ($s)
  329. {
  330. $a = explode ('-', $s);
  331. if (!$a || count($a) != 2)
  332. return $s;
  333. $i0 = new \DateInterval("P".(int)$a[0]."Y");
  334. $i1 = new \DateInterval("P".(int)$a[1]."Y");
  335. return [
  336. (new DateTime("now", new DateTimeZone('UTC')))->sub($i1)->format("Y-m-d"),
  337. (new DateTime("now", new DateTimeZone('UTC')))->sub($i0)->format("Y-m-d"),
  338. ];
  339. }
  340. }
  341. /** @} */