This repository has been archived on 2024-09-05. You can view files and clone it, but cannot push or open issues or pull requests.
shimmie2/ext/autocomplete/main.php

85 lines
2.1 KiB
PHP
Raw Normal View History

2021-12-14 18:32:47 +00:00
<?php
declare(strict_types=1);
namespace Shimmie2;
class AutoComplete extends Extension
{
2020-02-04 00:46:36 +00:00
/** @var AutoCompleteTheme */
2023-06-27 14:56:49 +00:00
protected Themelet $theme;
2020-02-04 00:46:36 +00:00
public function get_priority(): int
{
return 30;
} // before Home
public function onPageRequest(PageRequestEvent $event)
{
global $page;
if ($event->page_matches("api/internal/autocomplete")) {
2021-10-06 16:59:32 +00:00
$limit = (int)($_GET["limit"] ?? 0);
$s = $_GET["s"] ?? "";
$res = $this->complete($s, $limit);
2019-06-19 01:58:28 +00:00
$page->set_mode(PageMode::DATA);
2020-06-14 16:05:55 +00:00
$page->set_mime(MimeType::JSON);
$page->set_data(json_encode($res));
}
$this->theme->build_autocomplete($page);
}
2020-11-15 13:20:30 +00:00
private function complete(string $search, int $limit): array
{
global $cache, $database;
if (!$search) {
return [];
}
$search = strtolower($search);
if (
$search == '' ||
$search[0] == '_' ||
$search[0] == '%' ||
strlen($search) > 32
) {
return [];
}
2023-02-12 12:26:55 +00:00
# memcache keys can't contain spaces
2023-02-14 01:19:28 +00:00
$cache_key = "autocomplete:" . md5($search);
$limitSQL = "";
$search = str_replace('_', '\_', $search);
$search = str_replace('%', '\%', $search);
$SQLarr = ["search"=>"$search%"]; #, "cat_search"=>"%:$search%"];
if ($limit !== 0) {
$limitSQL = "LIMIT :limit";
$SQLarr['limit'] = $limit;
$cache_key .= "-" . $limit;
}
$res = $cache->get($cache_key);
if (is_null($res)) {
2020-11-15 13:20:30 +00:00
$res = $database->get_pairs(
"
SELECT tag, count
FROM tags
WHERE LOWER(tag) LIKE LOWER(:search)
-- OR LOWER(tag) LIKE LOWER(:cat_search)
AND count > 0
ORDER BY count DESC
$limitSQL
",
$SQLarr
);
$cache->set($cache_key, $res, 600);
}
return $res;
}
}