2021-12-14 18:32:47 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
declare(strict_types=1);
|
2015-02-01 00:47:09 +00:00
|
|
|
|
2023-01-10 22:44:09 +00:00
|
|
|
namespace Shimmie2;
|
|
|
|
|
2019-05-28 16:59:38 +00:00
|
|
|
class AutoComplete extends Extension
|
|
|
|
{
|
|
|
|
public function get_priority(): int
|
|
|
|
{
|
|
|
|
return 30;
|
|
|
|
} // before Home
|
|
|
|
|
2024-01-15 11:52:35 +00:00
|
|
|
public function onPageRequest(PageRequestEvent $event): void
|
2019-05-28 16:59:38 +00:00
|
|
|
{
|
2020-11-15 12:18:23 +00:00
|
|
|
global $page;
|
2019-05-28 16:59:38 +00:00
|
|
|
|
|
|
|
if ($event->page_matches("api/internal/autocomplete")) {
|
2023-12-29 11:10:58 +00:00
|
|
|
$limit = (int)($_GET["limit"] ?? 1000);
|
2021-11-06 16:12:23 +00:00
|
|
|
$s = $_GET["s"] ?? "";
|
2020-11-15 12:18:23 +00:00
|
|
|
|
|
|
|
$res = $this->complete($s, $limit);
|
2019-05-28 16:59:38 +00:00
|
|
|
|
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);
|
2020-11-15 12:18:23 +00:00
|
|
|
$page->set_data(json_encode($res));
|
|
|
|
}
|
|
|
|
}
|
2019-05-28 16:59:38 +00:00
|
|
|
|
2020-11-15 13:20:30 +00:00
|
|
|
private function complete(string $search, int $limit): array
|
|
|
|
{
|
2020-11-15 12:18:23 +00:00
|
|
|
global $cache, $database;
|
2019-05-28 16:59:38 +00:00
|
|
|
|
2020-11-15 12:18:23 +00:00
|
|
|
$search = strtolower($search);
|
|
|
|
if (
|
|
|
|
$search == '' ||
|
|
|
|
$search[0] == '_' ||
|
|
|
|
$search[0] == '%' ||
|
|
|
|
strlen($search) > 32
|
|
|
|
) {
|
|
|
|
return [];
|
|
|
|
}
|
2015-02-01 00:47:09 +00:00
|
|
|
|
2023-02-12 12:26:55 +00:00
|
|
|
# memcache keys can't contain spaces
|
2023-12-29 11:10:58 +00:00
|
|
|
$cache_key = "autocomplete:$limit:" . md5($search);
|
2020-11-15 12:18:23 +00:00
|
|
|
$limitSQL = "";
|
|
|
|
$search = str_replace('_', '\_', $search);
|
|
|
|
$search = str_replace('%', '\%', $search);
|
2024-01-05 12:24:50 +00:00
|
|
|
$SQLarr = [
|
|
|
|
"search" => "$search%",
|
|
|
|
"cat_search" => Extension::is_enabled(TagCategoriesInfo::KEY) ? "%:$search%" : "",
|
|
|
|
];
|
2020-11-15 12:18:23 +00:00
|
|
|
if ($limit !== 0) {
|
|
|
|
$limitSQL = "LIMIT :limit";
|
|
|
|
$SQLarr['limit'] = $limit;
|
|
|
|
$cache_key .= "-" . $limit;
|
2019-05-28 16:59:38 +00:00
|
|
|
}
|
2015-02-01 00:47:09 +00:00
|
|
|
|
2023-12-14 17:06:54 +00:00
|
|
|
return cache_get_or_set($cache_key, fn () => $database->get_pairs(
|
|
|
|
"
|
2020-11-15 12:18:23 +00:00
|
|
|
SELECT tag, count
|
|
|
|
FROM tags
|
2024-01-14 16:45:09 +00:00
|
|
|
WHERE (
|
|
|
|
LOWER(tag) LIKE LOWER(:search)
|
|
|
|
OR LOWER(tag) LIKE LOWER(:cat_search)
|
|
|
|
)
|
2020-11-15 12:18:23 +00:00
|
|
|
AND count > 0
|
2023-12-29 12:17:00 +00:00
|
|
|
ORDER BY count DESC, tag ASC
|
2020-11-15 12:18:23 +00:00
|
|
|
$limitSQL
|
|
|
|
",
|
2023-12-14 17:06:54 +00:00
|
|
|
$SQLarr
|
|
|
|
), 600);
|
2019-05-28 16:59:38 +00:00
|
|
|
}
|
2015-02-01 00:47:09 +00:00
|
|
|
}
|