DjVuHandler.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. <?php
  2. /**
  3. * Handler for DjVu images.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. * @ingroup Media
  22. */
  23. use MediaWiki\MediaWikiServices;
  24. use MediaWiki\Shell\Shell;
  25. /**
  26. * Handler for DjVu images
  27. *
  28. * @ingroup Media
  29. */
  30. class DjVuHandler extends ImageHandler {
  31. const EXPENSIVE_SIZE_LIMIT = 10485760; // 10MiB
  32. /**
  33. * @return bool
  34. */
  35. public function isEnabled() {
  36. global $wgDjvuRenderer, $wgDjvuDump, $wgDjvuToXML;
  37. if ( !$wgDjvuRenderer || ( !$wgDjvuDump && !$wgDjvuToXML ) ) {
  38. wfDebug( "DjVu is disabled, please set \$wgDjvuRenderer and \$wgDjvuDump\n" );
  39. return false;
  40. } else {
  41. return true;
  42. }
  43. }
  44. /**
  45. * @param File $file
  46. * @return bool
  47. */
  48. public function mustRender( $file ) {
  49. return true;
  50. }
  51. /**
  52. * True if creating thumbnails from the file is large or otherwise resource-intensive.
  53. * @param File $file
  54. * @return bool
  55. */
  56. public function isExpensiveToThumbnail( $file ) {
  57. return $file->getSize() > static::EXPENSIVE_SIZE_LIMIT;
  58. }
  59. /**
  60. * @param File $file
  61. * @return bool
  62. */
  63. public function isMultiPage( $file ) {
  64. return true;
  65. }
  66. /**
  67. * @return array
  68. */
  69. public function getParamMap() {
  70. return [
  71. 'img_width' => 'width',
  72. 'img_page' => 'page',
  73. ];
  74. }
  75. /**
  76. * @param string $name
  77. * @param mixed $value
  78. * @return bool
  79. */
  80. public function validateParam( $name, $value ) {
  81. if ( $name === 'page' && trim( $value ) !== (string)intval( $value ) ) {
  82. // Extra junk on the end of page, probably actually a caption
  83. // e.g. [[File:Foo.djvu|thumb|Page 3 of the document shows foo]]
  84. return false;
  85. }
  86. if ( in_array( $name, [ 'width', 'height', 'page' ] ) ) {
  87. if ( $value <= 0 ) {
  88. return false;
  89. } else {
  90. return true;
  91. }
  92. } else {
  93. return false;
  94. }
  95. }
  96. /**
  97. * @param array $params
  98. * @return bool|string
  99. */
  100. public function makeParamString( $params ) {
  101. $page = $params['page'] ?? 1;
  102. if ( !isset( $params['width'] ) ) {
  103. return false;
  104. }
  105. return "page{$page}-{$params['width']}px";
  106. }
  107. /**
  108. * @param string $str
  109. * @return array|bool
  110. */
  111. public function parseParamString( $str ) {
  112. $m = false;
  113. if ( preg_match( '/^page(\d+)-(\d+)px$/', $str, $m ) ) {
  114. return [ 'width' => $m[2], 'page' => $m[1] ];
  115. } else {
  116. return false;
  117. }
  118. }
  119. /**
  120. * @param array $params
  121. * @return array
  122. */
  123. protected function getScriptParams( $params ) {
  124. return [
  125. 'width' => $params['width'],
  126. 'page' => $params['page'],
  127. ];
  128. }
  129. /**
  130. * @param File $image
  131. * @param string $dstPath
  132. * @param string $dstUrl
  133. * @param array $params
  134. * @param int $flags
  135. * @return MediaTransformError|ThumbnailImage|TransformParameterError
  136. */
  137. function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
  138. global $wgDjvuRenderer, $wgDjvuPostProcessor;
  139. if ( !$this->normaliseParams( $image, $params ) ) {
  140. return new TransformParameterError( $params );
  141. }
  142. $width = $params['width'];
  143. $height = $params['height'];
  144. $page = $params['page'];
  145. if ( $flags & self::TRANSFORM_LATER ) {
  146. $params = [
  147. 'width' => $width,
  148. 'height' => $height,
  149. 'page' => $page
  150. ];
  151. return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
  152. }
  153. if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
  154. return new MediaTransformError(
  155. 'thumbnail_error',
  156. $width,
  157. $height,
  158. wfMessage( 'thumbnail_dest_directory' )
  159. );
  160. }
  161. // Get local copy source for shell scripts
  162. // Thumbnail extraction is very inefficient for large files.
  163. // Provide a way to pool count limit the number of downloaders.
  164. if ( $image->getSize() >= 1e7 ) { // 10MB
  165. $work = new PoolCounterWorkViaCallback( 'GetLocalFileCopy', sha1( $image->getName() ),
  166. [
  167. 'doWork' => function () use ( $image ) {
  168. return $image->getLocalRefPath();
  169. }
  170. ]
  171. );
  172. $srcPath = $work->execute();
  173. } else {
  174. $srcPath = $image->getLocalRefPath();
  175. }
  176. if ( $srcPath === false ) { // Failed to get local copy
  177. wfDebugLog( 'thumbnail',
  178. sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
  179. wfHostname(), $image->getName() ) );
  180. return new MediaTransformError( 'thumbnail_error',
  181. $params['width'], $params['height'],
  182. wfMessage( 'filemissing' )
  183. );
  184. }
  185. # Use a subshell (brackets) to aggregate stderr from both pipeline commands
  186. # before redirecting it to the overall stdout. This works in both Linux and Windows XP.
  187. $cmd = '(' . Shell::escape(
  188. $wgDjvuRenderer,
  189. "-format=ppm",
  190. "-page={$page}",
  191. "-size={$params['physicalWidth']}x{$params['physicalHeight']}",
  192. $srcPath );
  193. if ( $wgDjvuPostProcessor ) {
  194. $cmd .= " | {$wgDjvuPostProcessor}";
  195. }
  196. $cmd .= ' > ' . Shell::escape( $dstPath ) . ') 2>&1';
  197. wfDebug( __METHOD__ . ": $cmd\n" );
  198. $retval = '';
  199. $err = wfShellExec( $cmd, $retval );
  200. $removed = $this->removeBadFile( $dstPath, $retval );
  201. if ( $retval != 0 || $removed ) {
  202. $this->logErrorForExternalProcess( $retval, $err, $cmd );
  203. return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
  204. } else {
  205. $params = [
  206. 'width' => $width,
  207. 'height' => $height,
  208. 'page' => $page
  209. ];
  210. return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
  211. }
  212. }
  213. /**
  214. * Cache an instance of DjVuImage in an Image object, return that instance
  215. *
  216. * @param File|FSFile $image
  217. * @param string $path
  218. * @return DjVuImage
  219. * @suppress PhanUndeclaredProperty Custom property
  220. */
  221. function getDjVuImage( $image, $path ) {
  222. if ( !$image ) {
  223. $deja = new DjVuImage( $path );
  224. } elseif ( !isset( $image->dejaImage ) ) {
  225. $deja = $image->dejaImage = new DjVuImage( $path );
  226. } else {
  227. $deja = $image->dejaImage;
  228. }
  229. return $deja;
  230. }
  231. /**
  232. * Get metadata, unserializing it if necessary.
  233. *
  234. * @param File $file The DjVu file in question
  235. * @return string XML metadata as a string.
  236. * @throws MWException
  237. */
  238. private function getUnserializedMetadata( File $file ) {
  239. $metadata = $file->getMetadata();
  240. if ( substr( $metadata, 0, 3 ) === '<?xml' ) {
  241. // Old style. Not serialized but instead just a raw string of XML.
  242. return $metadata;
  243. }
  244. Wikimedia\suppressWarnings();
  245. $unser = unserialize( $metadata );
  246. Wikimedia\restoreWarnings();
  247. if ( is_array( $unser ) ) {
  248. if ( isset( $unser['error'] ) ) {
  249. return false;
  250. } elseif ( isset( $unser['xml'] ) ) {
  251. return $unser['xml'];
  252. } else {
  253. // Should never ever reach here.
  254. throw new MWException( "Error unserializing DjVu metadata." );
  255. }
  256. }
  257. // unserialize failed. Guess it wasn't really serialized after all,
  258. return $metadata;
  259. }
  260. /**
  261. * Cache a document tree for the DjVu XML metadata
  262. * @param File $image
  263. * @param bool $gettext DOCUMENT (Default: false)
  264. * @return bool|SimpleXMLElement
  265. * @suppress PhanUndeclaredProperty Custom property
  266. */
  267. public function getMetaTree( $image, $gettext = false ) {
  268. if ( $gettext && isset( $image->djvuTextTree ) ) {
  269. return $image->djvuTextTree;
  270. }
  271. if ( !$gettext && isset( $image->dejaMetaTree ) ) {
  272. return $image->dejaMetaTree;
  273. }
  274. $metadata = $this->getUnserializedMetadata( $image );
  275. if ( !$this->isMetadataValid( $image, $metadata ) ) {
  276. wfDebug( "DjVu XML metadata is invalid or missing, should have been fixed in upgradeRow\n" );
  277. return false;
  278. }
  279. $trees = $this->extractTreesFromMetadata( $metadata );
  280. $image->djvuTextTree = $trees['TextTree'];
  281. $image->dejaMetaTree = $trees['MetaTree'];
  282. if ( $gettext ) {
  283. return $image->djvuTextTree;
  284. } else {
  285. return $image->dejaMetaTree;
  286. }
  287. }
  288. /**
  289. * Extracts metadata and text trees from metadata XML in string form
  290. * @param string $metadata XML metadata as a string
  291. * @return array
  292. */
  293. protected function extractTreesFromMetadata( $metadata ) {
  294. Wikimedia\suppressWarnings();
  295. try {
  296. // Set to false rather than null to avoid further attempts
  297. $metaTree = false;
  298. $textTree = false;
  299. $tree = new SimpleXMLElement( $metadata, LIBXML_PARSEHUGE );
  300. if ( $tree->getName() == 'mw-djvu' ) {
  301. /** @var SimpleXMLElement $b */
  302. foreach ( $tree->children() as $b ) {
  303. if ( $b->getName() == 'DjVuTxt' ) {
  304. // @todo File::djvuTextTree and File::dejaMetaTree are declared
  305. // dynamically. Add a public File::$data to facilitate this?
  306. $textTree = $b;
  307. } elseif ( $b->getName() == 'DjVuXML' ) {
  308. $metaTree = $b;
  309. }
  310. }
  311. } else {
  312. $metaTree = $tree;
  313. }
  314. } catch ( Exception $e ) {
  315. wfDebug( "Bogus multipage XML metadata\n" );
  316. }
  317. Wikimedia\restoreWarnings();
  318. return [ 'MetaTree' => $metaTree, 'TextTree' => $textTree ];
  319. }
  320. function getImageSize( $image, $path ) {
  321. return $this->getDjVuImage( $image, $path )->getImageSize();
  322. }
  323. public function getThumbType( $ext, $mime, $params = null ) {
  324. global $wgDjvuOutputExtension;
  325. static $mime;
  326. if ( !isset( $mime ) ) {
  327. $magic = MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer();
  328. $mime = $magic->guessTypesForExtension( $wgDjvuOutputExtension );
  329. }
  330. return [ $wgDjvuOutputExtension, $mime ];
  331. }
  332. public function getMetadata( $image, $path ) {
  333. wfDebug( "Getting DjVu metadata for $path\n" );
  334. $xml = $this->getDjVuImage( $image, $path )->retrieveMetaData();
  335. if ( $xml === false ) {
  336. // Special value so that we don't repetitively try and decode a broken file.
  337. return serialize( [ 'error' => 'Error extracting metadata' ] );
  338. } else {
  339. return serialize( [ 'xml' => $xml ] );
  340. }
  341. }
  342. function getMetadataType( $image ) {
  343. return 'djvuxml';
  344. }
  345. public function isMetadataValid( $image, $metadata ) {
  346. return !empty( $metadata ) && $metadata != serialize( [] );
  347. }
  348. public function pageCount( File $image ) {
  349. $info = $this->getDimensionInfo( $image );
  350. return $info ? $info['pageCount'] : false;
  351. }
  352. public function getPageDimensions( File $image, $page ) {
  353. $index = $page - 1; // MW starts pages at 1
  354. $info = $this->getDimensionInfo( $image );
  355. if ( $info && isset( $info['dimensionsByPage'][$index] ) ) {
  356. return $info['dimensionsByPage'][$index];
  357. }
  358. return false;
  359. }
  360. protected function getDimensionInfo( File $file ) {
  361. $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
  362. return $cache->getWithSetCallback(
  363. $cache->makeKey( 'file-djvu', 'dimensions', $file->getSha1() ),
  364. $cache::TTL_INDEFINITE,
  365. function () use ( $file ) {
  366. $tree = $this->getMetaTree( $file );
  367. return $this->getDimensionInfoFromMetaTree( $tree );
  368. },
  369. [ 'pcTTL' => $cache::TTL_INDEFINITE ]
  370. );
  371. }
  372. /**
  373. * Given an XML metadata tree, returns dimension information about the document
  374. * @param bool|SimpleXMLElement $metatree The file's XML metadata tree
  375. * @return bool|array
  376. */
  377. protected function getDimensionInfoFromMetaTree( $metatree ) {
  378. if ( !$metatree ) {
  379. return false;
  380. }
  381. $dimsByPage = [];
  382. $count = count( $metatree->xpath( '//OBJECT' ) );
  383. for ( $i = 0; $i < $count; $i++ ) {
  384. $o = $metatree->BODY[0]->OBJECT[$i];
  385. if ( $o ) {
  386. $dimsByPage[$i] = [
  387. 'width' => (int)$o['width'],
  388. 'height' => (int)$o['height'],
  389. ];
  390. } else {
  391. $dimsByPage[$i] = false;
  392. }
  393. }
  394. return [ 'pageCount' => $count, 'dimensionsByPage' => $dimsByPage ];
  395. }
  396. /**
  397. * @param File $image
  398. * @param int $page Page number to get information for
  399. * @return bool|string Page text or false when no text found.
  400. */
  401. function getPageText( File $image, $page ) {
  402. $tree = $this->getMetaTree( $image, true );
  403. if ( !$tree ) {
  404. return false;
  405. }
  406. $o = $tree->BODY[0]->PAGE[$page - 1];
  407. if ( $o ) {
  408. $txt = $o['value'];
  409. return $txt;
  410. } else {
  411. return false;
  412. }
  413. }
  414. }