]> git.mxchange.org Git - friendica.git/blob - library/langdet/Text/LanguageDetect.php
Merge branch 'vagrant2' of https://github.com/silke/friendica into develop
[friendica.git] / library / langdet / Text / LanguageDetect.php
1 <?php
2 /**
3  * Part of Text_LanguageDetect
4  *
5  * PHP version 5
6  *
7  * @category  Text
8  * @package   Text_LanguageDetect
9  * @author    Nicholas Pisarro <infinityminusnine+pear@gmail.com>
10  * @copyright 2005-2006 Nicholas Pisarro
11  * @license   BSD http://www.opensource.org/licenses/bsd-license.php
12  * @link      http://pear.php.net/package/Text_LanguageDetect/
13  */
14
15 require_once 'Text/LanguageDetect/Exception.php';
16 require_once 'Text/LanguageDetect/Parser.php';
17 require_once 'Text/LanguageDetect/ISO639.php';
18
19 /**
20  * Detects the language of a given piece of text.
21  *
22  * Attempts to detect the language of a sample of text by correlating ranked
23  * 3-gram frequencies to a table of 3-gram frequencies of known languages.
24  *
25  * Implements a version of a technique originally proposed by Cavnar & Trenkle
26  * (1994): "N-Gram-Based Text Categorization"
27  *
28  * Requires the language model database (lang.dat) that should have
29  * accompanied this class definition in order to be instantiated.
30  *
31  * Example usage:
32  *
33  * <code>
34  * require_once 'Text/LanguageDetect.php';
35  *
36  * $l = new Text_LanguageDetect;
37  *
38  * $stdin = fopen('php://stdin', 'r');
39  *
40  * echo "Supported languages:\n";
41  *
42  * try {
43  *     $langs = $l->getLanguages();
44  * } catch (Text_LanguageDetect_Exception $e) {
45  *     die($e->getMessage());
46  * }
47  *
48  * sort($langs);
49  * echo join(', ', $langs);
50  *
51  * while ($line = fgets($stdin)) {
52  *     print_r($l->detect($line, 4));
53  * }
54  * </code>
55  *
56  * @category  Text
57  * @package   Text_LanguageDetect
58  * @author    Nicholas Pisarro <infinityminusnine+pear@gmail.com>
59  * @copyright 2005 Nicholas Pisarro
60  * @license   BSD http://www.opensource.org/licenses/bsd-license.php
61  * @version   Release: @package_version@
62  * @link      http://pear.php.net/package/Text_LanguageDetect/
63  */
64 class Text_LanguageDetect
65 {
66     /**
67      * The filename that stores the trigram data for the detector
68      *
69      * If this value starts with a slash (/) or a dot (.) the value of
70      * $this->_data_dir will be ignored
71      *
72      * @var string
73      */
74     protected $_db_filename = 'lang.dat';
75
76     /**
77      * The filename that stores the unicode block definitions
78      *
79      * If this value starts with a slash (/) or a dot (.) the value of
80      * $this->_data_dir will be ignored
81      *
82      * @var string
83      */
84     protected $_unicode_db_filename = 'unicode_blocks.dat';
85
86     /**
87      * The data directory
88      *
89      * Should be set by PEAR installer
90      *
91      * @var string
92      */
93     protected $_data_dir = '@data_dir@';
94
95     /**
96      * The trigram data for comparison
97      *
98      * Will be loaded on start from $this->_db_filename
99      *
100      * @var array
101      */
102     protected $_lang_db = array();
103
104     /**
105      * Stores the map of the trigram data to unicode characters
106      *
107      * @var array
108      */
109     protected $_unicode_map;
110
111     /**
112      * The size of the trigram data arrays
113      *
114      * @var int
115      */
116     protected $_threshold = 300;
117
118     /**
119      * The maximum possible score.
120      *
121      * Needed for score normalization. Different depending on the
122      * perl compatibility setting
123      *
124      * @var int
125      * @see setPerlCompatible()
126      */
127     protected $_max_score = 0;
128
129     /**
130      * Whether or not to simulate perl's Language::Guess exactly
131      *
132      * @var bool
133      * @see setPerlCompatible()
134      */
135     protected $_perl_compatible = false;
136
137     /**
138      * Whether to use the unicode block detection to speed up processing
139      *
140      * @var bool
141      */
142     protected $_use_unicode_narrowing = true;
143
144     /**
145      * Stores the result of the clustering operation
146      *
147      * @var array
148      * @see clusterLanguages()
149      */
150     protected $_clusters;
151
152     /**
153      * Which type of "language names" are accepted and returned:
154      *
155      * 0 - language name ("english")
156      * 2 - 2-letter ISO 639-1 code ("en")
157      * 3 - 3-letter ISO 639-2 code ("eng")
158      */
159     protected $_name_mode = 0;
160
161     /**
162      * Constructor
163      *
164      * Will attempt to load the language database. If it fails, you will get
165      * an exception.
166      */
167     public function __construct()
168     {
169         $data = $this->_readdb($this->_db_filename);
170         $this->_checkTrigram($data['trigram']);
171         $this->_lang_db = $data['trigram'];
172
173         if (isset($data['trigram-unicodemap'])) {
174             $this->_unicode_map = $data['trigram-unicodemap'];
175         }
176
177         // Not yet implemented:
178         if (isset($data['trigram-clusters'])) {
179             $this->_clusters = $data['trigram-clusters'];
180         }
181     }
182
183     /**
184      * Returns the path to the location of the database
185      *
186      * @param string $fname File name to load
187      *
188      * @return string expected path to the language model database
189      */
190     protected function _get_data_loc($fname)
191     {
192         if ($fname{0} == '/' || $fname{0} == '.') {
193             // if filename starts with a slash, assume it's an absolute pathname
194             // and skip whatever is in $this->_data_dir
195             return $fname;
196
197         } elseif ($this->_data_dir != '@' . 'data_dir' . '@') {
198             // if the data dir was set by the PEAR installer, use that
199             return $this->_data_dir . '/Text_LanguageDetect/' . $fname;
200
201         } else {
202             // assume this was just unpacked somewhere
203             // try the local working directory if otherwise
204             return __DIR__ . '/../data/' . $fname;
205         }
206     }
207
208     /**
209      * Loads the language trigram database from filename
210      *
211      * Trigram datbase should be a serialize()'d array
212      *
213      * @param string $fname the filename where the data is stored
214      *
215      * @return array the language model data
216      * @throws Text_LanguageDetect_Exception
217      */
218     protected function _readdb($fname)
219     {
220         // finds the correct data dir
221         $fname = $this->_get_data_loc($fname);
222
223         // input check
224         if (!file_exists($fname)) {
225             throw new Text_LanguageDetect_Exception(
226                 'Language database does not exist: ' . $fname,
227                 Text_LanguageDetect_Exception::DB_NOT_FOUND
228             );
229         } elseif (!is_readable($fname)) {
230             throw new Text_LanguageDetect_Exception(
231                 'Language database is not readable: ' . $fname,
232                 Text_LanguageDetect_Exception::DB_NOT_READABLE
233             );
234         }
235
236         return unserialize(file_get_contents($fname));
237     }
238
239
240     /**
241      * Checks if this object is ready to detect languages
242      *
243      * @param array $trigram Trigram data from database
244      *
245      * @return void
246      */
247     protected function _checkTrigram($trigram)
248     {
249         if (!is_array($trigram)) {
250             if (ini_get('magic_quotes_runtime')) {
251                 throw new Text_LanguageDetect_Exception(
252                     'Error loading database. Try turning magic_quotes_runtime off.',
253                     Text_LanguageDetect_Exception::MAGIC_QUOTES
254                 );
255             }
256             throw new Text_LanguageDetect_Exception(
257                 'Language database is not an array.',
258                 Text_LanguageDetect_Exception::DB_NOT_ARRAY
259             );
260         } elseif (empty($trigram)) {
261             throw new Text_LanguageDetect_Exception(
262                 'Language database has no elements.',
263                 Text_LanguageDetect_Exception::DB_EMPTY
264             );
265         }
266     }
267
268     /**
269      * Omits languages
270      *
271      * Pass this function the name of or an array of names of
272      * languages that you don't want considered
273      *
274      * If you're only expecting a limited set of languages, this can greatly
275      * speed up processing
276      *
277      * @param mixed $omit_list    language name or array of names to omit
278      * @param bool  $include_only if true will include (rather than
279      *                            exclude) only those in the list
280      *
281      * @return int number of languages successfully deleted
282      * @throws Text_LanguageDetect_Exception
283      */
284     public function omitLanguages($omit_list, $include_only = false)
285     {
286         $deleted = 0;
287
288         $omit_list = $this->_convertFromNameMode($omit_list);
289
290         if (!$include_only) {
291             // deleting the given languages
292             if (!is_array($omit_list)) {
293                 $omit_list = strtolower($omit_list); // case desensitize
294                 if (isset($this->_lang_db[$omit_list])) {
295                     unset($this->_lang_db[$omit_list]);
296                     $deleted++;
297                 }
298             } else {
299                 foreach ($omit_list as $omit_lang) {
300                     if (isset($this->_lang_db[$omit_lang])) {
301                         unset($this->_lang_db[$omit_lang]);
302                         $deleted++;
303                     }
304                 }
305             }
306
307         } else {
308             // deleting all except the given languages
309             if (!is_array($omit_list)) {
310                 $omit_list = array($omit_list);
311             }
312
313             // case desensitize
314             foreach ($omit_list as $key => $omit_lang) {
315                 $omit_list[$key] = strtolower($omit_lang);
316             }
317
318             foreach (array_keys($this->_lang_db) as $lang) {
319                 if (!in_array($lang, $omit_list)) {
320                     unset($this->_lang_db[$lang]);
321                     $deleted++;
322                 }
323             }
324         }
325
326         // reset the cluster cache if the number of languages changes
327         // this will then have to be recalculated
328         if (isset($this->_clusters) && $deleted > 0) {
329             $this->_clusters = null;
330         }
331
332         return $deleted;
333     }
334
335
336     /**
337      * Returns the number of languages that this object can detect
338      *
339      * @return int            the number of languages
340      * @throws Text_LanguageDetect_Exception
341      */
342     public function getLanguageCount()
343     {
344         return count($this->_lang_db);
345     }
346
347     /**
348      * Checks if the language with the given name exists in the database
349      *
350      * @param mixed $lang Language name or array of language names
351      *
352      * @return bool true if language model exists
353      */
354     public function languageExists($lang)
355     {
356         $lang = $this->_convertFromNameMode($lang);
357
358         if (is_string($lang)) {
359             return isset($this->_lang_db[strtolower($lang)]);
360
361         } elseif (is_array($lang)) {
362             foreach ($lang as $test_lang) {
363                 if (!isset($this->_lang_db[strtolower($test_lang)])) {
364                     return false;
365                 }
366             }
367             return true;
368
369         } else {
370             throw new Text_LanguageDetect_Exception(
371                 'Unsupported parameter type passed to languageExists()',
372                 Text_LanguageDetect_Exception::PARAM_TYPE
373             );
374         }
375     }
376
377     /**
378      * Returns the list of detectable languages
379      *
380      * @return array        the names of the languages known to this object<<<<<<<
381      * @throws Text_LanguageDetect_Exception
382      */
383     public function getLanguages()
384     {
385         return $this->_convertToNameMode(
386             array_keys($this->_lang_db)
387         );
388     }
389
390     /**
391      * Make this object behave like Language::Guess
392      *
393      * @param bool $setting false to turn off perl compatibility
394      *
395      * @return void
396      */
397     public function setPerlCompatible($setting = true)
398     {
399         if (is_bool($setting)) { // input check
400             $this->_perl_compatible = $setting;
401
402             if ($setting == true) {
403                 $this->_max_score = $this->_threshold;
404             } else {
405                 $this->_max_score = 0;
406             }
407         }
408
409     }
410
411     /**
412      * Sets the way how language names are accepted and returned.
413      *
414      * @param integer $name_mode One of the following modes:
415      *                           0 - language name ("english")
416      *                           2 - 2-letter ISO 639-1 code ("en")
417      *                           3 - 3-letter ISO 639-2 code ("eng")
418      *
419      * @return void
420      */
421     public function setNameMode($name_mode)
422     {
423         $this->_name_mode = $name_mode;
424     }
425
426     /**
427      * Whether to use unicode block ranges in detection
428      *
429      * Should speed up most detections if turned on (detault is on). In some
430      * circumstances it may be slower, such as for large text samples (> 10K)
431      * in languages that use latin scripts. In other cases it should speed up
432      * detection noticeably.
433      *
434      * @param bool $setting false to turn off
435      *
436      * @return void
437      */
438     public function useUnicodeBlocks($setting = true)
439     {
440         if (is_bool($setting)) {
441             $this->_use_unicode_narrowing = $setting;
442         }
443     }
444
445     /**
446      * Converts a piece of text into trigrams
447      *
448      * @param string $text text to convert
449      *
450      * @return     array array of trigram frequencies
451      * @deprecated Superceded by the Text_LanguageDetect_Parser class
452      */
453     protected function _trigram($text)
454     {
455         $s = new Text_LanguageDetect_Parser($text);
456         $s->prepareTrigram();
457         $s->prepareUnicode(false);
458         $s->setPadStart(!$this->_perl_compatible);
459         $s->analyze();
460         return $s->getTrigramFreqs();
461     }
462
463     /**
464      * Converts a set of trigrams from frequencies to ranks
465      *
466      * Thresholds (cuts off) the list at $this->_threshold
467      *
468      * @param array $arr array of trigram
469      *
470      * @return array ranks of trigrams
471      */
472     protected function _arr_rank($arr)
473     {
474
475         // sorts alphabetically first as a standard way of breaking rank ties
476         $this->_bub_sort($arr);
477
478         // below might also work, but seemed to introduce errors in testing
479         //ksort($arr);
480         //asort($arr);
481
482         $rank = array();
483
484         $i = 0;
485         foreach ($arr as $key => $value) {
486             $rank[$key] = $i++;
487
488             // cut off at a standard threshold
489             if ($i >= $this->_threshold) {
490                 break;
491             }
492         }
493
494         return $rank;
495     }
496
497     /**
498      * Sorts an array by value breaking ties alphabetically
499      *
500      * @param array $arr the array to sort
501      *
502      * @return void
503      */
504     protected function _bub_sort(&$arr)
505     {
506         // should do the same as this perl statement:
507         // sort { $trigrams{$b} == $trigrams{$a}
508         //   ?  $a cmp $b : $trigrams{$b} <=> $trigrams{$a} }
509
510         // needs to sort by both key and value at once
511         // using the key to break ties for the value
512
513         // converts array into an array of arrays of each key and value
514         // may be a better way of doing this
515         $combined = array();
516
517         foreach ($arr as $key => $value) {
518             $combined[] = array($key, $value);
519         }
520
521         usort($combined, array($this, '_sort_func'));
522
523         $replacement = array();
524         foreach ($combined as $key => $value) {
525             list($new_key, $new_value) = $value;
526             $replacement[$new_key] = $new_value;
527         }
528
529         $arr = $replacement;
530     }
531
532     /**
533      * Sort function used by bubble sort
534      *
535      * Callback function for usort().
536      *
537      * @param array $a first param passed by usort()
538      * @param array $b second param passed by usort()
539      *
540      * @return int 1 if $a is greater, -1 if not
541      * @see    _bub_sort()
542      */
543     protected function _sort_func($a, $b)
544     {
545         // each is actually a key/value pair, so that it can compare using both
546         list($a_key, $a_value) = $a;
547         list($b_key, $b_value) = $b;
548
549         if ($a_value == $b_value) {
550             // if the values are the same, break ties using the key
551             return strcmp($a_key, $b_key);
552
553         } else {
554             // if not, just sort normally
555             if ($a_value > $b_value) {
556                 return -1;
557             } else {
558                 return 1;
559             }
560         }
561
562         // 0 should not be possible because keys must be unique
563     }
564
565     /**
566      * Calculates a linear rank-order distance statistic between two sets of
567      * ranked trigrams
568      *
569      * Sums the differences in rank for each trigram. If the trigram does not
570      * appear in both, consider it a difference of $this->_threshold.
571      *
572      * This distance measure was proposed by Cavnar & Trenkle (1994). Despite
573      * its simplicity it has been shown to be highly accurate for language
574      * identification tasks.
575      *
576      * @param array $arr1 the reference set of trigram ranks
577      * @param array $arr2 the target set of trigram ranks
578      *
579      * @return int the sum of the differences between the ranks of
580      *             the two trigram sets
581      */
582     protected function _distance($arr1, $arr2)
583     {
584         $sumdist = 0;
585
586         foreach ($arr2 as $key => $value) {
587             if (isset($arr1[$key])) {
588                 $distance = abs($value - $arr1[$key]);
589             } else {
590                 // $this->_threshold sets the maximum possible distance value
591                 // for any one pair of trigrams
592                 $distance = $this->_threshold;
593             }
594             $sumdist += $distance;
595         }
596
597         return $sumdist;
598
599         // todo: there are other distance statistics to try, e.g. relative
600         //       entropy, but they're probably more costly to compute
601     }
602
603     /**
604      * Normalizes the score returned by _distance()
605      *
606      * Different if perl compatible or not
607      *
608      * @param int $score      the score from _distance()
609      * @param int $base_count the number of trigrams being considered
610      *
611      * @return float the normalized score
612      * @see    _distance()
613      */
614     protected function _normalize_score($score, $base_count = null)
615     {
616         if ($base_count === null) {
617             $base_count = $this->_threshold;
618         }
619
620         if (!$this->_perl_compatible) {
621             return 1 - ($score / $base_count / $this->_threshold);
622         } else {
623             return floor($score / $base_count);
624         }
625     }
626
627
628     /**
629      * Detects the closeness of a sample of text to the known languages
630      *
631      * Calculates the statistical difference between the text and
632      * the trigrams for each language, normalizes the score then
633      * returns results for all languages in sorted order
634      *
635      * If perl compatible, the score is 300-0, 0 being most similar.
636      * Otherwise, it's 0-1 with 1 being most similar.
637      *
638      * The $sample text should be at least a few sentences in length;
639      * should be ascii-7 or utf8 encoded, if another and the mbstring extension
640      * is present it will try to detect and convert. However, experience has
641      * shown that mb_detect_encoding() *does not work very well* with at least
642      * some types of encoding.
643      *
644      * @param string $sample a sample of text to compare.
645      * @param int    $limit  if specified, return an array of the most likely
646      *                       $limit languages and their scores.
647      *
648      * @return mixed sorted array of language scores, blank array if no
649      *               useable text was found
650      * @see    _distance()
651      * @throws Text_LanguageDetect_Exception
652      */
653     public function detect($sample, $limit = 0)
654     {
655         // input check
656         if (!Text_LanguageDetect_Parser::validateString($sample)) {
657             return array();
658         }
659
660         // check char encoding
661         // (only if mbstring extension is compiled and PHP > 4.0.6)
662         if (function_exists('mb_detect_encoding')
663             && function_exists('mb_convert_encoding')
664         ) {
665             // mb_detect_encoding isn't very reliable, to say the least
666             // detection should still work with a sufficient sample
667             //  of ascii characters
668             $encoding = mb_detect_encoding($sample);
669
670             // mb_detect_encoding() will return FALSE if detection fails
671             // don't attempt conversion if that's the case
672             if ($encoding != 'ASCII' && $encoding != 'UTF-8'
673                 && $encoding !== false
674             ) {
675                 // verify the encoding exists in mb_list_encodings
676                 if (in_array($encoding, mb_list_encodings())) {
677                     $sample = mb_convert_encoding($sample, 'UTF-8', $encoding);
678                 }
679             }
680         }
681
682         $sample_obj = new Text_LanguageDetect_Parser($sample);
683         $sample_obj->prepareTrigram();
684         if ($this->_use_unicode_narrowing) {
685             $sample_obj->prepareUnicode();
686         }
687         $sample_obj->setPadStart(!$this->_perl_compatible);
688         $sample_obj->analyze();
689
690         $trigram_freqs = $sample_obj->getTrigramRanks();
691         $trigram_count = count($trigram_freqs);
692
693         if ($trigram_count == 0) {
694             return array();
695         }
696
697         $scores = array();
698
699         // use unicode block detection to narrow down the possibilities
700         if ($this->_use_unicode_narrowing) {
701             $blocks = $sample_obj->getUnicodeBlocks();
702
703             if (is_array($blocks)) {
704                 $present_blocks = array_keys($blocks);
705             } else {
706                 throw new Text_LanguageDetect_Exception(
707                     'Error during block detection',
708                     Text_LanguageDetect_Exception::BLOCK_DETECTION
709                 );
710             }
711
712             $possible_langs = array();
713
714             foreach ($present_blocks as $blockname) {
715                 if (isset($this->_unicode_map[$blockname])) {
716
717                     $possible_langs = array_merge(
718                         $possible_langs,
719                         array_keys($this->_unicode_map[$blockname])
720                     );
721
722                     // todo: faster way to do this?
723                 }
724             }
725
726             // could also try an intersect operation rather than a union
727             // in other words, choose languages whose trigrams contain
728             // ALL of the unicode blocks found in this sample
729             // would improve speed but would be completely thrown off by an
730             // unexpected character, like an umlaut appearing in english text
731
732             $possible_langs = array_intersect(
733                 array_keys($this->_lang_db),
734                 array_unique($possible_langs)
735             );
736
737             // needs to intersect it with the keys of _lang_db in case
738             // languages have been omitted
739
740         } else {
741             // or just try 'em all
742             $possible_langs = array_keys($this->_lang_db);
743         }
744
745
746         foreach ($possible_langs as $lang) {
747             $scores[$lang] = $this->_normalize_score(
748                 $this->_distance($this->_lang_db[$lang], $trigram_freqs),
749                 $trigram_count
750             );
751         }
752
753         unset($sample_obj);
754
755         if ($this->_perl_compatible) {
756             asort($scores);
757         } else {
758             arsort($scores);
759         }
760
761         // todo: drop languages with a score of $this->_max_score?
762
763         // limit the number of returned scores
764         if ($limit && is_numeric($limit)) {
765             $limited_scores = array();
766
767             $i = 0;
768             foreach ($scores as $key => $value) {
769                 if ($i++ >= $limit) {
770                     break;
771                 }
772
773                 $limited_scores[$key] = $value;
774             }
775
776             return $this->_convertToNameMode($limited_scores, true);
777         } else {
778             return $this->_convertToNameMode($scores, true);
779         }
780     }
781
782     /**
783      * Returns only the most similar language to the text sample
784      *
785      * Calls $this->detect() and returns only the top result
786      *
787      * @param string $sample text to detect the language of
788      *
789      * @return string the name of the most likely language
790      *                or null if no language is similar
791      * @see    detect()
792      * @throws Text_LanguageDetect_Exception
793      */
794     public function detectSimple($sample)
795     {
796         $scores = $this->detect($sample, 1);
797
798         // if top language has the maximum possible score,
799         // then the top score will have been picked at random
800         if (!is_array($scores) || empty($scores)
801             || current($scores) == $this->_max_score
802         ) {
803             return null;
804         } else {
805             return key($scores);
806         }
807     }
808
809     /**
810      * Returns an array containing the most similar language and a confidence
811      * rating
812      *
813      * Confidence is a simple measure calculated from the similarity score
814      * minus the similarity score from the next most similar language
815      * divided by the highest possible score. Languages that have closely
816      * related cousins (e.g. Norwegian and Danish) should generally have lower
817      * confidence scores.
818      *
819      * The similarity score answers the question "How likely is the text the
820      * returned language regardless of the other languages considered?" The
821      * confidence score is one way of answering the question "how likely is the
822      * text the detected language relative to the rest of the language model
823      * set?"
824      *
825      * To see how similar languages are a priori, see languageSimilarity()
826      *
827      * @param string $sample text for which language will be detected
828      *
829      * @return array most similar language, score and confidence rating
830      *               or null if no language is similar
831      * @see    detect()
832      * @throws Text_LanguageDetect_Exception
833      */
834     public function detectConfidence($sample)
835     {
836         $scores = $this->detect($sample, 2);
837
838         // if most similar language has the max score, it
839         // will have been picked at random
840         if (!is_array($scores) || empty($scores)
841             || current($scores) == $this->_max_score
842         ) {
843             return null;
844         }
845
846         $arr['language'] = key($scores);
847         $arr['similarity'] = current($scores);
848         if (next($scores) !== false) { // if false then no next element
849             // the goal is to return a higher value if the distance between
850             // the similarity of the first score and the second score is high
851
852             if ($this->_perl_compatible) {
853                 $arr['confidence'] = (current($scores) - $arr['similarity'])
854                     / $this->_max_score;
855
856             } else {
857                 $arr['confidence'] = $arr['similarity'] - current($scores);
858
859             }
860
861         } else {
862             $arr['confidence'] = null;
863         }
864
865         return $arr;
866     }
867
868     /**
869      * Returns the distribution of unicode blocks in a given utf8 string
870      *
871      * For the block name of a single char, use unicodeBlockName()
872      *
873      * @param string $str          input string. Must be ascii or utf8
874      * @param bool   $skip_symbols if true, skip ascii digits, symbols and
875      *                             non-printing characters. Includes spaces,
876      *                             newlines and common punctutation characters.
877      *
878      * @return array
879      * @throws Text_LanguageDetect_Exception
880      */
881     public function detectUnicodeBlocks($str, $skip_symbols)
882     {
883         $skip_symbols = (bool)$skip_symbols;
884         $str          = (string)$str;
885
886         $sample_obj = new Text_LanguageDetect_Parser($str);
887         $sample_obj->prepareUnicode();
888         $sample_obj->prepareTrigram(false);
889         $sample_obj->setUnicodeSkipSymbols($skip_symbols);
890         $sample_obj->analyze();
891         $blocks = $sample_obj->getUnicodeBlocks();
892         unset($sample_obj);
893         return $blocks;
894     }
895
896     /**
897      * Returns the block name for a given unicode value
898      *
899      * If passed a string, will assume it is being passed a UTF8-formatted
900      * character and will automatically convert. Otherwise it will assume it
901      * is being passed a numeric unicode value.
902      *
903      * Make sure input is of the correct type!
904      *
905      * @param mixed $unicode unicode value or utf8 char
906      *
907      * @return mixed the block name string or false if not found
908      * @throws Text_LanguageDetect_Exception
909      */
910     public function unicodeBlockName($unicode)
911     {
912         if (is_string($unicode)) {
913             // assume it is being passed a utf8 char, so convert it
914             if (self::utf8strlen($unicode) > 1) {
915                 throw new Text_LanguageDetect_Exception(
916                     'Pass a single char only to this method',
917                     Text_LanguageDetect_Exception::PARAM_TYPE
918                 );
919             }
920             $unicode = $this->_utf8char2unicode($unicode);
921
922         } elseif (!is_int($unicode)) {
923             throw new Text_LanguageDetect_Exception(
924                 'Input must be of type string or int.',
925                 Text_LanguageDetect_Exception::PARAM_TYPE
926             );
927         }
928
929         $blocks = $this->_read_unicode_block_db();
930
931         $result = $this->_unicode_block_name($unicode, $blocks);
932
933         if ($result == -1) {
934             return false;
935         } else {
936             return $result[2];
937         }
938     }
939
940     /**
941      * Searches the unicode block database
942      *
943      * Returns the block name for a given unicode value. unicodeBlockName() is
944      * the public interface for this function, which does input checks which
945      * this function omits for speed.
946      *
947      * @param int   $unicode     the unicode value
948      * @param array $blocks      the block database
949      * @param int   $block_count the number of defined blocks in the database
950      *
951      * @return mixed Block name, -1 if it failed
952      * @see    unicodeBlockName()
953      */
954     protected function _unicode_block_name($unicode, $blocks, $block_count = -1)
955     {
956         // for a reference, see
957         // http://www.unicode.org/Public/UNIDATA/Blocks.txt
958
959         // assume that ascii characters are the most common
960         // so try it first for efficiency
961         if ($unicode <= $blocks[0][1]) {
962             return $blocks[0];
963         }
964
965         // the optional $block_count param is for efficiency
966         // so we this function doesn't have to run count() every time
967         if ($block_count != -1) {
968             $high = $block_count - 1;
969         } else {
970             $high = count($blocks) - 1;
971         }
972
973         $low = 1; // start with 1 because ascii was 0
974
975         // your average binary search algorithm
976         while ($low <= $high) {
977             $mid = floor(($low + $high) / 2);
978
979             if ($unicode < $blocks[$mid][0]) {
980                 // if it's lower than the lower bound
981                 $high = $mid - 1;
982
983             } elseif ($unicode > $blocks[$mid][1]) {
984                 // if it's higher than the upper bound
985                 $low = $mid + 1;
986
987             } else {
988                 // found it
989                 return $blocks[$mid];
990             }
991         }
992
993         // failed to find the block
994         return -1;
995
996         // todo: differentiate when it's out of range or when it falls
997         //       into an unassigned range?
998     }
999
1000     /**
1001      * Brings up the unicode block database
1002      *
1003      * @return array the database of unicode block definitions
1004      * @throws Text_LanguageDetect_Exception
1005      */
1006     protected function _read_unicode_block_db()
1007     {
1008         // since the unicode definitions are always going to be the same,
1009         // might as well share the memory for the db with all other instances
1010         // of this class
1011         static $data;
1012
1013         if (!isset($data)) {
1014             $data = $this->_readdb($this->_unicode_db_filename);
1015         }
1016
1017         return $data;
1018     }
1019
1020     /**
1021      * Calculate the similarities between the language models
1022      *
1023      * Use this function to see how similar languages are to each other.
1024      *
1025      * If passed 2 language names, will return just those languages compared.
1026      * If passed 1 language name, will return that language compared to
1027      * all others.
1028      * If passed none, will return an array of every language model compared
1029      * to every other one.
1030      *
1031      * @param string $lang1 the name of the first language to be compared
1032      * @param string $lang2 the name of the second language to be compared
1033      *
1034      * @return array scores of every language compared
1035      *               or the score of just the provided languages
1036      *               or null if one of the supplied languages does not exist
1037      * @throws Text_LanguageDetect_Exception
1038      */
1039     public function languageSimilarity($lang1 = null, $lang2 = null)
1040     {
1041         $lang1 = $this->_convertFromNameMode($lang1);
1042         $lang2 = $this->_convertFromNameMode($lang2);
1043         if ($lang1 != null) {
1044             $lang1 = strtolower($lang1);
1045
1046             // check if language model exists
1047             if (!isset($this->_lang_db[$lang1])) {
1048                 return null;
1049             }
1050
1051             if ($lang2 != null) {
1052                 if (!isset($this->_lang_db[$lang2])) {
1053                     // check if language model exists
1054                     return null;
1055                 }
1056
1057                 $lang2 = strtolower($lang2);
1058
1059                 // compare just these two languages
1060                 return $this->_normalize_score(
1061                     $this->_distance(
1062                         $this->_lang_db[$lang1],
1063                         $this->_lang_db[$lang2]
1064                     )
1065                 );
1066
1067             } else {
1068                 // compare just $lang1 to all languages
1069                 $return_arr = array();
1070                 foreach ($this->_lang_db as $key => $value) {
1071                     if ($key != $lang1) {
1072                         // don't compare a language to itself
1073                         $return_arr[$key] = $this->_normalize_score(
1074                             $this->_distance($this->_lang_db[$lang1], $value)
1075                         );
1076                     }
1077                 }
1078                 asort($return_arr);
1079
1080                 return $return_arr;
1081             }
1082
1083
1084         } else {
1085             // compare all languages to each other
1086             $return_arr = array();
1087             foreach (array_keys($this->_lang_db) as $lang1) {
1088                 foreach (array_keys($this->_lang_db) as $lang2) {
1089                     // skip comparing languages to themselves
1090                     if ($lang1 != $lang2) {
1091
1092                         if (isset($return_arr[$lang2][$lang1])) {
1093                             // don't re-calculate what's already been done
1094                             $return_arr[$lang1][$lang2]
1095                                 = $return_arr[$lang2][$lang1];
1096
1097                         } else {
1098                             // calculate
1099                             $return_arr[$lang1][$lang2]
1100                                 = $this->_normalize_score(
1101                                     $this->_distance(
1102                                         $this->_lang_db[$lang1],
1103                                         $this->_lang_db[$lang2]
1104                                     )
1105                                 );
1106
1107                         }
1108                     }
1109                 }
1110             }
1111             return $return_arr;
1112         }
1113     }
1114
1115     /**
1116      * Cluster known languages according to languageSimilarity()
1117      *
1118      * WARNING: this method is EXPERIMENTAL. It is not recommended for common
1119      * use, and it may disappear or its functionality may change in future
1120      * releases without notice.
1121      *
1122      * Uses a nearest neighbor technique to generate the maximum possible
1123      * number of dendograms from the similarity data.
1124      *
1125      * @return     array language cluster data
1126      * @throws     Text_LanguageDetect_Exception
1127      * @see        languageSimilarity()
1128      * @deprecated this function will eventually be removed and placed into
1129      *              the model generation class
1130      */
1131     public function clusterLanguages()
1132     {
1133         // todo: set the maximum number of clusters
1134         // return cached result, if any
1135         if (isset($this->_clusters)) {
1136             return $this->_clusters;
1137         }
1138
1139         $langs = array_keys($this->_lang_db);
1140
1141         $arr = $this->languageSimilarity();
1142
1143         sort($langs);
1144
1145         foreach ($langs as $lang) {
1146             if (!isset($this->_lang_db[$lang])) {
1147                 throw new Text_LanguageDetect_Exception(
1148                     "missing $lang!",
1149                     Text_LanguageDetect_Exception::UNKNOWN_LANGUAGE
1150                 );
1151             }
1152         }
1153
1154         // http://www.psychstat.missouristate.edu/multibook/mlt04m.html
1155         foreach ($langs as $old_key => $lang1) {
1156             $langs[$lang1] = $lang1;
1157             unset($langs[$old_key]);
1158         }
1159
1160         $result_data = $really_map = array();
1161
1162         $i = 0;
1163         while (count($langs) > 2 && $i++ < 200) {
1164             $highest_score = -1;
1165             $highest_key1 = '';
1166             $highest_key2 = '';
1167             foreach ($langs as $lang1) {
1168                 foreach ($langs as $lang2) {
1169                     if ($lang1 != $lang2
1170                         && $arr[$lang1][$lang2] > $highest_score
1171                     ) {
1172                         $highest_score = $arr[$lang1][$lang2];
1173                         $highest_key1 = $lang1;
1174                         $highest_key2 = $lang2;
1175                     }
1176                 }
1177             }
1178
1179             if (!$highest_key1) {
1180                 // should not ever happen
1181                 throw new Text_LanguageDetect_Exception(
1182                     "no highest key? (step: $i)",
1183                     Text_LanguageDetect_Exception::NO_HIGHEST_KEY
1184                 );
1185             }
1186
1187             if ($highest_score == 0) {
1188                 // languages are perfectly dissimilar
1189                 break;
1190             }
1191
1192             // $highest_key1 and $highest_key2 are most similar
1193             $sum1 = array_sum($arr[$highest_key1]);
1194             $sum2 = array_sum($arr[$highest_key2]);
1195
1196             // use the score for the one that is most similar to the rest of
1197             // the field as the score for the group
1198             // todo: could try averaging or "centroid" method instead
1199             // seems like that might make more sense
1200             // actually nearest neighbor may be better for binary searching
1201
1202
1203             // for "Complete Linkage"/"furthest neighbor"
1204             // sign should be <
1205             // for "Single Linkage"/"nearest neighbor" method
1206             // should should be >
1207             // results seem to be pretty much the same with either method
1208
1209             // figure out which to delete and which to replace
1210             if ($sum1 > $sum2) {
1211                 $replaceme = $highest_key1;
1212                 $deleteme = $highest_key2;
1213             } else {
1214                 $replaceme = $highest_key2;
1215                 $deleteme = $highest_key1;
1216             }
1217
1218             $newkey = $replaceme . ':' . $deleteme;
1219
1220             // $replaceme is most similar to remaining languages
1221             // replace $replaceme with '$newkey', deleting $deleteme
1222
1223             // keep a record of which fork is really which language
1224             $really_lang = $replaceme;
1225             while (isset($really_map[$really_lang])) {
1226                 $really_lang = $really_map[$really_lang];
1227             }
1228             $really_map[$newkey] = $really_lang;
1229
1230
1231             // replace the best fitting key, delete the other
1232             foreach ($arr as $key1 => $arr2) {
1233                 foreach ($arr2 as $key2 => $value2) {
1234                     if ($key2 == $replaceme) {
1235                         $arr[$key1][$newkey] = $arr[$key1][$key2];
1236                         unset($arr[$key1][$key2]);
1237                         // replacing $arr[$key1][$key2] with $arr[$key1][$newkey]
1238                     }
1239
1240                     if ($key1 == $replaceme) {
1241                         $arr[$newkey][$key2] = $arr[$key1][$key2];
1242                         unset($arr[$key1][$key2]);
1243                         // replacing $arr[$key1][$key2] with $arr[$newkey][$key2]
1244                     }
1245
1246                     if ($key1 == $deleteme || $key2 == $deleteme) {
1247                         // deleting $arr[$key1][$key2]
1248                         unset($arr[$key1][$key2]);
1249                     }
1250                 }
1251             }
1252
1253
1254             unset($langs[$highest_key1]);
1255             unset($langs[$highest_key2]);
1256             $langs[$newkey] = $newkey;
1257
1258
1259             // some of these may be overkill
1260             $result_data[$newkey] = array(
1261                                 'newkey' => $newkey,
1262                                 'count' => $i,
1263                                 'diff' => abs($sum1 - $sum2),
1264                                 'score' => $highest_score,
1265                                 'bestfit' => $replaceme,
1266                                 'otherfit' => $deleteme,
1267                                 'really' => $really_lang,
1268                             );
1269         }
1270
1271         $return_val = array(
1272                 'open_forks' => $langs,
1273                         // the top level of clusters
1274                         // clusters that are mutually exclusive
1275                         // or specified by a specific maximum
1276
1277                 'fork_data' => $result_data,
1278                         // data for each split
1279
1280                 'name_map' => $really_map,
1281                         // which cluster is really which language
1282                         // using the nearest neighbor technique, the cluster
1283                         // inherits all of the properties of its most-similar member
1284                         // this keeps track
1285             );
1286
1287
1288         // saves the result in the object
1289         $this->_clusters = $return_val;
1290
1291         return $return_val;
1292     }
1293
1294
1295     /**
1296      * Perform an intelligent detection based on clusterLanguages()
1297      *
1298      * WARNING: this method is EXPERIMENTAL. It is not recommended for common
1299      * use, and it may disappear or its functionality may change in future
1300      * releases without notice.
1301      *
1302      * This compares the sample text to top the top level of clusters. If the
1303      * sample is similar to the cluster it will drop down and compare it to the
1304      * languages in the cluster, and so on until it hits a leaf node.
1305      *
1306      * this should find the language in considerably fewer compares
1307      * (the equivalent of a binary search), however clusterLanguages() is costly
1308      * and the loss of accuracy from this technique is significant.
1309      *
1310      * This method may need to be 'fuzzier' in order to become more accurate.
1311      *
1312      * This function could be more useful if the universe of possible languages
1313      * was very large, however in such cases some method of Bayesian inference
1314      * might be more helpful.
1315      *
1316      * @param string $str input string
1317      *
1318      * @return array language scores (only those compared)
1319      * @throws Text_LanguageDetect_Exception
1320      * @see    clusterLanguages()
1321      */
1322     public function clusteredSearch($str)
1323     {
1324         // input check
1325         if (!Text_LanguageDetect_Parser::validateString($str)) {
1326             return array();
1327         }
1328
1329         // clusterLanguages() will return a cached result if possible
1330         // so it's safe to call it every time
1331         $result = $this->clusterLanguages();
1332
1333         $dendogram_start = $result['open_forks'];
1334         $dendogram_data  = $result['fork_data'];
1335         $dendogram_alias = $result['name_map'];
1336
1337         $sample_obj = new Text_LanguageDetect_Parser($str);
1338         $sample_obj->prepareTrigram();
1339         $sample_obj->setPadStart(!$this->_perl_compatible);
1340         $sample_obj->analyze();
1341         $sample_result = $sample_obj->getTrigramRanks();
1342         $sample_count  = count($sample_result);
1343
1344         // input check
1345         if ($sample_count == 0) {
1346             return array();
1347         }
1348
1349         $i = 0; // counts the number of steps
1350
1351         foreach ($dendogram_start as $lang) {
1352             if (isset($dendogram_alias[$lang])) {
1353                 $lang_key = $dendogram_alias[$lang];
1354             } else {
1355                 $lang_key = $lang;
1356             }
1357
1358             $scores[$lang] = $this->_normalize_score(
1359                 $this->_distance($this->_lang_db[$lang_key], $sample_result),
1360                 $sample_count
1361             );
1362
1363             $i++;
1364         }
1365
1366         if ($this->_perl_compatible) {
1367             asort($scores);
1368         } else {
1369             arsort($scores);
1370         }
1371
1372         $top_score = current($scores);
1373         $top_key = key($scores);
1374
1375         // of starting forks, $top_key is the most similar to the sample
1376
1377         $cur_key = $top_key;
1378         while (isset($dendogram_data[$cur_key])) {
1379             $lang1 = $dendogram_data[$cur_key]['bestfit'];
1380             $lang2 = $dendogram_data[$cur_key]['otherfit'];
1381             foreach (array($lang1, $lang2) as $lang) {
1382                 if (isset($dendogram_alias[$lang])) {
1383                     $lang_key = $dendogram_alias[$lang];
1384                 } else {
1385                     $lang_key = $lang;
1386                 }
1387
1388                 $scores[$lang] = $this->_normalize_score(
1389                     $this->_distance($this->_lang_db[$lang_key], $sample_result),
1390                     $sample_count
1391                 );
1392
1393                 //todo: does not need to do same comparison again
1394             }
1395
1396             $i++;
1397
1398             if ($scores[$lang1] > $scores[$lang2]) {
1399                 $cur_key = $lang1;
1400                 $loser_key = $lang2;
1401             } else {
1402                 $cur_key = $lang2;
1403                 $loser_key = $lang1;
1404             }
1405
1406             $diff = $scores[$cur_key] - $scores[$loser_key];
1407
1408             // $cur_key ({$dendogram_alias[$cur_key]}) wins
1409             // over $loser_key ({$dendogram_alias[$loser_key]})
1410             // with a difference of $diff
1411         }
1412
1413         // found result in $i compares
1414
1415         // rather than sorting the result, preserve it so that you can see
1416         // which paths the algorithm decided to take along the tree
1417
1418         // but sometimes the last item is only the second highest
1419         if (($this->_perl_compatible  && (end($scores) > prev($scores)))
1420             || (!$this->_perl_compatible && (end($scores) < prev($scores)))
1421         ) {
1422             $real_last_score = current($scores);
1423             $real_last_key = key($scores);
1424
1425             // swaps the 2nd-to-last item for the last item
1426             unset($scores[$real_last_key]);
1427             $scores[$real_last_key] = $real_last_score;
1428         }
1429
1430
1431         if (!$this->_perl_compatible) {
1432             $scores = array_reverse($scores, true);
1433             // second param requires php > 4.0.3
1434         }
1435
1436         return $scores;
1437     }
1438
1439     /**
1440      * UTF8-safe strlen()
1441      *
1442      * Returns the numbers of characters (not bytes) in a utf8 string
1443      *
1444      * @param string $str string to get the length of
1445      *
1446      * @return int number of chars
1447      */
1448     public static function utf8strlen($str)
1449     {
1450         // utf8_decode() will convert unknown chars to '?', which is actually
1451         // ideal for counting.
1452
1453         return strlen(utf8_decode($str));
1454
1455         // idea stolen from dokuwiki
1456     }
1457
1458     /**
1459      * Returns the unicode value of a utf8 char
1460      *
1461      * @param string $char a utf8 (possibly multi-byte) char
1462      *
1463      * @return int unicode value
1464      * @link   http://en.wikipedia.org/wiki/UTF-8
1465      */
1466     protected function _utf8char2unicode($char)
1467     {
1468         // strlen() here will actually get the binary length of a single char
1469         switch (strlen($char)) {
1470         case 1:
1471             // normal ASCII-7 byte
1472             // 0xxxxxxx -->  0xxxxxxx
1473             return ord($char{0});
1474
1475         case 2:
1476             // 2 byte unicode
1477             // 110zzzzx 10xxxxxx --> 00000zzz zxxxxxxx
1478             $z = (ord($char{0}) & 0x000001F) << 6;
1479             $x = (ord($char{1}) & 0x0000003F);
1480             return ($z | $x);
1481
1482         case 3:
1483             // 3 byte unicode
1484             // 1110zzzz 10zxxxxx 10xxxxxx --> zzzzzxxx xxxxxxxx
1485             $z =  (ord($char{0}) & 0x0000000F) << 12;
1486             $x1 = (ord($char{1}) & 0x0000003F) << 6;
1487             $x2 = (ord($char{2}) & 0x0000003F);
1488             return ($z | $x1 | $x2);
1489
1490         case 4:
1491             // 4 byte unicode
1492             // 11110zzz 10zzxxxx 10xxxxxx 10xxxxxx -->
1493             // 000zzzzz xxxxxxxx xxxxxxxx
1494             $z1 = (ord($char{0}) & 0x00000007) << 18;
1495             $z2 = (ord($char{1}) & 0x0000003F) << 12;
1496             $x1 = (ord($char{2}) & 0x0000003F) << 6;
1497             $x2 = (ord($char{3}) & 0x0000003F);
1498             return ($z1 | $z2 | $x1 | $x2);
1499         }
1500     }
1501
1502     /**
1503      * UTF8-safe fast character iterator
1504      *
1505      * Will get the next character starting from $counter, which will then be
1506      * incremented. If a multi-byte char the bytes will be concatenated and
1507      * $counter will be incremeted by the number of bytes in the char.
1508      *
1509      * @param string $str             the string being iterated over
1510      * @param int    $counter         the iterator, will increment by reference
1511      * @param bool   $special_convert whether to do special conversions
1512      *
1513      * @return char the next (possibly multi-byte) char from $counter
1514      */
1515     protected static function _next_char($str, &$counter, $special_convert = false)
1516     {
1517         $char = $str{$counter++};
1518         $ord = ord($char);
1519
1520         // for a description of the utf8 system see
1521         // http://www.phpclasses.org/browse/file/5131.html
1522
1523         // normal ascii one byte char
1524         if ($ord <= 127) {
1525             // special conversions needed for this package
1526             // (that only apply to regular ascii characters)
1527             // lower case, and convert all non-alphanumeric characters
1528             // other than "'" to space
1529             if ($special_convert && $char != ' ' && $char != "'") {
1530                 if ($ord >= 65 && $ord <= 90) { // A-Z
1531                     $char = chr($ord + 32); // lower case
1532                 } elseif ($ord < 97 || $ord > 122) { // NOT a-z
1533                     $char = ' '; // convert to space
1534                 }
1535             }
1536
1537             return $char;
1538
1539         } elseif ($ord >> 5 == 6) { // two-byte char
1540             // multi-byte chars
1541             $nextchar = $str{$counter++}; // get next byte
1542
1543             // lower-casing of non-ascii characters is still incomplete
1544
1545             if ($special_convert) {
1546                 // lower case latin accented characters
1547                 if ($ord == 195) {
1548                     $nextord = ord($nextchar);
1549                     $nextord_adj = $nextord + 64;
1550                     // for a reference, see
1551                     // http://www.ramsch.org/martin/uni/fmi-hp/iso8859-1.html
1552
1553                     // &Agrave; - &THORN; but not &times;
1554                     if ($nextord_adj >= 192
1555                         && $nextord_adj <= 222
1556                         && $nextord_adj != 215
1557                     ) {
1558                         $nextchar = chr($nextord + 32);
1559                     }
1560
1561                 } elseif ($ord == 208) {
1562                     // lower case cyrillic alphabet
1563                     $nextord = ord($nextchar);
1564                     // if A - Pe
1565                     if ($nextord >= 144 && $nextord <= 159) {
1566                         // lower case
1567                         $nextchar = chr($nextord + 32);
1568
1569                     } elseif ($nextord >= 160 && $nextord <= 175) {
1570                         // if Er - Ya
1571                         // lower case
1572                         $char = chr(209); // == $ord++
1573                         $nextchar = chr($nextord - 32);
1574                     }
1575                 }
1576             }
1577
1578             // tag on next byte
1579             return $char . $nextchar;
1580         } elseif ($ord >> 4  == 14) { // three-byte char
1581
1582             // tag on next 2 bytes
1583             return $char . $str{$counter++} . $str{$counter++};
1584
1585         } elseif ($ord >> 3 == 30) { // four-byte char
1586
1587             // tag on next 3 bytes
1588             return $char . $str{$counter++} . $str{$counter++} . $str{$counter++};
1589
1590         } else {
1591             // error?
1592         }
1593     }
1594
1595     /**
1596      * Converts an $language input parameter from the configured mode
1597      * to the language name that is used internally.
1598      *
1599      * Works for strings and arrays.
1600      *
1601      * @param string|array $lang       A language description ("english"/"en"/"eng")
1602      * @param boolean      $convertKey If $lang is an array, setting $key
1603      *                                 converts the keys to the language name.
1604      *
1605      * @return string|array Language name
1606      */
1607     protected function _convertFromNameMode($lang, $convertKey = false)
1608     {
1609         if ($this->_name_mode == 0) {
1610             return $lang;
1611         }
1612
1613         if ($this->_name_mode == 2) {
1614             $method = 'code2ToName';
1615         } else {
1616             $method = 'code3ToName';
1617         }
1618
1619         if (is_string($lang)) {
1620             return (string)Text_LanguageDetect_ISO639::$method($lang);
1621         }
1622
1623         $newlang = array();
1624         foreach ($lang as $key => $val) {
1625             if ($convertKey) {
1626                 $newkey = (string)Text_LanguageDetect_ISO639::$method($key);
1627                 $newlang[$newkey] = $val;
1628             } else {
1629                 $newlang[$key] = (string)Text_LanguageDetect_ISO639::$method($val);
1630             }
1631         }
1632         return $newlang;
1633     }
1634
1635     /**
1636      * Converts an $language output parameter from the language name that is
1637      * used internally to the configured mode.
1638      *
1639      * Works for strings and arrays.
1640      *
1641      * @param string|array $lang       A language description ("english"/"en"/"eng")
1642      * @param boolean      $convertKey If $lang is an array, setting $key
1643      *                                 converts the keys to the language name.
1644      *
1645      * @return string|array Language name
1646      */
1647     protected function _convertToNameMode($lang, $convertKey = false)
1648     {
1649         if ($this->_name_mode == 0) {
1650             return $lang;
1651         }
1652
1653         if ($this->_name_mode == 2) {
1654             $method = 'nameToCode2';
1655         } else {
1656             $method = 'nameToCode3';
1657         }
1658
1659         if (is_string($lang)) {
1660             return Text_LanguageDetect_ISO639::$method($lang);
1661         }
1662
1663         $newlang = array();
1664         foreach ($lang as $key => $val) {
1665             if ($convertKey) {
1666                 $newkey = Text_LanguageDetect_ISO639::$method($key);
1667                 $newlang[$newkey] = $val;
1668             } else {
1669                 $newlang[$key] = Text_LanguageDetect_ISO639::$method($val);
1670             }
1671         }
1672         return $newlang;
1673     }
1674 }
1675
1676 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
1677
1678 ?>