BxDolSearch.php 27 KB

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