thumb.php 21 KB

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