BxDolSearch.php 28 KB

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