Update website

This commit is contained in:
Guilhem Lavaux 2024-11-23 20:45:29 +01:00
parent 41ce1aa076
commit ea0eb1c6e0
4222 changed files with 721797 additions and 14 deletions

View file

@ -0,0 +1,136 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\MoTranslator\Cache;
use PhpMyAdmin\MoTranslator\CacheException;
use PhpMyAdmin\MoTranslator\MoParser;
use function apcu_enabled;
use function apcu_entry;
use function apcu_exists;
use function apcu_fetch;
use function apcu_store;
use function array_combine;
use function array_keys;
use function array_map;
use function assert;
use function function_exists;
use function is_array;
use function is_string;
final class ApcuCache implements CacheInterface
{
public const LOADED_KEY = '__TRANSLATIONS_LOADED__';
/** @var MoParser */
private $parser;
/** @var string */
private $locale;
/** @var string */
private $domain;
/** @var int */
private $ttl;
/** @var bool */
private $reloadOnMiss;
/** @var string */
private $prefix;
public function __construct(
MoParser $parser,
string $locale,
string $domain,
int $ttl = 0,
bool $reloadOnMiss = true,
string $prefix = 'mo_'
) {
if (! (function_exists('apcu_enabled') && apcu_enabled())) {
throw new CacheException('ACPu extension must be installed and enabled');
}
$this->parser = $parser;
$this->locale = $locale;
$this->domain = $domain;
$this->ttl = $ttl;
$this->reloadOnMiss = $reloadOnMiss;
$this->prefix = $prefix;
$this->ensureTranslationsLoaded();
}
public function get(string $msgid): string
{
$msgstr = apcu_fetch($this->getKey($msgid), $success);
if ($success && is_string($msgstr)) {
return $msgstr;
}
if (! $this->reloadOnMiss) {
return $msgid;
}
return $this->reloadOnMiss($msgid);
}
private function reloadOnMiss(string $msgid): string
{
// store original if translation is not present
$cached = apcu_entry($this->getKey($msgid), static function () use ($msgid) {
return $msgid;
}, $this->ttl);
// if another process has updated cache, return early
if ($cached !== $msgid && is_string($cached)) {
return $cached;
}
// reload .mo file, in case entry has been evicted
$this->parser->parseIntoCache($this);
$msgstr = apcu_fetch($this->getKey($msgid), $success);
return $success && is_string($msgstr) ? $msgstr : $msgid;
}
public function set(string $msgid, string $msgstr): void
{
apcu_store($this->getKey($msgid), $msgstr, $this->ttl);
}
public function has(string $msgid): bool
{
return apcu_exists($this->getKey($msgid));
}
public function setAll(array $translations): void
{
$keys = array_map(function (string $msgid): string {
return $this->getKey($msgid);
}, array_keys($translations));
$translations = array_combine($keys, $translations);
assert(is_array($translations));
apcu_store($translations, null, $this->ttl);
}
private function getKey(string $msgid): string
{
return $this->prefix . $this->locale . '.' . $this->domain . '.' . $msgid;
}
private function ensureTranslationsLoaded(): void
{
// Try to prevent cache slam if multiple processes are trying to load translations. There is still a race
// between the exists check and creating the entry, but at least it's small
$key = $this->getKey(self::LOADED_KEY);
$loaded = apcu_exists($key) || apcu_entry($key, static function (): int {
return 0;
}, $this->ttl);
if ($loaded) {
return;
}
$this->parser->parseIntoCache($this);
apcu_store($this->getKey(self::LOADED_KEY), 1, $this->ttl);
}
}

View file

@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\MoTranslator\Cache;
use PhpMyAdmin\MoTranslator\MoParser;
final class ApcuCacheFactory implements CacheFactoryInterface
{
/** @var int */
private $ttl;
/** @var bool */
private $reloadOnMiss;
/** @var string */
private $prefix;
public function __construct(int $ttl = 0, bool $reloadOnMiss = true, string $prefix = 'mo_')
{
$this->ttl = $ttl;
$this->reloadOnMiss = $reloadOnMiss;
$this->prefix = $prefix;
}
public function getInstance(MoParser $parser, string $locale, string $domain): CacheInterface
{
return new ApcuCache($parser, $locale, $domain, $this->ttl, $this->reloadOnMiss, $this->prefix);
}
}

View file

@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\MoTranslator\Cache;
use PhpMyAdmin\MoTranslator\MoParser;
interface CacheFactoryInterface
{
public function getInstance(MoParser $parser, string $locale, string $domain): CacheInterface;
}

View file

@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\MoTranslator\Cache;
interface CacheInterface
{
/**
* Returns cached `msgstr` if it is in cache, otherwise `$msgid`
*/
public function get(string $msgid): string;
/**
* Caches `$msgstr` value for key `$mesid`
*/
public function set(string $msgid, string $msgstr): void;
/**
* Returns true if cache has entry for `$msgid`
*/
public function has(string $msgid): bool;
/**
* Populates cache with array of `$msgid => $msgstr` entries
*
* This will overwrite existing values for `$msgid`, but is not guaranteed to clear cache of existing entries
* not present in `$translations`.
*
* @param array<string, string> $translations
*/
public function setAll(array $translations): void;
}

View file

@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\MoTranslator\Cache;
interface GetAllInterface
{
/**
* @return array<string, string>
*/
public function getAll(): array;
}

View file

@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\MoTranslator\Cache;
use PhpMyAdmin\MoTranslator\MoParser;
use function array_key_exists;
final class InMemoryCache implements CacheInterface, GetAllInterface
{
/** @var array<string, string> */
private $cache;
public function __construct(MoParser $parser)
{
$this->cache = [];
$parser->parseIntoCache($this);
}
public function get(string $msgid): string
{
return array_key_exists($msgid, $this->cache) ? $this->cache[$msgid] : $msgid;
}
public function set(string $msgid, string $msgstr): void
{
$this->cache[$msgid] = $msgstr;
}
public function has(string $msgid): bool
{
return array_key_exists($msgid, $this->cache);
}
public function setAll(array $translations): void
{
$this->cache = $translations;
}
/**
* @inheritDoc
*/
public function getAll(): array
{
return $this->cache;
}
}

View file

@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\MoTranslator;
use DomainException;
final class CacheException extends DomainException
{
}

View file

@ -0,0 +1,318 @@
<?php
declare(strict_types=1);
/*
Copyright (c) 2005 Steven Armstrong <sa at c-area dot ch>
Copyright (c) 2009 Danilo Segan <danilo@kvota.net>
Copyright (c) 2016 Michal Čihař <michal@cihar.com>
This file is part of MoTranslator.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
namespace PhpMyAdmin\MoTranslator;
use PhpMyAdmin\MoTranslator\Cache\CacheFactoryInterface;
use PhpMyAdmin\MoTranslator\Cache\InMemoryCache;
use function array_push;
use function file_exists;
use function getenv;
use function in_array;
use function preg_match;
use function sprintf;
class Loader
{
/**
* Loader instance.
*
* @static
* @var Loader
*/
private static $instance = null;
/**
* Factory to return a factory responsible for returning a `CacheInterface`
*
* @static
* @var CacheFactoryInterface|null
*/
private static $cacheFactory = null;
/**
* Default gettext domain to use.
*
* @var string
*/
private $defaultDomain = '';
/**
* Configured locale.
*
* @var string
*/
private $locale = '';
/**
* Loaded domains.
*
* @var array<string,array<string,Translator>>
*/
private $domains = [];
/**
* Bound paths for domains.
*
* @var array<string,string>
*/
private $paths = ['' => './'];
/**
* Returns the singleton Loader object.
*
* @return Loader object
*/
public static function getInstance(): Loader
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Loads global localization functions.
*/
public static function loadFunctions(): void
{
require_once __DIR__ . '/functions.php';
}
/**
* Figure out all possible locale names and start with the most
* specific ones. I.e. for sr_CS.UTF-8@latin, look through all of
* sr_CS.UTF-8@latin, sr_CS@latin, sr@latin, sr_CS.UTF-8, sr_CS, sr.
*
* @param string $locale Locale code
*
* @return string[] list of locales to try for any POSIX-style locale specification
*/
public static function listLocales(string $locale): array
{
$localeNames = [];
if ($locale) {
if (
preg_match(
'/^(?P<lang>[a-z]{2,3})' // language code
. '(?:_(?P<country>[A-Z]{2}))?' // country code
. '(?:\\.(?P<charset>[-A-Za-z0-9_]+))?' // charset
. '(?:@(?P<modifier>[-A-Za-z0-9_]+))?$/', // @ modifier
$locale,
$matches
)
) {
$lang = $matches['lang'] ?? null;
$country = $matches['country'] ?? null;
$charset = $matches['charset'] ?? null;
$modifier = $matches['modifier'] ?? null;
if ($modifier) {
if ($country) {
if ($charset) {
array_push(
$localeNames,
sprintf('%s_%s.%s@%s', $lang, $country, $charset, $modifier)
);
}
array_push(
$localeNames,
sprintf('%s_%s@%s', $lang, $country, $modifier)
);
} elseif ($charset) {
array_push(
$localeNames,
sprintf('%s.%s@%s', $lang, $charset, $modifier)
);
}
array_push(
$localeNames,
sprintf('%s@%s', $lang, $modifier)
);
}
if ($country) {
if ($charset) {
array_push(
$localeNames,
sprintf('%s_%s.%s', $lang, $country, $charset)
);
}
array_push(
$localeNames,
sprintf('%s_%s', $lang, $country)
);
} elseif ($charset) {
array_push(
$localeNames,
sprintf('%s.%s', $lang, $charset)
);
}
array_push($localeNames, $lang);
}
// If the locale name doesn't match POSIX style, just include it as-is.
if (! in_array($locale, $localeNames)) {
array_push($localeNames, $locale);
}
}
return $localeNames;
}
/**
* Sets factory responsible for composing a `CacheInterface`
*/
public static function setCacheFactory(?CacheFactoryInterface $cacheFactory): void
{
self::$cacheFactory = $cacheFactory;
}
/**
* Returns Translator object for domain or for default domain.
*
* @param string $domain Translation domain
*/
public function getTranslator(string $domain = ''): Translator
{
if (empty($domain)) {
$domain = $this->defaultDomain;
}
if (! isset($this->domains[$this->locale])) {
$this->domains[$this->locale] = [];
}
if (! isset($this->domains[$this->locale][$domain])) {
if (isset($this->paths[$domain])) {
$base = $this->paths[$domain];
} else {
$base = './';
}
$localeNames = $this->listLocales($this->locale);
$filename = '';
foreach ($localeNames as $locale) {
$filename = $base . '/' . $locale . '/LC_MESSAGES/' . $domain . '.mo';
if (file_exists($filename)) {
break;
}
}
// We don't care about invalid path, we will get fallback
// translator here
$moParser = new MoParser($filename);
if (self::$cacheFactory instanceof CacheFactoryInterface) {
$cache = self::$cacheFactory->getInstance($moParser, $this->locale, $domain);
} else {
$cache = new InMemoryCache($moParser);
}
$this->domains[$this->locale][$domain] = new Translator($cache);
}
return $this->domains[$this->locale][$domain];
}
/**
* Sets the path for a domain.
*
* @param string $domain Domain name
* @param string $path Path where to find locales
*/
public function bindtextdomain(string $domain, string $path): void
{
$this->paths[$domain] = $path;
}
/**
* Sets the default domain.
*
* @param string $domain Domain name
*/
public function textdomain(string $domain): void
{
$this->defaultDomain = $domain;
}
/**
* Sets a requested locale.
*
* @param string $locale Locale name
*
* @return string Set or current locale
*/
public function setlocale(string $locale): string
{
if (! empty($locale)) {
$this->locale = $locale;
}
return $this->locale;
}
/**
* Detects currently configured locale.
*
* It checks:
*
* - global lang variable
* - environment for LC_ALL, LC_MESSAGES and LANG
*
* @return string with locale name
*/
public function detectlocale(): string
{
if (isset($GLOBALS['lang'])) {
return $GLOBALS['lang'];
}
$locale = getenv('LC_ALL');
if ($locale !== false) {
return $locale;
}
$locale = getenv('LC_MESSAGES');
if ($locale !== false) {
return $locale;
}
$locale = getenv('LANG');
if ($locale !== false) {
return $locale;
}
return 'en';
}
}

View file

@ -0,0 +1,109 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\MoTranslator;
use PhpMyAdmin\MoTranslator\Cache\CacheInterface;
use function is_readable;
use function strcmp;
final class MoParser
{
/**
* None error.
*/
public const ERROR_NONE = 0;
/**
* File does not exist.
*/
public const ERROR_DOES_NOT_EXIST = 1;
/**
* File has bad magic number.
*/
public const ERROR_BAD_MAGIC = 2;
/**
* Error while reading file, probably too short.
*/
public const ERROR_READING = 3;
/**
* Big endian mo file magic bytes.
*/
public const MAGIC_BE = "\x95\x04\x12\xde";
/**
* Little endian mo file magic bytes.
*/
public const MAGIC_LE = "\xde\x12\x04\x95";
/**
* Parse error code (0 if no error).
*
* @var int
*/
public $error = self::ERROR_NONE;
/** @var string|null */
private $filename;
public function __construct(?string $filename)
{
$this->filename = $filename;
}
/**
* Parses .mo file and stores results to `$cache`
*/
public function parseIntoCache(CacheInterface $cache): void
{
if ($this->filename === null) {
return;
}
if (! is_readable($this->filename)) {
$this->error = self::ERROR_DOES_NOT_EXIST;
return;
}
$stream = new StringReader($this->filename);
try {
$magic = $stream->read(0, 4);
if (strcmp($magic, self::MAGIC_LE) === 0) {
$unpack = 'V';
} elseif (strcmp($magic, self::MAGIC_BE) === 0) {
$unpack = 'N';
} else {
$this->error = self::ERROR_BAD_MAGIC;
return;
}
/* Parse header */
$total = $stream->readint($unpack, 8);
$originals = $stream->readint($unpack, 12);
$translations = $stream->readint($unpack, 16);
/* get original and translations tables */
$totalTimesTwo = (int) ($total * 2);// Fix for issue #36 on ARM
$tableOriginals = $stream->readintarray($unpack, $originals, $totalTimesTwo);
$tableTranslations = $stream->readintarray($unpack, $translations, $totalTimesTwo);
/* read all strings to the cache */
for ($i = 0; $i < $total; ++$i) {
$iTimesTwo = $i * 2;
$iPlusOne = $iTimesTwo + 1;
$iPlusTwo = $iTimesTwo + 2;
$original = $stream->read($tableOriginals[$iPlusTwo], $tableOriginals[$iPlusOne]);
$translation = $stream->read($tableTranslations[$iPlusTwo], $tableTranslations[$iPlusOne]);
$cache->set($original, $translation);
}
} catch (ReaderException $e) {
$this->error = self::ERROR_READING;
return;
}
}
}

View file

@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
/*
Copyright (c) 2003, 2005, 2006, 2009 Danilo Segan <danilo@kvota.net>.
Copyright (c) 2016 Michal Čihař <michal@cihar.com>
This file is part of MoTranslator.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
namespace PhpMyAdmin\MoTranslator;
use Exception;
/**
* Exception thrown when file can not be read.
*/
class ReaderException extends Exception
{
}

View file

@ -0,0 +1,116 @@
<?php
declare(strict_types=1);
/*
Copyright (c) 2003, 2005, 2006, 2009 Danilo Segan <danilo@kvota.net>.
Copyright (c) 2016 Michal Čihař <michal@cihar.com>
This file is part of MoTranslator.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
namespace PhpMyAdmin\MoTranslator;
use function file_get_contents;
use function strlen;
use function substr;
use function unpack;
use const PHP_INT_MAX;
/**
* Simple wrapper around string buffer for
* random access and values parsing.
*/
class StringReader
{
/** @var string */
private $string;
/** @var int */
private $length;
/**
* @param string $filename Name of file to load
*/
public function __construct(string $filename)
{
$this->string = (string) file_get_contents($filename);
$this->length = strlen($this->string);
}
/**
* Read number of bytes from given offset.
*
* @param int $pos Offset
* @param int $bytes Number of bytes to read
*/
public function read(int $pos, int $bytes): string
{
if ($pos + $bytes > $this->length) {
throw new ReaderException('Not enough bytes!');
}
$data = substr($this->string, $pos, $bytes);
return $data === false ? '' : $data;
}
/**
* Reads a 32bit integer from the stream.
*
* @param string $unpack Unpack string
* @param int $pos Position
*
* @return int Integer from the stream
*/
public function readint(string $unpack, int $pos): int
{
$data = unpack($unpack, $this->read($pos, 4));
if ($data === false) {
return PHP_INT_MAX;
}
$result = $data[1];
/* We're reading unsigned int, but PHP will happily
* give us negative number on 32-bit platforms.
*
* See also documentation:
* https://secure.php.net/manual/en/function.unpack.php#refsect1-function.unpack-notes
*/
return $result < 0 ? PHP_INT_MAX : $result;
}
/**
* Reads an array of integers from the stream.
*
* @param string $unpack Unpack string
* @param int $pos Position
* @param int $count How many elements should be read
*
* @return int[] Array of Integers
*/
public function readintarray(string $unpack, int $pos, int $count): array
{
$data = unpack($unpack . $count, $this->read($pos, 4 * $count));
if ($data === false) {
return [];
}
return $data;
}
}

View file

@ -0,0 +1,388 @@
<?php
declare(strict_types=1);
/*
Copyright (c) 2003, 2009 Danilo Segan <danilo@kvota.net>.
Copyright (c) 2005 Nico Kaiser <nico@siriux.net>
Copyright (c) 2016 Michal Čihař <michal@cihar.com>
This file is part of MoTranslator.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
namespace PhpMyAdmin\MoTranslator;
use PhpMyAdmin\MoTranslator\Cache\CacheInterface;
use PhpMyAdmin\MoTranslator\Cache\GetAllInterface;
use PhpMyAdmin\MoTranslator\Cache\InMemoryCache;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Throwable;
use function chr;
use function count;
use function explode;
use function get_class;
use function implode;
use function intval;
use function ltrim;
use function preg_replace;
use function rtrim;
use function sprintf;
use function stripos;
use function strpos;
use function strtolower;
use function substr;
use function trim;
/**
* Provides a simple gettext replacement that works independently from
* the system's gettext abilities.
* It can read MO files and use them for translating strings.
*
* It caches ll strings and translations to speed up the string lookup.
*/
class Translator
{
/**
* None error.
*/
public const ERROR_NONE = 0;
/**
* File does not exist.
*/
public const ERROR_DOES_NOT_EXIST = 1;
/**
* File has bad magic number.
*/
public const ERROR_BAD_MAGIC = 2;
/**
* Error while reading file, probably too short.
*/
public const ERROR_READING = 3;
/**
* Big endian mo file magic bytes.
*/
public const MAGIC_BE = "\x95\x04\x12\xde";
/**
* Little endian mo file magic bytes.
*/
public const MAGIC_LE = "\xde\x12\x04\x95";
/**
* Parse error code (0 if no error).
*
* @var int
*/
public $error = self::ERROR_NONE;
/**
* Cache header field for plural forms.
*
* @var string|null
*/
private $pluralEquation = null;
/** @var ExpressionLanguage|null Evaluator for plurals */
private $pluralExpression = null;
/** @var int|null number of plurals */
private $pluralCount = null;
/** @var CacheInterface */
private $cache;
/**
* @param CacheInterface|string|null $cache Mo file to load (null for no file) or a CacheInterface implementation
*/
public function __construct($cache)
{
if (! $cache instanceof CacheInterface) {
$cache = new InMemoryCache(new MoParser($cache));
}
$this->cache = $cache;
}
/**
* Translates a string.
*
* @param string $msgid String to be translated
*
* @return string translated string (or original, if not found)
*/
public function gettext(string $msgid): string
{
return $this->cache->get($msgid);
}
/**
* Check if a string is translated.
*
* @param string $msgid String to be checked
*/
public function exists(string $msgid): bool
{
return $this->cache->has($msgid);
}
/**
* Sanitize plural form expression for use in ExpressionLanguage.
*
* @param string $expr Expression to sanitize
*
* @return string sanitized plural form expression
*/
public static function sanitizePluralExpression(string $expr): string
{
// Parse equation
$expr = explode(';', $expr);
if (count($expr) >= 2) {
$expr = $expr[1];
} else {
$expr = $expr[0];
}
$expr = trim(strtolower($expr));
// Strip plural prefix
if (substr($expr, 0, 6) === 'plural') {
$expr = ltrim(substr($expr, 6));
}
// Strip equals
if (substr($expr, 0, 1) === '=') {
$expr = ltrim(substr($expr, 1));
}
// Cleanup from unwanted chars
$expr = preg_replace('@[^n0-9:\(\)\?=!<>/%&| ]@', '', $expr);
return (string) $expr;
}
/**
* Extracts number of plurals from plurals form expression.
*
* @param string $expr Expression to process
*
* @return int Total number of plurals
*/
public static function extractPluralCount(string $expr): int
{
$parts = explode(';', $expr, 2);
$nplurals = explode('=', trim($parts[0]), 2);
if (strtolower(rtrim($nplurals[0])) !== 'nplurals') {
return 1;
}
if (count($nplurals) === 1) {
return 1;
}
return intval($nplurals[1]);
}
/**
* Parse full PO header and extract only plural forms line.
*
* @param string $header Gettext header
*
* @return string verbatim plural form header field
*/
public static function extractPluralsForms(string $header): string
{
$headers = explode("\n", $header);
$expr = 'nplurals=2; plural=n == 1 ? 0 : 1;';
foreach ($headers as $header) {
if (stripos($header, 'Plural-Forms:') !== 0) {
continue;
}
$expr = substr($header, 13);
}
return $expr;
}
/**
* Get possible plural forms from MO header.
*
* @return string plural form header
*/
private function getPluralForms(): string
{
// lets assume message number 0 is header
// this is true, right?
// cache header field for plural forms
if ($this->pluralEquation === null) {
$header = $this->cache->get('');
$expr = $this->extractPluralsForms($header);
$this->pluralEquation = $this->sanitizePluralExpression($expr);
$this->pluralCount = $this->extractPluralCount($expr);
}
return $this->pluralEquation;
}
/**
* Detects which plural form to take.
*
* @param int $n count of objects
*
* @return int array index of the right plural form
*/
private function selectString(int $n): int
{
if ($this->pluralExpression === null) {
$this->pluralExpression = new ExpressionLanguage();
}
try {
$plural = (int) $this->pluralExpression->evaluate(
$this->getPluralForms(),
['n' => $n]
);
} catch (Throwable $e) {
$plural = 0;
}
if ($plural >= $this->pluralCount) {
$plural = $this->pluralCount - 1;
}
return $plural;
}
/**
* Plural version of gettext.
*
* @param string $msgid Single form
* @param string $msgidPlural Plural form
* @param int $number Number of objects
*
* @return string translated plural form
*/
public function ngettext(string $msgid, string $msgidPlural, int $number): string
{
// this should contains all strings separated by NULLs
$key = implode(chr(0), [$msgid, $msgidPlural]);
if (! $this->cache->has($key)) {
return $number !== 1 ? $msgidPlural : $msgid;
}
$result = $this->cache->get($key);
// find out the appropriate form
$select = $this->selectString($number);
$list = explode(chr(0), $result);
// @codeCoverageIgnoreStart
if ($list === false) {
// This was added in 3ff2c63bcf85f81b3a205ce7222de11b33e2bf56 for phpstan
// But according to the php manual it should never happen
return '';
}
// @codeCoverageIgnoreEnd
if (! isset($list[$select])) {
return $list[0];
}
return $list[$select];
}
/**
* Translate with context.
*
* @param string $msgctxt Context
* @param string $msgid String to be translated
*
* @return string translated plural form
*/
public function pgettext(string $msgctxt, string $msgid): string
{
$key = implode(chr(4), [$msgctxt, $msgid]);
$ret = $this->gettext($key);
if (strpos($ret, chr(4)) !== false) {
return $msgid;
}
return $ret;
}
/**
* Plural version of pgettext.
*
* @param string $msgctxt Context
* @param string $msgid Single form
* @param string $msgidPlural Plural form
* @param int $number Number of objects
*
* @return string translated plural form
*/
public function npgettext(string $msgctxt, string $msgid, string $msgidPlural, int $number): string
{
$key = implode(chr(4), [$msgctxt, $msgid]);
$ret = $this->ngettext($key, $msgidPlural, $number);
if (strpos($ret, chr(4)) !== false) {
return $msgid;
}
return $ret;
}
/**
* Set translation in place
*
* @param string $msgid String to be set
* @param string $msgstr Translation
*/
public function setTranslation(string $msgid, string $msgstr): void
{
$this->cache->set($msgid, $msgstr);
}
/**
* Set the translations
*
* @param array<string,string> $translations The translations "key => value" array
*/
public function setTranslations(array $translations): void
{
$this->cache->setAll($translations);
}
/**
* Get the translations
*
* @return array<string,string> The translations "key => value" array
*/
public function getTranslations(): array
{
if ($this->cache instanceof GetAllInterface) {
return $this->cache->getAll();
}
throw new CacheException(sprintf(
"Cache '%s' does not support getting translations",
get_class($this->cache)
));
}
}

View file

@ -0,0 +1,200 @@
<?php
declare(strict_types=1);
/*
Copyright (c) 2005 Steven Armstrong <sa at c-area dot ch>
Copyright (c) 2009 Danilo Segan <danilo@kvota.net>
Copyright (c) 2016 Michal Čihař <michal@cihar.com>
This file is part of MoTranslator.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
use PhpMyAdmin\MoTranslator\Loader;
/**
* Sets a requested locale.
*
* @param int $category Locale category, ignored
* @param string $locale Locale name
*
* @return string Set or current locale
*/
function _setlocale(int $category, string $locale): string
{
return Loader::getInstance()->setlocale($locale);
}
/**
* Sets the path for a domain.
*
* @param string $domain Domain name
* @param string $path Path where to find locales
*/
function _bindtextdomain(string $domain, string $path): void
{
Loader::getInstance()->bindtextdomain($domain, $path);
}
/**
* Dummy compatibility function, MoTranslator assumes
* everything is using same character set on input and
* output.
*
* Generally it is wise to output in UTF-8 and have
* mo files in UTF-8.
*
* @param string $domain Domain where to set character set
* @param string $codeset Character set to set
*/
function _bind_textdomain_codeset($domain, $codeset): void
{
}
/**
* Sets the default domain.
*
* @param string $domain Domain name
*/
function _textdomain(string $domain): void
{
Loader::getInstance()->textdomain($domain);
}
/**
* Translates a string.
*
* @param string $msgid String to be translated
*
* @return string translated string (or original, if not found)
*/
function _gettext(string $msgid): string
{
return Loader::getInstance()->getTranslator()->gettext($msgid);
}
/**
* Translates a string, alias for _gettext.
*
* @param string $msgid String to be translated
*
* @return string translated string (or original, if not found)
*/
function __(string $msgid): string
{
return Loader::getInstance()->getTranslator()->gettext($msgid);
}
/**
* Plural version of gettext.
*
* @param string $msgid Single form
* @param string $msgidPlural Plural form
* @param int $number Number of objects
*
* @return string translated plural form
*/
function _ngettext(string $msgid, string $msgidPlural, int $number): string
{
return Loader::getInstance()->getTranslator()->ngettext($msgid, $msgidPlural, $number);
}
/**
* Translate with context.
*
* @param string $msgctxt Context
* @param string $msgid String to be translated
*
* @return string translated plural form
*/
function _pgettext(string $msgctxt, string $msgid): string
{
return Loader::getInstance()->getTranslator()->pgettext($msgctxt, $msgid);
}
/**
* Plural version of pgettext.
*
* @param string $msgctxt Context
* @param string $msgid Single form
* @param string $msgidPlural Plural form
* @param int $number Number of objects
*
* @return string translated plural form
*/
function _npgettext(string $msgctxt, string $msgid, string $msgidPlural, int $number): string
{
return Loader::getInstance()->getTranslator()->npgettext($msgctxt, $msgid, $msgidPlural, $number);
}
/**
* Translates a string.
*
* @param string $domain Domain to use
* @param string $msgid String to be translated
*
* @return string translated string (or original, if not found)
*/
function _dgettext(string $domain, string $msgid): string
{
return Loader::getInstance()->getTranslator($domain)->gettext($msgid);
}
/**
* Plural version of gettext.
*
* @param string $domain Domain to use
* @param string $msgid Single form
* @param string $msgidPlural Plural form
* @param int $number Number of objects
*
* @return string translated plural form
*/
function _dngettext(string $domain, string $msgid, string $msgidPlural, int $number): string
{
return Loader::getInstance()->getTranslator($domain)->ngettext($msgid, $msgidPlural, $number);
}
/**
* Translate with context.
*
* @param string $domain Domain to use
* @param string $msgctxt Context
* @param string $msgid String to be translated
*
* @return string translated plural form
*/
function _dpgettext(string $domain, string $msgctxt, string $msgid): string
{
return Loader::getInstance()->getTranslator($domain)->pgettext($msgctxt, $msgid);
}
/**
* Plural version of pgettext.
*
* @param string $domain Domain to use
* @param string $msgctxt Context
* @param string $msgid Single form
* @param string $msgidPlural Plural form
* @param int $number Number of objects
*
* @return string translated plural form
*/
function _dnpgettext(string $domain, string $msgctxt, string $msgid, string $msgidPlural, int $number): string
{
return Loader::getInstance()->getTranslator($domain)->npgettext($msgctxt, $msgid, $msgidPlural, $number);
}