pdf.lib.php 35 KB

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