-
Notifications
You must be signed in to change notification settings - Fork 2
/
Pages2Pdf.module
520 lines (455 loc) · 18.2 KB
/
Pages2Pdf.module
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
<?php
/**
* Pages2Pdf
*
* @author Stefan Wanzenried <stefan.wanzenried@gmail.com>
* @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License, version 2
* @version 1.1.7
*/
class Pages2Pdf extends WireData implements Module, ConfigurableModule
{
/**
* Folder name where PDF templates are stored inside /site/templates/
*/
const FOLDER_NAME = 'pages2pdf/';
/**
* Generating cache PDF files either on click (when requesting a download) or when saving a page in the admin
*/
const CREATION_MODE_CLICK = 1;
const CREATION_MODE_SAVE = 2;
/**
* @var WirePDF
*/
protected $pdf;
/**
* Default config
*
* @var array
*/
protected static $config = array(
'templates' => array(),
'getVar' => 'pages2pdf',
'filename' => '{page.name}-pdf-{page.id}.pdf',
'printHeader' => 1,
'printFooter' => 1,
'cacheTime' => 86400,
'creationMode' => self::CREATION_MODE_CLICK,
'multilanguageSupport' => false,
);
public function __construct()
{
foreach (self::$config as $k => $v) {
$this->set($k, $v);
}
}
/**
* @return array
*/
public static function getModuleInfo()
{
return array(
'title' => 'Pages2Pdf',
'summary' => __('Generates PDF files of pages. The HTML markup of the PDFs is customizable with ProcessWire templates.'),
'version' => 117,
'author' => 'Stefan Wanzenried (Wanze)',
'href' => 'http://processwire.com/talk/topic/3008-module-pages2pdf/',
'singular' => true,
'autoload' => true,
'installs' => array('WirePDF'),
);
}
public function init()
{
}
/**
* Called when ProcessWire API is ready
* Check if there is a request to download (and possibly create) a PDF file:
* If the GET variable is 1, download a PDF of the current page (this was used in previous versions)
* If the GET variable contains another page ID (integer), try to download the PDF from the this page
*
* If there is no request to download a PDF file, do nothing and just attach hooks
*
*/
public function ready()
{
$get_var = $this->get('getVar');
if ($page_id = $this->wire('input')->get($get_var)) {
$page = ($page_id == 1) ? $this->wire('page') : $this->wire('pages')->get((int) $page_id);
if ($page->id && in_array($page->template->name, $this->get('templates')) && $page->viewable()) {
$this->download($page);
}
}
$this->pages->addHookAfter('save', $this, 'hookDeletePDF');
if ($this->get('creationMode') == self::CREATION_MODE_SAVE) {
$this->pages->addHookAfter('save', $this, 'hookSavePDF');
}
}
/**
* Install this module
* Create pages2pdf folder in /site/templates/ and copy over the default pdf templates
*
*/
public function ___install()
{
$folder = self::FOLDER_NAME;
$templates_path = $this->wire('config')->paths->templates . $folder;
if (file_exists($templates_path)) {
return;
}
if (!wireMkdir($templates_path)) {
$this->error($this->_("Could not create directory '$folder' in '/site/templates/'. Please create it manually and copy all the files from '/site/modules/Pages2Pdf/default_templates/'"));
} else {
$path_from = $this->wire('config')->paths->Pages2Pdf . 'default_templates/';
$path_to = $templates_path;
$files = array('_footer.php', '_header.php', 'default.php', 'styles.css');
foreach ($files as $file) {
if (!copy($path_from . $file, $path_to . $file)) {
$this->error($this->_("Failed to copy '$file' from '$path_from' to '$path_to'. Please copy this file manually."));
}
}
}
}
/**
* @param string $key
* @return mixed|mPDF|null
*/
public function get($key)
{
switch ($key) {
case 'wirePDF':
case 'pdf':
return $this->getPDF();
break;
}
return parent::get($key);
}
/**
* @param string $key
* @param mixed $value
* @return $this
*/
public function set($key, $value)
{
switch ($key) {
case 'wirePDF':
case 'pdf':
$this->setPDF($value);
break;
}
return parent::set($key, $value);
}
/**
* Delete cached PDF file if page is saved
*
* @param HookEvent $event
*/
public function hookDeletePDF(HookEvent $event)
{
$page = $event->arguments[0];
if (!in_array($page->template->name, $this->get('templates'))) return;
// Delete PDF for each language, languages API variable is not available if language support module is not installed
$languages = $this->wire('languages') ? $this->wire('languages') : array(null);
foreach ($languages as $language) {
$pdf = $this->getPdfFilePath($page, $language);
if (is_file($pdf)) {
$name = $this->getPdfFileName($page, $language);
if (unlink($pdf)) {
$this->wire('session')->message(sprintf($this->_("Pages2Pdf: Deleted PDF file '%s'"), $name));
} else {
$this->wire('session')->error(sprintf($this->_("Pages2Pdf: Failed to delete PDF file '%s'"), $name));
}
}
}
}
/**
* Store a PDF file of a page
*
* @param HookEvent $event
*/
public function hookSavePDF(HookEvent $event)
{
/** @var Page $page */
$page = $event->arguments[0];
if (!in_array($page->template->name, $this->get('templates'))) return;
if ($page->is(Page::statusTrash)) return;
// If multilanguage support is enabled and multi-language support is given, create a PDF for each language
if ($this->get('multilanguageSupport') && $this->wire('languages')) {
$_language = $this->wire('user')->language;
$files = array();
foreach ($this->wire('languages') as $language) {
$this->wire('user')->language = $language;
$this->create($page, true);
$files[] = $this->getPDFFilename($page, $language);
$this->pdf = null; // This makes sure each language gets a new WirePDF object which is required
}
$this->wire('user')->language = $_language;
$this->wire('session')->message(sprintf($this->_("Pages2Pdf: Created PDF file(s) '%s'"), implode(', ', $files)));
} else {
$this->create($page, true);
$name = $this->getPDFFilename($page);
$this->wire('session')->message(sprintf($this->_("Pages2Pdf: Created PDF file(s) '%s'"), $name));
}
}
/**
* Render a link to download the PDF.
* Note that this method is not really necessary as downloading/creating PDFs is handled now in the ready() method.
* Instead of calling this method, one could create the link manually
*
* @param array $options Array
* @return string
*/
public function render(array $options = array())
{
$_options = array(
'title' => $this->_('Print PDF'),
'markup' => '<a href="{url}">{title}</a>',
'page_id' => '',
);
$options = array_merge($_options, $options);
$page = ($options['page_id']) ? $this->wire('pages')->get((int) $options['page_id']) : $this->wire('page');
if (!in_array($page->template->name, $this->get('templates'))) {
return ($this->wire('config')->debug) ? $this->_('Pages2Pdf: Template of requested page is not allowed to generate PDFs') : '';
}
$out = $options['markup'];
$get_var = $this->get('getVar');
$url = $this->wire('page')->url . "?{$get_var}={$page->id}";
$out = str_replace('{url}', $url, $out);
$out = str_replace('{title}', $options['title'], $out);
return $out;
}
/**
* Return path to PDF file
*
* @param Page $page
* @param Language $language Pass a language object to return the file path for the given language
* @return string
*/
public function getPDFFilePath(Page $page, Language $language = null)
{
return $page->filesManager()->path() . $this->getPDFFilename($page, $language);
}
/**
* Return URL to PDF file
*
* @param Page $page
* @param Language $language Pass a language object to return the file url for the given language
* @return string
*/
public function getPDFFileUrl(Page $page, Language $language = null)
{
return $page->filesManager()->url() . $this->getPDFFilename($page, $language);
}
/**
* @return WirePDF
*/
public function getPDF()
{
if (is_null($this->pdf)) {
$this->pdf = $this->wire('modules')->get('WirePDF');
}
return $this->pdf;
}
/**
* @param WirePDF $pdf
*/
public function setPDF(WirePDF $pdf)
{
$this->pdf = $pdf;
}
/**
* Download PDF from given page, create PDF if not yet existing
*
* @param Page $page
* @param bool $force True to bypass cached file and create a fresh PDF file before downloading
*/
public function ___download(Page $page, $force = false)
{
$language = $this->determineLanguage();
if ($force || !$this->isCached($page, $language)) {
$this->createPDF($page, $language);
}
wireSendFile($this->getPDFFilePath($page, $language), array('forceDownload' => true));
}
/**
* Create PDF file and store it without requesting to download the file afterwards
*
* @param Page $page
* @param bool $force True to bypass cache and create a fresh PDF file
*/
public function ___create(Page $page, $force = false)
{
$language = $this->determineLanguage();
if ($force || !$this->isCached($page, $language)) {
$this->createPDF($page, $language);
}
}
/**
* Get module config
*
* @param array $data
* @return InputfieldWrapper
*/
public static function getModuleConfigInputfields(array $data)
{
$data = array_merge(self::$config, $data);
$modules = wire('modules');
$fields = new InputfieldWrapper();
/** @var InputfieldAsmSelect $field */
$field = $modules->get('InputfieldAsmSelect');
$field->label = __('Enabled templates');
$field->description = __('Pages of the selected templates are allowed to create PDF files');
$field->name = 'templates';
$field->value = $data['templates'];
$templates = array();
foreach (wire('templates') as $template) {
if ($template->flags & Template::flagSystem) continue; //Exclude system templates
$templates[$template->name] = $template->name;
}
$field->addOptions($templates);
$fields->append($field);
$field = $modules->get('InputfieldCheckbox');
$field->label = __('Print header');
$field->description = __('Check to print a header in the PDF files. Markup defined in /site/templates/pages2pdf/_header.php');
if ($data['printHeader']) $field->attr('checked', 'checked');
$field->name = 'printHeader';
$fields->append($field);
$field = $modules->get('InputfieldCheckbox');
$field->label = __('Print footer');
$field->description = __('Check to print a footer in the PDF files. Markup defined in /site/templates/pages2pdf/_footer.php');
if ($data['printFooter']) $field->attr('checked', 'checked');
$field->name = 'printFooter';
$fields->append($field);
$field = $modules->get('InputfieldInteger');
$field->label = __('Cache time');
$field->description = __('Enter a time in seconds how long a PDF file is cached before it is recreated by the module');
$field->notes = __('If debug mode is on, caching is bypassed to serve fresh PDF files');
$field->value = $data['cacheTime'];
$field->name = 'cacheTime';
$fields->append($field);
$field = $modules->get('InputfieldText');
$field->label = __('PDF filename');
$field->description = __('Generated name of PDF files. Available Placeholders are {page.name} and {page.id}');
$field->value = $data['filename'];
$field->name = 'filename';
$field->pattern = '^([a-zA-Z0-9_-]|\{page\.id\}|\{page\.name\})+\.pdf$';
$field->notes = sprintf(__('Available characters: %s'), 'a-zA-Z0-9_-');
$field->required = 1;
$fields->append($field);
$field = $modules->get('InputfieldText');
$field->label = __('GET variable');
$field->description = __('GET variable used when requesting a PDF file of a page');
$field->value = $data['getVar'];
$field->name = 'getVar';
$field->required = 1;
$fields->append($field);
$field = $modules->get('InputfieldRadios');
$field->label = __('Creation mode');
$field->description = __('Should PDF files be generated and cached on click (when requesting a download) or when saving pages in the admin');
$field->name = 'creationMode';
$field->value = $data['creationMode'];
$modes = array(
self::CREATION_MODE_CLICK => __('On click, when requesting a download of a PDF file'),
self::CREATION_MODE_SAVE => __('After saving pages in the admin'),
);
$field->addOptions($modes);
$fields->append($field);
$field = $modules->get('InputfieldCheckbox');
$field->label = __('Multilanguage support');
$field->name = 'multilanguageSupport';
$field->description = __('If checked, the PDF files are generated per language. If a download is requested, the PDF is delivered in the language of the user, if available.');
$field->notes = __('This feature requires the core module "Languages Support" to be installed');
if ($data['multilanguageSupport']) $field->checked = true;
$fields->append($field);
return $fields;
}
/**
* Checks if the PDF of given page (and optionally language) can be served from cache
*
* @param Page $page
* @param Language $language
* @return bool
* @throws WireException
*/
protected function isCached(Page $page, Language $language = null)
{
$file = $this->getPDFFilePath($page, $language);
if (!is_file($file) || $this->wire('config')->debug) {
return false;
}
$last_modified = filemtime($file);
return ((time() - $last_modified) < $this->get('cacheTime'));
}
/**
* Helper method to find out the correct language to create/store/download a PDF file.
* If multilanguage support is enabled, the language of the current user is returned, otherwise default.
*
* @return Language
* @throws WireException
*/
protected function determineLanguage()
{
return ($this->get('multilanguageSupport') && $this->wire('languages')) ? $this->wire('user')->language : null;
}
/**
* Create PDF file for the given page and language, if multilanguage support is enabled.
* This method checks if a PDF template for the page's template is existing in /site/templates/pages2pdf/
* If no template is found, the standard template is used to render the pdf
*
* @param Page $page
* @param Language $language
* @throws WireException
*/
protected function ___createPDF(Page $page, Language $language = null)
{
if (!in_array($page->template->name, $this->get('templates'))) {
throw new WireException("Pages2Pdf: Not allowed to create PDF file for template '{$page->template->name}'");
}
$path = $page->filesManager()->path();
if (!is_dir($path)) {
if (!wireMkdir($path)) {
throw new WireException("Pages2Pdf: Could not create directory '{$path}'");
}
}
$templates_path = $this->wire('config')->paths->templates . self::FOLDER_NAME;
$template_main = $templates_path . $page->template->name . '.php';
$template_main = (is_file($template_main)) ? $template_main : $templates_path . 'default.php';
$this->getPDF()->set('markupMain', $template_main);
if ($this->get('printHeader')) {
$this->getPDF()->set('markupHeader', $templates_path . '_header.php');
}
if ($this->get('printFooter')) {
$this->getPDF()->set('markupFooter', $templates_path . '_footer.php');
}
if (is_file($templates_path . 'styles.css')) {
$this->getPDF()->set('cssFile', $templates_path . 'styles.css');
}
// Temporary set the wire page context to the given page, because $page can be different than wire('page')
$_page = $this->wire('page');
$this->wire('page', $page);
$this->getPDF()->save($this->getPDFFilePath($page, $language));
$this->wire('page', $_page);
}
/**
* Get PDF filename of a page, must be unique per language
*
* @param Page $page
* @param Language $language
* @return string
*/
protected function getPDFFilename(Page $page, Language $language = null)
{
$searches = array('{page.id}', '{page.name}');
$name = $page->name;
// If the module LanguageSupportPageNames is installed and a language is given, use local page name
if ($this->wire('modules')->isInstalled('LanguageSupportPageNames') && $page->localName($language)) {
$name = $page->localName($language);
}
$replaces = array($page->id, $name);
$filename = str_replace($searches, $replaces, $this->get('filename'));
// The filename is only different for languages other than the default one
if ($language && $language->name != 'default') {
$filename = preg_replace('/\.pdf$/', "-{$language->name}.pdf", $filename);
}
return $filename;
}
}