BxDolSearch.php 37 KB

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