BxDolSearch.php 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  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. }
  619. // owner
  620. if (isset($_GET['ownerName'])) {
  621. $sName = bx_process_input($_GET['ownerName']);
  622. $iUser = (int)BxDolProfileQuery::getInstance()->getIdByNickname($sName);
  623. BxDolMenu::getInstance()->setCurrentProfileID($iUser);
  624. } elseif (isset($_GET['userID']))
  625. $iUser = bx_process_input($_GET['userID'], BX_DATA_INT);
  626. if (!empty($iUser))
  627. $this->aCurrent['restriction']['owner']['value'] = $iUser;
  628. // meta info
  629. if ($this->_sMetaType && !empty($this->aCurrent['object_metatags'])) {
  630. $o = BxDolMetatags::getObjectInstance($this->aCurrent['object_metatags']);
  631. if ($o) {
  632. unset($this->aCurrent['restriction']['keyword']);
  633. switch ($this->_sMetaType) {
  634. case 'location_country':
  635. $o->locationsSetSearchCondition($this, $sKeyword);
  636. break;
  637. case 'location_country_state':
  638. $o->locationsSetSearchCondition($this, $sKeyword, bx_process_input(isset($this->_aCustomSearchCondition['state']) ? $this->_aCustomSearchCondition['state'] : bx_get('state')));
  639. break;
  640. case 'location_country_city':
  641. $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')));
  642. break;
  643. case 'mention':
  644. $oCmts = !empty($this->sModuleObjectComments) ? BxDolCmts::getObjectInstance($this->sModuleObjectComments, 0, false) : false;
  645. $o->mentionsSetSearchCondition($this, $sKeyword, $oCmts ? $oCmts->getSystemId() : 0);
  646. break;
  647. case 'keyword':
  648. $oCmts = !empty($this->sModuleObjectComments) ? BxDolCmts::getObjectInstance($this->sModuleObjectComments, 0, false) : false;
  649. $o->keywordsSetSearchCondition($this, $sKeyword, $oCmts ? $oCmts->getSystemId() : 0);
  650. break;
  651. }
  652. }
  653. }
  654. // category
  655. if ($this->_sCategoryObject && ($o = BxDolCategory::getObjectInstance($this->_sCategoryObject)) && $this->_bSingleSearch) {
  656. unset($this->aCurrent['restriction']['keyword']);
  657. $o->setSearchCondition($this, $sKeyword);
  658. }
  659. $this->setPaginate();
  660. $iNum = $this->getNum();
  661. if ($iNum > 0) {
  662. $this->aCurrent['paginate']['num'] = $iNum;
  663. } else {
  664. $this->aCurrent['paginate']['num'] = 0;
  665. }
  666. }
  667. /**
  668. * Check number of records on current page
  669. * return number of records on current page + 1
  670. */
  671. function getNum ()
  672. {
  673. $aJoins = $this->getJoins(false);
  674. $sqlQuery = "SELECT * FROM `{$this->aCurrent['table']}` " . (isset($aJoins['join']) ? $aJoins['join'] : '' ). $this->getRestriction() . (isset($aJoins['groupBy']) ? $aJoins['groupBy'] : '') . ' ' . $this->getLimit(true);
  675. return count(BxDolDb::getInstance()->getAll($sqlQuery));
  676. }
  677. /**
  678. * Check restriction params and make condition part of query
  679. * return $sqlWhere sql code of query for WHERE part
  680. */
  681. function getRestriction ()
  682. {
  683. $oDb = BxDolDb::getInstance();
  684. $sqlWhere = '';
  685. if (isset($this->aCurrent['restriction'])) {
  686. $aWhere[] = '1';
  687. foreach ($this->aCurrent['restriction'] as $sKey => $aValue) {
  688. $sqlCondition = '';
  689. if (isset($aValue['operator']) && isset($aValue['value']) && $aValue['value'] !== '' && $aValue['value'] !== false && $aValue['value'] !== null) {
  690. $sFieldTable = isset($aValue['table']) ? $aValue['table'] : $this->aCurrent['table'];
  691. $sqlCondition = "`{$sFieldTable}`.`{$aValue['field']}` ";
  692. switch ($aValue['operator']) {
  693. case 'nothing':
  694. $sqlCondition = " 0 ";
  695. break;
  696. case 'against':
  697. $aCond = isset($aValue['field']) && strlen($aValue['field']) > 0 ? $aValue['field'] : $this->aCurrent['searchFields'];
  698. $sqlCondition = !empty($aCond) ? $this->getSearchFieldsCond($aCond, $aValue['value']) : "";
  699. break;
  700. case 'like':
  701. $sqlCondition .= "LIKE " . $oDb->escape('%' . $aValue['value'] . '%');
  702. break;
  703. case 'in':
  704. case 'not in':
  705. $sValuesString = $this->getMultiValues($aValue['value']);
  706. $sqlCondition .= strtoupper($aValue['operator']) . '(' . $sValuesString . ')';
  707. break;
  708. default:
  709. $sqlCondition .= $aValue['operator'] . (isset($aValue['no_quote_value']) && $aValue['no_quote_value'] ? $aValue['value'] : $oDb->escape($aValue['value']));
  710. break;
  711. }
  712. }
  713. if (strlen($sqlCondition) > 0)
  714. $aWhere[] = $sqlCondition;
  715. }
  716. $sqlWhere .= "WHERE ". implode(' AND ', $aWhere) . (isset($this->aCurrent['restriction_sql']) ? $this->aCurrent['restriction_sql'] : '');
  717. }
  718. return $sqlWhere;
  719. }
  720. /**
  721. * Get limit part of query
  722. * return $sqlFrom code for limit part pf query
  723. */
  724. function getLimit ($isAddPlusOne = false)
  725. {
  726. if (!isset($this->aCurrent['paginate']))
  727. return;
  728. $sqlFrom = (int)$this->aCurrent['paginate']['start'] > 0 ? (int)$this->aCurrent['paginate']['start'] : 0;
  729. $sqlTo = $this->aCurrent['paginate']['perPage'] + ($isAddPlusOne ? 1 : 0);
  730. if ($sqlTo > 0)
  731. return 'LIMIT ' . $sqlFrom . ', ' . $sqlTo;
  732. }
  733. /**
  734. * Set sorting field of class
  735. */
  736. function setSorting ()
  737. {
  738. $this->aCurrent['sorting'] = isset($_GET[$this->aCurrent['name'] . '_mode']) ? $_GET[$this->aCurrent['name'] . '_mode'] : $this->aCurrent['sorting'];
  739. }
  740. /**
  741. * Get sorting part of query according current sorting mode
  742. * @param string $sSortType sorting type
  743. * return array with sql elements order and ownFields
  744. */
  745. function getSorting ($sSortType = 'last')
  746. {
  747. $aOverride = $this->getAlterOrder();
  748. if (is_array($aOverride) && !empty($aOverride))
  749. return $aOverride;
  750. $aSql = array();
  751. switch ($sSortType) {
  752. case 'rand':
  753. $aSql['order'] = "ORDER BY RAND()";
  754. break;
  755. case 'score':
  756. if (is_array($this->aCurrent['restriction']['keyword'])) {
  757. $sPseud = '';
  758. if ('on' == getParam('useLikeOperator')) {
  759. $aSql['order'] = "ORDER BY `score` DESC";
  760. $sPseud = 'score';
  761. }
  762. $aSql['ownFields'] .= $this->getSearchFieldsCond($this->aCurrent['searchFields'], $this->aCurrent['restriction']['keyword']['value'], $sPseud) . ',';
  763. }
  764. break;
  765. case 'none':
  766. $aSql['order'] = "";
  767. break;
  768. default:
  769. $aSql['order'] = "ORDER BY `date` DESC";
  770. }
  771. return $aSql;
  772. }
  773. /**
  774. * Return own varaint for sorting (redeclare if necessary)
  775. * return array of sql elements
  776. */
  777. function getAlterOrder ()
  778. {
  779. return array();
  780. }
  781. /**
  782. * Set paginate fields of class according GET params 'start' and 'per_page'
  783. * forcePage is need for setting most important number of current page
  784. */
  785. function setPaginate ()
  786. {
  787. $iPerPage = 0;
  788. //--- Check in aCurrent (low priority).
  789. if(isset($this->aCurrent['paginate']['perPage']) && (int)$this->aCurrent['paginate']['perPage'] != 0)
  790. $iPerPage = (int)$this->aCurrent['paginate']['perPage'];
  791. //--- Check in GET params (high priority).
  792. if(isset($_GET['per_page']) && (int)$_GET['per_page'] != 0)
  793. $iPerPage = (int)$_GET['per_page'];
  794. //--- Trying to get from System settings.
  795. if (empty($iPerPage))
  796. $iPerPage = (int)getParam('sys_per_page_search_keyword_' . ($this->_bSingleSearch ? 'single' : 'plural'));
  797. //--- Use default value in case of emergency.
  798. if (empty($iPerPage))
  799. $iPerPage = BX_DOL_SEARCH_RESULTS_PER_PAGE_DEFAULT;
  800. $this->aCurrent['paginate']['perPage'] = $iPerPage;
  801. $this->aCurrent['paginate']['start'] = isset($this->aCurrent['paginate']['forceStart'])
  802. ? (int)$this->aCurrent['paginate']['forceStart']
  803. : (empty($_GET['start']) ? 0 : (int)$_GET['start']);
  804. if ($this->aCurrent['paginate']['start'] < 0)
  805. $this->aCurrent['paginate']['start'] = 0;
  806. }
  807. function unsetPaginate()
  808. {
  809. unset($this->aCurrent['paginate']);
  810. }
  811. /**
  812. * Get sql where condition for search fields
  813. * @param array of search fields
  814. * @param string $sKeyword keyword value for search
  815. * @param string sPseud for setting new name for generated set of fields in query
  816. * return sql code of WHERE part in query
  817. */
  818. function getSearchFieldsCond ($aFields, $sKeyword, $sPseud = '')
  819. {
  820. if (!$sKeyword)
  821. return '';
  822. $sTable = empty($this->aCurrent['tableSearch']) ? $this->aCurrent['table'] : $this->aCurrent['tableSearch'];
  823. $oDb = BxDolDb::getInstance();
  824. $bLike = getParam('useLikeOperator');
  825. if (!is_array($aFields))
  826. $aFields = array($aFields);
  827. if ($bLike == 'on') {
  828. $sKeyword = $oDb->escape('%' . preg_replace('/\s+/', '%', $sKeyword) . '%');
  829. $sSqlWhere = '';
  830. foreach ($aFields as $sValue)
  831. $sSqlWhere .= "`{$sTable}`.`$sValue` LIKE " . $sKeyword . " OR ";
  832. $sSqlWhere = '(' . trim($sSqlWhere, 'OR ') . ')';
  833. } else {
  834. $sKeyword = $oDb->escape($sKeyword);
  835. $sSqlWhere = '';
  836. foreach ($aFields as $sValue)
  837. $sSqlWhere .= "`{$sTable}`.`$sValue`, ";
  838. $sSqlWhere = trim($sSqlWhere, ', ');
  839. $sSqlWhere = " MATCH({$sSqlWhere}) AGAINST (" . $sKeyword . ") ";
  840. if (!empty($sPseud))
  841. $sSqlWhere .= " AS `$sPseud` ";
  842. }
  843. return $sSqlWhere;
  844. }
  845. /**
  846. * Get set from several values for 'in' and 'not in' operators
  847. * @param $aValues array of values
  848. * return sql code for field with operator IN (NOT IN)
  849. */
  850. function getMultiValues ($aValues)
  851. {
  852. $oDb = BxDolDb::getInstance();
  853. return $oDb->implode_escape($aValues);
  854. }
  855. /**
  856. * System method for filling aPseud array.
  857. * Fill field aPseud for current class (if you will use own getSearchUnit methods then not necessary to redeclare).
  858. */
  859. function _getPseud ()
  860. {
  861. }
  862. /**
  863. * Add replace markers. Markers are replaced in titles and browse urls
  864. * @param $a array of markers as key => value
  865. * @return true on success or false on error
  866. */
  867. public function addMarkers ($a)
  868. {
  869. if (empty($a) || !is_array($a))
  870. return false;
  871. $this->_aMarkers = array_merge ($this->_aMarkers, $a);
  872. return true;
  873. }
  874. /**
  875. * Replace provided markers in a string
  876. * @param $mixed string or array to replace markers in
  877. * @return string where all occured markers are replaced
  878. */
  879. protected function _replaceMarkers ($mixed)
  880. {
  881. return bx_replace_markers($mixed, $this->_aMarkers);
  882. }
  883. }
  884. /** @} */