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