DatabaseDAO.php 18 KB

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