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 = array();
  13. public $custom_footer = array();
  14. public $params = array();
  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 = array(),
  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, array('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 = 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 = array(
  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, array('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, array('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 = array(
  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. //replace relative path by absolute path for resources
  442. //$document_html= str_replace('src="/chamilo/main/default_course_document/', 'temp_template_path', $document_html);// before save src templates not apply
  443. //$document_html= str_replace('src="/', 'temp_template_path', $document_html);// before save src templates not apply
  444. //$document_html= str_replace('src="/chamilo/main/default_course_document/', 'temp_template_path', $document_html);// before save src templates not apply
  445. //$src_http_www= 'src="'.api_get_path(WEB_COURSE_PATH).$course_data['path'].'/document/';
  446. //$document_html= str_replace('src="',$src_http_www, $document_html);
  447. //$document_html= str_replace('temp_template_path', 'src="/main/default_course_document/', $document_html);// restore src templates
  448. // The library mPDF expects UTF-8 encoded input data.
  449. api_set_encoding_html($document_html, 'UTF-8');
  450. // TODO: Maybe it is better idea the title to be passed through
  451. $title = api_get_title_html($document_html, 'UTF-8', 'UTF-8');
  452. // $_GET[] too, as it is done with file name.
  453. // At the moment the title is retrieved from the html document itself.
  454. if ($returnHtml) {
  455. return "<style>$css</style>".$document_html;
  456. }
  457. if (!empty($css)) {
  458. $this->pdf->WriteHTML($css, 1);
  459. }
  460. if ($addDefaultCss) {
  461. $basicStyles = [
  462. api_get_path(SYS_PATH).'web/assets/bootstrap/dist/css/bootstrap.min.css',
  463. api_get_path(SYS_PATH).'web/css/base.css',
  464. api_get_path(SYS_PATH).'web/css/themes/'.api_get_visual_theme().'/default.css'
  465. ];
  466. foreach ($basicStyles as $style) {
  467. $cssContent = file_get_contents($style);
  468. $this->pdf->WriteHTML($cssContent, 1);
  469. }
  470. }
  471. $this->pdf->WriteHTML($document_html);
  472. if (empty($pdf_name)) {
  473. $output_file = 'pdf_'.date('Y-m-d-his').'.pdf';
  474. } else {
  475. $pdf_name = api_replace_dangerous_char($pdf_name);
  476. $output_file = $pdf_name.'.pdf';
  477. }
  478. if ($outputMode == 'F') {
  479. $output_file = api_get_path(SYS_ARCHIVE_PATH).$output_file;
  480. }
  481. if ($saveInFile) {
  482. $fileToSave = !empty($fileToSave) ? $fileToSave : api_get_path(SYS_ARCHIVE_PATH).uniqid();
  483. $this->pdf->Output(
  484. $fileToSave,
  485. $outputMode
  486. ); // F to save the pdf in a file
  487. } else {
  488. $this->pdf->Output(
  489. $output_file,
  490. $outputMode
  491. ); // F to save the pdf in a file
  492. }
  493. if ($outputMode != 'F') {
  494. exit;
  495. }
  496. return $output_file;
  497. }
  498. /**
  499. * Gets the watermark from the platform or a course
  500. * @param string course code (optional)
  501. * @param mixed web path of the watermark image, false if there is nothing to return
  502. * @return string
  503. */
  504. public static function get_watermark($course_code = null)
  505. {
  506. $web_path = false;
  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. if (file_exists($store_path)) {
  513. $web_path = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/'.$urlId.'_pdf_watermark.png';
  514. }
  515. } else {
  516. // course path
  517. $store_path = api_get_path(SYS_CODE_PATH).'default_course_document/images/'.$urlId.'_pdf_watermark.png';
  518. if (file_exists($store_path)) {
  519. $web_path = api_get_path(WEB_CODE_PATH).'default_course_document/images/'.$urlId.'_pdf_watermark.png';
  520. }
  521. }
  522. return $web_path;
  523. }
  524. /**
  525. * Deletes the watermark from the Platform or Course
  526. * @param string $course_code course code (optional)
  527. * @param mixed web path of the watermark image, false if there is nothing to return
  528. * @return bool
  529. */
  530. public function delete_watermark($course_code = null)
  531. {
  532. $urlId = api_get_current_access_url_id();
  533. if (!empty($course_code) && api_get_setting('pdf_export_watermark_by_course') == 'true') {
  534. $course_info = api_get_course_info($course_code);
  535. // course path
  536. $store_path = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/'.$urlId.'_pdf_watermark.png';
  537. } else {
  538. // course path
  539. $store_path = api_get_path(SYS_CODE_PATH).'default_course_document/images/'.$urlId.'_pdf_watermark.png';
  540. }
  541. if (file_exists($store_path)) {
  542. unlink($store_path);
  543. return true;
  544. }
  545. return false;
  546. }
  547. /**
  548. * Uploads the pdf watermark in the main/default_course_document directory or in the course directory
  549. * @param string $filename filename
  550. * @param string $source_file path of the file
  551. * @param string $course_code
  552. * @return mixed web path of the file if sucess, false otherwise
  553. */
  554. public function upload_watermark($filename, $source_file, $course_code = null)
  555. {
  556. $urlId = api_get_current_access_url_id();
  557. if (!empty($course_code) && api_get_setting('pdf_export_watermark_by_course') == 'true') {
  558. $course_info = api_get_course_info($course_code);
  559. $store_path = api_get_path(SYS_COURSE_PATH).$course_info['path']; // course path
  560. $web_path = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/pdf_watermark.png';
  561. } else {
  562. $store_path = api_get_path(SYS_CODE_PATH).'default_course_document/images'; // course path
  563. $web_path = api_get_path(WEB_CODE_PATH).'default_course_document/images/'.$urlId.'_pdf_watermark.png';
  564. }
  565. $course_image = $store_path.'/'.$urlId.'_pdf_watermark.png';
  566. if (file_exists($course_image)) {
  567. @unlink($course_image);
  568. }
  569. $my_image = new Image($source_file);
  570. $result = $my_image->send_image($course_image, -1, 'png');
  571. if ($result) {
  572. $result = $web_path;
  573. }
  574. return $result;
  575. }
  576. /**
  577. * Returns the default header
  578. */
  579. public function get_header($course_code = null)
  580. {
  581. /*$header = api_get_setting('pdf_export_watermark_text');
  582. if (!empty($course_code) && api_get_setting('pdf_export_watermark_by_course') == 'true') {
  583. $header = api_get_course_setting('pdf_export_watermark_text');
  584. }
  585. return $header;*/
  586. }
  587. /**
  588. * Sets the PDF footer
  589. */
  590. public function set_footer()
  591. {
  592. $this->pdf->defaultfooterfontsize = 12; // in pts
  593. $this->pdf->defaultfooterfontstyle = 'B'; // blank, B, I, or BI
  594. $this->pdf->defaultfooterline = 1; // 1 to include line below header/above footer
  595. $view = new Template('', false, false, false, true, false, false);
  596. $template = $view->get_template('export/pdf_footer.tpl');
  597. $footerHTML = $view->fetch($template);
  598. $this->pdf->SetHTMLFooter($footerHTML, 'E'); //Even pages
  599. $this->pdf->SetHTMLFooter($footerHTML, 'O'); //Odd pages
  600. }
  601. /**
  602. * Sets the PDF header
  603. * @param array $course_data
  604. */
  605. public function set_header($course_data)
  606. {
  607. $this->pdf->defaultheaderfontsize = 10; // in pts
  608. $this->pdf->defaultheaderfontstyle = 'BI'; // blank, B, I, or BI
  609. $this->pdf->defaultheaderline = 1; // 1 to include line below header/above footer
  610. $userId = api_get_user_id();
  611. if (!empty($course_data['code'])) {
  612. $teacher_list = CourseManager::get_teacher_list_from_course_code($course_data['code']);
  613. $teachers = '';
  614. if (!empty($teacher_list)) {
  615. foreach ($teacher_list as $teacher) {
  616. if ($teacher['user_id'] != $userId) {
  617. continue;
  618. }
  619. // Do not show the teacher list see BT#4080 only the current teacher name
  620. $teachers = api_get_person_name($teacher['firstname'], $teacher['lastname']);
  621. }
  622. }
  623. $organization = ChamiloApi::getPlatformLogo('', [], true);
  624. // Use custom logo image.
  625. $pdfLogo = api_get_setting('pdf_logo_header');
  626. if ($pdfLogo === 'true') {
  627. $visualTheme = api_get_visual_theme();
  628. $img = api_get_path(SYS_CSS_PATH).'themes/'.$visualTheme.'/images/pdf_logo_header.png';
  629. if (file_exists($img)) {
  630. //$img = api_get_path(WEB_CSS_PATH).'themes/'.$visualTheme.'/images/pdf_logo_header.png';
  631. $organization = "<img src='$img'>";
  632. }
  633. }
  634. $view = new Template('', false, false, false, true, false, false);
  635. $view->assign('teacher_name', $teachers);
  636. $view->assign('organization', $organization);
  637. $template = $view->get_template('export/pdf_header.tpl');
  638. $headerHTML = $view->fetch($template);
  639. $this->pdf->SetHTMLHeader($headerHTML, 'E');
  640. $this->pdf->SetHTMLHeader($headerHTML, 'O');
  641. }
  642. }
  643. /**
  644. * @param string $header html content
  645. */
  646. public function set_custom_header($header)
  647. {
  648. $this->custom_header = $header;
  649. }
  650. /**
  651. * @param array $footer html content
  652. */
  653. public function set_custom_footer($footer)
  654. {
  655. $this->custom_footer = $footer;
  656. }
  657. /**
  658. * Pre-formats a PDF to the right size and, if not stated otherwise, with
  659. * header, footer and watermark (if any)
  660. * @param array $course_data General course information (to fill headers)
  661. * @param bool $complete Whether we want headers, footers and watermark or not
  662. */
  663. public function format_pdf($course_data, $complete = true)
  664. {
  665. $course_code = null;
  666. if (!empty($course_data)) {
  667. $course_code = $course_data['code'];
  668. }
  669. /*$pdf->SetAuthor('Documents Chamilo');
  670. $pdf->SetTitle('title');
  671. $pdf->SetSubject('Exported from Chamilo Documents');
  672. $pdf->SetKeywords('Chamilo Documents');
  673. */
  674. // TODO: To be read from the html document.
  675. $this->pdf->directionality = api_get_text_direction();
  676. $this->pdf->useOnlyCoreFonts = true;
  677. // Use different Odd/Even headers and footers and mirror margins
  678. $this->pdf->mirrorMargins = 1;
  679. // Add decoration only if not stated otherwise
  680. if ($complete) {
  681. // Adding watermark
  682. if (api_get_setting('pdf_export_watermark_enable') == 'true') {
  683. $watermark_file = self::get_watermark($course_code);
  684. if ($watermark_file) {
  685. //http://mpdf1.com/manual/index.php?tid=269&searchstring=watermark
  686. $this->pdf->SetWatermarkImage($watermark_file);
  687. $this->pdf->showWatermarkImage = true;
  688. } else {
  689. $watermark_file = self::get_watermark(null);
  690. if ($watermark_file) {
  691. $this->pdf->SetWatermarkImage($watermark_file);
  692. $this->pdf->showWatermarkImage = true;
  693. }
  694. }
  695. if ($course_code) {
  696. $watermark_text = api_get_course_setting('pdf_export_watermark_text');
  697. if (empty($watermark_text)) {
  698. $watermark_text = api_get_setting('pdf_export_watermark_text');
  699. }
  700. } else {
  701. $watermark_text = api_get_setting('pdf_export_watermark_text');
  702. }
  703. if (!empty($watermark_text)) {
  704. $this->pdf->SetWatermarkText(
  705. strcode2utf($watermark_text),
  706. 0.1
  707. );
  708. $this->pdf->showWatermarkText = true;
  709. }
  710. }
  711. if (empty($this->custom_header)) {
  712. self::set_header($course_data);
  713. } else {
  714. $this->pdf->SetHTMLHeader($this->custom_header, 'E');
  715. $this->pdf->SetHTMLHeader($this->custom_header, 'O');
  716. }
  717. if (empty($this->custom_footer)) {
  718. self::set_footer();
  719. } else {
  720. $this->pdf->SetHTMLFooter($this->custom_footer);
  721. }
  722. }
  723. }
  724. /**
  725. * Generate a PDF file from $html in SYS_APP_PATH
  726. *
  727. * @param string $html PDF content
  728. * @param string $fileName File name
  729. * @param string $dest Optional. Directory to move file
  730. * @return string The PDF path
  731. */
  732. public function exportFromHtmlToFile($html, $fileName, $dest = null)
  733. {
  734. $this->template = $this->template ?: new Template('', false, false, false, false, false, false);
  735. $cssFile = api_get_path(SYS_CSS_PATH).'themes/'.$this->template->theme.'/print.css';
  736. if (!file_exists($cssFile)) {
  737. $cssFile = api_get_path(SYS_CSS_PATH).'print.css';
  738. }
  739. $pdfPath = self::content_to_pdf(
  740. $html,
  741. file_get_contents($cssFile),
  742. $fileName,
  743. $this->params['course_code'],
  744. 'F'
  745. );
  746. if (!$dest) {
  747. return $pdfPath;
  748. }
  749. move($pdfPath, $dest);
  750. return $dest.basename($pdfPath);
  751. }
  752. /**
  753. * Create a PDF and save it into the documents area
  754. * @param string $htmlContent HTML Content
  755. * @param string $fileName The file name
  756. * @param integer $courseId The course ID
  757. * @param int $sessionId Optional. The session ID
  758. */
  759. public function exportFromHtmlToDocumentsArea(
  760. $htmlContent,
  761. $fileName,
  762. $courseId,
  763. $sessionId = 0
  764. ) {
  765. $userId = api_get_user_id();
  766. $courseInfo = api_get_course_info_by_id($courseId);
  767. $courseDirectory = api_get_path(SYS_COURSE_PATH).$courseInfo['directory'].'/document/';
  768. $docPath = $this->exportFromHtmlToFile(
  769. $htmlContent,
  770. $fileName,
  771. $courseDirectory
  772. );
  773. $docId = add_document(
  774. $courseInfo,
  775. str_replace($courseDirectory, '/', $docPath),
  776. 'file',
  777. filesize($docPath),
  778. $fileName,
  779. null,
  780. false,
  781. true,
  782. null,
  783. $sessionId,
  784. $userId
  785. );
  786. api_item_property_update(
  787. $courseInfo,
  788. TOOL_DOCUMENT,
  789. $docId,
  790. 'DocumentAdded',
  791. $userId
  792. );
  793. Display::addFlash(Display::return_message(get_lang('ItemAdded')));
  794. }
  795. }