TransformationalImageHandler.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. <?php
  2. /**
  3. * Base class for handlers which require transforming images in a
  4. * similar way as BitmapHandler does.
  5. *
  6. * This was split from BitmapHandler on the basis that some extensions
  7. * might want to work in a similar way to BitmapHandler, but for
  8. * different formats.
  9. *
  10. * This program is free software; you can redistribute it and/or modify
  11. * it under the terms of the GNU General Public License as published by
  12. * the Free Software Foundation; either version 2 of the License, or
  13. * (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License along
  21. * with this program; if not, write to the Free Software Foundation, Inc.,
  22. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  23. * http://www.gnu.org/copyleft/gpl.html
  24. *
  25. * @file
  26. * @ingroup Media
  27. */
  28. use MediaWiki\MediaWikiServices;
  29. use MediaWiki\Shell\Shell;
  30. /**
  31. * Handler for images that need to be transformed
  32. *
  33. * @since 1.24
  34. * @ingroup Media
  35. */
  36. abstract class TransformationalImageHandler extends ImageHandler {
  37. /**
  38. * @param File $image
  39. * @param array &$params Transform parameters. Entries with the keys 'width'
  40. * and 'height' are the respective screen width and height, while the keys
  41. * 'physicalWidth' and 'physicalHeight' indicate the thumbnail dimensions.
  42. * @return bool
  43. */
  44. public function normaliseParams( $image, &$params ) {
  45. if ( !parent::normaliseParams( $image, $params ) ) {
  46. return false;
  47. }
  48. # Obtain the source, pre-rotation dimensions
  49. $srcWidth = $image->getWidth( $params['page'] );
  50. $srcHeight = $image->getHeight( $params['page'] );
  51. # Don't make an image bigger than the source
  52. if ( $params['physicalWidth'] >= $srcWidth ) {
  53. $params['physicalWidth'] = $srcWidth;
  54. $params['physicalHeight'] = $srcHeight;
  55. # Skip scaling limit checks if no scaling is required
  56. # due to requested size being bigger than source.
  57. if ( !$image->mustRender() ) {
  58. return true;
  59. }
  60. }
  61. return true;
  62. }
  63. /**
  64. * Extracts the width/height if the image will be scaled before rotating
  65. *
  66. * This will match the physical size/aspect ratio of the original image
  67. * prior to application of the rotation -- so for a portrait image that's
  68. * stored as raw landscape with 90-degress rotation, the resulting size
  69. * will be wider than it is tall.
  70. *
  71. * @param array $params Parameters as returned by normaliseParams
  72. * @param int $rotation The rotation angle that will be applied
  73. * @return array ($width, $height) array
  74. */
  75. public function extractPreRotationDimensions( $params, $rotation ) {
  76. if ( $rotation == 90 || $rotation == 270 ) {
  77. # We'll resize before rotation, so swap the dimensions again
  78. $width = $params['physicalHeight'];
  79. $height = $params['physicalWidth'];
  80. } else {
  81. $width = $params['physicalWidth'];
  82. $height = $params['physicalHeight'];
  83. }
  84. return [ $width, $height ];
  85. }
  86. /**
  87. * Create a thumbnail.
  88. *
  89. * This sets up various parameters, and then calls a helper method
  90. * based on $this->getScalerType in order to scale the image.
  91. *
  92. * @param File $image
  93. * @param string $dstPath
  94. * @param string $dstUrl
  95. * @param array $params
  96. * @param int $flags
  97. * @return MediaTransformError|ThumbnailImage|TransformParameterError
  98. */
  99. function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
  100. if ( !$this->normaliseParams( $image, $params ) ) {
  101. return new TransformParameterError( $params );
  102. }
  103. # Create a parameter array to pass to the scaler
  104. $scalerParams = [
  105. # The size to which the image will be resized
  106. 'physicalWidth' => $params['physicalWidth'],
  107. 'physicalHeight' => $params['physicalHeight'],
  108. 'physicalDimensions' => "{$params['physicalWidth']}x{$params['physicalHeight']}",
  109. # The size of the image on the page
  110. 'clientWidth' => $params['width'],
  111. 'clientHeight' => $params['height'],
  112. # Comment as will be added to the Exif of the thumbnail
  113. 'comment' => isset( $params['descriptionUrl'] )
  114. ? "File source: {$params['descriptionUrl']}"
  115. : '',
  116. # Properties of the original image
  117. 'srcWidth' => $image->getWidth(),
  118. 'srcHeight' => $image->getHeight(),
  119. 'mimeType' => $image->getMimeType(),
  120. 'dstPath' => $dstPath,
  121. 'dstUrl' => $dstUrl,
  122. 'interlace' => $params['interlace'] ?? false,
  123. ];
  124. if ( isset( $params['quality'] ) && $params['quality'] === 'low' ) {
  125. $scalerParams['quality'] = 30;
  126. }
  127. // For subclasses that might be paged.
  128. if ( $image->isMultipage() && isset( $params['page'] ) ) {
  129. $scalerParams['page'] = intval( $params['page'] );
  130. }
  131. # Determine scaler type
  132. $scaler = $this->getScalerType( $dstPath );
  133. if ( is_array( $scaler ) ) {
  134. $scalerName = get_class( $scaler[0] );
  135. } else {
  136. $scalerName = $scaler;
  137. }
  138. wfDebug( __METHOD__ . ": creating {$scalerParams['physicalDimensions']} " .
  139. "thumbnail at $dstPath using scaler $scalerName\n" );
  140. if ( !$image->mustRender() &&
  141. $scalerParams['physicalWidth'] == $scalerParams['srcWidth']
  142. && $scalerParams['physicalHeight'] == $scalerParams['srcHeight']
  143. && !isset( $scalerParams['quality'] )
  144. ) {
  145. # normaliseParams (or the user) wants us to return the unscaled image
  146. wfDebug( __METHOD__ . ": returning unscaled image\n" );
  147. return $this->getClientScalingThumbnailImage( $image, $scalerParams );
  148. }
  149. if ( $scaler == 'client' ) {
  150. # Client-side image scaling, use the source URL
  151. # Using the destination URL in a TRANSFORM_LATER request would be incorrect
  152. return $this->getClientScalingThumbnailImage( $image, $scalerParams );
  153. }
  154. if ( $image->isTransformedLocally() && !$this->isImageAreaOkForThumbnaling( $image, $params ) ) {
  155. global $wgMaxImageArea;
  156. return new TransformTooBigImageAreaError( $params, $wgMaxImageArea );
  157. }
  158. if ( $flags & self::TRANSFORM_LATER ) {
  159. wfDebug( __METHOD__ . ": Transforming later per flags.\n" );
  160. $newParams = [
  161. 'width' => $scalerParams['clientWidth'],
  162. 'height' => $scalerParams['clientHeight']
  163. ];
  164. if ( isset( $params['quality'] ) ) {
  165. $newParams['quality'] = $params['quality'];
  166. }
  167. if ( isset( $params['page'] ) && $params['page'] ) {
  168. $newParams['page'] = $params['page'];
  169. }
  170. return new ThumbnailImage( $image, $dstUrl, false, $newParams );
  171. }
  172. # Try to make a target path for the thumbnail
  173. if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
  174. wfDebug( __METHOD__ . ": Unable to create thumbnail destination " .
  175. "directory, falling back to client scaling\n" );
  176. return $this->getClientScalingThumbnailImage( $image, $scalerParams );
  177. }
  178. # Transform functions and binaries need a FS source file
  179. $thumbnailSource = $this->getThumbnailSource( $image, $params );
  180. // If the source isn't the original, disable EXIF rotation because it's already been applied
  181. if ( $scalerParams['srcWidth'] != $thumbnailSource['width']
  182. || $scalerParams['srcHeight'] != $thumbnailSource['height'] ) {
  183. $scalerParams['disableRotation'] = true;
  184. }
  185. $scalerParams['srcPath'] = $thumbnailSource['path'];
  186. $scalerParams['srcWidth'] = $thumbnailSource['width'];
  187. $scalerParams['srcHeight'] = $thumbnailSource['height'];
  188. if ( $scalerParams['srcPath'] === false ) { // Failed to get local copy
  189. wfDebugLog( 'thumbnail',
  190. sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
  191. wfHostname(), $image->getName() ) );
  192. return new MediaTransformError( 'thumbnail_error',
  193. $scalerParams['clientWidth'], $scalerParams['clientHeight'],
  194. wfMessage( 'filemissing' )
  195. );
  196. }
  197. # Try a hook. Called "Bitmap" for historical reasons.
  198. /** @var MediaTransformOutput $mto */
  199. $mto = null;
  200. Hooks::run( 'BitmapHandlerTransform', [ $this, $image, &$scalerParams, &$mto ] );
  201. if ( !is_null( $mto ) ) {
  202. wfDebug( __METHOD__ . ": Hook to BitmapHandlerTransform created an mto\n" );
  203. $scaler = 'hookaborted';
  204. }
  205. // $scaler will return a MediaTransformError on failure, or false on success.
  206. // If the scaler is successful, it will have created a thumbnail at the destination
  207. // path.
  208. if ( is_array( $scaler ) && is_callable( $scaler ) ) {
  209. // Allow subclasses to specify their own rendering methods.
  210. $err = call_user_func( $scaler, $image, $scalerParams );
  211. } else {
  212. switch ( $scaler ) {
  213. case 'hookaborted':
  214. # Handled by the hook above
  215. $err = $mto->isError() ? $mto : false;
  216. break;
  217. case 'im':
  218. $err = $this->transformImageMagick( $image, $scalerParams );
  219. break;
  220. case 'custom':
  221. $err = $this->transformCustom( $image, $scalerParams );
  222. break;
  223. case 'imext':
  224. $err = $this->transformImageMagickExt( $image, $scalerParams );
  225. break;
  226. case 'gd':
  227. default:
  228. $err = $this->transformGd( $image, $scalerParams );
  229. break;
  230. }
  231. }
  232. # Remove the file if a zero-byte thumbnail was created, or if there was an error
  233. $removed = $this->removeBadFile( $dstPath, (bool)$err );
  234. if ( $err ) {
  235. # transform returned MediaTransforError
  236. return $err;
  237. } elseif ( $removed ) {
  238. # Thumbnail was zero-byte and had to be removed
  239. return new MediaTransformError( 'thumbnail_error',
  240. $scalerParams['clientWidth'], $scalerParams['clientHeight'],
  241. wfMessage( 'unknown-error' )
  242. );
  243. } elseif ( $mto ) {
  244. return $mto;
  245. } else {
  246. $newParams = [
  247. 'width' => $scalerParams['clientWidth'],
  248. 'height' => $scalerParams['clientHeight']
  249. ];
  250. if ( isset( $params['quality'] ) ) {
  251. $newParams['quality'] = $params['quality'];
  252. }
  253. if ( isset( $params['page'] ) && $params['page'] ) {
  254. $newParams['page'] = $params['page'];
  255. }
  256. return new ThumbnailImage( $image, $dstUrl, $dstPath, $newParams );
  257. }
  258. }
  259. /**
  260. * Get the source file for the transform
  261. *
  262. * @param File $file
  263. * @param array $params
  264. * @return array Array with keys width, height and path.
  265. */
  266. protected function getThumbnailSource( $file, $params ) {
  267. return $file->getThumbnailSource( $params );
  268. }
  269. /**
  270. * Returns what sort of scaler type should be used.
  271. *
  272. * Values can be one of client, im, custom, gd, imext, or an array
  273. * of object, method-name to call that specific method.
  274. *
  275. * If specifying a custom scaler command with [ Obj, method ],
  276. * the method in question should take 2 parameters, a File object,
  277. * and a $scalerParams array with various options (See doTransform
  278. * for what is in $scalerParams). On error it should return a
  279. * MediaTransformError object. On success it should return false,
  280. * and simply make sure the thumbnail file is located at
  281. * $scalerParams['dstPath'].
  282. *
  283. * If there is a problem with the output path, it returns "client"
  284. * to do client side scaling.
  285. *
  286. * @param string $dstPath
  287. * @param bool $checkDstPath Check that $dstPath is valid
  288. * @return string|Callable One of client, im, custom, gd, imext, or a Callable array.
  289. */
  290. abstract protected function getScalerType( $dstPath, $checkDstPath = true );
  291. /**
  292. * Get a ThumbnailImage that respresents an image that will be scaled
  293. * client side
  294. *
  295. * @param File $image File associated with this thumbnail
  296. * @param array $scalerParams Array with scaler params
  297. * @return ThumbnailImage
  298. *
  299. * @todo FIXME: No rotation support
  300. */
  301. protected function getClientScalingThumbnailImage( $image, $scalerParams ) {
  302. $params = [
  303. 'width' => $scalerParams['clientWidth'],
  304. 'height' => $scalerParams['clientHeight']
  305. ];
  306. return new ThumbnailImage( $image, $image->getUrl(), null, $params );
  307. }
  308. /**
  309. * Transform an image using ImageMagick
  310. *
  311. * This is a stub method. The real method is in BitmapHander.
  312. *
  313. * @param File $image File associated with this thumbnail
  314. * @param array $params Array with scaler params
  315. *
  316. * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
  317. */
  318. protected function transformImageMagick( $image, $params ) {
  319. return $this->getMediaTransformError( $params, "Unimplemented" );
  320. }
  321. /**
  322. * Transform an image using the Imagick PHP extension
  323. *
  324. * This is a stub method. The real method is in BitmapHander.
  325. *
  326. * @param File $image File associated with this thumbnail
  327. * @param array $params Array with scaler params
  328. *
  329. * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
  330. */
  331. protected function transformImageMagickExt( $image, $params ) {
  332. return $this->getMediaTransformError( $params, "Unimplemented" );
  333. }
  334. /**
  335. * Transform an image using a custom command
  336. *
  337. * This is a stub method. The real method is in BitmapHander.
  338. *
  339. * @param File $image File associated with this thumbnail
  340. * @param array $params Array with scaler params
  341. *
  342. * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
  343. */
  344. protected function transformCustom( $image, $params ) {
  345. return $this->getMediaTransformError( $params, "Unimplemented" );
  346. }
  347. /**
  348. * Get a MediaTransformError with error 'thumbnail_error'
  349. *
  350. * @param array $params Parameter array as passed to the transform* functions
  351. * @param string $errMsg Error message
  352. * @return MediaTransformError
  353. */
  354. public function getMediaTransformError( $params, $errMsg ) {
  355. return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
  356. $params['clientHeight'], $errMsg );
  357. }
  358. /**
  359. * Transform an image using the built in GD library
  360. *
  361. * This is a stub method. The real method is in BitmapHander.
  362. *
  363. * @param File $image File associated with this thumbnail
  364. * @param array $params Array with scaler params
  365. *
  366. * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
  367. */
  368. protected function transformGd( $image, $params ) {
  369. return $this->getMediaTransformError( $params, "Unimplemented" );
  370. }
  371. /**
  372. * Escape a string for ImageMagick's property input (e.g. -set -comment)
  373. * See InterpretImageProperties() in magick/property.c
  374. * @param string $s
  375. * @return string
  376. */
  377. function escapeMagickProperty( $s ) {
  378. // Double the backslashes
  379. $s = str_replace( '\\', '\\\\', $s );
  380. // Double the percents
  381. $s = str_replace( '%', '%%', $s );
  382. // Escape initial - or @
  383. if ( strlen( $s ) > 0 && ( $s[0] === '-' || $s[0] === '@' ) ) {
  384. $s = '\\' . $s;
  385. }
  386. return $s;
  387. }
  388. /**
  389. * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
  390. * and GetPathComponent() in magick/utility.c.
  391. *
  392. * This won't work with an initial ~ or @, so input files should be prefixed
  393. * with the directory name.
  394. *
  395. * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
  396. * it's broken in a way that doesn't involve trying to convert every file
  397. * in a directory, so we're better off escaping and waiting for the bugfix
  398. * to filter down to users.
  399. *
  400. * @param string $path The file path
  401. * @param bool|string $scene The scene specification, or false if there is none
  402. * @throws MWException
  403. * @return string
  404. */
  405. function escapeMagickInput( $path, $scene = false ) {
  406. # Die on initial metacharacters (caller should prepend path)
  407. $firstChar = substr( $path, 0, 1 );
  408. if ( $firstChar === '~' || $firstChar === '@' ) {
  409. throw new MWException( __METHOD__ . ': cannot escape this path name' );
  410. }
  411. # Escape glob chars
  412. $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
  413. return $this->escapeMagickPath( $path, $scene );
  414. }
  415. /**
  416. * Escape a string for ImageMagick's output filename. See
  417. * InterpretImageFilename() in magick/image.c.
  418. * @param string $path The file path
  419. * @param bool|string $scene The scene specification, or false if there is none
  420. * @return string
  421. */
  422. function escapeMagickOutput( $path, $scene = false ) {
  423. $path = str_replace( '%', '%%', $path );
  424. return $this->escapeMagickPath( $path, $scene );
  425. }
  426. /**
  427. * Armour a string against ImageMagick's GetPathComponent(). This is a
  428. * helper function for escapeMagickInput() and escapeMagickOutput().
  429. *
  430. * @param string $path The file path
  431. * @param bool|string $scene The scene specification, or false if there is none
  432. * @throws MWException
  433. * @return string
  434. */
  435. protected function escapeMagickPath( $path, $scene = false ) {
  436. # Die on format specifiers (other than drive letters). The regex is
  437. # meant to match all the formats you get from "convert -list format"
  438. if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
  439. if ( wfIsWindows() && is_dir( $m[0] ) ) {
  440. // OK, it's a drive letter
  441. // ImageMagick has a similar exception, see IsMagickConflict()
  442. } else {
  443. throw new MWException( __METHOD__ . ': unexpected colon character in path name' );
  444. }
  445. }
  446. # If there are square brackets, add a do-nothing scene specification
  447. # to force a literal interpretation
  448. if ( $scene === false ) {
  449. if ( strpos( $path, '[' ) !== false ) {
  450. $path .= '[0--1]';
  451. }
  452. } else {
  453. $path .= "[$scene]";
  454. }
  455. return $path;
  456. }
  457. /**
  458. * Retrieve the version of the installed ImageMagick
  459. * You can use PHPs version_compare() to use this value
  460. * Value is cached for one hour.
  461. * @return string|bool Representing the IM version; false on error
  462. */
  463. protected function getMagickVersion() {
  464. $cache = MediaWikiServices::getInstance()->getLocalServerObjectCache();
  465. $method = __METHOD__;
  466. return $cache->getWithSetCallback(
  467. $cache->makeGlobalKey( 'imagemagick-version' ),
  468. $cache::TTL_HOUR,
  469. function () use ( $method ) {
  470. global $wgImageMagickConvertCommand;
  471. $cmd = Shell::escape( $wgImageMagickConvertCommand ) . ' -version';
  472. wfDebug( $method . ": Running convert -version\n" );
  473. $retval = '';
  474. $return = wfShellExecWithStderr( $cmd, $retval );
  475. $x = preg_match(
  476. '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches
  477. );
  478. if ( $x != 1 ) {
  479. wfDebug( $method . ": ImageMagick version check failed\n" );
  480. return false;
  481. }
  482. return $matches[1];
  483. }
  484. );
  485. }
  486. /**
  487. * Returns whether the current scaler supports rotation.
  488. *
  489. * @since 1.24 No longer static
  490. * @return bool
  491. */
  492. public function canRotate() {
  493. return false;
  494. }
  495. /**
  496. * Should we automatically rotate an image based on exif
  497. *
  498. * @since 1.24 No longer static
  499. * @see $wgEnableAutoRotation
  500. * @return bool Whether auto rotation is enabled
  501. */
  502. public function autoRotateEnabled() {
  503. return false;
  504. }
  505. /**
  506. * Rotate a thumbnail.
  507. *
  508. * This is a stub. See BitmapHandler::rotate.
  509. *
  510. * @param File $file
  511. * @param array $params Rotate parameters.
  512. * 'rotation' clockwise rotation in degrees, allowed are multiples of 90
  513. * @since 1.24 Is non-static. From 1.21 it was static
  514. * @return bool|MediaTransformError
  515. */
  516. public function rotate( $file, $params ) {
  517. return new MediaTransformError( 'thumbnail_error', 0, 0,
  518. static::class . ' rotation not implemented' );
  519. }
  520. /**
  521. * Returns whether the file needs to be rendered. Returns true if the
  522. * file requires rotation and we are able to rotate it.
  523. *
  524. * @param File $file
  525. * @return bool
  526. */
  527. public function mustRender( $file ) {
  528. return $this->canRotate() && $this->getRotation( $file ) != 0;
  529. }
  530. /**
  531. * Check if the file is smaller than the maximum image area for thumbnailing.
  532. *
  533. * Runs the 'BitmapHandlerCheckImageArea' hook.
  534. *
  535. * @param File $file
  536. * @param array &$params
  537. * @return bool
  538. * @since 1.25
  539. */
  540. public function isImageAreaOkForThumbnaling( $file, &$params ) {
  541. global $wgMaxImageArea;
  542. # For historical reasons, hook starts with BitmapHandler
  543. $checkImageAreaHookResult = null;
  544. Hooks::run(
  545. 'BitmapHandlerCheckImageArea',
  546. [ $file, &$params, &$checkImageAreaHookResult ]
  547. );
  548. if ( !is_null( $checkImageAreaHookResult ) ) {
  549. // was set by hook, so return that value
  550. return (bool)$checkImageAreaHookResult;
  551. }
  552. $srcWidth = $file->getWidth( $params['page'] );
  553. $srcHeight = $file->getHeight( $params['page'] );
  554. if ( $srcWidth * $srcHeight > $wgMaxImageArea
  555. && !( $file->getMimeType() == 'image/jpeg'
  556. && $this->getScalerType( false, false ) == 'im' )
  557. ) {
  558. # Only ImageMagick can efficiently downsize jpg images without loading
  559. # the entire file in memory
  560. return false;
  561. }
  562. return true;
  563. }
  564. }