MediaWiki  1.30.0
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  $cmd = wfEscapeShellArg( $wgPdfInfo ) .
117  " -enc UTF-8 " . # Report metadata as UTF-8 text...
118  " -l 9999999 " . # Report page sizes for all pages
119  " -meta " . # Report XMP metadata
120  wfEscapeShellArg( $this->mFilename );
121  $retval = '';
122  $dump = wfShellExec( $cmd, $retval );
123  $data = $this->convertDumpToArray( $dump );
124  } else {
125  $data = null;
126  }
127 
128  // Read text layer
129  if ( isset( $wgPdftoText ) ) {
130  $cmd = wfEscapeShellArg( $wgPdftoText ) . ' '. wfEscapeShellArg( $this->mFilename ) . ' - ';
131  wfDebug( __METHOD__.": $cmd\n" );
132  $retval = '';
133  $txt = wfShellExec( $cmd, $retval );
134  if ( $retval == 0 ) {
135  $txt = str_replace( "\r\n", "\n", $txt );
136  $pages = explode( "\f", $txt );
137  foreach ( $pages as $page => $pageText ) {
138  // Get rid of invalid UTF-8, strip control characters
139  // Note we need to do this per page, as \f page feed would be stripped.
140  $pages[$page] = Validator::cleanUp( $pageText );
141  }
142  $data['text'] = $pages;
143  }
144  }
145  return $data;
146  }
147 
152  protected function convertDumpToArray( $dump ) {
153  if ( strval( $dump ) == '' ) {
154  return false;
155  }
156 
157  $lines = explode( "\n", $dump );
158  $data = [];
159 
160  // Metadata is always the last item, and spans multiple lines.
161  $inMetadata = false;
162 
163  // Basically this loop will go through each line, splitting key value
164  // pairs on the colon, until it gets to a "Metadata:\n" at which point
165  // it will gather all remaining lines into the xmp key.
166  foreach ( $lines as $line ) {
167  if ( $inMetadata ) {
168  // Handle XMP differently due to diffence in line break
169  $data['xmp'] .= "\n$line";
170  continue;
171  }
172  $bits = explode( ':', $line, 2 );
173  if ( count( $bits ) > 1 ) {
174  $key = trim( $bits[0] );
175  if ( $key === 'Metadata' ) {
176  $inMetadata = true;
177  $data['xmp'] = '';
178  continue;
179  }
180  $value = trim( $bits[1] );
181  $matches = [];
182  // "Page xx rot" will be in poppler 0.20's pdfinfo output
183  // See https://bugs.freedesktop.org/show_bug.cgi?id=41867
184  if ( preg_match( '/^Page +(\d+) (size|rot)$/', $key, $matches ) ) {
185  $data['pages'][$matches[1]][$matches[2] == 'size' ? 'Page size' : 'Page rot'] = $value;
186  } else {
187  $data[$key] = $value;
188  }
189  }
190  }
191  $data = $this->postProcessDump( $data );
192  return $data;
193  }
194 
204  protected function postProcessDump( array $data ) {
205  $meta = new BitmapMetadataHandler();
206  $items = [];
207  foreach ( $data as $key => $val ) {
208  switch ( $key ) {
209  case 'Title':
210  $items['ObjectName'] = $val;
211  break;
212  case 'Subject':
213  $items['ImageDescription'] = $val;
214  break;
215  case 'Keywords':
216  // Sometimes we have empty keywords. This seems
217  // to be a product of how pdfinfo deals with keywords
218  // with spaces in them. Filter such empty keywords
219  $keyList = array_filter( explode( ' ', $val ) );
220  if ( count( $keyList ) > 0 ) {
221  $items['Keywords'] = $keyList;
222  }
223  break;
224  case 'Author':
225  $items['Artist'] = $val;
226  break;
227  case 'Creator':
228  // Program used to create file.
229  // Different from program used to convert to pdf.
230  $items['Software'] = $val;
231  break;
232  case 'Producer':
233  // Conversion program
234  $items['pdf-Producer'] = $val;
235  break;
236  case 'ModTime':
237  $timestamp = wfTimestamp( TS_EXIF, $val );
238  if ( $timestamp ) {
239  // 'if' is just paranoia
240  $items['DateTime'] = $timestamp;
241  }
242  break;
243  case 'CreationTime':
244  $timestamp = wfTimestamp( TS_EXIF, $val );
245  if ( $timestamp ) {
246  $items['DateTimeDigitized'] = $timestamp;
247  }
248  break;
249  // These last two (version and encryption) I was unsure
250  // if we should include in the table, since they aren't
251  // all that useful to editors. I leaned on the side
252  // of including. However not including if file
253  // is optimized/linearized since that is really useless
254  // to an editor.
255  case 'PDF version':
256  $items['pdf-Version'] = $val;
257  break;
258  case 'Encrypted':
259  // @todo: The value isn't i18n-ised. The appropriate
260  // place to do that is in FormatMetadata.php
261  // should add a hook a there.
262  // For reference, if encrypted this fields value looks like:
263  // "yes (print:yes copy:no change:no addNotes:no)"
264  $items['pdf-Encrypted'] = $val;
265  break;
266  // Note 'pages' and 'Pages' are different keys (!)
267  case 'pages':
268  // A pdf document can have multiple sized pages in it.
269  // (However 95% of the time, all pages are the same size)
270  // get a list of all the unique page sizes in document.
271  // This doesn't do anything with rotation as of yet,
272  // mostly because I am unsure of what a good way to
273  // present that information to the user would be.
274  $pageSizes = [];
275  foreach ( $val as $page ) {
276  if ( isset( $page['Page size'] ) ) {
277  $pageSizes[$page['Page size']] = true;
278  }
279  }
280 
281  $pageSizeArray = array_keys( $pageSizes );
282  if ( count( $pageSizeArray ) > 0 ) {
283  $items['pdf-PageSize'] = $pageSizeArray;
284  }
285  break;
286  }
287 
288  }
289  $meta->addMetadata( $items, 'native' );
290 
291  if ( isset( $data['xmp'] ) && function_exists( 'xml_parser_create_ns' ) ) {
292  // func exists verifies that the xml extension required for XMPReader
293  // is present (Almost always is present)
294  // @todo: This only handles generic xmp properties. Would be improved
295  // by handling pdf xmp properties (pdf and pdfx) via XMPInfo hook.
296  $xmp = new XMPReader( LoggerFactory::getInstance( 'XMP' ) );
297  $xmp->parse( $data['xmp'] );
298  $xmpRes = $xmp->getResults();
299  foreach ( $xmpRes as $type => $xmpSection ) {
300  $meta->addMetadata( $xmpSection, $type );
301  }
302  }
303  unset( $data['xmp'] );
304  $data['mergedMetadata'] = $meta->getMetadataArray();
305  return $data;
306  }
307 }
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:152
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:67
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:204
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