MediaWiki  1.32.5
PdfImage.php
Go to the documentation of this file.
1 <?php
24 use UtfNormal\Validator;
25 use Wikimedia\XMPReader\Reader as XMPReader;
26 
32 class PdfImage {
33 
37  private $mFilename;
38 
42  function __construct( $filename ) {
43  $this->mFilename = $filename;
44  }
45 
49  public function isValid() {
50  return true;
51  }
52 
56  public function getImageSize() {
57  $data = $this->retrieveMetadata();
58  $size = self::getPageSize( $data, 1 );
59 
60  if ( $size ) {
61  $width = $size['width'];
62  $height = $size['height'];
63  return [ $width, $height, 'Pdf',
64  "width=\"$width\" height=\"$height\"" ];
65  }
66  return false;
67  }
68 
74  public static function getPageSize( $data, $page ) {
75  global $wgPdfHandlerDpi;
76 
77  if ( isset( $data['pages'][$page]['Page size'] ) ) {
78  $o = $data['pages'][$page]['Page size'];
79  } elseif ( isset( $data['Page size'] ) ) {
80  $o = $data['Page size'];
81  } else {
82  $o = false;
83  }
84 
85  if ( $o ) {
86  if ( isset( $data['pages'][$page]['Page rot'] ) ) {
87  $r = $data['pages'][$page]['Page rot'];
88  } elseif ( isset( $data['Page rot'] ) ) {
89  $r = $data['Page rot'];
90  } else {
91  $r = 0;
92  }
93  $size = explode( 'x', $o, 2 );
94 
95  if ( $size ) {
96  $width = intval( trim( $size[0] ) / 72 * $wgPdfHandlerDpi );
97  $height = explode( ' ', trim( $size[1] ), 2 );
98  $height = intval( trim( $height[0] ) / 72 * $wgPdfHandlerDpi );
99  if ( ( $r / 90 ) & 1 ) {
100  // Swap width and height for landscape pages
101  $t = $width;
102  $width = $height;
103  $height = $t;
104  }
105 
106  return [
107  'width' => $width,
108  'height' => $height
109  ];
110  }
111  }
112 
113  return false;
114  }
115 
119  public function retrieveMetaData() {
120  global $wgPdfInfo, $wgPdftoText;
121 
122  if ( $wgPdfInfo ) {
123  // Note in poppler 0.26 the -meta and page data options worked together,
124  // but as of poppler 0.48 they must be queried separately.
125  // https://bugs.freedesktop.org/show_bug.cgi?id=96801
126  $cmdMeta = [
127  $wgPdfInfo,
128  '-enc', 'UTF-8', # Report metadata as UTF-8 text...
129  '-meta', # Report XMP metadata
131  ];
132  $resultMeta = Shell::command( $cmdMeta )
133  ->execute();
134 
135  $cmdPages = [
136  $wgPdfInfo,
137  '-enc', 'UTF-8', # Report metadata as UTF-8 text...
138  '-l', '9999999', # Report page sizes for all pages
140  ];
141  $resultPages = Shell::command( $cmdPages )
142  ->execute();
143 
144  $dump = $resultMeta->getStdout() . $resultPages->getStdout();
145  $data = $this->convertDumpToArray( $dump );
146  } else {
147  $data = null;
148  }
149 
150  // Read text layer
151  if ( isset( $wgPdftoText ) ) {
152  $cmd = [ $wgPdftoText, $this->mFilename, '-' ];
153  $result = Shell::command( $cmd )
154  ->execute();
155  $retval = $result->getExitCode();
156  $txt = $result->getStdout();
157  if ( $retval == 0 ) {
158  $txt = str_replace( "\r\n", "\n", $txt );
159  $pages = explode( "\f", $txt );
160  foreach ( $pages as $page => $pageText ) {
161  // Get rid of invalid UTF-8, strip control characters
162  // Note we need to do this per page, as \f page feed would be stripped.
163  $pages[$page] = Validator::cleanUp( $pageText );
164  }
165  $data['text'] = $pages;
166  }
167  }
168  return $data;
169  }
170 
175  protected function convertDumpToArray( $dump ) {
176  if ( strval( $dump ) == '' ) {
177  return false;
178  }
179 
180  $lines = explode( "\n", $dump );
181  $data = [];
182 
183  // Metadata is always the last item, and spans multiple lines.
184  $inMetadata = false;
185 
186  // Basically this loop will go through each line, splitting key value
187  // pairs on the colon, until it gets to a "Metadata:\n" at which point
188  // it will gather all remaining lines into the xmp key.
189  foreach ( $lines as $line ) {
190  if ( $inMetadata ) {
191  // Handle XMP differently due to diffence in line break
192  $data['xmp'] .= "\n$line";
193  continue;
194  }
195  $bits = explode( ':', $line, 2 );
196  if ( count( $bits ) > 1 ) {
197  $key = trim( $bits[0] );
198  if ( $key === 'Metadata' ) {
199  $inMetadata = true;
200  $data['xmp'] = '';
201  continue;
202  }
203  $value = trim( $bits[1] );
204  $matches = [];
205  // "Page xx rot" will be in poppler 0.20's pdfinfo output
206  // See https://bugs.freedesktop.org/show_bug.cgi?id=41867
207  if ( preg_match( '/^Page +(\d+) (size|rot)$/', $key, $matches ) ) {
208  $data['pages'][$matches[1]][$matches[2] == 'size' ? 'Page size' : 'Page rot'] = $value;
209  } else {
210  $data[$key] = $value;
211  }
212  }
213  }
214  $data = $this->postProcessDump( $data );
215  return $data;
216  }
217 
227  protected function postProcessDump( array $data ) {
228  $meta = new BitmapMetadataHandler();
229  $items = [];
230  foreach ( $data as $key => $val ) {
231  switch ( $key ) {
232  case 'Title':
233  $items['ObjectName'] = $val;
234  break;
235  case 'Subject':
236  $items['ImageDescription'] = $val;
237  break;
238  case 'Keywords':
239  // Sometimes we have empty keywords. This seems
240  // to be a product of how pdfinfo deals with keywords
241  // with spaces in them. Filter such empty keywords
242  $keyList = array_filter( explode( ' ', $val ) );
243  if ( count( $keyList ) > 0 ) {
244  $items['Keywords'] = $keyList;
245  }
246  break;
247  case 'Author':
248  $items['Artist'] = $val;
249  break;
250  case 'Creator':
251  // Program used to create file.
252  // Different from program used to convert to pdf.
253  $items['Software'] = $val;
254  break;
255  case 'Producer':
256  // Conversion program
257  $items['pdf-Producer'] = $val;
258  break;
259  case 'ModTime':
260  $timestamp = wfTimestamp( TS_EXIF, $val );
261  if ( $timestamp ) {
262  // 'if' is just paranoia
263  $items['DateTime'] = $timestamp;
264  }
265  break;
266  case 'CreationTime':
267  $timestamp = wfTimestamp( TS_EXIF, $val );
268  if ( $timestamp ) {
269  $items['DateTimeDigitized'] = $timestamp;
270  }
271  break;
272  // These last two (version and encryption) I was unsure
273  // if we should include in the table, since they aren't
274  // all that useful to editors. I leaned on the side
275  // of including. However not including if file
276  // is optimized/linearized since that is really useless
277  // to an editor.
278  case 'PDF version':
279  $items['pdf-Version'] = $val;
280  break;
281  case 'Encrypted':
282  // @todo: The value isn't i18n-ised. The appropriate
283  // place to do that is in FormatMetadata.php
284  // should add a hook a there.
285  // For reference, if encrypted this fields value looks like:
286  // "yes (print:yes copy:no change:no addNotes:no)"
287  $items['pdf-Encrypted'] = $val;
288  break;
289  // Note 'pages' and 'Pages' are different keys (!)
290  case 'pages':
291  // A pdf document can have multiple sized pages in it.
292  // (However 95% of the time, all pages are the same size)
293  // get a list of all the unique page sizes in document.
294  // This doesn't do anything with rotation as of yet,
295  // mostly because I am unsure of what a good way to
296  // present that information to the user would be.
297  $pageSizes = [];
298  foreach ( $val as $page ) {
299  if ( isset( $page['Page size'] ) ) {
300  $pageSizes[$page['Page size']] = true;
301  }
302  }
303 
304  $pageSizeArray = array_keys( $pageSizes );
305  if ( count( $pageSizeArray ) > 0 ) {
306  $items['pdf-PageSize'] = $pageSizeArray;
307  }
308  break;
309  }
310 
311  }
312  $meta->addMetadata( $items, 'native' );
313 
314  if ( isset( $data['xmp'] ) && XMPReader::isSupported() ) {
315  // @todo: This only handles generic xmp properties. Would be improved
316  // by handling pdf xmp properties (pdf and pdfx) via a hook.
317  $xmp = new XMPReader( LoggerFactory::getInstance( 'XMP' ) );
318  $xmp->parse( $data['xmp'] );
319  $xmpRes = $xmp->getResults();
320  foreach ( $xmpRes as $type => $xmpSection ) {
321  $meta->addMetadata( $xmpSection, $type );
322  }
323  }
324  unset( $data['xmp'] );
325  $data['mergedMetadata'] = $meta->getMetadataArray();
326  return $data;
327  }
328 }
MediaWiki\Shell\Shell
Executes shell commands.
Definition: Shell.php:44
PdfImage\$mFilename
string $mFilename
Definition: PdfImage.php:37
PdfImage\retrieveMetaData
retrieveMetaData()
Definition: PdfImage.php:119
captcha-old.count
count
Definition: captcha-old.py:249
$result
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED since 1.16! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:2042
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1954
PdfImage\getPageSize
static getPageSize( $data, $page)
Definition: PdfImage.php:74
PdfImage\convertDumpToArray
convertDumpToArray( $dump)
Definition: PdfImage.php:175
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: PdfImage.php:32
BitmapMetadataHandler
Class to deal with reconciling and extracting metadata from bitmap images.
Definition: BitmapMetadataHandler.php:37
$matches
$matches
Definition: NoLocalSettings.php:24
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
$lines
$lines
Definition: router.php:61
array
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
PdfImage\__construct
__construct( $filename)
Definition: PdfImage.php:42
XMPReader
Definition: XMPReader.php:33
$line
$line
Definition: cdb.php:59
$value
$value
Definition: styleTest.css.php:49
$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
text
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second as well as the first line of the second redirect text
Definition: All_system_messages.txt:1267
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:69
PdfImage\postProcessDump
postProcessDump(array $data)
Postprocess the metadata (convert xmp into useful form, etc)
Definition: PdfImage.php:227
PdfImage\getImageSize
getImageSize()
Definition: PdfImage.php:56
$type
$type
Definition: testCompression.php:48
PdfImage\isValid
isValid()
Definition: PdfImage.php:49