-
-
Notifications
You must be signed in to change notification settings - Fork 263
Expand file tree
/
Copy pathSearch.php
More file actions
executable file
·477 lines (397 loc) · 15.5 KB
/
Search.php
File metadata and controls
executable file
·477 lines (397 loc) · 15.5 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
<?php
/**
* The phpMyFAQ Search class.
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at https://mozilla.org/MPL/2.0/.
*
* @package phpMyFAQ
* @author Thorsten Rinne <thorsten@phpmyfaq.de>
* @author Matteo Scaramuccia <matteo@scaramuccia.com>
* @author Adrianna Musiol <musiol@imageaccess.de>
* @copyright 2008-2026 phpMyFAQ Team
* @license https://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
* @link https://www.phpmyfaq.de
* @since 2008-01-26
*/
declare(strict_types=1);
namespace phpMyFAQ;
use DateTime;
use Exception;
use phpMyFAQ\Database\DatabaseDriver;
use phpMyFAQ\Search\Search\Elasticsearch;
use phpMyFAQ\Search\Search\OpenSearch;
use phpMyFAQ\Search\SearchFactory;
use stdClass;
/**
* Class Search
*
* @package phpMyFAQ
*/
class Search
{
private ?int $categoryId = null;
private ?Category $category = null;
private readonly string $table;
/**
* Constructor.
*/
public function __construct(
private readonly Configuration $configuration,
) {
$this->table = Database::getTablePrefix() . 'faqsearches';
}
/**
* Setter for category.
*
* @param int|null $categoryId Entity ID
*/
public function setCategoryId(?int $categoryId): void
{
$this->categoryId = $categoryId;
}
/**
* Getter for category.
*/
public function getCategoryId(): ?int
{
return $this->categoryId;
}
/**
* The search function to handle the different search engines.
*
* @param string $searchTerm Text/Number (solution id)
* @param bool $allLanguages true to search over all languages
* @throws Exception
*/
public function search(string $searchTerm, bool $allLanguages = true): array
{
if (is_numeric($searchTerm) && $this->configuration->get(item: 'search.searchForSolutionId')) {
return $this->searchDatabase($searchTerm, $allLanguages);
}
if ($this->configuration->get(item: 'search.enableElasticsearch')) {
return $this->searchElasticsearch($searchTerm, $allLanguages);
}
if ($this->configuration->get(item: 'search.enableOpenSearch')) {
return $this->searchOpenSearch($searchTerm, $allLanguages);
}
return $this->searchDatabase($searchTerm, $allLanguages);
}
/**
* The auto complete function to handle the different search engines.
*
* @param string $searchTerm Text to auto complete
* @throws Exception
*/
public function autoComplete(string $searchTerm): array
{
if ($this->configuration->get(item: 'search.enableElasticsearch')) {
$elasticsearch = new Elasticsearch($this->configuration);
$allCategories = $this->getCategory()->getAllCategoryIds();
$elasticsearch->setCategoryIds($allCategories);
$elasticsearch->setLanguage($this->configuration->getLanguage()->getLanguage());
// Elasticsearch autoComplete now includes custom pages from the index
return $elasticsearch->autoComplete($searchTerm);
}
if ($this->configuration->get(item: 'search.enableOpenSearch')) {
$opensearch = new OpenSearch($this->configuration);
$allCategories = $this->getCategory()->getAllCategoryIds();
$opensearch->setCategoryIds($allCategories);
$opensearch->setLanguage($this->configuration->getLanguage()->getLanguage());
// OpenSearch autoComplete will include custom pages once indexed
return $opensearch->autoComplete($searchTerm);
}
return $this->searchDatabase($searchTerm, false);
}
/**
* The search function for the database powered full text search.
*
* @param string $searchTerm Text/Number (solution id)
* @param bool $allLanguages true to search over all languages
* @throws Exception
*/
public function searchDatabase(string $searchTerm, bool $allLanguages = true): array
{
$fdTable = Database::getTablePrefix() . 'faqdata AS fd';
$fcrTable = Database::getTablePrefix() . 'faqcategoryrelations';
$condition = ['fd.active' => "'yes'"];
$searchDatabase = SearchFactory::create($this->configuration, ['database' =>
$this->resolveSearchDatabaseType()]);
if (!is_null($this->getCategoryId()) && 0 < $this->getCategoryId()) {
if ($this->getCategory() instanceof Category) {
$children = $this->getCategory()->getChildNodes($this->getCategoryId());
$selectedCategory = [
$fcrTable . '.category_id' => array_merge((array) $this->getCategoryId(), $children),
];
}
if (!$this->getCategory() instanceof Category) {
$selectedCategory = [
$fcrTable . '.category_id' => $this->getCategoryId(),
];
}
$condition = [...$selectedCategory, ...$condition];
}
if (!$allLanguages && !is_numeric($searchTerm)) {
$selectedLanguage = ['fd.lang' => "'" . $this->configuration->getLanguage()->getLanguage() . "'"];
$condition = [...$selectedLanguage, ...$condition];
}
$searchDatabase
->setTable($fdTable)
->setResultColumns([
'fd.id AS id',
'fd.lang AS lang',
'fd.solution_id AS solution_id',
$fcrTable . '.category_id AS category_id',
'fd.thema AS question',
'fd.content AS answer',
])
->setJoinedTable($fcrTable)
->setJoinedColumns([
'fd.id = ' . $fcrTable . '.record_id',
'fd.lang = ' . $fcrTable . '.record_lang',
])
->setConditions($condition);
if (is_numeric($searchTerm)) {
$searchDatabase->setMatchingColumns(['fd.solution_id']);
}
if (!is_numeric($searchTerm)) {
$searchDatabase->setMatchingColumns(['fd.thema', 'fd.content', 'fd.keywords']);
}
$result = $searchDatabase->search($searchTerm);
$faqResults = [];
if ($this->configuration->getDb()->numRows($result) > 0) {
$faqResults = $this->configuration->getDb()->fetchAll($result);
}
// Search custom pages (skip if searching by solution ID)
$pageResults = [];
if (!is_numeric($searchTerm)) {
$pageResults = $this->searchCustomPages($searchTerm, $allLanguages);
}
// Merge FAQ and custom page results
return array_merge($faqResults, $pageResults);
}
private function resolveSearchDatabaseType(): string
{
$driverClass = strtolower($this->getDatabaseDriverClassName($this->configuration->getDb()));
return match ($driverClass) {
'pdomysql' => 'pdo_mysql',
'pdopgsql' => 'pdo_pgsql',
'pdosqlite' => 'pdo_sqlite',
'pdosqlsrv' => 'pdo_sqlsrv',
default => $driverClass,
};
}
private function getDatabaseDriverClassName(DatabaseDriver $databaseDriver): string
{
$classNameParts = explode('\\', $databaseDriver::class);
return end($classNameParts);
}
/**
* Search custom pages for the given search term.
*
* @param string $searchTerm Search term
* @param bool $allLanguages Search all languages or current only
* @return array Custom page search results
*/
private function searchCustomPages(string $searchTerm, bool $allLanguages = true): array
{
$cpTable = Database::getTablePrefix() . 'faqcustompages';
$escapedSearchTerm = $this->configuration->getDb()->escape($searchTerm);
// Build WHERE clause with LIKE for custom pages (no FULLTEXT index)
$searchWords = explode(' ', $escapedSearchTerm);
$searchConditions = [];
foreach ($searchWords as $word) {
if (strlen($word) <= 2) {
continue;
}
// Escape LIKE metacharacters (%, _) to prevent wildcard injection
$escapedWord = str_replace(['|', '%', '_'], ['||', '|%', '|_'], $word);
$searchConditions[] = sprintf(
"(page_title LIKE '%%%s%%' ESCAPE '|' OR content LIKE '%%%s%%' ESCAPE '|')",
$escapedWord,
$escapedWord,
);
}
if ($searchConditions === []) {
return [];
}
$searchClause = implode(' OR ', $searchConditions);
// Build language condition
$langCondition = '';
if (!$allLanguages) {
$langCondition = sprintf(" AND lang = '%s'", $this->configuration->getLanguage()->getLanguage());
}
// Build the query
$query = sprintf("
SELECT
id,
lang,
0 AS solution_id,
0 AS category_id,
page_title AS question,
content AS answer,
slug,
0.5 AS score
FROM
%s
WHERE
active = 'y'
%s
AND (%s)
", $cpTable, $langCondition, $searchClause);
$result = $this->configuration->getDb()->query($query);
if (!$result || $this->configuration->getDb()->numRows($result) === 0) {
return [];
}
$pages = $this->configuration->getDb()->fetchAll($result);
// Mark results as custom pages for later identification
foreach ($pages as &$page) {
$page->content_type = 'page';
}
return $pages;
}
/**
* The search function for the Elasticsearch powered full text search.
*
* @param string $searchTerm Text/Number (solution id)
* @param bool $allLanguages true to search over all languages
* @return stdClass[]
*/
public function searchElasticsearch(string $searchTerm, bool $allLanguages = true): array
{
$elasticsearch = new Elasticsearch($this->configuration);
$allCategories = $this->getCategory()->getAllCategoryIds();
$elasticsearch->setCategoryIds($allCategories);
if (!is_null($this->getCategoryId()) && 0 < $this->getCategoryId()) {
$children = $this->getCategory()->getChildNodes($this->getCategoryId());
$elasticsearch->setCategoryIds(array_merge([$this->getCategoryId()], $children));
}
if (!$allLanguages) {
$elasticsearch->setLanguage($this->configuration->getLanguage()->getLanguage());
}
// Elasticsearch search now includes custom pages in the index
return $elasticsearch->search($searchTerm);
}
public function searchOpenSearch(string $searchTerm, bool $allLanguages = true): array
{
$opensearch = new OpenSearch($this->configuration);
$allCategories = $this->getCategory()->getAllCategoryIds();
$opensearch->setCategoryIds($allCategories);
if (!is_null($this->getCategoryId()) && 0 < $this->getCategoryId()) {
$children = $this->getCategory()->getChildNodes($this->getCategoryId());
$opensearch->setCategoryIds(array_merge([$this->getCategoryId()], $children));
}
if (!$allLanguages) {
$opensearch->setLanguage($this->configuration->getLanguage()->getLanguage());
}
// OpenSearch search now includes custom pages in the index
return $opensearch->search($searchTerm);
}
/**
* Logging of search terms for improvements.
*
* @param string $searchTerm Search term
* @throws Exception
*/
public function logSearchTerm(string $searchTerm): void
{
if (Strings::strlen($searchTerm) === 0) {
return;
}
$dateTime = new DateTime();
$query = sprintf(
"INSERT INTO %s (id, lang, searchterm, searchdate) VALUES (%d, '%s', '%s', '%s')",
$this->table,
$this->configuration->getDb()->nextId($this->table, 'id'),
$this->configuration->getLanguage()->getLanguage(),
$this->configuration->getDb()->escape($searchTerm),
$dateTime->format('Y-m-d H:i:s'),
);
$this->configuration->getDb()->query($query);
}
/**
* Deletes a search term.
*/
public function deleteSearchTermById(int $searchTermId): bool
{
$query = sprintf("DELETE FROM %s WHERE id = '%d'", $this->table, $searchTermId);
return (bool) $this->configuration->getDb()->query($query);
}
/**
* Deletes all search terms.
*/
public function deleteAllSearchTerms(): bool
{
$query = sprintf('DELETE FROM %s', $this->table);
return (bool) $this->configuration->getDb()->query($query);
}
/**
* Returns the most popular searches.
*
* @param int $numResults Number of Results, default: 7
* @param bool $withLang Should the language be included in the result?
* @param int $timeWindow Number of days to look back for searches, 0 for all time
*
* @return array<string[]>
*/
public function getMostPopularSearches(int $numResults = 7, bool $withLang = false, int $timeWindow = 0): array
{
$searchResult = [];
$byLang = $withLang ? ', lang' : '';
$timeCondition = '';
if ($timeWindow > 0) {
$dbType = Database::getType();
$timeCondition = match ($dbType) {
'pgsql', 'pdo_pgsql' => sprintf(" WHERE searchdate >= NOW() - INTERVAL '%d days'", $timeWindow),
'sqlite3', 'pdo_sqlite' => sprintf(" WHERE searchdate >= datetime('now', '-%d days')", $timeWindow),
'sqlsrv', 'pdo_sqlsrv' => sprintf(' WHERE searchdate >= DATEADD(day, -%d, GETDATE())', $timeWindow),
default => sprintf(' WHERE searchdate >= DATE_SUB(NOW(), INTERVAL %d DAY)', $timeWindow),
};
}
// Build database-specific LIMIT clause
$dbType = Database::getType();
$limitClause = match ($dbType) {
'sqlsrv', 'pdo_sqlsrv' => sprintf('OFFSET 0 ROWS FETCH NEXT %d ROWS ONLY', $numResults),
default => sprintf('LIMIT %d', $numResults),
};
$query = sprintf('
SELECT
MIN(id) as id, searchterm, COUNT(searchterm) AS number %s
FROM
%s%s
GROUP BY
searchterm %s
ORDER BY
number DESC
%s', $byLang, $this->table, $timeCondition, $byLang, $limitClause);
$result = $this->configuration->getDb()->query($query);
if (false !== $result) {
while (true) {
$row = $this->configuration->getDb()->fetchObject($result);
if (!is_object($row)) {
break;
}
$searchResult[] = (array) $row;
}
}
return $searchResult;
}
/**
* Returns row count from the "faqsearches" table.
*/
public function getSearchesCount(): int
{
$sql = sprintf('SELECT COUNT(*) AS count FROM %s', $this->table);
$result = $this->configuration->getDb()->query($sql);
return (int) $this->configuration->getDb()->fetchObject($result)->count;
}
public function setCategory(Category $category): void
{
$this->category = $category;
}
public function getCategory(): Category
{
return $this->category;
}
}