1<?php 2 3namespace ComboStrap; 4 5class FetcherPageSearch extends IFetcherAbs implements IFetcherString 6{ 7 8 const NAME = "page-search"; 9 10 private string $requestedSearchTerms; 11 12 /** 13 * No cache 14 * @return string 15 */ 16 function getBuster(): string 17 { 18 return time(); 19 } 20 21 public function getMime(): Mime 22 { 23 return Mime::getJson(); 24 } 25 26 public function getFetcherName(): string 27 { 28 return self::NAME; 29 } 30 31 /** 32 * @throws ExceptionNotFound|ExceptionBadArgument 33 */ 34 public function getFetchString(): string 35 { 36 $requestedSearchTerms = $this->getRequestedQuery(); 37 38 if (empty($requestedSearchTerms)) return Json::createEmpty()->toPrettyJsonString(); 39 40 41 /** 42 * Ter info: Old call: how dokuwiki call it. 43 * It's then executing the SEARCH_QUERY_PAGELOOKUP event 44 * 45 * $inTitle = useHeading('navigation'); 46 * $pages = ft_pageLookup($query, true, $inTitle); 47 */ 48 $pages = Search::getPages($requestedSearchTerms); 49 $maxElements = 50; 50 if (count($pages) > $maxElements) { 51 array_splice($pages, 0, $maxElements); 52 } 53 54 $data = []; 55 foreach ($pages as $page) { 56 if (!$page->exists()) { 57 $page->getDatabasePage()->delete(); 58 LogUtility::log2file("The page ($page) returned from the search query does not exist and was deleted from the database"); 59 continue; 60 } 61 $linkUtility = LinkMarkup::createFromPageIdOrPath($page->getWikiId()); 62 try { 63 $html = $linkUtility->toAttributes()->toHtmlEnterTag("a") . $page->getTitleOrDefault() . "</a>"; 64 } catch (ExceptionCompile $e) { 65 $html = "Unable to render the link for the page ($page). Error: {$e->getMessage()}"; 66 } 67 $data[] = $html; 68 } 69 $count = count($data); 70 if (!$count) { 71 return Json::createEmpty()->toPrettyJsonString(); 72 } 73 return Json::createFromArray($data)->toPrettyJsonString(); 74 75 } 76 77 /** 78 * @throws ExceptionNotFound 79 */ 80 private function getRequestedQuery(): string 81 { 82 if (!isset($this->requestedSearchTerms)) { 83 throw new ExceptionNotFound("No search terms were requested"); 84 } 85 return $this->requestedSearchTerms; 86 } 87 88 public function buildFromTagAttributes(TagAttributes $tagAttributes): IFetcher 89 { 90 $searchTerms = $tagAttributes->getValueAndRemoveIfPresent("q"); 91 if ($searchTerms !== null) { 92 $this->requestedSearchTerms = $searchTerms; 93 } 94 return parent::buildFromTagAttributes($tagAttributes); 95 } 96 97 98 public function getLabel(): string 99 { 100 return self::NAME; 101 } 102} 103