BxDolSearch.php 34 KB

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