DatabaseDAO.php 18 KB

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