1
0

BxDolSearch.php 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473
  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 $_bIsApi;
  39. protected $aClasses = array(); ///< array of all search classes
  40. protected $aChoice = array(); ///< array of current search classes which were choosen in search area
  41. protected $_bRawProcessing = false; ///< display search results without design box and paginate
  42. protected $_bDataProcessing = false; ///< return result as array of data
  43. protected $_bLiveSearch = false;
  44. protected $_sMetaType = '';
  45. protected $_sCategoryObject = ''; ///< by default = object from sys_objects_category table, for multicategories set to 'multi' string
  46. protected $_aCustomSearchCondition = array();
  47. protected $_aCustomCurrentCondition = array();
  48. protected $_sUnitTemplate = '';
  49. /**
  50. * Constructor
  51. * @param array $aChoice - array of choosen classes (will take a part only existing in `sys_objects_search` table)
  52. */
  53. public function __construct ($aChoice = '')
  54. {
  55. parent::__construct();
  56. $this->_bIsApi = bx_is_api();
  57. $this->aClasses = BxDolDb::getInstance()->fromCache('sys_objects_search', 'getAllWithKey',
  58. 'SELECT `ID` as `id`,
  59. `Title` as `title`,
  60. `ClassName` as `class`,
  61. `ClassPath` as `file`,
  62. `ObjectName`,
  63. `GlobalSearch`
  64. FROM `sys_objects_search`
  65. ORDER BY `Order` ASC', 'ObjectName'
  66. );
  67. if (is_array($aChoice) && !empty($aChoice)) {
  68. foreach ($aChoice as $sValue) {
  69. if (isset($this->aClasses[$sValue]))
  70. $this->aChoice[$sValue] = $this->aClasses[$sValue];
  71. }
  72. } else {
  73. $this->aChoice = $this->aClasses;
  74. }
  75. }
  76. /**
  77. * create units for all classes and calling their processing methods
  78. */
  79. public function response ()
  80. {
  81. $sCode = $this->_bDataProcessing ? [] : '';
  82. if($this->_bLiveSearch && ($iAssistant = BxDolAI::getAssistantForLiveSearch()) != 0) {
  83. $sKeyword = '';
  84. if(($sKeyword = bx_get('keyword')) !== false)
  85. $sKeyword = bx_process_input($sKeyword);
  86. $sCode .= BxDolAIAssistant::getObjectInstance($iAssistant)->getAskButton($sKeyword);
  87. }
  88. $bSingle = count($this->aChoice) == 1;
  89. foreach($this->aChoice as $sKey => $aValue) {
  90. if(!$this->_sMetaType && !$aValue['GlobalSearch'])
  91. continue;
  92. $sClassName = 'BxTemplSearchResult';
  93. if(!empty($aValue['class'])) {
  94. $sClassName = $aValue['class'];
  95. if(!empty($aValue['file']))
  96. require_once(BX_DIRECTORY_PATH_ROOT . $aValue['file']);
  97. }
  98. $oEx = new $sClassName();
  99. if($this->_sMetaType && !$oEx->isMetaEnabled($this->_sMetaType))
  100. continue;
  101. $oEx->setId($aValue['id']);
  102. $oEx->setLiveSearch($this->_bLiveSearch);
  103. $oEx->setMetaType($this->_sMetaType);
  104. $oEx->setCategoryObject($this->_sCategoryObject);
  105. $oEx->setCenterContentUnitSelector(false);
  106. $oEx->setSingleSearch($bSingle);
  107. $oEx->setCustomSearchCondition($this->_aCustomSearchCondition);
  108. $oEx->aCurrent = array_merge_recursive($oEx->aCurrent, $this->_aCustomCurrentCondition);
  109. if($this->_sUnitTemplate)
  110. $oEx->setUnitTemplate($this->_sUnitTemplate);
  111. if($this->_bDataProcessing) {
  112. if($this->_bIsApi) {
  113. if($bSingle) {
  114. $sMethod = 'decodeDataAPI';
  115. if($this->_bLiveSearch && ($sMethodLs = 'decodeLsDataAPI') && method_exists($oEx, $sMethodLs))
  116. $sMethod = $sMethodLs;
  117. $sCode = $oEx->$sMethod($oEx->getSearchData());
  118. }
  119. else
  120. $sCode[$sKey] = $oEx->getSearchQuery($sKey);
  121. }
  122. else
  123. $sCode[$sKey] = $oEx->getSearchData();
  124. }
  125. else
  126. $sCode .= $this->_bRawProcessing ? $oEx->processingRaw() : $oEx->processing();
  127. }
  128. if($this->_bIsApi && !$bSingle && is_array($sCode)) {
  129. $bExtendedUnits = getParam('sys_api_extended_units') == 'on';
  130. $aQueries = [];
  131. foreach($sCode as $aQuery)
  132. if(!empty($aQuery['query']))
  133. $aQueries[] = $aQuery['query'];
  134. $aItems = BxDolDb::getInstance()->getAll('(' . implode(') UNION (', $aQueries) . ') ORDER BY `added` DESC ' . current($sCode)['limit']);
  135. $sCode = [];
  136. foreach($aItems as $aItem)
  137. if(($oContentInfo = BxDolContentInfo::getObjectInstance($aItem['content_info'])) !== false)
  138. $sCode[] = $oContentInfo->getContentInfoAPI($aItem['id'], $bExtendedUnits);
  139. }
  140. return $sCode;
  141. }
  142. public function getEmptyResult ()
  143. {
  144. $sKey = _t('_Empty');
  145. return DesignBoxContent($sKey, MsgBox($sKey), BX_DB_PADDING_DEF);
  146. }
  147. public function getSearchResultObject($sChoice = '')
  148. {
  149. $aSearchResult = [];
  150. if($sChoice) {
  151. if(empty($this->aChoice[$sChoice]) || !is_array($this->aChoice[$sChoice]))
  152. return false;
  153. $aSearchResult = $this->aChoice[$sChoice];
  154. }
  155. else
  156. $aSearchResult = reset($this->aChoice);
  157. $sClassName = 'BxTemplSearchResult';
  158. if(!empty($aSearchResult['class'])) {
  159. $sClassName = $aSearchResult['class'];
  160. if(!empty($aSearchResult['file']))
  161. require_once(BX_DIRECTORY_PATH_ROOT . $aSearchResult['file']);
  162. }
  163. return new $sClassName();
  164. }
  165. protected function getKeyTitlesPairs ()
  166. {
  167. $a = array();
  168. foreach ($this->aChoice as $sKey => $r)
  169. if ($this->_sMetaType || $r['GlobalSearch'])
  170. $a[$sKey] = _t($r['title']);
  171. return $a;
  172. }
  173. public function setLiveSearch($bLiveSearch)
  174. {
  175. $this->_bLiveSearch = $bLiveSearch;
  176. }
  177. public function setMetaType($s)
  178. {
  179. $aMetaTypes = array('location_country', 'location_country_city', 'location_country_state', 'mention', 'keyword');
  180. if (in_array($s, $aMetaTypes))
  181. $this->_sMetaType = $s;
  182. }
  183. public function setCategoryObject($s)
  184. {
  185. $this->_sCategoryObject = $s;
  186. }
  187. /**
  188. * Set custom search condition to use istead of GET/POST variables
  189. * @param $a array of params, such as 'keyword', 'state', 'city'
  190. * @return nothing
  191. */
  192. public function setCustomSearchCondition($a)
  193. {
  194. $this->_aCustomSearchCondition = $a;
  195. }
  196. /**
  197. * Set custom data for aCurrent array
  198. * @param $a array of params
  199. * @return nothing
  200. */
  201. public function setCustomCurrentCondition($a)
  202. {
  203. $this->_aCustomCurrentCondition = $a;
  204. }
  205. /**
  206. * Set custom unit template
  207. * @param $s template name
  208. * @return nothing
  209. */
  210. public function setUnitTemplate($s)
  211. {
  212. $this->_sUnitTemplate = $s;
  213. }
  214. /**
  215. * Display search results without design box and paginate
  216. */
  217. public function setRawProcessing($b)
  218. {
  219. $this->_bRawProcessing = $b;
  220. }
  221. /**
  222. * Return search result as array of data
  223. */
  224. public function setDataProcessing($b)
  225. {
  226. $this->_bDataProcessing = $b;
  227. }
  228. }
  229. /*
  230. * Search class for processing search requests and displaying search results.
  231. *
  232. * Allows present content from modules on search params or internal (via fields of class) conditions.
  233. *
  234. * Example of usage (you can see example in any of default Dolhpin's modules):
  235. *
  236. * 1. Extends your own search class from this one (or from BxBaseSearchResult or BxBaseSearchResultSharedMedia classes)
  237. * 2. Set necessary fields of class (using as example BxFilesSearch):
  238. *
  239. * @code
  240. *
  241. * // main field of search class
  242. * $this->aCurrent = array(
  243. *
  244. * // name of module
  245. * 'name' => 'bx_files',
  246. *
  247. * // language key with name of module
  248. * 'title' => '_bx_files',
  249. *
  250. * // main content table
  251. * 'table' => 'bx_files_main',
  252. *
  253. * // array of all fields which can be choosen for select in result query
  254. * 'ownFields' => array('ID', 'Title', 'Uri', 'Desc', 'Date', 'Size', 'Ext', 'Views', 'Rate', 'RateCount', 'Type'),
  255. *
  256. * // array of fields which take a part in search by keyword (global search and related words only - in other cases leave it blank)
  257. * 'searchFields' => array('Title', 'Tags', 'Desc', 'Categories'),
  258. *
  259. * // array of join tables
  260. * // 'type' - type of join
  261. * // 'table' - join table
  262. * // 'mainField' - field from main table for 'on' condition
  263. * // 'onField' - field from joining table for 'on' condition
  264. * // 'joinFields' - array of fields from joining table
  265. *
  266. * 'join' => array(
  267. * 'profile' => array(
  268. * 'type' => 'left',
  269. * 'table' => 'Profiles',
  270. * 'mainField' => 'Owner',
  271. * 'onField' => 'ID',
  272. * 'joinFields' => array('NickName'),
  273. * ),
  274. * // ...
  275. * ),
  276. *
  277. * // array of search parameters
  278. * // 'value' - value of search parameter (can be number, string or array)
  279. * // '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
  280. * // 'operator' - operator between field and value (can be 'in', 'not in', '>', '<', 'against', 'like' and '=' by default),
  281. * // 'paramName' - GET param which will keep 'value' for pagianation
  282. *
  283. * 'restriction' => array(
  284. * 'activeStatus' => array('value'=>'approved', 'field'=>'Status', 'operator'=>'=', 'paramName' => 'status'),
  285. * 'albumType' => array('value'=>'', 'field'=>'Type', 'operator'=>'=', 'paramName'=>'albumType', 'table'=>'sys_albums'),
  286. * ),
  287. *
  288. * // array of pagination
  289. * // 'perPage' - units per page
  290. * // 'start' - show search results starting from this number
  291. * // 'num' - number of element to show on current page + 1
  292. *
  293. * 'paginate' => array('perPage' => 10, 'start' => 0, 'num' => 11),
  294. *
  295. * // sort mode - by default it was last (DESC by date)
  296. * 'sorting' => 'last',
  297. *
  298. * // mode of units presentation in search result, can be 'short' or 'full' view
  299. * 'view' => 'full',
  300. *
  301. * // field of id
  302. * 'ident' => 'ID',
  303. *
  304. * // rss feed array
  305. * 'rss' => array(
  306. * 'title' => '',
  307. * 'link' => '',
  308. * 'image' => '',
  309. * 'profile' => 0,
  310. * 'fields' => array (
  311. * 'Link' => '',
  312. * 'Title' => 'Title',
  313. * 'DateTimeUTS' => 'Date',
  314. * 'Desc' => 'Desc',
  315. * 'Photo' => '',
  316. * ),
  317. * ),
  318. * );
  319. *
  320. * // array of fields renamings
  321. * $aPseud - filling in costructor by function _getPseud
  322. *
  323. * // unique identificator from `sys_objects_search` table
  324. * $id;
  325. *
  326. * @endcode
  327. *
  328. * Memberships/ACL:
  329. * Doesn't depend on user's membership.
  330. *
  331. * Alerts:
  332. * no alerts available
  333. *
  334. */
  335. class BxDolSearchResult implements iBxDolReplaceable
  336. {
  337. public $aCurrent; ///< search results configuration
  338. protected $aPseud; ///< array of fields renamings
  339. protected $id; ///< unique identificator of block on mixed search results page
  340. protected $bDisplayEmptyMsg = false; ///< display empty message instead of nothing, when no results
  341. protected $sDisplayEmptyMsgKey = ''; ///< custom empty message language key, instead of default "empty" message
  342. protected $bProcessPrivateContent = true; ///< check each item for privacy, if view isn't allowed then display private view instead
  343. protected $aPrivateConditionsIndexes = array('restriction' => array(), 'join' => array()); ///< conditions indexes for bProcessPrivateContent
  344. protected $bForceAjaxPaginate = false; ///< force ajax paginate
  345. protected $iPaginatePerPage = BX_DOL_SEARCH_RESULTS_PER_PAGE_DEFAULT; ///< default 'per page' value for paginate.
  346. protected $_bIsApi;
  347. protected $_bSingleSearch = true;
  348. protected $_bLiveSearch = false;
  349. protected $_sMetaType = '';
  350. protected $_sMode = '';
  351. protected $_aParams = [];
  352. protected $_sCategoryObject = '';
  353. protected $_aCustomSearchCondition = array();
  354. protected $_aMarkers = array (); ///< markers to replace somewhere, usually title and browse url (defined in custom class)
  355. /**
  356. * constructor
  357. * filling identificator field
  358. */
  359. function __construct ()
  360. {
  361. $this->_bIsApi = bx_is_api();
  362. if (isset($this->aPseud['id']))
  363. $this->aCurrent['ident'] = $this->aPseud['id'];
  364. }
  365. public function getId()
  366. {
  367. return $this->id;
  368. }
  369. public function setId($sId)
  370. {
  371. $this->id = $sId;
  372. }
  373. public function getModuleName()
  374. {
  375. return isset($this->aCurrent['module_name']) ? $this->aCurrent['module_name'] : '';
  376. }
  377. public function getContentInfoName()
  378. {
  379. return isset($this->aCurrent['name']) ? $this->aCurrent['name'] : '';
  380. }
  381. public function setAjaxPaginate($b = true)
  382. {
  383. $this->bForceAjaxPaginate = $b;
  384. }
  385. public function setPaginatePerPage($iPerPage)
  386. {
  387. $this->iPaginatePerPage = $iPerPage;
  388. }
  389. public function setSingleSearch($bSingleSearch)
  390. {
  391. $this->_bSingleSearch = $bSingleSearch;
  392. }
  393. public function setLiveSearch($bLiveSearch)
  394. {
  395. $this->_bLiveSearch = $bLiveSearch;
  396. }
  397. public function setMetaType($s)
  398. {
  399. $this->_sMetaType = $s;
  400. }
  401. public function isMetaEnabled($s)
  402. {
  403. if (empty($this->aCurrent['object_metatags']))
  404. return false;
  405. if (!($o = BxDolMetatags::getObjectInstance($this->aCurrent['object_metatags'])))
  406. return false;
  407. switch ($s) {
  408. case 'location_country_city':
  409. case 'location_country_state':
  410. case 'location_country':
  411. return $o->locationsIsEnabled();
  412. case 'mention':
  413. return $o->mentionsIsEnabled();
  414. case 'keyword':
  415. return $o->keywordsIsEnabled();
  416. }
  417. return false;
  418. }
  419. public function setCategoryObject($s)
  420. {
  421. $this->_sCategoryObject = $s;
  422. }
  423. public function setCustomSearchCondition($a)
  424. {
  425. $this->_aCustomSearchCondition = $a;
  426. }
  427. public function setCustomCurrentCondition($a)
  428. {
  429. $this->aCurrent = array_merge_recursive($this->aCurrent, $a);
  430. }
  431. public function setCategoriesCondition($sKeyword)
  432. {
  433. $this->aCurrent['join']['multicat'] = array(
  434. 'type' => 'INNER',
  435. 'table' => 'sys_categories2objects',
  436. 'mainField' => 'id',
  437. 'onField' => 'object_id',
  438. 'joinFields' => array(),
  439. );
  440. if (isset($this->aCurrent['tableSearch'])){
  441. $this->aCurrent['join']['multicat']['mainTable'] = $this->aCurrent['tableSearch'];
  442. }
  443. $this->aCurrent['join']['multicat2'] = array(
  444. 'type' => 'INNER',
  445. 'table' => 'sys_categories',
  446. 'mainField' => 'category_id',
  447. 'mainTable' => 'sys_categories2objects',
  448. 'onField' => 'id',
  449. 'joinFields' => array(),
  450. );
  451. $this->aCurrent['restriction']['multicat'] = array('value' => $sKeyword, 'field' => 'value', 'operator' => '=', 'table' => 'sys_categories');
  452. }
  453. /**
  454. * Display empty message if there is no content, custom empty message can be used.
  455. * @param $b - boolan value to enable or disable 'empty' message
  456. * @param $sLangKey [optional] - custom 'empty' message
  457. */
  458. public function setDisplayEmptyMsg($b, $sLangKey = '')
  459. {
  460. $this->bDisplayEmptyMsg = $b;
  461. if ($sLangKey)
  462. $this->sDisplayEmptyMsgKey = $sLangKey;
  463. }
  464. /**
  465. * Perform privacy checking for every unit
  466. * @param $b - boolan value to enable or disable privacy checking
  467. */
  468. public function setProcessPrivateContent ($b)
  469. {
  470. $this->bProcessPrivateContent = $b;
  471. if ($b) {
  472. // unset condition which was set when 'bProcessPrivateContent' was set to 'false'
  473. foreach ($this->aPrivateConditionsIndexes['restriction'] as $sKey)
  474. unset($this->aCurrent['restriction'][$sKey]);
  475. foreach ($this->aPrivateConditionsIndexes['join'] as $sKey)
  476. unset($this->aCurrent['join'][$sKey]);
  477. }
  478. }
  479. /**
  480. * Get search results without design box and paginate
  481. * @return html code
  482. */
  483. function processingRaw ()
  484. {
  485. $sCode = $this->displayResultBlock();
  486. return $this->aCurrent['paginate']['num'] > 0 ? $sCode : '';
  487. }
  488. /**
  489. * Get html box of search results (usually used in grlobal search)
  490. * @return html code
  491. */
  492. function processing ()
  493. {
  494. if($this->_bIsApi)
  495. return $this->processingAPI();
  496. $sCode = $this->displayResultBlock();
  497. if ($this->aCurrent['paginate']['num'] > 0) {
  498. $sPaginate = $this->showPagination();
  499. $sCode = $this->displaySearchBox($sCode, $sPaginate);
  500. }
  501. else {
  502. $sCode = $this->bDisplayEmptyMsg ? $this->displaySearchBox($this->displayResultBlockEmpty()) : '';
  503. }
  504. return $sCode;
  505. }
  506. function processingAPI ($bForceGetData = false)
  507. {
  508. $sModule = 'system';
  509. $sUnitType = 'content';
  510. $sHomeUrl = '';
  511. if(!empty($this->oModule)) {
  512. $sModule = $this->oModule->getName();
  513. if(method_exists($this->oModule, 'serviceActAsProfile') && $this->oModule->serviceActAsProfile())
  514. $sUnitType = 'profile';
  515. if(method_exists($this->oModule, 'serviceIsGroupProfile') && $this->oModule->serviceIsGroupProfile())
  516. $sUnitType = 'context';
  517. $sHomeUrl = bx_api_get_relative_url(BxDolPermalinks::getInstance()->permalink($this->oModule->_oConfig->CNF['URL_HOME']));
  518. }
  519. $sUnit = 'list';
  520. if(in_array($this->sUnitViewDefault, ['showcase', 'gallery']))
  521. $sUnit = 'card';
  522. $aData = defined('BX_API_PAGE') && !$bForceGetData ? [] : $this->decodeDataAPI($this->getSearchData());
  523. $aParams = [
  524. 'per_page' => $this->aCurrent['paginate']['perPage'],
  525. 'start' => $this->aCurrent['paginate']['start'],
  526. 'type' => $this->_sMode,
  527. 'view' => $this->_aParams['unit_view']
  528. ];
  529. if ($sHomeUrl){
  530. $aParams['home_url'] = $sHomeUrl;
  531. }
  532. foreach(['author', 'category', 'context', 'joined_profile', 'followed_contexts', 'level'] as $sParamAdd)
  533. if(isset($this->_aParams[$sParamAdd]))
  534. $aParams[$sParamAdd] = $this->_aParams[$sParamAdd];
  535. return [
  536. 'module' => $sModule,
  537. 'unit' => 'general-' . $sUnitType . '-' . $sUnit,
  538. 'request_url' => !empty($this->aCurrent['api_request_url']) ? $this->aCurrent['api_request_url'] : '/api.php?r=' . $sModule . '/browse/&params[]=',
  539. 'data' => $aData,
  540. 'params' => $aParams
  541. ];
  542. }
  543. function decodeDataAPI ($a)
  544. {
  545. return $a;
  546. }
  547. /**
  548. * Get html output of search result
  549. * @return html code
  550. */
  551. function displayResultBlock ()
  552. {
  553. $aData = $this->getSearchData();
  554. $sCode = '';
  555. if (count($aData) > 0) {
  556. $sCode = $this->addCustomParts();
  557. foreach ($aData as $iKey => $aValue) {
  558. $sCode .= $this->displaySearchUnit($aValue);
  559. }
  560. }
  561. return $sCode;
  562. }
  563. /**
  564. * Get html output of empty search result
  565. * @return html code
  566. */
  567. function displayResultBlockEmpty ()
  568. {
  569. return MsgBox(_t($this->sDisplayEmptyMsgKey ? $this->sDisplayEmptyMsgKey : '_Empty'));
  570. }
  571. /**
  572. * Add different code before html output (usually redeclared)
  573. * no return result
  574. */
  575. function addCustomParts ()
  576. {
  577. }
  578. /**
  579. * Get XML string for rss output
  580. */
  581. function rss ()
  582. {
  583. if (!isset($this->aCurrent['rss']['fields']) || !isset($this->aCurrent['rss']['link']))
  584. return '';
  585. $aData = $this->getSearchData();
  586. $f = &$this->aCurrent['rss']['fields'];
  587. if ($aData) {
  588. foreach ($aData as $k => $a) {
  589. $aData[$k][$f['Link']] = $this->getRssUnitLink ($a);
  590. if(isset($f['Image']))
  591. $aData[$k][$f['Image']] = $this->getRssUnitImage ($a, $f['Image']);
  592. }
  593. }
  594. $oRss = new BxDolRssFactory ();
  595. return $oRss->GenRssByCustomData(
  596. $aData,
  597. isset($this->aCurrent['rss']['title']) && $this->aCurrent['rss']['title'] ? $this->aCurrent['rss']['title'] : $this->aCurrent['title'],
  598. $this->aCurrent['rss']['link'],
  599. $this->aCurrent['rss']['fields'],
  600. isset($this->aCurrent['rss']['image']) ? $this->aCurrent['rss']['image'] : '',
  601. isset($this->aCurrent['rss']['profile']) ? $this->aCurrent['rss']['profile'] : 0
  602. );
  603. }
  604. /**
  605. * Output RSS XML with XML header
  606. */
  607. function outputRSS ()
  608. {
  609. header('Content-Type: text/xml; charset=UTF-8');
  610. echo $this->rss();
  611. }
  612. /**
  613. * Return rss unit link (redeclared)
  614. */
  615. function getRssUnitLink (&$a)
  616. {
  617. // override this functions to return permalink to rss unit
  618. }
  619. /**
  620. * Return rss unit image (redeclared)
  621. */
  622. function getRssUnitImage (&$a, $sField)
  623. {
  624. // override this functions to return image for rss unit
  625. }
  626. /**
  627. * Naming fields in query's body
  628. * @param string $sFieldName name of field
  629. * @param string $sTableName name of field's table
  630. * $param string $sOperator of field's calculation (like MAX)
  631. * @param boolean $bRenameMode indicator for renaming and unsetting fields from field of class $this->aPseud
  632. * return $sqlUnit sql code and unsetting elements from aPseud field
  633. */
  634. function setFieldUnit ($sFieldName, $sTableName, $sOperator = '', $bRenameMode = true)
  635. {
  636. $bOperator = !empty($sOperator);
  637. $sqlUnit = "`$sTableName`.`$sFieldName`";
  638. if($bOperator)
  639. $sqlUnit = $sOperator . '(' . $sqlUnit . ')';
  640. if(!empty($this->aPseud) && $bRenameMode !== false && ($sKey = array_search($sFieldName . ($bOperator ? '_' . strtolower($sOperator) : ''), $this->aPseud)) !== false) {
  641. $sqlUnit .= " as `$sKey`";
  642. unset($this->aPseud[$sKey]);
  643. }
  644. return $sqlUnit . ', ';
  645. }
  646. /**
  647. * Get html code of of every search unit
  648. * @param array $aData array of every search unit
  649. * return html code
  650. */
  651. function displaySearchUnit ($aData)
  652. {
  653. }
  654. /**
  655. * Get html code of search box with search results
  656. * @param string $sCode html code of search results
  657. * $param $sPaginate html code of paginate
  658. * return html code
  659. */
  660. function displaySearchBox ($sCode, $sPaginate = '')
  661. {
  662. }
  663. /**
  664. * Get html code of pagination
  665. */
  666. function showPagination ($bAdmin = false, $bChangePage = true, $bPageReload = true)
  667. {
  668. }
  669. /**
  670. * Get array of data with search results
  671. * return array with data
  672. */
  673. function getSearchData ()
  674. {
  675. /**
  676. * @hooks
  677. * @hookdef hook-simple_search-before_get_data 'simple_search', 'before_get_data' - hook on before after get data
  678. * - $unit_name - equals `simple_search`
  679. * - $action - equals `before_get_data`
  680. * - $object_id - not used
  681. * - $sender_id - not used
  682. * - $extra_params - array of additional params with the following array keys:
  683. * - `object` - [array] by ref, array of parameters, can be overridden in hook processing
  684. * - `mode` - [string] search mode
  685. * @hook @ref hook-simple_search-before_get_data
  686. */
  687. bx_alert('simple_search', 'before_get_data', 0, false, [
  688. 'object' => &$this->aCurrent,
  689. 'mode' => $this->_sMode
  690. ]);
  691. if(($this->aPseud = $this->_getPseudFromParam()) === false)
  692. $this->aPseud = $this->_getPseud();
  693. $this->setConditionParams();
  694. $aData = $this->aCurrent['paginate']['num'] > 0 ? $this->getSearchDataByParams() : [];
  695. /**
  696. * @hooks
  697. * @hookdef hook-simple_search-get_data 'simple_search', 'get_data' - hook on after get data
  698. * - $unit_name - equals `simple_search`
  699. * - $action - equals `get_data`
  700. * - $object_id - not used
  701. * - $sender_id - not used
  702. * - $extra_params - array of additional params with the following array keys:
  703. * - `object` - [array] by ref, array of parameters, can be overridden in hook processing
  704. * - `mode` - [string] search mode
  705. * - `search_object` - [string] search object name
  706. * @hook @ref hook-simple_search-get_data
  707. */
  708. bx_alert('simple_search', 'get_data', 0, false, [
  709. 'object' => &$this->aCurrent,
  710. 'mode' => $this->_sMode,
  711. 'search_results' => &$aData
  712. ]);
  713. return $aData;
  714. }
  715. /**
  716. * Get query [query, limit] for search results. Is used for combined search from different sections.
  717. * @param type $aParams array with params
  718. * @return type array with query and limit
  719. */
  720. function getSearchQuery($sObject, $aParams = [])
  721. {
  722. if(!is_array($aParams))
  723. $aParams = [];
  724. $aParams = array_merge($aParams, ['for_union' => true]);
  725. $this->aPseud = [
  726. 'id' => !empty($this->aCurrent['ident']) ? $this->aCurrent['ident'] : 'id',
  727. 'added' => !empty($this->aCurrent['added']) ? $this->aCurrent['added'] : 'added'
  728. ];
  729. $this->setConditionParams();
  730. $aQuery = $this->getSearchDataByParams($aParams);
  731. /**
  732. * @hooks
  733. * @hookdef hook-simple_search-get_query 'simple_search', 'get_query' - hook on get sql queries
  734. * - $unit_name - equals `simple_search`
  735. * - $action - equals `get_query`
  736. * - $object_id - not used
  737. * - $sender_id - not used
  738. * - $extra_params - array of additional params with the following array keys:
  739. * - `object` - [array] by ref, array of parameters, can be overridden in hook processing
  740. * - `mode` - [string] search mode
  741. * - `search_object` - [string] search object name
  742. * - `search_query` - [array] by ref, array of sql, can be overridden in hook processing
  743. * @hook @ref hook-simple_search-get_query
  744. */
  745. bx_alert('simple_search', 'get_query', 0, false, [
  746. 'object' => &$this->aCurrent,
  747. 'mode' => $this->_sMode,
  748. 'search_object' => $sObject,
  749. 'search_query' => &$aQuery
  750. ]);
  751. return $aQuery;
  752. }
  753. function getFieldsOwn()
  754. {
  755. return false;
  756. }
  757. function getFieldsJoin($sJoin)
  758. {
  759. return false;
  760. }
  761. /**
  762. * Get array with code for sql elements
  763. * @param $bRenameMode indicator of renmaing fields
  764. * return array with joinFields, ownFields, groupBy and join elements
  765. */
  766. function getJoins ($bRenameMode = true)
  767. {
  768. if(!isset($this->aCurrent['join']) || !is_array($this->aCurrent['join']))
  769. return false;
  770. $aSql = [
  771. 'join' => '',
  772. 'ownFields' => '',
  773. 'joinFields' => '',
  774. 'groupBy' => '',
  775. 'groupHaving' => ''
  776. ];
  777. foreach($this->aCurrent['join'] as $sKey => $aValue) {
  778. $sAlias = isset($aValue['table_alias']) ? $aValue['table_alias'] : $aValue['table'];
  779. $sTableAlias = isset($aValue['table_alias']) ? " AS {$aValue['table_alias']} " : '';
  780. $sOperator = isset($aValue['operator']) ? $aValue['operator'] : null;
  781. // joinFields
  782. $aJoinFields = $this->getFieldsJoin($sKey);
  783. if($aJoinFields === false && !empty($aValue['joinFields']) && is_array($aValue['joinFields']))
  784. $aJoinFields = $aValue['joinFields'];
  785. if($aJoinFields)
  786. foreach($aJoinFields as $mixedField) {
  787. list($sFldName, $sFldOperator) = is_array($mixedField) ? $mixedField : [$mixedField, $sOperator];
  788. $aSql['joinFields'] .= $this->setFieldUnit($sFldName, $sAlias, $sFldOperator, $bRenameMode);
  789. }
  790. // group by
  791. if(isset($aValue['groupTable']))
  792. $aSql['groupBy'] .= "`{$aValue['groupTable']}`.`{$aValue['groupField']}`, ";
  793. // having
  794. if(isset($aValue['groupHaving']))
  795. $aSql['groupHaving'] .= $aValue['groupHaving'];
  796. $sOn = isset($aValue['mainTable']) ? $aValue['mainTable'] : $this->aCurrent['table'];
  797. $aSql['join'] .= " {$aValue['type']} JOIN `{$aValue['table']}` $sTableAlias ON " . (!empty($aValue['on_sql']) ? $aValue['on_sql'] : "`{$sAlias}`.`{$aValue['onField']}`=" . trim($this->setFieldUnit($aValue['mainField'], $sOn, isset($aValue['mainFieldFunc']) ? $aValue['mainFieldFunc'] : '', false), ", "));
  798. $aSql['ownFields'] .= $this->setFieldUnit($aValue['mainField'], $sOn, '', $bRenameMode);
  799. }
  800. $aSql['joinFields'] = trim($aSql['joinFields'], ', ');
  801. if(!empty($aSql['groupBy']))
  802. $aSql['groupBy'] = trim('GROUP BY ' . $aSql['groupBy'], ', ');
  803. if(!empty($aSql['groupHaving']))
  804. $aSql['groupHaving'] = 'HAVING ' . $aSql['groupHaving'];
  805. return $aSql;
  806. }
  807. /**
  808. * Concat sql parts of query, run it and return result array
  809. * @param $aParams addon param
  810. * return $aData multivariate array
  811. */
  812. function getSearchDataByParams ($aParams = '')
  813. {
  814. $bForUnion = isset($aParams['for_union']) && $aParams['for_union'] === true;
  815. $aSql = [
  816. 'ownFields' => '',
  817. 'order' => ''
  818. ];
  819. // searchFields
  820. if($bForUnion) {
  821. $sTable = isset($this->aCurrent['tableSearch']) ? $this->aCurrent['tableSearch'] : $this->aCurrent['table'];
  822. $aSql['ownFields'] .= $this->setFieldUnit(!empty($this->aCurrent['ident']) ? $this->aCurrent['ident'] : 'id', $sTable);
  823. $aSql['ownFields'] .= $this->setFieldUnit(!empty($this->aCurrent['added']) ? $this->aCurrent['added'] : 'added', $sTable);
  824. $aSql['ownFields'] .= "'" . $this->getContentInfoName() . "' AS `content_info`";
  825. }
  826. else {
  827. $aOwnFields = $this->getFieldsOwn();
  828. if($aOwnFields === false)
  829. $aOwnFields = $this->aCurrent['ownFields'];
  830. foreach($aOwnFields as $mixedField) {
  831. list($sFldName, $sFldOperator) = is_array($mixedField) ? $mixedField : [$mixedField, ''];
  832. $aSql['ownFields'] .= $this->setFieldUnit($sFldName, $this->aCurrent['table'], $sFldOperator);
  833. }
  834. }
  835. // joinFields & join
  836. if(($aJoins = $this->getJoins()) !== false) {
  837. if(!$bForUnion) {
  838. $aSql['ownFields'] .= $aJoins['ownFields'];
  839. $aSql['ownFields'] .= $aJoins['joinFields'];
  840. }
  841. $aSql['join'] = $aJoins['join'];
  842. $aSql['groupBy'] = $aJoins['groupBy'];
  843. $aSql['groupHaving'] = $aJoins['groupHaving'];
  844. }
  845. $aSql['ownFields'] = trim($aSql['ownFields'], ', ');
  846. // from
  847. $aSql['from'] = " FROM `{$this->aCurrent['table']}`";
  848. // where
  849. $aSql['where'] = $this->getRestriction();
  850. // limit
  851. $aSql['limit'] = $this->getLimit();
  852. // sorting
  853. $this->setSorting();
  854. $aSort = $this->getSorting($this->aCurrent['sorting']);
  855. foreach ($aSort as $sKey => $sValue)
  856. $aSql[$sKey] .= $sValue;
  857. // execution
  858. $sqlQuery = 'SELECT';
  859. if(isset($this->aCurrent['distinct']) && $this->aCurrent['distinct'] === true)
  860. $sqlQuery .= ' DISTINCT';
  861. $sqlQuery .= ' ' . $aSql['ownFields'];
  862. $sqlQuery .= ' ' . $aSql['from'];
  863. if (isset($aSql['join']))
  864. $sqlQuery .= ' ' . $aSql['join'];
  865. if (isset($aSql['where']))
  866. $sqlQuery .= ' ' . $aSql['where'];
  867. if (isset($aSql['groupBy']))
  868. $sqlQuery .= ' ' . $aSql['groupBy'];
  869. if (isset($aSql['groupHaving']))
  870. $sqlQuery .= ' ' . $aSql['groupHaving'];
  871. if($bForUnion)
  872. return [
  873. 'query' => $sqlQuery,
  874. 'limit' => $aSql['limit']
  875. ];
  876. if (isset($aSql['order']))
  877. $sqlQuery .= ' ' . $aSql['order'];
  878. if (isset($aSql['limit']))
  879. $sqlQuery .= ' ' . $aSql['limit'];
  880. //echoDbg($sqlQuery);
  881. $aRes = BxDolDb::getInstance()->getAll($sqlQuery);
  882. return $aRes;
  883. }
  884. /**
  885. * Set class fields condition params and paginate array
  886. */
  887. function setConditionParams()
  888. {
  889. $this->aCurrent['paginate']['num'] = 0;
  890. // keyword
  891. $sKeyword = bx_process_input(isset($this->_aCustomSearchCondition['keyword']) ? $this->_aCustomSearchCondition['keyword'] : bx_get('keyword'));
  892. $bKeyword = !empty($sKeyword);
  893. if ($this->_bLiveSearch && !$bKeyword)
  894. return;
  895. if ($bKeyword) {
  896. if (substr($sKeyword, 0, 1) == '@') {
  897. $sModule = $this->aCurrent['module_name'];
  898. $sMethod = 'act_as_profile';
  899. if(!bx_is_srv($sModule, $sMethod) || !bx_srv($sModule, $sMethod))
  900. return;
  901. $sKeyword = substr($sKeyword, 1);
  902. }
  903. $this->aCurrent['restriction']['keyword'] = array(
  904. 'value' => $sKeyword,
  905. 'field' => '',
  906. 'operator' => 'against'
  907. );
  908. // for search results we need to show all items, not only public content
  909. $this->setProcessPrivateContent(true);
  910. }
  911. // owner
  912. if (isset($_GET['ownerName'])) {
  913. $sName = bx_process_input($_GET['ownerName']);
  914. $iUser = (int)BxDolProfileQuery::getInstance()->getIdByNickname($sName);
  915. BxDolMenu::getInstance()->setCurrentProfileID($iUser);
  916. } elseif (isset($_GET['userID']))
  917. $iUser = bx_process_input($_GET['userID'], BX_DATA_INT);
  918. if (!empty($iUser))
  919. $this->aCurrent['restriction']['owner']['value'] = $iUser;
  920. // meta info
  921. if ($this->_sMetaType && !empty($this->aCurrent['object_metatags'])) {
  922. $o = BxDolMetatags::getObjectInstance($this->aCurrent['object_metatags']);
  923. if ($o) {
  924. unset($this->aCurrent['restriction']['keyword']);
  925. $aLocationString = [];
  926. switch ($this->_sMetaType) {
  927. case 'location_country':
  928. $aLocationString['country'] = $sKeyword;
  929. $o->locationsSetSearchCondition($this, $sKeyword);
  930. break;
  931. case 'location_country_state':
  932. $aLocationString['country'] = $sKeyword;
  933. $aLocationString['state'] = bx_process_input(isset($this->_aCustomSearchCondition['state']) ? $this->_aCustomSearchCondition['state'] : bx_get('state'));
  934. $o->locationsSetSearchCondition($this, $sKeyword, $aLocationString['state']);
  935. break;
  936. case 'location_country_city':
  937. $aLocationString['country'] = $sKeyword;
  938. $aLocationString['state'] = bx_process_input(isset($this->_aCustomSearchCondition['state']) ? $this->_aCustomSearchCondition['state'] : bx_get('state'));
  939. $aLocationString['city'] = bx_process_input(isset($this->_aCustomSearchCondition['city']) ? $this->_aCustomSearchCondition['city'] : bx_get('city'));
  940. $o->locationsSetSearchCondition($this, $sKeyword, $aLocationString['state'], $aLocationString['city']);
  941. break;
  942. case 'location_state':
  943. $aLocationString['state'] = $sKeyword;
  944. $o->locationsSetSearchCondition($this, false, $sKeyword);
  945. break;
  946. case 'location_city':
  947. $aLocationString['city'] = $sKeyword;
  948. $o->locationsSetSearchCondition($this, false, false, $sKeyword);
  949. break;
  950. case 'mention':
  951. $oCmts = !empty($this->sModuleObjectComments) ? BxDolCmts::getObjectInstance($this->sModuleObjectComments, 0, false) : false;
  952. $o->mentionsSetSearchCondition($this, $sKeyword, $oCmts ? $oCmts->getSystemId() : 0);
  953. if(($oProfile = BxDolProfile::getInstance((int)$sKeyword)) !== false)
  954. $this->_setPageDescription('_sys_page_description_mention', $oProfile->getDisplayName(), $this->aCurrent['title']);
  955. break;
  956. case 'keyword':
  957. $oCmts = !empty($this->sModuleObjectComments) ? BxDolCmts::getObjectInstance($this->sModuleObjectComments, 0, false) : false;
  958. $o->keywordsSetSearchCondition($this, $sKeyword, $oCmts ? $oCmts->getSystemId() : 0);
  959. $this->_setPageDescription('_sys_page_description_hashtag', $sKeyword, $this->aCurrent['title']);
  960. break;
  961. }
  962. if(in_array($this->_sMetaType, ['location_country', 'location_country_state', 'location_country_city', 'location_state', 'location_city']))
  963. $this->_setPageDescription('_sys_page_description_location', $o->locationsStringFromArray($aLocationString, false), $this->aCurrent['title']);
  964. }
  965. }
  966. // category
  967. if ($this->_sCategoryObject) {
  968. if(($o = BxDolCategory::getObjectInstance($this->_sCategoryObject)) && $this->_bSingleSearch) {
  969. if ($this->aCurrent['name'] == $o->getSearchObject()) {
  970. unset($this->aCurrent['restriction']['keyword']);
  971. $o->setSearchCondition($this, $sKeyword);
  972. }
  973. $this->_setPageDescription('_sys_page_description_category', $o->getCategoryTitle($sKeyword), $this->aCurrent['title']);
  974. }
  975. if ($this->_sCategoryObject == 'multi'){
  976. unset($this->aCurrent['restriction']['keyword']);
  977. $this->setCategoriesCondition($sKeyword);
  978. }
  979. }
  980. if($bKeyword && !$this->_sMetaType && !$this->_sCategoryObject)
  981. $this->_setPageDescription('_sys_page_description_keyword', $sKeyword, $this->aCurrent['title']);
  982. $this->setPaginate();
  983. $iNum = $this->getNum();
  984. if ($iNum > 0)
  985. $this->aCurrent['paginate']['num'] = $iNum;
  986. }
  987. /**
  988. * Check number of records on current page
  989. * return number of records on current page + 1
  990. */
  991. function getNum ()
  992. {
  993. $aJoins = $this->getJoins(false);
  994. $sqlQuery = "SELECT * FROM `{$this->aCurrent['table']}` " . (isset($aJoins['join']) ? ' ' . $aJoins['join'] : '' ) . $this->getRestriction() . (isset($aJoins['groupBy']) ? ' ' . $aJoins['groupBy'] : '') . ' ' . $this->getLimit(true);
  995. return count(BxDolDb::getInstance()->getAll($sqlQuery));
  996. }
  997. /**
  998. * Get total number of records
  999. * return total number of records
  1000. */
  1001. function getTotal ()
  1002. {
  1003. $aJoins = $this->getJoins(false);
  1004. $sqlQuery = "SELECT COUNT(*) FROM `{$this->aCurrent['table']}` " . (isset($aJoins['join']) ? ' ' . $aJoins['join'] : '' ) . $this->getRestriction() . (isset($aJoins['groupBy']) ? ' ' . $aJoins['groupBy'] : '');
  1005. return BxDolDb::getInstance()->getOne($sqlQuery);
  1006. }
  1007. /**
  1008. * Check restriction params and make condition part of query
  1009. * return $sqlWhere sql code of query for WHERE part
  1010. */
  1011. function getRestriction ()
  1012. {
  1013. $oDb = BxDolDb::getInstance();
  1014. $sqlWhere = '';
  1015. if (isset($this->aCurrent['restriction'])) {
  1016. $aWhere[] = '1';
  1017. foreach ($this->aCurrent['restriction'] as $sKey => $aValue) {
  1018. $sqlCondition = '';
  1019. if (isset($aValue['operator']) && isset($aValue['value']) && $aValue['value'] !== '' && $aValue['value'] !== false && $aValue['value'] !== null) {
  1020. $sFieldTable = isset($aValue['table']) ? $aValue['table'] : $this->aCurrent['table'];
  1021. $sqlCondition = "`{$sFieldTable}`.`{$aValue['field']}` ";
  1022. switch ($aValue['operator']) {
  1023. case 'empty value':
  1024. $sqlCondition .= " = '' ";
  1025. break;
  1026. case 'not empty value':
  1027. $sqlCondition .= " != '' ";
  1028. break;
  1029. case 'nothing':
  1030. $sqlCondition = " 0 ";
  1031. break;
  1032. case 'against':
  1033. $aCond = isset($aValue['field']) && strlen($aValue['field']) > 0 ? $aValue['field'] : $this->aCurrent['searchFields'];
  1034. $sqlCondition = !empty($aCond) ? $this->getSearchFieldsCond($aCond, $aValue['value']) : "";
  1035. break;
  1036. case 'like':
  1037. $sqlCondition .= "LIKE " . $oDb->escape('%' . $aValue['value'] . '%');
  1038. break;
  1039. case 'in':
  1040. case 'not in':
  1041. $sValuesString = $this->getMultiValues($aValue['value']);
  1042. $sqlCondition .= strtoupper($aValue['operator']) . '(' . $sValuesString . ')';
  1043. break;
  1044. case 'in_set':
  1045. $sqlCondition = "1 << (" . $sqlCondition . " - 1) & " . (int)$aValue['value'];
  1046. break;
  1047. default:
  1048. $sqlCondition .= $aValue['operator'] . (isset($aValue['no_quote_value']) && $aValue['no_quote_value'] ? $aValue['value'] : $oDb->escape($aValue['value']));
  1049. break;
  1050. }
  1051. }
  1052. if (strlen($sqlCondition) > 0)
  1053. $aWhere[] = $sqlCondition;
  1054. }
  1055. $sqlWhere .= "WHERE ". implode(' AND ', $aWhere) . (isset($this->aCurrent['restriction_sql']) ? $this->aCurrent['restriction_sql'] : '');
  1056. }
  1057. return $sqlWhere;
  1058. }
  1059. /**
  1060. * Get limit part of query
  1061. * return $sqlFrom code for limit part pf query
  1062. */
  1063. function getLimit ($isAddPlusOne = false)
  1064. {
  1065. if (!isset($this->aCurrent['paginate']))
  1066. return;
  1067. $sqlFrom = (int)$this->aCurrent['paginate']['start'] > 0 ? (int)$this->aCurrent['paginate']['start'] : 0;
  1068. $sqlTo = $this->aCurrent['paginate']['perPage'] + ($isAddPlusOne ? 1 : 0);
  1069. if ($sqlTo > 0)
  1070. return 'LIMIT ' . $sqlFrom . ', ' . $sqlTo;
  1071. }
  1072. /**
  1073. * Set sorting field of class
  1074. */
  1075. function setSorting ()
  1076. {
  1077. $this->aCurrent['sorting'] = isset($_GET[$this->aCurrent['name'] . '_mode']) ? $_GET[$this->aCurrent['name'] . '_mode'] : $this->aCurrent['sorting'];
  1078. }
  1079. /**
  1080. * Get sorting part of query according current sorting mode
  1081. * @param string $sSortType sorting type
  1082. * return array with sql elements order and ownFields
  1083. */
  1084. function getSorting ($sSortType = 'last')
  1085. {
  1086. if (isset($this->aCurrent['sorting_sql']))
  1087. return array('order' => $this->aCurrent['sorting_sql']);
  1088. $aOverride = $this->getAlterOrder();
  1089. if (is_array($aOverride) && !empty($aOverride))
  1090. return $aOverride;
  1091. $aSql = array();
  1092. switch ($sSortType) {
  1093. case 'rand':
  1094. $aSql['order'] = "ORDER BY RAND()";
  1095. break;
  1096. case 'score':
  1097. if (is_array($this->aCurrent['restriction']['keyword'])) {
  1098. $sPseud = '';
  1099. if ('on' == getParam('useLikeOperator')) {
  1100. $aSql['order'] = "ORDER BY `score` DESC";
  1101. $sPseud = 'score';
  1102. }
  1103. $aSql['ownFields'] .= $this->getSearchFieldsCond($this->aCurrent['searchFields'], $this->aCurrent['restriction']['keyword']['value'], $sPseud) . ',';
  1104. }
  1105. break;
  1106. case 'none':
  1107. $aSql['order'] = "";
  1108. break;
  1109. default:
  1110. $aSql['order'] = "ORDER BY `date` DESC";
  1111. }
  1112. return $aSql;
  1113. }
  1114. /**
  1115. * Return own varaint for sorting (redeclare if necessary)
  1116. * return array of sql elements
  1117. */
  1118. function getAlterOrder ()
  1119. {
  1120. return array();
  1121. }
  1122. /**
  1123. * Set paginate fields of class according GET params 'start' and 'per_page'
  1124. * forcePage is need for setting most important number of current page
  1125. */
  1126. function setPaginate ()
  1127. {
  1128. $iStart = 0;
  1129. $iPerPage = 0;
  1130. //--- Check in aCurrent (low priority).
  1131. if(isset($this->aCurrent['paginate']['perPage']) && (int)$this->aCurrent['paginate']['perPage'] != 0)
  1132. $iPerPage = (int)$this->aCurrent['paginate']['perPage'];
  1133. //--- Check in aParams (middle priority).
  1134. if(isset($this->_aParams['per_page']) && (int)$this->_aParams['per_page'] != 0)
  1135. $iPerPage = (int)$this->_aParams['per_page'];
  1136. //--- Check in GET params (high priority).
  1137. if(isset($_GET['per_page']) && (int)$_GET['per_page'] != 0)
  1138. $iPerPage = (int)$_GET['per_page'];
  1139. //--- Trying to get from System settings.
  1140. if (empty($iPerPage))
  1141. $iPerPage = (int)getParam('sys_per_page_search_keyword_' . ($this->_bSingleSearch ? 'single' : 'plural'));
  1142. //--- Use default value in case of emergency.
  1143. if (empty($iPerPage))
  1144. $iPerPage = BX_DOL_SEARCH_RESULTS_PER_PAGE_DEFAULT;
  1145. if ($this->iPaginatePerPage != BX_DOL_SEARCH_RESULTS_PER_PAGE_DEFAULT)
  1146. $iPerPage = $this->iPaginatePerPage;
  1147. $this->aCurrent['paginate']['perPage'] = $iPerPage;
  1148. if(!isset($this->aCurrent['paginate']['forceStart'])) {
  1149. if(isset($this->_aParams['start']))
  1150. $iStart = (int)$this->_aParams['start'];
  1151. if(($iStartGet = bx_get('start')) !== false)
  1152. $iStart = (int)$iStartGet;
  1153. }
  1154. else
  1155. $iStart = (int)$this->aCurrent['paginate']['forceStart'];
  1156. if($iStart < 0)
  1157. $iStart = 0;
  1158. $this->aCurrent['paginate']['start'] = $iStart;
  1159. }
  1160. function unsetPaginate()
  1161. {
  1162. unset($this->aCurrent['paginate']);
  1163. }
  1164. /**
  1165. * Get sql where condition for search fields
  1166. * @param array of search fields
  1167. * @param string $sKeyword keyword value for search
  1168. * @param string sPseud for setting new name for generated set of fields in query
  1169. * return sql code of WHERE part in query
  1170. */
  1171. function getSearchFieldsCond ($aFields, $sKeyword, $sPseud = '')
  1172. {
  1173. if (!$sKeyword)
  1174. return '';
  1175. $sTable = empty($this->aCurrent['tableSearch']) ? $this->aCurrent['table'] : $this->aCurrent['tableSearch'];
  1176. $oDb = BxDolDb::getInstance();
  1177. $bLike = getParam('useLikeOperator');
  1178. if (!is_array($aFields))
  1179. $aFields = array($aFields);
  1180. if ($bLike == 'on') {
  1181. $sKeyword = $oDb->escape('%' . preg_replace('/\s+/', '%', $sKeyword) . '%');
  1182. $sSqlWhere = '';
  1183. foreach ($aFields as $sValue)
  1184. $sSqlWhere .= "`{$sTable}`.`$sValue` LIKE " . $sKeyword . " OR ";
  1185. $sSqlWhere = '(' . trim($sSqlWhere, 'OR ') . ')';
  1186. } else {
  1187. $sKeyword = $oDb->escape($sKeyword);
  1188. $sSqlWhere = '';
  1189. foreach ($aFields as $sValue)
  1190. $sSqlWhere .= "`{$sTable}`.`$sValue`, ";
  1191. $sSqlWhere = trim($sSqlWhere, ', ');
  1192. $sSqlWhere = " MATCH({$sSqlWhere}) AGAINST (" . $sKeyword . ") ";
  1193. if (!empty($sPseud))
  1194. $sSqlWhere .= " AS `$sPseud` ";
  1195. }
  1196. return $sSqlWhere;
  1197. }
  1198. /**
  1199. * Get set from several values for 'in' and 'not in' operators
  1200. * @param $aValues array of values
  1201. * return sql code for field with operator IN (NOT IN)
  1202. */
  1203. function getMultiValues ($aValues)
  1204. {
  1205. $oDb = BxDolDb::getInstance();
  1206. return $oDb->implode_escape($aValues);
  1207. }
  1208. /**
  1209. * System method for filling aPseud array. Fill field aPseud for current class from system option.
  1210. * It may be useful when Fields are taken from system option too.
  1211. */
  1212. function _getPseudFromParam ()
  1213. {
  1214. return false;
  1215. }
  1216. /**
  1217. * System method for filling aPseud array.
  1218. * Fill field aPseud for current class (if you will use own getSearchUnit methods then not necessary to redeclare).
  1219. */
  1220. function _getPseud ()
  1221. {
  1222. }
  1223. /**
  1224. * Add replace markers. Markers are replaced in titles and browse urls
  1225. * @param $a array of markers as key => value
  1226. * @return true on success or false on error
  1227. */
  1228. public function addMarkers ($a)
  1229. {
  1230. if (empty($a) || !is_array($a))
  1231. return false;
  1232. $this->_aMarkers = array_merge ($this->_aMarkers, $a);
  1233. return true;
  1234. }
  1235. /**
  1236. * Replace provided markers in a string
  1237. * @param $mixed string or array to replace markers in
  1238. * @return string where all occured markers are replaced
  1239. */
  1240. protected function _replaceMarkers ($mixed)
  1241. {
  1242. return bx_replace_markers($mixed, $this->_aMarkers);
  1243. }
  1244. protected function _setPageDescription()
  1245. {
  1246. $aArgs = func_get_args();
  1247. if($this->_bSingleSearch)
  1248. $aArgs[0] .= '_in_section';
  1249. BxDolTemplate::getInstance()->setPageDescription(call_user_func_array('_t', $aArgs));
  1250. }
  1251. }
  1252. /** @} */