BxDolSearch.php 26 KB

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