1
0

BxBaseSearchExtended.php 16 KB

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