pdf.lib.php 35 KB

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