FontMetrics.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. <?php
  2. /**
  3. * @package dompdf
  4. * @link http://dompdf.github.com/
  5. * @author Benj Carson <benjcarson@digitaljunkies.ca>
  6. * @author Helmut Tischer <htischer@weihenstephan.org>
  7. * @author Fabien Ménager <fabien.menager@gmail.com>
  8. * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  9. */
  10. namespace Dompdf;
  11. use FontLib\Font;
  12. /**
  13. * The font metrics class
  14. *
  15. * This class provides information about fonts and text. It can resolve
  16. * font names into actual installed font files, as well as determine the
  17. * size of text in a particular font and size.
  18. *
  19. * @static
  20. * @package dompdf
  21. */
  22. class FontMetrics
  23. {
  24. /**
  25. * Name of the font cache file
  26. *
  27. * This file must be writable by the webserver process only to update it
  28. * with save_font_families() after adding the .afm file references of a new font family
  29. * with FontMetrics::saveFontFamilies().
  30. * This is typically done only from command line with load_font.php on converting
  31. * ttf fonts to ufm with php-font-lib.
  32. */
  33. const CACHE_FILE = "dompdf_font_family_cache.php";
  34. /**
  35. * @var Canvas
  36. * @deprecated
  37. */
  38. protected $pdf;
  39. /**
  40. * Underlying {@link Canvas} object to perform text size calculations
  41. *
  42. * @var Canvas
  43. */
  44. protected $canvas;
  45. /**
  46. * Array of font family names to font files
  47. *
  48. * Usually cached by the {@link load_font.php} script
  49. *
  50. * @var array
  51. */
  52. protected $fontLookup = [];
  53. /**
  54. * @var Options
  55. */
  56. private $options;
  57. /**
  58. * Class initialization
  59. */
  60. public function __construct(Canvas $canvas, Options $options)
  61. {
  62. $this->setCanvas($canvas);
  63. $this->setOptions($options);
  64. $this->loadFontFamilies();
  65. }
  66. /**
  67. * @deprecated
  68. */
  69. public function save_font_families()
  70. {
  71. $this->saveFontFamilies();
  72. }
  73. /**
  74. * Saves the stored font family cache
  75. *
  76. * The name and location of the cache file are determined by {@link
  77. * FontMetrics::CACHE_FILE}. This file should be writable by the
  78. * webserver process.
  79. *
  80. * @see FontMetrics::loadFontFamilies()
  81. */
  82. public function saveFontFamilies()
  83. {
  84. // replace the path to the DOMPDF font directories with the corresponding constants (allows for more portability)
  85. $cacheData = sprintf("<?php return array (%s", PHP_EOL);
  86. foreach ($this->fontLookup as $family => $variants) {
  87. $cacheData .= sprintf(" '%s' => array(%s", addslashes($family), PHP_EOL);
  88. foreach ($variants as $variant => $path) {
  89. $path = sprintf("'%s'", $path);
  90. $path = str_replace('\'' . $this->getOptions()->getFontDir() , '$fontDir . \'' , $path);
  91. $path = str_replace('\'' . $this->getOptions()->getRootDir() , '$rootDir . \'' , $path);
  92. $cacheData .= sprintf(" '%s' => %s,%s", $variant, $path, PHP_EOL);
  93. }
  94. $cacheData .= sprintf(" ),%s", PHP_EOL);
  95. }
  96. $cacheData .= ") ?>";
  97. file_put_contents($this->getCacheFile(), $cacheData);
  98. }
  99. /**
  100. * @deprecated
  101. */
  102. public function load_font_families()
  103. {
  104. $this->loadFontFamilies();
  105. }
  106. /**
  107. * Loads the stored font family cache
  108. *
  109. * @see FontMetrics::saveFontFamilies()
  110. */
  111. public function loadFontFamilies()
  112. {
  113. $fontDir = $this->getOptions()->getFontDir();
  114. $rootDir = $this->getOptions()->getRootDir();
  115. // FIXME: temporarily define constants for cache files <= v0.6.2
  116. if (!defined("DOMPDF_DIR")) { define("DOMPDF_DIR", $rootDir); }
  117. if (!defined("DOMPDF_FONT_DIR")) { define("DOMPDF_FONT_DIR", $fontDir); }
  118. $file = $rootDir . "/lib/fonts/dompdf_font_family_cache.dist.php";
  119. $distFonts = require $file;
  120. if (!is_readable($this->getCacheFile())) {
  121. $this->fontLookup = $distFonts;
  122. return;
  123. }
  124. $cacheData = require $this->getCacheFile();
  125. $this->fontLookup = [];
  126. if (is_array($this->fontLookup)) {
  127. foreach ($cacheData as $key => $value) {
  128. $this->fontLookup[stripslashes($key)] = $value;
  129. }
  130. }
  131. // Merge provided fonts
  132. $this->fontLookup += $distFonts;
  133. }
  134. /**
  135. * @param array $style
  136. * @param string $remote_file
  137. * @param resource $context
  138. * @return bool
  139. * @deprecated
  140. */
  141. public function register_font($style, $remote_file, $context = null)
  142. {
  143. return $this->registerFont($style, $remote_file);
  144. }
  145. /**
  146. * @param array $style
  147. * @param string $remoteFile
  148. * @param resource $context
  149. * @return bool
  150. */
  151. public function registerFont($style, $remoteFile, $context = null)
  152. {
  153. $fontname = mb_strtolower($style["family"]);
  154. $families = $this->getFontFamilies();
  155. $entry = [];
  156. if (isset($families[$fontname])) {
  157. $entry = $families[$fontname];
  158. }
  159. $styleString = $this->getType("{$style['weight']} {$style['style']}");
  160. $fontDir = $this->getOptions()->getFontDir();
  161. $remoteHash = md5($remoteFile);
  162. $prefix = $fontname . "_" . $styleString;
  163. $prefix = trim($prefix, "-");
  164. if (function_exists('iconv')) {
  165. $prefix = @iconv('utf-8', 'us-ascii//TRANSLIT', $prefix);
  166. }
  167. $prefix_encoding = mb_detect_encoding($prefix, mb_detect_order(), true);
  168. $substchar = mb_substitute_character();
  169. mb_substitute_character(0x005F);
  170. $prefix = mb_convert_encoding($prefix, "ISO-8859-1", $prefix_encoding);
  171. mb_substitute_character($substchar);
  172. $prefix = preg_replace("[\W]", "_", $prefix);
  173. $prefix = preg_replace("/[^-_\w]+/", "", $prefix);
  174. $localFile = $fontDir . "/" . $prefix . "_" . $remoteHash;
  175. if (isset($entry[$styleString]) && $localFile == $entry[$styleString]) {
  176. return true;
  177. }
  178. $cacheEntry = $localFile;
  179. $localFile .= ".".strtolower(pathinfo(parse_url($remoteFile, PHP_URL_PATH), PATHINFO_EXTENSION));
  180. $entry[$styleString] = $cacheEntry;
  181. // Download the remote file
  182. [$protocol, $baseHost, $basePath] = Helpers::explode_url($remoteFile);
  183. if (!$this->options->isRemoteEnabled() && ($protocol != "" && $protocol !== "file://")) {
  184. Helpers::record_warnings(E_USER_WARNING, "Remote font resource $remoteFile referenced, but remote file download is disabled.", __FILE__, __LINE__);
  185. return false;
  186. }
  187. if ($protocol == "" || $protocol === "file://") {
  188. $realfile = realpath($remoteFile);
  189. $rootDir = realpath($this->options->getRootDir());
  190. if (strpos($realfile, $rootDir) !== 0) {
  191. $chroot = $this->options->getChroot();
  192. $chrootValid = false;
  193. foreach($chroot as $chrootPath) {
  194. $chrootPath = realpath($chrootPath);
  195. if ($chrootPath !== false && strpos($realfile, $chrootPath) === 0) {
  196. $chrootValid = true;
  197. break;
  198. }
  199. }
  200. if ($chrootValid !== true) {
  201. Helpers::record_warnings(E_USER_WARNING, "Permission denied on $remoteFile. The file could not be found under the paths specified by Options::chroot.", __FILE__, __LINE__);
  202. return false;
  203. }
  204. }
  205. if (!$realfile) {
  206. Helpers::record_warnings(E_USER_WARNING, "File '$realfile' not found.", __FILE__, __LINE__);
  207. return false;
  208. }
  209. $remoteFile = $realfile;
  210. }
  211. list($remoteFileContent, $http_response_header) = @Helpers::getFileContent($remoteFile, $context);
  212. if (empty($remoteFileContent)) {
  213. return false;
  214. }
  215. $localTempFile = @tempnam($this->options->get("tempDir"), "dompdf-font-");
  216. file_put_contents($localTempFile, $remoteFileContent);
  217. $font = Font::load($localTempFile);
  218. if (!$font) {
  219. unlink($localTempFile);
  220. return false;
  221. }
  222. $font->parse();
  223. $font->saveAdobeFontMetrics("$cacheEntry.ufm");
  224. $font->close();
  225. unlink($localTempFile);
  226. if ( !file_exists("$cacheEntry.ufm") ) {
  227. return false;
  228. }
  229. // Save the changes
  230. file_put_contents($localFile, $remoteFileContent);
  231. if ( !file_exists($localFile) ) {
  232. unlink("$cacheEntry.ufm");
  233. return false;
  234. }
  235. $this->setFontFamily($fontname, $entry);
  236. $this->saveFontFamilies();
  237. return true;
  238. }
  239. /**
  240. * @param $text
  241. * @param $font
  242. * @param $size
  243. * @param float $word_spacing
  244. * @param float $char_spacing
  245. * @return float
  246. * @deprecated
  247. */
  248. public function get_text_width($text, $font, $size, $word_spacing = 0.0, $char_spacing = 0.0)
  249. {
  250. //return self::$_pdf->get_text_width($text, $font, $size, $word_spacing, $char_spacing);
  251. return $this->getTextWidth($text, $font, $size, $word_spacing, $char_spacing);
  252. }
  253. /**
  254. * Calculates text size, in points
  255. *
  256. * @param string $text the text to be sized
  257. * @param string $font the desired font
  258. * @param float $size the desired font size
  259. * @param float $wordSpacing
  260. * @param float $charSpacing
  261. *
  262. * @internal param float $spacing word spacing, if any
  263. * @return float
  264. */
  265. public function getTextWidth($text, $font, $size, $wordSpacing = 0.0, $charSpacing = 0.0)
  266. {
  267. // @todo Make sure this cache is efficient before enabling it
  268. static $cache = [];
  269. if ($text === "") {
  270. return 0;
  271. }
  272. // Don't cache long strings
  273. $useCache = !isset($text[50]); // Faster than strlen
  274. $key = "$font/$size/$wordSpacing/$charSpacing";
  275. if ($useCache && isset($cache[$key][$text])) {
  276. return $cache[$key]["$text"];
  277. }
  278. $width = $this->getCanvas()->get_text_width($text, $font, $size, $wordSpacing, $charSpacing);
  279. if ($useCache) {
  280. $cache[$key][$text] = $width;
  281. }
  282. return $width;
  283. }
  284. /**
  285. * @param $font
  286. * @param $size
  287. * @return float
  288. * @deprecated
  289. */
  290. public function get_font_height($font, $size)
  291. {
  292. return $this->getFontHeight($font, $size);
  293. }
  294. /**
  295. * Calculates font height
  296. *
  297. * @param string $font
  298. * @param float $size
  299. *
  300. * @return float
  301. */
  302. public function getFontHeight($font, $size)
  303. {
  304. return $this->getCanvas()->get_font_height($font, $size);
  305. }
  306. /**
  307. * @param $family_raw
  308. * @param string $subtype_raw
  309. * @return string
  310. * @deprecated
  311. */
  312. public function get_font($family_raw, $subtype_raw = "normal")
  313. {
  314. return $this->getFont($family_raw, $subtype_raw);
  315. }
  316. /**
  317. * Resolves a font family & subtype into an actual font file
  318. * Subtype can be one of 'normal', 'bold', 'italic' or 'bold_italic'. If
  319. * the particular font family has no suitable font file, the default font
  320. * ({@link Options::defaultFont}) is used. The font file returned
  321. * is the absolute pathname to the font file on the system.
  322. *
  323. * @param string $familyRaw
  324. * @param string $subtypeRaw
  325. *
  326. * @return string
  327. */
  328. public function getFont($familyRaw, $subtypeRaw = "normal")
  329. {
  330. static $cache = [];
  331. if (isset($cache[$familyRaw][$subtypeRaw])) {
  332. return $cache[$familyRaw][$subtypeRaw];
  333. }
  334. /* Allow calling for various fonts in search path. Therefore not immediately
  335. * return replacement on non match.
  336. * Only when called with NULL try replacement.
  337. * When this is also missing there is really trouble.
  338. * If only the subtype fails, nevertheless return failure.
  339. * Only on checking the fallback font, check various subtypes on same font.
  340. */
  341. $subtype = strtolower($subtypeRaw);
  342. if ($familyRaw) {
  343. $family = str_replace(["'", '"'], "", strtolower($familyRaw));
  344. if (isset($this->fontLookup[$family][$subtype])) {
  345. return $cache[$familyRaw][$subtypeRaw] = $this->fontLookup[$family][$subtype];
  346. }
  347. return null;
  348. }
  349. $family = "serif";
  350. if (isset($this->fontLookup[$family][$subtype])) {
  351. return $cache[$familyRaw][$subtypeRaw] = $this->fontLookup[$family][$subtype];
  352. }
  353. if (!isset($this->fontLookup[$family])) {
  354. return null;
  355. }
  356. $family = $this->fontLookup[$family];
  357. foreach ($family as $sub => $font) {
  358. if (strpos($subtype, $sub) !== false) {
  359. return $cache[$familyRaw][$subtypeRaw] = $font;
  360. }
  361. }
  362. if ($subtype !== "normal") {
  363. foreach ($family as $sub => $font) {
  364. if ($sub !== "normal") {
  365. return $cache[$familyRaw][$subtypeRaw] = $font;
  366. }
  367. }
  368. }
  369. $subtype = "normal";
  370. if (isset($family[$subtype])) {
  371. return $cache[$familyRaw][$subtypeRaw] = $family[$subtype];
  372. }
  373. return null;
  374. }
  375. /**
  376. * @param $family
  377. * @return null|string
  378. * @deprecated
  379. */
  380. public function get_family($family)
  381. {
  382. return $this->getFamily($family);
  383. }
  384. /**
  385. * @param string $family
  386. * @return null|string
  387. */
  388. public function getFamily($family)
  389. {
  390. $family = str_replace(["'", '"'], "", mb_strtolower($family));
  391. if (isset($this->fontLookup[$family])) {
  392. return $this->fontLookup[$family];
  393. }
  394. return null;
  395. }
  396. /**
  397. * @param $type
  398. * @return string
  399. * @deprecated
  400. */
  401. public function get_type($type)
  402. {
  403. return $this->getType($type);
  404. }
  405. /**
  406. * @param string $type
  407. * @return string
  408. */
  409. public function getType($type)
  410. {
  411. if (preg_match('/bold/i', $type)) {
  412. $weight = 700;
  413. } elseif (preg_match('/([1-9]00)/', $type, $match)) {
  414. $weight = (int)$match[0];
  415. } else {
  416. $weight = 400;
  417. }
  418. $weight = $weight === 400 ? 'normal' : $weight;
  419. $weight = $weight === 700 ? 'bold' : $weight;
  420. $style = preg_match('/italic|oblique/i', $type) ? 'italic' : null;
  421. if ($weight === 'normal' && $style !== null) {
  422. return $style;
  423. }
  424. return $style === null
  425. ? $weight
  426. : $weight.'_'.$style;
  427. }
  428. /**
  429. * @return array
  430. * @deprecated
  431. */
  432. public function get_font_families()
  433. {
  434. return $this->getFontFamilies();
  435. }
  436. /**
  437. * Returns the current font lookup table
  438. *
  439. * @return array
  440. */
  441. public function getFontFamilies()
  442. {
  443. return $this->fontLookup;
  444. }
  445. /**
  446. * @param string $fontname
  447. * @param mixed $entry
  448. * @deprecated
  449. */
  450. public function set_font_family($fontname, $entry)
  451. {
  452. $this->setFontFamily($fontname, $entry);
  453. }
  454. /**
  455. * @param string $fontname
  456. * @param mixed $entry
  457. */
  458. public function setFontFamily($fontname, $entry)
  459. {
  460. $this->fontLookup[mb_strtolower($fontname)] = $entry;
  461. }
  462. /**
  463. * @return string
  464. */
  465. public function getCacheFile()
  466. {
  467. return $this->getOptions()->getFontDir() . '/' . self::CACHE_FILE;
  468. }
  469. /**
  470. * @param Options $options
  471. * @return $this
  472. */
  473. public function setOptions(Options $options)
  474. {
  475. $this->options = $options;
  476. return $this;
  477. }
  478. /**
  479. * @return Options
  480. */
  481. public function getOptions()
  482. {
  483. return $this->options;
  484. }
  485. /**
  486. * @param Canvas $canvas
  487. * @return $this
  488. */
  489. public function setCanvas(Canvas $canvas)
  490. {
  491. $this->canvas = $canvas;
  492. // Still write deprecated pdf for now. It might be used by a parent class.
  493. $this->pdf = $canvas;
  494. return $this;
  495. }
  496. /**
  497. * @return Canvas
  498. */
  499. public function getCanvas()
  500. {
  501. return $this->canvas;
  502. }
  503. }