BxDolSearch.php 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500
  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 UnaCore UNA Core
  7. * @{
  8. */
  9. define('BX_DOL_SEARCH_RESULTS_PER_PAGE_DEFAULT', 10);
  10. define('BX_DOL_SEARCH_KEYWORD_PAGE', 'site-search-page');
  11. /**
  12. * Search class for different content.
  13. *
  14. * Allows present content in main search area for all modules.
  15. *
  16. * To add taking part content from your module to search area you need add a record to `sys_objects_search` table:
  17. * @code
  18. * ID - autoincremented id for internal usage
  19. * ObjectName - your unique module name, with vendor prefix, lowercase and spaces are underscored
  20. * Title - language key for module's choicer in global search form
  21. * ClassName - class name which is responsible for search process ad showing result for found results
  22. * ClassPath - file where your ClassName is stored (if class is stored in template folder then you can use key {tmpl})
  23. * @endcode
  24. *
  25. * For using this class you should have unit of BxDolSearchResult class (see description below) with method processing which is responsible for processing of search request.
  26. *
  27. * Example of usage can be seen in the BoonEx modules, for example: Posts
  28. *
  29. * Memberships/ACL:
  30. * Doesn't depend on user's membership.
  31. *
  32. * Alerts:
  33. * no alerts available
  34. *
  35. */
  36. class BxDolSearch extends BxDol
  37. {
  38. protected $_bIsApi;
  39. protected $_bAssitantForLiveSearch = true;
  40. protected $aClasses = array(); ///< array of all search classes
  41. protected $aChoice = array(); ///< array of current search classes which were choosen in search area
  42. protected $_bRawProcessing = false; ///< display search results without design box and paginate
  43. protected $_bDataProcessing = false; ///< return result as array of data
  44. protected $_bLiveSearch = false;
  45. protected $_sMetaType = '';
  46. protected $_sCategoryObject = ''; ///< by default = object from sys_objects_category table, for multicategories set to 'multi' string
  47. protected $_aCustomSearchCondition = array();
  48. protected $_aCustomCurrentCondition = array();
  49. protected $_sUnitTemplate = '';
  50. /**
  51. * Constructor
  52. * @param array $aChoice - array of choosen classes (will take a part only existing in `sys_objects_search` table)
  53. */
  54. public function __construct ($aChoice = '')
  55. {
  56. parent::__construct();
  57. $this->_bIsApi = bx_is_api();
  58. $this->aClasses = self::getSections();
  59. if (is_array($aChoice) && !empty($aChoice)) {
  60. foreach ($aChoice as $sValue) {
  61. if (isset($this->aClasses[$sValue]))
  62. $this->aChoice[$sValue] = $this->aClasses[$sValue];
  63. }
  64. } else {
  65. $this->aChoice = $this->aClasses;
  66. }
  67. }
  68. public static function getSections($bGlobal = null)
  69. {
  70. $sWhere = '';
  71. if ($bGlobal != null)
  72. $sWhere = ' AND `GlobalSearch` = ' . ($bGlobal ? '1' : '0');
  73. return BxDolDb::getInstance()->fromCache('sys_objects_search', 'getAllWithKey',
  74. 'SELECT `ID` as `id`,
  75. `Title` as `title`,
  76. `ClassName` as `class`,
  77. `ClassPath` as `file`,
  78. `ObjectName`,
  79. `GlobalSearch`
  80. FROM `sys_objects_search`
  81. WHERE 1 ' . $sWhere . '
  82. ORDER BY `Order` ASC', 'ObjectName'
  83. );
  84. }
  85. public function setApiOutput($bIsApi)
  86. {
  87. $this->_bIsApi = $bIsApi;
  88. }
  89. public function setAssistantForLiveSearch($bAssistantForLiveSearch)
  90. {
  91. $this->_bAssitantForLiveSearch = $bAssistantForLiveSearch;
  92. }
  93. /**
  94. * create units for all classes and calling their processing methods
  95. */
  96. public function response ()
  97. {
  98. $sCode = $this->_bDataProcessing ? [] : '';
  99. if($this->_bAssitantForLiveSearch && $this->_bLiveSearch && ($iAssistant = BxDolAI::getAssistantForLiveSearch()) != 0) {
  100. $sKeyword = '';
  101. if(($sKeyword = bx_get('keyword')) !== false)
  102. $sKeyword = bx_process_input($sKeyword);
  103. if($this->_bIsApi)
  104. $sCode .= BxDolAIAssistant::getObjectInstance($iAssistant)->getAskButton($sKeyword);
  105. }
  106. $bSingle = count($this->aChoice) == 1;
  107. foreach($this->aChoice as $sKey => $aValue) {
  108. if(!$this->_sMetaType && !$aValue['GlobalSearch'])
  109. continue;
  110. $sClassName = 'BxTemplSearchResult';
  111. if(!empty($aValue['class'])) {
  112. $sClassName = $aValue['class'];
  113. if(!empty($aValue['file']))
  114. require_once(BX_DIRECTORY_PATH_ROOT . $aValue['file']);
  115. }
  116. $oEx = new $sClassName();
  117. if($this->_sMetaType && !$oEx->isMetaEnabled($this->_sMetaType))
  118. continue;
  119. $oEx->setId($aValue['id']);
  120. $oEx->setLiveSearch($this->_bLiveSearch);
  121. $oEx->setMetaType($this->_sMetaType);
  122. $oEx->setCategoryObject($this->_sCategoryObject);
  123. $oEx->setCenterContentUnitSelector(false);
  124. $oEx->setSingleSearch($bSingle);
  125. $oEx->setCustomSearchCondition($this->_aCustomSearchCondition);
  126. $oEx->aCurrent = array_merge_recursive($oEx->aCurrent, $this->_aCustomCurrentCondition);
  127. if($this->_sUnitTemplate)
  128. $oEx->setUnitTemplate($this->_sUnitTemplate);
  129. if($this->_bDataProcessing) {
  130. if($this->_bIsApi) {
  131. if($bSingle) {
  132. $sMethod = 'decodeDataAPI';
  133. if($this->_bLiveSearch && ($sMethodLs = 'decodeLsDataAPI') && method_exists($oEx, $sMethodLs))
  134. $sMethod = $sMethodLs;
  135. $sCode = $oEx->$sMethod($oEx->getSearchData());
  136. }
  137. else
  138. $sCode[$sKey] = $oEx->getSearchQuery($sKey);
  139. }
  140. else
  141. $sCode[$sKey] = $oEx->getSearchData();
  142. }
  143. else
  144. $sCode .= $this->_bRawProcessing ? $oEx->processingRaw() : $oEx->processing();
  145. }
  146. if($this->_bIsApi && !$bSingle && is_array($sCode)) {
  147. $bExtendedUnits = getParam('sys_api_extended_units') == 'on';
  148. $aQueries = [];
  149. foreach($sCode as $aQuery)
  150. if(!empty($aQuery['query']))
  151. $aQueries[] = $aQuery['query'];
  152. $aItems = BxDolDb::getInstance()->getAll('(' . implode(') UNION (', $aQueries) . ') ORDER BY `added` DESC ' . current($sCode)['limit']);
  153. $sCode = [];
  154. foreach($aItems as $aItem)
  155. if(($oContentInfo = BxDolContentInfo::getObjectInstance($aItem['content_info'])) !== false)
  156. $sCode[] = $oContentInfo->getContentInfoAPI($aItem['id'], $bExtendedUnits);
  157. }
  158. return $sCode;
  159. }
  160. public function getEmptyResult ()
  161. {
  162. $sKey = _t('_Empty');
  163. return DesignBoxContent($sKey, MsgBox($sKey), BX_DB_PADDING_DEF);
  164. }
  165. public function getSearchResultObject($sChoice = '')
  166. {
  167. $aSearchResult = [];
  168. if($sChoice) {
  169. if(empty($this->aChoice[$sChoice]) || !is_array($this->aChoice[$sChoice]))
  170. return false;
  171. $aSearchResult = $this->aChoice[$sChoice];
  172. }
  173. else
  174. $aSearchResult = reset($this->aChoice);
  175. $sClassName = 'BxTemplSearchResult';
  176. if(!empty($aSearchResult['class'])) {
  177. $sClassName = $aSearchResult['class'];
  178. if(!empty($aSearchResult['file']))
  179. require_once(BX_DIRECTORY_PATH_ROOT . $aSearchResult['file']);
  180. }
  181. return new $sClassName();
  182. }
  183. protected function getKeyTitlesPairs ()
  184. {
  185. $a = array();
  186. foreach ($this->aChoice as $sKey => $r)
  187. if ($this->_sMetaType || $r['GlobalSearch'])
  188. $a[$sKey] = _t($r['title']);
  189. return $a;
  190. }
  191. public function setLiveSearch($bLiveSearch)
  192. {
  193. $this->_bLiveSearch = $bLiveSearch;
  194. }
  195. public function setMetaType($s)
  196. {
  197. $aMetaTypes = array('location_country', 'location_country_city', 'location_country_state', 'mention', 'keyword');
  198. if (in_array($s, $aMetaTypes))
  199. $this->_sMetaType = $s;
  200. }
  201. public function setCategoryObject($s)
  202. {
  203. $this->_sCategoryObject = $s;
  204. }
  205. /**
  206. * Set custom search condition to use istead of GET/POST variables
  207. * @param $a array of params, such as 'keyword', 'state', 'city'
  208. * @return nothing
  209. */
  210. public function setCustomSearchCondition($a)
  211. {
  212. $this->_aCustomSearchCondition = $a;
  213. }
  214. /**
  215. * Set custom data for aCurrent array
  216. * @param $a array of params
  217. * @return nothing
  218. */
  219. public function setCustomCurrentCondition($a)
  220. {
  221. $this->_aCustomCurrentCondition = $a;
  222. }
  223. /**
  224. * Set custom unit template
  225. * @param $s template name
  226. * @return nothing
  227. */
  228. public function setUnitTemplate($s)
  229. {
  230. $this->_sUnitTemplate = $s;
  231. }
  232. /**
  233. * Display search results without design box and paginate
  234. */
  235. public function setRawProcessing($b)
  236. {
  237. $this->_bRawProcessing = $b;
  238. }
  239. /**
  240. * Return search result as array of data
  241. */
  242. public function setDataProcessing($b)
  243. {
  244. $this->_bDataProcessing = $b;
  245. }
  246. }
  247. /*
  248. * Search class for processing search requests and displaying search results.
  249. *
  250. * Allows present content from modules on search params or internal (via fields of class) conditions.
  251. *
  252. * Example of usage (you can see example in any of default Dolhpin's modules):
  253. *
  254. * 1. Extends your own search class from this one (or from BxBaseSearchResult or BxBaseSearchResultSharedMedia classes)
  255. * 2. Set necessary fields of class (using as example BxFilesSearch):
  256. *
  257. * @code
  258. *
  259. * // main field of search class
  260. * $this->aCurrent = array(
  261. *
  262. * // name of module
  263. * 'name' => 'bx_files',
  264. *
  265. * // language key with name of module
  266. * 'title' => '_bx_files',
  267. *
  268. * // main content table
  269. * 'table' => 'bx_files_main',
  270. *
  271. * // array of all fields which can be choosen for select in result query
  272. * 'ownFields' => array('ID', 'Title', 'Uri', 'Desc', 'Date', 'Size', 'Ext', 'Views', 'Rate', 'RateCount', 'Type'),
  273. *
  274. * // array of fields which take a part in search by keyword (global search and related words only - in other cases leave it blank)
  275. * 'searchFields' => array('Title', 'Tags', 'Desc', 'Categories'),
  276. *
  277. * // array of join tables
  278. * // 'type' - type of join
  279. * // 'table' - join table
  280. * // 'mainField' - field from main table for 'on' condition
  281. * // 'onField' - field from joining table for 'on' condition
  282. * // 'joinFields' - array of fields from joining table
  283. *
  284. * 'join' => array(
  285. * 'profile' => array(
  286. * 'type' => 'left',
  287. * 'table' => 'Profiles',
  288. * 'mainField' => 'Owner',
  289. * 'onField' => 'ID',
  290. * 'joinFields' => array('NickName'),
  291. * ),
  292. * // ...
  293. * ),
  294. *
  295. * // array of search parameters
  296. * // 'value' - value of search parameter (can be number, string or array)
  297. * // 'field' - field which will take value of search, may be lefy as blank then in search query will be pasted to WHERE conditon via operator AGAINST
  298. * // 'operator' - operator between field and value (can be 'in', 'not in', '>', '<', 'against', 'like' and '=' by default),
  299. * // 'paramName' - GET param which will keep 'value' for pagianation
  300. *
  301. * 'restriction' => array(
  302. * 'activeStatus' => array('value'=>'approved', 'field'=>'Status', 'operator'=>'=', 'paramName' => 'status'),
  303. * 'albumType' => array('value'=>'', 'field'=>'Type', 'operator'=>'=', 'paramName'=>'albumType', 'table'=>'sys_albums'),
  304. * ),
  305. *
  306. * // array of pagination
  307. * // 'perPage' - units per page
  308. * // 'start' - show search results starting from this number
  309. * // 'num' - number of element to show on current page + 1
  310. *
  311. * 'paginate' => array('perPage' => 10, 'start' => 0, 'num' => 11),
  312. *
  313. * // sort mode - by default it was last (DESC by date)
  314. * 'sorting' => 'last',
  315. *
  316. * // mode of units presentation in search result, can be 'short' or 'full' view
  317. * 'view' => 'full',
  318. *
  319. * // field of id
  320. * 'ident' => 'ID',
  321. *
  322. * // rss feed array
  323. * 'rss' => array(
  324. * 'title' => '',
  325. * 'link' => '',
  326. * 'image' => '',
  327. * 'profile' => 0,
  328. * 'fields' => array (
  329. * 'Link' => '',
  330. * 'Title' => 'Title',
  331. * 'DateTimeUTS' => 'Date',
  332. * 'Desc' => 'Desc',
  333. * 'Photo' => '',
  334. * ),
  335. * ),
  336. * );
  337. *
  338. * // array of fields renamings
  339. * $aPseud - filling in costructor by function _getPseud
  340. *
  341. * // unique identificator from `sys_objects_search` table
  342. * $id;
  343. *
  344. * @endcode
  345. *
  346. * Memberships/ACL:
  347. * Doesn't depend on user's membership.
  348. *
  349. * Alerts:
  350. * no alerts available
  351. *
  352. */
  353. class BxDolSearchResult implements iBxDolReplaceable
  354. {
  355. public $aCurrent; ///< search results configuration
  356. protected $aPseud; ///< array of fields renamings
  357. protected $id; ///< unique identificator of block on mixed search results page
  358. protected $bDisplayEmptyMsg = false; ///< display empty message instead of nothing, when no results
  359. protected $sDisplayEmptyMsgKey = ''; ///< custom empty message language key, instead of default "empty" message
  360. protected $bProcessPrivateContent = true; ///< check each item for privacy, if view isn't allowed then display private view instead
  361. protected $aPrivateConditionsIndexes = array('restriction' => array(), 'join' => array()); ///< conditions indexes for bProcessPrivateContent
  362. protected $bForceAjaxPaginate = false; ///< force ajax paginate
  363. protected $iPaginatePerPage = BX_DOL_SEARCH_RESULTS_PER_PAGE_DEFAULT; ///< default 'per page' value for paginate.
  364. protected $_bIsApi;
  365. protected $_bSingleSearch = true;
  366. protected $_bLiveSearch = false;
  367. protected $_sMetaType = '';
  368. protected $_sMode = '';
  369. protected $_aParams = [];
  370. protected $_sCategoryObject = '';
  371. protected $_aCustomSearchCondition = array();
  372. protected $_aMarkers = array (); ///< markers to replace somewhere, usually title and browse url (defined in custom class)
  373. /**
  374. * constructor
  375. * filling identificator field
  376. */
  377. function __construct ()
  378. {
  379. $this->_bIsApi = bx_is_api();
  380. if (isset($this->aPseud['id']))
  381. $this->aCurrent['ident'] = $this->aPseud['id'];
  382. }
  383. public function getId()
  384. {
  385. return $this->id;
  386. }
  387. public function setId($sId)
  388. {
  389. $this->id = $sId;
  390. }
  391. public function getModuleName()
  392. {
  393. return isset($this->aCurrent['module_name']) ? $this->aCurrent['module_name'] : '';
  394. }
  395. public function getContentInfoName()
  396. {
  397. return isset($this->aCurrent['name']) ? $this->aCurrent['name'] : '';
  398. }
  399. public function setAjaxPaginate($b = true)
  400. {
  401. $this->bForceAjaxPaginate = $b;
  402. }
  403. public function setPaginatePerPage($iPerPage)
  404. {
  405. $this->iPaginatePerPage = $iPerPage;
  406. }
  407. public function setSingleSearch($bSingleSearch)
  408. {
  409. $this->_bSingleSearch = $bSingleSearch;
  410. }
  411. public function setLiveSearch($bLiveSearch)
  412. {
  413. $this->_bLiveSearch = $bLiveSearch;
  414. }
  415. public function setMetaType($s)
  416. {
  417. $this->_sMetaType = $s;
  418. }
  419. public function isMetaEnabled($s)
  420. {
  421. if (empty($this->aCurrent['object_metatags']))
  422. return false;
  423. if (!($o = BxDolMetatags::getObjectInstance($this->aCurrent['object_metatags'])))
  424. return false;
  425. switch ($s) {
  426. case 'location_country_city':
  427. case 'location_country_state':
  428. case 'location_country':
  429. return $o->locationsIsEnabled();
  430. case 'mention':
  431. return $o->mentionsIsEnabled();
  432. case 'keyword':
  433. return $o->keywordsIsEnabled();
  434. }
  435. return false;
  436. }
  437. public function setCategoryObject($s)
  438. {
  439. $this->_sCategoryObject = $s;
  440. }
  441. public function setCustomSearchCondition($a)
  442. {
  443. $this->_aCustomSearchCondition = $a;
  444. }
  445. public function setCustomCurrentCondition($a)
  446. {
  447. $this->aCurrent = array_merge_recursive($this->aCurrent, $a);
  448. }
  449. public function setCategoriesCondition($sKeyword)
  450. {
  451. $this->aCurrent['join']['multicat'] = array(
  452. 'type' => 'INNER',
  453. 'table' => 'sys_categories2objects',
  454. 'mainField' => 'id',
  455. 'onField' => 'object_id',
  456. 'joinFields' => array(),
  457. );
  458. if (isset($this->aCurrent['tableSearch'])){
  459. $this->aCurrent['join']['multicat']['mainTable'] = $this->aCurrent['tableSearch'];
  460. }
  461. $this->aCurrent['join']['multicat2'] = array(
  462. 'type' => 'INNER',
  463. 'table' => 'sys_categories',
  464. 'mainField' => 'category_id',
  465. 'mainTable' => 'sys_categories2objects',
  466. 'onField' => 'id',
  467. 'joinFields' => array(),
  468. );
  469. $this->aCurrent['restriction']['multicat'] = array('value' => $sKeyword, 'field' => 'value', 'operator' => '=', 'table' => 'sys_categories');
  470. }
  471. /**
  472. * Display empty message if there is no content, custom empty message can be used.
  473. * @param $b - boolan value to enable or disable 'empty' message
  474. * @param $sLangKey [optional] - custom 'empty' message
  475. */
  476. public function setDisplayEmptyMsg($b, $sLangKey = '')
  477. {
  478. $this->bDisplayEmptyMsg = $b;
  479. if ($sLangKey)
  480. $this->sDisplayEmptyMsgKey = $sLangKey;
  481. }
  482. /**
  483. * Perform privacy checking for every unit
  484. * @param $b - boolan value to enable or disable privacy checking
  485. */
  486. public function setProcessPrivateContent ($b)
  487. {
  488. $this->bProcessPrivateContent = $b;
  489. if ($b) {
  490. // unset condition which was set when 'bProcessPrivateContent' was set to 'false'
  491. foreach ($this->aPrivateConditionsIndexes['restriction'] as $sKey)
  492. unset($this->aCurrent['restriction'][$sKey]);
  493. foreach ($this->aPrivateConditionsIndexes['join'] as $sKey)
  494. unset($this->aCurrent['join'][$sKey]);
  495. }
  496. }
  497. /**
  498. * Get search results without design box and paginate
  499. * @return html code
  500. */
  501. function processingRaw ()
  502. {
  503. $sCode = $this->displayResultBlock();
  504. return $this->aCurrent['paginate']['num'] > 0 ? $sCode : '';
  505. }
  506. /**
  507. * Get html box of search results (usually used in grlobal search)
  508. * @return html code
  509. */
  510. function processing ()
  511. {
  512. if($this->_bIsApi)
  513. return $this->processingAPI();
  514. $sCode = $this->displayResultBlock();
  515. if ($this->aCurrent['paginate']['num'] > 0) {
  516. $sPaginate = $this->showPagination();
  517. $sCode = $this->displaySearchBox($sCode, $sPaginate);
  518. }
  519. else {
  520. $sCode = $this->bDisplayEmptyMsg ? $this->displaySearchBox($this->displayResultBlockEmpty()) : '';
  521. }
  522. return $sCode;
  523. }
  524. function processingAPI ($bForceGetData = false)
  525. {
  526. $sModule = 'system';
  527. $sUnitType = 'content';
  528. $sHomeUrl = '';
  529. if(!empty($this->oModule)) {
  530. $sModule = $this->oModule->getName();
  531. if(method_exists($this->oModule, 'serviceActAsProfile') && $this->oModule->serviceActAsProfile())
  532. $sUnitType = 'profile';
  533. if(method_exists($this->oModule, 'serviceIsGroupProfile') && $this->oModule->serviceIsGroupProfile())
  534. $sUnitType = 'context';
  535. $sHomeUrl = bx_api_get_relative_url(BxDolPermalinks::getInstance()->permalink($this->oModule->_oConfig->CNF['URL_HOME']));
  536. }
  537. $sUnit = 'list';
  538. if(in_array($this->sUnitViewDefault, ['showcase', 'gallery']))
  539. $sUnit = 'card';
  540. $aData = defined('BX_API_PAGE') && !$bForceGetData ? [] : $this->decodeDataAPI($this->getSearchData());
  541. $aParams = [
  542. 'per_page' => $this->aCurrent['paginate']['perPage'],
  543. 'start' => $this->aCurrent['paginate']['start'],
  544. 'type' => $this->_sMode,
  545. 'view' => $this->_aParams['unit_view']
  546. ];
  547. if ($sHomeUrl){
  548. $aParams['home_url'] = $sHomeUrl;
  549. }
  550. foreach(['author', 'category', 'context', 'joined_profile', 'followed_contexts', 'level'] as $sParamAdd)
  551. if(isset($this->_aParams[$sParamAdd]))
  552. $aParams[$sParamAdd] = $this->_aParams[$sParamAdd];
  553. return [
  554. 'module' => $sModule,
  555. 'unit' => 'general-' . $sUnitType . '-' . $sUnit,
  556. 'request_url' => !empty($this->aCurrent['api_request_url']) ? $this->aCurrent['api_request_url'] : '/api.php?r=' . $sModule . '/browse/&params[]=',
  557. 'data' => $aData,
  558. 'params' => $aParams
  559. ];
  560. }
  561. function decodeDataAPI ($a)
  562. {
  563. return $a;
  564. }
  565. /**
  566. * Get html output of search result
  567. * @return html code
  568. */
  569. function displayResultBlock ()
  570. {
  571. $aData = $this->getSearchData();
  572. $sCode = '';
  573. if (count($aData) > 0) {
  574. $sCode = $this->addCustomParts();
  575. foreach ($aData as $iKey => $aValue) {
  576. $sCode .= $this->displaySearchUnit($aValue);
  577. }
  578. }
  579. return $sCode;
  580. }
  581. /**
  582. * Get html output of empty search result
  583. * @return html code
  584. */
  585. function displayResultBlockEmpty ()
  586. {
  587. return MsgBox(_t($this->sDisplayEmptyMsgKey ? $this->sDisplayEmptyMsgKey : '_Empty'));
  588. }
  589. /**
  590. * Add different code before html output (usually redeclared)
  591. * no return result
  592. */
  593. function addCustomParts ()
  594. {
  595. }
  596. /**
  597. * Get XML string for rss output
  598. */
  599. function rss ()
  600. {
  601. if (!isset($this->aCurrent['rss']['fields']) || !isset($this->aCurrent['rss']['link']))
  602. return '';
  603. $aData = $this->getSearchData();
  604. $f = &$this->aCurrent['rss']['fields'];
  605. if ($aData) {
  606. foreach ($aData as $k => $a) {
  607. $aData[$k][$f['Link']] = $this->getRssUnitLink ($a);
  608. if(isset($f['Image']))
  609. $aData[$k][$f['Image']] = $this->getRssUnitImage ($a, $f['Image']);
  610. }
  611. }
  612. $oRss = new BxDolRssFactory ();
  613. return $oRss->GenRssByCustomData(
  614. $aData,
  615. isset($this->aCurrent['rss']['title']) && $this->aCurrent['rss']['title'] ? $this->aCurrent['rss']['title'] : $this->aCurrent['title'],
  616. $this->aCurrent['rss']['link'],
  617. $this->aCurrent['rss']['fields'],
  618. isset($this->aCurrent['rss']['image']) ? $this->aCurrent['rss']['image'] : '',
  619. isset($this->aCurrent['rss']['profile']) ? $this->aCurrent['rss']['profile'] : 0
  620. );
  621. }
  622. /**
  623. * Output RSS XML with XML header
  624. */
  625. function outputRSS ()
  626. {
  627. header('Content-Type: text/xml; charset=UTF-8');
  628. echo $this->rss();
  629. }
  630. /**
  631. * Return rss unit link (redeclared)
  632. */
  633. function getRssUnitLink (&$a)
  634. {
  635. // override this functions to return permalink to rss unit
  636. }
  637. /**
  638. * Return rss unit image (redeclared)
  639. */
  640. function getRssUnitImage (&$a, $sField)
  641. {
  642. // override this functions to return image for rss unit
  643. }
  644. /**
  645. * Naming fields in query's body
  646. * @param string $sFieldName name of field
  647. * @param string $sTableName name of field's table
  648. * $param string $sOperator of field's calculation (like MAX)
  649. * @param boolean $bRenameMode indicator for renaming and unsetting fields from field of class $this->aPseud
  650. * return $sqlUnit sql code and unsetting elements from aPseud field
  651. */
  652. function setFieldUnit ($sFieldName, $sTableName, $sOperator = '', $bRenameMode = true)
  653. {
  654. $bOperator = !empty($sOperator);
  655. $sqlUnit = "`$sTableName`.`$sFieldName`";
  656. if($bOperator)
  657. $sqlUnit = $sOperator . '(' . $sqlUnit . ')';
  658. if(!empty($this->aPseud) && $bRenameMode !== false && ($sKey = array_search($sFieldName . ($bOperator ? '_' . strtolower($sOperator) : ''), $this->aPseud)) !== false) {
  659. $sqlUnit .= " as `$sKey`";
  660. unset($this->aPseud[$sKey]);
  661. }
  662. return $sqlUnit . ', ';
  663. }
  664. /**
  665. * Get html code of of every search unit
  666. * @param array $aData array of every search unit
  667. * return html code
  668. */
  669. function displaySearchUnit ($aData)
  670. {
  671. }
  672. /**
  673. * Get html code of search box with search results
  674. * @param string $sCode html code of search results
  675. * $param $sPaginate html code of paginate
  676. * return html code
  677. */
  678. function displaySearchBox ($sCode, $sPaginate = '')
  679. {
  680. }
  681. /**
  682. * Get html code of pagination
  683. */
  684. function showPagination ($bAdmin = false, $bChangePage = true, $bPageReload = true)
  685. {
  686. }
  687. /**
  688. * Get array of data with search results
  689. * return array with data
  690. */
  691. function getSearchData ()
  692. {
  693. /**
  694. * @hooks
  695. * @hookdef hook-simple_search-before_get_data 'simple_search', 'before_get_data' - hook on before after get data
  696. * - $unit_name - equals `simple_search`
  697. * - $action - equals `before_get_data`
  698. * - $object_id - not used
  699. * - $sender_id - not used
  700. * - $extra_params - array of additional params with the following array keys:
  701. * - `object` - [array] by ref, array of parameters, can be overridden in hook processing
  702. * - `mode` - [string] search mode
  703. * @hook @ref hook-simple_search-before_get_data
  704. */
  705. bx_alert('simple_search', 'before_get_data', 0, false, [
  706. 'object' => &$this->aCurrent,
  707. 'object_ref' => &$this->aCurrent,
  708. 'mode' => $this->_sMode
  709. ]);
  710. if(($this->aPseud = $this->_getPseudFromParam()) === false)
  711. $this->aPseud = $this->_getPseud();
  712. $this->setConditionParams();
  713. $aData = $this->aCurrent['paginate']['num'] > 0 ? $this->getSearchDataByParams() : [];
  714. /**
  715. * @hooks
  716. * @hookdef hook-simple_search-get_data 'simple_search', 'get_data' - hook on after get data
  717. * - $unit_name - equals `simple_search`
  718. * - $action - equals `get_data`
  719. * - $object_id - not used
  720. * - $sender_id - not used
  721. * - $extra_params - array of additional params with the following array keys:
  722. * - `object` - [array] by ref, array of parameters, can be overridden in hook processing
  723. * - `mode` - [string] search mode
  724. * - `search_object` - [string] search object name
  725. * @hook @ref hook-simple_search-get_data
  726. */
  727. bx_alert('simple_search', 'get_data', 0, false, [
  728. 'object' => &$this->aCurrent,
  729. 'object_ref' => &$this->aCurrent,
  730. 'mode' => $this->_sMode,
  731. 'search_results' => &$aData,
  732. 'search_results_ref' => &$aData
  733. ]);
  734. return $aData;
  735. }
  736. /**
  737. * Get query [query, limit] for search results. Is used for combined search from different sections.
  738. * @param type $aParams array with params
  739. * @return type array with query and limit
  740. */
  741. function getSearchQuery($sObject, $aParams = [])
  742. {
  743. if(!is_array($aParams))
  744. $aParams = [];
  745. $aParams = array_merge($aParams, ['for_union' => true]);
  746. $this->aPseud = [
  747. 'id' => !empty($this->aCurrent['ident']) ? $this->aCurrent['ident'] : 'id',
  748. 'added' => !empty($this->aCurrent['added']) ? $this->aCurrent['added'] : 'added'
  749. ];
  750. $this->setConditionParams();
  751. $aQuery = $this->getSearchDataByParams($aParams);
  752. /**
  753. * @hooks
  754. * @hookdef hook-simple_search-get_query 'simple_search', 'get_query' - hook on get sql queries
  755. * - $unit_name - equals `simple_search`
  756. * - $action - equals `get_query`
  757. * - $object_id - not used
  758. * - $sender_id - not used
  759. * - $extra_params - array of additional params with the following array keys:
  760. * - `object` - [array] by ref, array of parameters, can be overridden in hook processing
  761. * - `mode` - [string] search mode
  762. * - `search_object` - [string] search object name
  763. * - `search_query` - [array] by ref, array of sql, can be overridden in hook processing
  764. * @hook @ref hook-simple_search-get_query
  765. */
  766. bx_alert('simple_search', 'get_query', 0, false, [
  767. 'object' => &$this->aCurrent,
  768. 'object_ref' => &$this->aCurrent,
  769. 'mode' => $this->_sMode,
  770. 'search_object' => $sObject,
  771. 'search_query' => &$aQuery,
  772. 'search_query_ref' => &$aQuery
  773. ]);
  774. return $aQuery;
  775. }
  776. function getFieldsOwn()
  777. {
  778. return false;
  779. }
  780. function getFieldsJoin($sJoin)
  781. {
  782. return false;
  783. }
  784. /**
  785. * Get array with code for sql elements
  786. * @param $bRenameMode indicator of renmaing fields
  787. * return array with joinFields, ownFields, groupBy and join elements
  788. */
  789. function getJoins ($bRenameMode = true)
  790. {
  791. if(!isset($this->aCurrent['join']) || !is_array($this->aCurrent['join']))
  792. return false;
  793. $aSql = [
  794. 'join' => '',
  795. 'ownFields' => '',
  796. 'joinFields' => '',
  797. 'groupBy' => '',
  798. 'groupHaving' => ''
  799. ];
  800. foreach($this->aCurrent['join'] as $sKey => $aValue) {
  801. $sAlias = isset($aValue['table_alias']) ? $aValue['table_alias'] : $aValue['table'];
  802. $sTableAlias = isset($aValue['table_alias']) ? " AS {$aValue['table_alias']} " : '';
  803. $sOperator = isset($aValue['operator']) ? $aValue['operator'] : null;
  804. // joinFields
  805. $aJoinFields = $this->getFieldsJoin($sKey);
  806. if($aJoinFields === false && !empty($aValue['joinFields']) && is_array($aValue['joinFields']))
  807. $aJoinFields = $aValue['joinFields'];
  808. if($aJoinFields)
  809. foreach($aJoinFields as $mixedField) {
  810. list($sFldName, $sFldOperator) = is_array($mixedField) ? $mixedField : [$mixedField, $sOperator];
  811. $aSql['joinFields'] .= $this->setFieldUnit($sFldName, $sAlias, $sFldOperator, $bRenameMode);
  812. }
  813. // group by
  814. if(isset($aValue['groupTable']))
  815. $aSql['groupBy'] .= "`{$aValue['groupTable']}`.`{$aValue['groupField']}`, ";
  816. // having
  817. if(isset($aValue['groupHaving']))
  818. $aSql['groupHaving'] .= $aValue['groupHaving'];
  819. $sOn = isset($aValue['mainTable']) ? $aValue['mainTable'] : $this->aCurrent['table'];
  820. $aSql['join'] .= " {$aValue['type']} JOIN `{$aValue['table']}` $sTableAlias ON " . (!empty($aValue['on_sql']) ? $aValue['on_sql'] : "`{$sAlias}`.`{$aValue['onField']}`=" . trim($this->setFieldUnit($aValue['mainField'], $sOn, isset($aValue['mainFieldFunc']) ? $aValue['mainFieldFunc'] : '', false), ", "));
  821. $aSql['ownFields'] .= $this->setFieldUnit($aValue['mainField'], $sOn, '', $bRenameMode);
  822. }
  823. $aSql['joinFields'] = trim($aSql['joinFields'], ', ');
  824. if(!empty($aSql['groupBy']))
  825. $aSql['groupBy'] = trim('GROUP BY ' . $aSql['groupBy'], ', ');
  826. if(!empty($aSql['groupHaving']))
  827. $aSql['groupHaving'] = 'HAVING ' . $aSql['groupHaving'];
  828. return $aSql;
  829. }
  830. /**
  831. * Concat sql parts of query, run it and return result array
  832. * @param $aParams addon param
  833. * return $aData multivariate array
  834. */
  835. function getSearchDataByParams ($aParams = '')
  836. {
  837. $bForUnion = isset($aParams['for_union']) && $aParams['for_union'] === true;
  838. $aSql = [
  839. 'ownFields' => '',
  840. 'order' => ''
  841. ];
  842. // searchFields
  843. if($bForUnion) {
  844. $sTable = isset($this->aCurrent['tableSearch']) ? $this->aCurrent['tableSearch'] : $this->aCurrent['table'];
  845. $aSql['ownFields'] .= $this->setFieldUnit(!empty($this->aCurrent['ident']) ? $this->aCurrent['ident'] : 'id', $sTable);
  846. $aSql['ownFields'] .= $this->setFieldUnit(!empty($this->aCurrent['added']) ? $this->aCurrent['added'] : 'added', $sTable);
  847. $aSql['ownFields'] .= "'" . $this->getContentInfoName() . "' AS `content_info`";
  848. }
  849. else {
  850. $aOwnFields = $this->getFieldsOwn();
  851. if($aOwnFields === false)
  852. $aOwnFields = $this->aCurrent['ownFields'];
  853. foreach($aOwnFields as $mixedField) {
  854. list($sFldName, $sFldOperator) = is_array($mixedField) ? $mixedField : [$mixedField, ''];
  855. $aSql['ownFields'] .= $this->setFieldUnit($sFldName, $this->aCurrent['table'], $sFldOperator);
  856. }
  857. }
  858. // joinFields & join
  859. if(($aJoins = $this->getJoins()) !== false) {
  860. if(!$bForUnion) {
  861. $aSql['ownFields'] .= $aJoins['ownFields'];
  862. $aSql['ownFields'] .= $aJoins['joinFields'];
  863. }
  864. $aSql['join'] = $aJoins['join'];
  865. $aSql['groupBy'] = $aJoins['groupBy'];
  866. $aSql['groupHaving'] = $aJoins['groupHaving'];
  867. }
  868. $aSql['ownFields'] = trim($aSql['ownFields'], ', ');
  869. // from
  870. $aSql['from'] = " FROM `{$this->aCurrent['table']}`";
  871. // where
  872. $aSql['where'] = $this->getRestriction();
  873. // limit
  874. $aSql['limit'] = $this->getLimit();
  875. // sorting
  876. $this->setSorting();
  877. $aSort = $this->getSorting($this->aCurrent['sorting']);
  878. foreach ($aSort as $sKey => $sValue)
  879. $aSql[$sKey] .= $sValue;
  880. // execution
  881. $sqlQuery = 'SELECT';
  882. if(isset($this->aCurrent['distinct']) && $this->aCurrent['distinct'] === true)
  883. $sqlQuery .= ' DISTINCT';
  884. $sqlQuery .= ' ' . $aSql['ownFields'];
  885. $sqlQuery .= ' ' . $aSql['from'];
  886. if (isset($aSql['join']))
  887. $sqlQuery .= ' ' . $aSql['join'];
  888. if (isset($aSql['where']))
  889. $sqlQuery .= ' ' . $aSql['where'];
  890. if (isset($aSql['groupBy']))
  891. $sqlQuery .= ' ' . $aSql['groupBy'];
  892. if (isset($aSql['groupHaving']))
  893. $sqlQuery .= ' ' . $aSql['groupHaving'];
  894. if($bForUnion)
  895. return [
  896. 'query' => $sqlQuery,
  897. 'limit' => $aSql['limit']
  898. ];
  899. if (isset($aSql['order']))
  900. $sqlQuery .= ' ' . $aSql['order'];
  901. if (isset($aSql['limit']))
  902. $sqlQuery .= ' ' . $aSql['limit'];
  903. //echoDbg($sqlQuery);
  904. $aRes = BxDolDb::getInstance()->getAll($sqlQuery);
  905. return $aRes;
  906. }
  907. /**
  908. * Set class fields condition params and paginate array
  909. */
  910. function setConditionParams()
  911. {
  912. $this->aCurrent['paginate']['num'] = 0;
  913. // keyword
  914. $sKeyword = bx_process_input(isset($this->_aCustomSearchCondition['keyword']) ? $this->_aCustomSearchCondition['keyword'] : bx_get('keyword'));
  915. $bKeyword = !empty($sKeyword);
  916. if ($this->_bLiveSearch && !$bKeyword)
  917. return;
  918. if ($bKeyword) {
  919. if (substr($sKeyword, 0, 1) == '@') {
  920. $sModule = $this->aCurrent['module_name'];
  921. $sMethod = 'act_as_profile';
  922. if(!bx_is_srv($sModule, $sMethod) || !bx_srv($sModule, $sMethod))
  923. return;
  924. $sKeyword = substr($sKeyword, 1);
  925. }
  926. $this->aCurrent['restriction']['keyword'] = array(
  927. 'value' => $sKeyword,
  928. 'field' => '',
  929. 'operator' => 'against'
  930. );
  931. // for search results we need to show all items, not only public content
  932. $this->setProcessPrivateContent(true);
  933. }
  934. // owner
  935. if (isset($_GET['ownerName'])) {
  936. $sName = bx_process_input($_GET['ownerName']);
  937. $iUser = (int)BxDolProfileQuery::getInstance()->getIdByNickname($sName);
  938. BxDolMenu::getInstance()->setCurrentProfileID($iUser);
  939. } elseif (isset($_GET['userID']))
  940. $iUser = bx_process_input($_GET['userID'], BX_DATA_INT);
  941. if (!empty($iUser))
  942. $this->aCurrent['restriction']['owner']['value'] = $iUser;
  943. // meta info
  944. if ($this->_sMetaType && !empty($this->aCurrent['object_metatags'])) {
  945. $o = BxDolMetatags::getObjectInstance($this->aCurrent['object_metatags']);
  946. if ($o) {
  947. unset($this->aCurrent['restriction']['keyword']);
  948. $aLocationString = [];
  949. switch ($this->_sMetaType) {
  950. case 'location_country':
  951. $aLocationString['country'] = $sKeyword;
  952. $o->locationsSetSearchCondition($this, $sKeyword);
  953. break;
  954. case 'location_country_state':
  955. $aLocationString['country'] = $sKeyword;
  956. $aLocationString['state'] = bx_process_input(isset($this->_aCustomSearchCondition['state']) ? $this->_aCustomSearchCondition['state'] : bx_get('state'));
  957. $o->locationsSetSearchCondition($this, $sKeyword, $aLocationString['state']);
  958. break;
  959. case 'location_country_city':
  960. $aLocationString['country'] = $sKeyword;
  961. $aLocationString['state'] = bx_process_input(isset($this->_aCustomSearchCondition['state']) ? $this->_aCustomSearchCondition['state'] : bx_get('state'));
  962. $aLocationString['city'] = bx_process_input(isset($this->_aCustomSearchCondition['city']) ? $this->_aCustomSearchCondition['city'] : bx_get('city'));
  963. $o->locationsSetSearchCondition($this, $sKeyword, $aLocationString['state'], $aLocationString['city']);
  964. break;
  965. case 'location_state':
  966. $aLocationString['state'] = $sKeyword;
  967. $o->locationsSetSearchCondition($this, false, $sKeyword);
  968. break;
  969. case 'location_city':
  970. $aLocationString['city'] = $sKeyword;
  971. $o->locationsSetSearchCondition($this, false, false, $sKeyword);
  972. break;
  973. case 'mention':
  974. $oCmts = !empty($this->sModuleObjectComments) ? BxDolCmts::getObjectInstance($this->sModuleObjectComments, 0, false) : false;
  975. $o->mentionsSetSearchCondition($this, $sKeyword, $oCmts ? $oCmts->getSystemId() : 0);
  976. if(($oProfile = BxDolProfile::getInstance((int)$sKeyword)) !== false)
  977. $this->_setPageDescription('_sys_page_description_mention', $oProfile->getDisplayName(), $this->aCurrent['title']);
  978. break;
  979. case 'keyword':
  980. $oCmts = !empty($this->sModuleObjectComments) ? BxDolCmts::getObjectInstance($this->sModuleObjectComments, 0, false) : false;
  981. $o->keywordsSetSearchCondition($this, $sKeyword, $oCmts ? $oCmts->getSystemId() : 0);
  982. $this->_setPageDescription('_sys_page_description_hashtag', $sKeyword, $this->aCurrent['title']);
  983. break;
  984. }
  985. if(in_array($this->_sMetaType, ['location_country', 'location_country_state', 'location_country_city', 'location_state', 'location_city']))
  986. $this->_setPageDescription('_sys_page_description_location', $o->locationsStringFromArray($aLocationString, false), $this->aCurrent['title']);
  987. }
  988. }
  989. // category
  990. if ($this->_sCategoryObject) {
  991. if(($o = BxDolCategory::getObjectInstance($this->_sCategoryObject)) && $this->_bSingleSearch) {
  992. if ($this->aCurrent['name'] == $o->getSearchObject()) {
  993. unset($this->aCurrent['restriction']['keyword']);
  994. $o->setSearchCondition($this, $sKeyword);
  995. }
  996. $this->_setPageDescription('_sys_page_description_category', $o->getCategoryTitle($sKeyword), $this->aCurrent['title']);
  997. }
  998. if ($this->_sCategoryObject == 'multi'){
  999. unset($this->aCurrent['restriction']['keyword']);
  1000. $this->setCategoriesCondition($sKeyword);
  1001. }
  1002. }
  1003. if($bKeyword && !$this->_sMetaType && !$this->_sCategoryObject)
  1004. $this->_setPageDescription('_sys_page_description_keyword', $sKeyword, $this->aCurrent['title']);
  1005. $this->setPaginate();
  1006. $iNum = $this->getNum();
  1007. if ($iNum > 0)
  1008. $this->aCurrent['paginate']['num'] = $iNum;
  1009. }
  1010. /**
  1011. * Check number of records on current page
  1012. * return number of records on current page + 1
  1013. */
  1014. function getNum ()
  1015. {
  1016. $aJoins = $this->getJoins(false);
  1017. $sqlQuery = "SELECT * FROM `{$this->aCurrent['table']}` " . (isset($aJoins['join']) ? ' ' . $aJoins['join'] : '' ) . $this->getRestriction() . (isset($aJoins['groupBy']) ? ' ' . $aJoins['groupBy'] : '') . ' ' . $this->getLimit(true);
  1018. return count(BxDolDb::getInstance()->getAll($sqlQuery));
  1019. }
  1020. /**
  1021. * Get total number of records
  1022. * return total number of records
  1023. */
  1024. function getTotal ()
  1025. {
  1026. $aJoins = $this->getJoins(false);
  1027. $sqlQuery = "SELECT COUNT(*) FROM `{$this->aCurrent['table']}` " . (isset($aJoins['join']) ? ' ' . $aJoins['join'] : '' ) . $this->getRestriction() . (isset($aJoins['groupBy']) ? ' ' . $aJoins['groupBy'] : '');
  1028. return BxDolDb::getInstance()->getOne($sqlQuery);
  1029. }
  1030. /**
  1031. * Check restriction params and make condition part of query
  1032. * return $sqlWhere sql code of query for WHERE part
  1033. */
  1034. function getRestriction ()
  1035. {
  1036. $oDb = BxDolDb::getInstance();
  1037. $sqlWhere = '';
  1038. if (isset($this->aCurrent['restriction'])) {
  1039. $aWhere[] = '1';
  1040. foreach ($this->aCurrent['restriction'] as $sKey => $aValue) {
  1041. $sqlCondition = '';
  1042. if (isset($aValue['operator']) && isset($aValue['value']) && $aValue['value'] !== '' && $aValue['value'] !== false && $aValue['value'] !== null) {
  1043. $sFieldTable = isset($aValue['table']) ? $aValue['table'] : $this->aCurrent['table'];
  1044. $sqlCondition = "`{$sFieldTable}`.`{$aValue['field']}` ";
  1045. switch ($aValue['operator']) {
  1046. case 'empty value':
  1047. $sqlCondition .= " = '' ";
  1048. break;
  1049. case 'not empty value':
  1050. $sqlCondition .= " != '' ";
  1051. break;
  1052. case 'nothing':
  1053. $sqlCondition = " 0 ";
  1054. break;
  1055. case 'against':
  1056. $aCond = isset($aValue['field']) && strlen($aValue['field']) > 0 ? $aValue['field'] : $this->aCurrent['searchFields'];
  1057. $sqlCondition = !empty($aCond) ? $this->getSearchFieldsCond($aCond, $aValue['value']) : "";
  1058. break;
  1059. case 'like':
  1060. $sqlCondition .= "LIKE " . $oDb->escape('%' . $aValue['value'] . '%');
  1061. break;
  1062. case 'in':
  1063. case 'not in':
  1064. $sValuesString = $this->getMultiValues($aValue['value']);
  1065. $sqlCondition .= strtoupper($aValue['operator']) . '(' . $sValuesString . ')';
  1066. break;
  1067. case 'in_set':
  1068. $sqlCondition = "1 << (" . $sqlCondition . " - 1) & " . (int)$aValue['value'];
  1069. break;
  1070. default:
  1071. $sqlCondition .= $aValue['operator'] . (isset($aValue['no_quote_value']) && $aValue['no_quote_value'] ? $aValue['value'] : $oDb->escape($aValue['value']));
  1072. break;
  1073. }
  1074. }
  1075. if (strlen($sqlCondition) > 0)
  1076. $aWhere[] = $sqlCondition;
  1077. }
  1078. $sqlWhere .= "WHERE ". implode(' AND ', $aWhere) . (isset($this->aCurrent['restriction_sql']) ? $this->aCurrent['restriction_sql'] : '');
  1079. }
  1080. return $sqlWhere;
  1081. }
  1082. /**
  1083. * Get limit part of query
  1084. * return $sqlFrom code for limit part pf query
  1085. */
  1086. function getLimit ($isAddPlusOne = false)
  1087. {
  1088. if (!isset($this->aCurrent['paginate']))
  1089. return;
  1090. $sqlFrom = (int)$this->aCurrent['paginate']['start'] > 0 ? (int)$this->aCurrent['paginate']['start'] : 0;
  1091. $sqlTo = $this->aCurrent['paginate']['perPage'] + ($isAddPlusOne ? 1 : 0);
  1092. if ($sqlTo > 0)
  1093. return 'LIMIT ' . $sqlFrom . ', ' . $sqlTo;
  1094. }
  1095. /**
  1096. * Set sorting field of class
  1097. */
  1098. function setSorting ()
  1099. {
  1100. $this->aCurrent['sorting'] = isset($_GET[$this->aCurrent['name'] . '_mode']) ? $_GET[$this->aCurrent['name'] . '_mode'] : $this->aCurrent['sorting'];
  1101. }
  1102. /**
  1103. * Get sorting part of query according current sorting mode
  1104. * @param string $sSortType sorting type
  1105. * return array with sql elements order and ownFields
  1106. */
  1107. function getSorting ($sSortType = 'last')
  1108. {
  1109. if (isset($this->aCurrent['sorting_sql']))
  1110. return array('order' => $this->aCurrent['sorting_sql']);
  1111. $aOverride = $this->getAlterOrder();
  1112. if (is_array($aOverride) && !empty($aOverride))
  1113. return $aOverride;
  1114. $aSql = array();
  1115. switch ($sSortType) {
  1116. case 'rand':
  1117. $aSql['order'] = "ORDER BY RAND()";
  1118. break;
  1119. case 'score':
  1120. if (is_array($this->aCurrent['restriction']['keyword'])) {
  1121. $sPseud = '';
  1122. if ('on' == getParam('useLikeOperator')) {
  1123. $aSql['order'] = "ORDER BY `score` DESC";
  1124. $sPseud = 'score';
  1125. }
  1126. $aSql['ownFields'] .= $this->getSearchFieldsCond($this->aCurrent['searchFields'], $this->aCurrent['restriction']['keyword']['value'], $sPseud) . ',';
  1127. }
  1128. break;
  1129. case 'none':
  1130. $aSql['order'] = "";
  1131. break;
  1132. default:
  1133. $aSql['order'] = "ORDER BY `date` DESC";
  1134. }
  1135. return $aSql;
  1136. }
  1137. /**
  1138. * Return own varaint for sorting (redeclare if necessary)
  1139. * return array of sql elements
  1140. */
  1141. function getAlterOrder ()
  1142. {
  1143. return array();
  1144. }
  1145. /**
  1146. * Set paginate fields of class according GET params 'start' and 'per_page'
  1147. * forcePage is need for setting most important number of current page
  1148. */
  1149. function setPaginate ()
  1150. {
  1151. $iStart = 0;
  1152. $iPerPage = 0;
  1153. //--- Check in aCurrent (low priority).
  1154. if(isset($this->aCurrent['paginate']['perPage']) && (int)$this->aCurrent['paginate']['perPage'] != 0)
  1155. $iPerPage = (int)$this->aCurrent['paginate']['perPage'];
  1156. //--- Check in aParams (middle priority).
  1157. if(isset($this->_aParams['per_page']) && (int)$this->_aParams['per_page'] != 0)
  1158. $iPerPage = (int)$this->_aParams['per_page'];
  1159. //--- Check in GET params (high priority).
  1160. if(isset($_GET['per_page']) && (int)$_GET['per_page'] != 0)
  1161. $iPerPage = (int)$_GET['per_page'];
  1162. //--- Trying to get from System settings.
  1163. if (empty($iPerPage))
  1164. $iPerPage = (int)getParam('sys_per_page_search_keyword_' . ($this->_bSingleSearch ? 'single' : 'plural'));
  1165. //--- Use default value in case of emergency.
  1166. if (empty($iPerPage))
  1167. $iPerPage = BX_DOL_SEARCH_RESULTS_PER_PAGE_DEFAULT;
  1168. if ($this->iPaginatePerPage != BX_DOL_SEARCH_RESULTS_PER_PAGE_DEFAULT)
  1169. $iPerPage = $this->iPaginatePerPage;
  1170. $this->aCurrent['paginate']['perPage'] = $iPerPage;
  1171. if(!isset($this->aCurrent['paginate']['forceStart'])) {
  1172. if(isset($this->_aParams['start']))
  1173. $iStart = (int)$this->_aParams['start'];
  1174. if(($iStartGet = bx_get('start')) !== false)
  1175. $iStart = (int)$iStartGet;
  1176. }
  1177. else
  1178. $iStart = (int)$this->aCurrent['paginate']['forceStart'];
  1179. if($iStart < 0)
  1180. $iStart = 0;
  1181. $this->aCurrent['paginate']['start'] = $iStart;
  1182. }
  1183. function unsetPaginate()
  1184. {
  1185. unset($this->aCurrent['paginate']);
  1186. }
  1187. /**
  1188. * Get sql where condition for search fields
  1189. * @param array of search fields
  1190. * @param string $sKeyword keyword value for search
  1191. * @param string sPseud for setting new name for generated set of fields in query
  1192. * return sql code of WHERE part in query
  1193. */
  1194. function getSearchFieldsCond ($aFields, $sKeyword, $sPseud = '')
  1195. {
  1196. if (!$sKeyword)
  1197. return '';
  1198. $sTable = empty($this->aCurrent['tableSearch']) ? $this->aCurrent['table'] : $this->aCurrent['tableSearch'];
  1199. $oDb = BxDolDb::getInstance();
  1200. $bLike = getParam('useLikeOperator');
  1201. if (!is_array($aFields))
  1202. $aFields = array($aFields);
  1203. if ($bLike == 'on') {
  1204. $sKeyword = $oDb->escape('%' . preg_replace('/\s+/', '%', $sKeyword) . '%');
  1205. $sSqlWhere = '';
  1206. foreach ($aFields as $sValue)
  1207. $sSqlWhere .= "`{$sTable}`.`$sValue` LIKE " . $sKeyword . " OR ";
  1208. $sSqlWhere = '(' . trim($sSqlWhere, 'OR ') . ')';
  1209. } else {
  1210. $sKeyword = $oDb->escape($sKeyword);
  1211. $sSqlWhere = '';
  1212. foreach ($aFields as $sValue)
  1213. $sSqlWhere .= "`{$sTable}`.`$sValue`, ";
  1214. $sSqlWhere = trim($sSqlWhere, ', ');
  1215. $sSqlWhere = " MATCH({$sSqlWhere}) AGAINST (" . $sKeyword . ") ";
  1216. if (!empty($sPseud))
  1217. $sSqlWhere .= " AS `$sPseud` ";
  1218. }
  1219. return $sSqlWhere;
  1220. }
  1221. /**
  1222. * Get set from several values for 'in' and 'not in' operators
  1223. * @param $aValues array of values
  1224. * return sql code for field with operator IN (NOT IN)
  1225. */
  1226. function getMultiValues ($aValues)
  1227. {
  1228. $oDb = BxDolDb::getInstance();
  1229. return $oDb->implode_escape($aValues);
  1230. }
  1231. /**
  1232. * System method for filling aPseud array. Fill field aPseud for current class from system option.
  1233. * It may be useful when Fields are taken from system option too.
  1234. */
  1235. function _getPseudFromParam ()
  1236. {
  1237. return false;
  1238. }
  1239. /**
  1240. * System method for filling aPseud array.
  1241. * Fill field aPseud for current class (if you will use own getSearchUnit methods then not necessary to redeclare).
  1242. */
  1243. function _getPseud ()
  1244. {
  1245. }
  1246. /**
  1247. * Add replace markers. Markers are replaced in titles and browse urls
  1248. * @param $a array of markers as key => value
  1249. * @return true on success or false on error
  1250. */
  1251. public function addMarkers ($a)
  1252. {
  1253. if (empty($a) || !is_array($a))
  1254. return false;
  1255. $this->_aMarkers = array_merge ($this->_aMarkers, $a);
  1256. return true;
  1257. }
  1258. /**
  1259. * Replace provided markers in a string
  1260. * @param $mixed string or array to replace markers in
  1261. * @return string where all occured markers are replaced
  1262. */
  1263. protected function _replaceMarkers ($mixed)
  1264. {
  1265. return bx_replace_markers($mixed, $this->_aMarkers);
  1266. }
  1267. protected function _setPageDescription()
  1268. {
  1269. $aArgs = func_get_args();
  1270. if($this->_bSingleSearch)
  1271. $aArgs[0] .= '_in_section';
  1272. BxDolTemplate::getInstance()->setPageDescription(call_user_func_array('_t', $aArgs));
  1273. }
  1274. }
  1275. /** @} */