MediaWiki  1.30.1
PdfHandler.image.php
Go to the documentation of this file.
1 <?php
23 use UtfNormal\Validator;
24 
30 class PdfImage {
31 
35  function __construct( $filename ) {
36  $this->mFilename = $filename;
37  }
38 
42  public function isValid() {
43  return true;
44  }
45 
49  public function getImageSize() {
50  $data = $this->retrieveMetadata();
51  $size = self::getPageSize( $data, 1 );
52 
53  if ( $size ) {
54  $width = $size['width'];
55  $height = $size['height'];
56  return [ $width, $height, 'Pdf',
57  "width=\"$width\" height=\"$height\"" ];
58  }
59  return false;
60  }
61 
67  public static function getPageSize( $data, $page ) {
68  global $wgPdfHandlerDpi;
69 
70  if ( isset( $data['pages'][$page]['Page size'] ) ) {
71  $o = $data['pages'][$page]['Page size'];
72  } elseif ( isset( $data['Page size'] ) ) {
73  $o = $data['Page size'];
74  } else {
75  $o = false;
76  }
77 
78  if ( $o ) {
79  if ( isset( $data['pages'][$page]['Page rot'] ) ) {
80  $r = $data['pages'][$page]['Page rot'];
81  } elseif ( isset( $data['Page rot'] ) ) {
82  $r = $data['Page rot'];
83  } else {
84  $r = 0;
85  }
86  $size = explode( 'x', $o, 2 );
87 
88  if ( $size ) {
89  $width = intval( trim( $size[0] ) / 72 * $wgPdfHandlerDpi );
90  $height = explode( ' ', trim( $size[1] ), 2 );
91  $height = intval( trim( $height[0] ) / 72 * $wgPdfHandlerDpi );
92  if ( ( $r / 90 ) & 1 ) {
93  // Swap width and height for landscape pages
94  $t = $width;
95  $width = $height;
96  $height = $t;
97  }
98 
99  return [
100  'width' => $width,
101  'height' => $height
102  ];
103  }
104  }
105 
106  return false;
107  }
108 
112  public function retrieveMetaData() {
113  global $wgPdfInfo, $wgPdftoText;
114 
115  if ( $wgPdfInfo ) {
116  // Note in poppler 0.26 the -meta and page data options worked together,
117  // but as of poppler 0.48 they must be queried separately.
118  // https://bugs.freedesktop.org/show_bug.cgi?id=96801
119  $cmd = wfEscapeShellArg( $wgPdfInfo ) .
120  " -enc UTF-8 " . # Report metadata as UTF-8 text...
121  " -meta " . # Report XMP metadata
122  wfEscapeShellArg( $this->mFilename );
123  $retval = '';
124  $resultMeta = wfShellExec( $cmd, $retval );
125 
126  $cmd = wfEscapeShellArg( $wgPdfInfo ) .
127  " -enc UTF-8 " . # Report metadata as UTF-8 text...
128  " -l 9999999 " . # Report page sizes for all pages
129  wfEscapeShellArg( $this->mFilename );
130  $retval = '';
131  $resultPages = wfShellExec( $cmd, $retval );
132 
133  $dump = $resultMeta . $resultPages;
134  $data = $this->convertDumpToArray( $dump );
135  } else {
136  $data = null;
137  }
138 
139  // Read text layer
140  if ( isset( $wgPdftoText ) ) {
141  $cmd = wfEscapeShellArg( $wgPdftoText ) . ' '. wfEscapeShellArg( $this->mFilename ) . ' - ';
142  wfDebug( __METHOD__.": $cmd\n" );
143  $retval = '';
144  $txt = wfShellExec( $cmd, $retval );
145  if ( $retval == 0 ) {
146  $txt = str_replace( "\r\n", "\n", $txt );
147  $pages = explode( "\f", $txt );
148  foreach ( $pages as $page => $pageText ) {
149  // Get rid of invalid UTF-8, strip control characters
150  // Note we need to do this per page, as \f page feed would be stripped.
151  $pages[$page] = Validator::cleanUp( $pageText );
152  }
153  $data['text'] = $pages;
154  }
155  }
156  return $data;
157  }
158 
163  protected function convertDumpToArray( $dump ) {
164  if ( strval( $dump ) == '' ) {
165  return false;
166  }
167 
168  $lines = explode( "\n", $dump );
169  $data = [];
170 
171  // Metadata is always the last item, and spans multiple lines.
172  $inMetadata = false;
173 
174  // Basically this loop will go through each line, splitting key value
175  // pairs on the colon, until it gets to a "Metadata:\n" at which point
176  // it will gather all remaining lines into the xmp key.
177  foreach ( $lines as $line ) {
178  if ( $inMetadata ) {
179  // Handle XMP differently due to diffence in line break
180  $data['xmp'] .= "\n$line";
181  continue;
182  }
183  $bits = explode( ':', $line, 2 );
184  if ( count( $bits ) > 1 ) {
185  $key = trim( $bits[0] );
186  if ( $key === 'Metadata' ) {
187  $inMetadata = true;
188  $data['xmp'] = '';
189  continue;
190  }
191  $value = trim( $bits[1] );
192  $matches = [];
193  // "Page xx rot" will be in poppler 0.20's pdfinfo output
194  // See https://bugs.freedesktop.org/show_bug.cgi?id=41867
195  if ( preg_match( '/^Page +(\d+) (size|rot)$/', $key, $matches ) ) {
196  $data['pages'][$matches[1]][$matches[2] == 'size' ? 'Page size' : 'Page rot'] = $value;
197  } else {
198  $data[$key] = $value;
199  }
200  }
201  }
202  $data = $this->postProcessDump( $data );
203  return $data;
204  }
205 
215  protected function postProcessDump( array $data ) {
216  $meta = new BitmapMetadataHandler();
217  $items = [];
218  foreach ( $data as $key => $val ) {
219  switch ( $key ) {
220  case 'Title':
221  $items['ObjectName'] = $val;
222  break;
223  case 'Subject':
224  $items['ImageDescription'] = $val;
225  break;
226  case 'Keywords':
227  // Sometimes we have empty keywords. This seems
228  // to be a product of how pdfinfo deals with keywords
229  // with spaces in them. Filter such empty keywords
230  $keyList = array_filter( explode( ' ', $val ) );
231  if ( count( $keyList ) > 0 ) {
232  $items['Keywords'] = $keyList;
233  }
234  break;
235  case 'Author':
236  $items['Artist'] = $val;
237  break;
238  case 'Creator':
239  // Program used to create file.
240  // Different from program used to convert to pdf.
241  $items['Software'] = $val;
242  break;
243  case 'Producer':
244  // Conversion program
245  $items['pdf-Producer'] = $val;
246  break;
247  case 'ModTime':
248  $timestamp = wfTimestamp( TS_EXIF, $val );
249  if ( $timestamp ) {
250  // 'if' is just paranoia
251  $items['DateTime'] = $timestamp;
252  }
253  break;
254  case 'CreationTime':
255  $timestamp = wfTimestamp( TS_EXIF, $val );
256  if ( $timestamp ) {
257  $items['DateTimeDigitized'] = $timestamp;
258  }
259  break;
260  // These last two (version and encryption) I was unsure
261  // if we should include in the table, since they aren't
262  // all that useful to editors. I leaned on the side
263  // of including. However not including if file
264  // is optimized/linearized since that is really useless
265  // to an editor.
266  case 'PDF version':
267  $items['pdf-Version'] = $val;
268  break;
269  case 'Encrypted':
270  // @todo: The value isn't i18n-ised. The appropriate
271  // place to do that is in FormatMetadata.php
272  // should add a hook a there.
273  // For reference, if encrypted this fields value looks like:
274  // "yes (print:yes copy:no change:no addNotes:no)"
275  $items['pdf-Encrypted'] = $val;
276  break;
277  // Note 'pages' and 'Pages' are different keys (!)
278  case 'pages':
279  // A pdf document can have multiple sized pages in it.
280  // (However 95% of the time, all pages are the same size)
281  // get a list of all the unique page sizes in document.
282  // This doesn't do anything with rotation as of yet,
283  // mostly because I am unsure of what a good way to
284  // present that information to the user would be.
285  $pageSizes = [];
286  foreach ( $val as $page ) {
287  if ( isset( $page['Page size'] ) ) {
288  $pageSizes[$page['Page size']] = true;
289  }
290  }
291 
292  $pageSizeArray = array_keys( $pageSizes );
293  if ( count( $pageSizeArray ) > 0 ) {
294  $items['pdf-PageSize'] = $pageSizeArray;
295  }
296  break;
297  }
298 
299  }
300  $meta->addMetadata( $items, 'native' );
301 
302  if ( isset( $data['xmp'] ) && function_exists( 'xml_parser_create_ns' ) ) {
303  // func exists verifies that the xml extension required for XMPReader
304  // is present (Almost always is present)
305  // @todo: This only handles generic xmp properties. Would be improved
306  // by handling pdf xmp properties (pdf and pdfx) via XMPInfo hook.
307  $xmp = new XMPReader( LoggerFactory::getInstance( 'XMP' ) );
308  $xmp->parse( $data['xmp'] );
309  $xmpRes = $xmp->getResults();
310  foreach ( $xmpRes as $type => $xmpSection ) {
311  $meta->addMetadata( $xmpSection, $type );
312  }
313  }
314  unset( $data['xmp'] );
315  $data['mergedMetadata'] = $meta->getMetadataArray();
316  return $data;
317  }
318 }
PdfImage::retrieveMetaData
retrieveMetaData()
Definition: PdfHandler.image.php:112
captcha-old.count
count
Definition: captcha-old.py:249
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
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:2040
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
PdfImage::getPageSize
static getPageSize( $data, $page)
Definition: PdfHandler.image.php:67
PdfImage::convertDumpToArray
convertDumpToArray( $dump)
Definition: PdfHandler.image.php:163
page
target page
Definition: All_system_messages.txt:1267
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
pages
The ContentHandler facility adds support for arbitrary content types on wiki pages
Definition: contenthandler.txt:1
PdfImage
inspired by djvuimage from Brion Vibber modified and written by xarax
Definition: PdfHandler.image.php:30
BitmapMetadataHandler
Class to deal with reconciling and extracting metadata from bitmap images.
Definition: BitmapMetadataHandler.php:36
$matches
$matches
Definition: NoLocalSettings.php:24
$lines
$lines
Definition: router.php:61
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
PdfImage::__construct
__construct( $filename)
Definition: PdfHandler.image.php:35
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:1047
XMPReader
Class for reading xmp data containing properties relevant to images, and spitting out an array that F...
Definition: XMP.php:53
$line
$line
Definition: cdb.php:58
$value
$value
Definition: styleTest.css.php:45
$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:244
wfEscapeShellArg
wfEscapeShellArg()
Version of escapeshellarg() that works better on Windows.
Definition: GlobalFunctions.php:2243
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
LoggerFactory
MediaWiki Logger LoggerFactory implements a PSR[0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method. MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances. The "Spi" in MediaWiki\Logger\Spi stands for "service provider interface". An SPI is an API intended to be implemented or extended by a third party. This software design pattern is intended to enable framework extension and replaceable components. It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki. The service provider interface allows the backend logging library to be implemented in multiple ways. The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime. This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance. Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
$t
$t
Definition: testCompression.php:67
PdfImage::postProcessDump
postProcessDump(array $data)
Postprocess the metadata (convert xmp into useful form, etc)
Definition: PdfHandler.image.php:215
array
the array() calling protocol came about after MediaWiki 1.4rc1.
PdfImage::getImageSize
getImageSize()
Definition: PdfHandler.image.php:49
wfShellExec
wfShellExec( $cmd, &$retval=null, $environ=[], $limits=[], $options=[])
Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported...
Definition: GlobalFunctions.php:2283
$type
$type
Definition: testCompression.php:48
PdfImage::isValid
isValid()
Definition: PdfHandler.image.php:42