Debian Codegraph @

extensions/PdfHandler/includes/PdfHandler.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\PdfHandler;
4
5 use File;
6 use ImageHandler;
7 use MediaTransformError;
8 use MediaTransformOutput;
9 use MediaWiki\Context\IContextSource;
10 use MediaWiki\MediaWikiServices;
11 use MediaWiki\PoolCounter\PoolCounterWorkViaCallback;
12 use ThumbnailImage;
13 use TransformParameterError;
14
15 /**
16 * Copyright © 2007 Martin Seidel (Xarax) <[email protected]>
17 *
18 * Inspired by djvuhandler from Tim Starling
19 * Modified and written by Xarax
20 *
21 * This program is free software; you can redistribute it and/or modify
22 * it under the terms of the GNU General Public License as published by
23 * the Free Software Foundation; either version 2 of the License, or
24 * (at your option) any later version.
25 *
26 * This program is distributed in the hope that it will be useful,
27 * but WITHOUT ANY WARRANTY; without even the implied warranty of
28 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 * GNU General Public License for more details.
30 *
31 * You should have received a copy of the GNU General Public License along
32 * with this program; if not, write to the Free Software Foundation, Inc.,
33 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
34 * http://www.gnu.org/copyleft/gpl.html
35 */
36
37 class PdfHandler extends ImageHandler {
38 /**
39 * Keep in sync with pdfhandler.messages in extension.json
40 *
41 * @see getWarningConfig
42 */
43 private const MESSAGES = [
44 'main' => 'pdf-file-page-warning',
45 'header' => 'pdf-file-page-warning-header',
46 'info' => 'pdf-file-page-warning-info',
47 'footer' => 'pdf-file-page-warning-footer',
48 ];
49
50 /**
51 * 10MB is considered a large file
52 */
53 private const LARGE_FILE = 1e7;
54
55 /**
56 * Key for getHandlerState for value of type PdfImage
57 */
58 private const STATE_PDF_IMAGE = 'pdfImage';
59
60 /**
61 * Key for getHandlerState for dimension info
62 */
63 private const STATE_DIMENSION_INFO = 'pdfDimensionInfo';
64
65 /**
66 * @param File $file
67 * @return bool
68 */
69 public function mustRender( $file ) {
70 return true;
71 }
72
73 /**
74 * @param File $file
75 * @return bool
76 */
77 public function isMultiPage( $file ) {
78 return true;
79 }
80
81 /**
82 * @param string $name
83 * @param string $value
84 * @return bool
85 */
86 public function validateParam( $name, $value ) {
87 if ( $name === 'page' && trim( $value ) !== (string)intval( $value ) ) {
88 // Extra junk on the end of page, probably actually a caption
89 // e.g. [[File:Foo.pdf|thumb|Page 3 of the document shows foo]]
90 return false;
91 }
92 if ( in_array( $name, [ 'width', 'height', 'page', 'physicalWidth', 'physicalHeight' ] ) ) {
93 return ( $value > 0 );
94 }
95 return false;
96 }
97
98 /**
99 * @param array $params
100 * @return bool|string
101 */
102 public function makeParamString( $params ) {
103 $page = $params['page'] ?? 1;
104 $width = $params['physicalWidth'] ?? $params['width'] ?? null;
105 if ( !$width ) {
106 return false;
107 }
108 return "page{$page}-{$width}px";
109 }
110
111 /**
112 * @param string $str
113 * @return array|bool
114 */
115 public function parseParamString( $str ) {
116 $m = [];
117
118 if ( preg_match( '/^page(\d+)-(\d+)px$/', $str, $m ) ) {
119 return [ 'width' => $m[2], 'page' => $m[1] ];
120 }
121
122 return false;
123 }
124
125 /**
126 * @param array $params
127 * @return array
128 */
129 public function getScriptParams( $params ) {
130 return [
131 'width' => $params['width'],
132 'page' => $params['page'],
133 ];
134 }
135
136 /**
137 * @return array
138 */
139 public function getParamMap() {
140 return [
141 'img_width' => 'width',
142 'img_page' => 'page',
143 ];
144 }
145
146 /**
147 * @param int $width
148 * @param int $height
149 * @param string $msg
150 * @return MediaTransformError
151 */
152 protected function doThumbError( $width, $height, $msg ) {
153 return new MediaTransformError( 'thumbnail_error',
154 $width, $height, wfMessage( $msg )->inContentLanguage()->text() );
155 }
156
157 /**
158 * @param File $image
159 * @param string $dstPath
160 * @param string $dstUrl
161 * @param array $params
162 * @param int $flags
163 * @return MediaTransformError|MediaTransformOutput|ThumbnailImage|TransformParameterError
164 */
165 public function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
166 global $wgPdfProcessor, $wgPdfPostProcessor, $wgPdfHandlerDpi, $wgPdfHandlerJpegQuality;
167
168 if ( !$this->normaliseParams( $image, $params ) ) {
169 return new TransformParameterError( $params );
170 }
171
172 $width = (int)$params['width'];
173 $height = (int)$params['height'];
174 $page = (int)$params['page'];
175
176 if ( $page > $this->pageCount( $image ) ) {
177 return $this->doThumbError( $width, $height, 'pdf_page_error' );
178 }
179
180 if ( $flags & self::TRANSFORM_LATER ) {
181 return new ThumbnailImage( $image, $dstUrl, false, [
182 'width' => $width,
183 'height' => $height,
184 'page' => $page,
185 ] );
186 }
187
188 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
189 return $this->doThumbError( $width, $height, 'thumbnail_dest_directory' );
190 }
191
192 // Thumbnail extraction is very inefficient for large files.
193 // Provide a way to pool count limit the number of downloaders.
194 if ( $image->getSize() >= self::LARGE_FILE ) {
195 $work = new PoolCounterWorkViaCallback( 'GetLocalFileCopy', sha1( $image->getName() ),
196 [
197 'doWork' => static function () use ( $image ) {
198 return $image->getLocalRefPath();
199 }
200 ]
201 );
202 $srcPath = $work->execute();
203 } else {
204 $srcPath = $image->getLocalRefPath();
205 }
206
207 if ( $srcPath === false ) {
208 // could not download original
209 return $this->doThumbError( $width, $height, 'filemissing' );
210 }
211
212 $cmd = '(' . wfEscapeShellArg(
213 $wgPdfProcessor,
214 "-sDEVICE=jpeg",
215 "-sOutputFile=-",
216 "-sstdout=%stderr",
217 "-dFirstPage={$page}",
218 "-dLastPage={$page}",
219 "-dSAFER",
220 "-r{$wgPdfHandlerDpi}",
221 // CropBox defines the region that the PDF viewer application is expected to display or print.
222 "-dUseCropBox",
223 "-dBATCH",
224 "-dNOPAUSE",
225 "-q",
226 $srcPath
227 );
228 $cmd .= " | " . wfEscapeShellArg(
229 $wgPdfPostProcessor,
230 "-",
231 "-depth",
232 "8",
233 "-quality",
234 $wgPdfHandlerJpegQuality,
235 "-resize",
236 (string)$width,
237 $dstPath
238 );
239 $cmd .= ")";
240
241 wfDebug( __METHOD__ . ": $cmd\n" );
242 $retval = '';
243 $err = wfShellExecWithStderr( $cmd, $retval );
244
245 $removed = $this->removeBadFile( $dstPath, $retval );
246
247 if ( $retval != 0 || $removed ) {
248 wfDebugLog( 'thumbnail',
249 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
250 wfHostname(), $retval, trim( $err ), $cmd ) );
251 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
252 }
253
254 return new ThumbnailImage( $image, $dstUrl, $dstPath, [
255 'width' => $width,
256 'height' => $height,
257 'page' => $page,
258 ] );
259 }
260
261 /**
262 * @inheritDoc
263 */
264 public function normaliseParams( $image, &$params ) {
265 // Copy-paste from TransformationalImageHandler::normaliseParams()
266 // Probably should be trait or subclass.
267 if ( !parent::normaliseParams( $image, $params ) ) {
268 return false;
269 }
270 $srcWidth = $image->getWidth( $params['page'] );
271 $srcHeight = $image->getHeight( $params['page'] );
272 $params['physicalWidth'] = $this->getSteppedThumbWidth(
273 $image, $params['physicalWidth'], $srcWidth, $srcHeight
274 );
275 $params['physicalHeight'] = File::scaleHeight( $srcWidth, $srcHeight, $params['physicalWidth'] );
276 return true;
277 }
278
279 /**
280 * @param \MediaHandlerState $state
281 * @param string $path
282 * @return PdfImage
283 */
284 private function getPdfImage( $state, $path ) {
285 $pdfImg = $state->getHandlerState( self::STATE_PDF_IMAGE );
286 if ( !$pdfImg ) {
287 $pdfImg = new PdfImage( $path );
288 $state->setHandlerState( self::STATE_PDF_IMAGE, $pdfImg );
289 }
290 return $pdfImg;
291 }
292
293 /**
294 * @param \MediaHandlerState $state
295 * @param string $path
296 * @return array|bool
297 */
298 public function getSizeAndMetadata( $state, $path ) {
299 $metadata = $this->getPdfImage( $state, $path )->retrieveMetaData();
300 $sizes = PdfImage::getPageSize( $metadata, 1 );
301 if ( $sizes ) {
302 return $sizes + [ 'metadata' => $metadata ];
303 }
304
305 return [ 'metadata' => $metadata ];
306 }
307
308 /**
309 * @param string $ext
310 * @param string $mime
311 * @param null $params
312 * @return array
313 */
314 public function getThumbType( $ext, $mime, $params = null ) {
315 global $wgPdfOutputExtension;
316 static $mime;
317
318 if ( !isset( $mime ) ) {
319 $magic = MediaWikiServices::getInstance()->getMimeAnalyzer();
320 $mime = $magic->guessTypesForExtension( $wgPdfOutputExtension );
321 }
322 return [ $wgPdfOutputExtension, $mime ];
323 }
324
325 /**
326 * @param File $file
327 * @return bool|int
328 */
329 public function isFileMetadataValid( $file ) {
330 $data = $file->getMetadataItems( [ 'mergedMetadata', 'pages' ] );
331 if ( !isset( $data['pages'] ) ) {
332 return self::METADATA_BAD;
333 }
334
335 if ( !isset( $data['mergedMetadata'] ) ) {
336 return self::METADATA_COMPATIBLE;
337 }
338
339 return self::METADATA_GOOD;
340 }
341
342 /**
343 * @param File $image
344 * @param bool|IContextSource $context Context to use (optional)
345 * @return bool|array
346 */
347 public function formatMetadata( $image, $context = false ) {
348 $mergedMetadata = $image->getMetadataItem( 'mergedMetadata' );
349
350 if ( !is_array( $mergedMetadata ) || !count( $mergedMetadata ) ) {
351 return false;
352 }
353
354 // Inherited from MediaHandler.
355 return $this->formatMetadataHelper( $mergedMetadata, $context );
356 }
357
358 /** @inheritDoc */
359 protected function formatTag( string $key, $vals, $context = false ) {
360 switch ( $key ) {
361 case 'pdf-Producer':
362 case 'pdf-Version':
363 return htmlspecialchars( $vals );
364 case 'pdf-PageSize':
365 foreach ( $vals as &$val ) {
366 $val = htmlspecialchars( $val );
367 }
368 return $vals;
369 case 'pdf-Encrypted':
370 // @todo: The value isn't i18n-ised; should be done here.
371 // For reference, if encrypted this field's value looks like:
372 // "yes (print:yes copy:no change:no addNotes:no)"
373 return htmlspecialchars( $vals );
374 default:
375 break;
376 }
377 // Use default formatting
378 return false;
379 }
380
381 /**
382 * @param File $image
383 * @return bool|int
384 */
385 public function pageCount( File $image ) {
386 $info = $this->getDimensionInfo( $image );
387
388 return $info ? $info['pageCount'] : false;
389 }
390
391 /**
392 * @param File $image
393 * @param int $page
394 * @return array|bool
395 */
396 public function getPageDimensions( File $image, $page ) {
397 // MW starts pages at 1, as they are stored here
398 $index = $page;
399
400 $info = $this->getDimensionInfo( $image );
401 if ( $info && isset( $info['dimensionsByPage'][$index] ) ) {
402 return $info['dimensionsByPage'][$index];
403 }
404
405 return false;
406 }
407
408 /**
409 * @param File $file
410 * @return bool|mixed
411 */
412 protected function getDimensionInfo( File $file ) {
413 $info = $file->getHandlerState( self::STATE_DIMENSION_INFO );
414 if ( !$info ) {
415 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
416 $info = $cache->getWithSetCallback(
417 $cache->makeKey( 'file-pdf-dimensions', $file->getSha1() ),
418 $cache::TTL_MONTH,
419 static function () use ( $file ) {
420 $data = $file->getMetadataItems( PdfImage::ITEMS_FOR_PAGE_SIZE );
421 if ( !$data || !isset( $data['Pages'] ) ) {
422 return false;
423 }
424
425 $dimsByPage = [];
426 $count = intval( $data['Pages'] );
427 for ( $i = 1; $i <= $count; $i++ ) {
428 $dimsByPage[$i] = PdfImage::getPageSize( $data, $i );
429 }
430
431 return [ 'pageCount' => $count, 'dimensionsByPage' => $dimsByPage ];
432 }
433 );
434 }
435 $file->setHandlerState( self::STATE_DIMENSION_INFO, $info );
436 return $info;
437 }
438
439 /**
440 * @param File $image
441 * @param int $page
442 * @return bool
443 */
444 public function getPageText( File $image, $page ) {
445 $pageTexts = $image->getMetadataItem( 'text' );
446 if ( !is_array( $pageTexts ) || !isset( $pageTexts[$page - 1] ) ) {
447 return false;
448 }
449 return $pageTexts[$page - 1];
450 }
451
452 /**
453 * Adds a warning about PDFs being potentially dangerous to the file
454 * page. Multiple messages with this base will be used.
455 * @param File $file
456 * @return array
457 */
458 public function getWarningConfig( $file ) {
459 return [
460 'messages' => self::MESSAGES,
461 'link' => '//www.mediawiki.org/wiki/Special:MyLanguage/Help:Security/PDF_files',
462 'module' => 'pdfhandler.messages',
463 ];
464 }
465
466 public function useSplitMetadata() {
467 return true;
468 }
469 }