This repository has been archived on 2022-07-28. You can view files and clone it, but cannot push or open issues or pull requests.
md-cms/inc/search.php

89 lines
2.2 KiB
PHP
Raw Normal View History

<?PHP
/**
* This file provides search functions.
*
* @file
*
* @author Joshua Ramon Enslin <joshua@jrenslin.de>
*/
/**
* Function for searching in all static pages.
*
* @param string $searchTerm Search term.
*
* @return array
*/
function searchInPages(string $searchTerm):array {
$files = scanDirConts(__DIR__ . "/../data/static");
$results = [];
foreach ($files as $file) {
$curResults = [];
$contents = json_decode(file_get_contents(__DIR__ . "/../data/static/$file"), true);
if (!$contents['public']) continue; // Don't display non-public files.
$curResults['inTitle'] = substr_count($contents['title'], $searchTerm);
$curResults['inDescription'] = substr_count($contents['content'], $searchTerm);
$curResults['priority'] = $curResults['inTitle'] * 3 + $curResults['inDescription'];
if ($curResults['priority'] == 0) continue;
$curResults['title'] = $contents['title'];
// Sanitize content for snippets.
$snippet = preg_replace('/[\[{\(].*[\]}\)]/U', '', strip_tags($contents['content']));
$curResults['snippet'] = createTextSnippet($snippet, 180);
$results[$file] = $curResults;
}
uasort($results, function($a, $b) {
if ($a['priority'] == $b['priority']) return 0;
return ($a['priority'] > $b['priority']) ? -1 : 1;
});
return $results;
}
/**
* Function for generating and listing search results.
*
* @param string $searchTerm Search term.
*
* @return string
*/
function displaySearchResults(string $searchTerm):string {
$searchResults = searchInPages($searchTerm);
$output = '
<ul id="pagesSearchList">';
foreach ($searchResults as $file => $item) {
$output .= '
<li>
<a href="./?id=' . str_replace(".json", "", $file) . '"><h4>' . $item['title'] . '</h4></a>
<p>' . (string)($item['snippet']) . '</p>
<dl class="searchMetadataLine">
<dt class="toTranslate" data-content="Hits"></dt>
<dd>' . (string)($item['inTitle'] + $item['inDescription']) . '</dd>
</dl>
</li>
';
}
$output .= "
</ul>";
return $output;
}
?>