BxDolSearch.php 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  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_recursive($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), BX_DB_PADDING_DEF);
  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 setCustomCurrentCondition($a)
  367. {
  368. $this->aCurrent = array_merge_recursive($this->aCurrent, $a);
  369. }
  370. public function setCategoriesCondition($sKeyword)
  371. {
  372. $this->aCurrent['join']['multicat'] = array(
  373. 'type' => 'INNER',
  374. 'table' => 'sys_categories2objects',
  375. 'mainField' => 'id',
  376. 'onField' => 'object_id',
  377. 'joinFields' => array(),
  378. );
  379. if (isset($this->aCurrent['tableSearch'])){
  380. $this->aCurrent['join']['multicat']['mainTable'] = $this->aCurrent['tableSearch'];
  381. }
  382. $this->aCurrent['join']['multicat2'] = array(
  383. 'type' => 'INNER',
  384. 'table' => 'sys_categories',
  385. 'mainField' => 'category_id',
  386. 'mainTable' => 'sys_categories2objects',
  387. 'onField' => 'id',
  388. 'joinFields' => array(),
  389. );
  390. $this->aCurrent['restriction']['multicat'] = array('value' => $sKeyword, 'field' => 'value', 'operator' => '=', 'table' => 'sys_categories');
  391. }
  392. /**
  393. * Display empty message if there is no content, custom empty message can be used.
  394. * @param $b - boolan value to enable or disable 'empty' message
  395. * @param $sLangKey [optional] - custom 'empty' message
  396. */
  397. public function setDisplayEmptyMsg($b, $sLangKey = '')
  398. {
  399. $this->bDisplayEmptyMsg = $b;
  400. if ($sLangKey)
  401. $this->sDisplayEmptyMsgKey = $sLangKey;
  402. }
  403. /**
  404. * Perform privacy checking for every unit
  405. * @param $b - boolan value to enable or disable privacy checking
  406. */
  407. public function setProcessPrivateContent ($b)
  408. {
  409. $this->bProcessPrivateContent = $b;
  410. if ($b) {
  411. // unset condition which was set when 'bProcessPrivateContent' was set to 'false'
  412. foreach ($this->aPrivateConditionsIndexes['restriction'] as $sKey)
  413. unset($this->aCurrent['restriction'][$sKey]);
  414. foreach ($this->aPrivateConditionsIndexes['join'] as $sKey)
  415. unset($this->aCurrent['join'][$sKey]);
  416. }
  417. }
  418. /**
  419. * Get search results without design box and paginate
  420. * @return html code
  421. */
  422. function processingRaw ()
  423. {
  424. $sCode = $this->displayResultBlock();
  425. return $this->aCurrent['paginate']['num'] > 0 ? $sCode : '';
  426. }
  427. /**
  428. * Get html box of search results (usually used in grlobal search)
  429. * @return html code
  430. */
  431. function processing ()
  432. {
  433. $sCode = $this->displayResultBlock();
  434. if ($this->aCurrent['paginate']['num'] > 0) {
  435. $sPaginate = $this->showPagination();
  436. $sCode = $this->displaySearchBox($sCode, $sPaginate);
  437. } else {
  438. $sCode = $this->bDisplayEmptyMsg ? $this->displaySearchBox(MsgBox(_t($this->sDisplayEmptyMsgKey ? $this->sDisplayEmptyMsgKey : '_Empty'))) : '';
  439. }
  440. return $sCode;
  441. }
  442. /**
  443. * Get html output of search result
  444. * @return html code
  445. */
  446. function displayResultBlock ()
  447. {
  448. $aData = $this->getSearchData();
  449. $sCode = '';
  450. if (count($aData) > 0) {
  451. $sCode = $this->addCustomParts();
  452. foreach ($aData as $iKey => $aValue) {
  453. $sCode .= $this->displaySearchUnit($aValue);
  454. }
  455. }
  456. return $sCode;
  457. }
  458. /**
  459. * Add different code before html output (usually redeclared)
  460. * no return result
  461. */
  462. function addCustomParts ()
  463. {
  464. }
  465. /**
  466. * Get XML string for rss output
  467. */
  468. function rss ()
  469. {
  470. if (!isset($this->aCurrent['rss']['fields']) || !isset($this->aCurrent['rss']['link']))
  471. return '';
  472. $aData = $this->getSearchData();
  473. $f = &$this->aCurrent['rss']['fields'];
  474. if ($aData) {
  475. foreach ($aData as $k => $a) {
  476. $aData[$k][$f['Link']] = $this->getRssUnitLink ($a);
  477. if(isset($f['Image']))
  478. $aData[$k][$f['Image']] = $this->getRssUnitImage ($a, $f['Image']);
  479. }
  480. }
  481. $oRss = new BxDolRssFactory ();
  482. return $oRss->GenRssByCustomData(
  483. $aData,
  484. isset($this->aCurrent['rss']['title']) && $this->aCurrent['rss']['title'] ? $this->aCurrent['rss']['title'] : $this->aCurrent['title'],
  485. $this->aCurrent['rss']['link'],
  486. $this->aCurrent['rss']['fields'],
  487. isset($this->aCurrent['rss']['image']) ? $this->aCurrent['rss']['image'] : '',
  488. isset($this->aCurrent['rss']['profile']) ? $this->aCurrent['rss']['profile'] : 0
  489. );
  490. }
  491. /**
  492. * Output RSS XML with XML header
  493. */
  494. function outputRSS ()
  495. {
  496. header('Content-Type: text/xml; charset=UTF-8');
  497. echo $this->rss();
  498. }
  499. /**
  500. * Return rss unit link (redeclared)
  501. */
  502. function getRssUnitLink (&$a)
  503. {
  504. // override this functions to return permalink to rss unit
  505. }
  506. /**
  507. * Return rss unit image (redeclared)
  508. */
  509. function getRssUnitImage (&$a, $sField)
  510. {
  511. // override this functions to return image for rss unit
  512. }
  513. /**
  514. * Naming fields in query's body
  515. * @param string $sFieldName name of field
  516. * @param string $sTableName name of field's table
  517. * $param string $sOperator of field's calculation (like MAX)
  518. * @param boolean $bRenameMode indicator for renaming and unsetting fields from field of class $this->aPseud
  519. * return $sqlUnit sql code and unsetting elements from aPseud field
  520. */
  521. function setFieldUnit ($sFieldName, $sTableName, $sOperator = '', $bRenameMode = true)
  522. {
  523. if (!empty($sOperator))
  524. $sqlUnit = "$sOperator(`$sTableName`.`$sFieldName`)";
  525. else
  526. $sqlUnit = "`$sTableName`.`$sFieldName`";
  527. if (isset($this->aPseud) && $bRenameMode !== false) {
  528. $sKey = array_search($sFieldName, $this->aPseud);
  529. if ($sKey !== false) {
  530. $sqlUnit .= " as `$sKey`";
  531. unset($this->aPseud[$sKey]);
  532. }
  533. }
  534. return $sqlUnit . ', ';
  535. }
  536. /**
  537. * Get html code of of every search unit
  538. * @param array $aData array of every search unit
  539. * return html code
  540. */
  541. function displaySearchUnit ($aData)
  542. {
  543. }
  544. /**
  545. * Get html code of search box with search results
  546. * @param string $sCode html code of search results
  547. * $param $sPaginate html code of paginate
  548. * return html code
  549. */
  550. function displaySearchBox ($sCode, $sPaginate = '')
  551. {
  552. }
  553. /**
  554. * Get html code of pagination
  555. */
  556. function showPagination ($bAdmin = false, $bChangePage = true, $bPageReload = true)
  557. {
  558. }
  559. /**
  560. * Get array of data with search results
  561. * return array with data
  562. */
  563. function getSearchData ()
  564. {
  565. $this->aPseud = $this->_getPseud();
  566. $this->setConditionParams();
  567. if ($this->aCurrent['paginate']['num'] > 0) {
  568. $aData = $this->getSearchDataByParams();
  569. return $aData;
  570. }
  571. return array();
  572. }
  573. /**
  574. * Get array with code for sql elements
  575. * @param $bRenameMode indicator of renmaing fields
  576. * return array with joinFields, ownFields, groupBy and join elements
  577. */
  578. function getJoins ($bRenameMode = true)
  579. {
  580. $aSql = array();
  581. // joinFields & join
  582. if (isset($this->aCurrent['join']) && is_array($this->aCurrent['join'])) {
  583. $aSql = array('join'=>'', 'ownFields'=>'', 'joinFields'=>'', 'groupBy'=>'');
  584. foreach ($this->aCurrent['join'] as $sKey => $aValue) {
  585. $sAlias = isset($aValue['table_alias']) ? $aValue['table_alias'] : $aValue['table'];
  586. $sTableAlias = isset($aValue['table_alias']) ? " AS {$aValue['table_alias']} " : '';
  587. if (is_array($aValue['joinFields'])) {
  588. foreach ($aValue['joinFields'] as $sValue) {
  589. $aSql['joinFields'] .= $this->setFieldUnit($sValue, $sAlias, isset($aValue['operator']) ? $aValue['operator'] : null, $bRenameMode);
  590. }
  591. }
  592. // group by
  593. if (isset($aValue['groupTable']))
  594. $aSql['groupBy'] = "GROUP BY `{$aValue['groupTable']}`.`{$aValue['groupField']}`, ";
  595. $sOn = isset($aValue['mainTable']) ? $aValue['mainTable'] : $this->aCurrent['table'];
  596. $aSql['join'] .= " {$aValue['type']} JOIN `{$aValue['table']}` $sTableAlias ON " . (!empty($aValue['on_sql']) ? $aValue['on_sql'] : "`{$sAlias}`.`{$aValue['onField']}`=`$sOn`.`{$aValue['mainField']}`");
  597. $aSql['ownFields'] .= $this->setFieldUnit($aValue['mainField'], $sOn, '', $bRenameMode);
  598. }
  599. $aSql['joinFields'] = trim($aSql['joinFields'], ', ');
  600. $aSql['groupBy'] = trim($aSql['groupBy'], ', ');
  601. }
  602. return $aSql;
  603. }
  604. /**
  605. * Concat sql parts of query, run it and return result array
  606. * @param $aParams addon param
  607. * return $aData multivariate array
  608. */
  609. function getSearchDataByParams ($aParams = '')
  610. {
  611. $aSql = array('ownFields'=>'', 'joinFields'=>'', 'order'=>'');
  612. // searchFields
  613. foreach ($this->aCurrent['ownFields'] as $sValue)
  614. $aSql['ownFields'] .= $this->setFieldUnit($sValue, $this->aCurrent['table']);
  615. // joinFields & join
  616. $aJoins = $this->getJoins();
  617. if (!empty($aJoins)) {
  618. $aSql['ownFields'] .= $aJoins['ownFields'];
  619. $aSql['ownFields'] .= $aJoins['joinFields'];
  620. $aSql['join'] = $aJoins['join'];
  621. $aSql['groupBy'] = $aJoins['groupBy'];
  622. }
  623. $aSql['ownFields'] = trim($aSql['ownFields'], ', ');
  624. // from
  625. $aSql['from'] = " FROM `{$this->aCurrent['table']}`";
  626. // where
  627. $aSql['where'] = $this->getRestriction();
  628. // limit
  629. $aSql['limit'] = $this->getLimit();
  630. // sorting
  631. $this->setSorting();
  632. $aSort = $this->getSorting($this->aCurrent['sorting']);
  633. foreach ($aSort as $sKey => $sValue)
  634. $aSql[$sKey] .= $sValue;
  635. // execution
  636. $sqlQuery = "SELECT " . $aSql['ownFields'];
  637. $sqlQuery .= ' ' . $aSql['from'];
  638. if (isset($aSql['join']))
  639. $sqlQuery .= ' ' . $aSql['join'];
  640. if (isset($aSql['where']))
  641. $sqlQuery .= ' ' . $aSql['where'];
  642. if (isset($aSql['groupBy']))
  643. $sqlQuery .= ' ' . $aSql['groupBy'];
  644. if (isset($aSql['order']))
  645. $sqlQuery .= ' ' . $aSql['order'];
  646. if (isset($aSql['limit']))
  647. $sqlQuery .= ' ' . $aSql['limit'];
  648. // echoDbg($sqlQuery);
  649. $aRes = BxDolDb::getInstance()->getAll($sqlQuery);
  650. return $aRes;
  651. }
  652. /**
  653. * Set class fields condition params and paginate array
  654. */
  655. function setConditionParams()
  656. {
  657. $this->aCurrent['paginate']['num'] = 0;
  658. // keyword
  659. $sKeyword = bx_process_input(isset($this->_aCustomSearchCondition['keyword']) ? $this->_aCustomSearchCondition['keyword'] : bx_get('keyword'));
  660. if ($this->_bLiveSearch && empty($sKeyword))
  661. return;
  662. if ($sKeyword !== false) {
  663. if (substr($sKeyword, 0, 1) == '@') {
  664. $sModule = $this->aCurrent['module_name'];
  665. $sMethod = 'act_as_profile';
  666. if(!bx_is_srv($sModule, $sMethod) || !bx_srv($sModule, $sMethod))
  667. return;
  668. $sKeyword = substr($sKeyword, 1);
  669. }
  670. $this->aCurrent['restriction']['keyword'] = array(
  671. 'value' => $sKeyword,
  672. 'field' => '',
  673. 'operator' => 'against'
  674. );
  675. // for search results we need to show all items, not only public content
  676. $this->setProcessPrivateContent(true);
  677. }
  678. // owner
  679. if (isset($_GET['ownerName'])) {
  680. $sName = bx_process_input($_GET['ownerName']);
  681. $iUser = (int)BxDolProfileQuery::getInstance()->getIdByNickname($sName);
  682. BxDolMenu::getInstance()->setCurrentProfileID($iUser);
  683. } elseif (isset($_GET['userID']))
  684. $iUser = bx_process_input($_GET['userID'], BX_DATA_INT);
  685. if (!empty($iUser))
  686. $this->aCurrent['restriction']['owner']['value'] = $iUser;
  687. // meta info
  688. if ($this->_sMetaType && !empty($this->aCurrent['object_metatags'])) {
  689. $o = BxDolMetatags::getObjectInstance($this->aCurrent['object_metatags']);
  690. if ($o) {
  691. unset($this->aCurrent['restriction']['keyword']);
  692. switch ($this->_sMetaType) {
  693. case 'location_country':
  694. $o->locationsSetSearchCondition($this, $sKeyword);
  695. break;
  696. case 'location_country_state':
  697. $o->locationsSetSearchCondition($this, $sKeyword, bx_process_input(isset($this->_aCustomSearchCondition['state']) ? $this->_aCustomSearchCondition['state'] : bx_get('state')));
  698. break;
  699. case 'location_country_city':
  700. $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')));
  701. break;
  702. case 'mention':
  703. $oCmts = !empty($this->sModuleObjectComments) ? BxDolCmts::getObjectInstance($this->sModuleObjectComments, 0, false) : false;
  704. $o->mentionsSetSearchCondition($this, $sKeyword, $oCmts ? $oCmts->getSystemId() : 0);
  705. break;
  706. case 'keyword':
  707. $oCmts = !empty($this->sModuleObjectComments) ? BxDolCmts::getObjectInstance($this->sModuleObjectComments, 0, false) : false;
  708. $o->keywordsSetSearchCondition($this, $sKeyword, $oCmts ? $oCmts->getSystemId() : 0);
  709. break;
  710. }
  711. }
  712. }
  713. // category
  714. if ($this->_sCategoryObject){
  715. if(($o = BxDolCategory::getObjectInstance($this->_sCategoryObject)) && $this->_bSingleSearch) {
  716. unset($this->aCurrent['restriction']['keyword']);
  717. $o->setSearchCondition($this, $sKeyword);
  718. }
  719. if ($this->_sCategoryObject == 'multi'){
  720. unset($this->aCurrent['restriction']['keyword']);
  721. $this->setCategoriesCondition($sKeyword);
  722. }
  723. }
  724. $this->setPaginate();
  725. $iNum = $this->getNum();
  726. if ($iNum > 0)
  727. $this->aCurrent['paginate']['num'] = $iNum;
  728. }
  729. /**
  730. * Check number of records on current page
  731. * return number of records on current page + 1
  732. */
  733. function getNum ()
  734. {
  735. $aJoins = $this->getJoins(false);
  736. $sqlQuery = "SELECT * FROM `{$this->aCurrent['table']}` " . (isset($aJoins['join']) ? $aJoins['join'] : '' ). $this->getRestriction() . (isset($aJoins['groupBy']) ? $aJoins['groupBy'] : '') . ' ' . $this->getLimit(true);
  737. return count(BxDolDb::getInstance()->getAll($sqlQuery));
  738. }
  739. /**
  740. * Check restriction params and make condition part of query
  741. * return $sqlWhere sql code of query for WHERE part
  742. */
  743. function getRestriction ()
  744. {
  745. $oDb = BxDolDb::getInstance();
  746. $sqlWhere = '';
  747. if (isset($this->aCurrent['restriction'])) {
  748. $aWhere[] = '1';
  749. foreach ($this->aCurrent['restriction'] as $sKey => $aValue) {
  750. $sqlCondition = '';
  751. if (isset($aValue['operator']) && isset($aValue['value']) && $aValue['value'] !== '' && $aValue['value'] !== false && $aValue['value'] !== null) {
  752. $sFieldTable = isset($aValue['table']) ? $aValue['table'] : $this->aCurrent['table'];
  753. $sqlCondition = "`{$sFieldTable}`.`{$aValue['field']}` ";
  754. switch ($aValue['operator']) {
  755. case 'empty value':
  756. $sqlCondition .= " = '' ";
  757. break;
  758. case 'not empty value':
  759. $sqlCondition .= " != '' ";
  760. break;
  761. case 'nothing':
  762. $sqlCondition = " 0 ";
  763. break;
  764. case 'against':
  765. $aCond = isset($aValue['field']) && strlen($aValue['field']) > 0 ? $aValue['field'] : $this->aCurrent['searchFields'];
  766. $sqlCondition = !empty($aCond) ? $this->getSearchFieldsCond($aCond, $aValue['value']) : "";
  767. break;
  768. case 'like':
  769. $sqlCondition .= "LIKE " . $oDb->escape('%' . $aValue['value'] . '%');
  770. break;
  771. case 'in':
  772. case 'not in':
  773. $sValuesString = $this->getMultiValues($aValue['value']);
  774. $sqlCondition .= strtoupper($aValue['operator']) . '(' . $sValuesString . ')';
  775. break;
  776. default:
  777. $sqlCondition .= $aValue['operator'] . (isset($aValue['no_quote_value']) && $aValue['no_quote_value'] ? $aValue['value'] : $oDb->escape($aValue['value']));
  778. break;
  779. }
  780. }
  781. if (strlen($sqlCondition) > 0)
  782. $aWhere[] = $sqlCondition;
  783. }
  784. $sqlWhere .= "WHERE ". implode(' AND ', $aWhere) . (isset($this->aCurrent['restriction_sql']) ? $this->aCurrent['restriction_sql'] : '');
  785. }
  786. return $sqlWhere;
  787. }
  788. /**
  789. * Get limit part of query
  790. * return $sqlFrom code for limit part pf query
  791. */
  792. function getLimit ($isAddPlusOne = false)
  793. {
  794. if (!isset($this->aCurrent['paginate']))
  795. return;
  796. $sqlFrom = (int)$this->aCurrent['paginate']['start'] > 0 ? (int)$this->aCurrent['paginate']['start'] : 0;
  797. $sqlTo = $this->aCurrent['paginate']['perPage'] + ($isAddPlusOne ? 1 : 0);
  798. if ($sqlTo > 0)
  799. return 'LIMIT ' . $sqlFrom . ', ' . $sqlTo;
  800. }
  801. /**
  802. * Set sorting field of class
  803. */
  804. function setSorting ()
  805. {
  806. $this->aCurrent['sorting'] = isset($_GET[$this->aCurrent['name'] . '_mode']) ? $_GET[$this->aCurrent['name'] . '_mode'] : $this->aCurrent['sorting'];
  807. }
  808. /**
  809. * Get sorting part of query according current sorting mode
  810. * @param string $sSortType sorting type
  811. * return array with sql elements order and ownFields
  812. */
  813. function getSorting ($sSortType = 'last')
  814. {
  815. $aOverride = $this->getAlterOrder();
  816. if (is_array($aOverride) && !empty($aOverride))
  817. return $aOverride;
  818. $aSql = array();
  819. switch ($sSortType) {
  820. case 'rand':
  821. $aSql['order'] = "ORDER BY RAND()";
  822. break;
  823. case 'score':
  824. if (is_array($this->aCurrent['restriction']['keyword'])) {
  825. $sPseud = '';
  826. if ('on' == getParam('useLikeOperator')) {
  827. $aSql['order'] = "ORDER BY `score` DESC";
  828. $sPseud = 'score';
  829. }
  830. $aSql['ownFields'] .= $this->getSearchFieldsCond($this->aCurrent['searchFields'], $this->aCurrent['restriction']['keyword']['value'], $sPseud) . ',';
  831. }
  832. break;
  833. case 'none':
  834. $aSql['order'] = "";
  835. break;
  836. default:
  837. $aSql['order'] = "ORDER BY `date` DESC";
  838. }
  839. return $aSql;
  840. }
  841. /**
  842. * Return own varaint for sorting (redeclare if necessary)
  843. * return array of sql elements
  844. */
  845. function getAlterOrder ()
  846. {
  847. return array();
  848. }
  849. /**
  850. * Set paginate fields of class according GET params 'start' and 'per_page'
  851. * forcePage is need for setting most important number of current page
  852. */
  853. function setPaginate ()
  854. {
  855. $iPerPage = 0;
  856. //--- Check in aCurrent (low priority).
  857. if(isset($this->aCurrent['paginate']['perPage']) && (int)$this->aCurrent['paginate']['perPage'] != 0)
  858. $iPerPage = (int)$this->aCurrent['paginate']['perPage'];
  859. //--- Check in GET params (high priority).
  860. if(isset($_GET['per_page']) && (int)$_GET['per_page'] != 0)
  861. $iPerPage = (int)$_GET['per_page'];
  862. //--- Trying to get from System settings.
  863. if (empty($iPerPage))
  864. $iPerPage = (int)getParam('sys_per_page_search_keyword_' . ($this->_bSingleSearch ? 'single' : 'plural'));
  865. //--- Use default value in case of emergency.
  866. if (empty($iPerPage))
  867. $iPerPage = BX_DOL_SEARCH_RESULTS_PER_PAGE_DEFAULT;
  868. if ($this->iPaginatePerPage != BX_DOL_SEARCH_RESULTS_PER_PAGE_DEFAULT)
  869. $iPerPage = $this->iPaginatePerPage;
  870. $this->aCurrent['paginate']['perPage'] = $iPerPage;
  871. $this->aCurrent['paginate']['start'] = isset($this->aCurrent['paginate']['forceStart'])
  872. ? (int)$this->aCurrent['paginate']['forceStart']
  873. : (empty($_GET['start']) ? 0 : (int)$_GET['start']);
  874. if ($this->aCurrent['paginate']['start'] < 0)
  875. $this->aCurrent['paginate']['start'] = 0;
  876. }
  877. function unsetPaginate()
  878. {
  879. unset($this->aCurrent['paginate']);
  880. }
  881. /**
  882. * Get sql where condition for search fields
  883. * @param array of search fields
  884. * @param string $sKeyword keyword value for search
  885. * @param string sPseud for setting new name for generated set of fields in query
  886. * return sql code of WHERE part in query
  887. */
  888. function getSearchFieldsCond ($aFields, $sKeyword, $sPseud = '')
  889. {
  890. if (!$sKeyword)
  891. return '';
  892. $sTable = empty($this->aCurrent['tableSearch']) ? $this->aCurrent['table'] : $this->aCurrent['tableSearch'];
  893. $oDb = BxDolDb::getInstance();
  894. $bLike = getParam('useLikeOperator');
  895. if (!is_array($aFields))
  896. $aFields = array($aFields);
  897. if ($bLike == 'on') {
  898. $sKeyword = $oDb->escape('%' . preg_replace('/\s+/', '%', $sKeyword) . '%');
  899. $sSqlWhere = '';
  900. foreach ($aFields as $sValue)
  901. $sSqlWhere .= "`{$sTable}`.`$sValue` LIKE " . $sKeyword . " OR ";
  902. $sSqlWhere = '(' . trim($sSqlWhere, 'OR ') . ')';
  903. } else {
  904. $sKeyword = $oDb->escape($sKeyword);
  905. $sSqlWhere = '';
  906. foreach ($aFields as $sValue)
  907. $sSqlWhere .= "`{$sTable}`.`$sValue`, ";
  908. $sSqlWhere = trim($sSqlWhere, ', ');
  909. $sSqlWhere = " MATCH({$sSqlWhere}) AGAINST (" . $sKeyword . ") ";
  910. if (!empty($sPseud))
  911. $sSqlWhere .= " AS `$sPseud` ";
  912. }
  913. return $sSqlWhere;
  914. }
  915. /**
  916. * Get set from several values for 'in' and 'not in' operators
  917. * @param $aValues array of values
  918. * return sql code for field with operator IN (NOT IN)
  919. */
  920. function getMultiValues ($aValues)
  921. {
  922. $oDb = BxDolDb::getInstance();
  923. return $oDb->implode_escape($aValues);
  924. }
  925. /**
  926. * System method for filling aPseud array.
  927. * Fill field aPseud for current class (if you will use own getSearchUnit methods then not necessary to redeclare).
  928. */
  929. function _getPseud ()
  930. {
  931. }
  932. /**
  933. * Add replace markers. Markers are replaced in titles and browse urls
  934. * @param $a array of markers as key => value
  935. * @return true on success or false on error
  936. */
  937. public function addMarkers ($a)
  938. {
  939. if (empty($a) || !is_array($a))
  940. return false;
  941. $this->_aMarkers = array_merge ($this->_aMarkers, $a);
  942. return true;
  943. }
  944. /**
  945. * Replace provided markers in a string
  946. * @param $mixed string or array to replace markers in
  947. * @return string where all occured markers are replaced
  948. */
  949. protected function _replaceMarkers ($mixed)
  950. {
  951. return bx_replace_markers($mixed, $this->_aMarkers);
  952. }
  953. }
  954. /** @} */