MediaWiki  REL1_24
Collation.php
Go to the documentation of this file.
00001 <?php
00023 abstract class Collation {
00024     private static $instance;
00025 
00029     static function singleton() {
00030         if ( !self::$instance ) {
00031             global $wgCategoryCollation;
00032             self::$instance = self::factory( $wgCategoryCollation );
00033         }
00034         return self::$instance;
00035     }
00036 
00042     static function factory( $collationName ) {
00043         switch ( $collationName ) {
00044             case 'uppercase':
00045                 return new UppercaseCollation;
00046             case 'identity':
00047                 return new IdentityCollation;
00048             case 'uca-default':
00049                 return new IcuCollation( 'root' );
00050             case 'xx-uca-ckb':
00051                 return new CollationCkb;
00052             case 'xx-uca-et':
00053                 return new CollationEt;
00054             default:
00055                 $match = array();
00056                 if ( preg_match( '/^uca-([a-z@=-]+)$/', $collationName, $match ) ) {
00057                     return new IcuCollation( $match[1] );
00058                 }
00059 
00060                 # Provide a mechanism for extensions to hook in.
00061                 $collationObject = null;
00062                 wfRunHooks( 'Collation::factory', array( $collationName, &$collationObject ) );
00063 
00064                 if ( $collationObject instanceof Collation ) {
00065                     return $collationObject;
00066                 }
00067 
00068                 // If all else fails...
00069                 throw new MWException( __METHOD__ . ": unknown collation type \"$collationName\"" );
00070         }
00071     }
00072 
00084     abstract function getSortKey( $string );
00085 
00109     abstract function getFirstLetter( $string );
00110 }
00111 
00112 class UppercaseCollation extends Collation {
00113     private $lang;
00114 
00115     function __construct() {
00116         // Get a language object so that we can use the generic UTF-8 uppercase
00117         // function there
00118         $this->lang = Language::factory( 'en' );
00119     }
00120 
00121     function getSortKey( $string ) {
00122         return $this->lang->uc( $string );
00123     }
00124 
00125     function getFirstLetter( $string ) {
00126         if ( $string[0] == "\0" ) {
00127             $string = substr( $string, 1 );
00128         }
00129         return $this->lang->ucfirst( $this->lang->firstChar( $string ) );
00130     }
00131 }
00132 
00139 class IdentityCollation extends Collation {
00140 
00141     function getSortKey( $string ) {
00142         return $string;
00143     }
00144 
00145     function getFirstLetter( $string ) {
00146         global $wgContLang;
00147         // Copied from UppercaseCollation.
00148         // I'm kind of unclear on when this could happen...
00149         if ( $string[0] == "\0" ) {
00150             $string = substr( $string, 1 );
00151         }
00152         return $wgContLang->firstChar( $string );
00153     }
00154 }
00155 
00156 class IcuCollation extends Collation {
00157     const FIRST_LETTER_VERSION = 2;
00158 
00160     private $primaryCollator;
00161 
00163     private $mainCollator;
00164 
00166     private $locale;
00167 
00169     protected $digitTransformLanguage;
00170 
00172     private $firstLetterData;
00173 
00183     private static $cjkBlocks = array(
00184         array( 0x2E80, 0x2EFF ), // CJK Radicals Supplement
00185         array( 0x2F00, 0x2FDF ), // Kangxi Radicals
00186         array( 0x2FF0, 0x2FFF ), // Ideographic Description Characters
00187         array( 0x3000, 0x303F ), // CJK Symbols and Punctuation
00188         array( 0x31C0, 0x31EF ), // CJK Strokes
00189         array( 0x3200, 0x32FF ), // Enclosed CJK Letters and Months
00190         array( 0x3300, 0x33FF ), // CJK Compatibility
00191         array( 0x3400, 0x4DBF ), // CJK Unified Ideographs Extension A
00192         array( 0x4E00, 0x9FFF ), // CJK Unified Ideographs
00193         array( 0xF900, 0xFAFF ), // CJK Compatibility Ideographs
00194         array( 0xFE30, 0xFE4F ), // CJK Compatibility Forms
00195         array( 0x20000, 0x2A6DF ), // CJK Unified Ideographs Extension B
00196         array( 0x2A700, 0x2B73F ), // CJK Unified Ideographs Extension C
00197         array( 0x2B740, 0x2B81F ), // CJK Unified Ideographs Extension D
00198         array( 0x2F800, 0x2FA1F ), // CJK Compatibility Ideographs Supplement
00199     );
00200 
00222     private static $tailoringFirstLetters = array(
00223         // Verified by native speakers
00224         'be' => array( "Ё" ),
00225         'be-tarask' => array( "Ё" ),
00226         'cy' => array( "Ch", "Dd", "Ff", "Ng", "Ll", "Ph", "Rh", "Th" ),
00227         'en' => array(),
00228         'fa' => array( "آ", "ء", "ه" ),
00229         'fi' => array( "Å", "Ä", "Ö" ),
00230         'fr' => array(),
00231         'hu' => array( "Cs", "Dz", "Dzs", "Gy", "Ly", "Ny", "Ö", "Sz", "Ty", "Ü", "Zs" ),
00232         'is' => array( "Á", "Ð", "É", "Í", "Ó", "Ú", "Ý", "Þ", "Æ", "Ö", "Å" ),
00233         'it' => array(),
00234         'lv' => array( "Č", "Ģ", "Ķ", "Ļ", "Ņ", "Š", "Ž" ),
00235         'pl' => array( "Ą", "Ć", "Ę", "Ł", "Ń", "Ó", "Ś", "Ź", "Ż" ),
00236         'pt' => array(),
00237         'ru' => array(),
00238         'sv' => array( "Å", "Ä", "Ö" ),
00239         'sv@collation=standard' => array( "Å", "Ä", "Ö" ),
00240         'uk' => array( "Ґ", "Ь" ),
00241         'vi' => array( "Ă", "Â", "Đ", "Ê", "Ô", "Ơ", "Ư" ),
00242         // Not verified, but likely correct
00243         'af' => array(),
00244         'ast' => array( "Ch", "Ll", "Ñ" ),
00245         'az' => array( "Ç", "Ə", "Ğ", "İ", "Ö", "Ş", "Ü" ),
00246         'bg' => array(),
00247         'br' => array( "Ch", "C'h" ),
00248         'bs' => array( "Č", "Ć", "Dž", "Đ", "Lj", "Nj", "Š", "Ž" ),
00249         'ca' => array(),
00250         'co' => array(),
00251         'cs' => array( "Č", "Ch", "Ř", "Š", "Ž" ),
00252         'da' => array( "Æ", "Ø", "Å" ),
00253         'de' => array(),
00254         'dsb' => array( "Č", "Ć", "Dź", "Ě", "Ch", "Ł", "Ń", "Ŕ", "Š", "Ś", "Ž", "Ź" ),
00255         'el' => array(),
00256         'eo' => array( "Ĉ", "Ĝ", "Ĥ", "Ĵ", "Ŝ", "Ŭ" ),
00257         'es' => array( "Ñ" ),
00258         'et' => array( "Š", "Ž", "Õ", "Ä", "Ö", "Ü", "W" ), // added W for CollationEt (xx-uca-et)
00259         'eu' => array( "Ñ" ),
00260         'fo' => array( "Á", "Ð", "Í", "Ó", "Ú", "Ý", "Æ", "Ø", "Å" ),
00261         'fur' => array( "À", "Á", "Â", "È", "Ì", "Ò", "Ù" ),
00262         'fy' => array(),
00263         'ga' => array(),
00264         'gd' => array(),
00265         'gl' => array( "Ch", "Ll", "Ñ" ),
00266         'hr' => array( "Č", "Ć", "Dž", "Đ", "Lj", "Nj", "Š", "Ž" ),
00267         'hsb' => array( "Č", "Dź", "Ě", "Ch", "Ł", "Ń", "Ř", "Š", "Ć", "Ž" ),
00268         'kk' => array( "Ү", "І" ),
00269         'kl' => array( "Æ", "Ø", "Å" ),
00270         'ku' => array( "Ç", "Ê", "Î", "Ş", "Û" ),
00271         'ky' => array( "Ё" ),
00272         'la' => array(),
00273         'lb' => array(),
00274         'lt' => array( "Č", "Š", "Ž" ),
00275         'mk' => array(),
00276         'mo' => array( "Ă", "Â", "Î", "Ş", "Ţ" ),
00277         'mt' => array( "Ċ", "Ġ", "Għ", "Ħ", "Ż" ),
00278         'nl' => array(),
00279         'no' => array( "Æ", "Ø", "Å" ),
00280         'oc' => array(),
00281         'rm' => array(),
00282         'ro' => array( "Ă", "Â", "Î", "Ş", "Ţ" ),
00283         'rup' => array( "Ă", "Â", "Î", "Ľ", "Ń", "Ş", "Ţ" ),
00284         'sco' => array(),
00285         'sk' => array( "Ä", "Č", "Ch", "Ô", "Š", "Ž" ),
00286         'sl' => array( "Č", "Š", "Ž" ),
00287         'smn' => array( "Á", "Č", "Đ", "Ŋ", "Š", "Ŧ", "Ž", "Æ", "Ø", "Å", "Ä", "Ö" ),
00288         'sq' => array( "Ç", "Dh", "Ë", "Gj", "Ll", "Nj", "Rr", "Sh", "Th", "Xh", "Zh" ),
00289         'sr' => array(),
00290         'tk' => array( "Ç", "Ä", "Ž", "Ň", "Ö", "Ş", "Ü", "Ý" ),
00291         'tl' => array( "Ñ", "Ng" ),
00292         'tr' => array( "Ç", "Ğ", "İ", "Ö", "Ş", "Ü" ),
00293         'tt' => array( "Ә", "Ө", "Ү", "Җ", "Ң", "Һ" ),
00294         'uz' => array( "Ch", "G'", "Ng", "O'", "Sh" ),
00295     );
00296 
00297     const RECORD_LENGTH = 14;
00298 
00299     function __construct( $locale ) {
00300         if ( !extension_loaded( 'intl' ) ) {
00301             throw new MWException( 'An ICU collation was requested, ' .
00302                 'but the intl extension is not available.' );
00303         }
00304 
00305         $this->locale = $locale;
00306         // Drop everything after the '@' in locale's name
00307         $localeParts = explode( '@', $locale );
00308         $this->digitTransformLanguage = Language::factory( $locale === 'root' ? 'en' : $localeParts[0] );
00309 
00310         $this->mainCollator = Collator::create( $locale );
00311         if ( !$this->mainCollator ) {
00312             throw new MWException( "Invalid ICU locale specified for collation: $locale" );
00313         }
00314 
00315         $this->primaryCollator = Collator::create( $locale );
00316         $this->primaryCollator->setStrength( Collator::PRIMARY );
00317     }
00318 
00319     function getSortKey( $string ) {
00320         // intl extension produces non null-terminated
00321         // strings. Appending '' fixes it so that it doesn't generate
00322         // a warning on each access in debug php.
00323         wfSuppressWarnings();
00324         $key = $this->mainCollator->getSortKey( $string ) . '';
00325         wfRestoreWarnings();
00326         return $key;
00327     }
00328 
00329     function getPrimarySortKey( $string ) {
00330         wfSuppressWarnings();
00331         $key = $this->primaryCollator->getSortKey( $string ) . '';
00332         wfRestoreWarnings();
00333         return $key;
00334     }
00335 
00336     function getFirstLetter( $string ) {
00337         $string = strval( $string );
00338         if ( $string === '' ) {
00339             return '';
00340         }
00341 
00342         // Check for CJK
00343         $firstChar = mb_substr( $string, 0, 1, 'UTF-8' );
00344         if ( ord( $firstChar ) > 0x7f && self::isCjk( utf8ToCodepoint( $firstChar ) ) ) {
00345             return $firstChar;
00346         }
00347 
00348         $sortKey = $this->getPrimarySortKey( $string );
00349 
00350         // Do a binary search to find the correct letter to sort under
00351         $min = ArrayUtils::findLowerBound(
00352             array( $this, 'getSortKeyByLetterIndex' ),
00353             $this->getFirstLetterCount(),
00354             'strcmp',
00355             $sortKey );
00356 
00357         if ( $min === false ) {
00358             // Before the first letter
00359             return '';
00360         }
00361         return $this->getLetterByIndex( $min );
00362     }
00363 
00364     function getFirstLetterData() {
00365         if ( $this->firstLetterData !== null ) {
00366             return $this->firstLetterData;
00367         }
00368 
00369         $cache = wfGetCache( CACHE_ANYTHING );
00370         $cacheKey = wfMemcKey(
00371             'first-letters',
00372             $this->locale,
00373             $this->digitTransformLanguage->getCode(),
00374             self::getICUVersion()
00375         );
00376         $cacheEntry = $cache->get( $cacheKey );
00377 
00378         if ( $cacheEntry && isset( $cacheEntry['version'] )
00379             && $cacheEntry['version'] == self::FIRST_LETTER_VERSION
00380         ) {
00381             $this->firstLetterData = $cacheEntry;
00382             return $this->firstLetterData;
00383         }
00384 
00385         // Generate data from serialized data file
00386 
00387         if ( isset( self::$tailoringFirstLetters[$this->locale] ) ) {
00388             $letters = wfGetPrecompiledData( "first-letters-root.ser" );
00389             // Append additional characters
00390             $letters = array_merge( $letters, self::$tailoringFirstLetters[$this->locale] );
00391             // Remove unnecessary ones, if any
00392             if ( isset( self::$tailoringFirstLetters['-' . $this->locale] ) ) {
00393                 $letters = array_diff( $letters, self::$tailoringFirstLetters['-' . $this->locale] );
00394             }
00395             // Apply digit transforms
00396             $digits = array( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' );
00397             $letters = array_diff( $letters, $digits );
00398             foreach ( $digits as $digit ) {
00399                 $letters[] = $this->digitTransformLanguage->formatNum( $digit, true );
00400             }
00401         } else {
00402             $letters = wfGetPrecompiledData( "first-letters-{$this->locale}.ser" );
00403             if ( $letters === false ) {
00404                 throw new MWException( "MediaWiki does not support ICU locale " .
00405                     "\"{$this->locale}\"" );
00406             }
00407         }
00408 
00409         // Sort the letters.
00410         //
00411         // It's impossible to have the precompiled data file properly sorted,
00412         // because the sort order changes depending on ICU version. If the
00413         // array is not properly sorted, the binary search will return random
00414         // results.
00415         //
00416         // We also take this opportunity to remove primary collisions.
00417         $letterMap = array();
00418         foreach ( $letters as $letter ) {
00419             $key = $this->getPrimarySortKey( $letter );
00420             if ( isset( $letterMap[$key] ) ) {
00421                 // Primary collision
00422                 // Keep whichever one sorts first in the main collator
00423                 if ( $this->mainCollator->compare( $letter, $letterMap[$key] ) < 0 ) {
00424                     $letterMap[$key] = $letter;
00425                 }
00426             } else {
00427                 $letterMap[$key] = $letter;
00428             }
00429         }
00430         ksort( $letterMap, SORT_STRING );
00431         // Remove duplicate prefixes. Basically if something has a sortkey
00432         // which is a prefix of some other sortkey, then it is an
00433         // expansion and probably should not be considered a section
00434         // header.
00435         //
00436         // For example 'þ' is sometimes sorted as if it is the letters
00437         // 'th'. Other times it is its own primary element. Another
00438         // example is '₨'. Sometimes its a currency symbol. Sometimes it
00439         // is an 'R' followed by an 's'.
00440         //
00441         // Additionally an expanded element should always sort directly
00442         // after its first element due to they way sortkeys work.
00443         //
00444         // UCA sortkey elements are of variable length but no collation
00445         // element should be a prefix of some other element, so I think
00446         // this is safe. See:
00447         // * https://ssl.icu-project.org/repos/icu/icuhtml/trunk/design/collation/ICU_collation_design.htm
00448         // * http://site.icu-project.org/design/collation/uca-weight-allocation
00449         //
00450         // Additionally, there is something called primary compression to
00451         // worry about. Basically, if you have two primary elements that
00452         // are more than one byte and both start with the same byte then
00453         // the first byte is dropped on the second primary. Additionally
00454         // either \x03 or \xFF may be added to mean that the next primary
00455         // does not start with the first byte of the first primary.
00456         //
00457         // This shouldn't matter much, as the first primary is not
00458         // changed, and that is what we are comparing against.
00459         //
00460         // tl;dr: This makes some assumptions about how icu implements
00461         // collations. It seems incredibly unlikely these assumptions
00462         // will change, but nonetheless they are assumptions.
00463 
00464         $prev = false;
00465         $duplicatePrefixes = array();
00466         foreach ( $letterMap as $key => $value ) {
00467             // Remove terminator byte. Otherwise the prefix
00468             // comparison will get hung up on that.
00469             $trimmedKey = rtrim( $key, "\0" );
00470             if ( $prev === false || $prev === '' ) {
00471                 $prev = $trimmedKey;
00472                 // We don't yet have a collation element
00473                 // to compare against, so continue.
00474                 continue;
00475             }
00476 
00477             // Due to the fact the array is sorted, we only have
00478             // to compare with the element directly previous
00479             // to the current element (skipping expansions).
00480             // An element "X" will always sort directly
00481             // before "XZ" (Unless we have "XY", but we
00482             // do not update $prev in that case).
00483             if ( substr( $trimmedKey, 0, strlen( $prev ) ) === $prev ) {
00484                 $duplicatePrefixes[] = $key;
00485                 // If this is an expansion, we don't want to
00486                 // compare the next element to this element,
00487                 // but to what is currently $prev
00488                 continue;
00489             }
00490             $prev = $trimmedKey;
00491         }
00492         foreach ( $duplicatePrefixes as $badKey ) {
00493             wfDebug( "Removing '{$letterMap[$badKey]}' from first letters.\n" );
00494             unset( $letterMap[$badKey] );
00495             // This code assumes that unsetting does not change sort order.
00496         }
00497         $data = array(
00498             'chars' => array_values( $letterMap ),
00499             'keys' => array_keys( $letterMap ),
00500             'version' => self::FIRST_LETTER_VERSION,
00501         );
00502 
00503         // Reduce memory usage before caching
00504         unset( $letterMap );
00505 
00506         // Save to cache
00507         $this->firstLetterData = $data;
00508         $cache->set( $cacheKey, $data, 86400 * 7 /* 1 week */ );
00509         return $data;
00510     }
00511 
00512     function getLetterByIndex( $index ) {
00513         if ( $this->firstLetterData === null ) {
00514             $this->getFirstLetterData();
00515         }
00516         return $this->firstLetterData['chars'][$index];
00517     }
00518 
00519     function getSortKeyByLetterIndex( $index ) {
00520         if ( $this->firstLetterData === null ) {
00521             $this->getFirstLetterData();
00522         }
00523         return $this->firstLetterData['keys'][$index];
00524     }
00525 
00526     function getFirstLetterCount() {
00527         if ( $this->firstLetterData === null ) {
00528             $this->getFirstLetterData();
00529         }
00530         return count( $this->firstLetterData['chars'] );
00531     }
00532 
00533     static function isCjk( $codepoint ) {
00534         foreach ( self::$cjkBlocks as $block ) {
00535             if ( $codepoint >= $block[0] && $codepoint <= $block[1] ) {
00536                 return true;
00537             }
00538         }
00539         return false;
00540     }
00541 
00554     static function getICUVersion() {
00555         return defined( 'INTL_ICU_VERSION' ) ? INTL_ICU_VERSION : false;
00556     }
00557 
00565     static function getUnicodeVersionForICU() {
00566         $icuVersion = IcuCollation::getICUVersion();
00567         if ( !$icuVersion ) {
00568             return false;
00569         }
00570 
00571         $versionPrefix = substr( $icuVersion, 0, 3 );
00572         // Source: http://site.icu-project.org/download
00573         $map = array(
00574             '50.' => '6.2',
00575             '49.' => '6.1',
00576             '4.8' => '6.0',
00577             '4.6' => '6.0',
00578             '4.4' => '5.2',
00579             '4.2' => '5.1',
00580             '4.0' => '5.1',
00581             '3.8' => '5.0',
00582             '3.6' => '5.0',
00583             '3.4' => '4.1',
00584         );
00585 
00586         if ( isset( $map[$versionPrefix] ) ) {
00587             return $map[$versionPrefix];
00588         } else {
00589             return false;
00590         }
00591     }
00592 }
00593 
00599 class CollationCkb extends IcuCollation {
00600     function __construct() {
00601         // This will set $locale and collators, which affect the actual sorting order
00602         parent::__construct( 'fa' );
00603         // Override the 'fa' language set by parent constructor, which affects #getFirstLetterData()
00604         $this->digitTransformLanguage = Language::factory( 'ckb' );
00605     }
00606 }
00607 
00616 class CollationEt extends IcuCollation {
00617     function __construct() {
00618         parent::__construct( 'et' );
00619     }
00620 
00621     private static function mangle( $string ) {
00622         return str_replace(
00623             array( 'w', 'W' ),
00624             'ᴡ', // U+1D21 'LATIN LETTER SMALL CAPITAL W'
00625             $string
00626         );
00627     }
00628 
00629     private static function unmangle( $string ) {
00630         // Casing data is lost…
00631         return str_replace(
00632             'ᴡ', // U+1D21 'LATIN LETTER SMALL CAPITAL W'
00633             'W',
00634             $string
00635         );
00636     }
00637 
00638     function getSortKey( $string ) {
00639         return parent::getSortKey( self::mangle( $string ) );
00640     }
00641 
00642     function getFirstLetter( $string ) {
00643         return self::unmangle( parent::getFirstLetter( self::mangle( $string ) ) );
00644     }
00645 }