1<?php 2namespace Fisharebest\Webtrees; 3 4/** 5 * webtrees: online genealogy 6 * Copyright (C) 2015 webtrees development team 7 * This program is free software: you can redistribute it and/or modify 8 * it under the terms of the GNU General Public License as published by 9 * the Free Software Foundation, either version 3 of the License, or 10 * (at your option) any later version. 11 * This program is distributed in the hope that it will be useful, 12 * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 * GNU General Public License for more details. 15 * You should have received a copy of the GNU General Public License 16 * along with this program. If not, see <http://www.gnu.org/licenses/>. 17 */ 18 19use Fisharebest\Localization\Locale; 20use Fisharebest\Localization\LocaleEnUs; 21use Fisharebest\Localization\Translation; 22use Fisharebest\Localization\Translator; 23use Patchwork\TurkishUtf8; 24 25/** 26 * Class I18N - Functions to support internationalization (i18n) functionality. 27 */ 28class I18N { 29 /** @var Locale The current locale (e.g. LocaleEnGb) */ 30 private static $locale; 31 32 /** @var Translator */ 33 private static $translator; 34 35 // Digits are always rendered LTR, even in RTL text. 36 const DIGITS = '0123456789٠١٢٣٤٥٦٧٨٩۰۱۲۳۴۵۶۷۸۹'; 37 38 // Reversable character conversions from the UNICODE 5.1 database. 39 // It excludes ambiguous (turkish dotless i) and mixed-case (Dz) characters. 40 // The characters should be arranged in default unicode-collation order. 41 const ALPHABET_LOWER = 'aàáâãäåāăąǎǟǡǻȁȃȧḁạảấầẩẫậắằẳẵặⓐaæǣǽbḃḅḇⓑbƀɓƃcçćĉċčḉⅽⓒcƈdďḋḍḏḑḓⅾⓓddždzđɖɗƌðeèéêëēĕėęěȅȇȩḕḗḙḛḝẹẻẽếềểễệⓔeǝəɛfḟⓕfƒgĝğġģǧǵḡⓖgǥɠɣƣhĥȟḣḥḧḩḫⓗhƕħiìíîïĩīĭįǐȉȋḭḯỉịⅰⓘiⅱⅲijⅳⅸɨɩjĵⓙjkķǩḱḳḵⓚkƙlĺļľḷḹḻḽⅼⓛlŀljłƚmḿṁṃⅿⓜmnñńņňǹṅṇṉṋⓝnnjɲƞŋoòóôõöōŏőơǒǫǭȍȏȫȭȯȱṍṏṑṓọỏốồổỗộớờởỡợⓞoœøǿɔɵȣpṕṗⓟpƥqⓠqrŕŗřȑȓṙṛṝṟⓡrʀsśŝşšșṡṣṥṧṩⓢsʃtţťțṫṭṯṱⓣtŧƭʈuùúûüũūŭůűųưǔǖǘǚǜȕȗṳṵṷṹṻụủứừửữựⓤuʉɯʊvṽṿⅴⓥvⅵⅶⅷʋʌwŵẁẃẅẇẉⓦwxẋẍⅹⓧxⅺⅻyýÿŷȳẏỳỵỷỹⓨyƴzźżžẑẓẕⓩzƶȥǯʒƹȝþƿƨƽƅάαἀἁἂἃἄἅἆἇὰάᾀᾁᾂᾃᾄᾅᾆᾇᾰᾱᾳβγδέεἐἑἒἓἔἕὲέϝϛζήηἠἡἢἣἤἥἦἧὴήᾐᾑᾒᾓᾔᾕᾖᾗῃθϊἰἱἲἳἴἵἶἷὶίῐῑκϗλμνξοόὀὁὂὃὄὅὸόπϟϙρῥσϲτυϋύὑὓὕὗὺύῠῡφχψωώὠὡὢὣὤὥὦὧὼώᾠᾡᾢᾣᾤᾥᾦᾧῳϡϸϻϣϥϧϩϫϭϯаӑӓәӛӕбвгґғҕдԁђԃѓҙеѐёӗєжӂӝҗзԅӟѕӡԇиѝӣҋӥіїйјкқӄҡҟҝлӆљԉмӎнӊңӈҥњԋоӧөӫпҧҁрҏсԍҫтԏҭћќуӯўӱӳүұѹфхҳһѡѿѽѻцҵчӵҷӌҹҽҿџшщъыӹьҍѣэӭюяѥѧѫѩѭѯѱѳѵѷҩաբգդեզէըթժիլխծկհձղճմյնշոչպջռսվտրցւփքօֆȼɂɇɉɋɍɏͱͳͷͻͼͽӏӷӻӽӿԑԓԕԗԙԛԝԟԡԣԥᵹᵽỻỽỿⅎↄⰰⰱⰲⰳⰴⰵⰶⰷⰸⰹⰺⰻⰼⰽⰾⰿⱀⱁⱂⱃⱄⱅⱆⱇⱈⱉⱊⱋⱌⱍⱎⱏⱐⱑⱒⱓⱔⱕⱖⱗⱘⱙⱚⱛⱜⱝⱞⱡⱨⱪⱬⱳⱶⲁⲃⲅⲇⲉⲋⲍⲏⲑⲓⲕⲗⲙⲛⲝⲟⲡⲣⲥⲧⲩⲫⲭⲯⲱⲳⲵⲷⲹⲻⲽⲿⳁⳃⳅⳇⳉⳋⳍⳏⳑⳓⳕⳗⳙⳛⳝⳟⳡⳣⳬⳮⴀⴁⴂⴃⴄⴅⴆⴇⴈⴉⴊⴋⴌⴍⴎⴏⴐⴑⴒⴓⴔⴕⴖⴗⴘⴙⴚⴛⴜⴝⴞⴟⴠⴡⴢⴣⴤⴥꙁꙃꙅꙇꙉꙋꙍꙏꙑꙓꙕꙗꙙꙛꙝꙟꙣꙥꙧꙩꙫꙭꚁꚃꚅꚇꚉꚋꚍꚏꚑꚓꚕꚗꜣꜥꜧꜩꜫꜭꜯꜳꜵꜷꜹꜻꜽꜿꝁꝃꝅꝇꝉꝋꝍꝏꝑꝓꝕꝗꝙꝛꝝꝟꝡꝣꝥꝧꝩꝫꝭꝯꝺꝼꝿꞁꞃꞅꞇꞌ'; 42 const ALPHABET_UPPER = 'AÀÁÂÃÄÅĀĂĄǍǞǠǺȀȂȦḀẠẢẤẦẨẪẬẮẰẲẴẶⒶAÆǢǼBḂḄḆⒷBɃƁƂCÇĆĈĊČḈⅭⒸCƇDĎḊḌḎḐḒⅮⒹDDŽDZĐƉƊƋÐEÈÉÊËĒĔĖĘĚȄȆȨḔḖḘḚḜẸẺẼẾỀỂỄỆⒺEƎƏƐFḞⒻFƑGĜĞĠĢǦǴḠⒼGǤƓƔƢHĤȞḢḤḦḨḪⒽHǶĦIÌÍÎÏĨĪĬĮǏȈȊḬḮỈỊⅠⒾIⅡⅢIJⅣⅨƗƖJĴⒿJKĶǨḰḲḴⓀKƘLĹĻĽḶḸḺḼⅬⓁLĿLJŁȽMḾṀṂⅯⓂMNÑŃŅŇǸṄṆṈṊⓃNNJƝȠŊOÒÓÔÕÖŌŎŐƠǑǪǬȌȎȪȬȮȰṌṎṐṒỌỎỐỒỔỖỘỚỜỞỠỢⓄOŒØǾƆƟȢPṔṖⓅPƤQⓆQRŔŖŘȐȒṘṚṜṞⓇRƦSŚŜŞŠȘṠṢṤṦṨⓈSƩTŢŤȚṪṬṮṰⓉTŦƬƮUÙÚÛÜŨŪŬŮŰŲƯǓǕǗǙǛȔȖṲṴṶṸṺỤỦỨỪỬỮỰⓊUɄƜƱVṼṾⅤⓋVⅥⅦⅧƲɅWŴẀẂẄẆẈⓌWXẊẌⅩⓍXⅪⅫYÝŸŶȲẎỲỴỶỸⓎYƳZŹŻŽẐẒẔⓏZƵȤǮƷƸȜÞǷƧƼƄΆΑἈἉἊἋἌἍἎἏᾺΆᾈᾉᾊᾋᾌᾍᾎᾏᾸᾹᾼΒΓΔΈΕἘἙἚἛἜἝῈΈϜϚΖΉΗἨἩἪἫἬἭἮἯῊΉᾘᾙᾚᾛᾜᾝᾞᾟῌΘΪἸἹἺἻἼἽἾἿῚΊῘῙΚϏΛΜΝΞΟΌὈὉὊὋὌὍῸΌΠϞϘΡῬΣϹΤΥΫΎὙὛὝὟῪΎῨῩΦΧΨΩΏὨὩὪὫὬὭὮὯῺΏᾨᾩᾪᾫᾬᾭᾮᾯῼϠϷϺϢϤϦϨϪϬϮАӐӒӘӚӔБВГҐҒҔДԀЂԂЃҘЕЀЁӖЄЖӁӜҖЗԄӞЅӠԆИЍӢҊӤІЇЙЈКҚӃҠҞҜЛӅЉԈМӍНӉҢӇҤЊԊОӦӨӪПҦҀРҎСԌҪТԎҬЋЌУӮЎӰӲҮҰѸФХҲҺѠѾѼѺЦҴЧӴҶӋҸҼҾЏШЩЪЫӸЬҌѢЭӬЮЯѤѦѪѨѬѮѰѲѴѶҨԱԲԳԴԵԶԷԸԹԺԻԼԽԾԿՀՁՂՃՄՅՆՇՈՉՊՋՌՍՎՏՐՑՒՓՔՕՖȻɁɆɈɊɌɎͰͲͶϽϾϿӀӶӺӼӾԐԒԔԖԘԚԜԞԠԢԤꝽⱣỺỼỾℲↃⰀⰁⰂⰃⰄⰅⰆⰇⰈⰉⰊⰋⰌⰍⰎⰏⰐⰑⰒⰓⰔⰕⰖⰗⰘⰙⰚⰛⰜⰝⰞⰟⰠⰡⰢⰣⰤⰥⰦⰧⰨⰩⰪⰫⰬⰭⰮⱠⱧⱩⱫⱲⱵⲀⲂⲄⲆⲈⲊⲌⲎⲐⲒⲔⲖⲘⲚⲜⲞⲠⲢⲤⲦⲨⲪⲬⲮⲰⲲⲴⲶⲸⲺⲼⲾⳀⳂⳄⳆⳈⳊⳌⳎⳐⳒⳔⳖⳘⳚⳜⳞⳠⳢⳫⳭႠႡႢႣႤႥႦႧႨႩႪႫႬႭႮႯႰႱႲႳႴႵႶႷႸႹႺႻႼႽႾႿჀჁჂჃჄჅꙀꙂꙄꙆꙈꙊꙌꙎꙐꙒꙔꙖꙘꙚꙜꙞꙢꙤꙦꙨꙪꙬꚀꚂꚄꚆꚈꚊꚌꚎꚐꚒꚔꚖꜢꜤꜦꜨꜪꜬꜮꜲꜴꜶꜸꜺꜼꜾꝀꝂꝄꝆꝈꝊꝌꝎꝐꝒꝔꝖꝘꝚꝜꝞꝠꝢꝤꝦꝨꝪꝬꝮꝹꝻꝾꞀꞂꞄꞆꞋ'; 43 44 // Alphabet for the currently selected locale 45 private static $alphabet_lower = 'abcdefghijklmnopqrstuvwxyz'; 46 private static $alphabet_upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; 47 48 // Lookup table to convert unicode code-points into scripts. 49 // See https://en.wikipedia.org/wiki/Unicode_block 50 // Note: we only need details for scripts of languages into which webtrees is translated. 51 private static $scripts = array( 52 array('Latn', 0x0041, 0x005A), // a-z 53 array('Latn', 0x0061, 0x007A), // A-Z 54 array('Latn', 0x0100, 0x02AF), 55 array('Grek', 0x0370, 0x03FF), 56 array('Cyrl', 0x0400, 0x052F), 57 array('Hebr', 0x0590, 0x05FF), 58 array('Arab', 0x0600, 0x06FF), 59 array('Arab', 0x0750, 0x077F), 60 array('Arab', 0x08A0, 0x08FF), 61 array('Deva', 0x0900, 0x097F), 62 array('Taml', 0x0B80, 0x0BFF), 63 array('Sinh', 0x0D80, 0x0DFF), 64 array('Thai', 0x0E00, 0x0E7F), 65 array('Geor', 0x10A0, 0x10FF), 66 array('Grek', 0x1F00, 0x1FFF), 67 array('Deva', 0xA8E0, 0xA8FF), 68 array('Hans', 0x3000, 0x303F), // Mixed CJK, not just Hans 69 array('Hans', 0x3400, 0xFAFF), // Mixed CJK, not just Hans 70 array('Hans', 0x20000, 0x2FA1F), // Mixed CJK, not just Hans 71 ); 72 73 // Characters that are displayed in mirror form in RTL text. 74 private static $mirror_characters = array( 75 '(' => ')', 76 ')' => '(', 77 '[' => ']', 78 ']' => '[', 79 '{' => '}', 80 '}' => '{', 81 '<' => '>', 82 '>' => '<', 83 '‹' => '›', 84 '›' => '‹', 85 '«' => '»', 86 '»' => '«', 87 '﴾' => '﴿', 88 '﴿' => '﴾', 89 '“' => '”', 90 '”' => '“', 91 '‘' => '’', 92 '’' => '‘', 93 ); 94 95 /** @var string The MySQL collation sequence used by this language, typically utf8_unicode_ci */ 96 public static $collation; 97 98 /** @var string Punctuation used to separate list items, typically a comma */ 99 public static $list_separator; 100 101 /** 102 * Initialise the translation adapter with a locale setting. 103 * 104 * @param string|null $code Use this locale/language code, or choose one automatically 105 * 106 * @return string $string 107 */ 108 public static function init($code = null) { 109 global $WT_SESSION, $WT_TREE; 110 111 if ($code !== null) { 112 // Create the specified locale 113 self::$locale = Locale::create($code); 114 } else { 115 // Negotiate a locale, but if we can't then use a failsafe 116 self::$locale = new LocaleEnUs; 117 if (Filter::get('lang')) { 118 // A request in the URL 119 try { 120 $locale = Locale::create(Filter::get('lang')); 121 if (file_exists(WT_ROOT . 'language/' . $locale->languageTag() . '.mo')) { 122 self::$locale = $locale; 123 } 124 } catch (\Exception $ex) { 125 } 126 } elseif ($WT_SESSION->locale) { 127 // Previously used 128 self::$locale = Locale::create($WT_SESSION->locale); 129 } elseif (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { 130 // Browser negotiation 131 $http_accept_language = strtolower(str_replace(' ', '', $_SERVER['HTTP_ACCEPT_LANGUAGE'])); 132 if (preg_match_all('/(?:([a-z][a-z0-9_-]+)(?:;q=([0-9.]+))?)/', $http_accept_language, $match)) { 133 $preferences = array_combine($match[1], $match[2]); 134 array_walk($preferences, function(&$x) { $x = $x === '' ? 1.0 : (float) $x; }); 135 } else { 136 $preferences = array(); 137 } 138 // Add the tree’s default language as a low-priority 139 if ($WT_TREE && !isset($preferences[$WT_TREE->getPreference('LANGUAGE')])) { 140 $preferences[$WT_TREE->getPreference('LANGUAGE')] = 0.2; 141 } 142 arsort($preferences); 143 foreach (array_keys($preferences) as $code) { 144 try { 145 $locale = Locale::create($code); 146 if (file_exists(WT_ROOT . 'language/' . $locale->languageTag() . '.mo')) { 147 self::$locale = $locale; 148 break; 149 } 150 } catch (\Exception $ex) { 151 // The user's prefered locale does not exist 152 } 153 } 154 } 155 } 156 157 File::mkdir( WT_DATA_DIR . 'cache'); 158 $cache_file = WT_DATA_DIR . 'cache/language-' . self::$locale->languageTag() . '-cache.php'; 159 if (file_exists($cache_file)) { 160 $filemtime = filemtime($cache_file); 161 } else { 162 $filemtime = 0; 163 } 164 165 // Load the translation file(s) 166 $translation_files = array_merge( 167 array(WT_ROOT . 'language/' . self::$locale->languageTag() . '.mo'), 168 glob(WT_MODULES_DIR . '*/language/*.{csv,php,mo}', GLOB_BRACE), 169 glob(WT_DATA_DIR . 'language/*.{csv,php,mo}', GLOB_BRACE) 170 ); 171 172 $rebuild_cache = false; 173 foreach ($translation_files as $translation_file) { 174 if (filemtime($translation_file) > $filemtime) { 175 $rebuild_cache = true; 176 break; 177 } 178 } 179 180 if ($rebuild_cache) { 181 $translations = array(); 182 foreach ($translation_files as $translation_file) { 183 $translation = new Translation($translation_file); 184 $translations = array_merge($translations, $translation->asArray()); 185 } 186 file_put_contents($cache_file, '<' . '?php return ' . var_export($translations, true) . ';'); 187 } else { 188 $translations = include $cache_file; 189 } 190 191 // Create a translator 192 self::$translator = new Translator($translations, self::$locale->pluralRule()); 193 194 // Extract language settings from the translation file 195 global $DATE_FORMAT; // I18N: This is the format string for full dates. See http://php.net/date for codes 196 $DATE_FORMAT = self::$translator->translate('%j %F %Y'); 197 198 global $TIME_FORMAT; // I18N: This is the format string for the time-of-day. See http://php.net/date for codes 199 $TIME_FORMAT = self::$translator->translate('%H:%i:%s'); 200 201 // Alphabetic sorting sequence (upper-case letters), used by webtrees to sort strings 202 list(, self::$alphabet_upper) = explode('=', self::$translator->translate('ALPHABET_upper=ABCDEFGHIJKLMNOPQRSTUVWXYZ')); 203 // Alphabetic sorting sequence (lower-case letters), used by webtrees to sort strings 204 list(, self::$alphabet_lower) = explode('=', self::$translator->translate('ALPHABET_lower=abcdefghijklmnopqrstuvwxyz')); 205 206 global $WEEK_START; 207 $WEEK_START = self::$locale->territory()->firstDay(); 208 209 self::$list_separator = /* I18N: This punctuation is used to separate lists of items */ self::translate(', '); 210 self::$collation = 'utf8_' . self::$locale->collation(); 211 212 return self::$locale->languageTag(); 213 } 214 215 /** 216 * The prefered locales for this site, or a default list if no preference. 217 * 218 * @return Locale[] 219 */ 220 public static function activeLocales() { 221 $code_list = Site::getPreference('LANGUAGES'); 222 223 if ($code_list) { 224 $codes = explode(',', $code_list); 225 } else { 226 $codes = array( 227 'ar', 'bg', 'bs', 'ca', 'cs', 'da', 'de', 'el', 'en-GB', 'en-US', 'es', 228 'et', 'fi', 'fr', 'he', 'hr', 'hu', 'is', 'it', 'ka', 'lt', 'mr', 'nb', 229 'nl', 'nn', 'pl', 'pt', 'ru', 'sk', 'sv', 'tr', 'uk', 'vi', 'zh-Hans', 230 ); 231 } 232 233 $locales = array(); 234 foreach ($codes as $code) { 235 if (file_exists(WT_ROOT . 'language/' . $code . '.mo')) { 236 try { 237 $locales[] = Locale::create($code); 238 } catch (\Exception $ex) { 239 // No such locale exists? 240 } 241 } 242 } 243 usort($locales, '\Fisharebest\Localization\Locale::compare'); 244 245 return $locales; 246 } 247 248 /** 249 * All locales for which a translation file exists. 250 * 251 * @return Locale[] 252 */ 253 public static function installedLocales() { 254 $locales = array(); 255 foreach (glob(WT_ROOT . 'language/*.mo') as $file) { 256 try { 257 $locales[] = Locale::create(basename($file, '.mo')); 258 } catch (\Exception $ex) { 259 // Not a recognised locale 260 } 261 } 262 usort($locales, '\Fisharebest\Localization\Locale::compare'); 263 264 return $locales; 265 } 266 267 /** 268 * Generate i18n markup for the <html> tag, e.g. lang="ar" dir="rtl" 269 * 270 * @return string 271 */ 272 public static function htmlAttributes() { 273 return self::$locale->htmlAttributes(); 274 } 275 276 /** 277 * Translate a number into the local representation. 278 * 279 * e.g. 12345.67 becomes 280 * en: 12,345.67 281 * fr: 12 345,67 282 * de: 12.345,67 283 * 284 * @param float $n 285 * @param integer $precision 286 * 287 * @return string 288 */ 289 public static function number($n, $precision = 0) { 290 return self::$locale->number(round($n, $precision)); 291 } 292 293 /** 294 * Convert the digits 0-9 into the local script 295 * 296 * Used for years, etc., where we do not want thousands-separators, decimals, etc. 297 * 298 * @param integer $n 299 * 300 * @return string 301 */ 302 public static function digits($n) { 303 return self::$locale->digits($n); 304 } 305 306 /** 307 * Translate a fraction into a percentage. 308 * 309 * e.g. 0.123 becomes 310 * en: 12.3% 311 * fr: 12,3 % 312 * de: 12,3% 313 * 314 * @param float $n 315 * @param integer $precision 316 * 317 * @return string 318 */ 319 public static function percentage($n, $precision = 0) { 320 return self::$locale->percent($n, $precision); 321 } 322 323 /** 324 * What is the direction of the current locale 325 * 326 * @return string "ltr" or "rtl" 327 */ 328 public static function direction() { 329 return self::$locale->direction(); 330 } 331 332 /** 333 * Translate a string, and then substitute placeholders 334 * 335 * echo I18N::translate('Hello World!'); 336 * echo I18N::translate('The %s sat on the mat', 'cat'); 337 * 338 * @return string 339 */ 340 public static function translate(/* var_args */) { 341 $args = func_get_args(); 342 $args[0] = self::$translator->translate($args[0]); 343 344 return call_user_func_array('sprintf', $args); 345 } 346 347 /** 348 * Context sensitive version of translate. 349 * 350 * echo I18N::translate_c('NOMINATIVE', 'January'); 351 * echo I18N::translate_c('GENITIVE', 'January'); 352 * 353 * @return string 354 */ 355 public static function translateContext(/* var_args */) { 356 $args = func_get_args(); 357 $args[0] = self::$translator->translateContext($args[0], $args[1]); 358 unset($args[1]); 359 360 return call_user_func_array('sprintf', $args); 361 } 362 363 /** 364 * Similar to translate, but do perform "no operation" on it. 365 * 366 * This is necessary to fetch a format string (containing % characters) without 367 * performing sustitution of arguments. 368 * 369 * @param string $string 370 * 371 * @return string 372 */ 373 public static function noop($string) { 374 return self::$translator->translate($string); 375 } 376 377 /** 378 * Translate a plural string 379 * 380 * echo self::plural('There is an error', 'There are errors', $num_errors); 381 * echo self::plural('There is one error', 'There are %s errors', $num_errors); 382 * echo self::plural('There is %1$s %2$s cat', 'There are %1$s %2$s cats', $num, $num, $colour); 383 * 384 * @return string 385 */ 386 public static function plural(/* var_args */) { 387 $args = func_get_args(); 388 $args[0] = self::$translator->plural($args[0], $args[1], $args[2]); 389 unset($args[1], $args[2]); 390 391 return call_user_func_array('sprintf', $args); 392 } 393 394 /** 395 * Convert a GEDCOM age string into translated_text 396 * 397 * NB: The import function will have normalised this, so we don't need 398 * to worry about badly formatted strings 399 * NOTE: this function is not yet complete - eventually it will replace get_age_at_event() 400 * 401 * @param $string 402 * 403 * @return string 404 */ 405 public static function gedcomAge($string) { 406 switch ($string) { 407 case 'STILLBORN': 408 // I18N: Description of an individual’s age at an event. For example, Died 14 Jan 1900 (stillborn) 409 return self::translate('(stillborn)'); 410 case 'INFANT': 411 // I18N: Description of an individual’s age at an event. For example, Died 14 Jan 1900 (in infancy) 412 return self::translate('(in infancy)'); 413 case 'CHILD': 414 // I18N: Description of an individual’s age at an event. For example, Died 14 Jan 1900 (in childhood) 415 return self::translate('(in childhood)'); 416 } 417 $age = array(); 418 if (preg_match('/(\d+)y/', $string, $match)) { 419 // I18N: Part of an age string. e.g. 5 years, 4 months and 3 days 420 $years = $match[1]; 421 $age[] = self::plural('%s year', '%s years', $years, self::number($years)); 422 } else { 423 $years = -1; 424 } 425 if (preg_match('/(\d+)m/', $string, $match)) { 426 // I18N: Part of an age string. e.g. 5 years, 4 months and 3 days 427 $age[] = self::plural('%s month', '%s months', $match[1], self::number($match[1])); 428 } 429 if (preg_match('/(\d+)w/', $string, $match)) { 430 // I18N: Part of an age string. e.g. 7 weeks and 3 days 431 $age[] = self::plural('%s week', '%s weeks', $match[1], self::number($match[1])); 432 } 433 if (preg_match('/(\d+)d/', $string, $match)) { 434 // I18N: Part of an age string. e.g. 5 years, 4 months and 3 days 435 $age[] = self::plural('%s day', '%s days', $match[1], self::number($match[1])); 436 } 437 // If an age is just a number of years, only show the number 438 if (count($age) === 1 && $years >= 0) { 439 $age = $years; 440 } 441 if ($age) { 442 if (!substr_compare($string, '<', 0, 1)) { 443 // I18N: Description of an individual’s age at an event. For example, Died 14 Jan 1900 (aged less than 21 years) 444 return self::translate('(aged less than %s)', $age); 445 } elseif (!substr_compare($string, '>', 0, 1)) { 446 // I18N: Description of an individual’s age at an event. For example, Died 14 Jan 1900 (aged more than 21 years) 447 return self::translate('(aged more than %s)', $age); 448 } else { 449 // I18N: Description of an individual’s age at an event. For example, Died 14 Jan 1900 (aged 43 years) 450 return self::translate('(aged %s)', $age); 451 } 452 } else { 453 // Not a valid string? 454 return self::translate('(aged %s)', $string); 455 } 456 } 457 458 /** 459 * Convert a number of seconds into a relative time. For example, 630 => "10 hours, 30 minutes ago" 460 * 461 * @param integer $seconds 462 * 463 * @return string 464 */ 465 public static function timeAgo($seconds) { 466 $minute = 60; 467 $hour = 60 * $minute; 468 $day = 24 * $hour; 469 $month = 30 * $day; 470 $year = 365 * $day; 471 472 if ($seconds > $year) { 473 $years = (int) ($seconds / $year); 474 return self::plural('%s year ago', '%s years ago', $years, self::number($years)); 475 } elseif ($seconds > $month) { 476 $months = (int) ($seconds / $month); 477 return self::plural('%s month ago', '%s months ago', $months, self::number($months)); 478 } elseif ($seconds > $day) { 479 $days = (int) ($seconds / $day); 480 return self::plural('%s day ago', '%s days ago', $days, self::number($days)); 481 } elseif ($seconds > $hour) { 482 $hours = (int) ($seconds / $hour); 483 return self::plural('%s hour ago', '%s hours ago', $hours, self::number($hours)); 484 } elseif ($seconds > $minute) { 485 $minutes = (int) ($seconds / $minute); 486 return self::plural('%s minute ago', '%s minutes ago', $minutes, self::number($minutes)); 487 } else { 488 return self::plural('%s second ago', '%s seconds ago', $seconds, self::number($seconds)); 489 } 490 } 491 492 /** 493 * Return the endonym for a given language - as per http://cldr.unicode.org/ 494 * 495 * @param string $locale 496 * 497 * @return string 498 */ 499 public static function languageName($locale) { 500 return Locale::create($locale)->endonym(); 501 } 502 503 /** 504 * Return the script used by a given language 505 * 506 * @param string $locale 507 * 508 * @return string 509 */ 510 public static function languageScript($locale) { 511 return Locale::create($locale)->script()->code(); 512 } 513 514 /** 515 * Identify the script used for a piece of text 516 * 517 * @param $string 518 * 519 * @return string 520 */ 521 public static function textScript($string) { 522 $string = strip_tags($string); // otherwise HTML tags show up as latin 523 $string = html_entity_decode($string, ENT_QUOTES, 'UTF-8'); // otherwise HTML entities show up as latin 524 $string = str_replace(array('@N.N.', '@P.N.'), '', $string); // otherwise unknown names show up as latin 525 $pos = 0; 526 $strlen = strlen($string); 527 while ($pos < $strlen) { 528 // get the Unicode Code Point for the character at position $pos 529 $byte1 = ord($string[$pos]); 530 if ($byte1 < 0x80) { 531 $code_point = $byte1; 532 $chrlen = 1; 533 } elseif ($byte1 < 0xC0) { 534 // Invalid continuation character 535 return 'Latn'; 536 } elseif ($byte1 < 0xE0) { 537 $code_point = (($byte1 & 0x1F) << 6) + (ord($string[$pos + 1]) & 0x3F); 538 $chrlen = 2; 539 } elseif ($byte1 < 0xF0) { 540 $code_point = (($byte1 & 0x0F) << 12) + ((ord($string[$pos + 1]) & 0x3F) << 6) + (ord($string[$pos + 2]) & 0x3F); 541 $chrlen = 3; 542 } elseif ($byte1 < 0xF8) { 543 $code_point = (($byte1 & 0x07) << 24) + ((ord($string[$pos + 1]) & 0x3F) << 12) + ((ord($string[$pos + 2]) & 0x3F) << 6) + (ord($string[$pos + 3]) & 0x3F); 544 $chrlen = 3; 545 } else { 546 // Invalid UTF 547 return 'Latn'; 548 } 549 550 foreach (self::$scripts as $range) { 551 if ($code_point >= $range[1] && $code_point <= $range[2]) { 552 return $range[0]; 553 } 554 } 555 // Not a recognised script. Maybe punctuation, spacing, etc. Keep looking. 556 $pos += $chrlen; 557 } 558 559 return 'Latn'; 560 } 561 562 /** 563 * Return the direction (ltr or rtl) for a given script 564 * 565 * The PHP/intl library does not provde this information, so we need 566 * our own lookup table. 567 * 568 * @param string $script 569 * 570 * @return string 571 */ 572 public static function scriptDirection($script) { 573 switch ($script) { 574 case 'Arab': 575 case 'Hebr': 576 case 'Mong': 577 case 'Thaa': 578 return 'rtl'; 579 default: 580 return 'ltr'; 581 } 582 } 583 584 /** 585 * UTF8 version of PHP::strtoupper() 586 * 587 * Convert a string to upper case, using the rules from the current locale 588 * 589 * @param string $string 590 * 591 * @return string 592 */ 593 public static function strtoupper($string) { 594 if (self::$locale->language()->code() === 'tr' || self::$locale->language()->code() === 'az') { 595 return TurkishUtf8::strtoupper($string); 596 } else { 597 return mb_strtoupper($string); 598 } 599 } 600 601 /** 602 * UTF8 version of PHP::strtolower() 603 * 604 * Convert a string to lower case, using the rules from the current locale 605 * 606 * @param string $string 607 * 608 * @return string 609 */ 610 public static function strtolower($string) { 611 if (self::$locale->language()->code() === 'tr' || self::$locale->language()->code() === 'az') { 612 return TurkishUtf8::strtolower($string); 613 } else { 614 return mb_strtolower($string); 615 } 616 } 617 618 /** 619 * UTF8 version of PHP::strcasecmp() 620 * 621 * Perform a case-insensitive comparison of two strings, using rules from the current locale 622 * 623 * @param string $string1 624 * @param string $string2 625 * 626 * @return integer 627 */ 628 public static function strcasecmp($string1, $string2) { 629 $strpos1 = 0; 630 $strpos2 = 0; 631 $strlen1 = strlen($string1); 632 $strlen2 = strlen($string2); 633 while ($strpos1 < $strlen1 && $strpos2 < $strlen2) { 634 $byte1 = ord($string1[$strpos1]); 635 $byte2 = ord($string2[$strpos2]); 636 if (($byte1 & 0xE0) === 0xC0) { 637 $chr1 = $string1[$strpos1++] . $string1[$strpos1++]; 638 } elseif (($byte1 & 0xF0) === 0xE0) { 639 $chr1 = $string1[$strpos1++] . $string1[$strpos1++] . $string1[$strpos1++]; 640 } else { 641 $chr1 = $string1[$strpos1++]; 642 } 643 if (($byte2 & 0xE0) === 0xC0) { 644 $chr2 = $string2[$strpos2++] . $string2[$strpos2++]; 645 } elseif (($byte2 & 0xF0) === 0xE0) { 646 $chr2 = $string2[$strpos2++] . $string2[$strpos2++] . $string2[$strpos2++]; 647 } else { 648 $chr2 = $string2[$strpos2++]; 649 } 650 if ($chr1 === $chr2) { 651 continue; 652 } 653 // Try the local alphabet first 654 $offset1 = strpos(self::$alphabet_lower, $chr1); 655 if ($offset1 === false) { 656 $offset1 = strpos(self::$alphabet_upper, $chr1); 657 } 658 $offset2 = strpos(self::$alphabet_lower, $chr2); 659 if ($offset2 === false) { 660 $offset2 = strpos(self::$alphabet_upper, $chr2); 661 } 662 if ($offset1 !== false && $offset2 !== false) { 663 if ($offset1 === $offset2) { 664 continue; 665 } else { 666 return $offset1 - $offset2; 667 } 668 } 669 // Try the global alphabet next 670 $offset1 = strpos(self::ALPHABET_LOWER, $chr1); 671 if ($offset1 === false) { 672 $offset1 = strpos(self::ALPHABET_UPPER, $chr1); 673 } 674 $offset2 = strpos(self::ALPHABET_LOWER, $chr2); 675 if ($offset2 === false) { 676 $offset2 = strpos(self::ALPHABET_UPPER, $chr2); 677 } 678 if ($offset1 !== false && $offset2 !== false) { 679 if ($offset1 === $offset2) { 680 continue; 681 } else { 682 return $offset1 - $offset2; 683 } 684 } 685 // Just compare by unicode order 686 return strcmp($chr1, $chr2); 687 } 688 // Shortest string comes first. 689 return ($strlen1 - $strpos1) - ($strlen2 - $strpos2); 690 } 691 692 /** 693 * UTF8 version of PHP::strrev() 694 * 695 * Reverse RTL text for third-party libraries such as GD2 and googlechart. 696 * 697 * These do not support UTF8 text direction, so we must mimic it for them. 698 * 699 * Numbers are always rendered LTR, even in RTL text. 700 * The visual direction of characters such as parentheses should be reversed. 701 * 702 * @param string $text Text to be reversed 703 * 704 * @return string 705 */ 706 public static function reverseText($text) { 707 // Remove HTML markup - we can't display it and it is LTR. 708 $text = Filter::unescapeHtml($text); 709 710 // LTR text doesn't need reversing 711 if (self::scriptDirection(self::textScript($text)) === 'ltr') { 712 return $text; 713 } 714 715 // Mirrored characters 716 $text = strtr($text, self::$mirror_characters); 717 718 $reversed = ''; 719 $digits = ''; 720 while ($text != '') { 721 $letter = mb_substr($text, 0, 1); 722 $text = mb_substr($text, 1); 723 if (strpos(self::DIGITS, $letter) !== false) { 724 $digits .= $letter; 725 } else { 726 $reversed = $letter . $digits . $reversed; 727 $digits = ''; 728 } 729 } 730 731 return $digits . $reversed; 732 } 733 734 /** 735 * Generate consistent I18N for datatables.js 736 * 737 * @param array|null $lengths An optional array of page lengths 738 * 739 * @return string 740 */ 741 public static function datatablesI18N(array $lengths = null) { 742 if ($lengths === null) { 743 $lengths = array(10, 20, 30, 50, 100, -1); 744 } 745 746 $length_menu = ''; 747 foreach ($lengths as $length) { 748 $length_menu .= 749 '<option value="' . $length . '">' . 750 ($length === -1 ? /* I18N: listbox option, e.g. “10,25,50,100,all” */ self::translate('All') : self::number($length)) . 751 '</option>'; 752 } 753 $length_menu = '<select>' . $length_menu . '</select>'; 754 $length_menu = /* I18N: Display %s [records per page], %s is a placeholder for listbox containing numeric options */ self::translate('Display %s', $length_menu); 755 756 $digits = self::$locale->digits('0123456789'); 757 if ($digits === '0123456789') { 758 $callback = ''; 759 } else { 760 $callback = ', 761 "infoCallback": function(oSettings, iStart, iEnd, iMax, iTotal, sPre) { 762 return sPre 763 .replace(/0/g, "' . mb_substr($digits, 0, 1) . '") 764 .replace(/1/g, "' . mb_substr($digits, 1, 1) . '") 765 .replace(/2/g, "' . mb_substr($digits, 2, 1) . '") 766 .replace(/3/g, "' . mb_substr($digits, 3, 1) . '") 767 .replace(/4/g, "' . mb_substr($digits, 4, 1) . '") 768 .replace(/5/g, "' . mb_substr($digits, 5, 1) . '") 769 .replace(/6/g, "' . mb_substr($digits, 6, 1) . '") 770 .replace(/7/g, "' . mb_substr($digits, 7, 1) . '") 771 .replace(/8/g, "' . mb_substr($digits, 8, 1) . '") 772 .replace(/9/g, "' . mb_substr($digits, 9, 1) . '"); 773 }, 774 "formatNumber": function(iIn) { 775 return String(iIn) 776 .replace(/0/g, "' . mb_substr($digits, 0, 1) . '") 777 .replace(/1/g, "' . mb_substr($digits, 1, 1) . '") 778 .replace(/2/g, "' . mb_substr($digits, 2, 1) . '") 779 .replace(/3/g, "' . mb_substr($digits, 3, 1) . '") 780 .replace(/4/g, "' . mb_substr($digits, 4, 1) . '") 781 .replace(/5/g, "' . mb_substr($digits, 5, 1) . '") 782 .replace(/6/g, "' . mb_substr($digits, 6, 1) . '") 783 .replace(/7/g, "' . mb_substr($digits, 7, 1) . '") 784 .replace(/8/g, "' . mb_substr($digits, 8, 1) . '") 785 .replace(/9/g, "' . mb_substr($digits, 9, 1) . '"); 786 } 787 '; 788 } 789 790 return 791 '"language": {' . 792 ' "paginate": {' . 793 ' "first": "' . /* I18N: button label, first page */ self::translate('first') . '",' . 794 ' "last": "' . /* I18N: button label, last page */ self::translate('last') . '",' . 795 ' "next": "' . /* I18N: button label, next page */ self::translate('next') . '",' . 796 ' "previous": "' . /* I18N: button label, previous page */ self::translate('previous') . '"' . 797 ' },' . 798 ' "emptyTable": "' . self::translate('No records to display') . '",' . 799 ' "info": "' . /* I18N: %s are placeholders for numbers */ self::translate('Showing %1$s to %2$s of %3$s', '_START_', '_END_', '_TOTAL_') . '",' . 800 ' "infoEmpty": "' . self::translate('Showing %1$s to %2$s of %3$s', 0, 0, 0) . '",' . 801 ' "infoFiltered": "' . /* I18N: %s is a placeholder for a number */ self::translate('(filtered from %s total entries)', '_MAX_') . '",' . 802 ' "infoPostfix": "",' . 803 ' "lengthMenu": "' . Filter::escapeJs($length_menu) . '",' . 804 ' "loadingRecords": "' . self::translate('Loading…') . '",' . 805 ' "processing": "' . self::translate('Loading…') . '",' . 806 ' "search": "' . self::translate('Filter') . '",' . 807 ' "url": "",' . 808 ' "zeroRecords": "' . self::translate('No records to display') . '"' . 809 '}' . 810 $callback; 811 } 812} 813