thumb.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. <?php
  2. /**
  3. * PHP script to stream out an image thumbnail.
  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\Logger\LoggerFactory;
  24. use MediaWiki\MediaWikiServices;
  25. define( 'MW_NO_OUTPUT_COMPRESSION', 1 );
  26. require __DIR__ . '/includes/WebStart.php';
  27. // Don't use fancy MIME detection, just check the file extension for jpg/gif/png
  28. $wgTrivialMimeDetection = true;
  29. if ( defined( 'THUMB_HANDLER' ) ) {
  30. // Called from thumb_handler.php via 404; extract params from the URI...
  31. wfThumbHandle404();
  32. } else {
  33. // Called directly, use $_GET params
  34. wfStreamThumb( $_GET );
  35. }
  36. $mediawiki = new MediaWiki();
  37. $mediawiki->doPostOutputShutdown( 'fast' );
  38. // --------------------------------------------------------------------------
  39. /**
  40. * Handle a thumbnail request via thumbnail file URL
  41. *
  42. * @return void
  43. */
  44. function wfThumbHandle404() {
  45. global $wgArticlePath;
  46. # Set action base paths so that WebRequest::getPathInfo()
  47. # recognizes the "X" as the 'title' in ../thumb_handler.php/X urls.
  48. # Note: If Custom per-extension repo paths are set, this may break.
  49. $repo = RepoGroup::singleton()->getLocalRepo();
  50. $oldArticlePath = $wgArticlePath;
  51. $wgArticlePath = $repo->getZoneUrl( 'thumb' ) . '/$1';
  52. $matches = WebRequest::getPathInfo();
  53. $wgArticlePath = $oldArticlePath;
  54. if ( !isset( $matches['title'] ) ) {
  55. wfThumbError( 404, 'Could not determine the name of the requested thumbnail.' );
  56. return;
  57. }
  58. $params = wfExtractThumbRequestInfo( $matches['title'] ); // basic wiki URL param extracting
  59. if ( $params == null ) {
  60. wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
  61. return;
  62. }
  63. wfStreamThumb( $params ); // stream the thumbnail
  64. }
  65. /**
  66. * Stream a thumbnail specified by parameters
  67. *
  68. * @param array $params List of thumbnailing parameters. In addition to parameters
  69. * passed to the MediaHandler, this may also includes the keys:
  70. * f (for filename), archived (if archived file), temp (if temp file),
  71. * w (alias for width), p (alias for page), r (ignored; historical),
  72. * rel404 (path for render on 404 to verify hash path correct),
  73. * thumbName (thumbnail name to potentially extract more parameters from
  74. * e.g. 'lossy-page1-120px-Foo.tiff' would add page, lossy and width
  75. * to the parameters)
  76. * @return void
  77. */
  78. function wfStreamThumb( array $params ) {
  79. global $wgVaryOnXFP;
  80. $headers = []; // HTTP headers to send
  81. $fileName = isset( $params['f'] ) ? $params['f'] : '';
  82. // Backwards compatibility parameters
  83. if ( isset( $params['w'] ) ) {
  84. $params['width'] = $params['w'];
  85. unset( $params['w'] );
  86. }
  87. if ( isset( $params['width'] ) && substr( $params['width'], -2 ) == 'px' ) {
  88. // strip the px (pixel) suffix, if found
  89. $params['width'] = substr( $params['width'], 0, -2 );
  90. }
  91. if ( isset( $params['p'] ) ) {
  92. $params['page'] = $params['p'];
  93. }
  94. // Is this a thumb of an archived file?
  95. $isOld = ( isset( $params['archived'] ) && $params['archived'] );
  96. unset( $params['archived'] ); // handlers don't care
  97. // Is this a thumb of a temp file?
  98. $isTemp = ( isset( $params['temp'] ) && $params['temp'] );
  99. unset( $params['temp'] ); // handlers don't care
  100. // Some basic input validation
  101. $fileName = strtr( $fileName, '\\/', '__' );
  102. // Actually fetch the image. Method depends on whether it is archived or not.
  103. if ( $isTemp ) {
  104. $repo = RepoGroup::singleton()->getLocalRepo()->getTempRepo();
  105. $img = new UnregisteredLocalFile( null, $repo,
  106. # Temp files are hashed based on the name without the timestamp.
  107. # The thumbnails will be hashed based on the entire name however.
  108. # @todo fix this convention to actually be reasonable.
  109. $repo->getZonePath( 'public' ) . '/' . $repo->getTempHashPath( $fileName ) . $fileName
  110. );
  111. } elseif ( $isOld ) {
  112. // Format is <timestamp>!<name>
  113. $bits = explode( '!', $fileName, 2 );
  114. if ( count( $bits ) != 2 ) {
  115. wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
  116. return;
  117. }
  118. $title = Title::makeTitleSafe( NS_FILE, $bits[1] );
  119. if ( !$title ) {
  120. wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
  121. return;
  122. }
  123. $img = RepoGroup::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
  124. } else {
  125. $img = wfLocalFile( $fileName );
  126. }
  127. // Check the source file title
  128. if ( !$img ) {
  129. wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
  130. return;
  131. }
  132. // Check permissions if there are read restrictions
  133. $varyHeader = [];
  134. if ( !in_array( 'read', User::getGroupPermissions( [ '*' ] ), true ) ) {
  135. if ( !$img->getTitle() || !$img->getTitle()->userCan( 'read' ) ) {
  136. wfThumbError( 403, 'Access denied. You do not have permission to access ' .
  137. 'the source file.' );
  138. return;
  139. }
  140. $headers[] = 'Cache-Control: private';
  141. $varyHeader[] = 'Cookie';
  142. }
  143. // Check if the file is hidden
  144. if ( $img->isDeleted( File::DELETED_FILE ) ) {
  145. wfThumbErrorText( 404, "The source file '$fileName' does not exist." );
  146. return;
  147. }
  148. // Do rendering parameters extraction from thumbnail name.
  149. if ( isset( $params['thumbName'] ) ) {
  150. $params = wfExtractThumbParams( $img, $params );
  151. }
  152. if ( $params == null ) {
  153. wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
  154. return;
  155. }
  156. // Check the source file storage path
  157. if ( !$img->exists() ) {
  158. $redirectedLocation = false;
  159. if ( !$isTemp ) {
  160. // Check for file redirect
  161. // Since redirects are associated with pages, not versions of files,
  162. // we look for the most current version to see if its a redirect.
  163. $possRedirFile = RepoGroup::singleton()->getLocalRepo()->findFile( $img->getName() );
  164. if ( $possRedirFile && !is_null( $possRedirFile->getRedirected() ) ) {
  165. $redirTarget = $possRedirFile->getName();
  166. $targetFile = wfLocalFile( Title::makeTitleSafe( NS_FILE, $redirTarget ) );
  167. if ( $targetFile->exists() ) {
  168. $newThumbName = $targetFile->thumbName( $params );
  169. if ( $isOld ) {
  170. /** @var array $bits */
  171. $newThumbUrl = $targetFile->getArchiveThumbUrl(
  172. $bits[0] . '!' . $targetFile->getName(), $newThumbName );
  173. } else {
  174. $newThumbUrl = $targetFile->getThumbUrl( $newThumbName );
  175. }
  176. $redirectedLocation = wfExpandUrl( $newThumbUrl, PROTO_CURRENT );
  177. }
  178. }
  179. }
  180. if ( $redirectedLocation ) {
  181. // File has been moved. Give redirect.
  182. $response = RequestContext::getMain()->getRequest()->response();
  183. $response->statusHeader( 302 );
  184. $response->header( 'Location: ' . $redirectedLocation );
  185. $response->header( 'Expires: ' .
  186. gmdate( 'D, d M Y H:i:s', time() + 12 * 3600 ) . ' GMT' );
  187. if ( $wgVaryOnXFP ) {
  188. $varyHeader[] = 'X-Forwarded-Proto';
  189. }
  190. if ( count( $varyHeader ) ) {
  191. $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
  192. }
  193. $response->header( 'Content-Length: 0' );
  194. return;
  195. }
  196. // If its not a redirect that has a target as a local file, give 404.
  197. wfThumbErrorText( 404, "The source file '$fileName' does not exist." );
  198. return;
  199. } elseif ( $img->getPath() === false ) {
  200. wfThumbErrorText( 400, "The source file '$fileName' is not locally accessible." );
  201. return;
  202. }
  203. // Check IMS against the source file
  204. // This means that clients can keep a cached copy even after it has been deleted on the server
  205. if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
  206. // Fix IE brokenness
  207. $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
  208. // Calculate time
  209. MediaWiki\suppressWarnings();
  210. $imsUnix = strtotime( $imsString );
  211. MediaWiki\restoreWarnings();
  212. if ( wfTimestamp( TS_UNIX, $img->getTimestamp() ) <= $imsUnix ) {
  213. HttpStatus::header( 304 );
  214. return;
  215. }
  216. }
  217. $rel404 = isset( $params['rel404'] ) ? $params['rel404'] : null;
  218. unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
  219. unset( $params['f'] ); // We're done with 'f' parameter.
  220. unset( $params['rel404'] ); // moved to $rel404
  221. // Get the normalized thumbnail name from the parameters...
  222. try {
  223. $thumbName = $img->thumbName( $params );
  224. if ( !strlen( $thumbName ) ) { // invalid params?
  225. throw new MediaTransformInvalidParametersException(
  226. 'Empty return from File::thumbName'
  227. );
  228. }
  229. $thumbName2 = $img->thumbName( $params, File::THUMB_FULL_NAME ); // b/c; "long" style
  230. } catch ( MediaTransformInvalidParametersException $e ) {
  231. wfThumbError(
  232. 400,
  233. 'The specified thumbnail parameters are not valid: ' . $e->getMessage()
  234. );
  235. return;
  236. } catch ( MWException $e ) {
  237. wfThumbError( 500, $e->getHTML(), 'Exception caught while extracting thumb name',
  238. [ 'exception' => $e ] );
  239. return;
  240. }
  241. // For 404 handled thumbnails, we only use the base name of the URI
  242. // for the thumb params and the parent directory for the source file name.
  243. // Check that the zone relative path matches up so squid caches won't pick
  244. // up thumbs that would not be purged on source file deletion (T36231).
  245. if ( $rel404 !== null ) { // thumbnail was handled via 404
  246. if ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName ) ) {
  247. // Request for the canonical thumbnail name
  248. } elseif ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName2 ) ) {
  249. // Request for the "long" thumbnail name; redirect to canonical name
  250. $response = RequestContext::getMain()->getRequest()->response();
  251. $response->statusHeader( 301 );
  252. $response->header( 'Location: ' .
  253. wfExpandUrl( $img->getThumbUrl( $thumbName ), PROTO_CURRENT ) );
  254. $response->header( 'Expires: ' .
  255. gmdate( 'D, d M Y H:i:s', time() + 7 * 86400 ) . ' GMT' );
  256. if ( $wgVaryOnXFP ) {
  257. $varyHeader[] = 'X-Forwarded-Proto';
  258. }
  259. if ( count( $varyHeader ) ) {
  260. $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
  261. }
  262. return;
  263. } else {
  264. wfThumbErrorText( 404, "The given path of the specified thumbnail is incorrect;
  265. expected '" . $img->getThumbRel( $thumbName ) . "' but got '" .
  266. rawurldecode( $rel404 ) . "'." );
  267. return;
  268. }
  269. }
  270. $dispositionType = isset( $params['download'] ) ? 'attachment' : 'inline';
  271. // Suggest a good name for users downloading this thumbnail
  272. $headers[] =
  273. "Content-Disposition: {$img->getThumbDisposition( $thumbName, $dispositionType )}";
  274. if ( count( $varyHeader ) ) {
  275. $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
  276. }
  277. // Stream the file if it exists already...
  278. $thumbPath = $img->getThumbPath( $thumbName );
  279. if ( $img->getRepo()->fileExists( $thumbPath ) ) {
  280. $starttime = microtime( true );
  281. $status = $img->getRepo()->streamFileWithStatus( $thumbPath, $headers );
  282. $streamtime = microtime( true ) - $starttime;
  283. if ( $status->isOK() ) {
  284. MediaWikiServices::getInstance()->getStatsdDataFactory()->timing(
  285. 'media.thumbnail.stream', $streamtime
  286. );
  287. } else {
  288. wfThumbError( 500, 'Could not stream the file', null, [ 'file' => $thumbName,
  289. 'path' => $thumbPath, 'error' => $status->getWikiText( false, false, 'en' ) ] );
  290. }
  291. return;
  292. }
  293. $user = RequestContext::getMain()->getUser();
  294. if ( !wfThumbIsStandard( $img, $params ) && $user->pingLimiter( 'renderfile-nonstandard' ) ) {
  295. wfThumbError( 429, wfMessage( 'actionthrottledtext' )->parse() );
  296. return;
  297. } elseif ( $user->pingLimiter( 'renderfile' ) ) {
  298. wfThumbError( 429, wfMessage( 'actionthrottledtext' )->parse() );
  299. return;
  300. }
  301. list( $thumb, $errorMsg ) = wfGenerateThumbnail( $img, $params, $thumbName, $thumbPath );
  302. /** @var MediaTransformOutput|MediaTransformError|bool $thumb */
  303. // Check for thumbnail generation errors...
  304. $msg = wfMessage( 'thumbnail_error' );
  305. $errorCode = 500;
  306. if ( !$thumb ) {
  307. $errorMsg = $errorMsg ?: $msg->rawParams( 'File::transform() returned false' )->escaped();
  308. if ( $errorMsg instanceof MessageSpecifier &&
  309. $errorMsg->getKey() === 'thumbnail_image-failure-limit'
  310. ) {
  311. $errorCode = 429;
  312. }
  313. } elseif ( $thumb->isError() ) {
  314. $errorMsg = $thumb->getHtmlMsg();
  315. $errorCode = $thumb->getHttpStatusCode();
  316. } elseif ( !$thumb->hasFile() ) {
  317. $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped();
  318. } elseif ( $thumb->fileIsSource() ) {
  319. $errorMsg = $msg
  320. ->rawParams( 'Image was not scaled, is the requested width bigger than the source?' )
  321. ->escaped();
  322. $errorCode = 400;
  323. }
  324. if ( $errorMsg !== false ) {
  325. wfThumbError( $errorCode, $errorMsg, null, [ 'file' => $thumbName, 'path' => $thumbPath ] );
  326. } else {
  327. // Stream the file if there were no errors
  328. $status = $thumb->streamFileWithStatus( $headers );
  329. if ( !$status->isOK() ) {
  330. wfThumbError( 500, 'Could not stream the file', null, [
  331. 'file' => $thumbName, 'path' => $thumbPath,
  332. 'error' => $status->getWikiText( false, false, 'en' ) ] );
  333. }
  334. }
  335. }
  336. /**
  337. * Actually try to generate a new thumbnail
  338. *
  339. * @param File $file
  340. * @param array $params
  341. * @param string $thumbName
  342. * @param string $thumbPath
  343. * @return array (MediaTransformOutput|bool, string|bool error message HTML)
  344. */
  345. function wfGenerateThumbnail( File $file, array $params, $thumbName, $thumbPath ) {
  346. global $wgAttemptFailureEpoch;
  347. $cache = ObjectCache::getLocalClusterInstance();
  348. $key = $cache->makeKey(
  349. 'attempt-failures',
  350. $wgAttemptFailureEpoch,
  351. $file->getRepo()->getName(),
  352. $file->getSha1(),
  353. md5( $thumbName )
  354. );
  355. // Check if this file keeps failing to render
  356. if ( $cache->get( $key ) >= 4 ) {
  357. return [ false, wfMessage( 'thumbnail_image-failure-limit', 4 ) ];
  358. }
  359. $done = false;
  360. // Record failures on PHP fatals in addition to caching exceptions
  361. register_shutdown_function( function () use ( $cache, &$done, $key ) {
  362. if ( !$done ) { // transform() gave a fatal
  363. // Randomize TTL to reduce stampedes
  364. $cache->incrWithInit( $key, $cache::TTL_HOUR + mt_rand( 0, 300 ) );
  365. }
  366. } );
  367. $thumb = false;
  368. $errorHtml = false;
  369. // guard thumbnail rendering with PoolCounter to avoid stampedes
  370. // expensive files use a separate PoolCounter config so it is possible
  371. // to set up a global limit on them
  372. if ( $file->isExpensiveToThumbnail() ) {
  373. $poolCounterType = 'FileRenderExpensive';
  374. } else {
  375. $poolCounterType = 'FileRender';
  376. }
  377. // Thumbnail isn't already there, so create the new thumbnail...
  378. try {
  379. $work = new PoolCounterWorkViaCallback( $poolCounterType, sha1( $file->getName() ),
  380. [
  381. 'doWork' => function () use ( $file, $params ) {
  382. return $file->transform( $params, File::RENDER_NOW );
  383. },
  384. 'doCachedWork' => function () use ( $file, $params, $thumbPath ) {
  385. // If the worker that finished made this thumbnail then use it.
  386. // Otherwise, it probably made a different thumbnail for this file.
  387. return $file->getRepo()->fileExists( $thumbPath )
  388. ? $file->transform( $params, File::RENDER_NOW )
  389. : false; // retry once more in exclusive mode
  390. },
  391. 'error' => function ( Status $status ) {
  392. return wfMessage( 'generic-pool-error' )->parse() . '<hr>' . $status->getHTML();
  393. }
  394. ]
  395. );
  396. $result = $work->execute();
  397. if ( $result instanceof MediaTransformOutput ) {
  398. $thumb = $result;
  399. } elseif ( is_string( $result ) ) { // error
  400. $errorHtml = $result;
  401. }
  402. } catch ( Exception $e ) {
  403. // Tried to select a page on a non-paged file?
  404. }
  405. /** @noinspection PhpUnusedLocalVariableInspection */
  406. $done = true; // no PHP fatal occured
  407. if ( !$thumb || $thumb->isError() ) {
  408. // Randomize TTL to reduce stampedes
  409. $cache->incrWithInit( $key, $cache::TTL_HOUR + mt_rand( 0, 300 ) );
  410. }
  411. return [ $thumb, $errorHtml ];
  412. }
  413. /**
  414. * Convert pathinfo type parameter, into normal request parameters
  415. *
  416. * So for example, if the request was redirected from
  417. * /w/images/thumb/a/ab/Foo.png/120px-Foo.png. The $thumbRel parameter
  418. * of this function would be set to "a/ab/Foo.png/120px-Foo.png".
  419. * This method is responsible for turning that into an array
  420. * with the folowing keys:
  421. * * f => the filename (Foo.png)
  422. * * rel404 => the whole thing (a/ab/Foo.png/120px-Foo.png)
  423. * * archived => 1 (If the request is for an archived thumb)
  424. * * temp => 1 (If the file is in the "temporary" zone)
  425. * * thumbName => the thumbnail name, including parameters (120px-Foo.png)
  426. *
  427. * Transform specific parameters are set later via wfExtractThumbParams().
  428. *
  429. * @param string $thumbRel Thumbnail path relative to the thumb zone
  430. * @return array|null Associative params array or null
  431. */
  432. function wfExtractThumbRequestInfo( $thumbRel ) {
  433. $repo = RepoGroup::singleton()->getLocalRepo();
  434. $hashDirReg = $subdirReg = '';
  435. $hashLevels = $repo->getHashLevels();
  436. for ( $i = 0; $i < $hashLevels; $i++ ) {
  437. $subdirReg .= '[0-9a-f]';
  438. $hashDirReg .= "$subdirReg/";
  439. }
  440. // Check if this is a thumbnail of an original in the local file repo
  441. if ( preg_match( "!^((archive/)?$hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
  442. list( /*all*/, $rel, $archOrTemp, $filename, $thumbname ) = $m;
  443. // Check if this is a thumbnail of an temp file in the local file repo
  444. } elseif ( preg_match( "!^(temp/)($hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
  445. list( /*all*/, $archOrTemp, $rel, $filename, $thumbname ) = $m;
  446. } else {
  447. return null; // not a valid looking thumbnail request
  448. }
  449. $params = [ 'f' => $filename, 'rel404' => $rel ];
  450. if ( $archOrTemp === 'archive/' ) {
  451. $params['archived'] = 1;
  452. } elseif ( $archOrTemp === 'temp/' ) {
  453. $params['temp'] = 1;
  454. }
  455. $params['thumbName'] = $thumbname;
  456. return $params;
  457. }
  458. /**
  459. * Convert a thumbnail name (122px-foo.png) to parameters, using
  460. * file handler.
  461. *
  462. * @param File $file File object for file in question
  463. * @param array $params Array of parameters so far
  464. * @return array Parameters array with more parameters
  465. */
  466. function wfExtractThumbParams( $file, $params ) {
  467. if ( !isset( $params['thumbName'] ) ) {
  468. throw new InvalidArgumentException( "No thumbnail name passed to wfExtractThumbParams" );
  469. }
  470. $thumbname = $params['thumbName'];
  471. unset( $params['thumbName'] );
  472. // Do the hook first for older extensions that rely on it.
  473. if ( !Hooks::run( 'ExtractThumbParameters', [ $thumbname, &$params ] ) ) {
  474. // Check hooks if parameters can be extracted
  475. // Hooks return false if they manage to *resolve* the parameters
  476. // This hook should be considered deprecated
  477. wfDeprecated( 'ExtractThumbParameters', '1.22' );
  478. return $params; // valid thumbnail URL (via extension or config)
  479. }
  480. // FIXME: Files in the temp zone don't set a MIME type, which means
  481. // they don't have a handler. Which means we can't parse the param
  482. // string. However, not a big issue as what good is a param string
  483. // if you have no handler to make use of the param string and
  484. // actually generate the thumbnail.
  485. $handler = $file->getHandler();
  486. // Based on UploadStash::parseKey
  487. $fileNamePos = strrpos( $thumbname, $params['f'] );
  488. if ( $fileNamePos === false ) {
  489. // Maybe using a short filename? (see FileRepo::nameForThumb)
  490. $fileNamePos = strrpos( $thumbname, 'thumbnail' );
  491. }
  492. if ( $handler && $fileNamePos !== false ) {
  493. $paramString = substr( $thumbname, 0, $fileNamePos - 1 );
  494. $extraParams = $handler->parseParamString( $paramString );
  495. if ( $extraParams !== false ) {
  496. return $params + $extraParams;
  497. }
  498. }
  499. // As a last ditch fallback, use the traditional common parameters
  500. if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
  501. list( /* all */, /* pagefull */, $pagenum, $size ) = $matches;
  502. $params['width'] = $size;
  503. if ( $pagenum ) {
  504. $params['page'] = $pagenum;
  505. }
  506. return $params; // valid thumbnail URL
  507. }
  508. return null;
  509. }
  510. /**
  511. * Output a thumbnail generation error message
  512. *
  513. * @param int $status
  514. * @param string $msgText Plain text (will be html escaped)
  515. * @return void
  516. */
  517. function wfThumbErrorText( $status, $msgText ) {
  518. wfThumbError( $status, htmlspecialchars( $msgText ) );
  519. }
  520. /**
  521. * Output a thumbnail generation error message
  522. *
  523. * @param int $status
  524. * @param string $msgHtml HTML
  525. * @param string $msgText Short error description, for internal logging. Defaults to $msgHtml.
  526. * Only used for HTTP 500 errors.
  527. * @param array $context Error context, for internal logging. Only used for HTTP 500 errors.
  528. * @return void
  529. */
  530. function wfThumbError( $status, $msgHtml, $msgText = null, $context = [] ) {
  531. global $wgShowHostnames;
  532. header( 'Cache-Control: no-cache' );
  533. header( 'Content-Type: text/html; charset=utf-8' );
  534. if ( $status == 400 || $status == 404 || $status == 429 ) {
  535. HttpStatus::header( $status );
  536. } elseif ( $status == 403 ) {
  537. HttpStatus::header( 403 );
  538. header( 'Vary: Cookie' );
  539. } else {
  540. LoggerFactory::getInstance( 'thumb' )->error( $msgText ?: $msgHtml, $context );
  541. HttpStatus::header( 500 );
  542. }
  543. if ( $wgShowHostnames ) {
  544. header( 'X-MW-Thumbnail-Renderer: ' . wfHostname() );
  545. $url = htmlspecialchars(
  546. isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : ''
  547. );
  548. $hostname = htmlspecialchars( wfHostname() );
  549. $debug = "<!-- $url -->\n<!-- $hostname -->\n";
  550. } else {
  551. $debug = '';
  552. }
  553. $content = <<<EOT
  554. <!DOCTYPE html>
  555. <html><head>
  556. <meta charset="UTF-8" />
  557. <title>Error generating thumbnail</title>
  558. </head>
  559. <body>
  560. <h1>Error generating thumbnail</h1>
  561. <p>
  562. $msgHtml
  563. </p>
  564. $debug
  565. </body>
  566. </html>
  567. EOT;
  568. header( 'Content-Length: ' . strlen( $content ) );
  569. echo $content;
  570. }