BxDolSearch.php 28 KB

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