MediaWiki  1.29.2
PdfHandler_body.php
Go to the documentation of this file.
1 <?php
24 class PdfHandler extends ImageHandler {
25  static $messages = array(
26  'main' => 'pdf-file-page-warning',
27  'header' => 'pdf-file-page-warning-header',
28  'info' => 'pdf-file-page-warning-info',
29  'footer' => 'pdf-file-page-warning-footer',
30  );
31 
35  function isEnabled() {
36  global $wgPdfProcessor, $wgPdfPostProcessor, $wgPdfInfo;
37 
38  if ( !isset( $wgPdfProcessor ) || !isset( $wgPdfPostProcessor ) || !isset( $wgPdfInfo ) ) {
39  wfDebug( "PdfHandler is disabled, please set the following\n" );
40  wfDebug( "variables in LocalSettings.php:\n" );
41  wfDebug( "\$wgPdfProcessor, \$wgPdfPostProcessor, \$wgPdfInfo\n" );
42  return false;
43  }
44  return true;
45  }
46 
51  function mustRender( $file ) {
52  return true;
53  }
54 
59  function isMultiPage( $file ) {
60  return true;
61  }
62 
68  function validateParam( $name, $value ) {
69  if ( $name === 'page' && trim( $value ) !== (string) intval( $value ) ) {
70  // Extra junk on the end of page, probably actually a caption
71  // e.g. [[File:Foo.pdf|thumb|Page 3 of the document shows foo]]
72  return false;
73  }
74  if ( in_array( $name, array( 'width', 'height', 'page' ) ) ) {
75  return ( $value > 0 );
76  }
77  return false;
78  }
79 
84  function makeParamString( $params ) {
85  $page = isset( $params['page'] ) ? $params['page'] : 1;
86  if ( !isset( $params['width'] ) ) {
87  return false;
88  }
89  return "page{$page}-{$params['width']}px";
90  }
91 
96  function parseParamString( $str ) {
97  $m = false;
98 
99  if ( preg_match( '/^page(\d+)-(\d+)px$/', $str, $m ) ) {
100  return array( 'width' => $m[2], 'page' => $m[1] );
101  }
102 
103  return false;
104  }
105 
110  function getScriptParams( $params ) {
111  return array(
112  'width' => $params['width'],
113  'page' => $params['page'],
114  );
115  }
116 
120  function getParamMap() {
121  return array(
122  'img_width' => 'width',
123  'img_page' => 'page',
124  );
125  }
126 
133  protected function doThumbError( $width, $height, $msg ) {
134  return new MediaTransformError( 'thumbnail_error',
135  $width, $height, wfMessage( $msg )->inContentLanguage()->text() );
136  }
137 
146  function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
147  global $wgPdfProcessor, $wgPdfPostProcessor, $wgPdfHandlerDpi, $wgPdfHandlerJpegQuality;
148 
149  if ( !$this->normaliseParams( $image, $params ) ) {
150  return new TransformParameterError( $params );
151  }
152 
153  $width = (int)$params['width'];
154  $height = (int)$params['height'];
155  $page = (int)$params['page'];
156 
157  if ( $page > $this->pageCount( $image ) ) {
158  return $this->doThumbError( $width, $height, 'pdf_page_error' );
159  }
160 
161  if ( $flags & self::TRANSFORM_LATER ) {
162  return new ThumbnailImage( $image, $dstUrl, $width, $height, false, $page );
163  }
164 
165  if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
166  return $this->doThumbError( $width, $height, 'thumbnail_dest_directory' );
167  }
168 
169  // Thumbnail extraction is very inefficient for large files.
170  // Provide a way to pool count limit the number of downloaders.
171  if ( $image->getSize() >= 1e7 ) { // 10MB
172  $work = new PoolCounterWorkViaCallback( 'GetLocalFileCopy', sha1( $image->getName() ),
173  array(
174  'doWork' => function() use ( $image ) {
175  return $image->getLocalRefPath();
176  }
177  )
178  );
179  $srcPath = $work->execute();
180  } else {
181  $srcPath = $image->getLocalRefPath();
182  }
183 
184  if ( $srcPath === false ) { // could not download original
185  return $this->doThumbError( $width, $height, 'filemissing' );
186  }
187 
188  $cmd = '(' . wfEscapeShellArg(
189  $wgPdfProcessor,
190  "-sDEVICE=jpeg",
191  "-sOutputFile=-",
192  "-dFirstPage={$page}",
193  "-dLastPage={$page}",
194  "-dSAFER",
195  "-r{$wgPdfHandlerDpi}",
196  "-dBATCH",
197  "-dNOPAUSE",
198  "-q",
199  $srcPath
200  );
201  $cmd .= " | " . wfEscapeShellArg(
202  $wgPdfPostProcessor,
203  "-depth",
204  "8",
205  "-quality",
206  $wgPdfHandlerJpegQuality,
207  "-resize",
208  $width,
209  "-",
210  $dstPath
211  );
212  $cmd .= ")";
213 
214  wfDebug( __METHOD__ . ": $cmd\n" );
215  $retval = '';
216  $err = wfShellExecWithStderr( $cmd, $retval );
217 
218  $removed = $this->removeBadFile( $dstPath, $retval );
219 
220  if ( $retval != 0 || $removed ) {
221  wfDebugLog( 'thumbnail',
222  sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
223  wfHostname(), $retval, trim( $err ), $cmd ) );
224  return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
225  } else {
226  return new ThumbnailImage( $image, $dstUrl, $width, $height, $dstPath, $page );
227  }
228  }
229 
235  function getPdfImage( $image, $path ) {
236  if ( !$image ) {
237  $pdfimg = new PdfImage( $path );
238  } elseif ( !isset( $image->pdfImage ) ) {
239  $pdfimg = $image->pdfImage = new PdfImage( $path );
240  } else {
241  $pdfimg = $image->pdfImage;
242  }
243 
244  return $pdfimg;
245  }
246 
251  function getMetaArray( $image ) {
252  if ( isset( $image->pdfMetaArray ) ) {
253  return $image->pdfMetaArray;
254  }
255 
256  $metadata = $image->getMetadata();
257 
258  if ( !$this->isMetadataValid( $image, $metadata ) ) {
259  wfDebug( "Pdf metadata is invalid or missing, should have been fixed in upgradeRow\n" );
260  return false;
261  }
262 
263  $work = new PoolCounterWorkViaCallback( 'PdfHandler-unserialize-metadata', $image->getName(), array(
264  'doWork' => function() use ( $image, $metadata ) {
266  $image->pdfMetaArray = unserialize( $metadata );
268  },
269  ) );
270  $work->execute();
271 
272  return $image->pdfMetaArray;
273  }
274 
280  function getImageSize( $image, $path ) {
281  return $this->getPdfImage( $image, $path )->getImageSize();
282  }
283 
290  function getThumbType( $ext, $mime, $params = null ) {
291  global $wgPdfOutputExtension;
292  static $mime;
293 
294  if ( !isset( $mime ) ) {
295  $magic = MimeMagic::singleton();
296  $mime = $magic->guessTypesForExtension( $wgPdfOutputExtension );
297  }
298  return array( $wgPdfOutputExtension, $mime );
299  }
300 
306  function getMetadata( $image, $path ) {
307  return serialize( $this->getPdfImage( $image, $path )->retrieveMetaData() );
308  }
309 
315  function isMetadataValid( $image, $metadata ) {
316  if ( !$metadata || $metadata === serialize(array()) ) {
317  return self::METADATA_BAD;
318  } elseif ( strpos( $metadata, 'mergedMetadata' ) === false ) {
320  }
321  return self::METADATA_GOOD;
322  }
323 
329  function formatMetadata( $image, $context = false ) {
330  $meta = $image->getMetadata();
331 
332  if ( !$meta ) {
333  return false;
334  }
336  $meta = unserialize( $meta );
338 
339  if ( !isset( $meta['mergedMetadata'] )
340  || !is_array( $meta['mergedMetadata'] )
341  || count( $meta['mergedMetadata'] ) < 1
342  ) {
343  return false;
344  }
345 
346  // Inherited from MediaHandler.
347  return $this->formatMetadataHelper( $meta['mergedMetadata'], $context );
348  }
349 
354  function pageCount( File $image ) {
355  $info = $this->getDimensionInfo( $image );
356 
357  return $info ? $info['pageCount'] : false;
358  }
359 
366  $index = $page; // MW starts pages at 1, as they are stored here
367 
368  $info = $this->getDimensionInfo( $image );
369  if ( $info && isset( $info['dimensionsByPage'][$index] ) ) {
370  return $info['dimensionsByPage'][$index];
371  }
372 
373  return false;
374  }
375 
376  protected function getDimensionInfo( File $file ) {
378  return $cache->getWithSetCallback(
379  $cache->makeKey( 'file-pdf', 'dimensions', $file->getSha1() ),
380  $cache::TTL_INDEFINITE,
381  function () use ( $file ) {
382  $data = $this->getMetaArray( $file );
383  if ( !$data || !isset( $data['Pages'] ) ) {
384  return false;
385  }
386  unset( $data['text'] ); // lower peak RAM
387 
388  $dimsByPage = [];
389  $count = intval( $data['Pages'] );
390  for ( $i = 1; $i <= $count; $i++ ) {
391  $dimsByPage[$i] = PdfImage::getPageSize( $data, $i );
392  }
393 
394  return [ 'pageCount' => $count, 'dimensionsByPage' => $dimsByPage ];
395  },
396  [ 'pcTTL' => $cache::TTL_INDEFINITE ]
397  );
398  }
399 
405  function getPageText( File $image, $page ) {
406  $data = $this->getMetaArray( $image );
407  if ( !$data || !isset( $data['text'] ) || !isset( $data['text'][$page - 1] ) ) {
408  return false;
409  }
410  return $data['text'][$page - 1];
411  }
412 
419  function getWarningConfig( $file ) {
420  return array(
421  'messages' => self::$messages,
422  'link' => '//www.mediawiki.org/wiki/Special:MyLanguage/Help:Security/PDF_files',
423  'module' => 'pdfhandler.messages',
424  );
425  }
426 
432  $resourceLoader->register( 'pdfhandler.messages', array(
433  'messages' => array_values( self::$messages ),
434  ) );
435  }
436 }
MediaHandler\removeBadFile
removeBadFile( $dstPath, $retval=0)
Check for zero-sized thumbnails.
Definition: MediaHandler.php:686
PdfHandler
Copyright © 2007 Martin Seidel (Xarax) jodeldi@gmx.de
Definition: PdfHandler_body.php:24
MediaTransformError
Basic media transform error class.
Definition: MediaTransformOutput.php:441
ThumbnailImage
Media transform output for images.
Definition: MediaTransformOutput.php:277
$context
error also a ContextSource you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition: hooks.txt:2612
PdfHandler\mustRender
mustRender( $file)
Definition: PdfHandler_body.php:51
wfMkdirParents
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
Definition: GlobalFunctions.php:2080
captcha-old.count
count
Definition: captcha-old.py:225
text
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition: design.txt:12
PdfHandler\parseParamString
parseParamString( $str)
Definition: PdfHandler_body.php:96
PdfHandler\isMultiPage
isMultiPage( $file)
Definition: PdfHandler_body.php:59
File\getSha1
getSha1()
Get the SHA-1 base 36 hash of the file.
Definition: File.php:2117
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
wfSuppressWarnings
wfSuppressWarnings( $end=false)
Reference-counted warning suppression.
Definition: GlobalFunctions.php:1974
PdfHandler\isMetadataValid
isMetadataValid( $image, $metadata)
Definition: PdfHandler_body.php:315
PdfImage::getPageSize
static getPageSize( $data, $page)
Definition: PdfHandler.image.php:67
unserialize
unserialize( $serialized)
Definition: ApiMessage.php:185
PdfHandler\makeParamString
makeParamString( $params)
Definition: PdfHandler_body.php:84
$params
$params
Definition: styleTest.css.php:40
wfHostname
wfHostname()
Fetch server name for use in error reporting etc.
Definition: GlobalFunctions.php:1435
serialize
serialize()
Definition: ApiMessage.php:177
PdfHandler\getDimensionInfo
getDimensionInfo(File $file)
Definition: PdfHandler_body.php:376
PdfHandler\getWarningConfig
getWarningConfig( $file)
Adds a warning about PDFs being potentially dangerous to the file page.
Definition: PdfHandler_body.php:419
PdfHandler\getPageText
getPageText(File $image, $page)
Definition: PdfHandler_body.php:405
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:304
PoolCounterWorkViaCallback
Convenience class for dealing with PoolCounters using callbacks.
Definition: PoolCounterWorkViaCallback.php:28
$messages
$messages
Definition: LogTests.i18n.php:8
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:1092
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
PdfImage
inspired by djvuimage from Brion Vibber modified and written by xarax
Definition: PdfHandler.image.php:30
MediaHandler\METADATA_COMPATIBLE
const METADATA_COMPATIBLE
Definition: MediaHandler.php:34
File
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition: File.php:51
wfRestoreWarnings
wfRestoreWarnings()
Definition: GlobalFunctions.php:1982
$page
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
Definition: hooks.txt:2536
ImageHandler
Media handler abstract base class for images.
Definition: ImageHandler.php:29
PdfHandler\pageCount
pageCount(File $image)
Definition: PdfHandler_body.php:354
PdfHandler\registerWarningModule
static registerWarningModule(&$resourceLoader)
Register a module with the warning messages in it.
Definition: PdfHandler_body.php:431
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
MimeMagic\singleton
static singleton()
Get an instance of this class.
Definition: MimeMagic.php:33
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:999
$image
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check $image
Definition: hooks.txt:783
ImageHandler\normaliseParams
normaliseParams( $image, &$params)
Definition: ImageHandler.php:86
$mime
if( $ext=='php'|| $ext=='php5') $mime
Definition: router.php:65
PdfHandler\getMetaArray
getMetaArray( $image)
Definition: PdfHandler_body.php:251
$value
$value
Definition: styleTest.css.php:45
PdfHandler\getImageSize
getImageSize( $image, $path)
Definition: PdfHandler_body.php:280
$retval
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account incomplete not yet checked for validity & $retval
Definition: hooks.txt:246
PdfHandler\doThumbError
doThumbError( $width, $height, $msg)
Definition: PdfHandler_body.php:133
PdfHandler\getMetadata
getMetadata( $image, $path)
Definition: PdfHandler_body.php:306
TransformParameterError
Shortcut class for parameter validation errors.
Definition: MediaTransformOutput.php:487
wfEscapeShellArg
wfEscapeShellArg()
Version of escapeshellarg() that works better on Windows.
Definition: GlobalFunctions.php:2195
PdfHandler\formatMetadata
formatMetadata( $image, $context=false)
Definition: PdfHandler_body.php:329
PdfHandler\getScriptParams
getScriptParams( $params)
Definition: PdfHandler_body.php:110
$resourceLoader
error also a ContextSource you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext such as when responding to a resource loader request or generating HTML output & $resourceLoader
Definition: hooks.txt:2612
PdfHandler\doTransform
doTransform( $image, $dstPath, $dstUrl, $params, $flags=0)
Definition: PdfHandler_body.php:146
PdfHandler\getParamMap
getParamMap()
Definition: PdfHandler_body.php:120
$cache
$cache
Definition: mcc.php:33
ObjectCache\getMainWANInstance
static getMainWANInstance()
Get the main WAN cache object.
Definition: ObjectCache.php:370
$ext
$ext
Definition: NoLocalSettings.php:25
MediaHandler\formatMetadataHelper
formatMetadataHelper( $metadataArray, $context=false)
sorts the visible/invisible field.
Definition: MediaHandler.php:505
$path
$path
Definition: NoLocalSettings.php:26
MediaHandler\METADATA_BAD
const METADATA_BAD
Definition: MediaHandler.php:33
wfMessage
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt
PdfHandler\getPageDimensions
getPageDimensions(File $image, $page)
Definition: PdfHandler_body.php:365
PdfHandler\isEnabled
isEnabled()
Definition: PdfHandler_body.php:35
PdfHandler\getThumbType
getThumbType( $ext, $mime, $params=null)
Definition: PdfHandler_body.php:290
PdfHandler\getPdfImage
getPdfImage( $image, $path)
Definition: PdfHandler_body.php:235
$flags
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2749
PdfHandler\$messages
static $messages
Definition: PdfHandler_body.php:25
MediaHandler\METADATA_GOOD
const METADATA_GOOD
Definition: MediaHandler.php:32
array
the array() calling protocol came about after MediaWiki 1.4rc1.
wfShellExecWithStderr
wfShellExecWithStderr( $cmd, &$retval=null, $environ=[], $limits=[])
Execute a shell command, returning both stdout and stderr.
Definition: GlobalFunctions.php:2531
PdfHandler\validateParam
validateParam( $name, $value)
Definition: PdfHandler_body.php:68