pdf.lib.php 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  1. <?php
  2. /* See license terms in /license.txt */
  3. use Chamilo\CoreBundle\Component\Utils\ChamiloApi;
  4. /**
  5. * Class PDF.
  6. *
  7. * @package chamilo.library
  8. */
  9. class PDF
  10. {
  11. /** @var mPDF */
  12. public $pdf;
  13. public $custom_header = [];
  14. public $custom_footer = [];
  15. public $params = [];
  16. public $template;
  17. /**
  18. * Creates the mPDF object.
  19. *
  20. * @param string $pageFormat format A4 A4-L see
  21. * http://mpdf1.com/manual/index.php?tid=184&searchstring=format
  22. * @param string $orientation orientation "P" = Portrait "L" = Landscape
  23. * @param array $params
  24. * @param Template $template
  25. */
  26. public function __construct(
  27. $pageFormat = 'A4',
  28. $orientation = 'P',
  29. $params = [],
  30. $template = null
  31. ) {
  32. $this->template = $template;
  33. /* More info @ http://mpdf1.com/manual/index.php?tid=184&searchstring=mPDF */
  34. if (!in_array($orientation, ['P', 'L'])) {
  35. $orientation = 'P';
  36. }
  37. //left, right, top, bottom, margin_header, margin footer
  38. $params['left'] = isset($params['left']) ? $params['left'] : 15;
  39. $params['right'] = isset($params['right']) ? $params['right'] : 15;
  40. $params['top'] = isset($params['top']) ? $params['top'] : 30;
  41. $params['bottom'] = isset($params['bottom']) ? $params['bottom'] : 30;
  42. $params['margin_footer'] = isset($params['margin_footer']) ? $params['margin_footer'] : 8;
  43. $this->params['filename'] = isset($params['filename']) ? $params['filename'] : api_get_local_time();
  44. $this->params['pdf_title'] = isset($params['pdf_title']) ? $params['pdf_title'] : '';
  45. $this->params['course_info'] = isset($params['course_info']) ? $params['course_info'] : api_get_course_info();
  46. $this->params['session_info'] = isset($params['session_info']) ? $params['session_info'] : api_get_session_info(api_get_session_id());
  47. $this->params['course_code'] = isset($params['course_code']) ? $params['course_code'] : api_get_course_id();
  48. $this->params['add_signatures'] = isset($params['add_signatures']) ? $params['add_signatures'] : [];
  49. $this->params['show_real_course_teachers'] = isset($params['show_real_course_teachers']) ? $params['show_real_course_teachers'] : false;
  50. $this->params['student_info'] = isset($params['student_info']) ? $params['student_info'] : false;
  51. $this->params['show_grade_generated_date'] = isset($params['show_grade_generated_date']) ? $params['show_grade_generated_date'] : false;
  52. $this->params['show_teacher_as_myself'] = isset($params['show_teacher_as_myself']) ? $params['show_teacher_as_myself'] : true;
  53. $localTime = api_get_local_time();
  54. $this->params['pdf_date'] = isset($params['pdf_date']) ? $params['pdf_date'] : api_format_date($localTime, DATE_TIME_FORMAT_LONG);
  55. $this->params['pdf_date_only'] = isset($params['pdf_date']) ? $params['pdf_date'] : api_format_date($localTime, DATE_FORMAT_LONG);
  56. $this->pdf = new mPDF(
  57. 'UTF-8',
  58. $pageFormat,
  59. '',
  60. '',
  61. $params['left'],
  62. $params['right'],
  63. $params['top'],
  64. $params['bottom'],
  65. 8,
  66. 8,
  67. $orientation
  68. );
  69. $this->pdf->margin_footer = $params['margin_footer'];
  70. // Default value is 96 set in the mpdf library file config.php
  71. $value = api_get_configuration_value('pdf_img_dpi');
  72. if (!empty($value)) {
  73. $this->pdf->img_dpi = (int) $value;
  74. }
  75. }
  76. /**
  77. * Export the given HTML to PDF, using a global template.
  78. *
  79. * @uses \export/table_pdf.tpl
  80. *
  81. * @param string $content
  82. * @param bool|false $saveToFile
  83. * @param bool|false $returnHtml
  84. * @param bool $addDefaultCss (bootstrap/default/base.css)
  85. *
  86. * @return string
  87. */
  88. public function html_to_pdf_with_template(
  89. $content,
  90. $saveToFile = false,
  91. $returnHtml = false,
  92. $addDefaultCss = false
  93. ) {
  94. if (empty($this->template)) {
  95. $tpl = new Template('', false, false, false, false, true, false);
  96. } else {
  97. $tpl = $this->template;
  98. }
  99. // Assignments
  100. $tpl->assign('pdf_content', $content);
  101. // Showing only the current teacher/admin instead the all teacher list name see BT#4080
  102. $teacher_list = null;
  103. if (isset($this->params['show_real_course_teachers']) &&
  104. $this->params['show_real_course_teachers']
  105. ) {
  106. if (isset($this->params['session_info']) &&
  107. !empty($this->params['session_info'])
  108. ) {
  109. $teacher_list = SessionManager::getCoachesByCourseSessionToString(
  110. $this->params['session_info']['id'],
  111. $this->params['course_info']['real_id']
  112. );
  113. } else {
  114. $teacher_list = CourseManager::getTeacherListFromCourseCodeToString(
  115. $this->params['course_code']
  116. );
  117. }
  118. } else {
  119. $user_info = api_get_user_info();
  120. if ($this->params['show_teacher_as_myself']) {
  121. $teacher_list = $user_info['complete_name'];
  122. }
  123. }
  124. $tpl->assign('pdf_course', $this->params['course_code']);
  125. $tpl->assign('pdf_course_info', $this->params['course_info']);
  126. $tpl->assign('pdf_session_info', $this->params['session_info']);
  127. $tpl->assign('pdf_date', $this->params['pdf_date']);
  128. $tpl->assign('pdf_date_only', $this->params['pdf_date_only']);
  129. $tpl->assign('pdf_teachers', $teacher_list);
  130. $tpl->assign('pdf_title', $this->params['pdf_title']);
  131. $tpl->assign('pdf_student_info', $this->params['student_info']);
  132. $tpl->assign('show_grade_generated_date', $this->params['show_grade_generated_date']);
  133. $tpl->assign('add_signatures', $this->params['add_signatures']);
  134. // Getting template
  135. $tableTemplate = $tpl->get_template('export/table_pdf.tpl');
  136. $html = $tpl->fetch($tableTemplate);
  137. $html = api_utf8_encode($html);
  138. if ($returnHtml) {
  139. return $html;
  140. }
  141. $css_file = api_get_path(SYS_CSS_PATH).'themes/'.$tpl->theme.'/print.css';
  142. if (!file_exists($css_file)) {
  143. $css_file = api_get_path(SYS_CSS_PATH).'print.css';
  144. }
  145. $css = file_get_contents($css_file);
  146. self::content_to_pdf(
  147. $html,
  148. $css,
  149. $this->params['filename'],
  150. $this->params['course_code'],
  151. 'D',
  152. $saveToFile,
  153. null,
  154. $returnHtml,
  155. $addDefaultCss
  156. );
  157. }
  158. /**
  159. * Converts HTML files to PDF.
  160. *
  161. * @param mixed $html_file_array could be an html file path or an array
  162. * with paths example:
  163. * /var/www/myfile.html or array('/myfile.html','myotherfile.html') or
  164. * even an indexed array with both 'title' and 'path' indexes
  165. * for each element like
  166. * array(
  167. * 0 => array('title'=>'Hello','path'=>'file.html'),
  168. * 1 => array('title'=>'Bye','path'=>'file2.html')
  169. * );
  170. * @param string $pdf_name pdf name
  171. * @param string $course_code (if you are using html that are located
  172. * in the document tool you must provide this)
  173. * @param bool $print_title add title
  174. * @param bool $complete_style show header and footer if true
  175. * @param bool $addStyle
  176. * @param string $mainTitle
  177. *
  178. * @return false|null
  179. */
  180. public function html_to_pdf(
  181. $html_file_array,
  182. $pdf_name = '',
  183. $course_code = null,
  184. $print_title = false,
  185. $complete_style = true,
  186. $addStyle = true,
  187. $mainTitle = ''
  188. ) {
  189. if (empty($html_file_array)) {
  190. return false;
  191. }
  192. if (is_array($html_file_array)) {
  193. if (count($html_file_array) == 0) {
  194. return false;
  195. }
  196. } else {
  197. if (!file_exists($html_file_array)) {
  198. return false;
  199. }
  200. // Converting the string into an array
  201. $html_file_array = [$html_file_array];
  202. }
  203. if (!empty($course_code)) {
  204. $course_data = api_get_course_info($course_code);
  205. } else {
  206. $course_data = api_get_course_info();
  207. }
  208. // Clean styles and javascript document
  209. $clean_search = [
  210. '@<script[^>]*?>.*?</script>@si',
  211. '@<style[^>]*?>.*?</style>@si',
  212. ];
  213. // Formatting the pdf
  214. self::format_pdf($course_data, $complete_style);
  215. $counter = 1;
  216. foreach ($html_file_array as $file) {
  217. // Add a page break per file
  218. $page_break = '<pagebreak>';
  219. if ($counter == count($html_file_array)) {
  220. $page_break = '';
  221. }
  222. // if the array provided contained subarrays with 'title' entry,
  223. // then print the title in the PDF
  224. if (is_array($file) && isset($file['title'])) {
  225. $html_title = $file['title'];
  226. $file = $file['path'];
  227. } else {
  228. //we suppose we've only been sent a file path
  229. $html_title = basename($file);
  230. }
  231. $counter++;
  232. if (empty($file) && !empty($html_title)) {
  233. // this is a chapter, print title & skip the rest
  234. if ($counter === 2 && !empty($mainTitle)) {
  235. $this->pdf->WriteHTML(
  236. '<html><body><h2 style="text-align: center">'.$mainTitle.'</h2></body></html>'
  237. );
  238. }
  239. if ($print_title) {
  240. $this->pdf->WriteHTML(
  241. '<html><body><h3>'.$html_title.'</h3></body></html>'.$page_break
  242. );
  243. }
  244. continue;
  245. } else {
  246. if ($counter === 2 && !empty($mainTitle)) {
  247. $this->pdf->WriteHTML(
  248. '<html><body><h2 style="text-align: center">'.$mainTitle.'</h2></body></html>'
  249. );
  250. }
  251. }
  252. if (!file_exists($file)) {
  253. continue;
  254. }
  255. if ($addStyle) {
  256. $basicStyles = [
  257. api_get_path(SYS_PATH).'web/assets/bootstrap/dist/css/bootstrap.min.css',
  258. api_get_path(SYS_PATH).'web/css/base.css',
  259. api_get_path(SYS_PATH).'web/css/themes/'.api_get_visual_theme().'/default.css',
  260. api_get_path(SYS_PATH).'web/css/themes/'.api_get_visual_theme().'/print.css',
  261. ];
  262. foreach ($basicStyles as $style) {
  263. if (file_exists($style)) {
  264. $cssContent = file_get_contents($style);
  265. try {
  266. $this->pdf->WriteHTML($cssContent, 1);
  267. } catch (MpdfException $e) {
  268. error_log($e);
  269. }
  270. }
  271. }
  272. }
  273. // it's not a chapter but the file exists, print its title
  274. if ($print_title) {
  275. $this->pdf->WriteHTML(
  276. '<html><body><h3>'.$html_title.'</h3></body></html>'
  277. );
  278. }
  279. $file_info = pathinfo($file);
  280. $extension = $file_info['extension'];
  281. if (in_array($extension, ['html', 'htm'])) {
  282. $dirName = $file_info['dirname'];
  283. $filename = $file_info['basename'];
  284. $filename = str_replace('_', ' ', $filename);
  285. if ($extension === 'html') {
  286. $filename = basename($filename, '.html');
  287. } elseif ($extension === 'htm') {
  288. $filename = basename($filename, '.htm');
  289. }
  290. $document_html = @file_get_contents($file);
  291. $document_html = preg_replace($clean_search, '', $document_html);
  292. //absolute path for frames.css //TODO: necessary?
  293. $absolute_css_path = api_get_path(WEB_CODE_PATH).'css/'.api_get_setting('stylesheets').'/frames.css';
  294. $document_html = str_replace('href="./css/frames.css"', $absolute_css_path, $document_html);
  295. if (!empty($course_data['path'])) {
  296. $document_html = str_replace('../', '', $document_html);
  297. // Fix app/upload links convert web to system paths
  298. $document_html = str_replace(
  299. api_get_path(WEB_UPLOAD_PATH),
  300. api_get_path(SYS_UPLOAD_PATH),
  301. $document_html
  302. );
  303. }
  304. $document_html = self::fixImagesPaths($document_html, $course_data, $dirName);
  305. // The library mPDF expects UTF-8 encoded input data.
  306. api_set_encoding_html($document_html, 'UTF-8');
  307. // TODO: Maybe it is better idea the title to be passed through
  308. $title = api_get_title_html($document_html, 'UTF-8', 'UTF-8');
  309. // $_GET[] too, as it is done with file name.
  310. // At the moment the title is retrieved from the html document itself.
  311. if (empty($title)) {
  312. $title = $filename; // Here file name is expected to contain ASCII symbols only.
  313. }
  314. if (!empty($document_html)) {
  315. $this->pdf->WriteHTML($document_html.$page_break);
  316. }
  317. } elseif (in_array($extension, ['jpg', 'jpeg', 'png', 'gif'])) {
  318. // Images
  319. $image = Display::img($file);
  320. $this->pdf->WriteHTML('<html><body>'.$image.'</body></html>'.$page_break);
  321. }
  322. }
  323. if (empty($pdf_name)) {
  324. $output_file = 'pdf_'.date('Y-m-d-his').'.pdf';
  325. } else {
  326. $pdf_name = api_replace_dangerous_char($pdf_name);
  327. $output_file = $pdf_name.'.pdf';
  328. }
  329. // F to save the pdf in a file
  330. @$this->pdf->Output($output_file, 'D');
  331. exit;
  332. }
  333. /**
  334. * Converts an html string to PDF.
  335. *
  336. * @param string $document_html valid html
  337. * @param string $css CSS content of a CSS file
  338. * @param string $pdf_name pdf name
  339. * @param string $course_code course code
  340. * (if you are using html that are located in the document tool you must provide this)
  341. * @param string $outputMode the MPDF output mode can be:
  342. * @param bool $saveInFile
  343. * @param string $fileToSave
  344. * @param bool $returnHtml
  345. * @param bool $addDefaultCss
  346. * @param bool $completeHeader
  347. *
  348. * 'I' (print on standard output),
  349. * 'D' (download file) (this is the default value),
  350. * 'F' (save to local file) or
  351. * 'S' (return as a string)
  352. *
  353. * @throws MpdfException
  354. *
  355. * @return string Web path
  356. */
  357. public function content_to_pdf(
  358. $document_html,
  359. $css = '',
  360. $pdf_name = '',
  361. $course_code = null,
  362. $outputMode = 'D',
  363. $saveInFile = false,
  364. $fileToSave = null,
  365. $returnHtml = false,
  366. $addDefaultCss = false,
  367. $completeHeader = true
  368. ) {
  369. $urlAppend = api_get_configuration_value('url_append');
  370. if (empty($document_html)) {
  371. return false;
  372. }
  373. // clean styles and javascript document
  374. $clean_search = [
  375. '@<script[^>]*?>.*?</script>@si',
  376. '@<style[^>]*?>.*?</style>@siU',
  377. ];
  378. // Formatting the pdf
  379. $course_data = api_get_course_info($course_code);
  380. self::format_pdf($course_data, $completeHeader);
  381. $document_html = preg_replace($clean_search, '', $document_html);
  382. //absolute path for frames.css //TODO: necessary?
  383. $absolute_css_path = api_get_path(WEB_CSS_PATH).api_get_setting('stylesheets').'/frames.css';
  384. $document_html = str_replace('href="./css/frames.css"', 'href="'.$absolute_css_path.'"', $document_html);
  385. $document_html = str_replace('../../', '', $document_html);
  386. $document_html = str_replace('../', '', $document_html);
  387. $document_html = str_replace(
  388. (empty($urlAppend) ? '' : $urlAppend.'/').'courses/'.$course_code.'/document/',
  389. '',
  390. $document_html
  391. );
  392. if (!empty($course_data['path'])) {
  393. $document_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document/';
  394. $doc = new DOMDocument();
  395. @$doc->loadHTML($document_html);
  396. //Fixing only images @todo do the same thing with other elements
  397. $elements = $doc->getElementsByTagName('img');
  398. $protocol = api_get_protocol();
  399. $replaced = [];
  400. if (!empty($elements)) {
  401. foreach ($elements as $item) {
  402. $old_src = $item->getAttribute('src');
  403. if (in_array($old_src, $replaced)) {
  404. continue;
  405. }
  406. if (strpos($old_src, $protocol) === false) {
  407. if (strpos($old_src, '/main/default_course_document') === false) {
  408. if (strpos($old_src, '/main/inc/lib/') === false &&
  409. strpos($old_src, '/app/upload/') === false
  410. ) {
  411. $old_src_fixed = str_replace(
  412. api_get_path(REL_COURSE_PATH).$course_data['path'].'/document/',
  413. '',
  414. $old_src
  415. );
  416. $old_src_fixed = str_replace(
  417. 'courses/'.$course_data['path'].'/document/',
  418. '',
  419. $old_src_fixed
  420. );
  421. $new_path = $document_path.$old_src_fixed;
  422. $document_html = str_replace($old_src, $new_path, $document_html);
  423. $replaced[] = $old_src;
  424. }
  425. }
  426. }
  427. }
  428. }
  429. }
  430. // Use sys path to correct export images
  431. $document_html = str_replace(
  432. api_get_path(WEB_CODE_PATH).'img/',
  433. api_get_path(SYS_CODE_PATH).'img/',
  434. $document_html
  435. );
  436. $document_html = str_replace(api_get_path(WEB_ARCHIVE_PATH), api_get_path(SYS_ARCHIVE_PATH), $document_html);
  437. // The library mPDF expects UTF-8 encoded input data.
  438. api_set_encoding_html($document_html, 'UTF-8');
  439. // At the moment the title is retrieved from the html document itself.
  440. if ($returnHtml) {
  441. return "<style>$css</style>".$document_html;
  442. }
  443. if (!empty($css)) {
  444. try {
  445. $this->pdf->WriteHTML($css, 1);
  446. } catch (MpdfException $e) {
  447. error_log($e);
  448. }
  449. }
  450. if ($addDefaultCss) {
  451. $basicStyles = [
  452. api_get_path(SYS_PATH).'web/assets/bootstrap/dist/css/bootstrap.min.css',
  453. api_get_path(SYS_PATH).'web/css/base.css',
  454. api_get_path(SYS_PATH).'web/css/themes/'.api_get_visual_theme().'/default.css',
  455. api_get_path(SYS_PATH).'web/css/themes/'.api_get_visual_theme().'/print.css',
  456. ];
  457. foreach ($basicStyles as $style) {
  458. if (file_exists($style)) {
  459. $cssContent = file_get_contents($style);
  460. try {
  461. $this->pdf->WriteHTML($cssContent, 1);
  462. } catch (MpdfException $e) {
  463. error_log($e);
  464. }
  465. }
  466. }
  467. }
  468. try {
  469. $this->pdf->WriteHTML($document_html);
  470. } catch (MpdfException $e) {
  471. error_log($e);
  472. }
  473. if (empty($pdf_name)) {
  474. $output_file = 'pdf_'.date('Y-m-d-his').'.pdf';
  475. } else {
  476. $pdf_name = api_replace_dangerous_char($pdf_name);
  477. $output_file = $pdf_name.'.pdf';
  478. }
  479. if ($outputMode == 'F') {
  480. $output_file = api_get_path(SYS_ARCHIVE_PATH).$output_file;
  481. }
  482. if ($saveInFile) {
  483. $fileToSave = !empty($fileToSave) ? $fileToSave : api_get_path(SYS_ARCHIVE_PATH).uniqid();
  484. @$this->pdf->Output(
  485. $fileToSave,
  486. $outputMode
  487. ); // F to save the pdf in a file
  488. } else {
  489. @$this->pdf->Output(
  490. $output_file,
  491. $outputMode
  492. ); // F to save the pdf in a file
  493. }
  494. if ($outputMode != 'F') {
  495. exit;
  496. }
  497. return $output_file;
  498. }
  499. /**
  500. * Gets the watermark from the platform or a course.
  501. *
  502. * @param string course code (optional)
  503. * @param mixed web path of the watermark image, false if there is nothing to return
  504. *
  505. * @return string
  506. */
  507. public static function get_watermark($course_code = null)
  508. {
  509. $web_path = false;
  510. $urlId = api_get_current_access_url_id();
  511. if (!empty($course_code) && api_get_setting('pdf_export_watermark_by_course') == 'true') {
  512. $course_info = api_get_course_info($course_code);
  513. // course path
  514. $store_path = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/'.$urlId.'_pdf_watermark.png';
  515. if (file_exists($store_path)) {
  516. $web_path = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/'.$urlId.'_pdf_watermark.png';
  517. }
  518. } else {
  519. // course path
  520. $store_path = api_get_path(SYS_CODE_PATH).'default_course_document/images/'.$urlId.'_pdf_watermark.png';
  521. if (file_exists($store_path)) {
  522. $web_path = api_get_path(WEB_CODE_PATH).'default_course_document/images/'.$urlId.'_pdf_watermark.png';
  523. }
  524. }
  525. return $web_path;
  526. }
  527. /**
  528. * Deletes the watermark from the Platform or Course.
  529. *
  530. * @param string $course_code course code (optional)
  531. * @param mixed web path of the watermark image, false if there is nothing to return
  532. *
  533. * @return bool
  534. */
  535. public function delete_watermark($course_code = null)
  536. {
  537. $urlId = api_get_current_access_url_id();
  538. if (!empty($course_code) && api_get_setting('pdf_export_watermark_by_course') == 'true') {
  539. $course_info = api_get_course_info($course_code);
  540. // course path
  541. $store_path = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/'.$urlId.'_pdf_watermark.png';
  542. } else {
  543. // course path
  544. $store_path = api_get_path(SYS_CODE_PATH).'default_course_document/images/'.$urlId.'_pdf_watermark.png';
  545. }
  546. if (file_exists($store_path)) {
  547. unlink($store_path);
  548. return true;
  549. }
  550. return false;
  551. }
  552. /**
  553. * Uploads the pdf watermark in the main/default_course_document directory or in the course directory.
  554. *
  555. * @param string $filename filename
  556. * @param string $source_file path of the file
  557. * @param string $course_code
  558. *
  559. * @return mixed web path of the file if sucess, false otherwise
  560. */
  561. public function upload_watermark($filename, $source_file, $course_code = null)
  562. {
  563. $urlId = api_get_current_access_url_id();
  564. if (!empty($course_code) && api_get_setting('pdf_export_watermark_by_course') == 'true') {
  565. $course_info = api_get_course_info($course_code);
  566. $store_path = api_get_path(SYS_COURSE_PATH).$course_info['path']; // course path
  567. $web_path = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/pdf_watermark.png';
  568. } else {
  569. $store_path = api_get_path(SYS_CODE_PATH).'default_course_document/images'; // course path
  570. $web_path = api_get_path(WEB_CODE_PATH).'default_course_document/images/'.$urlId.'_pdf_watermark.png';
  571. }
  572. $course_image = $store_path.'/'.$urlId.'_pdf_watermark.png';
  573. if (file_exists($course_image)) {
  574. @unlink($course_image);
  575. }
  576. $my_image = new Image($source_file);
  577. $result = $my_image->send_image($course_image, -1, 'png');
  578. if ($result) {
  579. $result = $web_path;
  580. }
  581. return $result;
  582. }
  583. /**
  584. * Returns the default header.
  585. */
  586. public function get_header($course_code = null)
  587. {
  588. /*$header = api_get_setting('pdf_export_watermark_text');
  589. if (!empty($course_code) && api_get_setting('pdf_export_watermark_by_course') == 'true') {
  590. $header = api_get_course_setting('pdf_export_watermark_text');
  591. }
  592. return $header;*/
  593. }
  594. /**
  595. * Sets the PDF footer.
  596. */
  597. public function set_footer()
  598. {
  599. $this->pdf->defaultfooterfontsize = 12; // in pts
  600. $this->pdf->defaultfooterfontstyle = 'B'; // blank, B, I, or BI
  601. $this->pdf->defaultfooterline = 1; // 1 to include line below header/above footer
  602. $view = new Template('', false, false, false, true, false, false);
  603. $template = $view->get_template('export/pdf_footer.tpl');
  604. $footerHTML = $view->fetch($template);
  605. $this->pdf->SetHTMLFooter($footerHTML, 'E'); //Even pages
  606. $this->pdf->SetHTMLFooter($footerHTML, 'O'); //Odd pages
  607. }
  608. /**
  609. * Sets the PDF header.
  610. *
  611. * @param array $courseInfo
  612. */
  613. public function set_header($courseInfo)
  614. {
  615. $this->pdf->defaultheaderfontsize = 10; // in pts
  616. $this->pdf->defaultheaderfontstyle = 'BI'; // blank, B, I, or BI
  617. $this->pdf->defaultheaderline = 1; // 1 to include line below header/above footer
  618. $userId = api_get_user_id();
  619. if (!empty($courseInfo['code'])) {
  620. $teacher_list = CourseManager::get_teacher_list_from_course_code($courseInfo['code']);
  621. $teachers = '';
  622. if (!empty($teacher_list)) {
  623. foreach ($teacher_list as $teacher) {
  624. if ($teacher['user_id'] != $userId) {
  625. continue;
  626. }
  627. // Do not show the teacher list see BT#4080 only the current teacher name
  628. $teachers = api_get_person_name($teacher['firstname'], $teacher['lastname']);
  629. }
  630. }
  631. $organization = ChamiloApi::getPlatformLogo('', [], true);
  632. // Use custom logo image.
  633. $pdfLogo = api_get_setting('pdf_logo_header');
  634. if ($pdfLogo === 'true') {
  635. $visualTheme = api_get_visual_theme();
  636. $img = api_get_path(SYS_CSS_PATH).'themes/'.$visualTheme.'/images/pdf_logo_header.png';
  637. if (file_exists($img)) {
  638. //$img = api_get_path(WEB_CSS_PATH).'themes/'.$visualTheme.'/images/pdf_logo_header.png';
  639. $organization = "<img src='$img'>";
  640. }
  641. }
  642. $view = new Template('', false, false, false, true, false, false);
  643. $view->assign('teacher_name', $teachers);
  644. $view->assign('organization', $organization);
  645. $template = $view->get_template('export/pdf_header.tpl');
  646. $headerHTML = $view->fetch($template);
  647. $this->pdf->SetHTMLHeader($headerHTML, 'E');
  648. $this->pdf->SetHTMLHeader($headerHTML, 'O');
  649. }
  650. }
  651. /**
  652. * @param string $header html content
  653. */
  654. public function set_custom_header($header)
  655. {
  656. $this->custom_header = $header;
  657. }
  658. /**
  659. * @param array $footer html content
  660. */
  661. public function set_custom_footer($footer)
  662. {
  663. $this->custom_footer = $footer;
  664. }
  665. /**
  666. * Pre-formats a PDF to the right size and, if not stated otherwise, with
  667. * header, footer and watermark (if any).
  668. *
  669. * @param array $courseInfo General course information (to fill headers)
  670. * @param bool $complete Whether we want headers, footers and watermark or not
  671. */
  672. public function format_pdf($courseInfo, $complete = true)
  673. {
  674. $courseCode = null;
  675. if (!empty($courseInfo)) {
  676. $courseCode = $courseInfo['code'];
  677. }
  678. /*$pdf->SetAuthor('Documents Chamilo');
  679. $pdf->SetTitle('title');
  680. $pdf->SetSubject('Exported from Chamilo Documents');
  681. $pdf->SetKeywords('Chamilo Documents');
  682. */
  683. // TODO: To be read from the html document.
  684. $this->pdf->directionality = api_get_text_direction();
  685. $this->pdf->useOnlyCoreFonts = true;
  686. // Use different Odd/Even headers and footers and mirror margins
  687. $this->pdf->mirrorMargins = 1;
  688. // Add decoration only if not stated otherwise
  689. if ($complete) {
  690. // Adding watermark
  691. if (api_get_setting('pdf_export_watermark_enable') == 'true') {
  692. $watermark_file = self::get_watermark($courseCode);
  693. if ($watermark_file) {
  694. //http://mpdf1.com/manual/index.php?tid=269&searchstring=watermark
  695. $this->pdf->SetWatermarkImage($watermark_file);
  696. $this->pdf->showWatermarkImage = true;
  697. } else {
  698. $watermark_file = self::get_watermark(null);
  699. if ($watermark_file) {
  700. $this->pdf->SetWatermarkImage($watermark_file);
  701. $this->pdf->showWatermarkImage = true;
  702. }
  703. }
  704. if ($courseCode) {
  705. $watermark_text = api_get_course_setting('pdf_export_watermark_text');
  706. if (empty($watermark_text)) {
  707. $watermark_text = api_get_setting('pdf_export_watermark_text');
  708. }
  709. } else {
  710. $watermark_text = api_get_setting('pdf_export_watermark_text');
  711. }
  712. if (!empty($watermark_text)) {
  713. $this->pdf->SetWatermarkText(
  714. strcode2utf($watermark_text),
  715. 0.1
  716. );
  717. $this->pdf->showWatermarkText = true;
  718. }
  719. }
  720. if (empty($this->custom_header)) {
  721. self::set_header($courseInfo);
  722. } else {
  723. $this->pdf->SetHTMLHeader($this->custom_header, 'E');
  724. $this->pdf->SetHTMLHeader($this->custom_header, 'O');
  725. }
  726. if (empty($this->custom_footer)) {
  727. self::set_footer();
  728. } else {
  729. $this->pdf->SetHTMLFooter($this->custom_footer);
  730. }
  731. }
  732. }
  733. /**
  734. * Generate a PDF file from $html in SYS_APP_PATH.
  735. *
  736. * @param string $html PDF content
  737. * @param string $fileName File name
  738. * @param string $dest Optional. Directory to move file
  739. *
  740. * @return string The PDF path
  741. */
  742. public function exportFromHtmlToFile($html, $fileName, $dest = null)
  743. {
  744. $this->template = $this->template ?: new Template('', false, false, false, false, false, false);
  745. $cssFile = api_get_path(SYS_CSS_PATH).'themes/'.$this->template->theme.'/print.css';
  746. if (!file_exists($cssFile)) {
  747. $cssFile = api_get_path(SYS_CSS_PATH).'print.css';
  748. }
  749. $pdfPath = self::content_to_pdf(
  750. $html,
  751. file_get_contents($cssFile),
  752. $fileName,
  753. $this->params['course_code'],
  754. 'F'
  755. );
  756. if (!$dest) {
  757. return $pdfPath;
  758. }
  759. move($pdfPath, $dest);
  760. return $dest.basename($pdfPath);
  761. }
  762. /**
  763. * Create a PDF and save it into the documents area.
  764. *
  765. * @param string $htmlContent HTML Content
  766. * @param string $fileName The file name
  767. * @param int $courseId The course ID
  768. * @param int $sessionId Optional. The session ID
  769. */
  770. public function exportFromHtmlToDocumentsArea(
  771. $htmlContent,
  772. $fileName,
  773. $courseId,
  774. $sessionId = 0
  775. ) {
  776. $userId = api_get_user_id();
  777. $courseInfo = api_get_course_info_by_id($courseId);
  778. $courseDirectory = api_get_path(SYS_COURSE_PATH).$courseInfo['directory'].'/document/';
  779. $docPath = $this->exportFromHtmlToFile(
  780. $htmlContent,
  781. $fileName,
  782. $courseDirectory
  783. );
  784. $docId = add_document(
  785. $courseInfo,
  786. str_replace($courseDirectory, '/', $docPath),
  787. 'file',
  788. filesize($docPath),
  789. $fileName,
  790. null,
  791. false,
  792. true,
  793. null,
  794. $sessionId,
  795. $userId
  796. );
  797. api_item_property_update(
  798. $courseInfo,
  799. TOOL_DOCUMENT,
  800. $docId,
  801. 'DocumentAdded',
  802. $userId
  803. );
  804. Display::addFlash(Display::return_message(get_lang('ItemAdded')));
  805. }
  806. /**
  807. * @param string $theme
  808. *
  809. * @throws MpdfException
  810. */
  811. public function setBackground($theme)
  812. {
  813. $themeName = empty($theme) ? api_get_visual_theme() : $theme;
  814. $themeDir = \Template::getThemeDir($themeName);
  815. $customLetterhead = $themeDir.'images/letterhead.png';
  816. $urlPathLetterhead = api_get_path(SYS_CSS_PATH).$customLetterhead;
  817. $urlWebLetterhead = '#FFFFFF';
  818. $fullPage = false;
  819. if (file_exists($urlPathLetterhead)) {
  820. $fullPage = true;
  821. $urlWebLetterhead = 'url('.api_get_path(WEB_CSS_PATH).$customLetterhead.')';
  822. }
  823. if ($fullPage) {
  824. $this->pdf->SetDisplayMode('fullpage');
  825. $this->pdf->SetDefaultBodyCSS('background', $urlWebLetterhead);
  826. $this->pdf->SetDefaultBodyCSS('background-image-resize', '6');
  827. }
  828. }
  829. /**
  830. * Fix images source paths to allow export to pdf.
  831. *
  832. * @param string $documentHtml
  833. * @param array $courseInfo
  834. * @param string $dirName
  835. *
  836. * @return string
  837. */
  838. private static function fixImagesPaths($documentHtml, array $courseInfo, $dirName = '')
  839. {
  840. $documentHtml = '<?xml encoding="utf-8" ?>'.$documentHtml;
  841. $doc = new DOMDocument();
  842. @$doc->loadHTML($documentHtml);
  843. $elements = $doc->getElementsByTagName('img');
  844. if (empty($elements)) {
  845. return $doc->saveHTML();
  846. }
  847. $protocol = api_get_protocol();
  848. $sysCodePath = api_get_path(SYS_CODE_PATH);
  849. $sysCoursePath = api_get_path(SYS_COURSE_PATH);
  850. $sysUploadPath = api_get_path(SYS_UPLOAD_PATH);
  851. $documentPath = $courseInfo ? $sysCoursePath.$courseInfo['path'].'/document/' : '';
  852. /** @var \DOMElement $element */
  853. foreach ($elements as $element) {
  854. $src = $element->getAttribute('src');
  855. $src = trim($src);
  856. if (strpos($src, $protocol) !== false) {
  857. continue;
  858. }
  859. // It's a reference to a file in the system, do not change it
  860. if (file_exists($src)) {
  861. continue;
  862. }
  863. if (strpos($src, '/main/default_course_document') === 0) {
  864. $element->setAttribute(
  865. 'src',
  866. str_replace('/main/default_course_document', $sysCodePath.'default_course_document', $src)
  867. );
  868. continue;
  869. }
  870. if (strpos($src, '/main/img') === 0) {
  871. $element->setAttribute(
  872. 'src',
  873. str_replace('/main/img/', $sysCodePath.'img/', $src)
  874. );
  875. continue;
  876. }
  877. if (strpos($src, '/app/upload/') === 0) {
  878. $element->setAttribute(
  879. 'src',
  880. str_replace('/app/upload/', $sysUploadPath, $src)
  881. );
  882. continue;
  883. }
  884. if (empty($courseInfo)) {
  885. continue;
  886. }
  887. if (api_get_path(REL_PATH) != '/') {
  888. $oldSrcFixed = str_replace(
  889. api_get_path(REL_PATH).'courses/'.$courseInfo['path'].'/document/',
  890. '',
  891. $src
  892. );
  893. // Try with the dirname if exists
  894. if ($oldSrcFixed == $src) {
  895. if (file_exists($dirName.'/'.$src)) {
  896. $documentPath = '';
  897. $oldSrcFixed = $dirName.'/'.$src;
  898. }
  899. }
  900. } else {
  901. if (strpos($src, 'courses/'.$courseInfo['path'].'/document/') !== false) {
  902. $oldSrcFixed = str_replace('courses/'.$courseInfo['path'].'/document/', '', $src);
  903. } else {
  904. // Try with the dirname if exists
  905. if (file_exists($dirName.'/'.$src)) {
  906. $documentPath = '';
  907. $oldSrcFixed = $dirName.'/'.$src;
  908. } else {
  909. $documentPath = '';
  910. $oldSrcFixed = $src;
  911. }
  912. }
  913. }
  914. $element->setAttribute('src', $documentPath.$oldSrcFixed);
  915. }
  916. return $doc->saveHTML();
  917. }
  918. }