PageRenderTime 57ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/tcpdf/include/tcpdf_fonts.php

https://bitbucket.org/synergylearning/campusconnect
PHP | 2562 lines | 1943 code | 47 blank | 572 comment | 545 complexity | 60dfdd884343a68963a363deb165cac3 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, LGPL-2.1, Apache-2.0, BSD-3-Clause, AGPL-3.0
  1. <?php
  2. //============================================================+
  3. // File name : tcpdf_fonts.php
  4. // Version : 1.0.009
  5. // Begin : 2008-01-01
  6. // Last Update : 2013-09-04
  7. // Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
  8. // License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
  9. // -------------------------------------------------------------------
  10. // Copyright (C) 2008-2013 Nicola Asuni - Tecnick.com LTD
  11. //
  12. // This file is part of TCPDF software library.
  13. //
  14. // TCPDF is free software: you can redistribute it and/or modify it
  15. // under the terms of the GNU Lesser General Public License as
  16. // published by the Free Software Foundation, either version 3 of the
  17. // License, or (at your option) any later version.
  18. //
  19. // TCPDF is distributed in the hope that it will be useful, but
  20. // WITHOUT ANY WARRANTY; without even the implied warranty of
  21. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  22. // See the GNU Lesser General Public License for more details.
  23. //
  24. // You should have received a copy of the GNU Lesser General Public License
  25. // along with TCPDF. If not, see <http://www.gnu.org/licenses/>.
  26. //
  27. // See LICENSE.TXT file for more information.
  28. // -------------------------------------------------------------------
  29. //
  30. // Description :Font methods for TCPDF library.
  31. //
  32. //============================================================+
  33. /**
  34. * @file
  35. * Unicode data and font methods for TCPDF library.
  36. * @author Nicola Asuni
  37. * @package com.tecnick.tcpdf
  38. */
  39. /**
  40. * @class TCPDF_FONTS
  41. * Font methods for TCPDF library.
  42. * @package com.tecnick.tcpdf
  43. * @version 1.0.009
  44. * @author Nicola Asuni - info@tecnick.com
  45. */
  46. class TCPDF_FONTS {
  47. /**
  48. * Convert and add the selected TrueType or Type1 font to the fonts folder (that must be writeable).
  49. * @param $fontfile (string) Font file (full path).
  50. * @param $fonttype (string) Font type. Leave empty for autodetect mode. Valid values are: TrueTypeUnicode, TrueType, Type1, CID0JP = CID-0 Japanese, CID0KR = CID-0 Korean, CID0CS = CID-0 Chinese Simplified, CID0CT = CID-0 Chinese Traditional.
  51. * @param $enc (string) Name of the encoding table to use. Leave empty for default mode. Omit this parameter for TrueType Unicode and symbolic fonts like Symbol or ZapfDingBats.
  52. * @param $flags (int) Unsigned 32-bit integer containing flags specifying various characteristics of the font (PDF32000:2008 - 9.8.2 Font Descriptor Flags): +1 for fixed font; +4 for symbol or +32 for non-symbol; +64 for italic. Fixed and Italic mode are generally autodetected so you have to set it to 32 = non-symbolic font (default) or 4 = symbolic font.
  53. * @param $outpath (string) Output path for generated font files (must be writeable by the web server). Leave empty for default font folder.
  54. * @param $platid (int) Platform ID for CMAP table to extract (when building a Unicode font for Windows this value should be 3, for Macintosh should be 1).
  55. * @param $encid (int) Encoding ID for CMAP table to extract (when building a Unicode font for Windows this value should be 1, for Macintosh should be 0). When Platform ID is 3, legal values for Encoding ID are: 0=Symbol, 1=Unicode, 2=ShiftJIS, 3=PRC, 4=Big5, 5=Wansung, 6=Johab, 7=Reserved, 8=Reserved, 9=Reserved, 10=UCS-4.
  56. * @param $addcbbox (boolean) If true includes the character bounding box information on the php font file.
  57. * @param $link (boolean) If true link to system font instead of copying the font data (not transportable) - Note: do not work with Type1 fonts.
  58. * @return (string) TCPDF font name or boolean false in case of error.
  59. * @author Nicola Asuni
  60. * @since 5.9.123 (2010-09-30)
  61. * @public static
  62. */
  63. public static function addTTFfont($fontfile, $fonttype='', $enc='', $flags=32, $outpath='', $platid=3, $encid=1, $addcbbox=false, $link=false) {
  64. if (!file_exists($fontfile)) {
  65. // Could not find file
  66. return false;
  67. }
  68. // font metrics
  69. $fmetric = array();
  70. // build new font name for TCPDF compatibility
  71. $font_path_parts = pathinfo($fontfile);
  72. if (!isset($font_path_parts['filename'])) {
  73. $font_path_parts['filename'] = substr($font_path_parts['basename'], 0, -(strlen($font_path_parts['extension']) + 1));
  74. }
  75. $font_name = strtolower($font_path_parts['filename']);
  76. $font_name = preg_replace('/[^a-z0-9_]/', '', $font_name);
  77. $search = array('bold', 'oblique', 'italic', 'regular');
  78. $replace = array('b', 'i', 'i', '');
  79. $font_name = str_replace($search, $replace, $font_name);
  80. if (empty($font_name)) {
  81. // set generic name
  82. $font_name = 'tcpdffont';
  83. }
  84. // set output path
  85. if (empty($outpath)) {
  86. $outpath = self::_getfontpath();
  87. }
  88. // check if this font already exist
  89. if (@file_exists($outpath.$font_name.'.php')) {
  90. // this font already exist (delete it from fonts folder to rebuild it)
  91. return $font_name;
  92. }
  93. $fmetric['file'] = $font_name;
  94. $fmetric['ctg'] = $font_name.'.ctg.z';
  95. // get font data
  96. $font = file_get_contents($fontfile);
  97. $fmetric['originalsize'] = strlen($font);
  98. // autodetect font type
  99. if (empty($fonttype)) {
  100. if (TCPDF_STATIC::_getULONG($font, 0) == 0x10000) {
  101. // True Type (Unicode or not)
  102. $fonttype = 'TrueTypeUnicode';
  103. } elseif (substr($font, 0, 4) == 'OTTO') {
  104. // Open Type (Unicode or not)
  105. //Unsupported font format: OpenType with CFF data
  106. return false;
  107. } else {
  108. // Type 1
  109. $fonttype = 'Type1';
  110. }
  111. }
  112. // set font type
  113. switch ($fonttype) {
  114. case 'CID0CT':
  115. case 'CID0CS':
  116. case 'CID0KR':
  117. case 'CID0JP': {
  118. $fmetric['type'] = 'cidfont0';
  119. break;
  120. }
  121. case 'Type1': {
  122. $fmetric['type'] = 'Type1';
  123. if (empty($enc) AND (($flags & 4) == 0)) {
  124. $enc = 'cp1252';
  125. }
  126. break;
  127. }
  128. case 'TrueType': {
  129. $fmetric['type'] = 'TrueType';
  130. break;
  131. }
  132. case 'TrueTypeUnicode':
  133. default: {
  134. $fmetric['type'] = 'TrueTypeUnicode';
  135. break;
  136. }
  137. }
  138. // set encoding maps (if any)
  139. $fmetric['enc'] = preg_replace('/[^A-Za-z0-9_\-]/', '', $enc);
  140. $fmetric['diff'] = '';
  141. if (($fmetric['type'] == 'TrueType') OR ($fmetric['type'] == 'Type1')) {
  142. if (!empty($enc) AND ($enc != 'cp1252') AND isset(TCPDF_FONT_DATA::$encmap[$enc])) {
  143. // build differences from reference encoding
  144. $enc_ref = TCPDF_FONT_DATA::$encmap['cp1252'];
  145. $enc_target = TCPDF_FONT_DATA::$encmap[$enc];
  146. $last = 0;
  147. for ($i = 32; $i <= 255; ++$i) {
  148. if ($enc_target != $enc_ref[$i]) {
  149. if ($i != ($last + 1)) {
  150. $fmetric['diff'] .= $i.' ';
  151. }
  152. $last = $i;
  153. $fmetric['diff'] .= '/'.$enc_target[$i].' ';
  154. }
  155. }
  156. }
  157. }
  158. // parse the font by type
  159. if ($fmetric['type'] == 'Type1') {
  160. // ---------- TYPE 1 ----------
  161. // read first segment
  162. $a = unpack('Cmarker/Ctype/Vsize', substr($font, 0, 6));
  163. if ($a['marker'] != 128) {
  164. // Font file is not a valid binary Type1
  165. return false;
  166. }
  167. $fmetric['size1'] = $a['size'];
  168. $data = substr($font, 6, $fmetric['size1']);
  169. // read second segment
  170. $a = unpack('Cmarker/Ctype/Vsize', substr($font, (6 + $fmetric['size1']), 6));
  171. if ($a['marker'] != 128) {
  172. // Font file is not a valid binary Type1
  173. return false;
  174. }
  175. $fmetric['size2'] = $a['size'];
  176. $encrypted = substr($font, (12 + $fmetric['size1']), $fmetric['size2']);
  177. $data .= $encrypted;
  178. // store compressed font
  179. $fmetric['file'] .= '.z';
  180. $fp = fopen($outpath.$fmetric['file'], 'wb');
  181. fwrite($fp, gzcompress($data));
  182. fclose($fp);
  183. // get font info
  184. $fmetric['Flags'] = $flags;
  185. preg_match ('#/FullName[\s]*\(([^\)]*)#', $font, $matches);
  186. $fmetric['name'] = preg_replace('/[^a-zA-Z0-9_\-]/', '', $matches[1]);
  187. preg_match('#/FontBBox[\s]*{([^}]*)#', $font, $matches);
  188. $fmetric['bbox'] = trim($matches[1]);
  189. $bv = explode(' ', $fmetric['bbox']);
  190. $fmetric['Ascent'] = intval($bv[3]);
  191. $fmetric['Descent'] = intval($bv[1]);
  192. preg_match('#/ItalicAngle[\s]*([0-9\+\-]*)#', $font, $matches);
  193. $fmetric['italicAngle'] = intval($matches[1]);
  194. if ($fmetric['italicAngle'] != 0) {
  195. $fmetric['Flags'] |= 64;
  196. }
  197. preg_match('#/UnderlinePosition[\s]*([0-9\+\-]*)#', $font, $matches);
  198. $fmetric['underlinePosition'] = intval($matches[1]);
  199. preg_match('#/UnderlineThickness[\s]*([0-9\+\-]*)#', $font, $matches);
  200. $fmetric['underlineThickness'] = intval($matches[1]);
  201. preg_match('#/isFixedPitch[\s]*([^\s]*)#', $font, $matches);
  202. if ($matches[1] == 'true') {
  203. $fmetric['Flags'] |= 1;
  204. }
  205. // get internal map
  206. $imap = array();
  207. if (preg_match_all('#dup[\s]([0-9]+)[\s]*/([^\s]*)[\s]put#sU', $font, $fmap, PREG_SET_ORDER) > 0) {
  208. foreach ($fmap as $v) {
  209. $imap[$v[2]] = $v[1];
  210. }
  211. }
  212. // decrypt eexec encrypted part
  213. $r = 55665; // eexec encryption constant
  214. $c1 = 52845;
  215. $c2 = 22719;
  216. $elen = strlen($encrypted);
  217. $eplain = '';
  218. for ($i = 0; $i < $elen; ++$i) {
  219. $chr = ord($encrypted[$i]);
  220. $eplain .= chr($chr ^ ($r >> 8));
  221. $r = ((($chr + $r) * $c1 + $c2) % 65536);
  222. }
  223. if (preg_match('#/ForceBold[\s]*([^\s]*)#', $eplain, $matches) > 0) {
  224. if ($matches[1] == 'true') {
  225. $fmetric['Flags'] |= 0x40000;
  226. }
  227. }
  228. if (preg_match('#/StdVW[\s]*\[([^\]]*)#', $eplain, $matches) > 0) {
  229. $fmetric['StemV'] = intval($matches[1]);
  230. } else {
  231. $fmetric['StemV'] = 70;
  232. }
  233. if (preg_match('#/StdHW[\s]*\[([^\]]*)#', $eplain, $matches) > 0) {
  234. $fmetric['StemH'] = intval($matches[1]);
  235. } else {
  236. $fmetric['StemH'] = 30;
  237. }
  238. if (preg_match('#/BlueValues[\s]*\[([^\]]*)#', $eplain, $matches) > 0) {
  239. $bv = explode(' ', $matches[1]);
  240. if (count($bv) >= 6) {
  241. $v1 = intval($bv[2]);
  242. $v2 = intval($bv[4]);
  243. if ($v1 <= $v2) {
  244. $fmetric['XHeight'] = $v1;
  245. $fmetric['CapHeight'] = $v2;
  246. } else {
  247. $fmetric['XHeight'] = $v2;
  248. $fmetric['CapHeight'] = $v1;
  249. }
  250. } else {
  251. $fmetric['XHeight'] = 450;
  252. $fmetric['CapHeight'] = 700;
  253. }
  254. } else {
  255. $fmetric['XHeight'] = 450;
  256. $fmetric['CapHeight'] = 700;
  257. }
  258. // get the number of random bytes at the beginning of charstrings
  259. if (preg_match('#/lenIV[\s]*([0-9]*)#', $eplain, $matches) > 0) {
  260. $lenIV = intval($matches[1]);
  261. } else {
  262. $lenIV = 4;
  263. }
  264. $fmetric['Leading'] = 0;
  265. // get charstring data
  266. $eplain = substr($eplain, (strpos($eplain, '/CharStrings') + 1));
  267. preg_match_all('#/([A-Za-z0-9\.]*)[\s][0-9]+[\s]RD[\s](.*)[\s]ND#sU', $eplain, $matches, PREG_SET_ORDER);
  268. if (!empty($enc) AND isset(TCPDF_FONT_DATA::$encmap[$enc])) {
  269. $enc_map = TCPDF_FONT_DATA::$encmap[$enc];
  270. } else {
  271. $enc_map = false;
  272. }
  273. $fmetric['cw'] = '';
  274. $fmetric['MaxWidth'] = 0;
  275. $cwidths = array();
  276. foreach ($matches as $k => $v) {
  277. $cid = 0;
  278. if (isset($imap[$v[1]])) {
  279. $cid = $imap[$v[1]];
  280. } elseif ($enc_map !== false) {
  281. $cid = array_search($v[1], $enc_map);
  282. if ($cid === false) {
  283. $cid = 0;
  284. } elseif ($cid > 1000) {
  285. $cid -= 1000;
  286. }
  287. }
  288. // decrypt charstring encrypted part
  289. $r = 4330; // charstring encryption constant
  290. $c1 = 52845;
  291. $c2 = 22719;
  292. $cd = $v[2];
  293. $clen = strlen($cd);
  294. $ccom = array();
  295. for ($i = 0; $i < $clen; ++$i) {
  296. $chr = ord($cd[$i]);
  297. $ccom[] = ($chr ^ ($r >> 8));
  298. $r = ((($chr + $r) * $c1 + $c2) % 65536);
  299. }
  300. // decode numbers
  301. $cdec = array();
  302. $ck = 0;
  303. $i = $lenIV;
  304. while ($i < $clen) {
  305. if ($ccom[$i] < 32) {
  306. $cdec[$ck] = $ccom[$i];
  307. if (($ck > 0) AND ($cdec[$ck] == 13)) {
  308. // hsbw command: update width
  309. $cwidths[$cid] = $cdec[($ck - 1)];
  310. }
  311. ++$i;
  312. } elseif (($ccom[$i] >= 32) AND ($ccom[$i] <= 246)) {
  313. $cdec[$ck] = ($ccom[$i] - 139);
  314. ++$i;
  315. } elseif (($ccom[$i] >= 247) AND ($ccom[$i] <= 250)) {
  316. $cdec[$ck] = ((($ccom[$i] - 247) * 256) + $ccom[($i + 1)] + 108);
  317. $i += 2;
  318. } elseif (($ccom[$i] >= 251) AND ($ccom[$i] <= 254)) {
  319. $cdec[$ck] = ((-($ccom[$i] - 251) * 256) - $ccom[($i + 1)] - 108);
  320. $i += 2;
  321. } elseif ($ccom[$i] == 255) {
  322. $sval = chr($ccom[($i + 1)]).chr($ccom[($i + 2)]).chr($ccom[($i + 3)]).chr($ccom[($i + 4)]);
  323. $vsval = unpack('li', $sval);
  324. $cdec[$ck] = $vsval['i'];
  325. $i += 5;
  326. }
  327. ++$ck;
  328. }
  329. } // end for each matches
  330. $fmetric['MissingWidth'] = $cwidths[0];
  331. $fmetric['MaxWidth'] = $fmetric['MissingWidth'];
  332. $fmetric['AvgWidth'] = 0;
  333. // set chars widths
  334. for ($cid = 0; $cid <= 255; ++$cid) {
  335. if (isset($cwidths[$cid])) {
  336. if ($cwidths[$cid] > $fmetric['MaxWidth']) {
  337. $fmetric['MaxWidth'] = $cwidths[$cid];
  338. }
  339. $fmetric['AvgWidth'] += $cwidths[$cid];
  340. $fmetric['cw'] .= ','.$cid.'=>'.$cwidths[$cid];
  341. } else {
  342. $fmetric['cw'] .= ','.$cid.'=>'.$fmetric['MissingWidth'];
  343. }
  344. }
  345. $fmetric['AvgWidth'] = round($fmetric['AvgWidth'] / count($cwidths));
  346. } else {
  347. // ---------- TRUE TYPE ----------
  348. if ($fmetric['type'] != 'cidfont0') {
  349. if ($link) {
  350. // creates a symbolic link to the existing font
  351. symlink($fontfile, $outpath.$fmetric['file']);
  352. } else {
  353. // store compressed font
  354. $fmetric['file'] .= '.z';
  355. $fp = fopen($outpath.$fmetric['file'], 'wb');
  356. fwrite($fp, gzcompress($font));
  357. fclose($fp);
  358. }
  359. }
  360. $offset = 0; // offset position of the font data
  361. if (TCPDF_STATIC::_getULONG($font, $offset) != 0x10000) {
  362. // sfnt version must be 0x00010000 for TrueType version 1.0.
  363. return false;
  364. }
  365. $offset += 4;
  366. // get number of tables
  367. $numTables = TCPDF_STATIC::_getUSHORT($font, $offset);
  368. $offset += 2;
  369. // skip searchRange, entrySelector and rangeShift
  370. $offset += 6;
  371. // tables array
  372. $table = array();
  373. // ---------- get tables ----------
  374. for ($i = 0; $i < $numTables; ++$i) {
  375. // get table info
  376. $tag = substr($font, $offset, 4);
  377. $offset += 4;
  378. $table[$tag] = array();
  379. $table[$tag]['checkSum'] = TCPDF_STATIC::_getULONG($font, $offset);
  380. $offset += 4;
  381. $table[$tag]['offset'] = TCPDF_STATIC::_getULONG($font, $offset);
  382. $offset += 4;
  383. $table[$tag]['length'] = TCPDF_STATIC::_getULONG($font, $offset);
  384. $offset += 4;
  385. }
  386. // check magicNumber
  387. $offset = $table['head']['offset'] + 12;
  388. if (TCPDF_STATIC::_getULONG($font, $offset) != 0x5F0F3CF5) {
  389. // magicNumber must be 0x5F0F3CF5
  390. return false;
  391. }
  392. $offset += 4;
  393. $offset += 2; // skip flags
  394. // get FUnits
  395. $fmetric['unitsPerEm'] = TCPDF_STATIC::_getUSHORT($font, $offset);
  396. $offset += 2;
  397. // units ratio constant
  398. $urk = (1000 / $fmetric['unitsPerEm']);
  399. $offset += 16; // skip created, modified
  400. $xMin = round(TCPDF_STATIC::_getFWORD($font, $offset) * $urk);
  401. $offset += 2;
  402. $yMin = round(TCPDF_STATIC::_getFWORD($font, $offset) * $urk);
  403. $offset += 2;
  404. $xMax = round(TCPDF_STATIC::_getFWORD($font, $offset) * $urk);
  405. $offset += 2;
  406. $yMax = round(TCPDF_STATIC::_getFWORD($font, $offset) * $urk);
  407. $offset += 2;
  408. $fmetric['bbox'] = ''.$xMin.' '.$yMin.' '.$xMax.' '.$yMax.'';
  409. $macStyle = TCPDF_STATIC::_getUSHORT($font, $offset);
  410. $offset += 2;
  411. // PDF font flags
  412. $fmetric['Flags'] = $flags;
  413. if (($macStyle & 2) == 2) {
  414. // italic flag
  415. $fmetric['Flags'] |= 64;
  416. }
  417. // get offset mode (indexToLocFormat : 0 = short, 1 = long)
  418. $offset = $table['head']['offset'] + 50;
  419. $short_offset = (TCPDF_STATIC::_getSHORT($font, $offset) == 0);
  420. $offset += 2;
  421. // get the offsets to the locations of the glyphs in the font, relative to the beginning of the glyphData table
  422. $indexToLoc = array();
  423. $offset = $table['loca']['offset'];
  424. if ($short_offset) {
  425. // short version
  426. $tot_num_glyphs = floor($table['loca']['length'] / 2); // numGlyphs + 1
  427. for ($i = 0; $i < $tot_num_glyphs; ++$i) {
  428. $indexToLoc[$i] = TCPDF_STATIC::_getUSHORT($font, $offset) * 2;
  429. $offset += 2;
  430. }
  431. } else {
  432. // long version
  433. $tot_num_glyphs = floor($table['loca']['length'] / 4); // numGlyphs + 1
  434. for ($i = 0; $i < $tot_num_glyphs; ++$i) {
  435. $indexToLoc[$i] = TCPDF_STATIC::_getULONG($font, $offset);
  436. $offset += 4;
  437. }
  438. }
  439. // get glyphs indexes of chars from cmap table
  440. $offset = $table['cmap']['offset'] + 2;
  441. $numEncodingTables = TCPDF_STATIC::_getUSHORT($font, $offset);
  442. $offset += 2;
  443. $encodingTables = array();
  444. for ($i = 0; $i < $numEncodingTables; ++$i) {
  445. $encodingTables[$i]['platformID'] = TCPDF_STATIC::_getUSHORT($font, $offset);
  446. $offset += 2;
  447. $encodingTables[$i]['encodingID'] = TCPDF_STATIC::_getUSHORT($font, $offset);
  448. $offset += 2;
  449. $encodingTables[$i]['offset'] = TCPDF_STATIC::_getULONG($font, $offset);
  450. $offset += 4;
  451. }
  452. // ---------- get os/2 metrics ----------
  453. $offset = $table['OS/2']['offset'];
  454. $offset += 2; // skip version
  455. // xAvgCharWidth
  456. $fmetric['AvgWidth'] = round(TCPDF_STATIC::_getFWORD($font, $offset) * $urk);
  457. $offset += 2;
  458. // usWeightClass
  459. $usWeightClass = round(TCPDF_STATIC::_getUFWORD($font, $offset) * $urk);
  460. // estimate StemV and StemH (400 = usWeightClass for Normal - Regular font)
  461. $fmetric['StemV'] = round((70 * $usWeightClass) / 400);
  462. $fmetric['StemH'] = round((30 * $usWeightClass) / 400);
  463. $offset += 2;
  464. $offset += 2; // usWidthClass
  465. $fsType = TCPDF_STATIC::_getSHORT($font, $offset);
  466. $offset += 2;
  467. if ($fsType == 2) {
  468. // This Font cannot be modified, embedded or exchanged in any manner without first obtaining permission of the legal owner.
  469. return false;
  470. }
  471. // ---------- get font name ----------
  472. $fmetric['name'] = '';
  473. $offset = $table['name']['offset'];
  474. $offset += 2; // skip Format selector (=0).
  475. // Number of NameRecords that follow n.
  476. $numNameRecords = TCPDF_STATIC::_getUSHORT($font, $offset);
  477. $offset += 2;
  478. // Offset to start of string storage (from start of table).
  479. $stringStorageOffset = TCPDF_STATIC::_getUSHORT($font, $offset);
  480. $offset += 2;
  481. for ($i = 0; $i < $numNameRecords; ++$i) {
  482. $offset += 6; // skip Platform ID, Platform-specific encoding ID, Language ID.
  483. // Name ID.
  484. $nameID = TCPDF_STATIC::_getUSHORT($font, $offset);
  485. $offset += 2;
  486. if ($nameID == 6) {
  487. // String length (in bytes).
  488. $stringLength = TCPDF_STATIC::_getUSHORT($font, $offset);
  489. $offset += 2;
  490. // String offset from start of storage area (in bytes).
  491. $stringOffset = TCPDF_STATIC::_getUSHORT($font, $offset);
  492. $offset += 2;
  493. $offset = ($table['name']['offset'] + $stringStorageOffset + $stringOffset);
  494. $fmetric['name'] = substr($font, $offset, $stringLength);
  495. $fmetric['name'] = preg_replace('/[^a-zA-Z0-9_\-]/', '', $fmetric['name']);
  496. break;
  497. } else {
  498. $offset += 4; // skip String length, String offset
  499. }
  500. }
  501. if (empty($fmetric['name'])) {
  502. $fmetric['name'] = $font_name;
  503. }
  504. // ---------- get post data ----------
  505. $offset = $table['post']['offset'];
  506. $offset += 4; // skip Format Type
  507. $fmetric['italicAngle'] = TCPDF_STATIC::_getFIXED($font, $offset);
  508. $offset += 4;
  509. $fmetric['underlinePosition'] = round(TCPDF_STATIC::_getFWORD($font, $offset) * $urk);
  510. $offset += 2;
  511. $fmetric['underlineThickness'] = round(TCPDF_STATIC::_getFWORD($font, $offset) * $urk);
  512. $offset += 2;
  513. $isFixedPitch = (TCPDF_STATIC::_getULONG($font, $offset) == 0) ? false : true;
  514. $offset += 2;
  515. if ($isFixedPitch) {
  516. $fmetric['Flags'] |= 1;
  517. }
  518. // ---------- get hhea data ----------
  519. $offset = $table['hhea']['offset'];
  520. $offset += 4; // skip Table version number
  521. // Ascender
  522. $fmetric['Ascent'] = round(TCPDF_STATIC::_getFWORD($font, $offset) * $urk);
  523. $offset += 2;
  524. // Descender
  525. $fmetric['Descent'] = round(TCPDF_STATIC::_getFWORD($font, $offset) * $urk);
  526. $offset += 2;
  527. // LineGap
  528. $fmetric['Leading'] = round(TCPDF_STATIC::_getFWORD($font, $offset) * $urk);
  529. $offset += 2;
  530. // advanceWidthMax
  531. $fmetric['MaxWidth'] = round(TCPDF_STATIC::_getUFWORD($font, $offset) * $urk);
  532. $offset += 2;
  533. $offset += 22; // skip some values
  534. // get the number of hMetric entries in hmtx table
  535. $numberOfHMetrics = TCPDF_STATIC::_getUSHORT($font, $offset);
  536. // ---------- get maxp data ----------
  537. $offset = $table['maxp']['offset'];
  538. $offset += 4; // skip Table version number
  539. // get the the number of glyphs in the font.
  540. $numGlyphs = TCPDF_STATIC::_getUSHORT($font, $offset);
  541. // ---------- get CIDToGIDMap ----------
  542. $ctg = array();
  543. foreach ($encodingTables as $enctable) {
  544. // get only specified Platform ID and Encoding ID
  545. if (($enctable['platformID'] == $platid) AND ($enctable['encodingID'] == $encid)) {
  546. $offset = $table['cmap']['offset'] + $enctable['offset'];
  547. $format = TCPDF_STATIC::_getUSHORT($font, $offset);
  548. $offset += 2;
  549. switch ($format) {
  550. case 0: { // Format 0: Byte encoding table
  551. $offset += 4; // skip length and version/language
  552. for ($c = 0; $c < 256; ++$c) {
  553. $g = TCPDF_STATIC::_getBYTE($font, $offset);
  554. $ctg[$c] = $g;
  555. ++$offset;
  556. }
  557. break;
  558. }
  559. case 2: { // Format 2: High-byte mapping through table
  560. $offset += 4; // skip length and version/language
  561. $numSubHeaders = 0;
  562. for ($i = 0; $i < 256; ++$i) {
  563. // Array that maps high bytes to subHeaders: value is subHeader index * 8.
  564. $subHeaderKeys[$i] = (TCPDF_STATIC::_getUSHORT($font, $offset) / 8);
  565. $offset += 2;
  566. if ($numSubHeaders < $subHeaderKeys[$i]) {
  567. $numSubHeaders = $subHeaderKeys[$i];
  568. }
  569. }
  570. // the number of subHeaders is equal to the max of subHeaderKeys + 1
  571. ++$numSubHeaders;
  572. // read subHeader structures
  573. $subHeaders = array();
  574. $numGlyphIndexArray = 0;
  575. for ($k = 0; $k < $numSubHeaders; ++$k) {
  576. $subHeaders[$k]['firstCode'] = TCPDF_STATIC::_getUSHORT($font, $offset);
  577. $offset += 2;
  578. $subHeaders[$k]['entryCount'] = TCPDF_STATIC::_getUSHORT($font, $offset);
  579. $offset += 2;
  580. $subHeaders[$k]['idDelta'] = TCPDF_STATIC::_getUSHORT($font, $offset);
  581. $offset += 2;
  582. $subHeaders[$k]['idRangeOffset'] = TCPDF_STATIC::_getUSHORT($font, $offset);
  583. $offset += 2;
  584. $subHeaders[$k]['idRangeOffset'] -= (2 + (($numSubHeaders - $k - 1) * 8));
  585. $subHeaders[$k]['idRangeOffset'] /= 2;
  586. $numGlyphIndexArray += $subHeaders[$k]['entryCount'];
  587. }
  588. for ($k = 0; $k < $numGlyphIndexArray; ++$k) {
  589. $glyphIndexArray[$k] = TCPDF_STATIC::_getUSHORT($font, $offset);
  590. $offset += 2;
  591. }
  592. for ($i = 0; $i < 256; ++$i) {
  593. $k = $subHeaderKeys[$i];
  594. if ($k == 0) {
  595. // one byte code
  596. $c = $i;
  597. $g = $glyphIndexArray[0];
  598. $ctg[$c] = $g;
  599. } else {
  600. // two bytes code
  601. $start_byte = $subHeaders[$k]['firstCode'];
  602. $end_byte = $start_byte + $subHeaders[$k]['entryCount'];
  603. for ($j = $start_byte; $j < $end_byte; ++$j) {
  604. // combine high and low bytes
  605. $c = (($i << 8) + $j);
  606. $idRangeOffset = ($subHeaders[$k]['idRangeOffset'] + $j - $subHeaders[$k]['firstCode']);
  607. $g = ($glyphIndexArray[$idRangeOffset] + $idDelta[$k]) % 65536;
  608. if ($g < 0) {
  609. $g = 0;
  610. }
  611. $ctg[$c] = $g;
  612. }
  613. }
  614. }
  615. break;
  616. }
  617. case 4: { // Format 4: Segment mapping to delta values
  618. $length = TCPDF_STATIC::_getUSHORT($font, $offset);
  619. $offset += 2;
  620. $offset += 2; // skip version/language
  621. $segCount = floor(TCPDF_STATIC::_getUSHORT($font, $offset) / 2);
  622. $offset += 2;
  623. $offset += 6; // skip searchRange, entrySelector, rangeShift
  624. $endCount = array(); // array of end character codes for each segment
  625. for ($k = 0; $k < $segCount; ++$k) {
  626. $endCount[$k] = TCPDF_STATIC::_getUSHORT($font, $offset);
  627. $offset += 2;
  628. }
  629. $offset += 2; // skip reservedPad
  630. $startCount = array(); // array of start character codes for each segment
  631. for ($k = 0; $k < $segCount; ++$k) {
  632. $startCount[$k] = TCPDF_STATIC::_getUSHORT($font, $offset);
  633. $offset += 2;
  634. }
  635. $idDelta = array(); // delta for all character codes in segment
  636. for ($k = 0; $k < $segCount; ++$k) {
  637. $idDelta[$k] = TCPDF_STATIC::_getUSHORT($font, $offset);
  638. $offset += 2;
  639. }
  640. $idRangeOffset = array(); // Offsets into glyphIdArray or 0
  641. for ($k = 0; $k < $segCount; ++$k) {
  642. $idRangeOffset[$k] = TCPDF_STATIC::_getUSHORT($font, $offset);
  643. $offset += 2;
  644. }
  645. $gidlen = (floor($length / 2) - 8 - (4 * $segCount));
  646. $glyphIdArray = array(); // glyph index array
  647. for ($k = 0; $k < $gidlen; ++$k) {
  648. $glyphIdArray[$k] = TCPDF_STATIC::_getUSHORT($font, $offset);
  649. $offset += 2;
  650. }
  651. for ($k = 0; $k < $segCount; ++$k) {
  652. for ($c = $startCount[$k]; $c <= $endCount[$k]; ++$c) {
  653. if ($idRangeOffset[$k] == 0) {
  654. $g = ($idDelta[$k] + $c) % 65536;
  655. } else {
  656. $gid = (floor($idRangeOffset[$k] / 2) + ($c - $startCount[$k]) - ($segCount - $k));
  657. $g = ($glyphIdArray[$gid] + $idDelta[$k]) % 65536;
  658. }
  659. if ($g < 0) {
  660. $g = 0;
  661. }
  662. $ctg[$c] = $g;
  663. }
  664. }
  665. break;
  666. }
  667. case 6: { // Format 6: Trimmed table mapping
  668. $offset += 4; // skip length and version/language
  669. $firstCode = TCPDF_STATIC::_getUSHORT($font, $offset);
  670. $offset += 2;
  671. $entryCount = TCPDF_STATIC::_getUSHORT($font, $offset);
  672. $offset += 2;
  673. for ($k = 0; $k < $entryCount; ++$k) {
  674. $c = ($k + $firstCode);
  675. $g = TCPDF_STATIC::_getUSHORT($font, $offset);
  676. $offset += 2;
  677. $ctg[$c] = $g;
  678. }
  679. break;
  680. }
  681. case 8: { // Format 8: Mixed 16-bit and 32-bit coverage
  682. $offset += 10; // skip reserved, length and version/language
  683. for ($k = 0; $k < 8192; ++$k) {
  684. $is32[$k] = TCPDF_STATIC::_getBYTE($font, $offset);
  685. ++$offset;
  686. }
  687. $nGroups = TCPDF_STATIC::_getULONG($font, $offset);
  688. $offset += 4;
  689. for ($i = 0; $i < $nGroups; ++$i) {
  690. $startCharCode = TCPDF_STATIC::_getULONG($font, $offset);
  691. $offset += 4;
  692. $endCharCode = TCPDF_STATIC::_getULONG($font, $offset);
  693. $offset += 4;
  694. $startGlyphID = TCPDF_STATIC::_getULONG($font, $offset);
  695. $offset += 4;
  696. for ($k = $startCharCode; $k <= $endCharCode; ++$k) {
  697. $is32idx = floor($c / 8);
  698. if ((isset($is32[$is32idx])) AND (($is32[$is32idx] & (1 << (7 - ($c % 8)))) == 0)) {
  699. $c = $k;
  700. } else {
  701. // 32 bit format
  702. // convert to decimal (http://www.unicode.org/faq//utf_bom.html#utf16-4)
  703. //LEAD_OFFSET = (0xD800 - (0x10000 >> 10)) = 55232
  704. //SURROGATE_OFFSET = (0x10000 - (0xD800 << 10) - 0xDC00) = -56613888
  705. $c = ((55232 + ($k >> 10)) << 10) + (0xDC00 + ($k & 0x3FF)) -56613888;
  706. }
  707. $ctg[$c] = 0;
  708. ++$startGlyphID;
  709. }
  710. }
  711. break;
  712. }
  713. case 10: { // Format 10: Trimmed array
  714. $offset += 10; // skip reserved, length and version/language
  715. $startCharCode = TCPDF_STATIC::_getULONG($font, $offset);
  716. $offset += 4;
  717. $numChars = TCPDF_STATIC::_getULONG($font, $offset);
  718. $offset += 4;
  719. for ($k = 0; $k < $numChars; ++$k) {
  720. $c = ($k + $startCharCode);
  721. $g = TCPDF_STATIC::_getUSHORT($font, $offset);
  722. $ctg[$c] = $g;
  723. $offset += 2;
  724. }
  725. break;
  726. }
  727. case 12: { // Format 12: Segmented coverage
  728. $offset += 10; // skip length and version/language
  729. $nGroups = TCPDF_STATIC::_getULONG($font, $offset);
  730. $offset += 4;
  731. for ($k = 0; $k < $nGroups; ++$k) {
  732. $startCharCode = TCPDF_STATIC::_getULONG($font, $offset);
  733. $offset += 4;
  734. $endCharCode = TCPDF_STATIC::_getULONG($font, $offset);
  735. $offset += 4;
  736. $startGlyphCode = TCPDF_STATIC::_getULONG($font, $offset);
  737. $offset += 4;
  738. for ($c = $startCharCode; $c <= $endCharCode; ++$c) {
  739. $ctg[$c] = $startGlyphCode;
  740. ++$startGlyphCode;
  741. }
  742. }
  743. break;
  744. }
  745. case 13: { // Format 13: Many-to-one range mappings
  746. // to be implemented ...
  747. break;
  748. }
  749. case 14: { // Format 14: Unicode Variation Sequences
  750. // to be implemented ...
  751. break;
  752. }
  753. }
  754. }
  755. }
  756. if (!isset($ctg[0])) {
  757. $ctg[0] = 0;
  758. }
  759. // get xHeight (height of x)
  760. $offset = ($table['glyf']['offset'] + $indexToLoc[$ctg[120]] + 4);
  761. $yMin = TCPDF_STATIC::_getFWORD($font, $offset);
  762. $offset += 4;
  763. $yMax = TCPDF_STATIC::_getFWORD($font, $offset);
  764. $offset += 2;
  765. $fmetric['XHeight'] = round(($yMax - $yMin) * $urk);
  766. // get CapHeight (height of H)
  767. $offset = ($table['glyf']['offset'] + $indexToLoc[$ctg[72]] + 4);
  768. $yMin = TCPDF_STATIC::_getFWORD($font, $offset);
  769. $offset += 4;
  770. $yMax = TCPDF_STATIC::_getFWORD($font, $offset);
  771. $offset += 2;
  772. $fmetric['CapHeight'] = round(($yMax - $yMin) * $urk);
  773. // ceate widths array
  774. $cw = array();
  775. $offset = $table['hmtx']['offset'];
  776. for ($i = 0 ; $i < $numberOfHMetrics; ++$i) {
  777. $cw[$i] = round(TCPDF_STATIC::_getUFWORD($font, $offset) * $urk);
  778. $offset += 4; // skip lsb
  779. }
  780. if ($numberOfHMetrics < $numGlyphs) {
  781. // fill missing widths with the last value
  782. $cw = array_pad($cw, $numGlyphs, $cw[($numberOfHMetrics - 1)]);
  783. }
  784. $fmetric['MissingWidth'] = $cw[0];
  785. $fmetric['cw'] = '';
  786. for ($cid = 0; $cid <= 65535; ++$cid) {
  787. if (isset($ctg[$cid])) {
  788. if (isset($cw[$ctg[$cid]])) {
  789. $fmetric['cw'] .= ','.$cid.'=>'.$cw[$ctg[$cid]];
  790. }
  791. if ($addcbbox AND isset($indexToLoc[$ctg[$cid]])) {
  792. $offset = ($table['glyf']['offset'] + $indexToLoc[$ctg[$cid]]);
  793. $xMin = round(TCPDF_STATIC::_getFWORD($font, $offset + 2)) * $urk;
  794. $yMin = round(TCPDF_STATIC::_getFWORD($font, $offset + 4)) * $urk;
  795. $xMax = round(TCPDF_STATIC::_getFWORD($font, $offset + 6)) * $urk;
  796. $yMax = round(TCPDF_STATIC::_getFWORD($font, $offset + 8)) * $urk;
  797. $fmetric['cbbox'] .= ','.$cid.'=>array('.$xMin.','.$yMin.','.$xMax.','.$yMax.')';
  798. }
  799. }
  800. }
  801. } // end of true type
  802. if (($fmetric['type'] == 'TrueTypeUnicode') AND (count($ctg) == 256)) {
  803. $fmetric['type'] == 'TrueType';
  804. }
  805. // ---------- create php font file ----------
  806. $pfile = '<'.'?'.'php'."\n";
  807. $pfile .= '// TCPDF FONT FILE DESCRIPTION'."\n";
  808. $pfile .= '$type=\''.$fmetric['type'].'\';'."\n";
  809. $pfile .= '$name=\''.$fmetric['name'].'\';'."\n";
  810. $pfile .= '$up='.$fmetric['underlinePosition'].';'."\n";
  811. $pfile .= '$ut='.$fmetric['underlineThickness'].';'."\n";
  812. if ($fmetric['MissingWidth'] > 0) {
  813. $pfile .= '$dw='.$fmetric['MissingWidth'].';'."\n";
  814. } else {
  815. $pfile .= '$dw='.$fmetric['AvgWidth'].';'."\n";
  816. }
  817. $pfile .= '$diff=\''.$fmetric['diff'].'\';'."\n";
  818. if ($fmetric['type'] == 'Type1') {
  819. // Type 1
  820. $pfile .= '$enc=\''.$fmetric['enc'].'\';'."\n";
  821. $pfile .= '$file=\''.$fmetric['file'].'\';'."\n";
  822. $pfile .= '$size1='.$fmetric['size1'].';'."\n";
  823. $pfile .= '$size2='.$fmetric['size2'].';'."\n";
  824. } else {
  825. $pfile .= '$originalsize='.$fmetric['originalsize'].';'."\n";
  826. if ($fmetric['type'] == 'cidfont0') {
  827. // CID-0
  828. switch ($fonttype) {
  829. case 'CID0JP': {
  830. $pfile .= '// Japanese'."\n";
  831. $pfile .= '$enc=\'UniJIS-UTF16-H\';'."\n";
  832. $pfile .= '$cidinfo=array(\'Registry\'=>\'Adobe\', \'Ordering\'=>\'Japan1\',\'Supplement\'=>5);'."\n";
  833. $pfile .= 'include(dirname(__FILE__).\'/uni2cid_aj16.php\');'."\n";
  834. break;
  835. }
  836. case 'CID0KR': {
  837. $pfile .= '// Korean'."\n";
  838. $pfile .= '$enc=\'UniKS-UTF16-H\';'."\n";
  839. $pfile .= '$cidinfo=array(\'Registry\'=>\'Adobe\', \'Ordering\'=>\'Korea1\',\'Supplement\'=>0);'."\n";
  840. $pfile .= 'include(dirname(__FILE__).\'/uni2cid_ak12.php\');'."\n";
  841. break;
  842. }
  843. case 'CID0CS': {
  844. $pfile .= '// Chinese Simplified'."\n";
  845. $pfile .= '$enc=\'UniGB-UTF16-H\';'."\n";
  846. $pfile .= '$cidinfo=array(\'Registry\'=>\'Adobe\', \'Ordering\'=>\'GB1\',\'Supplement\'=>2);'."\n";
  847. $pfile .= 'include(dirname(__FILE__).\'/uni2cid_ag15.php\');'."\n";
  848. break;
  849. }
  850. case 'CID0CT':
  851. default: {
  852. $pfile .= '// Chinese Traditional'."\n";
  853. $pfile .= '$enc=\'UniCNS-UTF16-H\';'."\n";
  854. $pfile .= '$cidinfo=array(\'Registry\'=>\'Adobe\', \'Ordering\'=>\'CNS1\',\'Supplement\'=>0);'."\n";
  855. $pfile .= 'include(dirname(__FILE__).\'/uni2cid_aj16.php\');'."\n";
  856. break;
  857. }
  858. }
  859. } else {
  860. // TrueType
  861. $pfile .= '$enc=\''.$fmetric['enc'].'\';'."\n";
  862. $pfile .= '$file=\''.$fmetric['file'].'\';'."\n";
  863. $pfile .= '$ctg=\''.$fmetric['ctg'].'\';'."\n";
  864. // create CIDToGIDMap
  865. $cidtogidmap = str_pad('', 131072, "\x00"); // (256 * 256 * 2) = 131072
  866. foreach ($ctg as $cid => $gid) {
  867. $cidtogidmap = self::updateCIDtoGIDmap($cidtogidmap, $cid, $ctg[$cid]);
  868. }
  869. // store compressed CIDToGIDMap
  870. $fp = fopen($outpath.$fmetric['ctg'], 'wb');
  871. fwrite($fp, gzcompress($cidtogidmap));
  872. fclose($fp);
  873. }
  874. }
  875. $pfile .= '$desc=array(';
  876. $pfile .= '\'Flags\'=>'.$fmetric['Flags'].',';
  877. $pfile .= '\'FontBBox\'=>\'['.$fmetric['bbox'].']\',';
  878. $pfile .= '\'ItalicAngle\'=>'.$fmetric['italicAngle'].',';
  879. $pfile .= '\'Ascent\'=>'.$fmetric['Ascent'].',';
  880. $pfile .= '\'Descent\'=>'.$fmetric['Descent'].',';
  881. $pfile .= '\'Leading\'=>'.$fmetric['Leading'].',';
  882. $pfile .= '\'CapHeight\'=>'.$fmetric['CapHeight'].',';
  883. $pfile .= '\'XHeight\'=>'.$fmetric['XHeight'].',';
  884. $pfile .= '\'StemV\'=>'.$fmetric['StemV'].',';
  885. $pfile .= '\'StemH\'=>'.$fmetric['StemH'].',';
  886. $pfile .= '\'AvgWidth\'=>'.$fmetric['AvgWidth'].',';
  887. $pfile .= '\'MaxWidth\'=>'.$fmetric['MaxWidth'].',';
  888. $pfile .= '\'MissingWidth\'=>'.$fmetric['MissingWidth'].'';
  889. $pfile .= ');'."\n";
  890. if (isset($fmetric['cbbox'])) {
  891. $pfile .= '$cbbox=array('.substr($fmetric['cbbox'], 1).');'."\n";
  892. }
  893. $pfile .= '$cw=array('.substr($fmetric['cw'], 1).');'."\n";
  894. $pfile .= '// --- EOF ---'."\n";
  895. // store file
  896. $fp = fopen($outpath.$font_name.'.php', 'w');
  897. fwrite($fp, $pfile);
  898. fclose($fp);
  899. // return TCPDF font name
  900. return $font_name;
  901. }
  902. /**
  903. * Returs the checksum of a TTF table.
  904. * @param $table (string) table to check
  905. * @param $length (int) length of table in bytes
  906. * @return int checksum
  907. * @author Nicola Asuni
  908. * @since 5.2.000 (2010-06-02)
  909. * @public static
  910. */
  911. public static function _getTTFtableChecksum($table, $length) {
  912. $sum = 0;
  913. $tlen = ($length / 4);
  914. $offset = 0;
  915. for ($i = 0; $i < $tlen; ++$i) {
  916. $v = unpack('Ni', substr($table, $offset, 4));
  917. $sum += $v['i'];
  918. $offset += 4;
  919. }
  920. $sum = unpack('Ni', pack('N', $sum));
  921. return $sum['i'];
  922. }
  923. /**
  924. * Returns a subset of the TrueType font data without the unused glyphs.
  925. * @param $font (string) TrueType font data.
  926. * @param $subsetchars (array) Array of used characters (the glyphs to keep).
  927. * @return (string) A subset of TrueType font data without the unused glyphs.
  928. * @author Nicola Asuni
  929. * @since 5.2.000 (2010-06-02)
  930. * @public static
  931. */
  932. public static function _getTrueTypeFontSubset($font, $subsetchars) {
  933. ksort($subsetchars);
  934. $offset = 0; // offset position of the font data
  935. if (TCPDF_STATIC::_getULONG($font, $offset) != 0x10000) {
  936. // sfnt version must be 0x00010000 for TrueType version 1.0.
  937. return $font;
  938. }
  939. $offset += 4;
  940. // get number of tables
  941. $numTables = TCPDF_STATIC::_getUSHORT($font, $offset);
  942. $offset += 2;
  943. // skip searchRange, entrySelector and rangeShift
  944. $offset += 6;
  945. // tables array
  946. $table = array();
  947. // for each table
  948. for ($i = 0; $i < $numTables; ++$i) {
  949. // get table info
  950. $tag = substr($font, $offset, 4);
  951. $offset += 4;
  952. $table[$tag] = array();
  953. $table[$tag]['checkSum'] = TCPDF_STATIC::_getULONG($font, $offset);
  954. $offset += 4;
  955. $table[$tag]['offset'] = TCPDF_STATIC::_getULONG($font, $offset);
  956. $offset += 4;
  957. $table[$tag]['length'] = TCPDF_STATIC::_getULONG($font, $offset);
  958. $offset += 4;
  959. }
  960. // check magicNumber
  961. $offset = $table['head']['offset'] + 12;
  962. if (TCPDF_STATIC::_getULONG($font, $offset) != 0x5F0F3CF5) {
  963. // magicNumber must be 0x5F0F3CF5
  964. return $font;
  965. }
  966. $offset += 4;
  967. // get offset mode (indexToLocFormat : 0 = short, 1 = long)
  968. $offset = $table['head']['offset'] + 50;
  969. $short_offset = (TCPDF_STATIC::_getSHORT($font, $offset) == 0);
  970. $offset += 2;
  971. // get the offsets to the locations of the glyphs in the font, relative to the beginning of the glyphData table
  972. $indexToLoc = array();
  973. $offset = $table['loca']['offset'];
  974. if ($short_offset) {
  975. // short version
  976. $tot_num_glyphs = floor($table['loca']['length'] / 2); // numGlyphs + 1
  977. for ($i = 0; $i < $tot_num_glyphs; ++$i) {
  978. $indexToLoc[$i] = TCPDF_STATIC::_getUSHORT($font, $offset) * 2;
  979. $offset += 2;
  980. }
  981. } else {
  982. // long version
  983. $tot_num_glyphs = ($table['loca']['length'] / 4); // numGlyphs + 1
  984. for ($i = 0; $i < $tot_num_glyphs; ++$i) {
  985. $indexToLoc[$i] = TCPDF_STATIC::_getULONG($font, $offset);
  986. $offset += 4;
  987. }
  988. }
  989. // get glyphs indexes of chars from cmap table
  990. $subsetglyphs = array(); // glyph IDs on key
  991. $subsetglyphs[0] = true; // character codes that do not correspond to any glyph in the font should be mapped to glyph index 0
  992. $offset = $table['cmap']['offset'] + 2;
  993. $numEncodingTables = TCPDF_STATIC::_getUSHORT($font, $offset);
  994. $offset += 2;
  995. $encodingTables = array();
  996. for ($i = 0; $i < $numEncodingTables; ++$i) {
  997. $encodingTables[$i]['platformID'] = TCPDF_STATIC::_getUSHORT($font, $offset);
  998. $offset += 2;
  999. $encodingTables[$i]['encodingID'] = TCPDF_STATIC::_getUSHORT($font, $offset);
  1000. $offset += 2;
  1001. $encodingTables[$i]['offset'] = TCPDF_STATIC::_getULONG($font, $offset);
  1002. $offset += 4;
  1003. }
  1004. foreach ($encodingTables as $enctable) {
  1005. // get all platforms and encodings
  1006. $offset = $table['cmap']['offset'] + $enctable['offset'];
  1007. $format = TCPDF_STATIC::_getUSHORT($font, $offset);
  1008. $offset += 2;
  1009. switch ($format) {
  1010. case 0: { // Format 0: Byte encoding table
  1011. $offset += 4; // skip length and version/language
  1012. for ($c = 0; $c < 256; ++$c) {
  1013. if (isset($subsetchars[$c])) {
  1014. $g = TCPDF_STATIC::_getBYTE($font, $offset);
  1015. $subsetglyphs[$g] = true;
  1016. }
  1017. ++$offset;
  1018. }
  1019. break;
  1020. }
  1021. case 2: { // Format 2: High-byte mapping through table
  1022. $offset += 4; // skip length and version/language
  1023. $numSubHeaders = 0;
  1024. for ($i = 0; $i < 256; ++$i) {
  1025. // Array that maps high bytes to subHeaders: value is subHeader index * 8.
  1026. $subHeaderKeys[$i] = (TCPDF_STATIC::_getUSHORT($font, $offset) / 8);
  1027. $offset += 2;
  1028. if ($numSubHeaders < $subHeaderKeys[$i]) {
  1029. $numSubHeaders = $subHeaderKeys[$i];
  1030. }
  1031. }
  1032. // the number of subHeaders is equal to the max of subHeaderKeys + 1
  1033. ++$numSubHeaders;
  1034. // read subHeader structures
  1035. $subHeaders = array();
  1036. $numGlyphIndexArray = 0;
  1037. for ($k = 0; $k < $numSubHeaders; ++$k) {
  1038. $subHeaders[$k]['firstCode'] = TCPDF_STATIC::_getUSHORT($font, $offset);
  1039. $offset += 2;
  1040. $subHeaders[$k]['entryCount'] = TCPDF_STATIC::_getUSHORT($font, $offset);
  1041. $offset += 2;
  1042. $subHeaders[$k]['idDelta'] = TCPDF_STATIC::_getUSHORT($font, $offset);
  1043. $offset += 2;
  1044. $subHeaders[$k]['idRangeOffset'] = TCPDF_STATIC::_getUSHORT($font, $offset);
  1045. $offset += 2;
  1046. $subHeaders[$k]['idRangeOffset'] -= (2 + (($numSubHeaders - $k - 1) * 8));
  1047. $subHeaders[$k]['idRangeOffset'] /= 2;
  1048. $numGlyphIndexArray += $subHeaders[$k]['entryCount'];
  1049. }
  1050. for ($k = 0; $k < $numGlyphIndexArray; ++$k) {
  1051. $glyphIndexArray[$k] = TCPDF_STATIC::_getUSHORT($font, $offset);
  1052. $offset += 2;
  1053. }
  1054. for ($i = 0; $i < 256; ++$i) {
  1055. $k = $subHeaderKeys[$i];
  1056. if ($k == 0) {
  1057. // one byte code
  1058. $c = $i;
  1059. if (isset($subsetchars[$c])) {
  1060. $g = $glyphIndexArray[0];
  1061. $subsetglyphs[$g] = true;
  1062. }
  1063. } else {
  1064. // two bytes code
  1065. $start_byte = $subHeaders[$k]['firstCode'];
  1066. $end_byte = $start_byte + $subHeaders[$k]['entryCount'];
  1067. for ($j = $start_byte; $j < $end_byte; ++$j) {
  1068. // combine high and low bytes
  1069. $c = (($i << 8) + $j);
  1070. if (isset($subsetchars[$c])) {
  1071. $idRangeOffset = ($subHeaders[$k]['idRangeOffset'] + $j - $subHeaders[$k]['firstCode']);
  1072. $g = ($glyphIndexArray[$idRangeOffset] + $idDelta[$k]) % 65536;
  1073. if ($g < 0) {
  1074. $g = 0;
  1075. }
  1076. $subsetglyphs[$g] = true;
  1077. }
  1078. }
  1079. }
  1080. }
  1081. break;
  1082. }
  1083. case 4: { // Format 4: Segment mapping to delta values
  1084. $length = TCPDF_STATIC::_getUSHORT($font, $offset);
  1085. $offset += 2;
  1086. $offset += 2; // skip version/language
  1087. $segCount = floor(TCPDF_STATIC::_getUSHORT($font, $offset) / 2);
  1088. $offset += 2;
  1089. $offset += 6; // skip searchRange, entrySelector, rangeShift
  1090. $endCount = array(); // array of end character codes for each segment
  1091. for ($k = 0; $k < $segCount; ++$k) {
  1092. $endCount[$k] = TCPDF_STATIC::_getUSHORT($font, $offset);
  1093. $offset += 2;
  1094. }
  1095. $offset += 2; // skip reservedPad
  1096. $startCount = array(); // array of start character codes for each segment
  1097. for ($k = 0; $k < $segCount; ++$k) {
  1098. $startCount[$k] = TCPDF_STATIC::_getUSHORT($font, $offset);
  1099. $offset += 2;
  1100. }
  1101. $idDelta = array(); // delta for all character codes in segment
  1102. for ($k = 0; $k < $segCount; ++$k) {
  1103. $idDelta[$k] = TCPDF_STATIC::_getUSHORT($font, $offset);
  1104. $offset += 2;
  1105. }
  1106. $idRangeOffset = array(); // Offsets into glyphIdArray or 0
  1107. for ($k = 0; $k < $segCount; ++$k) {
  1108. $idRangeOffset[$k] = TCPDF_STATIC::_getUSHORT($font, $offset);
  1109. $offset += 2;
  1110. }
  1111. $gidlen = (floor($length / 2) - 8 - (4 * $segCount));
  1112. $glyphIdArray = array(); // glyph index array
  1113. for ($k = 0; $k < $gidlen; ++$k) {
  1114. $glyphIdArray[$k] = TCPDF_STATIC::_getUSHORT($font, $offset);
  1115. $offset += 2;
  1116. }
  1117. for ($k = 0; $k < $segCount; ++$k) {
  1118. for ($c = $startCount[$k]; $c <= $endCount[$k]; ++$c) {
  1119. if (isset($subsetchars[$c])) {
  1120. if ($idRangeOffset[$k] == 0) {
  1121. $g = ($idDelta[$k] + $c) % 65536;
  1122. } else {
  1123. $gid = (floor($idRangeOffset[$k] / 2) + ($c - $startCount[$k]) - ($segCount - $k));
  1124. $g = ($glyphIdArray[$gid] + $idDelta[$k]) % 65536;
  1125. }
  1126. if ($g < 0) {
  1127. $g = 0;
  1128. }
  1129. $subsetglyphs[$g] = true;
  1130. }
  1131. }
  1132. }
  1133. break;
  1134. }
  1135. case 6: { // Format 6: Trimmed table mapping
  1136. $offset += 4; // skip length and version/language
  1137. $firstCode = TCPDF_STATIC::_getUSHORT($font, $offset);
  1138. $offset += 2;
  1139. $entryCount = TCPDF_STATIC::_getUSHORT($font, $offset);
  1140. $offset += 2;
  1141. for ($k = 0; $k < $entryCount; ++$k) {
  1142. $c = ($k + $firstCode);
  1143. if (isset($subsetchars[$c])) {
  1144. $g = TCPDF_STATIC::_getUSHORT($font, $offset);
  1145. $subsetglyphs[$g] = true;
  1146. }
  1147. $offset += 2;
  1148. }
  1149. break;
  1150. }
  1151. case 8: { // Format 8: Mixed 16-bit and 32-bit coverage
  1152. $offset += 10; // skip reserved, length and version/language
  1153. for ($k = 0; $k < 8192; ++$k) {
  1154. $is32[$k] = TCPDF_STATIC::_getBYTE($font, $offset);
  1155. ++$offset;
  1156. }
  1157. $nGroups = TCPDF_STATIC::_getULONG($font, $offset);
  1158. $offset += 4;
  1159. for ($i = 0; $i < $nGroups; ++$i) {
  1160. $startCharCode = TCPDF_STATIC::_getULONG($font, $offset);
  1161. $offset += 4;
  1162. $endCharCode = TCPDF_STATIC::_getULONG($font, $offset);
  1163. $offset += 4;
  1164. $startGlyphID = TCPDF_STATIC::_getULONG($font, $offset);
  1165. $offset += 4;
  1166. for ($k = $startCharCode; $k <= $endCharCode; ++$k) {
  1167. $is32idx = floor($c / 8);
  1168. if ((isset($is32[$is32idx])) AND (($is32[$is32idx] & (1 << (7 - ($c % 8)))) == 0)) {
  1169. $c = $k;
  1170. } else {
  1171. // 32 bit format
  1172. // convert to decimal (http://www.unicode.org/faq//utf_bom.html#utf16-4)
  1173. //LEAD_OFFSET = (0xD800 - (0x10000 >> 10)) = 55232
  1174. //SURROGATE_OFFSET = (0x10000 - (0xD800 << 10) - 0xDC00) = -56613888
  1175. $c = ((55232 + ($k >> 10)) << 10) + (0xDC00 + ($k & 0x3FF)) -56613888;
  1176. }
  1177. if (isset($subsetchars[$c])) {
  1178. $subsetglyphs[$startGlyphID] = true;
  1179. }
  1180. ++$startGlyphID;
  1181. }
  1182. }
  1183. break;
  1184. }
  1185. case 10: { // Format 10: Trimmed array
  1186. $offset += 10; // skip reserved, length and version/language
  1187. $startCharCode = TCPDF_STATIC::_getULONG($font, $offset);
  1188. $offset += 4;
  1189. $numChars = TCPDF_STATIC::_getULONG($font, $offset);
  1190. $offset += 4;
  1191. for ($k = 0; $k < $numChars; ++$k) {
  1192. $c = ($k + $startCharCode);
  1193. if (isset($subsetchars[$c])) {
  1194. $g = TCPDF_STATIC::_getUSHORT($font, $offset);
  1195. $subsetglyphs[$g] = true;
  1196. }
  1197. $offset += 2;
  1198. }
  1199. break;
  1200. }
  1201. case 12: { // Format 12: Segmented coverage
  1202. $offset += 10; // skip length and version/language
  1203. $nGroups = TCPDF_STATIC::_getULONG($font, $offset);
  1204. $offset += 4;
  1205. for ($k = 0; $k < $nGroups; ++$k) {
  1206. $startCharCode = TCPDF_STATIC::_getULONG($font, $offset);
  1207. $offset += 4;
  1208. $endCharCode = TCPDF_STATIC::_getULONG($font, $offset);
  1209. $offset += 4;
  1210. $startGlyphCode = TCPDF_STATIC::_getULONG($font, $offset);
  1211. $offset += 4;
  1212. for ($c = $startCharCode; $c <= $endCharCode; ++$c) {
  1213. if (isset($subsetchars[$c])) {
  1214. $subsetglyphs[$startGlyphCode] = true;
  1215. }
  1216. ++$startGlyphCode;
  1217. }
  1218. }
  1219. break;
  1220. }
  1221. case 13: { // Format 13: Many-to-one range mappings
  1222. // to be implemented ...
  1223. break;
  1224. }
  1225. case 14: { // Format 14: Unicode Variation Sequences
  1226. // to be implemented ...
  1227. break;
  1228. }
  1229. }
  1230. }
  1231. // include all parts of composite glyphs
  1232. $new_sga = $subsetglyphs;
  1233. while (!empty($new_sga)) {
  1234. $sga = $new_sga;
  1235. $new_sga = array();
  1236. foreach ($sga as $key => $val) {
  1237. if (isset($indexToLoc[$key])) {
  1238. $offset = ($table['glyf']['offset'] + $indexToLoc[$key]);
  1239. $numberOfContours = TCPDF_STATIC::_getSHORT($font, $offset);
  1240. $offset += 2;
  1241. if ($numberOfContours < 0) { // composite glyph
  1242. $offset += 8; // skip xMin, yMin, xMax, yMax
  1243. do {
  1244. $flags = TCPDF_STATIC::_getUSHORT($font, $offset);
  1245. $offset += 2;
  1246. $glyphIndex = TCPDF_STATIC::_getUSHORT($font, $offset);
  1247. $offset += 2;
  1248. if (!isset($subsetglyphs[$glyphIndex])) {
  1249. // add missing glyphs
  1250. $new_sga[$glyphIndex] = true;
  1251. }
  1252. // skip some bytes by case
  1253. if ($flags & 1) {
  1254. $offset += 4;
  1255. } else {
  1256. $offset += 2;
  1257. }
  1258. if ($flags & 8) {
  1259. $offset += 2;
  1260. } elseif ($flags & 64) {
  1261. $offset += 4;
  1262. } elseif ($flags & 128) {
  1263. $offset += 8;
  1264. }
  1265. } while ($flags & 32);
  1266. }
  1267. }
  1268. }
  1269. $subsetglyphs += $new_sga;
  1270. }
  1271. // sort glyphs by key (and remove duplicates)
  1272. ksort($subsetglyphs);
  1273. // build new glyf and loca tables
  1274. $glyf = '';
  1275. $loca = '';
  1276. $offset = 0;
  1277. $glyf_offset = $table['glyf']['offset'];
  1278. for ($i = 0; $i < $tot_num_glyphs; ++$i) {
  1279. if (isset($subsetglyphs[$i])) {
  1280. $length = ($indexToLoc[($i + 1)] - $indexToLoc[$i]);
  1281. $glyf .= substr($font, ($glyf_offset + $indexToLoc[$i]), $length);
  1282. } else {
  1283. $length = 0;
  1284. }
  1285. if ($short_offset) {
  1286. $loca .= pack('n', floor($offset / 2));
  1287. } else {
  1288. $loca .= pack('N', $offset);
  1289. }
  1290. $offset += $length;
  1291. }
  1292. // array of table names to preserve (loca and glyf tables will be added later)
  1293. // the cmap table is not needed and shall not be present, since the mapping from character codes to glyph descriptions is provided separately
  1294. $table_names = array ('head', 'hhea', 'hmtx', 'maxp', 'cvt ', 'fpgm', 'prep'); // minimum required table names
  1295. // get the tables to preserve
  1296. $offset = 12;
  1297. foreach ($table as $tag => $val) {
  1298. if (in_array($tag, $table_names)) {
  1299. $table[$tag]['data'] = substr($font, $table[$tag]['offset'], $table[$tag]['length']);
  1300. if ($tag == 'head') {
  1301. // set the checkSumAdjustment to 0
  1302. $table[$tag]['data'] = substr($table[$tag]['data'], 0, 8)."\x0\x0\x0\x0".substr($table[$tag]['data'], 12);
  1303. }
  1304. $pad = 4 - ($table[$tag]['length'] % 4);
  1305. if ($pad != 4) {
  1306. // the length of a table must be a multiple of four bytes
  1307. $table[$tag]['length'] += $pad;
  1308. $table[$tag]['data'] .= str_repeat("\x0", $pad);
  1309. }
  1310. $table[$tag]['offset'] = $offset;
  1311. $offset += $table[$tag]['length'];
  1312. // check sum is not changed (so keep the following line commented)
  1313. //$table[$tag]['checkSum'] = self::_getTTFtableChecksum($table[$tag]['data'], $table[$tag]['length']);
  1314. } else {
  1315. unset($table[$tag]);
  1316. }
  1317. }
  1318. // add loca
  1319. $table['loca']['data'] = $loca;
  1320. $table['loca']['length'] = strlen($loca);
  1321. $pad = 4 - ($table['loca']['length'] % 4);
  1322. if ($pad != 4) {
  1323. // the length of a table must be a multiple of four bytes
  1324. $table['loca']['length'] += $pad;
  1325. $table['loca']['data'] .= str_repeat("\x0", $pad);
  1326. }
  1327. $table['loca']['offset'] = $offset;
  1328. $table['loca']['checkSum'] = self::_getTTFtableChecksum($table['loca']['data'], $table['loca']['length']);
  1329. $offset += $table['loca']['length'];
  1330. // add glyf
  1331. $table['glyf']['data'] = $glyf;
  1332. $table['glyf']['length'] = strlen($glyf);
  1333. $pad = 4 - ($table['glyf']['length'] % 4);
  1334. if ($pad != 4) {
  1335. // the length of a table must be a multiple of four bytes
  1336. $table['glyf']['length'] += $pad;
  1337. $table['glyf']['data'] .= str_repeat("\x0", $pad);
  1338. }
  1339. $table['glyf']['offset'] = $offset;
  1340. $table['glyf']['checkSum'] = self::_getTTFtableChecksum($table['glyf']['data'], $table['glyf']['length']);
  1341. // rebuild font
  1342. $font = '';
  1343. $font .= pack('N', 0x10000); // sfnt version
  1344. $numTables = count($table);
  1345. $font .= pack('n', $numTables); // numTables
  1346. $entrySelector = floor(log($numTables, 2));
  1347. $searchRange = pow(2, $entrySelector) * 16;
  1348. $rangeShift = ($numTables * 16) - $searchRange;
  1349. $font .= pack('n', $searchRange); // searchRange
  1350. $font .= pack('n', $entrySelector); // entrySelector
  1351. $font .= pack('n', $rangeShift); // rangeShift
  1352. $offset = ($numTables * 16);
  1353. foreach ($table as $tag => $data) {
  1354. $font .= $tag; // tag
  1355. $font .= pack('N', $data['checkSum']); // checkSum
  1356. $font .= pack('N', ($data['offset'] + $offset)); // offset
  1357. $font .= pack('N', $data['length']); // length
  1358. }
  1359. foreach ($table as $data) {
  1360. $font .= $data['data'];
  1361. }
  1362. // set checkSumAdjustment on head table
  1363. $checkSumAdjustment = 0xB1B0AFBA - self::_getTTFtableChecksum($font, strlen($font));
  1364. $font = substr($font, 0, $table['head']['offset'] + 8).pack('N', $checkSumAdjustment).substr($font, $table['head']['offset'] + 12);
  1365. return $font;
  1366. }
  1367. /**
  1368. * Outputs font widths
  1369. * @param $font (array) font data
  1370. * @param $cidoffset (int) offset for CID values
  1371. * @return PDF command string for font widths
  1372. * @author Nicola Asuni
  1373. * @since 4.4.000 (2008-12-07)
  1374. * @public static
  1375. */
  1376. public static function _putfontwidths($font, $cidoffset=0) {
  1377. ksort($font['cw']);
  1378. $rangeid = 0;
  1379. $range = array();
  1380. $prevcid = -2;
  1381. $prevwidth = -1;
  1382. $interval = false;
  1383. // for each character
  1384. foreach ($font['cw'] as $cid => $width) {
  1385. $cid -= $cidoffset;
  1386. if ($font['subset'] AND (!isset($font['subsetchars'][$cid]))) {
  1387. // ignore the unused characters (font subsetting)
  1388. continue;
  1389. }
  1390. if ($width != $font['dw']) {
  1391. if ($cid == ($prevcid + 1)) {
  1392. // consecutive CID
  1393. if ($width == $prevwidth) {
  1394. if ($width == $range[$rangeid][0]) {
  1395. $range[$rangeid][] = $width;
  1396. } else {
  1397. array_pop($range[$rangeid]);
  1398. // new range
  1399. $rangeid = $prevcid;
  1400. $range[$rangeid] = array();
  1401. $range[$rangeid][] = $prevwidth;
  1402. $range[$rangeid][] = $width;
  1403. }
  1404. $interval = true;
  1405. $range[$rangeid]['interval'] = true;
  1406. } else {
  1407. if ($interval) {
  1408. // new range
  1409. $rangeid = $cid;
  1410. $range[$rangeid] = array();
  1411. $range[$rangeid][] = $width;
  1412. } else {
  1413. $range[$rangeid][] = $width;
  1414. }
  1415. $interval = false;
  1416. }
  1417. } else {
  1418. // new range
  1419. $rangeid = $cid;
  1420. $range[$rangeid] = array();
  1421. $range[$rangeid][] = $width;
  1422. $interval = false;
  1423. }
  1424. $prevcid = $cid;
  1425. $prevwidth = $width;
  1426. }
  1427. }
  1428. // optimize ranges
  1429. $prevk = -1;
  1430. $nextk = -1;
  1431. $prevint = false;
  1432. foreach ($range as $k => $ws) {
  1433. $cws = count($ws);
  1434. if (($k == $nextk) AND (!$prevint) AND ((!isset($ws['interval'])) OR ($cws < 4))) {
  1435. if (isset($range[$k]['interval'])) {
  1436. unset($range[$k]['interval']);
  1437. }
  1438. $range[$prevk] = array_merge($range[$prevk], $range[$k]);
  1439. unset($range[$k]);
  1440. } else {
  1441. $prevk = $k;
  1442. }
  1443. $nextk = $k + $cws;
  1444. if (isset($ws['interval'])) {
  1445. if ($cws > 3) {
  1446. $prevint = true;
  1447. } else {
  1448. $prevint = false;
  1449. }
  1450. if (isset($range[$k]['interval'])) {
  1451. unset($range[$k]['interval']);
  1452. }
  1453. --$nextk;
  1454. } else {
  1455. $prevint = false;
  1456. }
  1457. }
  1458. // output data
  1459. $w = '';
  1460. foreach ($range as $k => $ws) {
  1461. if (count(array_count_values($ws)) == 1) {
  1462. // interval mode is more compact
  1463. $w .= ' '.$k.' '.($k + count($ws) - 1).' '.$ws[0];
  1464. } else {
  1465. // range mode
  1466. $w .= ' '.$k.' [ '.implode(' ', $ws).' ]';
  1467. }
  1468. }
  1469. return '/W ['.$w.' ]';
  1470. }
  1471. /**
  1472. * Returns the unicode caracter specified by the value
  1473. * @param $c (int) UTF-8 value
  1474. * @param $unicode (boolean) True if we are in unicode mode, false otherwise.
  1475. * @return Returns the specified character.
  1476. * @since 2.3.000 (2008-03-05)
  1477. * @public static
  1478. */
  1479. public static function unichr($c, $unicode=true) {
  1480. if (!$unicode) {
  1481. return chr($c);
  1482. } elseif ($c <= 0x7F) {
  1483. // one byte
  1484. return chr($c);
  1485. } elseif ($c <= 0x7FF) {
  1486. // two bytes
  1487. return chr(0xC0 | $c >> 6).chr(0x80 | $c & 0x3F);
  1488. } elseif ($c <= 0xFFFF) {
  1489. // three bytes
  1490. return chr(0xE0 | $c >> 12).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
  1491. } elseif ($c <= 0x10FFFF) {
  1492. // four bytes
  1493. return chr(0xF0 | $c >> 18).chr(0x80 | $c >> 12 & 0x3F).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
  1494. } else {
  1495. return '';
  1496. }
  1497. }
  1498. /**
  1499. * Returns the unicode caracter specified by UTF-8 value
  1500. * @param $c (int) UTF-8 value
  1501. * @return Returns the specified character.
  1502. * @public static
  1503. */
  1504. public static function unichrUnicode($c) {
  1505. return self::unichr($c, true);
  1506. }
  1507. /**
  1508. * Returns the unicode caracter specified by ASCII value
  1509. * @param $c (int) UTF-8 value
  1510. * @return Returns the specified character.
  1511. * @public static
  1512. */
  1513. public static function unichrASCII($c) {
  1514. return self::unichr($c, false);
  1515. }
  1516. /**
  1517. * Converts array of UTF-8 characters to UTF16-BE string.<br>
  1518. * Based on: http://www.faqs.org/rfcs/rfc2781.html
  1519. * <pre>
  1520. * Encoding UTF-16:
  1521. *
  1522. * Encoding of a single character from an ISO 10646 character value to
  1523. * UTF-16 proceeds as follows. Let U be the character number, no greater
  1524. * than 0x10FFFF.
  1525. *
  1526. * 1) If U < 0x10000, encode U as a 16-bit unsigned integer and
  1527. * terminate.
  1528. *
  1529. * 2) Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF,
  1530. * U' must be less than or equal to 0xFFFFF. That is, U' can be
  1531. * represented in 20 bits.
  1532. *
  1533. * 3) Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and
  1534. * 0xDC00, respectively. These integers each have 10 bits free to
  1535. * encode the character value, for a total of 20 bits.
  1536. *
  1537. * 4) Assign the 10 high-order bits of the 20-bit U' to the 10 low-order
  1538. * bits of W1 and the 10 low-order bits of U' to the 10 low-order
  1539. * bits of W2. Terminate.
  1540. *
  1541. * Graphically, steps 2 through 4 look like:
  1542. * U' = yyyyyyyyyyxxxxxxxxxx
  1543. * W1 = 110110yyyyyyyyyy
  1544. * W2 = 110111xxxxxxxxxx
  1545. * </pre>
  1546. * @param $unicode (array) array containing UTF-8 unicode values
  1547. * @param $setbom (boolean) if true set the Byte Order Mark (BOM = 0xFEFF)
  1548. * @return string
  1549. * @protected
  1550. * @author Nicola Asuni
  1551. * @since 2.1.000 (2008-01-08)
  1552. * @public static
  1553. */
  1554. public static function arrUTF8ToUTF16BE($unicode, $setbom=false) {
  1555. $outstr = ''; // string to be returned
  1556. if ($setbom) {
  1557. $outstr .= "\xFE\xFF"; // Byte Order Mark (BOM)
  1558. }
  1559. foreach ($unicode as $char) {
  1560. if ($char == 0x200b) {
  1561. // skip Unicode Character 'ZERO WIDTH SPACE' (DEC:8203, U+200B)
  1562. } elseif ($char == 0xFFFD) {
  1563. $outstr .= "\xFF\xFD"; // replacement character
  1564. } elseif ($char < 0x10000) {
  1565. $outstr .= chr($char >> 0x08);
  1566. $outstr .= chr($char & 0xFF);
  1567. } else {
  1568. $char -= 0x10000;
  1569. $w1 = 0xD800 | ($char >> 0x0a);
  1570. $w2 = 0xDC00 | ($char & 0x3FF);
  1571. $outstr .= chr($w1 >> 0x08);
  1572. $outstr .= chr($w1 & 0xFF);
  1573. $outstr .= chr($w2 >> 0x08);
  1574. $outstr .= chr($w2 & 0xFF);
  1575. }
  1576. }
  1577. return $outstr;
  1578. }
  1579. /**
  1580. * Convert an array of UTF8 values to array of unicode characters
  1581. * @param $ta (array) The input array of UTF8 values.
  1582. * @param $isunicode (boolean) True for Unicode mode, false otherwise.
  1583. * @return Return array of unicode characters
  1584. * @since 4.5.037 (2009-04-07)
  1585. * @public static
  1586. */
  1587. public static function UTF8ArrayToUniArray($ta, $isunicode=true) {
  1588. if ($isunicode) {
  1589. return array_map(array('self', 'unichrUnicode'), $ta);
  1590. }
  1591. return array_map(array('self', 'unichrASCII'), $ta);
  1592. }
  1593. /**
  1594. * Extract a slice of the $strarr array and return it as string.
  1595. * @param $strarr (string) The input array of characters.
  1596. * @param $start (int) the starting element of $strarr.
  1597. * @param $end (int) first element that will not be returned.
  1598. * @param $unicode (boolean) True if we are in unicode mode, false otherwise.
  1599. * @return Return part of a string
  1600. * @public static
  1601. */
  1602. public static function UTF8ArrSubString($strarr, $start='', $end='', $unicode=true) {
  1603. if (strlen($start) == 0) {
  1604. $start = 0;
  1605. }
  1606. if (strlen($end) == 0) {
  1607. $end = count($strarr);
  1608. }
  1609. $string = '';
  1610. for ($i = $start; $i < $end; ++$i) {
  1611. $string .= self::unichr($strarr[$i], $unicode);
  1612. }
  1613. return $string;
  1614. }
  1615. /**
  1616. * Extract a slice of the $uniarr array and return it as string.
  1617. * @param $uniarr (string) The input array of characters.
  1618. * @param $start (int) the starting element of $strarr.
  1619. * @param $end (int) first element that will not be returned.
  1620. * @return Return part of a string
  1621. * @since 4.5.037 (2009-04-07)
  1622. * @public static
  1623. */
  1624. public static function UniArrSubString($uniarr, $start='', $end='') {
  1625. if (strlen($start) == 0) {
  1626. $start = 0;
  1627. }
  1628. if (strlen($end) == 0) {
  1629. $end = count($uniarr);
  1630. }
  1631. $string = '';
  1632. for ($i=$start; $i < $end; ++$i) {
  1633. $string .= $uniarr[$i];
  1634. }
  1635. return $string;
  1636. }
  1637. /**
  1638. * Update the CIDToGIDMap string with a new value.
  1639. * @param $map (string) CIDToGIDMap.
  1640. * @param $cid (int) CID value.
  1641. * @param $gid (int) GID value.
  1642. * @return (string) CIDToGIDMap.
  1643. * @author Nicola Asuni
  1644. * @since 5.9.123 (2011-09-29)
  1645. * @public static
  1646. */
  1647. public static function updateCIDtoGIDmap($map, $cid, $gid) {
  1648. if (($cid >= 0) AND ($cid <= 0xFFFF) AND ($gid >= 0)) {
  1649. if ($gid > 0xFFFF) {
  1650. $gid -= 0x10000;
  1651. }
  1652. $map[($cid * 2)] = chr($gid >> 8);
  1653. $map[(($cid * 2) + 1)] = chr($gid & 0xFF);
  1654. }
  1655. return $map;
  1656. }
  1657. /**
  1658. * Return fonts path
  1659. * @return string
  1660. * @public static
  1661. */
  1662. public static function _getfontpath() {
  1663. if (!defined('K_PATH_FONTS') AND is_dir($fdir = realpath(dirname(__FILE__).'/../fonts'))) {
  1664. if (substr($fdir, -1) != '/') {
  1665. $fdir .= '/';
  1666. }
  1667. define('K_PATH_FONTS', $fdir);
  1668. }
  1669. return defined('K_PATH_FONTS') ? K_PATH_FONTS : '';
  1670. }
  1671. /**
  1672. * Return font full path
  1673. * @param $file (string) Font file name.
  1674. * @param $fontdir (string) Font directory (set to false fto search on default directories)
  1675. * @return string Font full path or empty string
  1676. * @author Nicola Asuni
  1677. * @since 6.0.025
  1678. * @public static
  1679. */
  1680. public static function getFontFullPath($file, $fontdir=false) {
  1681. $fontfile = '';
  1682. // search files on various directories
  1683. if (($fontdir !== false) AND @file_exists($fontdir.$file)) {
  1684. $fontfile = $fontdir.$file;
  1685. } elseif (@file_exists(self::_getfontpath().$file)) {
  1686. $fontfile = self::_getfontpath().$file;
  1687. } elseif (@file_exists($file)) {
  1688. $fontfile = $file;
  1689. }
  1690. return $fontfile;
  1691. }
  1692. /**
  1693. * Converts UTF-8 characters array to array of Latin1 characters array<br>
  1694. * @param $unicode (array) array containing UTF-8 unicode values
  1695. * @return array
  1696. * @author Nicola Asuni
  1697. * @since 4.8.023 (2010-01-15)
  1698. * @public static
  1699. */
  1700. public static function UTF8ArrToLatin1Arr($unicode) {
  1701. $outarr = array(); // array to be returned
  1702. foreach ($unicode as $char) {
  1703. if ($char < 256) {
  1704. $outarr[] = $char;
  1705. } elseif (array_key_exists($char, TCPDF_FONT_DATA::$uni_utf8tolatin)) {
  1706. // map from UTF-8
  1707. $outarr[] = TCPDF_FONT_DATA::$uni_utf8tolatin[$char];
  1708. } elseif ($char == 0xFFFD) {
  1709. // skip
  1710. } else {
  1711. $outarr[] = 63; // '?' character
  1712. }
  1713. }
  1714. return $outarr;
  1715. }
  1716. /**
  1717. * Converts UTF-8 characters array to array of Latin1 string<br>
  1718. * @param $unicode (array) array containing UTF-8 unicode values
  1719. * @return array
  1720. * @author Nicola Asuni
  1721. * @since 4.8.023 (2010-01-15)
  1722. * @public static
  1723. */
  1724. public static function UTF8ArrToLatin1($unicode) {
  1725. $outstr = ''; // string to be returned
  1726. foreach ($unicode as $char) {
  1727. if ($char < 256) {
  1728. $outstr .= chr($char);
  1729. } elseif (array_key_exists($char, TCPDF_FONT_DATA::$uni_utf8tolatin)) {
  1730. // map from UTF-8
  1731. $outstr .= chr(TCPDF_FONT_DATA::$uni_utf8tolatin[$char]);
  1732. } elseif ($char == 0xFFFD) {
  1733. // skip
  1734. } else {
  1735. $outstr .= '?';
  1736. }
  1737. }
  1738. return $outstr;
  1739. }
  1740. /**
  1741. * Converts UTF-8 character to integer value.<br>
  1742. * Invalid byte sequences will be replaced with 0xFFFD (replacement character)<br>
  1743. * Based on: http://www.faqs.org/rfcs/rfc3629.html
  1744. * <pre>
  1745. * Char. number range | UTF-8 octet sequence
  1746. * (hexadecimal) | (binary)
  1747. * --------------------+-----------------------------------------------
  1748. * 0000 0000-0000 007F | 0xxxxxxx
  1749. * 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
  1750. * 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
  1751. * 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  1752. * ---------------------------------------------------------------------
  1753. *
  1754. * ABFN notation:
  1755. * ---------------------------------------------------------------------
  1756. * UTF8-octets = *( UTF8-char )
  1757. * UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
  1758. * UTF8-1 = %x00-7F
  1759. * UTF8-2 = %xC2-DF UTF8-tail
  1760. *
  1761. * UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
  1762. * %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
  1763. * UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
  1764. * %xF4 %x80-8F 2( UTF8-tail )
  1765. * UTF8-tail = %x80-BF
  1766. * ---------------------------------------------------------------------
  1767. * </pre>
  1768. * @param $uch (string) character string to process.
  1769. * @return integer Unicode value
  1770. * @author Nicola Asuni
  1771. * @public static
  1772. */
  1773. public static function uniord($uch) {
  1774. if (function_exists('mb_convert_encoding')) {
  1775. list(, $char) = @unpack('N', mb_convert_encoding($uch, 'UCS-4BE', 'UTF-8'));
  1776. if ($char >= 0) {
  1777. return $char;
  1778. }
  1779. }
  1780. $bytes = array(); // array containing single character byte sequences
  1781. $countbytes = 0;
  1782. $numbytes = 1; // number of octetc needed to represent the UTF-8 character
  1783. $length = strlen($uch);
  1784. for ($i = 0; $i < $length; ++$i) {
  1785. $char = ord($uch[$i]); // get one string character at time
  1786. if ($countbytes == 0) { // get starting octect
  1787. if ($char <= 0x7F) {
  1788. return $char; // use the character "as is" because is ASCII
  1789. } elseif (($char >> 0x05) == 0x06) { // 2 bytes character (0x06 = 110 BIN)
  1790. $bytes[] = ($char - 0xC0) << 0x06;
  1791. ++$countbytes;
  1792. $numbytes = 2;
  1793. } elseif (($char >> 0x04) == 0x0E) { // 3 bytes character (0x0E = 1110 BIN)
  1794. $bytes[] = ($char - 0xE0) << 0x0C;
  1795. ++$countbytes;
  1796. $numbytes = 3;
  1797. } elseif (($char >> 0x03) == 0x1E) { // 4 bytes character (0x1E = 11110 BIN)
  1798. $bytes[] = ($char - 0xF0) << 0x12;
  1799. ++$countbytes;
  1800. $numbytes = 4;
  1801. } else {
  1802. // use replacement character for other invalid sequences
  1803. return 0xFFFD;
  1804. }
  1805. } elseif (($char >> 0x06) == 0x02) { // bytes 2, 3 and 4 must start with 0x02 = 10 BIN
  1806. $bytes[] = $char - 0x80;
  1807. ++$countbytes;
  1808. if ($countbytes == $numbytes) {
  1809. // compose UTF-8 bytes to a single unicode value
  1810. $char = $bytes[0];
  1811. for ($j = 1; $j < $numbytes; ++$j) {
  1812. $char += ($bytes[$j] << (($numbytes - $j - 1) * 0x06));
  1813. }
  1814. if ((($char >= 0xD800) AND ($char <= 0xDFFF)) OR ($char >= 0x10FFFF)) {
  1815. // The definition of UTF-8 prohibits encoding character numbers between
  1816. // U+D800 and U+DFFF, which are reserved for use with the UTF-16
  1817. // encoding form (as surrogate pairs) and do not directly represent
  1818. // characters.
  1819. return 0xFFFD; // use replacement character
  1820. } else {
  1821. return $char;
  1822. }
  1823. }
  1824. } else {
  1825. // use replacement character for other invalid sequences
  1826. return 0xFFFD;
  1827. }
  1828. }
  1829. return 0xFFFD;
  1830. }
  1831. /**
  1832. * Converts UTF-8 strings to codepoints array.<br>
  1833. * Invalid byte sequences will be replaced with 0xFFFD (replacement character)<br>
  1834. * @param $str (string) string to process.
  1835. * @param $isunicode (boolean) True when the documetn is in Unicode mode, false otherwise.
  1836. * @param $currentfont (array) Reference to current font array.
  1837. * @return array containing codepoints (UTF-8 characters values)
  1838. * @author Nicola Asuni
  1839. * @public static
  1840. */
  1841. public static function UTF8StringToArray($str, $isunicode=true, &$currentfont) {
  1842. if ($isunicode) {
  1843. // requires PCRE unicode support turned on
  1844. $chars = TCPDF_STATIC::pregSplit('//','u', $str, -1, PREG_SPLIT_NO_EMPTY);
  1845. $carr = array_map(array('self', 'uniord'), $chars);
  1846. } else {
  1847. $chars = str_split($str);
  1848. $carr = array_map('ord', $chars);
  1849. }
  1850. $currentfont['subsetchars'] += array_fill_keys($carr, true);
  1851. return $carr;
  1852. }
  1853. /**
  1854. * Converts UTF-8 strings to Latin1 when using the standard 14 core fonts.<br>
  1855. * @param $str (string) string to process.
  1856. * @param $isunicode (boolean) True when the documetn is in Unicode mode, false otherwise.
  1857. * @param $currentfont (array) Reference to current font array.
  1858. * @return string
  1859. * @since 3.2.000 (2008-06-23)
  1860. * @public static
  1861. */
  1862. public static function UTF8ToLatin1($str, $isunicode=true, &$currentfont) {
  1863. $unicode = self::UTF8StringToArray($str, $isunicode, $currentfont); // array containing UTF-8 unicode values
  1864. return self::UTF8ArrToLatin1($unicode);
  1865. }
  1866. /**
  1867. * Converts UTF-8 strings to UTF16-BE.<br>
  1868. * @param $str (string) string to process.
  1869. * @param $setbom (boolean) if true set the Byte Order Mark (BOM = 0xFEFF)
  1870. * @param $isunicode (boolean) True when the documetn is in Unicode mode, false otherwise.
  1871. * @param $currentfont (array) Reference to current font array.
  1872. * @return string
  1873. * @author Nicola Asuni
  1874. * @since 1.53.0.TC005 (2005-01-05)
  1875. * @public static
  1876. */
  1877. public static function UTF8ToUTF16BE($str, $setbom=false, $isunicode=true, &$currentfont) {
  1878. if (!$isunicode) {
  1879. return $str; // string is not in unicode
  1880. }
  1881. $unicode = self::UTF8StringToArray($str, $isunicode, $currentfont); // array containing UTF-8 unicode values
  1882. return self::arrUTF8ToUTF16BE($unicode, $setbom);
  1883. }
  1884. /**
  1885. * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
  1886. * @param $str (string) string to manipulate.
  1887. * @param $setbom (bool) if true set the Byte Order Mark (BOM = 0xFEFF)
  1888. * @param $forcertl (bool) if true forces RTL text direction
  1889. * @param $isunicode (boolean) True if the document is in Unicode mode, false otherwise.
  1890. * @param $currentfont (array) Reference to current font array.
  1891. * @return string
  1892. * @author Nicola Asuni
  1893. * @since 2.1.000 (2008-01-08)
  1894. * @public static
  1895. */
  1896. public static function utf8StrRev($str, $setbom=false, $forcertl=false, $isunicode=true, &$currentfont) {
  1897. return self::utf8StrArrRev(self::UTF8StringToArray($str, $isunicode, $currentfont), $str, $setbom, $forcertl, $isunicode, $currentfont);
  1898. }
  1899. /**
  1900. * Reverse the RLT substrings array using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
  1901. * @param $arr (array) array of unicode values.
  1902. * @param $str (string) string to manipulate (or empty value).
  1903. * @param $setbom (bool) if true set the Byte Order Mark (BOM = 0xFEFF)
  1904. * @param $forcertl (bool) if true forces RTL text direction
  1905. * @param $isunicode (boolean) True if the document is in Unicode mode, false otherwise.
  1906. * @param $currentfont (array) Reference to current font array.
  1907. * @return string
  1908. * @author Nicola Asuni
  1909. * @since 4.9.000 (2010-03-27)
  1910. * @public static
  1911. */
  1912. public static function utf8StrArrRev($arr, $str='', $setbom=false, $forcertl=false, $isunicode=true, &$currentfont) {
  1913. return self::arrUTF8ToUTF16BE(self::utf8Bidi($arr, $str, $forcertl, $isunicode, $currentfont), $setbom);
  1914. }
  1915. /**
  1916. * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
  1917. * @param $ta (array) array of characters composing the string.
  1918. * @param $str (string) string to process
  1919. * @param $forcertl (bool) if 'R' forces RTL, if 'L' forces LTR
  1920. * @param $isunicode (boolean) True if the document is in Unicode mode, false otherwise.
  1921. * @param $currentfont (array) Reference to current font array.
  1922. * @return array of unicode chars
  1923. * @author Nicola Asuni
  1924. * @since 2.4.000 (2008-03-06)
  1925. * @public static
  1926. */
  1927. public static function utf8Bidi($ta, $str='', $forcertl=false, $isunicode=true, &$currentfont) {
  1928. // paragraph embedding level
  1929. $pel = 0;
  1930. // max level
  1931. $maxlevel = 0;
  1932. if (TCPDF_STATIC::empty_string($str)) {
  1933. // create string from array
  1934. $str = self::UTF8ArrSubString($ta, '', '', $isunicode);
  1935. }
  1936. // check if string contains arabic text
  1937. if (preg_match(TCPDF_FONT_DATA::$uni_RE_PATTERN_ARABIC, $str)) {
  1938. $arabic = true;
  1939. } else {
  1940. $arabic = false;
  1941. }
  1942. // check if string contains RTL text
  1943. if (!($forcertl OR $arabic OR preg_match(TCPDF_FONT_DATA::$uni_RE_PATTERN_RTL, $str))) {
  1944. return $ta;
  1945. }
  1946. // get number of chars
  1947. $numchars = count($ta);
  1948. if ($forcertl == 'R') {
  1949. $pel = 1;
  1950. } elseif ($forcertl == 'L') {
  1951. $pel = 0;
  1952. } else {
  1953. // P2. In each paragraph, find the first character of type L, AL, or R.
  1954. // P3. If a character is found in P2 and it is of type AL or R, then set the paragraph embedding level to one; otherwise, set it to zero.
  1955. for ($i=0; $i < $numchars; ++$i) {
  1956. $type = TCPDF_FONT_DATA::$uni_type[$ta[$i]];
  1957. if ($type == 'L') {
  1958. $pel = 0;
  1959. break;
  1960. } elseif (($type == 'AL') OR ($type == 'R')) {
  1961. $pel = 1;
  1962. break;
  1963. }
  1964. }
  1965. }
  1966. // Current Embedding Level
  1967. $cel = $pel;
  1968. // directional override status
  1969. $dos = 'N';
  1970. $remember = array();
  1971. // start-of-level-run
  1972. $sor = $pel % 2 ? 'R' : 'L';
  1973. $eor = $sor;
  1974. // Array of characters data
  1975. $chardata = Array();
  1976. // X1. Begin by setting the current embedding level to the paragraph embedding level. Set the directional override status to neutral. Process each character iteratively, applying rules X2 through X9. Only embedding levels from 0 to 61 are valid in this phase.
  1977. // In the resolution of levels in rules I1 and I2, the maximum embedding level of 62 can be reached.
  1978. for ($i=0; $i < $numchars; ++$i) {
  1979. if ($ta[$i] == TCPDF_FONT_DATA::$uni_RLE) {
  1980. // X2. With each RLE, compute the least greater odd embedding level.
  1981. // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to neutral.
  1982. // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
  1983. $next_level = $cel + ($cel % 2) + 1;
  1984. if ($next_level < 62) {
  1985. $remember[] = array('num' => TCPDF_FONT_DATA::$uni_RLE, 'cel' => $cel, 'dos' => $dos);
  1986. $cel = $next_level;
  1987. $dos = 'N';
  1988. $sor = $eor;
  1989. $eor = $cel % 2 ? 'R' : 'L';
  1990. }
  1991. } elseif ($ta[$i] == TCPDF_FONT_DATA::$uni_LRE) {
  1992. // X3. With each LRE, compute the least greater even embedding level.
  1993. // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to neutral.
  1994. // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
  1995. $next_level = $cel + 2 - ($cel % 2);
  1996. if ( $next_level < 62 ) {
  1997. $remember[] = array('num' => TCPDF_FONT_DATA::$uni_LRE, 'cel' => $cel, 'dos' => $dos);
  1998. $cel = $next_level;
  1999. $dos = 'N';
  2000. $sor = $eor;
  2001. $eor = $cel % 2 ? 'R' : 'L';
  2002. }
  2003. } elseif ($ta[$i] == TCPDF_FONT_DATA::$uni_RLO) {
  2004. // X4. With each RLO, compute the least greater odd embedding level.
  2005. // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to right-to-left.
  2006. // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
  2007. $next_level = $cel + ($cel % 2) + 1;
  2008. if ($next_level < 62) {
  2009. $remember[] = array('num' => TCPDF_FONT_DATA::$uni_RLO, 'cel' => $cel, 'dos' => $dos);
  2010. $cel = $next_level;
  2011. $dos = 'R';
  2012. $sor = $eor;
  2013. $eor = $cel % 2 ? 'R' : 'L';
  2014. }
  2015. } elseif ($ta[$i] == TCPDF_FONT_DATA::$uni_LRO) {
  2016. // X5. With each LRO, compute the least greater even embedding level.
  2017. // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to left-to-right.
  2018. // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
  2019. $next_level = $cel + 2 - ($cel % 2);
  2020. if ( $next_level < 62 ) {
  2021. $remember[] = array('num' => TCPDF_FONT_DATA::$uni_LRO, 'cel' => $cel, 'dos' => $dos);
  2022. $cel = $next_level;
  2023. $dos = 'L';
  2024. $sor = $eor;
  2025. $eor = $cel % 2 ? 'R' : 'L';
  2026. }
  2027. } elseif ($ta[$i] == TCPDF_FONT_DATA::$uni_PDF) {
  2028. // X7. With each PDF, determine the matching embedding or override code. If there was a valid matching code, restore (pop) the last remembered (pushed) embedding level and directional override.
  2029. if (count($remember)) {
  2030. $last = count($remember ) - 1;
  2031. if (($remember[$last]['num'] == TCPDF_FONT_DATA::$uni_RLE) OR
  2032. ($remember[$last]['num'] == TCPDF_FONT_DATA::$uni_LRE) OR
  2033. ($remember[$last]['num'] == TCPDF_FONT_DATA::$uni_RLO) OR
  2034. ($remember[$last]['num'] == TCPDF_FONT_DATA::$uni_LRO)) {
  2035. $match = array_pop($remember);
  2036. $cel = $match['cel'];
  2037. $dos = $match['dos'];
  2038. $sor = $eor;
  2039. $eor = ($cel > $match['cel'] ? $cel : $match['cel']) % 2 ? 'R' : 'L';
  2040. }
  2041. }
  2042. } elseif (($ta[$i] != TCPDF_FONT_DATA::$uni_RLE) AND
  2043. ($ta[$i] != TCPDF_FONT_DATA::$uni_LRE) AND
  2044. ($ta[$i] != TCPDF_FONT_DATA::$uni_RLO) AND
  2045. ($ta[$i] != TCPDF_FONT_DATA::$uni_LRO) AND
  2046. ($ta[$i] != TCPDF_FONT_DATA::$uni_PDF)) {
  2047. // X6. For all types besides RLE, LRE, RLO, LRO, and PDF:
  2048. // a. Set the level of the current character to the current embedding level.
  2049. // b. Whenever the directional override status is not neutral, reset the current character type to the directional override status.
  2050. if ($dos != 'N') {
  2051. $chardir = $dos;
  2052. } else {
  2053. if (isset(TCPDF_FONT_DATA::$uni_type[$ta[$i]])) {
  2054. $chardir = TCPDF_FONT_DATA::$uni_type[$ta[$i]];
  2055. } else {
  2056. $chardir = 'L';
  2057. }
  2058. }
  2059. // stores string characters and other information
  2060. $chardata[] = array('char' => $ta[$i], 'level' => $cel, 'type' => $chardir, 'sor' => $sor, 'eor' => $eor);
  2061. }
  2062. } // end for each char
  2063. // X8. All explicit directional embeddings and overrides are completely terminated at the end of each paragraph. Paragraph separators are not included in the embedding.
  2064. // X9. Remove all RLE, LRE, RLO, LRO, PDF, and BN codes.
  2065. // X10. The remaining rules are applied to each run of characters at the same level. For each run, determine the start-of-level-run (sor) and end-of-level-run (eor) type, either L or R. This depends on the higher of the two levels on either side of the boundary (at the start or end of the paragraph, the level of the 'other' run is the base embedding level). If the higher level is odd, the type is R; otherwise, it is L.
  2066. // 3.3.3 Resolving Weak Types
  2067. // Weak types are now resolved one level run at a time. At level run boundaries where the type of the character on the other side of the boundary is required, the type assigned to sor or eor is used.
  2068. // Nonspacing marks are now resolved based on the previous characters.
  2069. $numchars = count($chardata);
  2070. // W1. Examine each nonspacing mark (NSM) in the level run, and change the type of the NSM to the type of the previous character. If the NSM is at the start of the level run, it will get the type of sor.
  2071. $prevlevel = -1; // track level changes
  2072. $levcount = 0; // counts consecutive chars at the same level
  2073. for ($i=0; $i < $numchars; ++$i) {
  2074. if ($chardata[$i]['type'] == 'NSM') {
  2075. if ($levcount) {
  2076. $chardata[$i]['type'] = $chardata[$i]['sor'];
  2077. } elseif ($i > 0) {
  2078. $chardata[$i]['type'] = $chardata[($i-1)]['type'];
  2079. }
  2080. }
  2081. if ($chardata[$i]['level'] != $prevlevel) {
  2082. $levcount = 0;
  2083. } else {
  2084. ++$levcount;
  2085. }
  2086. $prevlevel = $chardata[$i]['level'];
  2087. }
  2088. // W2. Search backward from each instance of a European number until the first strong type (R, L, AL, or sor) is found. If an AL is found, change the type of the European number to Arabic number.
  2089. $prevlevel = -1;
  2090. $levcount = 0;
  2091. for ($i=0; $i < $numchars; ++$i) {
  2092. if ($chardata[$i]['char'] == 'EN') {
  2093. for ($j=$levcount; $j >= 0; $j--) {
  2094. if ($chardata[$j]['type'] == 'AL') {
  2095. $chardata[$i]['type'] = 'AN';
  2096. } elseif (($chardata[$j]['type'] == 'L') OR ($chardata[$j]['type'] == 'R')) {
  2097. break;
  2098. }
  2099. }
  2100. }
  2101. if ($chardata[$i]['level'] != $prevlevel) {
  2102. $levcount = 0;
  2103. } else {
  2104. ++$levcount;
  2105. }
  2106. $prevlevel = $chardata[$i]['level'];
  2107. }
  2108. // W3. Change all ALs to R.
  2109. for ($i=0; $i < $numchars; ++$i) {
  2110. if ($chardata[$i]['type'] == 'AL') {
  2111. $chardata[$i]['type'] = 'R';
  2112. }
  2113. }
  2114. // W4. A single European separator between two European numbers changes to a European number. A single common separator between two numbers of the same type changes to that type.
  2115. $prevlevel = -1;
  2116. $levcount = 0;
  2117. for ($i=0; $i < $numchars; ++$i) {
  2118. if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
  2119. if (($chardata[$i]['type'] == 'ES') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
  2120. $chardata[$i]['type'] = 'EN';
  2121. } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
  2122. $chardata[$i]['type'] = 'EN';
  2123. } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'AN') AND ($chardata[($i+1)]['type'] == 'AN')) {
  2124. $chardata[$i]['type'] = 'AN';
  2125. }
  2126. }
  2127. if ($chardata[$i]['level'] != $prevlevel) {
  2128. $levcount = 0;
  2129. } else {
  2130. ++$levcount;
  2131. }
  2132. $prevlevel = $chardata[$i]['level'];
  2133. }
  2134. // W5. A sequence of European terminators adjacent to European numbers changes to all European numbers.
  2135. $prevlevel = -1;
  2136. $levcount = 0;
  2137. for ($i=0; $i < $numchars; ++$i) {
  2138. if ($chardata[$i]['type'] == 'ET') {
  2139. if (($levcount > 0) AND ($chardata[($i-1)]['type'] == 'EN')) {
  2140. $chardata[$i]['type'] = 'EN';
  2141. } else {
  2142. $j = $i+1;
  2143. while (($j < $numchars) AND ($chardata[$j]['level'] == $prevlevel)) {
  2144. if ($chardata[$j]['type'] == 'EN') {
  2145. $chardata[$i]['type'] = 'EN';
  2146. break;
  2147. } elseif ($chardata[$j]['type'] != 'ET') {
  2148. break;
  2149. }
  2150. ++$j;
  2151. }
  2152. }
  2153. }
  2154. if ($chardata[$i]['level'] != $prevlevel) {
  2155. $levcount = 0;
  2156. } else {
  2157. ++$levcount;
  2158. }
  2159. $prevlevel = $chardata[$i]['level'];
  2160. }
  2161. // W6. Otherwise, separators and terminators change to Other Neutral.
  2162. $prevlevel = -1;
  2163. $levcount = 0;
  2164. for ($i=0; $i < $numchars; ++$i) {
  2165. if (($chardata[$i]['type'] == 'ET') OR ($chardata[$i]['type'] == 'ES') OR ($chardata[$i]['type'] == 'CS')) {
  2166. $chardata[$i]['type'] = 'ON';
  2167. }
  2168. if ($chardata[$i]['level'] != $prevlevel) {
  2169. $levcount = 0;
  2170. } else {
  2171. ++$levcount;
  2172. }
  2173. $prevlevel = $chardata[$i]['level'];
  2174. }
  2175. //W7. Search backward from each instance of a European number until the first strong type (R, L, or sor) is found. If an L is found, then change the type of the European number to L.
  2176. $prevlevel = -1;
  2177. $levcount = 0;
  2178. for ($i=0; $i < $numchars; ++$i) {
  2179. if ($chardata[$i]['char'] == 'EN') {
  2180. for ($j=$levcount; $j >= 0; $j--) {
  2181. if ($chardata[$j]['type'] == 'L') {
  2182. $chardata[$i]['type'] = 'L';
  2183. } elseif ($chardata[$j]['type'] == 'R') {
  2184. break;
  2185. }
  2186. }
  2187. }
  2188. if ($chardata[$i]['level'] != $prevlevel) {
  2189. $levcount = 0;
  2190. } else {
  2191. ++$levcount;
  2192. }
  2193. $prevlevel = $chardata[$i]['level'];
  2194. }
  2195. // N1. A sequence of neutrals takes the direction of the surrounding strong text if the text on both sides has the same direction. European and Arabic numbers act as if they were R in terms of their influence on neutrals. Start-of-level-run (sor) and end-of-level-run (eor) are used at level run boundaries.
  2196. $prevlevel = -1;
  2197. $levcount = 0;
  2198. for ($i=0; $i < $numchars; ++$i) {
  2199. if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
  2200. if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
  2201. $chardata[$i]['type'] = 'L';
  2202. } elseif (($chardata[$i]['type'] == 'N') AND
  2203. (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
  2204. (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
  2205. $chardata[$i]['type'] = 'R';
  2206. } elseif ($chardata[$i]['type'] == 'N') {
  2207. // N2. Any remaining neutrals take the embedding direction
  2208. $chardata[$i]['type'] = $chardata[$i]['sor'];
  2209. }
  2210. } elseif (($levcount == 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
  2211. // first char
  2212. if (($chardata[$i]['type'] == 'N') AND ($chardata[$i]['sor'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
  2213. $chardata[$i]['type'] = 'L';
  2214. } elseif (($chardata[$i]['type'] == 'N') AND
  2215. (($chardata[$i]['sor'] == 'R') OR ($chardata[$i]['sor'] == 'EN') OR ($chardata[$i]['sor'] == 'AN')) AND
  2216. (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
  2217. $chardata[$i]['type'] = 'R';
  2218. } elseif ($chardata[$i]['type'] == 'N') {
  2219. // N2. Any remaining neutrals take the embedding direction
  2220. $chardata[$i]['type'] = $chardata[$i]['sor'];
  2221. }
  2222. } elseif (($levcount > 0) AND ((($i+1) == $numchars) OR (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] != $prevlevel))) {
  2223. //last char
  2224. if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[$i]['eor'] == 'L')) {
  2225. $chardata[$i]['type'] = 'L';
  2226. } elseif (($chardata[$i]['type'] == 'N') AND
  2227. (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
  2228. (($chardata[$i]['eor'] == 'R') OR ($chardata[$i]['eor'] == 'EN') OR ($chardata[$i]['eor'] == 'AN'))) {
  2229. $chardata[$i]['type'] = 'R';
  2230. } elseif ($chardata[$i]['type'] == 'N') {
  2231. // N2. Any remaining neutrals take the embedding direction
  2232. $chardata[$i]['type'] = $chardata[$i]['sor'];
  2233. }
  2234. } elseif ($chardata[$i]['type'] == 'N') {
  2235. // N2. Any remaining neutrals take the embedding direction
  2236. $chardata[$i]['type'] = $chardata[$i]['sor'];
  2237. }
  2238. if ($chardata[$i]['level'] != $prevlevel) {
  2239. $levcount = 0;
  2240. } else {
  2241. ++$levcount;
  2242. }
  2243. $prevlevel = $chardata[$i]['level'];
  2244. }
  2245. // I1. For all characters with an even (left-to-right) embedding direction, those of type R go up one level and those of type AN or EN go up two levels.
  2246. // I2. For all characters with an odd (right-to-left) embedding direction, those of type L, EN or AN go up one level.
  2247. for ($i=0; $i < $numchars; ++$i) {
  2248. $odd = $chardata[$i]['level'] % 2;
  2249. if ($odd) {
  2250. if (($chardata[$i]['type'] == 'L') OR ($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')) {
  2251. $chardata[$i]['level'] += 1;
  2252. }
  2253. } else {
  2254. if ($chardata[$i]['type'] == 'R') {
  2255. $chardata[$i]['level'] += 1;
  2256. } elseif (($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')) {
  2257. $chardata[$i]['level'] += 2;
  2258. }
  2259. }
  2260. $maxlevel = max($chardata[$i]['level'],$maxlevel);
  2261. }
  2262. // L1. On each line, reset the embedding level of the following characters to the paragraph embedding level:
  2263. // 1. Segment separators,
  2264. // 2. Paragraph separators,
  2265. // 3. Any sequence of whitespace characters preceding a segment separator or paragraph separator, and
  2266. // 4. Any sequence of white space characters at the end of the line.
  2267. for ($i=0; $i < $numchars; ++$i) {
  2268. if (($chardata[$i]['type'] == 'B') OR ($chardata[$i]['type'] == 'S')) {
  2269. $chardata[$i]['level'] = $pel;
  2270. } elseif ($chardata[$i]['type'] == 'WS') {
  2271. $j = $i+1;
  2272. while ($j < $numchars) {
  2273. if ((($chardata[$j]['type'] == 'B') OR ($chardata[$j]['type'] == 'S')) OR
  2274. (($j == ($numchars-1)) AND ($chardata[$j]['type'] == 'WS'))) {
  2275. $chardata[$i]['level'] = $pel;
  2276. break;
  2277. } elseif ($chardata[$j]['type'] != 'WS') {
  2278. break;
  2279. }
  2280. ++$j;
  2281. }
  2282. }
  2283. }
  2284. // Arabic Shaping
  2285. // Cursively connected scripts, such as Arabic or Syriac, require the selection of positional character shapes that depend on adjacent characters. Shaping is logically applied after the Bidirectional Algorithm is used and is limited to characters within the same directional run.
  2286. if ($arabic) {
  2287. $endedletter = array(1569,1570,1571,1572,1573,1575,1577,1583,1584,1585,1586,1608,1688);
  2288. $alfletter = array(1570,1571,1573,1575);
  2289. $chardata2 = $chardata;
  2290. $laaletter = false;
  2291. $charAL = array();
  2292. $x = 0;
  2293. for ($i=0; $i < $numchars; ++$i) {
  2294. if ((TCPDF_FONT_DATA::$uni_type[$chardata[$i]['char']] == 'AL') OR ($chardata[$i]['char'] == 32) OR ($chardata[$i]['char'] == 8204)) {
  2295. $charAL[$x] = $chardata[$i];
  2296. $charAL[$x]['i'] = $i;
  2297. $chardata[$i]['x'] = $x;
  2298. ++$x;
  2299. }
  2300. }
  2301. $numAL = $x;
  2302. for ($i=0; $i < $numchars; ++$i) {
  2303. $thischar = $chardata[$i];
  2304. if ($i > 0) {
  2305. $prevchar = $chardata[($i-1)];
  2306. } else {
  2307. $prevchar = false;
  2308. }
  2309. if (($i+1) < $numchars) {
  2310. $nextchar = $chardata[($i+1)];
  2311. } else {
  2312. $nextchar = false;
  2313. }
  2314. if (TCPDF_FONT_DATA::$uni_type[$thischar['char']] == 'AL') {
  2315. $x = $thischar['x'];
  2316. if ($x > 0) {
  2317. $prevchar = $charAL[($x-1)];
  2318. } else {
  2319. $prevchar = false;
  2320. }
  2321. if (($x+1) < $numAL) {
  2322. $nextchar = $charAL[($x+1)];
  2323. } else {
  2324. $nextchar = false;
  2325. }
  2326. // if laa letter
  2327. if (($prevchar !== false) AND ($prevchar['char'] == 1604) AND (in_array($thischar['char'], $alfletter))) {
  2328. $arabicarr = TCPDF_FONT_DATA::$uni_laa_array;
  2329. $laaletter = true;
  2330. if ($x > 1) {
  2331. $prevchar = $charAL[($x-2)];
  2332. } else {
  2333. $prevchar = false;
  2334. }
  2335. } else {
  2336. $arabicarr = TCPDF_FONT_DATA::$uni_arabicsubst;
  2337. $laaletter = false;
  2338. }
  2339. if (($prevchar !== false) AND ($nextchar !== false) AND
  2340. ((TCPDF_FONT_DATA::$uni_type[$prevchar['char']] == 'AL') OR (TCPDF_FONT_DATA::$uni_type[$prevchar['char']] == 'NSM')) AND
  2341. ((TCPDF_FONT_DATA::$uni_type[$nextchar['char']] == 'AL') OR (TCPDF_FONT_DATA::$uni_type[$nextchar['char']] == 'NSM')) AND
  2342. ($prevchar['type'] == $thischar['type']) AND
  2343. ($nextchar['type'] == $thischar['type']) AND
  2344. ($nextchar['char'] != 1567)) {
  2345. if (in_array($prevchar['char'], $endedletter)) {
  2346. if (isset($arabicarr[$thischar['char']][2])) {
  2347. // initial
  2348. $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
  2349. }
  2350. } else {
  2351. if (isset($arabicarr[$thischar['char']][3])) {
  2352. // medial
  2353. $chardata2[$i]['char'] = $arabicarr[$thischar['char']][3];
  2354. }
  2355. }
  2356. } elseif (($nextchar !== false) AND
  2357. ((TCPDF_FONT_DATA::$uni_type[$nextchar['char']] == 'AL') OR (TCPDF_FONT_DATA::$uni_type[$nextchar['char']] == 'NSM')) AND
  2358. ($nextchar['type'] == $thischar['type']) AND
  2359. ($nextchar['char'] != 1567)) {
  2360. if (isset($arabicarr[$chardata[$i]['char']][2])) {
  2361. // initial
  2362. $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
  2363. }
  2364. } elseif ((($prevchar !== false) AND
  2365. ((TCPDF_FONT_DATA::$uni_type[$prevchar['char']] == 'AL') OR (TCPDF_FONT_DATA::$uni_type[$prevchar['char']] == 'NSM')) AND
  2366. ($prevchar['type'] == $thischar['type'])) OR
  2367. (($nextchar !== false) AND ($nextchar['char'] == 1567))) {
  2368. // final
  2369. if (($i > 1) AND ($thischar['char'] == 1607) AND
  2370. ($chardata[$i-1]['char'] == 1604) AND
  2371. ($chardata[$i-2]['char'] == 1604)) {
  2372. //Allah Word
  2373. // mark characters to delete with false
  2374. $chardata2[$i-2]['char'] = false;
  2375. $chardata2[$i-1]['char'] = false;
  2376. $chardata2[$i]['char'] = 65010;
  2377. } else {
  2378. if (($prevchar !== false) AND in_array($prevchar['char'], $endedletter)) {
  2379. if (isset($arabicarr[$thischar['char']][0])) {
  2380. // isolated
  2381. $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
  2382. }
  2383. } else {
  2384. if (isset($arabicarr[$thischar['char']][1])) {
  2385. // final
  2386. $chardata2[$i]['char'] = $arabicarr[$thischar['char']][1];
  2387. }
  2388. }
  2389. }
  2390. } elseif (isset($arabicarr[$thischar['char']][0])) {
  2391. // isolated
  2392. $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
  2393. }
  2394. // if laa letter
  2395. if ($laaletter) {
  2396. // mark characters to delete with false
  2397. $chardata2[($charAL[($x-1)]['i'])]['char'] = false;
  2398. }
  2399. } // end if AL (Arabic Letter)
  2400. } // end for each char
  2401. /*
  2402. * Combining characters that can occur with Arabic Shadda (0651 HEX, 1617 DEC) are replaced.
  2403. * Putting the combining mark and shadda in the same glyph allows us to avoid the two marks overlapping each other in an illegible manner.
  2404. */
  2405. for ($i = 0; $i < ($numchars-1); ++$i) {
  2406. if (($chardata2[$i]['char'] == 1617) AND (isset(TCPDF_FONT_DATA::$uni_diacritics[($chardata2[$i+1]['char'])]))) {
  2407. // check if the subtitution font is defined on current font
  2408. if (isset($currentfont['cw'][(TCPDF_FONT_DATA::$uni_diacritics[($chardata2[$i+1]['char'])])])) {
  2409. $chardata2[$i]['char'] = false;
  2410. $chardata2[$i+1]['char'] = TCPDF_FONT_DATA::$uni_diacritics[($chardata2[$i+1]['char'])];
  2411. }
  2412. }
  2413. }
  2414. // remove marked characters
  2415. foreach ($chardata2 as $key => $value) {
  2416. if ($value['char'] === false) {
  2417. unset($chardata2[$key]);
  2418. }
  2419. }
  2420. $chardata = array_values($chardata2);
  2421. $numchars = count($chardata);
  2422. unset($chardata2);
  2423. unset($arabicarr);
  2424. unset($laaletter);
  2425. unset($charAL);
  2426. }
  2427. // L2. From the highest level found in the text to the lowest odd level on each line, including intermediate levels not actually present in the text, reverse any contiguous sequence of characters that are at that level or higher.
  2428. for ($j=$maxlevel; $j > 0; $j--) {
  2429. $ordarray = Array();
  2430. $revarr = Array();
  2431. $onlevel = false;
  2432. for ($i=0; $i < $numchars; ++$i) {
  2433. if ($chardata[$i]['level'] >= $j) {
  2434. $onlevel = true;
  2435. if (isset(TCPDF_FONT_DATA::$uni_mirror[$chardata[$i]['char']])) {
  2436. // L4. A character is depicted by a mirrored glyph if and only if (a) the resolved directionality of that character is R, and (b) the Bidi_Mirrored property value of that character is true.
  2437. $chardata[$i]['char'] = TCPDF_FONT_DATA::$uni_mirror[$chardata[$i]['char']];
  2438. }
  2439. $revarr[] = $chardata[$i];
  2440. } else {
  2441. if ($onlevel) {
  2442. $revarr = array_reverse($revarr);
  2443. $ordarray = array_merge($ordarray, $revarr);
  2444. $revarr = Array();
  2445. $onlevel = false;
  2446. }
  2447. $ordarray[] = $chardata[$i];
  2448. }
  2449. }
  2450. if ($onlevel) {
  2451. $revarr = array_reverse($revarr);
  2452. $ordarray = array_merge($ordarray, $revarr);
  2453. }
  2454. $chardata = $ordarray;
  2455. }
  2456. $ordarray = array();
  2457. foreach ($chardata as $cd) {
  2458. $ordarray[] = $cd['char'];
  2459. // store char values for subsetting
  2460. $currentfont['subsetchars'][$cd['char']] = true;
  2461. }
  2462. return $ordarray;
  2463. }
  2464. /**
  2465. * Get a reference font size.
  2466. * @param $size (string) String containing font size value.
  2467. * @param $refsize (float) Reference font size in points.
  2468. * @return float value in points
  2469. * @public static
  2470. */
  2471. public static function getFontRefSize($size, $refsize=12) {
  2472. switch ($size) {
  2473. case 'xx-small': {
  2474. $size = ($refsize - 4);
  2475. break;
  2476. }
  2477. case 'x-small': {
  2478. $size = ($refsize - 3);
  2479. break;
  2480. }
  2481. case 'small': {
  2482. $size = ($refsize - 2);
  2483. break;
  2484. }
  2485. case 'medium': {
  2486. $size = $refsize;
  2487. break;
  2488. }
  2489. case 'large': {
  2490. $size = ($refsize + 2);
  2491. break;
  2492. }
  2493. case 'x-large': {
  2494. $size = ($refsize + 4);
  2495. break;
  2496. }
  2497. case 'xx-large': {
  2498. $size = ($refsize + 6);
  2499. break;
  2500. }
  2501. case 'smaller': {
  2502. $size = ($refsize - 3);
  2503. break;
  2504. }
  2505. case 'larger': {
  2506. $size = ($refsize + 3);
  2507. break;
  2508. }
  2509. }
  2510. return $size;
  2511. }
  2512. } // END OF TCPDF_FONTS CLASS
  2513. //============================================================+
  2514. // END OF FILE
  2515. //============================================================+