pdf.lib.php 36 KB

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