pdf.lib.php 36 KB

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