-
-
Notifications
You must be signed in to change notification settings - Fork 366
Expand file tree
/
Copy pathGetSearchRequest.php
More file actions
77 lines (67 loc) · 2.24 KB
/
GetSearchRequest.php
File metadata and controls
77 lines (67 loc) · 2.24 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
/**
* SPDX-License-Identifier: MIT
* Copyright (c) 2017-2018 Tobias Reich
* Copyright (c) 2018-2025 LycheeOrg.
*/
namespace App\Http\Requests\Search;
use App\Contracts\Http\Requests\HasAbstractAlbum;
use App\Contracts\Http\Requests\HasTerms;
use App\Contracts\Http\Requests\RequestAttribute;
use App\Contracts\Models\AbstractAlbum;
use App\Http\Requests\BaseApiRequest;
use App\Http\Requests\Traits\HasAbstractAlbumTrait;
use App\Http\Requests\Traits\HasTermsTrait;
use App\Models\Configs;
use App\Policies\AlbumPolicy;
use App\Rules\RandomIDRule;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use function Safe\base64_decode;
use function Safe\preg_match_all;
class GetSearchRequest extends BaseApiRequest implements HasAbstractAlbum, HasTerms
{
use HasTermsTrait;
use HasAbstractAlbumTrait;
/**
* {@inheritDoc}
*/
public function authorize(): bool
{
if (!Auth::check() && !Configs::getValueAsBool('search_public')) {
return false;
}
return Gate::check(AlbumPolicy::CAN_ACCESS, [AbstractAlbum::class, $this->album]);
}
/**
* {@inheritDoc}
*/
public function rules(): array
{
return [
RequestAttribute::TERM_ATTRIBUTE => ['required', 'string'],
RequestAttribute::ALBUM_ID_ATTRIBUTE => ['sometimes', new RandomIDRule(true)],
];
}
/**
* {@inheritDoc}
*/
protected function processValidatedValues(array $values, array $files): void
{
$album_id = $values[RequestAttribute::ALBUM_ID_ATTRIBUTE] ?? null;
$this->album = $this->album_factory->findNullalbleAbstractAlbumOrFail($album_id);
// Escape special characters for a LIKE query
$terms = str_replace(
['\\', '%', '_'],
['\\\\', '\\%', '\\_'],
base64_decode($values[RequestAttribute::TERM_ATTRIBUTE], true)
);
// Explode the string by spaces but keep encapsulated strings as single terms
// This regex matches quoted strings and unquoted words
// Note: This regex is not perfect and may not handle all edge cases, but it works for most common cases.
// It captures quoted strings as a single match and unquoted words separately.
// Example: "hello world" foo bar -> ["hello world", "foo", "bar"]
preg_match_all('/"[^"]*"|\S+/', $terms, $matches);
$this->terms = array_map(fn ($term) => trim($term, '"'), $matches[0]);
}
}