BxDolSearch.php 49 KB

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