DatabaseDAO.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This class is used to test database is well-constructed.
  5. */
  6. class FreshRSS_DatabaseDAO extends Minz_ModelPdo {
  7. //MySQL error codes
  8. public const ER_BAD_FIELD_ERROR = '42S22';
  9. public const ER_BAD_TABLE_ERROR = '42S02';
  10. public const ER_DATA_TOO_LONG = '1406';
  11. /**
  12. * Based on SQLite SQLITE_MAX_VARIABLE_NUMBER
  13. */
  14. public const MAX_VARIABLE_NUMBER = 998;
  15. //MySQL InnoDB maximum index length for UTF8MB4
  16. //https://dev.mysql.com/doc/refman/8.0/en/innodb-restrictions.html
  17. public const LENGTH_INDEX_UNICODE = 191;
  18. public function create(): string {
  19. require_once APP_PATH . '/SQL/install.sql.' . $this->pdo->dbType() . '.php';
  20. $db = FreshRSS_Context::systemConf()->db;
  21. try {
  22. $sql = $GLOBALS['SQL_CREATE_DB'];
  23. if (!is_string($sql)) {
  24. throw new Exception('SQL_CREATE_DB is not a string!');
  25. }
  26. $sql = sprintf($sql, empty($db['base']) ? '' : $db['base']);
  27. return $this->pdo->exec($sql) === false ? 'Error during CREATE DATABASE' : '';
  28. } catch (Exception $e) {
  29. syslog(LOG_DEBUG, __METHOD__ . ' notice: ' . $e->getMessage());
  30. return $e->getMessage();
  31. }
  32. }
  33. public function testConnection(): string {
  34. try {
  35. $sql = <<<'SQL'
  36. SELECT 1
  37. SQL;
  38. $stm = $this->pdo->query($sql);
  39. if ($stm === false) {
  40. return 'Error during SQL connection test!';
  41. }
  42. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  43. return $res == false ? 'Error during SQL connection fetch test!' : '';
  44. } catch (Exception $e) {
  45. syslog(LOG_DEBUG, __METHOD__ . ' warning: ' . $e->getMessage());
  46. return $e->getMessage();
  47. }
  48. }
  49. public function exits(): bool {
  50. $sql = <<<'SQL'
  51. SELECT * FROM `_entry` LIMIT 1
  52. SQL;
  53. $stm = $this->pdo->query($sql);
  54. if ($stm !== false) {
  55. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  56. if ($res !== false) {
  57. return true;
  58. }
  59. }
  60. return false;
  61. }
  62. public function tablesAreCorrect(): bool {
  63. $res = $this->fetchAssoc('SHOW TABLES');
  64. if ($res == null) {
  65. return false;
  66. }
  67. $tables = [
  68. $this->pdo->prefix() . 'category' => false,
  69. $this->pdo->prefix() . 'feed' => false,
  70. $this->pdo->prefix() . 'entry' => false,
  71. $this->pdo->prefix() . 'entrytmp' => false,
  72. $this->pdo->prefix() . 'tag' => false,
  73. $this->pdo->prefix() . 'entrytag' => false,
  74. ];
  75. foreach ($res as $value) {
  76. $tables[array_pop($value)] = true;
  77. }
  78. return count(array_keys($tables, true, true)) === count($tables);
  79. }
  80. /** @return list<array{name:string,type:string,notnull:bool,default:mixed}> */
  81. public function getSchema(string $table): array {
  82. $res = $this->fetchAssoc('DESC `_' . $table . '`');
  83. return $res == null ? [] : $this->listDaoToSchema($res);
  84. }
  85. /**
  86. * Verify that database table has at least the given columns
  87. *
  88. * @param string $table
  89. * @param array<string> $expectedColumns
  90. */
  91. public function checkTable(string $table, array $expectedColumns): bool {
  92. $columnInfo = $this->getSchema($table);
  93. $exististingColumns = array_column($columnInfo, 'name');
  94. if (count($exististingColumns) === 0 || count($expectedColumns) === 0) {
  95. return false;
  96. }
  97. //allow for extensions adding additional columns
  98. $ok = count($exististingColumns) >= count($expectedColumns);
  99. foreach ($expectedColumns as $name) {
  100. $ok &= in_array($name, $exististingColumns, true);
  101. }
  102. return (bool)$ok;
  103. }
  104. public function categoryIsCorrect(): bool {
  105. return $this->checkTable('category', [
  106. 'id',
  107. 'name',
  108. 'kind',
  109. 'lastUpdate',
  110. 'error',
  111. 'attributes',
  112. ]);
  113. }
  114. public function feedIsCorrect(): bool {
  115. return $this->checkTable('feed', [
  116. 'id',
  117. 'url',
  118. 'kind',
  119. 'category',
  120. 'name',
  121. 'website',
  122. 'description',
  123. 'lastUpdate',
  124. 'priority',
  125. 'pathEntries',
  126. 'httpAuth',
  127. 'error',
  128. 'ttl',
  129. 'attributes',
  130. 'cache_nbEntries',
  131. 'cache_nbUnreads',
  132. ]);
  133. }
  134. public function entryIsCorrect(): bool {
  135. $entryDAO = FreshRSS_Factory::createEntryDao();
  136. return $this->checkTable('entry', [
  137. 'id',
  138. 'guid',
  139. 'title',
  140. 'author',
  141. $entryDAO::isCompressed() ? 'content_bin' : 'content',
  142. 'link',
  143. 'date',
  144. 'lastSeen',
  145. 'lastUserModified',
  146. 'hash',
  147. 'is_read',
  148. 'is_favorite',
  149. 'id_feed',
  150. 'tags',
  151. 'attributes',
  152. ]);
  153. }
  154. public function entrytmpIsCorrect(): bool {
  155. $entryDAO = FreshRSS_Factory::createEntryDao();
  156. return $this->checkTable('entrytmp', [
  157. 'id',
  158. 'guid',
  159. 'title',
  160. 'author',
  161. $entryDAO::isCompressed() ? 'content_bin' : 'content',
  162. 'link',
  163. 'date',
  164. 'lastSeen',
  165. 'hash',
  166. 'is_read',
  167. 'is_favorite',
  168. 'id_feed',
  169. 'tags',
  170. 'attributes',
  171. ]);
  172. }
  173. public function tagIsCorrect(): bool {
  174. return $this->checkTable('tag', ['id', 'name', 'attributes']);
  175. }
  176. public function entrytagIsCorrect(): bool {
  177. return $this->checkTable('entrytag', ['id_tag', 'id_entry']);
  178. }
  179. /**
  180. * @param array<string,string|int|bool|null> $dao
  181. * @return array{name:string,type:string,notnull:bool,default:mixed}
  182. */
  183. public function daoToSchema(array $dao): array {
  184. return [
  185. 'name' => is_string($dao['Field'] ?? null) ? $dao['Field'] : '',
  186. 'type' => is_string($dao['Type'] ?? null) ? strtolower($dao['Type']) : '',
  187. 'notnull' => empty($dao['Null']),
  188. 'default' => is_scalar($dao['Default'] ?? null) ? $dao['Default'] : null,
  189. ];
  190. }
  191. /**
  192. * @param array<array<string,string|int|bool|null>> $listDAO
  193. * @return list<array{name:string,type:string,notnull:bool,default:mixed}>
  194. */
  195. public function listDaoToSchema(array $listDAO): array {
  196. $list = [];
  197. foreach ($listDAO as $dao) {
  198. $list[] = $this->daoToSchema($dao);
  199. }
  200. return $list;
  201. }
  202. private static ?string $staticVersion = null;
  203. /**
  204. * To override the database version. Useful for testing.
  205. */
  206. public static function setStaticVersion(?string $version): void {
  207. self::$staticVersion = $version;
  208. }
  209. protected function selectVersion(): string {
  210. return $this->fetchString('SELECT version()') ?? '';
  211. }
  212. public function version(): string {
  213. if (self::$staticVersion !== null) {
  214. return self::$staticVersion;
  215. }
  216. static $version = null;
  217. if (!is_string($version)) {
  218. $version = $this->selectVersion();
  219. }
  220. return $version;
  221. }
  222. public function pdoClientVersion(): string {
  223. $version = $this->pdo->getAttribute(PDO::ATTR_CLIENT_VERSION);
  224. return is_string($version) ? $version : '';
  225. }
  226. final public function isMariaDB(): bool {
  227. // MariaDB includes its name in version, but not MySQL
  228. return str_contains($this->version(), 'MariaDB');
  229. }
  230. /**
  231. * @return bool true if the database PDO driver returns typed integer values as it should, false otherwise.
  232. */
  233. final public function testTyping(): bool {
  234. $sql = <<<'SQL'
  235. SELECT 2 + 3
  236. SQL;
  237. if (($stm = $this->pdo->query($sql)) !== false) {
  238. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  239. return ($res[0] ?? null) === 5;
  240. }
  241. return false;
  242. }
  243. public function size(bool $all = false): int {
  244. $db = FreshRSS_Context::systemConf()->db;
  245. // MariaDB does not refresh size information automatically
  246. $sql = <<<'SQL'
  247. ANALYZE TABLE `_category`, `_feed`, `_entry`, `_entrytmp`, `_tag`, `_entrytag`
  248. SQL;
  249. $stm = $this->pdo->query($sql);
  250. if ($stm !== false) {
  251. $stm->fetchAll();
  252. }
  253. //MySQL:
  254. $sql = <<<'SQL'
  255. SELECT SUM(DATA_LENGTH + INDEX_LENGTH + DATA_FREE)
  256. FROM information_schema.TABLES WHERE TABLE_SCHEMA=:table_schema
  257. SQL;
  258. $values = [':table_schema' => $db['base']];
  259. if (!$all) {
  260. $sql .= "\n" . <<<'SQL'
  261. AND table_name LIKE :table_name
  262. SQL;
  263. $values[':table_name'] = addcslashes($this->pdo->prefix(), '\\%_') . '%';
  264. }
  265. $res = $this->fetchColumn($sql, 0, $values);
  266. return isset($res[0]) ? (int)($res[0]) : -1;
  267. }
  268. public function optimize(): bool {
  269. $ok = true;
  270. $tables = ['category', 'feed', 'entry', 'entrytmp', 'tag', 'entrytag'];
  271. foreach ($tables as $table) {
  272. $sql = <<<SQL
  273. OPTIMIZE TABLE `_{$table}`
  274. SQL; //MySQL
  275. $stm = $this->pdo->query($sql);
  276. if ($stm === false || $stm->fetchAll(PDO::FETCH_ASSOC) == false) {
  277. $ok = false;
  278. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  279. Minz_Log::warning(__METHOD__ . ' error: ' . $sql . ' : ' . json_encode($info));
  280. }
  281. }
  282. return $ok;
  283. }
  284. public function minorDbMaintenance(): void {
  285. $catDAO = FreshRSS_Factory::createCategoryDao();
  286. $catDAO->resetDefaultCategoryName();
  287. include_once APP_PATH . '/SQL/install.sql.' . $this->pdo->dbType() . '.php';
  288. if (!empty($GLOBALS['SQL_UPDATE_MINOR']) && is_string($GLOBALS['SQL_UPDATE_MINOR'])) {
  289. $sql = $GLOBALS['SQL_UPDATE_MINOR'];
  290. $isMariaDB = false;
  291. if ($this->pdo->dbType() === 'mysql') {
  292. $isMariaDB = $this->isMariaDB();
  293. if (!$isMariaDB) {
  294. // MySQL does not support `DROP INDEX IF EXISTS` yet https://dev.mysql.com/doc/refman/8.3/en/drop-index.html
  295. // but MariaDB does https://mariadb.com/kb/en/drop-index/
  296. $sql = str_replace('DROP INDEX IF EXISTS', 'DROP INDEX', $sql);
  297. }
  298. }
  299. if ($this->pdo->exec($sql) === false) {
  300. $info = $this->pdo->errorInfo();
  301. if ($this->pdo->dbType() === 'mysql' &&
  302. !$isMariaDB && is_string($info[2] ?? null) && (stripos($info[2], "Can't DROP ") !== false)) {
  303. // Too bad for MySQL, but ignore error
  304. return;
  305. }
  306. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($this->pdo->errorInfo()));
  307. }
  308. }
  309. }
  310. private static function stdError(string $error): bool {
  311. if (defined('STDERR')) {
  312. fwrite(STDERR, $error . "\n");
  313. }
  314. Minz_Log::error($error);
  315. return false;
  316. }
  317. public const SQLITE_EXPORT = 1;
  318. public const SQLITE_IMPORT = 2;
  319. public function dbCopy(string $filename, int $mode, bool $clearFirst = false, bool $verbose = true): bool {
  320. if (!extension_loaded('pdo_sqlite')) {
  321. return self::stdError('PHP extension pdo_sqlite is missing!');
  322. }
  323. $error = '';
  324. $databaseDAO = FreshRSS_Factory::createDatabaseDAO();
  325. $userDAO = FreshRSS_Factory::createUserDao();
  326. $catDAO = FreshRSS_Factory::createCategoryDao();
  327. $feedDAO = FreshRSS_Factory::createFeedDao();
  328. $entryDAO = FreshRSS_Factory::createEntryDao();
  329. $tagDAO = FreshRSS_Factory::createTagDao();
  330. switch ($mode) {
  331. case self::SQLITE_EXPORT:
  332. if (@filesize($filename) > 0) {
  333. $error = 'Error: SQLite export file already exists: ' . $filename;
  334. }
  335. break;
  336. case self::SQLITE_IMPORT:
  337. if (!is_readable($filename)) {
  338. $error = 'Error: SQLite import file is not readable: ' . $filename;
  339. } elseif ($clearFirst) {
  340. $userDAO->deleteUser();
  341. $userDAO = FreshRSS_Factory::createUserDao();
  342. if ($this->pdo->dbType() === 'sqlite') {
  343. //We cannot just delete the .sqlite file otherwise PDO gets buggy.
  344. //SQLite is the only one with database-level optimization, instead of at table level.
  345. $this->optimize();
  346. }
  347. } elseif ($databaseDAO->exits() && $entryDAO->count() > 0) {
  348. $error = 'Error: Destination database already contains some entries!';
  349. }
  350. break;
  351. default:
  352. $error = 'Invalid copy mode!';
  353. break;
  354. }
  355. if ($error != '') {
  356. return self::stdError($error);
  357. }
  358. $sqlite = null;
  359. try {
  360. $sqlite = new Minz_PdoSqlite('sqlite:' . $filename);
  361. $sqlite->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
  362. } catch (Exception $e) {
  363. $error = 'Error while initialising SQLite copy: ' . $e->getMessage();
  364. return self::stdError($error);
  365. }
  366. Minz_ModelPdo::clean();
  367. $userDAOSQLite = new FreshRSS_UserDAO('', $sqlite);
  368. $categoryDAOSQLite = new FreshRSS_CategoryDAOSQLite('', $sqlite);
  369. $feedDAOSQLite = new FreshRSS_FeedDAOSQLite('', $sqlite);
  370. $entryDAOSQLite = new FreshRSS_EntryDAOSQLite('', $sqlite);
  371. $tagDAOSQLite = new FreshRSS_TagDAOSQLite('', $sqlite);
  372. switch ($mode) {
  373. case self::SQLITE_EXPORT:
  374. $userFrom = $userDAO; $userTo = $userDAOSQLite;
  375. $catFrom = $catDAO; $catTo = $categoryDAOSQLite;
  376. $feedFrom = $feedDAO; $feedTo = $feedDAOSQLite;
  377. $entryFrom = $entryDAO; $entryTo = $entryDAOSQLite;
  378. $tagFrom = $tagDAO; $tagTo = $tagDAOSQLite;
  379. break;
  380. case self::SQLITE_IMPORT:
  381. $userFrom = $userDAOSQLite; $userTo = $userDAO;
  382. $catFrom = $categoryDAOSQLite; $catTo = $catDAO;
  383. $feedFrom = $feedDAOSQLite; $feedTo = $feedDAO;
  384. $entryFrom = $entryDAOSQLite; $entryTo = $entryDAO;
  385. $tagFrom = $tagDAOSQLite; $tagTo = $tagDAO;
  386. break;
  387. default:
  388. return false;
  389. }
  390. $idMaps = [];
  391. if (defined('STDERR') && $verbose) {
  392. fwrite(STDERR, "Start SQL copy…\n");
  393. }
  394. $userTo->createUser();
  395. $catTo->beginTransaction();
  396. $catTo->deleteCategory(FreshRSS_CategoryDAO::DEFAULTCATEGORYID);
  397. $catTo->sqlResetSequence();
  398. foreach ($catFrom->selectAll() as $category) {
  399. $catId = $catTo->addCategory($category);
  400. if ($catId === false) {
  401. $error = 'Error during SQLite copy of categories!';
  402. return self::stdError($error);
  403. }
  404. $idMaps['c' . $category['id']] = $catId;
  405. }
  406. $catTo->sqlResetSequence();
  407. foreach ($feedFrom->selectAll() as $feed) {
  408. $feed['category'] = empty($idMaps['c' . $feed['category']]) ? FreshRSS_CategoryDAO::DEFAULTCATEGORYID : $idMaps['c' . $feed['category']];
  409. $feedId = $feedTo->addFeed($feed);
  410. if ($feedId == false) {
  411. $error = 'Error during SQLite copy of feeds!';
  412. return self::stdError($error);
  413. }
  414. $idMaps['f' . $feed['id']] = $feedId;
  415. }
  416. $feedTo->sqlResetSequence();
  417. $catTo->commit();
  418. $nbEntries = $entryFrom->count();
  419. $n = 0;
  420. $brokenEntries = 0;
  421. $entryTo->beginTransaction();
  422. while ($n < $nbEntries) {
  423. foreach ($entryFrom->selectAll(offset: $n) as $entry) {
  424. $n++;
  425. if (!empty($idMaps['f' . $entry['id_feed']])) {
  426. $entry['id_feed'] = $idMaps['f' . $entry['id_feed']];
  427. if (!$entryTo->addEntry($entry, false)) {
  428. $error = 'Error during SQLite copy of entries!';
  429. return self::stdError($error);
  430. }
  431. }
  432. if ($n % 100 === 1 && defined('STDERR') && $verbose) { //Display progression
  433. fwrite(STDERR, "\033[0G" . $n . '/' . $nbEntries . ($brokenEntries > 0 ? " ($brokenEntries broken)" : ''));
  434. }
  435. }
  436. if ($n < $nbEntries) {
  437. $brokenEntries++;
  438. // Attempt to skip broken records in the case of corrupted database
  439. $n++;
  440. }
  441. if (defined('STDERR') && $verbose) {
  442. fwrite(STDERR, "\033[0G" . $n . '/' . $nbEntries . ($brokenEntries > 0 ? " ($brokenEntries broken)" : '') . PHP_EOL);
  443. }
  444. }
  445. $entryTo->commit();
  446. $feedTo->updateCachedValues();
  447. $idMaps = [];
  448. $tagTo->beginTransaction();
  449. foreach ($tagFrom->selectAll() as $tag) {
  450. $tagId = $tagTo->addTag($tag);
  451. if ($tagId == false) {
  452. $error = 'Error during SQLite copy of tags!';
  453. return self::stdError($error);
  454. }
  455. $idMaps['t' . $tag['id']] = $tagId;
  456. }
  457. foreach ($tagFrom->selectEntryTag() as $entryTag) {
  458. if (!empty($idMaps['t' . $entryTag['id_tag']])) {
  459. $entryTag['id_tag'] = $idMaps['t' . $entryTag['id_tag']];
  460. if (!$tagTo->tagEntry($entryTag['id_tag'], (string)$entryTag['id_entry'])) {
  461. $error = 'Error during SQLite copy of entry-tags!';
  462. return self::stdError($error);
  463. }
  464. }
  465. }
  466. $tagTo->sqlResetSequence();
  467. $tagTo->commit();
  468. return true;
  469. }
  470. /**
  471. * Remove accents from characters and lowercase. Relevant for emulating MySQL utf8mb4_unicode_ci collation.
  472. * Example: `Café` becomes `cafe`.
  473. */
  474. private static function removeAccentsLower(string $str): string {
  475. if (function_exists('transliterator_transliterate')) {
  476. // https://unicode-org.github.io/icu/userguide/transforms/general/#overview
  477. $transliterated = transliterator_transliterate('NFD; [:Nonspacing Mark:] Remove; NFC; Lower', $str);
  478. if ($transliterated !== false) {
  479. return $transliterated;
  480. }
  481. }
  482. // Fallback covering only Latin: Windows-1252 / ISO-8859-15 / ISO-8859-1, Windows-1250 / ISO-8859-2, Windows-1257 / ISO-8859-13, Windows-1254 / ISO-8859-9
  483. // phpcs:disable PSR12.Operators.OperatorSpacing.NoSpaceBefore, PSR12.Operators.OperatorSpacing.NoSpaceAfter, Squiz.WhiteSpace.OperatorSpacing.NoSpaceBefore, Squiz.WhiteSpace.OperatorSpacing.NoSpaceAfter
  484. $replacements = [
  485. 'A' => 'a', 'À'=>'a', 'Á'=>'a', 'Â'=>'a', 'Ä'=>'a', 'Ã'=>'a', 'Å'=>'a', 'Ă'=>'a', 'Ą'=>'a', 'Ā'=>'a',
  486. 'à'=>'a', 'á'=>'a', 'â'=>'a', 'ä'=>'a', 'ã'=>'a', 'å'=>'a', 'ă'=>'a', 'ą'=>'a', 'ā'=>'a',
  487. 'B' => 'b',
  488. 'C' => 'c', 'Ç'=>'c', 'Ć'=>'c', 'Č'=>'c', 'ç'=>'c', 'ć'=>'c', 'č'=>'c',
  489. 'D' => 'd', 'Ď'=>'d', 'Đ'=>'d', 'ď'=>'d', 'đ'=>'d',
  490. 'E' => 'e', 'È'=>'e', 'É'=>'e', 'Ê'=>'e', 'Ë'=>'e', 'Ę'=>'e', 'Ě'=>'e', 'Ē'=>'e', 'Ė'=>'e',
  491. 'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ę'=>'e', 'ě'=>'e', 'ē'=>'e', 'ė'=>'e',
  492. 'F' => 'f',
  493. 'G' => 'g', 'Ğ'=>'g', 'Ģ'=>'g', 'ğ'=>'g', 'ģ'=>'g',
  494. 'H' => 'h',
  495. 'I' => 'i', 'Ì'=>'i', 'Í'=>'i', 'Î'=>'i', 'Ï'=>'i', 'İ'=>'i', 'Ī'=>'i', 'Į'=>'i',
  496. 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ı'=>'i', 'ī'=>'i', 'į'=>'i',
  497. 'J' => 'j',
  498. 'K' => 'k', 'Ķ'=>'k', 'ķ'=>'k',
  499. 'L' => 'l', 'Ĺ'=>'l', 'Ľ'=>'l', 'Ł'=>'l', 'Ļ'=>'l', 'ĺ'=>'l', 'ľ'=>'l', 'ł'=>'l', 'ļ'=>'l',
  500. 'M' => 'm',
  501. 'N' => 'n', 'Ñ'=>'n', 'Ń'=>'n', 'Ň'=>'n', 'Ņ'=>'n', 'ñ'=>'n', 'ń'=>'n', 'ň'=>'n', 'ņ'=>'n',
  502. 'O' => 'o', 'Ò'=>'o', 'Ó'=>'o', 'Ô'=>'o', 'Ö'=>'o', 'Õ'=>'o', 'Ø'=>'o', 'Ő'=>'o', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'ö'=>'o', 'õ'=>'o', 'ø'=>'o', 'ő'=>'o',
  503. 'P' => 'p',
  504. 'Q' => 'q',
  505. 'R' => 'r', 'Ŕ'=>'r', 'Ř'=>'r', 'ŕ'=>'r', 'ř'=>'r',
  506. 'S' => 's', 'Ś'=>'s', 'Š'=>'s', 'Ş'=>'s', 'ß'=>'ss', 'ś'=>'s', 'š'=>'s', 'ş'=>'s',
  507. 'T' => 't', 'Ť'=>'t', 'Ţ'=>'t', 'ť'=>'t', 'ţ'=>'t',
  508. 'U' => 'u', 'Ù'=>'u', 'Ú'=>'u', 'Û'=>'u', 'Ü'=>'u', 'Ů'=>'u', 'Ű'=>'u', 'Ū'=>'u', 'Ų'=>'u',
  509. 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ü'=>'u', 'ů'=>'u', 'ű'=>'u', 'ū'=>'u', 'ų'=>'u',
  510. 'V' => 'v',
  511. 'W' => 'w',
  512. 'X' => 'x',
  513. 'Y' => 'y', 'Ý'=>'y', 'Ÿ'=>'y', 'ý'=>'y', 'ÿ'=>'y',
  514. 'Z' => 'z', 'Ź'=>'z', 'Ż'=>'z', 'Ž'=>'z', 'ź'=>'z', 'ż'=>'z', 'ž'=>'z',
  515. 'Æ'=>'ae', 'æ'=>'ae',
  516. 'Œ'=>'oe', 'œ'=>'oe',
  517. ];
  518. // phpcs:enable PSR12.Operators.OperatorSpacing.NoSpaceBefore, PSR12.Operators.OperatorSpacing.NoSpaceAfter, Squiz.WhiteSpace.OperatorSpacing.NoSpaceBefore, Squiz.WhiteSpace.OperatorSpacing.NoSpaceAfter
  519. return strtr($str, $replacements);
  520. }
  521. /**
  522. * PHP emulation of the SQL ILIKE operation of the selected database.
  523. * Note that it depends on the database collation settings and Unicode extensions.
  524. * @param bool $contains If true, checks whether $haystack contains $needle (`'Testing' ILIKE '%Test%'`),
  525. * otherwise checks whether they are alike (`'Testing' ILIKE 'Test'`).
  526. */
  527. public static function strilike(string $haystack, string $needle, bool $contains = false): bool {
  528. // Implementation approximating MySQL/MariaDB `LIKE` with `utf8mb4_unicode_ci` collation.
  529. $haystack = self::removeAccentsLower($haystack);
  530. $needle = self::removeAccentsLower($needle);
  531. return $contains ? str_contains($haystack, $needle) : ($haystack === $needle);
  532. }
  533. }