PageRenderTime 48ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/core/packages/simplesearch-1.9-pl/modCategory/1959218a0a36e4671ecc829ac12facfc/0/simplesearch/model/simplesearch/driver/simplesearchdriversolr.class.php

https://gitlab.com/haque.mdmanzurul/nga-loyaltymatters
PHP | 267 lines | 168 code | 18 blank | 81 comment | 27 complexity | 38ba57eb01e30e589cd6e0548814ab06 MD5 | raw file
  1. <?php
  2. /**
  3. * SimpleSearch
  4. *
  5. * Copyright 2010-11 by Shaun McCormick <shaun+sisea@modx.com>
  6. *
  7. * This file is part of SimpleSearch, a simple search component for MODx
  8. * Revolution. It is loosely based off of AjaxSearch for MODx Evolution by
  9. * coroico/kylej, minus the ajax.
  10. *
  11. * SimpleSearch is free software; you can redistribute it and/or modify it under
  12. * the terms of the GNU General Public License as published by the Free Software
  13. * Foundation; either version 2 of the License, or (at your option) any later
  14. * version.
  15. *
  16. * SimpleSearch is distributed in the hope that it will be useful, but WITHOUT
  17. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  18. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  19. * details.
  20. *
  21. * You should have received a copy of the GNU General Public License along with
  22. * SimpleSearch; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
  23. * Suite 330, Boston, MA 02111-1307 USA
  24. *
  25. * @package simplesearch
  26. */
  27. require_once dirname(__FILE__) . '/simplesearchdriver.class.php';
  28. /**
  29. * Solr search driver for SimpleSearch. This requires a few things to run:
  30. *
  31. * - The PECL Solr package, found here: http://pecl.php.net/package/solr
  32. * - A working schema.xml file and running Solr instance.
  33. *
  34. * A sample schema.xml file is provided for you in the core/components/simplesearch/docs/
  35. * directory. Rename the file from solr.schema.xml to schema.xml and put in
  36. * the appropriate conf/ directory in your preferred Solr core. You may
  37. * customize the schema as you feel the need.
  38. *
  39. * @package simplesearch
  40. */
  41. class SimpleSearchDriverSolr extends SimpleSearchDriver {
  42. /** @var array An array of connection properties for our SolrClient */
  43. private $_connectionOptions = array();
  44. /** @var A reference to the SolrClient object */
  45. public $client;
  46. /**
  47. * Initialize the Solr client, and setup settings for the client.
  48. *
  49. * @return void
  50. */
  51. public function initialize() {
  52. $this->_connectionOptions = array(
  53. 'hostname' => $this->modx->getOption('sisea.solr.hostname',null,'127.0.0.1'),
  54. 'port' => $this->modx->getOption('sisea.solr.port',null,'8983'),
  55. 'path' => $this->modx->getOption('sisea.solr.path',null,''),
  56. 'login' => $this->modx->getOption('sisea.solr.username',null,''),
  57. 'password' => $this->modx->getOption('sisea.solr.password',null,''),
  58. 'timeout' => $this->modx->getOption('sisea.solr.timeout',null,30),
  59. 'secure' => $this->modx->getOption('sisea.solr.ssl',null,false),
  60. 'ssl_cert' => $this->modx->getOption('sisea.solr.ssl_cert',null,''),
  61. 'ssl_key' => $this->modx->getOption('sisea.solr.ssl_key',null,''),
  62. 'ssl_keypassword' => $this->modx->getOption('sisea.solr.ssl_keypassword',null,''),
  63. 'ssl_cainfo' => $this->modx->getOption('sisea.solr.ssl_cainfo',null,''),
  64. 'ssl_capath' => $this->modx->getOption('sisea.solr.ssl_capath',null,''),
  65. 'proxy_host' => $this->modx->getOption('sisea.solr.proxy_host',null,''),
  66. 'proxy_port' => $this->modx->getOption('sisea.solr.proxy_port',null,''),
  67. 'proxy_login' => $this->modx->getOption('sisea.solr.proxy_username',null,''),
  68. 'proxy_password' => $this->modx->getOption('sisea.solr.proxy_password',null,''),
  69. );
  70. try {
  71. $this->client = new SolrClient($this->_connectionOptions);
  72. } catch (Exception $e) {
  73. $this->modx->log(xPDO::LOG_LEVEL_ERROR,'Error connecting to Solr server: '.$e->getMessage());
  74. }
  75. }
  76. /**
  77. * Run the search against a sanitized query string via Solr.
  78. *
  79. * @param string $string
  80. * @param array $scriptProperties The scriptProperties array from the SimpleSearch snippet
  81. * @return array
  82. */
  83. public function search($string,array $scriptProperties = array()) {
  84. /** @var SolrQuery $query */
  85. $query = new SolrQuery();
  86. $query->setQuery($string);
  87. /* set limit */
  88. $perPage = $this->modx->getOption('perPage',$scriptProperties,10);
  89. if (!empty($perPage)) {
  90. $offset = $this->modx->getOption('start',$scriptProperties,0);
  91. $offsetIndex = $this->modx->getOption('offsetIndex',$scriptProperties,'sisea_offset');
  92. if (isset($_REQUEST[$offsetIndex])) $offset = (int)$_REQUEST[$offsetIndex];
  93. $query->setStart($offset);
  94. $query->setRows($perPage);
  95. }
  96. /* add fields to search */
  97. $fields = $this->modx->getFields('modResource');
  98. foreach ($fields as $fieldName => $default) {
  99. $query->addField($fieldName);
  100. }
  101. $includeTVs = $this->modx->getOption('includeTVs',$scriptProperties,false);
  102. if ($includeTVs) {
  103. $sql = $this->modx->newQuery('modTemplateVar');
  104. $sql->select($this->modx->getSelectColumns('modTemplateVar','','',array('id','name')));
  105. $sql->sortby($this->modx->escape('name'),'ASC');
  106. $sql->prepare();
  107. $sql = $sql->toSql();
  108. $tvs = $this->modx->query($sql);
  109. if ($tvs && $tvs instanceof PDOStatement) {
  110. while ($tv = $tvs->fetch(PDO::FETCH_ASSOC)) {
  111. $query->addField($tv['name']);
  112. }
  113. }
  114. }
  115. /* handle hidemenu option */
  116. $hideMenu = $this->modx->getOption('hideMenu',$scriptProperties,2);
  117. if ($hideMenu != 2) {
  118. $query->addFilterQuery('hidemenu:'.($hideMenu ? 1 : 0));
  119. }
  120. /* handle contexts */
  121. $contexts = $this->modx->getOption('contexts',$scriptProperties,'');
  122. $contexts = !empty($contexts) ? $contexts : $this->modx->context->get('key');
  123. $contexts = implode(' ',explode(',',$contexts));
  124. $query->addFilterQuery('context_key:('.$contexts.')');
  125. /* handle restrict search to these IDs */
  126. $ids = $this->modx->getOption('ids',$scriptProperties,'');
  127. if (!empty($ids)) {
  128. $idType = $this->modx->getOption('idType',$this->config,'parents');
  129. $depth = $this->modx->getOption('depth',$this->config,10);
  130. $ids = $this->processIds($ids,$idType,$depth);
  131. $query->addFilterQuery('id:('.implode(' ',$ids).')');
  132. }
  133. /* handle exclude IDs from search */
  134. $exclude = $this->modx->getOption('exclude',$scriptProperties,'');
  135. if (!empty($exclude)) {
  136. $exclude = $this->cleanIds($exclude);
  137. $exclude = implode(' ',explode(',', $exclude));
  138. $query->addFilterQuery('-id:('.$exclude.')');
  139. }
  140. /* basic always-on conditions */
  141. $query->addFilterQuery('published:1');
  142. $query->addFilterQuery('searchable:1');
  143. $query->addFilterQuery('deleted:0');
  144. /* sorting */
  145. if (!empty($scriptProperties['sortBy'])) {
  146. $sortDir = $this->modx->getOption('sortDir',$scriptProperties,'desc');
  147. $sortDirs = explode(',',$sortDir);
  148. $sortBys = explode(',',$scriptProperties['sortBy']);
  149. $dir = 'desc';
  150. for ($i=0;$i<count($sortBys);$i++) {
  151. if (isset($sortDirs[$i])) {
  152. $dir= $sortDirs[$i];
  153. }
  154. $dir = strtolower($dir) == 'asc' ? SolrQuery::ORDER_ASC : SolrQuery::ORDER_DESC;
  155. $query->addSortField($sortBys[$i],$dir);
  156. }
  157. }
  158. /* prepare response array */
  159. $response = array(
  160. 'total' => 0,
  161. 'start' => !empty($offset) ? $offset : 0,
  162. 'limit' => $perPage,
  163. 'status' => 0,
  164. 'query_time' => 0,
  165. 'results' => array(),
  166. );
  167. /* query Solr */
  168. try {
  169. $queryResponse = $this->client->query($query);
  170. $responseObject = $queryResponse->getResponse();
  171. if ($responseObject) {
  172. $response['total'] = $responseObject->response->numFound;
  173. $response['query_time'] = $responseObject->responseHeader->QTime;
  174. $response['status'] = $responseObject->responseHeader->status;
  175. $response['results'] = array();
  176. if (!empty($responseObject->response->docs)) {
  177. foreach ($responseObject->response->docs as $doc) {
  178. $d = array();
  179. foreach ($doc as $k => $v) {
  180. $d[$k] = $v;
  181. }
  182. /** @var modResource $resource */
  183. $resource = $this->modx->newObject($d['class_key']);
  184. if ($resource->checkPolicy('list')) {
  185. $response['results'][] = $d;
  186. }
  187. }
  188. }
  189. }
  190. } catch (Exception $e) {
  191. $this->modx->log(xPDO::LOG_LEVEL_ERROR,'Error running query on Solr server: '.$e->getMessage());
  192. }
  193. return $response;
  194. }
  195. /**
  196. * Index a Resource.
  197. *
  198. * @param array $fields
  199. * @return boolean
  200. */
  201. public function index(array $fields = array()) {
  202. if (isset($fields['searchable']) && empty($fields['searchable'])) return false;
  203. if (isset($fields['published']) && empty($fields['published'])) return false;
  204. if (isset($fields['deleted']) && !empty($fields['deleted'])) return false;
  205. $document = new SolrInputDocument();
  206. $dateFields = array('createdon','editedon','deletedon','publishedon');
  207. foreach ($fields as $fieldName => $value) {
  208. if (is_string($fieldName) && !is_array($value) && !is_object($value)) {
  209. if (in_array($fieldName,$dateFields)) {
  210. $value = ''.strftime('%Y-%m-%dT%H:%M:%SZ',strtotime($value));
  211. $fields[$fieldName] = $value;
  212. }
  213. $document->addField($fieldName,$value);
  214. }
  215. }
  216. $this->modx->log(modX::LOG_LEVEL_DEBUG,'[SimpleSearch] Indexing Resource: '.print_r($fields,true));
  217. $response = false;
  218. try {
  219. $response = $this->client->addDocument($document);
  220. } catch (Exception $e) {
  221. $this->modx->log(xPDO::LOG_LEVEL_ERROR,'Error adding Document to index on Solr server: '.$e->getMessage());
  222. }
  223. $this->commit();
  224. return $response;
  225. }
  226. /**
  227. * Remove a Resource from the Solr index.
  228. *
  229. * @param string|int $id
  230. * @return boolean
  231. */
  232. public function removeIndex($id) {
  233. $this->modx->log(modX::LOG_LEVEL_DEBUG,'[SimpleSearch] Removing Resource From Index: '.$id);
  234. $this->client->deleteById($id);
  235. $this->commit();
  236. }
  237. /**
  238. * Commit the operation to the Solr core.
  239. *
  240. * @return void
  241. */
  242. public function commit() {
  243. try {
  244. $this->client->commit();
  245. } catch (Exception $e) {
  246. $this->modx->log(xPDO::LOG_LEVEL_ERROR,'Error committing query on Solr server: '.$e->getMessage());
  247. }
  248. }
  249. }