BxDolSearch.php 30 KB

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