BxDolSearch.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  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 $aClasses = array(); ///< array of all search classes
  39. protected $aChoice = array(); ///< array of current search classes which were choosen in search area
  40. protected $_bLiveSearch = false;
  41. protected $_sMetaType = '';
  42. protected $_sCategoryObject = '';
  43. /**
  44. * Constructor
  45. * @param array $aChoice - array of choosen classes (will take a part only existing in `sys_objects_search` table)
  46. */
  47. public function __construct ($aChoice = '')
  48. {
  49. parent::__construct();
  50. $this->aClasses = BxDolDb::getInstance()->fromCache('sys_objects_search', 'getAllWithKey',
  51. 'SELECT `ID` as `id`,
  52. `Title` as `title`,
  53. `ClassName` as `class`,
  54. `ClassPath` as `file`,
  55. `ObjectName`,
  56. `GlobalSearch`
  57. FROM `sys_objects_search`
  58. ORDER BY `Order` ASC', 'ObjectName'
  59. );
  60. if (is_array($aChoice) && !empty($aChoice)) {
  61. foreach ($aChoice as $sValue) {
  62. if (isset($this->aClasses[$sValue]))
  63. $this->aChoice[$sValue] = $this->aClasses[$sValue];
  64. }
  65. } else {
  66. $this->aChoice = $this->aClasses;
  67. }
  68. }
  69. /**
  70. * create units for all classes and calling their processing methods
  71. */
  72. public function response ()
  73. {
  74. $sCode = '';
  75. $bSingle = count($this->aChoice) == 1;
  76. foreach ($this->aChoice as $sKey => $aValue) {
  77. if (!$this->_sMetaType && !$aValue['GlobalSearch'])
  78. continue;
  79. $sClassName = 'BxTemplSearchResult';
  80. if(!empty($aValue['class'])) {
  81. $sClassName = $aValue['class'];
  82. if(!empty($aValue['file']))
  83. require_once(BX_DIRECTORY_PATH_ROOT . $aValue['file']);
  84. }
  85. $oEx = new $sClassName();
  86. if ($this->_sMetaType && !$oEx->isMetaEnabled($this->_sMetaType))
  87. continue;
  88. $oEx->setId($aValue['id']);
  89. $oEx->setLiveSearch($this->_bLiveSearch);
  90. $oEx->setMetaType($this->_sMetaType);
  91. $oEx->setCategoryObject($this->_sCategoryObject);
  92. $oEx->setCenterContentUnitSelector(false);
  93. $oEx->setSingleSearch($bSingle);
  94. $sCode .= $oEx->processing();
  95. }
  96. return $sCode;
  97. }
  98. public function getEmptyResult ()
  99. {
  100. $sKey = _t('_Empty');
  101. return DesignBoxContent($sKey, MsgBox($sKey), 1);
  102. }
  103. protected function getKeyTitlesPairs ()
  104. {
  105. $a = array();
  106. foreach ($this->aChoice as $sKey => $r)
  107. if ($this->_sMetaType || $r['GlobalSearch'])
  108. $a[$sKey] = _t($r['title']);
  109. return $a;
  110. }
  111. public function setLiveSearch($bLiveSearch)
  112. {
  113. $this->_bLiveSearch = $bLiveSearch;
  114. }
  115. public function setMetaType($s)
  116. {
  117. $aMetaTypes = array('location_country', 'location_country_city', 'location_country_state', 'mention', 'keyword');
  118. if (in_array($s, $aMetaTypes))
  119. $this->_sMetaType = $s;
  120. }
  121. public function setCategoryObject($s)
  122. {
  123. $this->_sCategoryObject = $s;
  124. }
  125. }
  126. /*
  127. * Search class for processing search requests and displaying search results.
  128. *
  129. * Allows present content from modules on search params or internal (via fields of class) conditions.
  130. *
  131. * Example of usage (you can see example in any of default Dolhpin's modules):
  132. *
  133. * 1. Extends your own search class from this one (or from BxBaseSearchResult or BxBaseSearchResultSharedMedia classes)
  134. * 2. Set necessary fields of class (using as example BxFilesSearch):
  135. *
  136. * @code
  137. *
  138. * // main field of search class
  139. * $this->aCurrent = array(
  140. *
  141. * // name of module
  142. * 'name' => 'bx_files',
  143. *
  144. * // language key with name of module
  145. * 'title' => '_bx_files',
  146. *
  147. * // main content table
  148. * 'table' => 'bx_files_main',
  149. *
  150. * // array of all fields which can be choosen for select in result query
  151. * 'ownFields' => array('ID', 'Title', 'Uri', 'Desc', 'Date', 'Size', 'Ext', 'Views', 'Rate', 'RateCount', 'Type'),
  152. *
  153. * // array of fields which take a part in search by keyword (global search and related words only - in other cases leave it blank)
  154. * 'searchFields' => array('Title', 'Tags', 'Desc', 'Categories'),
  155. *
  156. * // array of join tables
  157. * // 'type' - type of join
  158. * // 'table' - join table
  159. * // 'mainField' - field from main table for 'on' condition
  160. * // 'onField' - field from joining table for 'on' condition
  161. * // 'joinFields' - array of fields from joining table
  162. *
  163. * 'join' => array(
  164. * 'profile' => array(
  165. * 'type' => 'left',
  166. * 'table' => 'Profiles',
  167. * 'mainField' => 'Owner',
  168. * 'onField' => 'ID',
  169. * 'joinFields' => array('NickName'),
  170. * ),
  171. * // ...
  172. * ),
  173. *
  174. * // array of search parameters
  175. * // 'value' - value of search parameter (can be number, string or array)
  176. * // '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
  177. * // 'operator' - operator between field and value (can be 'in', 'not in', '>', '<', 'against', 'like' and '=' by default),
  178. * // 'paramName' - GET param which will keep 'value' for pagianation
  179. *
  180. * 'restriction' => array(
  181. * 'activeStatus' => array('value'=>'approved', 'field'=>'Status', 'operator'=>'=', 'paramName' => 'status'),
  182. * 'albumType' => array('value'=>'', 'field'=>'Type', 'operator'=>'=', 'paramName'=>'albumType', 'table'=>'sys_albums'),
  183. * ),
  184. *
  185. * // array of pagination
  186. * // 'perPage' - units per page
  187. * // 'start' - show search results starting from this number
  188. * // 'num' - number of element to show on current page + 1
  189. *
  190. * 'paginate' => array('perPage' => 10, 'start' => 0, 'num' => 11),
  191. *
  192. * // sort mode - by default it was last (DESC by date)
  193. * 'sorting' => 'last',
  194. *
  195. * // mode of units presentation in search result, can be 'short' or 'full' view
  196. * 'view' => 'full',
  197. *
  198. * // field of id
  199. * 'ident' => 'ID',
  200. *
  201. * // rss feed array
  202. * 'rss' => array(
  203. * 'title' => '',
  204. * 'link' => '',
  205. * 'image' => '',
  206. * 'profile' => 0,
  207. * 'fields' => array (
  208. * 'Link' => '',
  209. * 'Title' => 'Title',
  210. * 'DateTimeUTS' => 'Date',
  211. * 'Desc' => 'Desc',
  212. * 'Photo' => '',
  213. * ),
  214. * ),
  215. * );
  216. *
  217. * // array of fields renamings
  218. * $aPseud - filling in costructor by function _getPseud
  219. *
  220. * // unique identificator from `sys_objects_search` table
  221. * $id;
  222. *
  223. * @endcode
  224. *
  225. * Memberships/ACL:
  226. * Doesn't depend on user's membership.
  227. *
  228. * Alerts:
  229. * no alerts available
  230. *
  231. */
  232. class BxDolSearchResult implements iBxDolReplaceable
  233. {
  234. public $aCurrent; ///< search results configuration
  235. protected $aPseud; ///< array of fields renamings
  236. protected $id; ///< unique identificator of block on mixed search results page
  237. protected $bDisplayEmptyMsg = false; ///< display empty message instead of nothing, when no results
  238. protected $sDisplayEmptyMsgKey = ''; ///< custom empty message language key, instead of default "empty" message
  239. protected $bProcessPrivateContent = true; ///< check each item for privacy, if view isn't allowed then display private view instead
  240. protected $bForceAjaxPaginate = false; ///< force ajax paginate
  241. protected $iPaginatePerPage = BX_DOL_SEARCH_RESULTS_PER_PAGE_DEFAULT; ///< default 'per page' value for paginate.
  242. protected $_bSingleSearch = true;
  243. protected $_bLiveSearch = false;
  244. protected $_sMetaType = '';
  245. protected $_sCategoryObject = '';
  246. protected $_aMarkers = array (); ///< markers to replace somewhere, usually title and browse url (defined in custom class)
  247. /**
  248. * constructor
  249. * filling identificator field
  250. */
  251. function __construct ()
  252. {
  253. if (isset($this->aPseud['id']))
  254. $this->aCurrent['ident'] = $this->aPseud['id'];
  255. }
  256. public function getId()
  257. {
  258. return $this->id;
  259. }
  260. public function setId($sId)
  261. {
  262. $this->id = $sId;
  263. }
  264. public function setAjaxPaginate($b = true)
  265. {
  266. $this->bForceAjaxPaginate = $b;
  267. }
  268. public function setPaginatePerPage($iPerPage)
  269. {
  270. $this->iPaginatePerPage = $iPerPage;
  271. }
  272. public function setSingleSearch($bSingleSearch)
  273. {
  274. $this->_bSingleSearch = $bSingleSearch;
  275. }
  276. public function setLiveSearch($bLiveSearch)
  277. {
  278. $this->_bLiveSearch = $bLiveSearch;
  279. }
  280. public function setMetaType($s)
  281. {
  282. $this->_sMetaType = $s;
  283. }
  284. public function isMetaEnabled($s)
  285. {
  286. if (empty($this->aCurrent['object_metatags']))
  287. return false;
  288. if (!($o = BxDolMetatags::getObjectInstance($this->aCurrent['object_metatags'])))
  289. return false;
  290. switch ($s) {
  291. case 'location_country_city':
  292. case 'location_country_state':
  293. case 'location_country':
  294. return $o->locationsIsEnabled();
  295. case 'mention':
  296. return $o->mentionsIsEnabled();
  297. case 'keyword':
  298. return $o->keywordsIsEnabled();
  299. }
  300. return false;
  301. }
  302. public function setCategoryObject($s)
  303. {
  304. $this->_sCategoryObject = $s;
  305. }
  306. /**
  307. * Display empty message if there is no content, custom empty message can be used.
  308. * @param $b - boolan value to enable or disable 'empty' message
  309. * @param $sLangKey [optional] - custom 'empty' message
  310. */
  311. public function setDisplayEmptyMsg($b, $sLangKey = '')
  312. {
  313. $this->bDisplayEmptyMsg = $b;
  314. if ($sLangKey)
  315. $this->sDisplayEmptyMsgKey = $sLangKey;
  316. }
  317. /**
  318. * Perform privacy checking for every unit
  319. * @param $b - boolan value to enable or disable privacy checking
  320. */
  321. public function setProcessPrivateContent ($b)
  322. {
  323. $this->bProcessPrivateContent = $b;
  324. }
  325. /**
  326. * Get html box of search results (usually used in grlobal search)
  327. * @return html code
  328. */
  329. function processing ()
  330. {
  331. $sCode = $this->displayResultBlock();
  332. if ($this->aCurrent['paginate']['num'] > 0) {
  333. $sPaginate = $this->showPagination();
  334. $sCode = $this->displaySearchBox($sCode, $sPaginate);
  335. } else {
  336. $sCode = $this->bDisplayEmptyMsg ? $this->displaySearchBox(MsgBox(_t($this->sDisplayEmptyMsgKey ? $this->sDisplayEmptyMsgKey : '_Empty'))) : '';
  337. }
  338. return $sCode;
  339. }
  340. /**
  341. * Get html output of search result
  342. * @return html code
  343. */
  344. function displayResultBlock ()
  345. {
  346. $aData = $this->getSearchData();
  347. if (count($aData) > 0) {
  348. $sCode .= $this->addCustomParts();
  349. foreach ($aData as $iKey => $aValue) {
  350. $sCode .= $this->displaySearchUnit($aValue);
  351. }
  352. }
  353. return $sCode;
  354. }
  355. /**
  356. * Add different code before html output (usually redeclared)
  357. * no return result
  358. */
  359. function addCustomParts ()
  360. {
  361. }
  362. /**
  363. * Get XML string for rss output
  364. */
  365. function rss ()
  366. {
  367. if (!isset($this->aCurrent['rss']['fields']) || !isset($this->aCurrent['rss']['link']))
  368. return '';
  369. $aData = $this->getSearchData();
  370. $f = &$this->aCurrent['rss']['fields'];
  371. if ($aData) {
  372. foreach ($aData as $k => $a)
  373. $aData[$k][$f['Link']] = $this->getRssUnitLink ($a);
  374. }
  375. $oRss = new BxDolRssFactory ();
  376. return $oRss->GenRssByCustomData(
  377. $aData,
  378. isset($this->aCurrent['rss']['title']) && $this->aCurrent['rss']['title'] ? $this->aCurrent['rss']['title'] : $this->aCurrent['title'],
  379. $this->aCurrent['rss']['link'],
  380. $this->aCurrent['rss']['fields'],
  381. isset($this->aCurrent['rss']['image']) ? $this->aCurrent['rss']['image'] : '',
  382. isset($this->aCurrent['rss']['profile']) ? $this->aCurrent['rss']['profile'] : 0
  383. );
  384. }
  385. /**
  386. * Output RSS XML with XML header
  387. */
  388. function outputRSS ()
  389. {
  390. header('Content-Type: text/xml; charset=UTF-8');
  391. echo $this->rss();
  392. }
  393. /**
  394. * Return rss unit link (redeclared)
  395. */
  396. function getRssUnitLink (&$a)
  397. {
  398. // override this functions to return permalink to rss unit
  399. }
  400. /**
  401. * Naming fields in query's body
  402. * @param string $sFieldName name of field
  403. * @param string $sTableName name of field's table
  404. * $param string $sOperator of field's calculation (like MAX)
  405. * @param boolean $bRenameMode indicator for renaming and unsetting fields from field of class $this->aPseud
  406. * return $sqlUnit sql code and unsetting elements from aPseud field
  407. */
  408. function setFieldUnit ($sFieldName, $sTableName, $sOperator = '', $bRenameMode = true)
  409. {
  410. if (!empty($sOperator))
  411. $sqlUnit = "$sOperator(`$sTableName`.`$sFieldName`)";
  412. else
  413. $sqlUnit = "`$sTableName`.`$sFieldName`";
  414. if (isset($this->aPseud) && $bRenameMode !== false) {
  415. $sKey = array_search($sFieldName, $this->aPseud);
  416. if ($sKey !== false) {
  417. $sqlUnit .= " as `$sKey`";
  418. unset($this->aPseud[$sKey]);
  419. }
  420. }
  421. return $sqlUnit . ', ';
  422. }
  423. /**
  424. * Get html code of of every search unit
  425. * @param array $aData array of every search unit
  426. * return html code
  427. */
  428. function displaySearchUnit ($aData)
  429. {
  430. }
  431. /**
  432. * Get html code of search box with search results
  433. * @param string $sCode html code of search results
  434. * $param $sPaginate html code of paginate
  435. * return html code
  436. */
  437. function displaySearchBox ($sCode, $sPaginate = '')
  438. {
  439. }
  440. /**
  441. * Get html code of pagination
  442. */
  443. function showPagination ($bAdmin = false, $bChangePage = true, $bPageReload = true)
  444. {
  445. }
  446. /**
  447. * Get array of data with search results
  448. * return array with data
  449. */
  450. function getSearchData ()
  451. {
  452. $this->aPseud = $this->_getPseud();
  453. $this->setConditionParams();
  454. if ($this->aCurrent['paginate']['num'] > 0) {
  455. $aData = $this->getSearchDataByParams();
  456. return $aData;
  457. }
  458. return array();
  459. }
  460. /**
  461. * Get array with code for sql elements
  462. * @param $bRenameMode indicator of renmaing fields
  463. * return array with joinFields, ownFields, groupBy and join elements
  464. */
  465. function getJoins ($bRenameMode = true)
  466. {
  467. $aSql = array();
  468. // joinFields & join
  469. if (isset($this->aCurrent['join']) && is_array($this->aCurrent['join'])) {
  470. $aSql = array('join'=>'', 'ownFields'=>'', 'joinFields'=>'', 'groupBy'=>'');
  471. foreach ($this->aCurrent['join'] as $sKey => $aValue) {
  472. $sAlias = isset($aValue['table_alias']) ? $aValue['table_alias'] : $aValue['table'];
  473. $sTableAlias = isset($aValue['table_alias']) ? " AS {$aValue['table_alias']} " : '';
  474. if (is_array($aValue['joinFields'])) {
  475. foreach ($aValue['joinFields'] as $sValue) {
  476. $aSql['joinFields'] .= $this->setFieldUnit($sValue, $sAlias, isset($aValue['operator']) ? $aValue['operator'] : null, $bRenameMode);
  477. }
  478. }
  479. // group by
  480. if (isset($aValue['groupTable']))
  481. $aSql['groupBy'] = "GROUP BY `{$aValue['groupTable']}`.`{$aValue['groupField']}`, ";
  482. $sOn = isset($aValue['mainTable']) ? $aValue['mainTable'] : $this->aCurrent['table'];
  483. $aSql['join'] .= " {$aValue['type']} JOIN `{$aValue['table']}` $sTableAlias ON `{$sAlias}`.`{$aValue['onField']}`=`$sOn`.`{$aValue['mainField']}`";
  484. $aSql['ownFields'] .= $this->setFieldUnit($aValue['mainField'], $sOn, '', $bRenameMode);
  485. }
  486. $aSql['joinFields'] = trim($aSql['joinFields'], ', ');
  487. $aSql['groupBy'] = trim($aSql['groupBy'], ', ');
  488. }
  489. return $aSql;
  490. }
  491. /**
  492. * Concat sql parts of query, run it and return result array
  493. * @param $aParams addon param
  494. * return $aData multivariate array
  495. */
  496. function getSearchDataByParams ($aParams = '')
  497. {
  498. $aSql = array('ownFields'=>'', 'joinFields'=>'', 'order'=>'');
  499. // searchFields
  500. foreach ($this->aCurrent['ownFields'] as $sValue)
  501. $aSql['ownFields'] .= $this->setFieldUnit($sValue, $this->aCurrent['table']);
  502. // joinFields & join
  503. $aJoins = $this->getJoins();
  504. if (!empty($aJoins)) {
  505. $aSql['ownFields'] .= $aJoins['ownFields'];
  506. $aSql['ownFields'] .= $aJoins['joinFields'];
  507. $aSql['join'] = $aJoins['join'];
  508. $aSql['groupBy'] = $aJoins['groupBy'];
  509. }
  510. $aSql['ownFields'] = trim($aSql['ownFields'], ', ');
  511. // from
  512. $aSql['from'] = " FROM `{$this->aCurrent['table']}`";
  513. // where
  514. $aSql['where'] = $this->getRestriction();
  515. // limit
  516. $aSql['limit'] = $this->getLimit();
  517. // sorting
  518. $this->setSorting();
  519. $aSort = $this->getSorting($this->aCurrent['sorting']);
  520. foreach ($aSort as $sKey => $sValue)
  521. $aSql[$sKey] .= $sValue;
  522. // execution
  523. $sqlQuery = "SELECT " . $aSql['ownFields'];
  524. $sqlQuery .= ' ' . $aSql['from'];
  525. if (isset($aSql['join']))
  526. $sqlQuery .= ' ' . $aSql['join'];
  527. if (isset($aSql['where']))
  528. $sqlQuery .= ' ' . $aSql['where'];
  529. if (isset($aSql['groupBy']))
  530. $sqlQuery .= ' ' . $aSql['groupBy'];
  531. if (isset($aSql['order']))
  532. $sqlQuery .= ' ' . $aSql['order'];
  533. if (isset($aSql['limit']))
  534. $sqlQuery .= ' ' . $aSql['limit'];
  535. // echoDbg($sqlQuery);
  536. $aRes = BxDolDb::getInstance()->getAll($sqlQuery);
  537. return $aRes;
  538. }
  539. /**
  540. * Set class fields condition params and paginate array
  541. */
  542. function setConditionParams()
  543. {
  544. // keyword
  545. $sKeyword = bx_process_input(bx_get('keyword'));
  546. if ($sKeyword !== false)
  547. $this->aCurrent['restriction']['keyword'] = array(
  548. 'value' => $sKeyword,
  549. 'field' => '',
  550. 'operator' => 'against'
  551. );
  552. // owner
  553. if (isset($_GET['ownerName'])) {
  554. $sName = bx_process_input($_GET['ownerName']);
  555. $iUser = (int)BxDolProfileQuery::getInstance()->getIdByNickname($sName);
  556. BxDolMenu::getInstance()->setCurrentProfileID($iUser);
  557. } elseif (isset($_GET['userID']))
  558. $iUser = bx_process_input($_GET['userID'], BX_DATA_INT);
  559. if (!empty($iUser))
  560. $this->aCurrent['restriction']['owner']['value'] = $iUser;
  561. // meta info
  562. if ($this->_sMetaType && !empty($this->aCurrent['object_metatags'])) {
  563. $o = BxDolMetatags::getObjectInstance($this->aCurrent['object_metatags']);
  564. if ($o) {
  565. unset($this->aCurrent['restriction']['keyword']);
  566. switch ($this->_sMetaType) {
  567. case 'location_country':
  568. $o->locationsSetSearchCondition($this, $sKeyword);
  569. break;
  570. case 'location_country_state':
  571. $o->locationsSetSearchCondition($this, $sKeyword, bx_process_input(bx_get('state')));
  572. break;
  573. case 'location_country_city':
  574. $o->locationsSetSearchCondition($this, $sKeyword, bx_process_input(bx_get('state')), bx_process_input(bx_get('city')));
  575. break;
  576. case 'mention':
  577. $oCmts = !empty($this->sModuleObjectComments) ? BxDolCmts::getObjectInstance($this->sModuleObjectComments, 0, false) : false;
  578. $o->mentionsSetSearchCondition($this, $sKeyword, $oCmts ? $oCmts->getSystemId() : 0);
  579. break;
  580. case 'keyword':
  581. $oCmts = !empty($this->sModuleObjectComments) ? BxDolCmts::getObjectInstance($this->sModuleObjectComments, 0, false) : false;
  582. $o->keywordsSetSearchCondition($this, $sKeyword, $oCmts ? $oCmts->getSystemId() : 0);
  583. break;
  584. }
  585. }
  586. }
  587. // category
  588. if ($this->_sCategoryObject && $o = BxDolCategory::getObjectInstance($this->_sCategoryObject)) {
  589. unset($this->aCurrent['restriction']['keyword']);
  590. $o->setSearchCondition($this, $sKeyword);
  591. }
  592. $this->setPaginate();
  593. $iNum = $this->getNum();
  594. if ($iNum > 0) {
  595. $this->aCurrent['paginate']['num'] = $iNum;
  596. } else {
  597. $this->aCurrent['paginate']['num'] = 0;
  598. }
  599. }
  600. /**
  601. * Check number of records on current page
  602. * return number of records on current page + 1
  603. */
  604. function getNum ()
  605. {
  606. $aJoins = $this->getJoins(false);
  607. $sqlQuery = "SELECT * FROM `{$this->aCurrent['table']}` " . (isset($aJoins['join']) ? $aJoins['join'] : '' ). $this->getRestriction() . (isset($aJoins['groupBy']) ? $aJoins['groupBy'] : '') . ' ' . $this->getLimit(true);
  608. return count(BxDolDb::getInstance()->getAll($sqlQuery));
  609. }
  610. /**
  611. * Check restriction params and make condition part of query
  612. * return $sqlWhere sql code of query for WHERE part
  613. */
  614. function getRestriction ()
  615. {
  616. $oDb = BxDolDb::getInstance();
  617. $sqlWhere = '';
  618. if (isset($this->aCurrent['restriction'])) {
  619. $aWhere[] = '1';
  620. foreach ($this->aCurrent['restriction'] as $sKey => $aValue) {
  621. $sqlCondition = '';
  622. if (isset($aValue['operator']) && isset($aValue['value']) && $aValue['value'] !== '' && $aValue['value'] !== false && $aValue['value'] !== null) {
  623. $sFieldTable = isset($aValue['table']) ? $aValue['table'] : $this->aCurrent['table'];
  624. $sqlCondition = "`{$sFieldTable}`.`{$aValue['field']}` ";
  625. switch ($aValue['operator']) {
  626. case 'nothing':
  627. $sqlCondition = " 0 ";
  628. break;
  629. case 'against':
  630. $aCond = isset($aValue['field']) && strlen($aValue['field']) > 0 ? $aValue['field'] : $this->aCurrent['searchFields'];
  631. $sqlCondition = !empty($aCond) ? $this->getSearchFieldsCond($aCond, $aValue['value']) : "";
  632. break;
  633. case 'like':
  634. $sqlCondition .= "LIKE " . $oDb->escape('%' . $aValue['value'] . '%');
  635. break;
  636. case 'in':
  637. case 'not in':
  638. $sValuesString = $this->getMultiValues($aValue['value']);
  639. $sqlCondition .= strtoupper($aValue['operator']) . '(' . $sValuesString . ')';
  640. break;
  641. default:
  642. $sqlCondition .= $aValue['operator'] . (isset($aValue['no_quote_value']) && $aValue['no_quote_value'] ? $aValue['value'] : $oDb->escape($aValue['value']));
  643. break;
  644. }
  645. }
  646. if (strlen($sqlCondition) > 0)
  647. $aWhere[] = $sqlCondition;
  648. }
  649. $sqlWhere .= "WHERE ". implode(' AND ', $aWhere) . (isset($this->aCurrent['restriction_sql']) ? $this->aCurrent['restriction_sql'] : '');
  650. }
  651. return $sqlWhere;
  652. }
  653. /**
  654. * Get limit part of query
  655. * return $sqlFrom code for limit part pf query
  656. */
  657. function getLimit ($isAddPlusOne = false)
  658. {
  659. if (!isset($this->aCurrent['paginate']))
  660. return;
  661. $sqlFrom = (int)$this->aCurrent['paginate']['start'] > 0 ? (int)$this->aCurrent['paginate']['start'] : 0;
  662. $sqlTo = $this->aCurrent['paginate']['perPage'] + ($isAddPlusOne ? 1 : 0);
  663. if ($sqlTo > 0)
  664. return 'LIMIT ' . $sqlFrom . ', ' . $sqlTo;
  665. }
  666. /**
  667. * Set sorting field of class
  668. */
  669. function setSorting ()
  670. {
  671. $this->aCurrent['sorting'] = isset($_GET[$this->aCurrent['name'] . '_mode']) ? $_GET[$this->aCurrent['name'] . '_mode'] : $this->aCurrent['sorting'];
  672. }
  673. /**
  674. * Get sorting part of query according current sorting mode
  675. * @param string $sSortType sorting type
  676. * return array with sql elements order and ownFields
  677. */
  678. function getSorting ($sSortType = 'last')
  679. {
  680. $aOverride = $this->getAlterOrder();
  681. if (is_array($aOverride) && !empty($aOverride))
  682. return $aOverride;
  683. $aSql = array();
  684. switch ($sSortType) {
  685. case 'rand':
  686. $aSql['order'] = "ORDER BY RAND()";
  687. break;
  688. case 'score':
  689. if (is_array($this->aCurrent['restriction']['keyword'])) {
  690. $sPseud = '';
  691. if ('on' == getParam('useLikeOperator')) {
  692. $aSql['order'] = "ORDER BY `score` DESC";
  693. $sPseud = 'score';
  694. }
  695. $aSql['ownFields'] .= $this->getSearchFieldsCond($this->aCurrent['searchFields'], $this->aCurrent['restriction']['keyword']['value'], $sPseud) . ',';
  696. }
  697. break;
  698. case 'none':
  699. $aSql['order'] = "";
  700. break;
  701. default:
  702. $aSql['order'] = "ORDER BY `date` DESC";
  703. }
  704. return $aSql;
  705. }
  706. /**
  707. * Return own varaint for sorting (redeclare if necessary)
  708. * return array of sql elements
  709. */
  710. function getAlterOrder ()
  711. {
  712. return array();
  713. }
  714. /**
  715. * Set paginate fields of class according GET params 'start' and 'per_page'
  716. * forcePage is need for setting most important number of current page
  717. */
  718. function setPaginate ()
  719. {
  720. $iPerPage = 0;
  721. //--- Check in aCurrent (low priority).
  722. if(isset($this->aCurrent['paginate']['perPage']) && (int)$this->aCurrent['paginate']['perPage'] != 0)
  723. $iPerPage = (int)$this->aCurrent['paginate']['perPage'];
  724. //--- Check in GET params (high priority).
  725. if(isset($_GET['per_page']) && (int)$_GET['per_page'] != 0)
  726. $iPerPage = (int)$_GET['per_page'];
  727. //--- Trying to get from System settings.
  728. if (empty($iPerPage))
  729. $iPerPage = (int)getParam('sys_per_page_search_keyword_' . ($this->_bSingleSearch ? 'single' : 'plural'));
  730. //--- Use default value in case of emergency.
  731. if (empty($iPerPage))
  732. $iPerPage = BX_DOL_SEARCH_RESULTS_PER_PAGE_DEFAULT;
  733. $this->aCurrent['paginate']['perPage'] = $iPerPage;
  734. $this->aCurrent['paginate']['start'] = isset($this->aCurrent['paginate']['forceStart'])
  735. ? (int)$this->aCurrent['paginate']['forceStart']
  736. : (empty($_GET['start']) ? 0 : (int)$_GET['start']);
  737. if ($this->aCurrent['paginate']['start'] < 0)
  738. $this->aCurrent['paginate']['start'] = 0;
  739. }
  740. function unsetPaginate()
  741. {
  742. unset($this->aCurrent['paginate']);
  743. }
  744. /**
  745. * Get sql where condition for search fields
  746. * @param array of search fields
  747. * @param string $sKeyword keyword value for search
  748. * @param string sPseud for setting new name for generated set of fields in query
  749. * return sql code of WHERE part in query
  750. */
  751. function getSearchFieldsCond ($aFields, $sKeyword, $sPseud = '')
  752. {
  753. if (!$sKeyword)
  754. return '';
  755. $sTable = empty($this->aCurrent['tableSearch']) ? $this->aCurrent['table'] : $this->aCurrent['tableSearch'];
  756. $oDb = BxDolDb::getInstance();
  757. $bLike = getParam('useLikeOperator');
  758. if (!is_array($aFields))
  759. $aFields = array($aFields);
  760. if ($bLike == 'on') {
  761. $sKeyword = $oDb->escape('%' . preg_replace('/\s+/', '%', $sKeyword) . '%');
  762. $sSqlWhere = '';
  763. foreach ($aFields as $sValue)
  764. $sSqlWhere .= "`{$sTable}`.`$sValue` LIKE " . $sKeyword . " OR ";
  765. $sSqlWhere = '(' . trim($sSqlWhere, 'OR ') . ')';
  766. } else {
  767. $sKeyword = $oDb->escape($sKeyword);
  768. $sSqlWhere = '';
  769. foreach ($aFields as $sValue)
  770. $sSqlWhere .= "`{$sTable}`.`$sValue`, ";
  771. $sSqlWhere = trim($sSqlWhere, ', ');
  772. $sSqlWhere = " MATCH({$sSqlWhere}) AGAINST (" . $sKeyword . ") ";
  773. if (!empty($sPseud))
  774. $sSqlWhere .= " AS `$sPseud` ";
  775. }
  776. return $sSqlWhere;
  777. }
  778. /**
  779. * Get set from several values for 'in' and 'not in' operators
  780. * @param $aValues array of values
  781. * return sql code for field with operator IN (NOT IN)
  782. */
  783. function getMultiValues ($aValues)
  784. {
  785. $oDb = BxDolDb::getInstance();
  786. return $oDb->implode_escape($aValues);
  787. }
  788. /**
  789. * System method for filling aPseud array.
  790. * Fill field aPseud for current class (if you will use own getSearchUnit methods then not necessary to redeclare).
  791. */
  792. function _getPseud ()
  793. {
  794. }
  795. /**
  796. * Add replace markers. Markers are replaced in titles and browse urls
  797. * @param $a array of markers as key => value
  798. * @return true on success or false on error
  799. */
  800. public function addMarkers ($a)
  801. {
  802. if (empty($a) || !is_array($a))
  803. return false;
  804. $this->_aMarkers = array_merge ($this->_aMarkers, $a);
  805. return true;
  806. }
  807. /**
  808. * Replace provided markers in a string
  809. * @param $mixed string or array to replace markers in
  810. * @return string where all occured markers are replaced
  811. */
  812. protected function _replaceMarkers ($mixed)
  813. {
  814. return bx_replace_markers($mixed, $this->_aMarkers);
  815. }
  816. }
  817. /** @} */