PageRenderTime 44ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/common.php

https://github.com/paszczus/lms
PHP | 911 lines | 696 code | 132 blank | 83 comment | 135 complexity | 95b32c915db62efb1e266fe7e3c8b8ac MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.1
  1. <?php
  2. /*
  3. * LMS version 1.11-git
  4. *
  5. * (C) Copyright 2001-2013 LMS Developers
  6. *
  7. * Please, see the doc/AUTHORS for more information about authors!
  8. *
  9. * This program is free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License Version 2 as
  11. * published by the Free Software Foundation.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program; if not, write to the Free Software
  20. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
  21. * USA.
  22. *
  23. * $Id: common.php,v 1.130 2012/01/02 11:01:28 alec Exp $
  24. */
  25. // Common functions, that making it in class would be nonsense :)
  26. // Execute a system program. return a trim()'d result.
  27. // does very crude pipe checking. you need ' | ' for it to work
  28. // ie $program = execute_program('netstat', '-anp | grep LIST');
  29. // NOT $program = execute_program('netstat', '-anp|grep LIST');
  30. function bsd_grab_key ($key)
  31. {
  32. return execute_program('sysctl', '-n '.$key);
  33. }
  34. function find_program ($program)
  35. {
  36. $path = array('/bin', '/sbin', '/usr/bin', '/usr/sbin', '/usr/local/bin', '/usr/local/sbin');
  37. while ($this_path = current($path))
  38. {
  39. if (is_executable($this_path.'/'.$program))
  40. {
  41. return $this_path.'/'.$program;
  42. }
  43. next($path);
  44. }
  45. return;
  46. }
  47. function execute_program ($program, $args = '')
  48. {
  49. $buffer = '';
  50. $program = find_program($program);
  51. if (!$program) { return; }
  52. // see if we've gotten a |, if we have we need to do patch checking on the cmd
  53. if ($args)
  54. {
  55. $args_list = preg_split('/ /', $args);
  56. for ($i = 0; $i < count($args_list); $i++)
  57. {
  58. if ($args_list[$i] == '|')
  59. {
  60. $cmd = $args_list[$i + 1];
  61. $new_cmd = find_program($cmd);
  62. $args = preg_replace('/\| '.preg_quote($cmd, '/').'/', '| '.$new_cmd, $args);
  63. }
  64. }
  65. }
  66. // we've finally got a good cmd line.. execute it
  67. if ($fp = popen($program.' '.$args, 'r'))
  68. {
  69. while (!feof($fp))
  70. {
  71. $buffer .= fgets($fp, 4096);
  72. }
  73. return trim($buffer);
  74. }
  75. }
  76. function hostname()
  77. {
  78. switch(PHP_OS)
  79. {
  80. case 'Linux':
  81. exec('hostname -f',$return);
  82. $hostname=$return[0];
  83. break;
  84. case 'Darwin':
  85. case 'FreeBSD':
  86. case 'OpenBSD':
  87. case 'NetBSD':
  88. case 'WinNT':
  89. exec('hostname',$return);
  90. $hostname=$return[0];
  91. break;
  92. default:
  93. $return = trans('unknown OS ($a)', PHP_OS);
  94. }
  95. if(!$hostname)
  96. $hostname = $_ENV['HOSTNAME'] ? $_ENV['HOSTNAME'] : $_SERVER['SERVER_NAME'];
  97. if(!$hostname)
  98. $hostname='N.A.';
  99. return $hostname;
  100. }
  101. function ip_long($sip)
  102. {
  103. if(check_ip($sip)){
  104. return sprintf('%u',ip2long($sip));
  105. }else{
  106. return 0;
  107. }
  108. }
  109. function check_ip($ip)
  110. {
  111. return (bool) preg_match('/^((25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)$/', $ip);
  112. }
  113. function check_ipv6($ip)
  114. {
  115. // fast exit for localhost
  116. if (strlen($ip) < 3)
  117. return $IP == '::';
  118. // Check if part is in IPv4 format
  119. if (strpos($ip, '.')) {
  120. $lastcolon = strrpos($ip, ':');
  121. if (!($lastcolon && check_ip(substr($ip, $lastcolon + 1))))
  122. return false;
  123. // replace IPv4 part with dummy
  124. $ip = substr($ip, 0, $lastcolon) . ':0:0';
  125. }
  126. // check uncompressed
  127. if (strpos($ip, '::') === false) {
  128. return preg_match('/^(?:[a-f0-9]{1,4}:){7}[a-f0-9]{1,4}$/i', $ip);
  129. }
  130. // check colon-count for compressed format
  131. if (substr_count($ip, ':') < 8) {
  132. return preg_match('/^(?::|(?:[a-f0-9]{1,4}:)+):(?:(?:[a-f0-9]{1,4}:)*[a-f0-9]{1,4})?$/i', $ip);
  133. }
  134. return false;
  135. }
  136. function check_mask($mask)
  137. {
  138. $i=0;
  139. $j=0;
  140. $maskb=decbin(ip2long($mask));
  141. if (strlen($maskb) < 32)
  142. return FALSE;
  143. else
  144. {
  145. while (($i<32) && ($maskb[$i] == '1'))
  146. {
  147. $i++;
  148. }
  149. $j=$i+1;
  150. while (($j<32) && ($maskb[$j] == '0'))
  151. {
  152. $j++;
  153. }
  154. if ($j<32)
  155. return FALSE;
  156. else
  157. return TRUE;
  158. }
  159. }
  160. function getbraddr($ip,$mask)
  161. {
  162. if(check_ip($ip) && check_mask($mask))
  163. {
  164. $net = ip2long(getnetaddr($ip, $mask));
  165. $mask = ip2long($mask);
  166. return long2ip($net | (~$mask));
  167. }
  168. else
  169. return false;
  170. }
  171. function getnetaddr($ip,$mask)
  172. {
  173. if(check_ip($ip) && check_mask($mask))
  174. {
  175. $ip = ip2long($ip);
  176. $mask = ip2long($mask);
  177. return long2ip($ip & $mask);
  178. }
  179. else
  180. return false;
  181. }
  182. function prefix2mask($prefix)
  183. {
  184. if($prefix>=0&&$prefix<=32)
  185. {
  186. $out = '';
  187. for($ti=0;$ti<$prefix;$ti++)
  188. $out .= '1';
  189. for($ti=$prefix;$ti<32;$ti++)
  190. $out .= '0';
  191. return long2ip(bindec($out));
  192. }
  193. else
  194. return false;
  195. }
  196. function mask2prefix($mask)
  197. {
  198. if(check_mask($mask))
  199. {
  200. return strlen(str_replace('0','',decbin(ip2long($mask))));
  201. }
  202. else
  203. {
  204. return -1;
  205. }
  206. }
  207. /*
  208. * mac checking function - requires macaddr passed as reference,
  209. * so it can fix mac address instantly to valid string
  210. */
  211. function check_mac(&$macaddr)
  212. {
  213. // save passed macaddr for future use
  214. $oldmac = $macaddr;
  215. // strip EVERYTHING that doesnt match 0-9 and a-f,
  216. // so $macaddr should contains 12 hex digits, and that's
  217. // will be base for our test
  218. $macaddr = preg_replace('/[^0-9a-f]/i', '', $macaddr);
  219. if(!preg_match('/^[0-9a-f]{12}$/i', $macaddr))
  220. {
  221. // mac address isn't valid, restore it (cause we working on
  222. // reference) and return false
  223. $macaddr = $oldmac;
  224. return FALSE;
  225. }
  226. else
  227. {
  228. // mac address is valid, return nice mac address that LMS
  229. // uses.
  230. $macaddr = $macaddr[0].$macaddr[1].':'.
  231. $macaddr[2].$macaddr[3].':'.
  232. $macaddr[4].$macaddr[5].':'.
  233. $macaddr[6].$macaddr[7].':'.
  234. $macaddr[8].$macaddr[9].':'.
  235. $macaddr[10].$macaddr[11];
  236. return TRUE;
  237. }
  238. }
  239. function textwrap($text, $wrap=76, $break = "\n")
  240. {
  241. // This function is takem from newsportal
  242. $len = strlen($text);
  243. if ($len > $wrap)
  244. {
  245. $h = ''; // massaged text
  246. $lastWhite = 0; // position of last whitespace char
  247. $lastChar = 0; // position of last char
  248. $lastBreak = 0; // position of last break
  249. // while there is text to process
  250. while ($lastChar < $len)
  251. {
  252. $char = substr($text, $lastChar, 1); // get the next character
  253. // if we are beyond the wrap boundry and there is a place to break
  254. if (($lastChar - $lastBreak > $wrap) && ($lastWhite > $lastBreak))
  255. {
  256. $h .= substr($text, $lastBreak, ($lastWhite - $lastBreak)) . $break;
  257. $lastChar = $lastWhite + 1;
  258. $lastBreak = $lastChar;
  259. }
  260. // You may wish to include other characters as valid whitespace...
  261. if ($char == ' ' || $char == chr(13) || $char == chr(10))
  262. $lastWhite = $lastChar; // note the position of the last whitespace
  263. $lastChar = $lastChar + 1; // advance the last character position by one
  264. }
  265. $h .= substr($text, $lastBreak); // build line
  266. }
  267. else
  268. {
  269. $h = $text; // in this case everything can fit on one line
  270. }
  271. return $h;
  272. }
  273. function isipin($ip,$net,$mask)
  274. {
  275. if(ip_long($ip) > ip_long(getnetaddr($net,$mask)) && ip_long($ip) < ip_long(getbraddr($net,$mask)))
  276. return true;
  277. else
  278. return false;
  279. }
  280. function isipinstrict($ip,$net,$mask)
  281. {
  282. if(ip_long($ip) >= ip_long(getnetaddr($net,$mask)) && ip_long($ip) <= ip_long(getbraddr($net,$mask)))
  283. return true;
  284. else
  285. return false;
  286. }
  287. function getmicrotime()
  288. {
  289. // This function has been taken from PHP manual
  290. list($usec, $sec) = explode(' ',microtime());
  291. return ((float)$usec + (float)$sec);
  292. }
  293. function writesyslog($message,$type)
  294. {
  295. // Untested on *BSD. Can anyone chek this out on *BSD machine? Thanx.
  296. switch(PHP_OS)
  297. {
  298. case 'OpenBSD':
  299. case 'Linux':
  300. $access = date('Y/m/d H:i:s');
  301. // open syslog, include the process ID and also send
  302. // the log to standard error, and use a user defined
  303. // logging mechanism
  304. openlog('lms-php', LOG_PID | LOG_NDELAY, LOG_AUTH);
  305. syslog($type,$message.' (at '.$access.' from '.$_SERVER['REMOTE_ADDR'].' ('.$_SERVER['HTTP_USER_AGENT'].'))');
  306. closelog();
  307. break;
  308. default:
  309. return FALSE;
  310. break;
  311. }
  312. return TRUE;
  313. }
  314. // Creates directories tree
  315. function rmkdir($dir)
  316. {
  317. if($dir[0]!='/')
  318. $dir = getcwd() . '/' . $dir;
  319. $directories = explode('/',$dir);
  320. $makedirs = 0;
  321. for($i=1;$i<sizeof($directories);$i++)
  322. {
  323. $cdir = '';
  324. for($j=1;$j<$i+1;$j++)
  325. $cdir .= '/'.$directories[$j];
  326. if(!is_dir($cdir))
  327. {
  328. $result = mkdir($cdir,0777);
  329. $makedirs ++;
  330. }
  331. }
  332. if(!$result && $makedirs)
  333. return $result;
  334. else
  335. return $makedirs;
  336. }
  337. // Deletes directory and all subdirs and files in it
  338. function rrmdir($dir)
  339. {
  340. $files = glob($dir . '/*', GLOB_MARK);
  341. foreach ($files as $file) {
  342. if (is_dir($file))
  343. rrmdir($file);
  344. else
  345. unlink($file);
  346. }
  347. if (is_dir($dir))
  348. rmdir($dir);
  349. }
  350. function striphtml($text)
  351. {
  352. $search = array ("'<script[^>]*?>.*?</script>'si", // Strip out javascript
  353. "'<[\/\!]*?[^<>]*?>'si", // Strip out html tags
  354. "'([\r\n])[\s]+'", // Strip out white space
  355. "'&(quot|#34);'i", // Replace html entities
  356. "'&(amp|#38);'i",
  357. "'&(lt|#60);'i",
  358. "'&(gt|#62);'i",
  359. "'&(nbsp|#160);'i",
  360. "'&(iexcl|#161);'i",
  361. "'&(cent|#162);'i",
  362. "'&(pound|#163);'i",
  363. "'&(copy|#169);'i",
  364. "'&#(\d+);'e"); // evaluate as php
  365. $replace = array ('',
  366. '',
  367. "\\1",
  368. '"',
  369. '&',
  370. '<',
  371. '>',
  372. ' ',
  373. chr(161),
  374. chr(162),
  375. chr(163),
  376. chr(169),
  377. "chr(\\1)");
  378. return preg_replace ($search, $replace, $text);
  379. }
  380. function check_email( $email )
  381. {
  382. $length = strlen( $email );
  383. if(
  384. !$email
  385. || substr($email,0,1) == '@'
  386. || substr($email,0,1) == '.'
  387. || strrpos($email,'@') == ($length - 1)
  388. || strrpos($email,'.') == ($length - 1)
  389. || substr_count($email,'@') != 1
  390. || !substr_count(substr($email,strpos($email,'@')),'.')
  391. || substr_count($email,'..')
  392. || ($length-strrpos($email,'.'))<3
  393. )
  394. return FALSE;
  395. $email_charset = 'qwertyuiopasdfghjklzxcvbnm1234567890@-._';
  396. $i = 0;
  397. while ( $i < $length )
  398. {
  399. $char = $email[$i++];
  400. if ( stristr( $email_charset, $char ) === false )
  401. return FALSE;
  402. }
  403. return TRUE;
  404. }
  405. function get_producer($mac) {
  406. $mac = strtoupper(str_replace(':', '-', substr($mac, 0, 8)));
  407. if (!$mac)
  408. return '';
  409. $maclines = @file(LIB_DIR . '/ethercodes.txt', FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
  410. if (!empty($maclines))
  411. foreach ($maclines as $line) {
  412. list ($prefix, $producer) = explode(':', $line);
  413. if ($mac == $prefix)
  414. return $producer;
  415. }
  416. return '';
  417. }
  418. function setunits($data) // for traffic data
  419. {
  420. if ( $data >= (1024*1024*1024*1024))
  421. {
  422. $number = $data / (1024*1024*1024*1024);
  423. $unit = "TiB";
  424. }
  425. elseif ( $data >= (1024*1024*1024))
  426. {
  427. $number = $data / (1024*1024*1024);
  428. $unit = "GiB";
  429. }
  430. elseif ( $data >= (1024*1024))
  431. {
  432. $number = $data / (1024*1024);
  433. $unit = "MiB";
  434. }
  435. else
  436. {
  437. $number = $data / 1024;
  438. $unit = "KiB";
  439. }
  440. return array($number, $unit);
  441. }
  442. function r_trim($array)
  443. {
  444. foreach($array as $key => $value)
  445. if(is_array($value))
  446. $array[$key] = r_trim($value);
  447. else
  448. $array[$key] = trim($value);
  449. return $array;
  450. }
  451. // config value testers
  452. function isboolean($value)
  453. {
  454. if(preg_match('/^(1|y|on|yes|true|tak|t|0|n|no|off|false|nie|enabled|disabled)$/i', $value))
  455. return TRUE;
  456. else
  457. return FALSE;
  458. }
  459. function moneyf($value)
  460. {
  461. global $LANGDEFS, $_language;
  462. return sprintf($LANGDEFS[$_language]['money_format'], $value);
  463. }
  464. if (!function_exists('bcmod'))
  465. {
  466. function bcmod( $x, $y )
  467. {
  468. // how many numbers to take at once? carefull not to exceed (int)
  469. $take = 5;
  470. $mod = '';
  471. do
  472. {
  473. $a = (int)$mod.substr( $x, 0, $take );
  474. $x = substr( $x, $take );
  475. $mod = $a % $y;
  476. }
  477. while ( strlen($x) );
  478. return (int)$mod;
  479. }
  480. }
  481. function docnumber($number=NULL, $template=NULL, $time=NULL, $ext_num='')
  482. {
  483. $number = $number ? $number : 1;
  484. $template = $template ? $template : DEFAULT_NUMBER_TEMPLATE;
  485. $time = $time ? $time : time();
  486. // extended number part
  487. $result = str_replace('%I', $ext_num, $template);
  488. // main document number
  489. $result = preg_replace_callback(
  490. '/%(\\d*)N/',
  491. create_function('$m', "return sprintf(\"%0\$m[1]d\", $number);"),
  492. $result);
  493. // time conversion specifiers
  494. return strftime($result, $time);
  495. }
  496. // our finance round
  497. function f_round($value)
  498. {
  499. $value = str_replace(',','.', $value);
  500. $value = round ( (float) $value, 2);
  501. return $value;
  502. }
  503. function fetch_url($url)
  504. {
  505. $url_parsed = parse_url($url);
  506. $host = $url_parsed['host'];
  507. $path = $url_parsed['path'];
  508. $port = isset($url_parsed['port']) ? $url_parsed['port'] : 0; //sometimes port is undefined
  509. if ($port==0)
  510. $port = 80;
  511. if ($url_parsed['query'] != '')
  512. $path .= '?'.$url_parsed['query'];
  513. $request = "GET $path HTTP/1.0\r\nHost: $host\r\n\r\n";
  514. $fp = @fsockopen($host, $port, $errno, $errstr, 5);
  515. if(!$fp) return FALSE;
  516. if (!stream_set_timeout($fp, 3)) return FALSE;
  517. fwrite($fp, $request);
  518. $info = stream_get_meta_data($fp);
  519. if ($info['timed_out']) return FALSE;
  520. $body = FALSE;
  521. $out = '';
  522. while(!feof($fp))
  523. {
  524. $s = fgets($fp, 1024);
  525. $info = stream_get_meta_data($fp);
  526. if ($info['timed_out']) return FALSE;
  527. if($body)
  528. $out .= $s;
  529. if($s == "\r\n")
  530. $body = TRUE;
  531. }
  532. fclose($fp);
  533. return $out;
  534. }
  535. // quoted-printable encoding
  536. function qp_encode($string) {
  537. // ASCII only - don't encode
  538. if (!preg_match('#[\x80-\xFF]{1}#', $string))
  539. return $string;
  540. $encoded = preg_replace_callback(
  541. '/([\x2C\x3F\x80-\xFF])/',
  542. create_function('$m', 'return "=".sprintf("%02X", ord($m[1]));'),
  543. $string);
  544. // replace spaces with _
  545. $encoded = str_replace(' ', '_', $encoded);
  546. return '=?UTF-8?Q?'.$encoded.'?=';
  547. }
  548. // escape quotes and backslashes, newlines, etc.
  549. function escape_js($string)
  550. {
  551. return strtr($string, array('\\'=>'\\\\',"'"=>"\\'",'"'=>'\\"',"\r"=>'\\r',"\n"=>'\\n','</'=>'<\/'));
  552. }
  553. function lms_ucwords($str)
  554. {
  555. $result = array();
  556. $arr = preg_split('/\s+/', $str);
  557. foreach($arr as $word)
  558. $result[] = mb_strlen($word) > 1 ? mb_convert_case($word, MB_CASE_TITLE) : $word;
  559. return implode(' ', $result);
  560. }
  561. // replace national character with ASCII equivalent
  562. function clear_utf($str)
  563. {
  564. $r = '';
  565. $s = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
  566. for ($i=0, $len=strlen($s); $i<$len; $i++)
  567. {
  568. $ch1 = $s[$i];
  569. $ch2 = mb_substr($str, $i, 1);
  570. $r .= $ch1=='?' ? $ch2 : $ch1;
  571. }
  572. return $r;
  573. }
  574. function lastonline_date($timestamp)
  575. {
  576. global $CONFIG;
  577. if (!$timestamp)
  578. return null;
  579. $delta = time()-$timestamp;
  580. if ($delta > $CONFIG['phpui']['lastonline_limit']) {
  581. if($delta>59)
  582. return trans('$a ago ($b)', uptimef($delta), date('Y/m/d, H:i', $timestamp));
  583. else
  584. return date('(Y/m/d, H:i)', $timestamp);
  585. }
  586. return trans('online');
  587. }
  588. function is_leap_year($year)
  589. {
  590. if ($year % 4) return false;
  591. if ($year % 100) return true;
  592. if ($year % 400) return false;
  593. return true;
  594. }
  595. function truncate_str($string, $length, $etc='...')
  596. {
  597. if ($length == 0)
  598. return '';
  599. if (mb_strlen($string) > $length) {
  600. $length -= min($length, mb_strlen($etc));
  601. return mb_substr($string, 0, $length) . $etc;
  602. } else {
  603. return $string;
  604. }
  605. }
  606. function location_str($data)
  607. {
  608. $location = $data['city_name'];
  609. if ($data['location_flat']) {
  610. $h = $CONFIG['phpui']['house_template'] ? $CONFIG['phpui']['house_template'] : '%h/%f';
  611. $h = str_replace('%h', $data['location_house'], $h);
  612. $h = str_replace('%f', $data['location_flat'], $h);
  613. }
  614. else
  615. $h = $data['location_house'];
  616. if ($data['street_name']) {
  617. $street = $data['street_type'] .' '. $data['street_name'];
  618. $location .= ($location ? ', ' : '') . $street;
  619. }
  620. if ($h)
  621. $location .= ' ' . $h;
  622. return $location;
  623. }
  624. function set_timer($label = 0)
  625. {
  626. $GLOBALS['lms_timer'][$label] = microtime(true);
  627. }
  628. function get_timer($label = 0)
  629. {
  630. return sprintf('%.4f', microtime(true) - $GLOBALS['lms_timer'][$label]);
  631. }
  632. /* Functions for modularized LMS */
  633. function plugin_handle($name)
  634. {
  635. global $PLUGINS;
  636. if(isset($PLUGINS[$name]))
  637. foreach($PLUGINS[$name] as $plugin)
  638. include($plugin);
  639. }
  640. function clearheader()
  641. {
  642. global $ExecStack, $layout;
  643. $ExecStack->replaceTemplate('core', 'header', 'core', 'clearheader');
  644. //$ExecStack->dropTemplate('core', 'menu');
  645. }
  646. /*
  647. Registering "plugin" function is for use in actions.
  648. $handle - handle name
  649. $plugin - template or action for including in handle. Example of use:
  650. register_plugin('nodeinfobox-end', '/path/sometemplate.html');
  651. */
  652. function register_plugin($handle, $plugin)
  653. {
  654. global $PLUGINS;
  655. $PLUGINS[$handle][] = $plugin;
  656. }
  657. function html2pdf($content, $subject=NULL, $title=NULL, $type=NULL, $id=NULL, $orientation='P', $margins=array(5, 10, 5, 10), $save=false, $copy=false)
  658. {
  659. global $layout, $DB;
  660. require_once(LIB_DIR.'/html2pdf/html2pdf.class.php');
  661. if (isset($margins))
  662. if (!is_array($margins))
  663. $margins = array(5, 10, 5, 10); /* default */
  664. $html2pdf = new HTML2PDF($orientation, 'A4', 'en', true, 'UTF-8', $margins);
  665. /* disable font subsetting to improve performance */
  666. $html2pdf->pdf->setFontSubsetting(false);
  667. if ($id) {
  668. $info = $DB->GetRow('SELECT di.name, di.description FROM divisions di
  669. LEFT JOIN documents d ON (d.divisionid = di.id)
  670. WHERE d.id = ?', array($id));
  671. }
  672. $html2pdf->pdf->SetProducer('LMS Developers');
  673. $html2pdf->pdf->SetCreator('LMS '.$layout['lmsv']);
  674. if ($info)
  675. $html2pdf->pdf->SetAuthor($info['name']);
  676. if ($subject)
  677. $html2pdf->pdf->SetSubject($subject);
  678. if ($title)
  679. $html2pdf->pdf->SetTitle($title);
  680. $html2pdf->pdf->SetDisplayMode('fullpage', 'SinglePage', 'UseNone');
  681. $html2pdf->AddFont('arial', '', 'arial.php');
  682. $html2pdf->AddFont('arial', 'B', 'arialb.php');
  683. $html2pdf->AddFont('arial', 'I', 'ariali.php');
  684. $html2pdf->AddFont('arial', 'BI', 'arialbi.php');
  685. $html2pdf->AddFont('times', '', 'times.php');
  686. /* if tidy extension is loaded we repair html content */
  687. if (extension_loaded('tidy')) {
  688. $config = array(
  689. 'indent' => true,
  690. 'output-html' => true,
  691. 'indent-spaces' => 4,
  692. 'join-styles' => true,
  693. 'join-classes' => true,
  694. 'fix-bad-comments' => true,
  695. 'fix-backslash' => true,
  696. 'repeated-attributes' => 'keep-last',
  697. 'drop-proprietary-attribute' => true,
  698. 'sort-attributes' => 'alpha',
  699. 'hide-comments' => true,
  700. 'new-blocklevel-tags' => 'page, page_header, page_footer, barcode',
  701. 'wrap' => 200);
  702. $tidy = new tidy;
  703. $content = $tidy->repairString($content, $config, 'utf8');
  704. }
  705. $html2pdf->WriteHTML($content);
  706. if ($copy) {
  707. /* add watermark only for contract & annex */
  708. if(($type == DOC_CONTRACT) || ($type == DOC_ANNEX)) {
  709. $html2pdf->AddFont('courier', '', 'courier.php');
  710. $html2pdf->AddFont('courier', 'B', 'courierb.php');
  711. $html2pdf->pdf->SetTextColor(255, 0, 0);
  712. $PageWidth = $html2pdf->pdf->getPageWidth();
  713. $PageHeight = $html2pdf->pdf->getPageHeight();
  714. $PageCount = $html2pdf->pdf->getNumPages();
  715. $txt = trim(preg_replace("/(.)/i", "\${1} ", trans('COPY')));
  716. $w = $html2pdf->pdf->getStringWidth($txt, 'courier', 'B', 120);
  717. $x = ($PageWidth / 2) - (($w / 2) * sin(45));
  718. $y = ($PageHeight / 2) + 50;
  719. for($i = 1; $i <= $PageCount; $i++) {
  720. $html2pdf->pdf->setPage($i);
  721. $html2pdf->pdf->SetAlpha(0.2);
  722. $html2pdf->pdf->SetFont('courier', 'B', 120);
  723. $html2pdf->pdf->StartTransform();
  724. $html2pdf->pdf->Rotate(45, $x, $y);
  725. $html2pdf->pdf->Text($x, $y, $txt);
  726. $html2pdf->pdf->StopTransform();
  727. }
  728. $html2pdf->pdf->SetAlpha(1);
  729. }
  730. }
  731. if(($type == DOC_CONTRACT) || ($type == DOC_ANNEX)) {
  732. /* set signature additional information */
  733. $info = array(
  734. 'Name' => $info['name'],
  735. 'Location' => $subject,
  736. 'Reason' => $title,
  737. 'ContactInfo' => $info['description'],
  738. );
  739. /* setup your cert & key file */
  740. $cert = 'file://'.LIB_DIR.'/tcpdf/config/lms.cert';
  741. $key = 'file://'.LIB_DIR.'/tcpdf/config/lms.key';
  742. /* set document digital signature & protection */
  743. if (file_exists($cert) && file_exists($key)) {
  744. $html2pdf->pdf->setSignature($cert, $key, 'lms-documents', '', 1, $info);
  745. }
  746. }
  747. $html2pdf->pdf->SetProtection(array('modify', 'annot-forms', 'fill-forms', 'extract', 'assemble'), '', PASSWORD_CHANGEME, '1');
  748. if ($save) {
  749. if (function_exists('mb_convert_encoding'))
  750. $filename = mb_convert_encoding($title, "ISO-8859-2", "UTF-8");
  751. else
  752. $filename = iconv("UTF-8", "ISO-8859-2//TRANSLIT", $title);
  753. $html2pdf->Output($filename.'.pdf', 'D');
  754. } else {
  755. $html2pdf->Output();
  756. }
  757. }
  758. function is_natural($var) {
  759. return preg_match('/^[1-9][0-9]*$/', $var);
  760. }
  761. function check_password_strength($password) {
  762. return (preg_match('/[a-z]/', $password) && preg_match('/[A-Z]/', $password)
  763. && preg_match('/[0-9]/', $password) && mb_strlen($password) >= 8);
  764. }
  765. function access_denied() {
  766. global $SMARTY, $SESSION;
  767. $SMARTY->display('noaccess.html');
  768. $SESSION->close();
  769. die;
  770. }
  771. function check_date($date) {
  772. return preg_match('/^[0-9]{4}\/[0-9]{2}\/[0-9]{2}$/', $date);
  773. }
  774. ?>