BxDolSearch.php 34 KB

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