LanguageDetect.php 54 KB

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