-
Notifications
You must be signed in to change notification settings - Fork 68
/
action.php
1122 lines (980 loc) · 37.3 KB
/
action.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
use dokuwiki\Cache\Cache;
use dokuwiki\Extension\ActionPlugin;
use dokuwiki\Extension\Event;
use dokuwiki\Extension\EventHandler;
use dokuwiki\plugin\dw2pdf\MenuItem;
use dokuwiki\StyleUtils;
use Mpdf\MpdfException;
/**
* dw2Pdf Plugin: Conversion from dokuwiki content to pdf.
*
* Export html content to pdf, for different url parameter configurations
* DokuPDF which extends mPDF is used for generating the pdf from html.
*
* @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
* @author Luigi Micco <l.micco@tiscali.it>
* @author Andreas Gohr <andi@splitbrain.org>
*/
class action_plugin_dw2pdf extends ActionPlugin
{
/**
* Settings for current export, collected from url param, plugin config, global config
*
* @var array
*/
protected $exportConfig;
/** @var string template name, to use templates from dw2pdf/tpl/<template name> */
protected $tpl;
/** @var string title of exported pdf */
protected $title;
/** @var array list of pages included in exported pdf */
protected $list = [];
/** @var bool|string path to temporary cachefile */
protected $onetimefile = false;
protected $currentBookChapter = 0;
/**
* Constructor. Sets the correct template
*/
public function __construct()
{
require_once __DIR__ . '/vendor/autoload.php';
$this->tpl = $this->getExportConfig('template');
}
/**
* Delete cached files that were for one-time use
*/
public function __destruct()
{
if ($this->onetimefile) {
unlink($this->onetimefile);
}
}
/**
* Return the value of currentBookChapter, which is the order of the file to be added in a book generation
*/
public function getCurrentBookChapter()
{
return $this->currentBookChapter;
}
/**
* Register the events
*
* @param EventHandler $controller
*/
public function register(EventHandler $controller)
{
$controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'convert');
$controller->register_hook('TEMPLATE_PAGETOOLS_DISPLAY', 'BEFORE', $this, 'addbutton');
$controller->register_hook('MENU_ITEMS_ASSEMBLY', 'AFTER', $this, 'addsvgbutton');
}
/**
* Do the HTML to PDF conversion work
*
* @param Event $event
*/
public function convert(Event $event)
{
global $REV, $DATE_AT;
global $conf, $INPUT;
// our event?
$allowedEvents = ['export_pdfbook', 'export_pdf', 'export_pdfns'];
if (!in_array($event->data, $allowedEvents)) {
return;
}
try {
//collect pages and check permissions
[$this->title, $this->list] = $this->collectExportablePages($event);
if ($event->data === 'export_pdf' && ($REV || $DATE_AT)) {
$cachefile = tempnam($conf['tmpdir'] . '/dwpdf', 'dw2pdf_');
$this->onetimefile = $cachefile;
$generateNewPdf = true;
} else {
// prepare cache and its dependencies
$depends = [];
$cache = $this->prepareCache($depends);
$cachefile = $cache->cache;
$generateNewPdf = !$this->getConf('usecache')
|| $this->getExportConfig('isDebug')
|| !$cache->useCache($depends);
}
// hard work only when no cache available or needed for debugging
if ($generateNewPdf) {
// generating the pdf may take a long time for larger wikis / namespaces with many pages
set_time_limit(0);
//may throw Mpdf\MpdfException as well
$this->generatePDF($cachefile, $event);
}
} catch (Exception $e) {
if ($INPUT->has('selection')) {
http_status(400);
echo $e->getMessage();
exit();
} else {
//prevent Action/Export()
msg($e->getMessage(), -1);
$event->data = 'redirect';
return;
}
}
$event->preventDefault(); // after prevent, $event->data cannot be changed
// deliver the file
$this->sendPDFFile($cachefile); //exits
}
/**
* Obtain list of pages and title, for different methods of exporting the pdf.
* - Return a title and selection, throw otherwise an exception
* - Check permisions
*
* @param Event $event
* @return array
* @throws Exception
*/
protected function collectExportablePages(Event $event)
{
global $ID, $REV;
global $INPUT;
global $conf, $lang;
// list of one or multiple pages
$list = [];
if ($event->data == 'export_pdf') {
if (auth_quickaclcheck($ID) < AUTH_READ) { // set more specific denied message
throw new Exception($lang['accessdenied']);
}
$list[0] = $ID;
$title = $INPUT->str('pdftitle'); //DEPRECATED
$title = $INPUT->str('book_title', $title, true);
if (empty($title)) {
$title = p_get_first_heading($ID);
}
// use page name if title is still empty
if (empty($title)) {
$title = noNS($ID);
}
$filename = wikiFN($ID, $REV);
if (!file_exists($filename)) {
throw new Exception($this->getLang('notexist'));
}
} elseif ($event->data == 'export_pdfns') {
//check input for title and ns
if (!$title = $INPUT->str('book_title')) {
throw new Exception($this->getLang('needtitle'));
}
$pdfnamespace = cleanID($INPUT->str('book_ns'));
if (!@is_dir(dirname(wikiFN($pdfnamespace . ':dummy')))) {
throw new Exception($this->getLang('needns'));
}
//sort order
$order = $INPUT->str('book_order', 'natural', true);
$sortoptions = ['pagename', 'date', 'natural'];
if (!in_array($order, $sortoptions)) {
$order = 'natural';
}
//search depth
$depth = $INPUT->int('book_nsdepth', 0);
if ($depth < 0) {
$depth = 0;
}
//page search
$result = [];
$opts = ['depth' => $depth]; //recursive all levels
$dir = utf8_encodeFN(str_replace(':', '/', $pdfnamespace));
search($result, $conf['datadir'], 'search_allpages', $opts, $dir);
// exclude ids
$excludes = $INPUT->arr('excludes');
if (!empty($excludes)) {
$result = array_filter($result, function ($item) use ($excludes) {
return !in_array($item['id'], $excludes);
});
}
// exclude namespaces
$excludesns = $INPUT->arr('excludesns');
if (!empty($excludesns)) {
$result = array_filter($result, function ($item) use ($excludesns) {
foreach ($excludesns as $ns) {
if (strpos($item['id'], $ns . ':') === 0) {
return false;
}
}
return true;
});
}
//sorting
if (count($result) > 0) {
if ($order == 'date') {
usort($result, [$this, 'cbDateSort']);
} elseif ($order == 'pagename' || $order == 'natural') {
usort($result, [$this, 'cbPagenameSort']);
}
}
foreach ($result as $item) {
$list[] = $item['id'];
}
if ($pdfnamespace !== '') {
if (!in_array($pdfnamespace . ':' . $conf['start'], $list, true)) {
if (file_exists(wikiFN(rtrim($pdfnamespace, ':')))) {
array_unshift($list, rtrim($pdfnamespace, ':'));
}
}
}
} elseif (!empty($_COOKIE['list-pagelist'])) {
/** @deprecated April 2016 replaced by localStorage version of Bookcreator */
//is in Bookmanager of bookcreator plugin a title given?
$title = $INPUT->str('pdfbook_title'); //DEPRECATED
$title = $INPUT->str('book_title', $title, true);
if (empty($title)) {
throw new Exception($this->getLang('needtitle'));
}
$list = explode("|", $_COOKIE['list-pagelist']);
} elseif ($INPUT->has('selection')) {
//handle Bookcreator requests based at localStorage
// if(!checkSecurityToken()) {
// http_status(403);
// print $this->getLang('empty');
// exit();
// }
$list = json_decode($INPUT->str('selection', '', true), true);
if (!is_array($list) || $list === []) {
throw new Exception($this->getLang('empty'));
}
$title = $INPUT->str('pdfbook_title'); //DEPRECATED
$title = $INPUT->str('book_title', $title, true);
if (empty($title)) {
throw new Exception($this->getLang('needtitle'));
}
} elseif ($INPUT->has('savedselection')) {
//export a saved selection of the Bookcreator Plugin
if (plugin_isdisabled('bookcreator')) {
throw new Exception($this->getLang('missingbookcreator'));
}
/** @var action_plugin_bookcreator_handleselection $SelectionHandling */
$SelectionHandling = plugin_load('action', 'bookcreator_handleselection');
$savedselection = $SelectionHandling->loadSavedSelection($INPUT->str('savedselection'));
$title = $savedselection['title'];
$title = $INPUT->str('book_title', $title, true);
$list = $savedselection['selection'];
if (empty($title)) {
throw new Exception($this->getLang('needtitle'));
}
} else {
//show empty bookcreator message
throw new Exception($this->getLang('empty'));
}
$list = array_map('cleanID', $list);
$skippedpages = [];
foreach ($list as $index => $pageid) {
if (auth_quickaclcheck($pageid) < AUTH_READ) {
$skippedpages[] = $pageid;
unset($list[$index]);
}
}
$list = array_filter($list, 'strlen'); //use of strlen() callback prevents removal of pagename '0'
//if selection contains forbidden pages throw (overridable) warning
if (!$INPUT->bool('book_skipforbiddenpages') && $skippedpages !== []) {
$msg = hsc(implode(', ', $skippedpages));
throw new Exception(sprintf($this->getLang('forbidden'), $msg));
}
return [$title, $list];
}
/**
* Prepare cache
*
* @param array $depends (reference) array with dependencies
* @return cache
*/
protected function prepareCache(&$depends)
{
global $REV;
$cachekey = implode(',', $this->list)
. $REV
. $this->getExportConfig('template')
. $this->getExportConfig('pagesize')
. $this->getExportConfig('orientation')
. $this->getExportConfig('font-size')
. $this->getExportConfig('doublesided')
. $this->getExportConfig('headernumber')
. ($this->getExportConfig('hasToC') ? implode('-', $this->getExportConfig('levels')) : '0')
. $this->title;
$cache = new Cache($cachekey, '.dw2.pdf');
$dependencies = [];
foreach ($this->list as $pageid) {
$relations = p_get_metadata($pageid, 'relation');
if (is_array($relations)) {
if (array_key_exists('media', $relations) && is_array($relations['media'])) {
foreach ($relations['media'] as $mediaid => $exists) {
if ($exists) {
$dependencies[] = mediaFN($mediaid);
}
}
}
if (array_key_exists('haspart', $relations) && is_array($relations['haspart'])) {
foreach ($relations['haspart'] as $part_pageid => $exists) {
if ($exists) {
$dependencies[] = wikiFN($part_pageid);
}
}
}
}
$dependencies[] = metaFN($pageid, '.meta');
}
$depends['files'] = array_map('wikiFN', $this->list);
$depends['files'][] = __FILE__;
$depends['files'][] = __DIR__ . '/renderer.php';
$depends['files'][] = __DIR__ . '/mpdf/mpdf.php';
$depends['files'] = array_merge(
$depends['files'],
$dependencies,
getConfigFiles('main')
);
return $cache;
}
/**
* Returns the parsed Wikitext in dw2pdf for the given id and revision
*
* @param string $id page id
* @param string|int $rev revision timestamp or empty string
* @param string $date_at
* @return null|string
*/
protected function wikiToDW2PDF($id, $rev = '', $date_at = '')
{
$file = wikiFN($id, $rev);
if (!file_exists($file)) {
return '';
}
//ensure $id is in global $ID (needed for parsing)
global $ID;
$keep = $ID;
$ID = $id;
if ($rev || $date_at) {
//no caching on old revisions
$ret = p_render('dw2pdf', p_get_instructions(io_readWikiPage($file, $id, $rev)), $info, $date_at);
} else {
$ret = p_cached_output($file, 'dw2pdf', $id);
}
//restore ID (just in case)
$ID = $keep;
return $ret;
}
/**
* Build a pdf from the html
*
* @param string $cachefile
* @param Event $event
* @throws MpdfException
*/
protected function generatePDF($cachefile, $event)
{
global $REV, $INPUT, $DATE_AT;
if ($event->data == 'export_pdf') { //only one page is exported
$rev = $REV;
$date_at = $DATE_AT;
} else {
//we are exporting entire namespace, ommit revisions
$rev = '';
$date_at = '';
}
//some shortcuts to export settings
$hasToC = $this->getExportConfig('hasToC');
$levels = $this->getExportConfig('levels');
$isDebug = $this->getExportConfig('isDebug');
$watermark = $this->getExportConfig('watermark');
// initialize PDF library
require_once(__DIR__ . "/DokuPDF.class.php");
$mpdf = new DokuPDF(
$this->getExportConfig('pagesize'),
$this->getExportConfig('orientation'),
$this->getExportConfig('font-size'),
$this->getDocumentLanguage($this->list[0]) //use language of first page
);
// let mpdf fix local links
$self = parse_url(DOKU_URL);
$url = $self['scheme'] . '://' . $self['host'];
if (!empty($self['port'])) {
$url .= ':' . $self['port'];
}
$mpdf->SetBasePath($url);
// Set the title
$mpdf->SetTitle($this->title);
// some default document settings
//note: double-sided document, starts at an odd page (first page is a right-hand side page)
// single-side document has only odd pages
$mpdf->mirrorMargins = $this->getExportConfig('doublesided');
$mpdf->setAutoTopMargin = 'stretch';
$mpdf->setAutoBottomMargin = 'stretch';
// $mpdf->pagenumSuffix = '/'; //prefix for {nbpg}
if ($hasToC) {
$mpdf->h2toc = $levels;
}
$mpdf->PageNumSubstitutions[] = ['from' => 1, 'reset' => 0, 'type' => '1', 'suppress' => 'off'];
// Watermarker
if ($watermark) {
$mpdf->SetWatermarkText($watermark);
$mpdf->showWatermarkText = true;
}
// load the template
$template = $this->loadTemplate();
// prepare HTML header styles
$html = '';
if ($isDebug) {
$html .= '<html><head>';
$html .= '<style>';
}
$styles = '@page { size:auto; ' . $template['page'] . '}';
$styles .= '@page :first {' . $template['first'] . '}';
$styles .= '@page landscape-page { size:landscape }';
$styles .= 'div.dw2pdf-landscape { page:landscape-page }';
$styles .= '@page portrait-page { size:portrait }';
$styles .= 'div.dw2pdf-portrait { page:portrait-page }';
$styles .= $this->loadCSS();
$mpdf->WriteHTML($styles, 1);
if ($isDebug) {
$html .= $styles;
$html .= '</style>';
$html .= '</head><body>';
}
$body_start = $template['html'];
$body_start .= '<div class="dokuwiki">';
// insert the cover page
$body_start .= $template['cover'];
$mpdf->WriteHTML($body_start, 2, true, false); //start body html
if ($isDebug) {
$html .= $body_start;
}
if ($hasToC) {
//Note: - for double-sided document the ToC is always on an even number of pages, so that the
// following content is on a correct odd/even page
// - first page of ToC starts always at odd page (so eventually an additional blank page
// is included before)
// - there is no page numbering at the pages of the ToC
$mpdf->TOCpagebreakByArray([
'toc-preHTML' => '<h2>' . $this->getLang('tocheader') . '</h2>',
'toc-bookmarkText' => $this->getLang('tocheader'),
'links' => true,
'outdent' => '1em',
'pagenumstyle' => '1'
]);
$html .= '<tocpagebreak>';
}
// loop over all pages
$counter = 0;
$no_pages = count($this->list);
foreach ($this->list as $page) {
$this->currentBookChapter = $counter;
$counter++;
$pagehtml = $this->wikiToDW2PDF($page, $rev, $date_at);
//file doesn't exists
if ($pagehtml == '') {
continue;
}
$pagehtml .= $this->pageDependReplacements($template['cite'], $page);
if ($counter < $no_pages) {
$pagehtml .= '<pagebreak />';
}
$mpdf->WriteHTML($pagehtml, 2, false, false); //intermediate body html
if ($isDebug) {
$html .= $pagehtml;
}
}
// insert the back page
$body_end = $template['back'];
$body_end .= '</div>';
$mpdf->WriteHTML($body_end, 2, false); // finish body html
if ($isDebug) {
$html .= $body_end;
$html .= '</body>';
$html .= '</html>';
}
//Return html for debugging
if ($isDebug) {
if ($INPUT->str('debughtml', 'text', true) == 'text') {
header('Content-Type: text/plain; charset=utf-8');
}
echo $html;
exit();
}
// write to cache file
$mpdf->Output($cachefile, 'F');
}
/**
* @param string $cachefile
*/
protected function sendPDFFile($cachefile)
{
header('Content-Type: application/pdf');
header('Cache-Control: must-revalidate, no-transform, post-check=0, pre-check=0');
header('Pragma: public');
http_conditionalRequest(filemtime($cachefile));
global $INPUT;
$outputTarget = $INPUT->str('outputTarget', $this->getConf('output'));
$filename = rawurlencode(cleanID(strtr($this->title, ':/;"', ' ')));
if ($outputTarget === 'file') {
header('Content-Disposition: attachment; filename="' . $filename . '.pdf";');
} else {
header('Content-Disposition: inline; filename="' . $filename . '.pdf";');
}
//Bookcreator uses jQuery.fileDownload.js, which requires a cookie.
header('Set-Cookie: fileDownload=true; path=/');
//try to send file, and exit if done
http_sendfile($cachefile);
$fp = @fopen($cachefile, "rb");
if ($fp) {
http_rangeRequest($fp, filesize($cachefile), 'application/pdf');
} else {
header("HTTP/1.0 500 Internal Server Error");
echo "Could not read file - bad permissions?";
}
exit();
}
/**
* Load the various template files and prepare the HTML/CSS for insertion
*
* @return array
*/
protected function loadTemplate()
{
global $ID;
global $conf;
global $INFO;
// this is what we'll return
$output = [
'cover' => '',
'back' => '',
'html' => '',
'page' => '',
'first' => '',
'cite' => '',
];
// prepare header/footer elements
$html = '';
foreach (['header', 'footer'] as $section) {
foreach (['', '_odd', '_even', '_first'] as $order) {
$file = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/' . $section . $order . '.html';
if (file_exists($file)) {
$html .= '<htmlpage' . $section . ' name="' . $section . $order . '">' . DOKU_LF;
$html .= file_get_contents($file) . DOKU_LF;
$html .= '</htmlpage' . $section . '>' . DOKU_LF;
// register the needed pseudo CSS
if ($order == '_first') {
$output['first'] .= $section . ': html_' . $section . $order . ';' . DOKU_LF;
} elseif ($order == '_even') {
$output['page'] .= 'even-' . $section . '-name: html_' . $section . $order . ';' . DOKU_LF;
} elseif ($order == '_odd') {
$output['page'] .= 'odd-' . $section . '-name: html_' . $section . $order . ';' . DOKU_LF;
} else {
$output['page'] .= $section . ': html_' . $section . $order . ';' . DOKU_LF;
}
}
}
}
// prepare replacements
$replace = [
'@PAGE@' => '{PAGENO}',
'@PAGES@' => '{nbpg}', //see also $mpdf->pagenumSuffix = ' / '
'@TITLE@' => hsc($this->title),
'@WIKI@' => $conf['title'],
'@WIKIURL@' => DOKU_URL,
'@DATE@' => dformat(time()),
'@USERNAME@' => $INFO['userinfo']['name'] ?? '',
'@BASE@' => DOKU_BASE,
'@INC@' => DOKU_INC,
'@TPLBASE@' => DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/',
'@TPLINC@' => DOKU_INC . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/'
];
// set HTML element
$html = str_replace(array_keys($replace), array_values($replace), $html);
//TODO For bookcreator $ID (= bookmanager page) makes no sense
$output['html'] = $this->pageDependReplacements($html, $ID);
// cover page
$coverfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/cover.html';
if (file_exists($coverfile)) {
$output['cover'] = file_get_contents($coverfile);
$output['cover'] = str_replace(array_keys($replace), array_values($replace), $output['cover']);
$output['cover'] = $this->pageDependReplacements($output['cover'], $ID);
$output['cover'] .= '<pagebreak />';
}
// cover page
$backfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/back.html';
if (file_exists($backfile)) {
$output['back'] = '<pagebreak />';
$output['back'] .= file_get_contents($backfile);
$output['back'] = str_replace(array_keys($replace), array_values($replace), $output['back']);
$output['back'] = $this->pageDependReplacements($output['back'], $ID);
}
// citation box
$citationfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/citation.html';
if (file_exists($citationfile)) {
$output['cite'] = file_get_contents($citationfile);
$output['cite'] = str_replace(array_keys($replace), array_values($replace), $output['cite']);
}
return $output;
}
/**
* @param string $raw code with placeholders
* @param string $id pageid
* @return string
*/
protected function pageDependReplacements($raw, $id)
{
global $REV, $DATE_AT;
// generate qr code for this page
$qr_code = '';
if ($this->getConf('qrcodescale')) {
$url = hsc(wl($id, '', '&', true));
$size = (float)$this->getConf('qrcodescale');
$qr_code = sprintf(
'<barcode type="QR" code="%s" error="Q" disableborder="1" class="qrcode" size="%s" />',
$url,
$size
);
}
// prepare replacements
$replace['@ID@'] = $id;
$replace['@UPDATE@'] = dformat(filemtime(wikiFN($id, $REV)));
$params = [];
if ($DATE_AT) {
$params['at'] = $DATE_AT;
} elseif ($REV) {
$params['rev'] = $REV;
}
$replace['@PAGEURL@'] = wl($id, $params, true, "&");
$replace['@QRCODE@'] = $qr_code;
$content = $raw;
// let other plugins define their own replacements
$evdata = ['id' => $id, 'replace' => &$replace, 'content' => &$content];
$event = new Event('PLUGIN_DW2PDF_REPLACE', $evdata);
if ($event->advise_before()) {
$content = str_replace(array_keys($replace), array_values($replace), $raw);
}
// plugins may post-process HTML, e.g to clean up unused replacements
$event->advise_after();
// @DATE(<date>[, <format>])@
$content = preg_replace_callback(
'/@DATE\((.*?)(?:,\s*(.*?))?\)@/',
[$this, 'replaceDate'],
$content
);
return $content;
}
/**
* (callback) Replace date by request datestring
* e.g. '%m(30-11-1975)' is replaced by '11'
*
* @param array $match with [0]=>whole match, [1]=> first subpattern, [2] => second subpattern
* @return string
*/
public function replaceDate($match)
{
global $conf;
//no 2nd argument for default date format
if ($match[2] == null) {
$match[2] = $conf['dformat'];
}
return strftime($match[2], strtotime($match[1]));
}
/**
* Load all the style sheets and apply the needed replacements
*
* @return string css styles
*/
protected function loadCSS()
{
global $conf;
//reuse the CSS dispatcher functions without triggering the main function
define('SIMPLE_TEST', 1);
require_once(DOKU_INC . 'lib/exe/css.php');
// prepare CSS files
$files = array_merge(
[
DOKU_INC . 'lib/styles/screen.css' => DOKU_BASE . 'lib/styles/',
DOKU_INC . 'lib/styles/print.css' => DOKU_BASE . 'lib/styles/',
],
$this->cssPluginPDFstyles(),
[
DOKU_PLUGIN . 'dw2pdf/conf/style.css' => DOKU_BASE . 'lib/plugins/dw2pdf/conf/',
DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/style.css' =>
DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/',
DOKU_PLUGIN . 'dw2pdf/conf/style.local.css' => DOKU_BASE . 'lib/plugins/dw2pdf/conf/',
]
);
$css = '';
foreach ($files as $file => $location) {
$display = str_replace(fullpath(DOKU_INC), '', fullpath($file));
$css .= "\n/* XXXXXXXXX $display XXXXXXXXX */\n";
$css .= css_loadfile($file, $location);
}
// apply pattern replacements
if (function_exists('css_styleini')) {
// compatiblity layer for pre-Greebo releases of DokuWiki
$styleini = css_styleini($conf['template']);
} else {
// Greebo functionality
$styleUtils = new StyleUtils();
$styleini = $styleUtils->cssStyleini($conf['template']); // older versions need still the template
}
$css = css_applystyle($css, $styleini['replacements']);
// parse less
return css_parseless($css);
}
/**
* Returns a list of possible Plugin PDF Styles
*
* Checks for a pdf.css, falls back to print.css
*
* @author Andreas Gohr <andi@splitbrain.org>
*/
protected function cssPluginPDFstyles()
{
$list = [];
$plugins = plugin_list();
$usestyle = explode(',', $this->getConf('usestyles'));
foreach ($plugins as $p) {
if (in_array($p, $usestyle)) {
$list[DOKU_PLUGIN . "$p/screen.css"] = DOKU_BASE . "lib/plugins/$p/";
$list[DOKU_PLUGIN . "$p/screen.less"] = DOKU_BASE . "lib/plugins/$p/";
$list[DOKU_PLUGIN . "$p/style.css"] = DOKU_BASE . "lib/plugins/$p/";
$list[DOKU_PLUGIN . "$p/style.less"] = DOKU_BASE . "lib/plugins/$p/";
}
$list[DOKU_PLUGIN . "$p/all.css"] = DOKU_BASE . "lib/plugins/$p/";
$list[DOKU_PLUGIN . "$p/all.less"] = DOKU_BASE . "lib/plugins/$p/";
if (file_exists(DOKU_PLUGIN . "$p/pdf.css") || file_exists(DOKU_PLUGIN . "$p/pdf.less")) {
$list[DOKU_PLUGIN . "$p/pdf.css"] = DOKU_BASE . "lib/plugins/$p/";
$list[DOKU_PLUGIN . "$p/pdf.less"] = DOKU_BASE . "lib/plugins/$p/";
} else {
$list[DOKU_PLUGIN . "$p/print.css"] = DOKU_BASE . "lib/plugins/$p/";
$list[DOKU_PLUGIN . "$p/print.less"] = DOKU_BASE . "lib/plugins/$p/";
}
}
// template support
foreach (
[
'pdf.css',
'pdf.less',
'css/pdf.css',
'css/pdf.less',
'styles/pdf.css',
'styles/pdf.less'
] as $file
) {
if (file_exists(tpl_incdir() . $file)) {
$list[tpl_incdir() . $file] = tpl_basedir() . $file;
}
}
return $list;
}
/**
* Returns array of pages which will be included in the exported pdf
*
* @return array
*/
public function getExportedPages()
{
return $this->list;
}
/**
* usort callback to sort by file lastmodified time
*
* @param array $a
* @param array $b
* @return int
*/
public function cbDateSort($a, $b)
{
if ($b['rev'] < $a['rev']) {
return -1;
}
if ($b['rev'] > $a['rev']) {
return 1;
}
return strcmp($b['id'], $a['id']);
}
/**
* usort callback to sort by page id
* @param array $a
* @param array $b
* @return int
*/
public function cbPagenameSort($a, $b)
{
global $conf;
$partsA = explode(':', $a['id']);
$countA = count($partsA);
$partsB = explode(':', $b['id']);
$countB = count($partsB);
$max = max($countA, $countB);
// compare namepsace by namespace
for ($i = 0; $i < $max; $i++) {
$partA = $partsA[$i] ?: null;
$partB = $partsB[$i] ?: null;
// have we reached the page level?
if ($i === ($countA - 1) || $i === ($countB - 1)) {
// start page first
if ($partA == $conf['start']) {
return -1;
}
if ($partB == $conf['start']) {
return 1;
}
}
// prefer page over namespace
if ($partA === $partB) {
if (!isset($partsA[$i + 1])) {
return -1;
}
if (!isset($partsB[$i + 1])) {
return 1;
}
continue;
}
// simply compare
return strnatcmp($partA, $partB);
}
return strnatcmp($a['id'], $b['id']);
}
/**
* Collects settings from:
* 1. url parameters
* 2. plugin config
* 3. global config
*/
protected function loadExportConfig()
{
global $INPUT;
global $conf;
$this->exportConfig = [];
// decide on the paper setup from param or config
$this->exportConfig['pagesize'] = $INPUT->str('pagesize', $this->getConf('pagesize'), true);
$this->exportConfig['orientation'] = $INPUT->str('orientation', $this->getConf('orientation'), true);
// decide on the font-size from param or config
$this->exportConfig['font-size'] = $INPUT->str('font-size', $this->getConf('font-size'), true);
$doublesided = $INPUT->bool('doublesided', (bool)$this->getConf('doublesided'));
$this->exportConfig['doublesided'] = $doublesided ? '1' : '0';
$this->exportConfig['watermark'] = $INPUT->str('watermark', '');
$hasToC = $INPUT->bool('toc', (bool)$this->getConf('toc'));
$levels = [];
if ($hasToC) {
$toclevels = $INPUT->str('toclevels', $this->getConf('toclevels'), true);
[$top_input, $max_input] = array_pad(explode('-', $toclevels, 2), 2, '');
[$top_conf, $max_conf] = array_pad(explode('-', $this->getConf('toclevels'), 2), 2, '');
$bounds_input = [
'top' => [
(int)$top_input,
(int)$top_conf
],
'max' => [
(int)$max_input,
(int)$max_conf
]
];
$bounds = [
'top' => $conf['toptoclevel'],
'max' => $conf['maxtoclevel']
];
foreach ($bounds_input as $bound => $values) {
foreach ($values as $value) {