summaryrefslogtreecommitdiff
path: root/src/application/actions/search/get.php
blob: fab0a7fee7aea94f557a6ab9f8523c6cd90d3adb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php

use mystic\forum\orm\Attachment;
use mystic\forum\orm\Post;
use mystic\forum\orm\Topic;
use mystic\forum\orm\User;
use mystic\forum\utils\RequestUtils;

$query = $_GET["query"] ?? null;
if ($query !== null) {
    $start_time = microtime(true);
    /** @var Post[] $posts */
    $posts = $db->execCustomQuery(<<<SQL
        SELECT posts.* FROM topics, posts
        WHERE
            NOT posts.deleted
            AND to_tsvector('english', topics.title || ' ' || posts.content) @@ websearch_to_tsquery('english', $1)
        ORDER BY posts.post_date DESC
        ;
    SQL, [ $query ], Post::class);

    $topicLookup = [];
    $attachmentLookup = [];
    $userLookup = [];
    foreach ($posts as $item) {
        if (!isset($topicLookup[$item->topicId])) {
            $topic = new Topic;
            $topic->id = $item->topicId;
            if ($db->fetch($topic))
                $topicLookup[$topic->id] = $topic;
        }
        if (!isset($attachmentLookup[$item->id])) {
            $attachmentLookup[$item->id] = $db->fetchCustom(Attachment::class, 'WHERE post_id = $1', [ $item->id ]);
        }
        if (!isset($userLookup[$item->authorId])) {
            $user = new User;
            $user->id = $item->authorId;
            if ($db->fetch($user))
                $userLookup[$item->authorId] = $user;
        }
    }
    $end_time = microtime(true);
    $search_duration = $end_time - $start_time;

    render("search.twig", [
        "posts" => &$posts,
        "topics" => &$topicLookup,
        "users" => &$userLookup,
        "attachments" => &$attachmentLookup,
        "search_duration" => $search_duration,
    ]);
} else {
    render("search.twig");
}