simplesearch.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. <?php
  2. namespace Grav\Plugin;
  3. use Grav\Common\Config\Config;
  4. use Grav\Common\Data\Data;
  5. use Grav\Common\Page\Collection;
  6. use Grav\Common\Page\Page;
  7. use Grav\Common\Page\Types;
  8. use Grav\Common\Plugin;
  9. use Grav\Common\Taxonomy;
  10. use Grav\Common\Uri;
  11. use Grav\Common\Utils;
  12. use RocketTheme\Toolbox\Event\Event;
  13. class SimplesearchPlugin extends Plugin
  14. {
  15. /**
  16. * @var array
  17. */
  18. protected $query;
  19. /**
  20. * @var string
  21. */
  22. protected $query_id;
  23. /**
  24. * @var Collection
  25. */
  26. protected $collection;
  27. /**
  28. * @return array
  29. */
  30. public static function getSubscribedEvents()
  31. {
  32. return [
  33. 'onPluginsInitialized' => ['onPluginsInitialized', 0],
  34. 'onTwigTemplatePaths' => ['onTwigTemplatePaths', 0],
  35. 'onGetPageTemplates' => ['onGetPageTemplates', 0],
  36. ];
  37. }
  38. /**
  39. * Add page template types. (for Admin plugin)
  40. */
  41. public function onGetPageTemplates(Event $event)
  42. {
  43. /** @var Types $types */
  44. $types = $event->types;
  45. $types->scanTemplates('plugins://simplesearch/templates');
  46. }
  47. /**
  48. * Add current directory to twig lookup paths.
  49. */
  50. public function onTwigTemplatePaths()
  51. {
  52. $this->grav['twig']->twig_paths[] = __DIR__ . '/templates';
  53. }
  54. /**
  55. * Enable search only if url matches to the configuration.
  56. */
  57. public function onPluginsInitialized()
  58. {
  59. if ($this->isAdmin()) {
  60. return;
  61. }
  62. $this->enable([
  63. 'onPagesInitialized' => ['onPagesInitialized', 0],
  64. 'onTwigSiteVariables' => ['onTwigSiteVariables', 0]
  65. ]);
  66. }
  67. /**
  68. * Build search results.
  69. */
  70. public function onPagesInitialized()
  71. {
  72. $page = $this->grav['page'];
  73. $route = null;
  74. if (isset($page->header()->simplesearch['route'])) {
  75. $route = $page->header()->simplesearch['route'];
  76. // Support `route: '@self'` syntax
  77. if ($route === '@self') {
  78. $route = $page->route();
  79. $page->header()->simplesearch['route'] = $route;
  80. }
  81. }
  82. // If a page exists merge the configs
  83. if ($page) {
  84. $this->config->set('plugins.simplesearch', $this->mergeConfig($page));
  85. }
  86. /** @var Uri $uri */
  87. $uri = $this->grav['uri'];
  88. $query = $uri->param('query') ?: $uri->query('query');
  89. $route = $this->config->get('plugins.simplesearch.route');
  90. // performance check for route
  91. if (!($route && $route == $uri->path())) {
  92. return;
  93. }
  94. // Explode query into multiple strings. Drop empty values
  95. $this->query = array_filter(array_filter(explode(',', $query), 'trim'), 'strlen');
  96. /** @var Taxonomy $taxonomy_map */
  97. $taxonomy_map = $this->grav['taxonomy'];
  98. $taxonomies = [];
  99. $find_taxonomy = [];
  100. $filters = (array)$this->config->get('plugins.simplesearch.filters');
  101. $operator = $this->config->get('plugins.simplesearch.filter_combinator', 'and');
  102. $new_approach = false;
  103. // if @none found, skip processing taxonomies
  104. $should_process = true;
  105. if (is_array($filters)) {
  106. $the_filter = reset($filters);
  107. if (is_array($the_filter)) {
  108. if (in_array(reset($the_filter), ['@none', 'none@'])) {
  109. $should_process = false;
  110. }
  111. }
  112. }
  113. if (!$should_process || !$filters || $query === false || (count($filters) == 1 && !reset($filters))) {
  114. /** @var \Grav\Common\Page\Pages $pages */
  115. $pages = $this->grav['pages'];
  116. $this->collection = $pages->all();
  117. } else {
  118. foreach ($filters as $key => $filter) {
  119. // flatten item if it's wrapped in an array
  120. if (is_int($key)) {
  121. if (is_array($filter)) {
  122. $key = key($filter);
  123. $filter = $filter[$key];
  124. } else {
  125. $key = $filter;
  126. }
  127. }
  128. // see if the filter uses the new 'items-type' syntax
  129. if ($key === '@self' || $key === 'self@') {
  130. $new_approach = true;
  131. } elseif ($key === '@taxonomy' || $key === 'taxonomy@') {
  132. $taxonomies = $filter === false ? false : array_merge($taxonomies, (array)$filter);
  133. } else {
  134. $find_taxonomy[$key] = $filter;
  135. }
  136. }
  137. if ($new_approach) {
  138. $params = $page->header()->content;
  139. $params['query'] = $this->config->get('plugins.simplesearch.query');
  140. $this->collection = $page->collection($params, false);
  141. } else {
  142. $this->collection = new Collection();
  143. $this->collection->append($taxonomy_map->findTaxonomy($find_taxonomy, $operator)->toArray());
  144. }
  145. }
  146. //Drop unpublished and unroutable pages
  147. $this->collection->published()->routable();
  148. //Check if user has permission to view page
  149. if ($this->grav['config']->get('plugins.login.enabled')) {
  150. $this->collection = $this->checkForPermissions($this->collection);
  151. }
  152. $extras = [];
  153. if ($query) {
  154. foreach ($this->collection as $cpage) {
  155. foreach ($this->query as $query) {
  156. $query = trim($query);
  157. if ($this->notFound($query, $cpage, $taxonomies)) {
  158. $this->collection->remove($cpage);
  159. continue;
  160. }
  161. if ($cpage->modular()) {
  162. $this->collection->remove($cpage);
  163. $parent = $cpage->parent();
  164. $extras[$parent->path()] = ['slug' => $parent->slug()];
  165. }
  166. }
  167. }
  168. }
  169. if (!empty($extras)) {
  170. $this->collection->append($extras);
  171. }
  172. // use a configured sorting order if not already done
  173. if (!$new_approach) {
  174. $this->collection = $this->collection->order(
  175. $this->config->get('plugins.simplesearch.order.by'),
  176. $this->config->get('plugins.simplesearch.order.dir')
  177. );
  178. }
  179. // if page doesn't have settings set, create a page
  180. if (!isset($page->header()->simplesearch)) {
  181. // create the search page
  182. $page = new Page;
  183. $page->init(new \SplFileInfo(__DIR__ . '/pages/simplesearch.md'));
  184. // override the template is set in the config
  185. $template_override = $this->config->get('plugins.simplesearch.template');
  186. if ($template_override) {
  187. $page->template($template_override);
  188. }
  189. // fix RuntimeException: Cannot override frozen service "page" issue
  190. unset($this->grav['page']);
  191. $this->grav['page'] = $page;
  192. }
  193. }
  194. /**
  195. * Filter the pages, and return only the pages the user has access to.
  196. * Implementation based on Login Plugin authorizePage() function.
  197. */
  198. public function checkForPermissions($collection)
  199. {
  200. $user = $this->grav['user'];
  201. $returnCollection = new Collection();
  202. foreach ($collection as $page) {
  203. $header = $page->header();
  204. $rules = isset($header->access) ? (array)$header->access : [];
  205. if ($this->config->get('plugins.login.parent_acl')) {
  206. // If page has no ACL rules, use its parent's rules
  207. if (!$rules) {
  208. $parent = $page->parent();
  209. while (!$rules and $parent) {
  210. $header = $parent->header();
  211. $rules = isset($header->access) ? (array)$header->access : [];
  212. $parent = $parent->parent();
  213. }
  214. }
  215. }
  216. // Continue to the page if it has no ACL rules.
  217. if (!$rules) {
  218. $returnCollection[$page->path()] = ['slug' => $page->slug()];
  219. } else {
  220. // Continue to the page if user is authorized to access the page.
  221. foreach ($rules as $rule => $value) {
  222. if (is_array($value)) {
  223. foreach ($value as $nested_rule => $nested_value) {
  224. if ($user->authorize($rule . '.' . $nested_rule) == $nested_value) {
  225. $returnCollection[$page->path()] = ['slug' => $page->slug()];
  226. break;
  227. }
  228. }
  229. } else {
  230. if ($user->authorize($rule) == $value) {
  231. $returnCollection[$page->path()] = ['slug' => $page->slug()];
  232. break;
  233. }
  234. }
  235. }
  236. }
  237. }
  238. return $returnCollection;
  239. }
  240. /**
  241. * @param $query
  242. * @param Page $page
  243. * @param $taxonomies
  244. * @return bool
  245. */
  246. private function notFound($query, $page, $taxonomies)
  247. {
  248. $searchable_types = ['title', 'content', 'taxonomy'];
  249. $results = true;
  250. $search_content = $this->config->get('plugins.simplesearch.search_content');
  251. foreach ($searchable_types as $type) {
  252. if ($type === 'title') {
  253. $result = $this->matchText(strip_tags($page->title()), $query) === false;
  254. } elseif ($type === 'taxonomy') {
  255. if ($taxonomies === false) {
  256. continue;
  257. }
  258. $page_taxonomies = $page->taxonomy();
  259. $taxonomy_match = false;
  260. foreach ((array)$page_taxonomies as $taxonomy => $values) {
  261. // if taxonomies filter set, make sure taxonomy filter is valid
  262. if (!is_array($values) || (is_array($taxonomies) && !empty($taxonomies) && !in_array($taxonomy, $taxonomies))) {
  263. continue;
  264. }
  265. $taxonomy_values = implode('|', $values);
  266. if ($this->matchText($taxonomy_values, $query) !== false) {
  267. $taxonomy_match = true;
  268. break;
  269. }
  270. }
  271. $result = !$taxonomy_match;
  272. } else {
  273. if ($search_content == 'raw') {
  274. $content = $page->rawMarkdown();
  275. } else {
  276. $content = $page->content();
  277. }
  278. $result = $this->matchText(strip_tags($content), $query) === false;
  279. }
  280. $results = $results && $result;
  281. if ($results === false) {
  282. break;
  283. }
  284. }
  285. return $results;
  286. }
  287. private function matchText($haystack, $needle)
  288. {
  289. if ($this->config->get('plugins.simplesearch.ignore_accented_characters')) {
  290. setlocale(LC_ALL, 'en_US');
  291. try {
  292. $result = mb_stripos(iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $haystack), iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $needle));
  293. } catch (\Exception $e) {
  294. $result = mb_stripos($haystack, $needle);
  295. }
  296. setlocale(LC_ALL, '');
  297. return $result;
  298. } else {
  299. return mb_stripos($haystack, $needle);
  300. }
  301. }
  302. /**
  303. * Set needed variables to display the search results.
  304. */
  305. public function onTwigSiteVariables()
  306. {
  307. $twig = $this->grav['twig'];
  308. if ($this->query) {
  309. $twig->twig_vars['query'] = implode(', ', $this->query);
  310. $twig->twig_vars['search_results'] = $this->collection;
  311. }
  312. if ($this->config->get('plugins.simplesearch.built_in_css')) {
  313. $this->grav['assets']->add('plugin://simplesearch/css/simplesearch.css');
  314. }
  315. if ($this->config->get('plugins.simplesearch.built_in_js')) {
  316. $this->grav['assets']->addJs('plugin://simplesearch/js/simplesearch.js', ['group' => 'bottom']);
  317. }
  318. }
  319. }