PageRenderTime 145ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 1ms

/lib/tcpdf/include/tcpdf_static.php

https://bitbucket.org/moodle/moodle
PHP | 2650 lines | 1786 code | 79 blank | 785 comment | 280 complexity | ea1a6634e0b98be60da294b38f7b507c MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1, BSD-3-Clause, MIT, GPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. //============================================================+
  3. // File name : tcpdf_static.php
  4. // Version : 1.1.4
  5. // Begin : 2002-08-03
  6. // Last Update : 2019-11-01
  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) 2002-2015 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 License
  25. // along with TCPDF. If not, see
  26. // <http://www.tecnick.com/pagefiles/tcpdf/LICENSE.TXT>.
  27. //
  28. // See LICENSE.TXT file for more information.
  29. // -------------------------------------------------------------------
  30. //
  31. // Description :
  32. // Static methods used by the TCPDF class.
  33. //
  34. //============================================================+
  35. /**
  36. * @file
  37. * This is a PHP class that contains static methods for the TCPDF class.<br>
  38. * @package com.tecnick.tcpdf
  39. * @author Nicola Asuni
  40. * @version 1.1.2
  41. */
  42. /**
  43. * @class TCPDF_STATIC
  44. * Static methods used by the TCPDF class.
  45. * @package com.tecnick.tcpdf
  46. * @brief PHP class for generating PDF documents without requiring external extensions.
  47. * @version 1.1.1
  48. * @author Nicola Asuni - info@tecnick.com
  49. */
  50. class TCPDF_STATIC {
  51. /**
  52. * Current TCPDF version.
  53. * @private static
  54. */
  55. private static $tcpdf_version = '6.3.5';
  56. /**
  57. * String alias for total number of pages.
  58. * @public static
  59. */
  60. public static $alias_tot_pages = '{:ptp:}';
  61. /**
  62. * String alias for page number.
  63. * @public static
  64. */
  65. public static $alias_num_page = '{:pnp:}';
  66. /**
  67. * String alias for total number of pages in a single group.
  68. * @public static
  69. */
  70. public static $alias_group_tot_pages = '{:ptg:}';
  71. /**
  72. * String alias for group page number.
  73. * @public static
  74. */
  75. public static $alias_group_num_page = '{:png:}';
  76. /**
  77. * String alias for right shift compensation used to correctly align page numbers on the right.
  78. * @public static
  79. */
  80. public static $alias_right_shift = '{rsc:';
  81. /**
  82. * Encryption padding string.
  83. * @public static
  84. */
  85. public static $enc_padding = "\x28\xBF\x4E\x5E\x4E\x75\x8A\x41\x64\x00\x4E\x56\xFF\xFA\x01\x08\x2E\x2E\x00\xB6\xD0\x68\x3E\x80\x2F\x0C\xA9\xFE\x64\x53\x69\x7A";
  86. /**
  87. * ByteRange placemark used during digital signature process.
  88. * @since 4.6.028 (2009-08-25)
  89. * @public static
  90. */
  91. public static $byterange_string = '/ByteRange[0 ********** ********** **********]';
  92. /**
  93. * Array page boxes names
  94. * @public static
  95. */
  96. public static $pageboxes = array('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox');
  97. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  98. /**
  99. * Return the current TCPDF version.
  100. * @return TCPDF version string
  101. * @since 5.9.012 (2010-11-10)
  102. * @public static
  103. */
  104. public static function getTCPDFVersion() {
  105. return self::$tcpdf_version;
  106. }
  107. /**
  108. * Return the current TCPDF producer.
  109. * @return TCPDF producer string
  110. * @since 6.0.000 (2013-03-16)
  111. * @public static
  112. */
  113. public static function getTCPDFProducer() {
  114. return "\x54\x43\x50\x44\x46\x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x74\x63\x70\x64\x66\x2e\x6f\x72\x67\x29";
  115. }
  116. /**
  117. * Sets the current active configuration setting of magic_quotes_runtime (if the set_magic_quotes_runtime function exist)
  118. * @param $mqr (boolean) FALSE for off, TRUE for on.
  119. * @since 4.6.025 (2009-08-17)
  120. * @public static
  121. */
  122. public static function set_mqr($mqr) {
  123. if (!defined('PHP_VERSION_ID')) {
  124. $version = PHP_VERSION;
  125. define('PHP_VERSION_ID', (($version[0] * 10000) + ($version[2] * 100) + $version[4]));
  126. }
  127. if (PHP_VERSION_ID < 50300) {
  128. @set_magic_quotes_runtime($mqr);
  129. }
  130. }
  131. /**
  132. * Gets the current active configuration setting of magic_quotes_runtime (if the get_magic_quotes_runtime function exist)
  133. * @return Returns 0 if magic quotes runtime is off or get_magic_quotes_runtime doesn't exist, 1 otherwise.
  134. * @since 4.6.025 (2009-08-17)
  135. * @public static
  136. */
  137. public static function get_mqr() {
  138. if (!defined('PHP_VERSION_ID')) {
  139. $version = PHP_VERSION;
  140. define('PHP_VERSION_ID', (($version[0] * 10000) + ($version[2] * 100) + $version[4]));
  141. }
  142. if (PHP_VERSION_ID < 50300) {
  143. return @get_magic_quotes_runtime();
  144. }
  145. return 0;
  146. }
  147. /**
  148. * Check if the URL exist.
  149. * @param $url (string) URL to check.
  150. * @return Boolean true if the URl exist, false otherwise.
  151. * @since 5.9.204 (2013-01-28)
  152. * @public static
  153. */
  154. public static function isValidURL($url) {
  155. $headers = @get_headers($url);
  156. return (strpos($headers[0], '200') !== false);
  157. }
  158. /**
  159. * Removes SHY characters from text.
  160. * Unicode Data:<ul>
  161. * <li>Name : SOFT HYPHEN, commonly abbreviated as SHY</li>
  162. * <li>HTML Entity (decimal): "&amp;#173;"</li>
  163. * <li>HTML Entity (hex): "&amp;#xad;"</li>
  164. * <li>HTML Entity (named): "&amp;shy;"</li>
  165. * <li>How to type in Microsoft Windows: [Alt +00AD] or [Alt 0173]</li>
  166. * <li>UTF-8 (hex): 0xC2 0xAD (c2ad)</li>
  167. * <li>UTF-8 character: chr(194).chr(173)</li>
  168. * </ul>
  169. * @param $txt (string) input string
  170. * @param $unicode (boolean) True if we are in unicode mode, false otherwise.
  171. * @return string without SHY characters.
  172. * @since (4.5.019) 2009-02-28
  173. * @public static
  174. */
  175. public static function removeSHY($txt='', $unicode=true) {
  176. $txt = preg_replace('/([\\xc2]{1}[\\xad]{1})/', '', $txt);
  177. if (!$unicode) {
  178. $txt = preg_replace('/([\\xad]{1})/', '', $txt);
  179. }
  180. return $txt;
  181. }
  182. /**
  183. * Get the border mode accounting for multicell position (opens bottom side of multicell crossing pages)
  184. * @param $brd (mixed) Indicates if borders must be drawn around the cell block. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
  185. * @param $position (string) multicell position: 'start', 'middle', 'end'
  186. * @param $opencell (boolean) True when the cell is left open at the page bottom, false otherwise.
  187. * @return border mode array
  188. * @since 4.4.002 (2008-12-09)
  189. * @public static
  190. */
  191. public static function getBorderMode($brd, $position='start', $opencell=true) {
  192. if ((!$opencell) OR empty($brd)) {
  193. return $brd;
  194. }
  195. if ($brd == 1) {
  196. $brd = 'LTRB';
  197. }
  198. if (is_string($brd)) {
  199. // convert string to array
  200. $slen = strlen($brd);
  201. $newbrd = array();
  202. for ($i = 0; $i < $slen; ++$i) {
  203. $newbrd[$brd[$i]] = array('cap' => 'square', 'join' => 'miter');
  204. }
  205. $brd = $newbrd;
  206. }
  207. foreach ($brd as $border => $style) {
  208. switch ($position) {
  209. case 'start': {
  210. if (strpos($border, 'B') !== false) {
  211. // remove bottom line
  212. $newkey = str_replace('B', '', $border);
  213. if (strlen($newkey) > 0) {
  214. $brd[$newkey] = $style;
  215. }
  216. unset($brd[$border]);
  217. }
  218. break;
  219. }
  220. case 'middle': {
  221. if (strpos($border, 'B') !== false) {
  222. // remove bottom line
  223. $newkey = str_replace('B', '', $border);
  224. if (strlen($newkey) > 0) {
  225. $brd[$newkey] = $style;
  226. }
  227. unset($brd[$border]);
  228. $border = $newkey;
  229. }
  230. if (strpos($border, 'T') !== false) {
  231. // remove bottom line
  232. $newkey = str_replace('T', '', $border);
  233. if (strlen($newkey) > 0) {
  234. $brd[$newkey] = $style;
  235. }
  236. unset($brd[$border]);
  237. }
  238. break;
  239. }
  240. case 'end': {
  241. if (strpos($border, 'T') !== false) {
  242. // remove bottom line
  243. $newkey = str_replace('T', '', $border);
  244. if (strlen($newkey) > 0) {
  245. $brd[$newkey] = $style;
  246. }
  247. unset($brd[$border]);
  248. }
  249. break;
  250. }
  251. }
  252. }
  253. return $brd;
  254. }
  255. /**
  256. * Determine whether a string is empty.
  257. * @param $str (string) string to be checked
  258. * @return bool true if string is empty
  259. * @since 4.5.044 (2009-04-16)
  260. * @public static
  261. */
  262. public static function empty_string($str) {
  263. return (is_null($str) OR (is_string($str) AND (strlen($str) == 0)));
  264. }
  265. /**
  266. * Returns a temporary filename for caching object on filesystem.
  267. * @param $type (string) Type of file (name of the subdir on the tcpdf cache folder).
  268. * @param $file_id (string) TCPDF file_id.
  269. * @return string filename.
  270. * @since 4.5.000 (2008-12-31)
  271. * @public static
  272. */
  273. public static function getObjFilename($type='tmp', $file_id='') {
  274. return tempnam(K_PATH_CACHE, '__tcpdf_'.$file_id.'_'.$type.'_'.md5(TCPDF_STATIC::getRandomSeed()).'_');
  275. }
  276. /**
  277. * Add "\" before "\", "(" and ")"
  278. * @param $s (string) string to escape.
  279. * @return string escaped string.
  280. * @public static
  281. */
  282. public static function _escape($s) {
  283. // the chr(13) substitution fixes the Bugs item #1421290.
  284. return strtr($s, array(')' => '\\)', '(' => '\\(', '\\' => '\\\\', chr(13) => '\r'));
  285. }
  286. /**
  287. * Escape some special characters (&lt; &gt; &amp;) for XML output.
  288. * @param $str (string) Input string to convert.
  289. * @return converted string
  290. * @since 5.9.121 (2011-09-28)
  291. * @public static
  292. */
  293. public static function _escapeXML($str) {
  294. $replaceTable = array("\0" => '', '&' => '&amp;', '<' => '&lt;', '>' => '&gt;');
  295. $str = strtr($str, $replaceTable);
  296. return $str;
  297. }
  298. /**
  299. * Creates a copy of a class object
  300. * @param $object (object) class object to be cloned
  301. * @return cloned object
  302. * @since 4.5.029 (2009-03-19)
  303. * @public static
  304. */
  305. public static function objclone($object) {
  306. if (($object instanceof Imagick) AND (version_compare(phpversion('imagick'), '3.0.1') !== 1)) {
  307. // on the versions after 3.0.1 the clone() method was deprecated in favour of clone keyword
  308. return @$object->clone();
  309. }
  310. return @clone($object);
  311. }
  312. /**
  313. * Output input data and compress it if possible.
  314. * @param $data (string) Data to output.
  315. * @param $length (int) Data length in bytes.
  316. * @since 5.9.086
  317. * @public static
  318. */
  319. public static function sendOutputData($data, $length) {
  320. if (!isset($_SERVER['HTTP_ACCEPT_ENCODING']) OR empty($_SERVER['HTTP_ACCEPT_ENCODING'])) {
  321. // the content length may vary if the server is using compression
  322. header('Content-Length: '.$length);
  323. }
  324. echo $data;
  325. }
  326. /**
  327. * Replace page number aliases with number.
  328. * @param $page (string) Page content.
  329. * @param $replace (array) Array of replacements (array keys are replacement strings, values are alias arrays).
  330. * @param $diff (int) If passed, this will be set to the total char number difference between alias and replacements.
  331. * @return replaced page content and updated $diff parameter as array.
  332. * @public static
  333. */
  334. public static function replacePageNumAliases($page, $replace, $diff=0) {
  335. foreach ($replace as $rep) {
  336. foreach ($rep[3] as $a) {
  337. if (strpos($page, $a) !== false) {
  338. $page = str_replace($a, $rep[0], $page);
  339. $diff += ($rep[2] - $rep[1]);
  340. }
  341. }
  342. }
  343. return array($page, $diff);
  344. }
  345. /**
  346. * Returns timestamp in seconds from formatted date-time.
  347. * @param $date (string) Formatted date-time.
  348. * @return int seconds.
  349. * @since 5.9.152 (2012-03-23)
  350. * @public static
  351. */
  352. public static function getTimestamp($date) {
  353. if (($date[0] == 'D') AND ($date[1] == ':')) {
  354. // remove date prefix if present
  355. $date = substr($date, 2);
  356. }
  357. return strtotime($date);
  358. }
  359. /**
  360. * Returns a formatted date-time.
  361. * @param $time (int) Time in seconds.
  362. * @return string escaped date string.
  363. * @since 5.9.152 (2012-03-23)
  364. * @public static
  365. */
  366. public static function getFormattedDate($time) {
  367. return substr_replace(date('YmdHisO', intval($time)), '\'', (0 - 2), 0).'\'';
  368. }
  369. /**
  370. * Returns a string containing random data to be used as a seed for encryption methods.
  371. * @param $seed (string) starting seed value
  372. * @return string containing random data
  373. * @author Nicola Asuni
  374. * @since 5.9.006 (2010-10-19)
  375. * @public static
  376. */
  377. public static function getRandomSeed($seed='') {
  378. $rnd = uniqid(rand().microtime(true), true);
  379. if (function_exists('posix_getpid')) {
  380. $rnd .= posix_getpid();
  381. }
  382. if (function_exists('openssl_random_pseudo_bytes') AND (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')) {
  383. // this is not used on windows systems because it is very slow for a know bug
  384. $rnd .= openssl_random_pseudo_bytes(512);
  385. } else {
  386. for ($i = 0; $i < 23; ++$i) {
  387. $rnd .= uniqid('', true);
  388. }
  389. }
  390. return $rnd.$seed.__FILE__.serialize($_SERVER).microtime(true);
  391. }
  392. /**
  393. * Encrypts a string using MD5 and returns it's value as a binary string.
  394. * @param $str (string) input string
  395. * @return String MD5 encrypted binary string
  396. * @since 2.0.000 (2008-01-02)
  397. * @public static
  398. */
  399. public static function _md5_16($str) {
  400. return pack('H*', md5($str));
  401. }
  402. /**
  403. * Returns the input text exrypted using AES algorithm and the specified key.
  404. * This method requires openssl or mcrypt. Text is padded to 16bytes blocks
  405. * @param $key (string) encryption key
  406. * @param $text (String) input text to be encrypted
  407. * @return String encrypted text
  408. * @author Nicola Asuni
  409. * @since 5.0.005 (2010-05-11)
  410. * @public static
  411. */
  412. public static function _AES($key, $text) {
  413. // padding (RFC 2898, PKCS #5: Password-Based Cryptography Specification Version 2.0)
  414. $padding = 16 - (strlen($text) % 16);
  415. $text .= str_repeat(chr($padding), $padding);
  416. if (extension_loaded('openssl')) {
  417. $iv = openssl_random_pseudo_bytes (openssl_cipher_iv_length('aes-256-cbc'));
  418. $text = openssl_encrypt($text, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
  419. return $iv.substr($text, 0, -16);
  420. }
  421. $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
  422. $text = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $text, MCRYPT_MODE_CBC, $iv);
  423. $text = $iv.$text;
  424. return $text;
  425. }
  426. /**
  427. * Returns the input text exrypted using AES algorithm and the specified key.
  428. * This method requires openssl or mcrypt. Text is not padded
  429. * @param $key (string) encryption key
  430. * @param $text (String) input text to be encrypted
  431. * @return String encrypted text
  432. * @author Nicola Asuni
  433. * @since TODO
  434. * @public static
  435. */
  436. public static function _AESnopad($key, $text) {
  437. if (extension_loaded('openssl')) {
  438. $iv = str_repeat("\x00", openssl_cipher_iv_length('aes-256-cbc'));
  439. $text = openssl_encrypt($text, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
  440. return substr($text, 0, -16);
  441. }
  442. $iv = str_repeat("\x00", mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));
  443. $text = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $text, MCRYPT_MODE_CBC, $iv);
  444. return $text;
  445. }
  446. /**
  447. * Returns the input text encrypted using RC4 algorithm and the specified key.
  448. * RC4 is the standard encryption algorithm used in PDF format
  449. * @param $key (string) Encryption key.
  450. * @param $text (String) Input text to be encrypted.
  451. * @param $last_enc_key (String) Reference to last RC4 key encrypted.
  452. * @param $last_enc_key_c (String) Reference to last RC4 computed key.
  453. * @return String encrypted text
  454. * @since 2.0.000 (2008-01-02)
  455. * @author Klemen Vodopivec, Nicola Asuni
  456. * @public static
  457. */
  458. public static function _RC4($key, $text, &$last_enc_key, &$last_enc_key_c) {
  459. if (function_exists('mcrypt_encrypt') AND ($out = @mcrypt_encrypt(MCRYPT_ARCFOUR, $key, $text, MCRYPT_MODE_STREAM, ''))) {
  460. // try to use mcrypt function if exist
  461. return $out;
  462. }
  463. if ($last_enc_key != $key) {
  464. $k = str_repeat($key, ((256 / strlen($key)) + 1));
  465. $rc4 = range(0, 255);
  466. $j = 0;
  467. for ($i = 0; $i < 256; ++$i) {
  468. $t = $rc4[$i];
  469. $j = ($j + $t + ord($k[$i])) % 256;
  470. $rc4[$i] = $rc4[$j];
  471. $rc4[$j] = $t;
  472. }
  473. $last_enc_key = $key;
  474. $last_enc_key_c = $rc4;
  475. } else {
  476. $rc4 = $last_enc_key_c;
  477. }
  478. $len = strlen($text);
  479. $a = 0;
  480. $b = 0;
  481. $out = '';
  482. for ($i = 0; $i < $len; ++$i) {
  483. $a = ($a + 1) % 256;
  484. $t = $rc4[$a];
  485. $b = ($b + $t) % 256;
  486. $rc4[$a] = $rc4[$b];
  487. $rc4[$b] = $t;
  488. $k = $rc4[($rc4[$a] + $rc4[$b]) % 256];
  489. $out .= chr(ord($text[$i]) ^ $k);
  490. }
  491. return $out;
  492. }
  493. /**
  494. * Return the permission code used on encryption (P value).
  495. * @param $permissions (Array) the set of permissions (specify the ones you want to block).
  496. * @param $mode (int) encryption strength: 0 = RC4 40 bit; 1 = RC4 128 bit; 2 = AES 128 bit; 3 = AES 256 bit.
  497. * @since 5.0.005 (2010-05-12)
  498. * @author Nicola Asuni
  499. * @public static
  500. */
  501. public static function getUserPermissionCode($permissions, $mode=0) {
  502. $options = array(
  503. 'owner' => 2, // bit 2 -- inverted logic: cleared by default
  504. 'print' => 4, // bit 3
  505. 'modify' => 8, // bit 4
  506. 'copy' => 16, // bit 5
  507. 'annot-forms' => 32, // bit 6
  508. 'fill-forms' => 256, // bit 9
  509. 'extract' => 512, // bit 10
  510. 'assemble' => 1024,// bit 11
  511. 'print-high' => 2048 // bit 12
  512. );
  513. $protection = 2147422012; // 32 bit: (01111111 11111111 00001111 00111100)
  514. foreach ($permissions as $permission) {
  515. if (isset($options[$permission])) {
  516. if (($mode > 0) OR ($options[$permission] <= 32)) {
  517. // set only valid permissions
  518. if ($options[$permission] == 2) {
  519. // the logic for bit 2 is inverted (cleared by default)
  520. $protection += $options[$permission];
  521. } else {
  522. $protection -= $options[$permission];
  523. }
  524. }
  525. }
  526. }
  527. return $protection;
  528. }
  529. /**
  530. * Convert hexadecimal string to string
  531. * @param $bs (string) byte-string to convert
  532. * @return String
  533. * @since 5.0.005 (2010-05-12)
  534. * @author Nicola Asuni
  535. * @public static
  536. */
  537. public static function convertHexStringToString($bs) {
  538. $string = ''; // string to be returned
  539. $bslength = strlen($bs);
  540. if (($bslength % 2) != 0) {
  541. // padding
  542. $bs .= '0';
  543. ++$bslength;
  544. }
  545. for ($i = 0; $i < $bslength; $i += 2) {
  546. $string .= chr(hexdec($bs[$i].$bs[($i + 1)]));
  547. }
  548. return $string;
  549. }
  550. /**
  551. * Convert string to hexadecimal string (byte string)
  552. * @param $s (string) string to convert
  553. * @return byte string
  554. * @since 5.0.010 (2010-05-17)
  555. * @author Nicola Asuni
  556. * @public static
  557. */
  558. public static function convertStringToHexString($s) {
  559. $bs = '';
  560. $chars = preg_split('//', $s, -1, PREG_SPLIT_NO_EMPTY);
  561. foreach ($chars as $c) {
  562. $bs .= sprintf('%02s', dechex(ord($c)));
  563. }
  564. return $bs;
  565. }
  566. /**
  567. * Convert encryption P value to a string of bytes, low-order byte first.
  568. * @param $protection (string) 32bit encryption permission value (P value)
  569. * @return String
  570. * @since 5.0.005 (2010-05-12)
  571. * @author Nicola Asuni
  572. * @public static
  573. */
  574. public static function getEncPermissionsString($protection) {
  575. $binprot = sprintf('%032b', $protection);
  576. $str = chr(bindec(substr($binprot, 24, 8)));
  577. $str .= chr(bindec(substr($binprot, 16, 8)));
  578. $str .= chr(bindec(substr($binprot, 8, 8)));
  579. $str .= chr(bindec(substr($binprot, 0, 8)));
  580. return $str;
  581. }
  582. /**
  583. * Encode a name object.
  584. * @param $name (string) Name object to encode.
  585. * @return (string) Encoded name object.
  586. * @author Nicola Asuni
  587. * @since 5.9.097 (2011-06-23)
  588. * @public static
  589. */
  590. public static function encodeNameObject($name) {
  591. $escname = '';
  592. $length = strlen($name);
  593. for ($i = 0; $i < $length; ++$i) {
  594. $chr = $name[$i];
  595. if (preg_match('/[0-9a-zA-Z#_=-]/', $chr) == 1) {
  596. $escname .= $chr;
  597. } else {
  598. $escname .= sprintf('#%02X', ord($chr));
  599. }
  600. }
  601. return $escname;
  602. }
  603. /**
  604. * Convert JavaScript form fields properties array to Annotation Properties array.
  605. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  606. * @param $spot_colors (array) Reference to spot colors array.
  607. * @param $rtl (boolean) True if in Right-To-Left text direction mode, false otherwise.
  608. * @return array of annotation properties
  609. * @author Nicola Asuni
  610. * @since 4.8.000 (2009-09-06)
  611. * @public static
  612. */
  613. public static function getAnnotOptFromJSProp($prop, &$spot_colors, $rtl=false) {
  614. if (isset($prop['aopt']) AND is_array($prop['aopt'])) {
  615. // the annotation options area lready defined
  616. return $prop['aopt'];
  617. }
  618. $opt = array(); // value to be returned
  619. // alignment: Controls how the text is laid out within the text field.
  620. if (isset($prop['alignment'])) {
  621. switch ($prop['alignment']) {
  622. case 'left': {
  623. $opt['q'] = 0;
  624. break;
  625. }
  626. case 'center': {
  627. $opt['q'] = 1;
  628. break;
  629. }
  630. case 'right': {
  631. $opt['q'] = 2;
  632. break;
  633. }
  634. default: {
  635. $opt['q'] = ($rtl)?2:0;
  636. break;
  637. }
  638. }
  639. }
  640. // lineWidth: Specifies the thickness of the border when stroking the perimeter of a field's rectangle.
  641. if (isset($prop['lineWidth'])) {
  642. $linewidth = intval($prop['lineWidth']);
  643. } else {
  644. $linewidth = 1;
  645. }
  646. // borderStyle: The border style for a field.
  647. if (isset($prop['borderStyle'])) {
  648. switch ($prop['borderStyle']) {
  649. case 'border.d':
  650. case 'dashed': {
  651. $opt['border'] = array(0, 0, $linewidth, array(3, 2));
  652. $opt['bs'] = array('w'=>$linewidth, 's'=>'D', 'd'=>array(3, 2));
  653. break;
  654. }
  655. case 'border.b':
  656. case 'beveled': {
  657. $opt['border'] = array(0, 0, $linewidth);
  658. $opt['bs'] = array('w'=>$linewidth, 's'=>'B');
  659. break;
  660. }
  661. case 'border.i':
  662. case 'inset': {
  663. $opt['border'] = array(0, 0, $linewidth);
  664. $opt['bs'] = array('w'=>$linewidth, 's'=>'I');
  665. break;
  666. }
  667. case 'border.u':
  668. case 'underline': {
  669. $opt['border'] = array(0, 0, $linewidth);
  670. $opt['bs'] = array('w'=>$linewidth, 's'=>'U');
  671. break;
  672. }
  673. case 'border.s':
  674. case 'solid': {
  675. $opt['border'] = array(0, 0, $linewidth);
  676. $opt['bs'] = array('w'=>$linewidth, 's'=>'S');
  677. break;
  678. }
  679. default: {
  680. break;
  681. }
  682. }
  683. }
  684. if (isset($prop['border']) AND is_array($prop['border'])) {
  685. $opt['border'] = $prop['border'];
  686. }
  687. if (!isset($opt['mk'])) {
  688. $opt['mk'] = array();
  689. }
  690. if (!isset($opt['mk']['if'])) {
  691. $opt['mk']['if'] = array();
  692. }
  693. $opt['mk']['if']['a'] = array(0.5, 0.5);
  694. // buttonAlignX: Controls how space is distributed from the left of the button face with respect to the icon.
  695. if (isset($prop['buttonAlignX'])) {
  696. $opt['mk']['if']['a'][0] = $prop['buttonAlignX'];
  697. }
  698. // buttonAlignY: Controls how unused space is distributed from the bottom of the button face with respect to the icon.
  699. if (isset($prop['buttonAlignY'])) {
  700. $opt['mk']['if']['a'][1] = $prop['buttonAlignY'];
  701. }
  702. // buttonFitBounds: If true, the extent to which the icon may be scaled is set to the bounds of the button field.
  703. if (isset($prop['buttonFitBounds']) AND ($prop['buttonFitBounds'] == 'true')) {
  704. $opt['mk']['if']['fb'] = true;
  705. }
  706. // buttonScaleHow: Controls how the icon is scaled (if necessary) to fit inside the button face.
  707. if (isset($prop['buttonScaleHow'])) {
  708. switch ($prop['buttonScaleHow']) {
  709. case 'scaleHow.proportional': {
  710. $opt['mk']['if']['s'] = 'P';
  711. break;
  712. }
  713. case 'scaleHow.anamorphic': {
  714. $opt['mk']['if']['s'] = 'A';
  715. break;
  716. }
  717. }
  718. }
  719. // buttonScaleWhen: Controls when an icon is scaled to fit inside the button face.
  720. if (isset($prop['buttonScaleWhen'])) {
  721. switch ($prop['buttonScaleWhen']) {
  722. case 'scaleWhen.always': {
  723. $opt['mk']['if']['sw'] = 'A';
  724. break;
  725. }
  726. case 'scaleWhen.never': {
  727. $opt['mk']['if']['sw'] = 'N';
  728. break;
  729. }
  730. case 'scaleWhen.tooBig': {
  731. $opt['mk']['if']['sw'] = 'B';
  732. break;
  733. }
  734. case 'scaleWhen.tooSmall': {
  735. $opt['mk']['if']['sw'] = 'S';
  736. break;
  737. }
  738. }
  739. }
  740. // buttonPosition: Controls how the text and the icon of the button are positioned with respect to each other within the button face.
  741. if (isset($prop['buttonPosition'])) {
  742. switch ($prop['buttonPosition']) {
  743. case 0:
  744. case 'position.textOnly': {
  745. $opt['mk']['tp'] = 0;
  746. break;
  747. }
  748. case 1:
  749. case 'position.iconOnly': {
  750. $opt['mk']['tp'] = 1;
  751. break;
  752. }
  753. case 2:
  754. case 'position.iconTextV': {
  755. $opt['mk']['tp'] = 2;
  756. break;
  757. }
  758. case 3:
  759. case 'position.textIconV': {
  760. $opt['mk']['tp'] = 3;
  761. break;
  762. }
  763. case 4:
  764. case 'position.iconTextH': {
  765. $opt['mk']['tp'] = 4;
  766. break;
  767. }
  768. case 5:
  769. case 'position.textIconH': {
  770. $opt['mk']['tp'] = 5;
  771. break;
  772. }
  773. case 6:
  774. case 'position.overlay': {
  775. $opt['mk']['tp'] = 6;
  776. break;
  777. }
  778. }
  779. }
  780. // fillColor: Specifies the background color for a field.
  781. if (isset($prop['fillColor'])) {
  782. if (is_array($prop['fillColor'])) {
  783. $opt['mk']['bg'] = $prop['fillColor'];
  784. } else {
  785. $opt['mk']['bg'] = TCPDF_COLORS::convertHTMLColorToDec($prop['fillColor'], $spot_colors);
  786. }
  787. }
  788. // strokeColor: Specifies the stroke color for a field that is used to stroke the rectangle of the field with a line as large as the line width.
  789. if (isset($prop['strokeColor'])) {
  790. if (is_array($prop['strokeColor'])) {
  791. $opt['mk']['bc'] = $prop['strokeColor'];
  792. } else {
  793. $opt['mk']['bc'] = TCPDF_COLORS::convertHTMLColorToDec($prop['strokeColor'], $spot_colors);
  794. }
  795. }
  796. // rotation: The rotation of a widget in counterclockwise increments.
  797. if (isset($prop['rotation'])) {
  798. $opt['mk']['r'] = $prop['rotation'];
  799. }
  800. // charLimit: Limits the number of characters that a user can type into a text field.
  801. if (isset($prop['charLimit'])) {
  802. $opt['maxlen'] = intval($prop['charLimit']);
  803. }
  804. if (!isset($ff)) {
  805. $ff = 0; // default value
  806. }
  807. // readonly: The read-only characteristic of a field. If a field is read-only, the user can see the field but cannot change it.
  808. if (isset($prop['readonly']) AND ($prop['readonly'] == 'true')) {
  809. $ff += 1 << 0;
  810. }
  811. // required: Specifies whether a field requires a value.
  812. if (isset($prop['required']) AND ($prop['required'] == 'true')) {
  813. $ff += 1 << 1;
  814. }
  815. // multiline: Controls how text is wrapped within the field.
  816. if (isset($prop['multiline']) AND ($prop['multiline'] == 'true')) {
  817. $ff += 1 << 12;
  818. }
  819. // password: Specifies whether the field should display asterisks when data is entered in the field.
  820. if (isset($prop['password']) AND ($prop['password'] == 'true')) {
  821. $ff += 1 << 13;
  822. }
  823. // NoToggleToOff: If set, exactly one radio button shall be selected at all times; selecting the currently selected button has no effect.
  824. if (isset($prop['NoToggleToOff']) AND ($prop['NoToggleToOff'] == 'true')) {
  825. $ff += 1 << 14;
  826. }
  827. // Radio: If set, the field is a set of radio buttons.
  828. if (isset($prop['Radio']) AND ($prop['Radio'] == 'true')) {
  829. $ff += 1 << 15;
  830. }
  831. // Pushbutton: If set, the field is a pushbutton that does not retain a permanent value.
  832. if (isset($prop['Pushbutton']) AND ($prop['Pushbutton'] == 'true')) {
  833. $ff += 1 << 16;
  834. }
  835. // Combo: If set, the field is a combo box; if clear, the field is a list box.
  836. if (isset($prop['Combo']) AND ($prop['Combo'] == 'true')) {
  837. $ff += 1 << 17;
  838. }
  839. // editable: Controls whether a combo box is editable.
  840. if (isset($prop['editable']) AND ($prop['editable'] == 'true')) {
  841. $ff += 1 << 18;
  842. }
  843. // Sort: If set, the field's option items shall be sorted alphabetically.
  844. if (isset($prop['Sort']) AND ($prop['Sort'] == 'true')) {
  845. $ff += 1 << 19;
  846. }
  847. // fileSelect: If true, sets the file-select flag in the Options tab of the text field (Field is Used for File Selection).
  848. if (isset($prop['fileSelect']) AND ($prop['fileSelect'] == 'true')) {
  849. $ff += 1 << 20;
  850. }
  851. // multipleSelection: If true, indicates that a list box allows a multiple selection of items.
  852. if (isset($prop['multipleSelection']) AND ($prop['multipleSelection'] == 'true')) {
  853. $ff += 1 << 21;
  854. }
  855. // doNotSpellCheck: If true, spell checking is not performed on this editable text field.
  856. if (isset($prop['doNotSpellCheck']) AND ($prop['doNotSpellCheck'] == 'true')) {
  857. $ff += 1 << 22;
  858. }
  859. // doNotScroll: If true, the text field does not scroll and the user, therefore, is limited by the rectangular region designed for the field.
  860. if (isset($prop['doNotScroll']) AND ($prop['doNotScroll'] == 'true')) {
  861. $ff += 1 << 23;
  862. }
  863. // comb: If set to true, the field background is drawn as series of boxes (one for each character in the value of the field) and each character of the content is drawn within those boxes. The number of boxes drawn is determined from the charLimit property. It applies only to text fields. The setter will also raise if any of the following field properties are also set multiline, password, and fileSelect. A side-effect of setting this property is that the doNotScroll property is also set.
  864. if (isset($prop['comb']) AND ($prop['comb'] == 'true')) {
  865. $ff += 1 << 24;
  866. }
  867. // radiosInUnison: If false, even if a group of radio buttons have the same name and export value, they behave in a mutually exclusive fashion, like HTML radio buttons.
  868. if (isset($prop['radiosInUnison']) AND ($prop['radiosInUnison'] == 'true')) {
  869. $ff += 1 << 25;
  870. }
  871. // richText: If true, the field allows rich text formatting.
  872. if (isset($prop['richText']) AND ($prop['richText'] == 'true')) {
  873. $ff += 1 << 25;
  874. }
  875. // commitOnSelChange: Controls whether a field value is committed after a selection change.
  876. if (isset($prop['commitOnSelChange']) AND ($prop['commitOnSelChange'] == 'true')) {
  877. $ff += 1 << 26;
  878. }
  879. $opt['ff'] = $ff;
  880. // defaultValue: The default value of a field - that is, the value that the field is set to when the form is reset.
  881. if (isset($prop['defaultValue'])) {
  882. $opt['dv'] = $prop['defaultValue'];
  883. }
  884. $f = 4; // default value for annotation flags
  885. // readonly: The read-only characteristic of a field. If a field is read-only, the user can see the field but cannot change it.
  886. if (isset($prop['readonly']) AND ($prop['readonly'] == 'true')) {
  887. $f += 1 << 6;
  888. }
  889. // display: Controls whether the field is hidden or visible on screen and in print.
  890. if (isset($prop['display'])) {
  891. if ($prop['display'] == 'display.visible') {
  892. //
  893. } elseif ($prop['display'] == 'display.hidden') {
  894. $f += 1 << 1;
  895. } elseif ($prop['display'] == 'display.noPrint') {
  896. $f -= 1 << 2;
  897. } elseif ($prop['display'] == 'display.noView') {
  898. $f += 1 << 5;
  899. }
  900. }
  901. $opt['f'] = $f;
  902. // currentValueIndices: Reads and writes single or multiple values of a list box or combo box.
  903. if (isset($prop['currentValueIndices']) AND is_array($prop['currentValueIndices'])) {
  904. $opt['i'] = $prop['currentValueIndices'];
  905. }
  906. // value: The value of the field data that the user has entered.
  907. if (isset($prop['value'])) {
  908. if (is_array($prop['value'])) {
  909. $opt['opt'] = array();
  910. foreach ($prop['value'] AS $key => $optval) {
  911. // exportValues: An array of strings representing the export values for the field.
  912. if (isset($prop['exportValues'][$key])) {
  913. $opt['opt'][$key] = array($prop['exportValues'][$key], $prop['value'][$key]);
  914. } else {
  915. $opt['opt'][$key] = $prop['value'][$key];
  916. }
  917. }
  918. } else {
  919. $opt['v'] = $prop['value'];
  920. }
  921. }
  922. // richValue: This property specifies the text contents and formatting of a rich text field.
  923. if (isset($prop['richValue'])) {
  924. $opt['rv'] = $prop['richValue'];
  925. }
  926. // submitName: If nonempty, used during form submission instead of name. Only applicable if submitting in HTML format (that is, URL-encoded).
  927. if (isset($prop['submitName'])) {
  928. $opt['tm'] = $prop['submitName'];
  929. }
  930. // name: Fully qualified field name.
  931. if (isset($prop['name'])) {
  932. $opt['t'] = $prop['name'];
  933. }
  934. // userName: The user name (short description string) of the field.
  935. if (isset($prop['userName'])) {
  936. $opt['tu'] = $prop['userName'];
  937. }
  938. // highlight: Defines how a button reacts when a user clicks it.
  939. if (isset($prop['highlight'])) {
  940. switch ($prop['highlight']) {
  941. case 'none':
  942. case 'highlight.n': {
  943. $opt['h'] = 'N';
  944. break;
  945. }
  946. case 'invert':
  947. case 'highlight.i': {
  948. $opt['h'] = 'i';
  949. break;
  950. }
  951. case 'push':
  952. case 'highlight.p': {
  953. $opt['h'] = 'P';
  954. break;
  955. }
  956. case 'outline':
  957. case 'highlight.o': {
  958. $opt['h'] = 'O';
  959. break;
  960. }
  961. }
  962. }
  963. // Unsupported options:
  964. // - calcOrderIndex: Changes the calculation order of fields in the document.
  965. // - delay: Delays the redrawing of a field's appearance.
  966. // - defaultStyle: This property defines the default style attributes for the form field.
  967. // - style: Allows the user to set the glyph style of a check box or radio button.
  968. // - textColor, textFont, textSize
  969. return $opt;
  970. }
  971. /**
  972. * Format the page numbers.
  973. * This method can be overriden for custom formats.
  974. * @param $num (int) page number
  975. * @since 4.2.005 (2008-11-06)
  976. * @public static
  977. */
  978. public static function formatPageNumber($num) {
  979. return number_format((float)$num, 0, '', '.');
  980. }
  981. /**
  982. * Format the page numbers on the Table Of Content.
  983. * This method can be overriden for custom formats.
  984. * @param $num (int) page number
  985. * @since 4.5.001 (2009-01-04)
  986. * @see addTOC(), addHTMLTOC()
  987. * @public static
  988. */
  989. public static function formatTOCPageNumber($num) {
  990. return number_format((float)$num, 0, '', '.');
  991. }
  992. /**
  993. * Extracts the CSS properties from a CSS string.
  994. * @param $cssdata (string) string containing CSS definitions.
  995. * @return An array where the keys are the CSS selectors and the values are the CSS properties.
  996. * @author Nicola Asuni
  997. * @since 5.1.000 (2010-05-25)
  998. * @public static
  999. */
  1000. public static function extractCSSproperties($cssdata) {
  1001. if (empty($cssdata)) {
  1002. return array();
  1003. }
  1004. // remove comments
  1005. $cssdata = preg_replace('/\/\*[^\*]*\*\//', '', $cssdata);
  1006. // remove newlines and multiple spaces
  1007. $cssdata = preg_replace('/[\s]+/', ' ', $cssdata);
  1008. // remove some spaces
  1009. $cssdata = preg_replace('/[\s]*([;:\{\}]{1})[\s]*/', '\\1', $cssdata);
  1010. // remove empty blocks
  1011. $cssdata = preg_replace('/([^\}\{]+)\{\}/', '', $cssdata);
  1012. // replace media type parenthesis
  1013. $cssdata = preg_replace('/@media[\s]+([^\{]*)\{/i', '@media \\1§', $cssdata);
  1014. $cssdata = preg_replace('/\}\}/si', '}§', $cssdata);
  1015. // trim string
  1016. $cssdata = trim($cssdata);
  1017. // find media blocks (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv)
  1018. $cssblocks = array();
  1019. $matches = array();
  1020. if (preg_match_all('/@media[\s]+([^\§]*)§([^§]*)§/i', $cssdata, $matches) > 0) {
  1021. foreach ($matches[1] as $key => $type) {
  1022. $cssblocks[$type] = $matches[2][$key];
  1023. }
  1024. // remove media blocks
  1025. $cssdata = preg_replace('/@media[\s]+([^\§]*)§([^§]*)§/i', '', $cssdata);
  1026. }
  1027. // keep 'all' and 'print' media, other media types are discarded
  1028. if (isset($cssblocks['all']) AND !empty($cssblocks['all'])) {
  1029. $cssdata .= $cssblocks['all'];
  1030. }
  1031. if (isset($cssblocks['print']) AND !empty($cssblocks['print'])) {
  1032. $cssdata .= $cssblocks['print'];
  1033. }
  1034. // reset css blocks array
  1035. $cssblocks = array();
  1036. $matches = array();
  1037. // explode css data string into array
  1038. if (substr($cssdata, -1) == '}') {
  1039. // remove last parethesis
  1040. $cssdata = substr($cssdata, 0, -1);
  1041. }
  1042. $matches = explode('}', $cssdata);
  1043. foreach ($matches as $key => $block) {
  1044. // index 0 contains the CSS selector, index 1 contains CSS properties
  1045. $cssblocks[$key] = explode('{', $block);
  1046. if (!isset($cssblocks[$key][1])) {
  1047. // remove empty definitions
  1048. unset($cssblocks[$key]);
  1049. }
  1050. }
  1051. // split groups of selectors (comma-separated list of selectors)
  1052. foreach ($cssblocks as $key => $block) {
  1053. if (strpos($block[0], ',') > 0) {
  1054. $selectors = explode(',', $block[0]);
  1055. foreach ($selectors as $sel) {
  1056. $cssblocks[] = array(0 => trim($sel), 1 => $block[1]);
  1057. }
  1058. unset($cssblocks[$key]);
  1059. }
  1060. }
  1061. // covert array to selector => properties
  1062. $cssdata = array();
  1063. foreach ($cssblocks as $block) {
  1064. $selector = $block[0];
  1065. // calculate selector's specificity
  1066. $matches = array();
  1067. $a = 0; // the declaration is not from is a 'style' attribute
  1068. $b = intval(preg_match_all('/[\#]/', $selector, $matches)); // number of ID attributes
  1069. $c = intval(preg_match_all('/[\[\.]/', $selector, $matches)); // number of other attributes
  1070. $c += intval(preg_match_all('/[\:]link|visited|hover|active|focus|target|lang|enabled|disabled|checked|indeterminate|root|nth|first|last|only|empty|contains|not/i', $selector, $matches)); // number of pseudo-classes
  1071. $d = intval(preg_match_all('/[\>\+\~\s]{1}[a-zA-Z0-9]+/', ' '.$selector, $matches)); // number of element names
  1072. $d += intval(preg_match_all('/[\:][\:]/', $selector, $matches)); // number of pseudo-elements
  1073. $specificity = $a.$b.$c.$d;
  1074. // add specificity to the beginning of the selector
  1075. $cssdata[$specificity.' '.$selector] = $block[1];
  1076. }
  1077. // sort selectors alphabetically to account for specificity
  1078. ksort($cssdata, SORT_STRING);
  1079. // return array
  1080. return $cssdata;
  1081. }
  1082. /**
  1083. * Cleanup HTML code (requires HTML Tidy library).
  1084. * @param $html (string) htmlcode to fix
  1085. * @param $default_css (string) CSS commands to add
  1086. * @param $tagvs (array) parameters for setHtmlVSpace method
  1087. * @param $tidy_options (array) options for tidy_parse_string function
  1088. * @param $tagvspaces (array) Array of vertical spaces for tags.
  1089. * @return string XHTML code cleaned up
  1090. * @author Nicola Asuni
  1091. * @since 5.9.017 (2010-11-16)
  1092. * @see setHtmlVSpace()
  1093. * @public static
  1094. */
  1095. public static function fixHTMLCode($html, $default_css, $tagvs, $tidy_options, &$tagvspaces) {
  1096. // configure parameters for HTML Tidy
  1097. if ($tidy_options === '') {
  1098. $tidy_options = array (
  1099. 'clean' => 1,
  1100. 'drop-empty-paras' => 0,
  1101. 'drop-proprietary-attributes' => 1,
  1102. 'fix-backslash' => 1,
  1103. 'hide-comments' => 1,
  1104. 'join-styles' => 1,
  1105. 'lower-literals' => 1,
  1106. 'merge-divs' => 1,
  1107. 'merge-spans' => 1,
  1108. 'output-xhtml' => 1,
  1109. 'word-2000' => 1,
  1110. 'wrap' => 0,
  1111. 'output-bom' => 0,
  1112. //'char-encoding' => 'utf8',
  1113. //'input-encoding' => 'utf8',
  1114. //'output-encoding' => 'utf8'
  1115. );
  1116. }
  1117. // clean up the HTML code
  1118. $tidy = tidy_parse_string($html, $tidy_options);
  1119. // fix the HTML
  1120. $tidy->cleanRepair();
  1121. // get the CSS part
  1122. $tidy_head = tidy_get_head($tidy);
  1123. $css = $tidy_head->value;
  1124. $css = preg_replace('/<style([^>]+)>/ims', '<style>', $css);
  1125. $css = preg_replace('/<\/style>(.*)<style>/ims', "\n", $css);
  1126. $css = str_replace('/*<![CDATA[*/', '', $css);
  1127. $css = str_replace('/*]]>*/', '', $css);
  1128. preg_match('/<style>(.*)<\/style>/ims', $css, $matches);
  1129. if (isset($matches[1])) {
  1130. $css = strtolower($matches[1]);
  1131. } else {
  1132. $css = '';
  1133. }
  1134. // include default css
  1135. $css = '<style>'.$default_css.$css.'</style>';
  1136. // get the body part
  1137. $tidy_body = tidy_get_body($tidy);
  1138. $html = $tidy_body->value;
  1139. // fix some self-closing tags
  1140. $html = str_replace('<br>', '<br />', $html);
  1141. // remove some empty tag blocks
  1142. $html = preg_replace('/<div([^\>]*)><\/div>/', '', $html);
  1143. $html = preg_replace('/<p([^\>]*)><\/p>/', '', $html);
  1144. if ($tagvs !== '') {
  1145. // set vertical space for some XHTML tags
  1146. $tagvspaces = $tagvs;
  1147. }
  1148. // return the cleaned XHTML code + CSS
  1149. return $css.$html;
  1150. }
  1151. /**
  1152. * Returns true if the CSS selector is valid for the selected HTML tag
  1153. * @param $dom (array) array of HTML tags and properties
  1154. * @param $key (int) key of the current HTML tag
  1155. * @param $selector (string) CSS selector string
  1156. * @return true if the selector is valid, false otherwise
  1157. * @since 5.1.000 (2010-05-25)
  1158. * @public static
  1159. */
  1160. public static function isValidCSSSelectorForTag($dom, $key, $selector) {
  1161. $valid = false; // value to be returned
  1162. $tag = $dom[$key]['value'];
  1163. $class = array();
  1164. if (isset($dom[$key]['attribute']['class']) AND !empty($dom[$key]['attribute']['class'])) {
  1165. $class = explode(' ', strtolower($dom[$key]['attribute']['class']));
  1166. }
  1167. $id = '';
  1168. if (isset($dom[$key]['attribute']['id']) AND !empty($dom[$key]['attribute']['id'])) {
  1169. $id = strtolower($dom[$key]['attribute']['id']);
  1170. }
  1171. $selector = preg_replace('/([\>\+\~\s]{1})([\.]{1})([^\>\+\~\s]*)/si', '\\1*.\\3', $selector);
  1172. $matches = array();
  1173. if (preg_match_all('/([\>\+\~\s]{1})([a-zA-Z0-9\*]+)([^\>\+\~\s]*)/si', $selector, $matches, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE) > 0) {
  1174. $parentop = array_pop($matches[1]);
  1175. $operator = $parentop[0];
  1176. $offset = $parentop[1];
  1177. $lasttag = array_pop($matches[2]);
  1178. $lasttag = strtolower(trim($lasttag[0]));
  1179. if (($lasttag == '*') OR ($lasttag == $tag)) {
  1180. // the last element on selector is our tag or 'any tag'
  1181. $attrib = array_pop($matches[3]);
  1182. $attrib = strtolower(trim($attrib[0]));
  1183. if (!empty($attrib)) {
  1184. // check if matches class, id, attribute, pseudo-class or pseudo-element
  1185. switch ($attrib[0]) {
  1186. case '.': { // class
  1187. if (in_array(substr($attrib, 1), $class)) {
  1188. $valid = true;
  1189. }
  1190. break;
  1191. }
  1192. case '#': { // ID
  1193. if (substr($attrib, 1) == $id) {
  1194. $valid = true;
  1195. }
  1196. break;
  1197. }
  1198. case '[': { // attribute
  1199. $attrmatch = array();
  1200. if (preg_match('/\[([a-zA-Z0-9]*)[\s]*([\~\^\$\*\|\=]*)[\s]*["]?([^"\]]*)["]?\]/i', $attrib, $attrmatch) > 0) {
  1201. $att = strtolower($attrmatch[1]);
  1202. $val = $attrmatch[3];
  1203. if (isset($dom[$key]['attribute'][$att])) {
  1204. switch ($attrmatch[2]) {
  1205. case '=': {
  1206. if ($dom[$key]['attribute'][$att] == $val) {
  1207. $valid = true;
  1208. }
  1209. break;
  1210. }
  1211. case '~=': {
  1212. if (in_array($val, explode(' ', $dom[$key]['attribute'][$att]))) {
  1213. $valid = true;
  1214. }
  1215. break;
  1216. }
  1217. case '^=': {
  1218. if ($val == substr($dom[$key]['attribute'][$att], 0, strlen($val))) {
  1219. $valid = true;
  1220. }
  1221. break;
  1222. }
  1223. case '$=': {
  1224. if ($val == substr($dom[$key]['attribute'][$att], -strlen($val))) {
  1225. $valid = true;
  1226. }
  1227. break;
  1228. }
  1229. case '*=': {
  1230. if (strpos($dom[$key]['attribute'][$att], $val) !== false) {
  1231. $valid = true;
  1232. }
  1233. break;
  1234. }
  1235. case '|=': {
  1236. if ($dom[$key]['attribute'][$att] == $val) {
  1237. $valid = true;
  1238. } elseif (preg_match('/'.$val.'[\-]{1}/i', $dom[$key]['attribute'][$att]) > 0) {
  1239. $valid = true;
  1240. }
  1241. break;
  1242. }
  1243. default: {
  1244. $valid = true;
  1245. }
  1246. }
  1247. }
  1248. }
  1249. break;
  1250. }
  1251. case ':': { // pseudo-class or pseudo-element
  1252. if ($attrib[1] == ':') { // pseudo-element
  1253. // pseudo-elements are not supported!
  1254. // (::first-line, ::first-letter, ::before, ::after)
  1255. } else { // pseudo-class
  1256. // pseudo-classes are not supported!
  1257. // (:root, :nth-child(n), :nth-last-child(n), :nth-of-type(n), :nth-last-of-type(n), :first-child, :last-child, :first-of-type, :last-of-type, :only-child, :only-of-type, :empty, :link, :visited, :active, :hover, :focus, :target, :lang(fr), :enabled, :disabled, :checked)
  1258. }
  1259. break;
  1260. }
  1261. } // end of switch
  1262. } else {
  1263. $valid = true;
  1264. }
  1265. if ($valid AND ($offset > 0)) {
  1266. $valid = false;
  1267. // check remaining selector part
  1268. $selector = substr($selector, 0, $offset);
  1269. switch ($operator) {
  1270. case ' ': { // descendant of an element
  1271. while ($dom[$key]['parent'] > 0) {
  1272. if (self::isValidCSSSelectorForTag($dom, $dom[$key]['parent'], $selector)) {
  1273. $valid = true;
  1274. break;
  1275. } else {
  1276. $key = $dom[$key]['parent'];
  1277. }
  1278. }
  1279. break;
  1280. }
  1281. case '>': { // child of an element
  1282. $valid = self::isValidCSSSelectorForTag($dom, $dom[$key]['parent'], $selector);
  1283. break;
  1284. }
  1285. case '+': { // immediately preceded by an element
  1286. for ($i = ($key - 1); $i > $dom[$key]['parent']; --$i) {
  1287. if ($dom[$i]['tag'] AND $dom[$i]['opening']) {
  1288. $valid = self::isValidCSSSelectorForTag($dom, $i, $selector);
  1289. break;
  1290. }
  1291. }
  1292. break;
  1293. }
  1294. case '~': { // preceded by an element
  1295. for ($i = ($key - 1); $i > $dom[$key]['parent']; --$i) {
  1296. if ($dom[$i]['tag'] AND $dom[$i]['opening']) {
  1297. if (self::isValidCSSSelectorForTag($dom, $i, $selector)) {
  1298. break;
  1299. }
  1300. }
  1301. }
  1302. break;
  1303. }
  1304. }
  1305. }
  1306. }
  1307. }
  1308. return $valid;
  1309. }
  1310. /**
  1311. * Returns the styles array that apply for the selected HTML tag.
  1312. * @param $dom (array) array of HTML tags and properties
  1313. * @param $key (int) key of the current HTML tag
  1314. * @param $css (array) array of CSS properties
  1315. * @return array containing CSS properties
  1316. * @since 5.1.000 (2010-05-25)
  1317. * @public static
  1318. */
  1319. public static function getCSSdataArray($dom, $key, $css) {
  1320. $cssarray = array(); // style to be returned
  1321. // get parent CSS selectors
  1322. $selectors = array();
  1323. if (isset($dom[($dom[$key]['parent'])]['csssel'])) {
  1324. $selectors = $dom[($dom[$key]['parent'])]['csssel'];
  1325. }
  1326. // get all styles that apply
  1327. foreach($css as $selector => $style) {
  1328. $pos = strpos($selector, ' ');
  1329. // get specificity
  1330. $specificity = substr($selector, 0, $pos);
  1331. // remove specificity
  1332. $selector = substr($selector, $pos);
  1333. // check if this selector apply to current tag
  1334. if (self::isValidCSSSelectorForTag($dom, $key, $selector)) {
  1335. if (!in_array($selector, $selectors)) {
  1336. // add style if not already added on parent selector
  1337. $cssarray[] = array('k' => $selector, 's' => $specificity, 'c' => $style);
  1338. $selectors[] = $selector;
  1339. }
  1340. }
  1341. }
  1342. if (isset($dom[$key]['attribute']['style'])) {
  1343. // attach inline style (latest properties have high priority)
  1344. $cssarray[] = array('k' => '', 's' => '1000', 'c' => $dom[$key]['attribute']['style']);
  1345. }
  1346. // order the css array to account for specificity
  1347. $cssordered = array();
  1348. foreach ($cssarray as $key => $val) {
  1349. $skey = sprintf('%04d', $key);
  1350. $cssordered[$val['s'].'_'.$skey] = $val;
  1351. }
  1352. // sort selectors alphabetically to account for specificity
  1353. ksort($cssordered, SORT_STRING);
  1354. return array($selectors, $cssordered);
  1355. }
  1356. /**
  1357. * Compact CSS data array into single string.
  1358. * @param $css (array) array of CSS properties
  1359. * @return string containing merged CSS properties
  1360. * @since 5.9.070 (2011-04-19)
  1361. * @public static
  1362. */
  1363. public static function getTagStyleFromCSSarray($css) {
  1364. $tagstyle = ''; // value to be returned
  1365. foreach ($css as $style) {
  1366. // split single css commands
  1367. $csscmds = explode(';', $style['c']);
  1368. foreach ($csscmds as $cmd) {
  1369. if (!empty($cmd)) {
  1370. $pos = strpos($cmd, ':');
  1371. if ($pos !== false) {
  1372. $cmd = substr($cmd, 0, ($pos + 1));
  1373. if (strpos($tagstyle, $cmd) !== false) {
  1374. // remove duplicate commands (last commands have high priority)
  1375. $tagstyle = preg_replace('/'.$cmd.'[^;]+/i', '', $tagstyle);
  1376. }
  1377. }
  1378. }
  1379. }
  1380. $tagstyle .= ';'.$style['c'];
  1381. }
  1382. // remove multiple semicolons
  1383. $tagstyle = preg_replace('/[;]+/', ';', $tagstyle);
  1384. return $tagstyle;
  1385. }
  1386. /**
  1387. * Returns the Roman representation of an integer number
  1388. * @param $number (int) number to convert
  1389. * @return string roman representation of the specified number
  1390. * @since 4.4.004 (2008-12-10)
  1391. * @public static
  1392. */
  1393. public static function intToRoman($number) {
  1394. $roman = '';
  1395. if ($number >= 4000) {
  1396. // do not represent numbers above 4000 in Roman numerals
  1397. return strval($number);
  1398. }
  1399. while ($number >= 1000) {
  1400. $roman .= 'M';
  1401. $number -= 1000;
  1402. }
  1403. while ($number >= 900) {
  1404. $roman .= 'CM';
  1405. $number -= 900;
  1406. }
  1407. while ($number >= 500) {
  1408. $roman .= 'D';
  1409. $number -= 500;
  1410. }
  1411. while ($number >= 400) {
  1412. $roman .= 'CD';
  1413. $number -= 400;
  1414. }
  1415. while ($number >= 100) {
  1416. $roman .= 'C';
  1417. $number -= 100;
  1418. }
  1419. while ($number >= 90) {
  1420. $roman .= 'XC';
  1421. $number -= 90;
  1422. }
  1423. while ($number >= 50) {
  1424. $roman .= 'L';
  1425. $number -= 50;
  1426. }
  1427. while ($number >= 40) {
  1428. $roman .= 'XL';
  1429. $number -= 40;
  1430. }
  1431. while ($number >= 10) {
  1432. $roman .= 'X';
  1433. $number -= 10;
  1434. }
  1435. while ($number >= 9) {
  1436. $roman .= 'IX';
  1437. $number -= 9;
  1438. }
  1439. while ($number >= 5) {
  1440. $roman .= 'V';
  1441. $number -= 5;
  1442. }
  1443. while ($number >= 4) {
  1444. $roman .= 'IV';
  1445. $number -= 4;
  1446. }
  1447. while ($number >= 1) {
  1448. $roman .= 'I';
  1449. --$number;
  1450. }
  1451. return $roman;
  1452. }
  1453. /**
  1454. * Find position of last occurrence of a substring in a string
  1455. * @param $haystack (string) The string to search in.
  1456. * @param $needle (string) substring to search.
  1457. * @param $offset (int) May be specified to begin searching an arbitrary number of characters into the string.
  1458. * @return Returns the position where the needle exists. Returns FALSE if the needle was not found.
  1459. * @since 4.8.038 (2010-03-13)
  1460. * @public static
  1461. */
  1462. public static function revstrpos($haystack, $needle, $offset = 0) {
  1463. $length = strlen($haystack);
  1464. $offset = ($offset > 0)?($length - $offset):abs($offset);
  1465. $pos = strpos(strrev($haystack), strrev($needle), $offset);
  1466. return ($pos === false)?false:($length - $pos - strlen($needle));
  1467. }
  1468. /**
  1469. * Returns an array of hyphenation patterns.
  1470. * @param $file (string) TEX file containing hypenation patterns. TEX pattrns can be downloaded from http://www.ctan.org/tex-archive/language/hyph-utf8/tex/generic/hyph-utf8/patterns/
  1471. * @return array of hyphenation pattern…

Large files files are truncated, but you can click here to view the full file