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