thumb.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  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( $wgRequest->getQueryValues() );
  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 = $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. Wikimedia\suppressWarnings();
  210. $imsUnix = strtotime( $imsString );
  211. Wikimedia\restoreWarnings();
  212. if ( wfTimestamp( TS_UNIX, $img->getTimestamp() ) <= $imsUnix ) {
  213. HttpStatus::header( 304 );
  214. return;
  215. }
  216. }
  217. $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. $thumbProxyUrl = $img->getRepo()->getThumbProxyUrl();
  302. if ( strlen( $thumbProxyUrl ) ) {
  303. wfProxyThumbnailRequest( $img, $thumbName );
  304. // No local fallback when in proxy mode
  305. return;
  306. } else {
  307. // Generate the thumbnail locally
  308. list( $thumb, $errorMsg ) = wfGenerateThumbnail( $img, $params, $thumbName, $thumbPath );
  309. }
  310. /** @var MediaTransformOutput|MediaTransformError|bool $thumb */
  311. // Check for thumbnail generation errors...
  312. $msg = wfMessage( 'thumbnail_error' );
  313. $errorCode = 500;
  314. if ( !$thumb ) {
  315. $errorMsg = $errorMsg ?: $msg->rawParams( 'File::transform() returned false' )->escaped();
  316. if ( $errorMsg instanceof MessageSpecifier &&
  317. $errorMsg->getKey() === 'thumbnail_image-failure-limit'
  318. ) {
  319. $errorCode = 429;
  320. }
  321. } elseif ( $thumb->isError() ) {
  322. $errorMsg = $thumb->getHtmlMsg();
  323. $errorCode = $thumb->getHttpStatusCode();
  324. } elseif ( !$thumb->hasFile() ) {
  325. $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped();
  326. } elseif ( $thumb->fileIsSource() ) {
  327. $errorMsg = $msg
  328. ->rawParams( 'Image was not scaled, is the requested width bigger than the source?' )
  329. ->escaped();
  330. $errorCode = 400;
  331. }
  332. if ( $errorMsg !== false ) {
  333. wfThumbError( $errorCode, $errorMsg, null, [ 'file' => $thumbName, 'path' => $thumbPath ] );
  334. } else {
  335. // Stream the file if there were no errors
  336. $status = $thumb->streamFileWithStatus( $headers );
  337. if ( !$status->isOK() ) {
  338. wfThumbError( 500, 'Could not stream the file', null, [
  339. 'file' => $thumbName, 'path' => $thumbPath,
  340. 'error' => $status->getWikiText( false, false, 'en' ) ] );
  341. }
  342. }
  343. }
  344. /**
  345. * Proxies thumbnail request to a service that handles thumbnailing
  346. *
  347. * @param File $img
  348. * @param string $thumbName
  349. */
  350. function wfProxyThumbnailRequest( $img, $thumbName ) {
  351. $thumbProxyUrl = $img->getRepo()->getThumbProxyUrl();
  352. // Instead of generating the thumbnail ourselves, we proxy the request to another service
  353. $thumbProxiedUrl = $thumbProxyUrl . $img->getThumbRel( $thumbName );
  354. $req = MWHttpRequest::factory( $thumbProxiedUrl );
  355. $secret = $img->getRepo()->getThumbProxySecret();
  356. // Pass a secret key shared with the proxied service if any
  357. if ( strlen( $secret ) ) {
  358. $req->setHeader( 'X-Swift-Secret', $secret );
  359. }
  360. // Send request to proxied service
  361. $status = $req->execute();
  362. // Simply serve the response from the proxied service as-is
  363. header( 'HTTP/1.1 ' . $req->getStatus() );
  364. $headers = $req->getResponseHeaders();
  365. foreach ( $headers as $key => $values ) {
  366. foreach ( $values as $value ) {
  367. header( $key . ': ' . $value, false );
  368. }
  369. }
  370. echo $req->getContent();
  371. }
  372. /**
  373. * Actually try to generate a new thumbnail
  374. *
  375. * @param File $file
  376. * @param array $params
  377. * @param string $thumbName
  378. * @param string $thumbPath
  379. * @return array (MediaTransformOutput|bool, string|bool error message HTML)
  380. */
  381. function wfGenerateThumbnail( File $file, array $params, $thumbName, $thumbPath ) {
  382. global $wgAttemptFailureEpoch;
  383. $cache = ObjectCache::getLocalClusterInstance();
  384. $key = $cache->makeKey(
  385. 'attempt-failures',
  386. $wgAttemptFailureEpoch,
  387. $file->getRepo()->getName(),
  388. $file->getSha1(),
  389. md5( $thumbName )
  390. );
  391. // Check if this file keeps failing to render
  392. if ( $cache->get( $key ) >= 4 ) {
  393. return [ false, wfMessage( 'thumbnail_image-failure-limit', 4 ) ];
  394. }
  395. $done = false;
  396. // Record failures on PHP fatals in addition to caching exceptions
  397. register_shutdown_function( function () use ( $cache, &$done, $key ) {
  398. if ( !$done ) { // transform() gave a fatal
  399. // Randomize TTL to reduce stampedes
  400. $cache->incrWithInit( $key, $cache::TTL_HOUR + mt_rand( 0, 300 ) );
  401. }
  402. } );
  403. $thumb = false;
  404. $errorHtml = false;
  405. // guard thumbnail rendering with PoolCounter to avoid stampedes
  406. // expensive files use a separate PoolCounter config so it is possible
  407. // to set up a global limit on them
  408. if ( $file->isExpensiveToThumbnail() ) {
  409. $poolCounterType = 'FileRenderExpensive';
  410. } else {
  411. $poolCounterType = 'FileRender';
  412. }
  413. // Thumbnail isn't already there, so create the new thumbnail...
  414. try {
  415. $work = new PoolCounterWorkViaCallback( $poolCounterType, sha1( $file->getName() ),
  416. [
  417. 'doWork' => function () use ( $file, $params ) {
  418. return $file->transform( $params, File::RENDER_NOW );
  419. },
  420. 'doCachedWork' => function () use ( $file, $params, $thumbPath ) {
  421. // If the worker that finished made this thumbnail then use it.
  422. // Otherwise, it probably made a different thumbnail for this file.
  423. return $file->getRepo()->fileExists( $thumbPath )
  424. ? $file->transform( $params, File::RENDER_NOW )
  425. : false; // retry once more in exclusive mode
  426. },
  427. 'error' => function ( Status $status ) {
  428. return wfMessage( 'generic-pool-error' )->parse() . '<hr>' . $status->getHTML();
  429. }
  430. ]
  431. );
  432. $result = $work->execute();
  433. if ( $result instanceof MediaTransformOutput ) {
  434. $thumb = $result;
  435. } elseif ( is_string( $result ) ) { // error
  436. $errorHtml = $result;
  437. }
  438. } catch ( Exception $e ) {
  439. // Tried to select a page on a non-paged file?
  440. }
  441. /** @noinspection PhpUnusedLocalVariableInspection */
  442. $done = true; // no PHP fatal occurred
  443. if ( !$thumb || $thumb->isError() ) {
  444. // Randomize TTL to reduce stampedes
  445. $cache->incrWithInit( $key, $cache::TTL_HOUR + mt_rand( 0, 300 ) );
  446. }
  447. return [ $thumb, $errorHtml ];
  448. }
  449. /**
  450. * Convert pathinfo type parameter, into normal request parameters
  451. *
  452. * So for example, if the request was redirected from
  453. * /w/images/thumb/a/ab/Foo.png/120px-Foo.png. The $thumbRel parameter
  454. * of this function would be set to "a/ab/Foo.png/120px-Foo.png".
  455. * This method is responsible for turning that into an array
  456. * with the folowing keys:
  457. * * f => the filename (Foo.png)
  458. * * rel404 => the whole thing (a/ab/Foo.png/120px-Foo.png)
  459. * * archived => 1 (If the request is for an archived thumb)
  460. * * temp => 1 (If the file is in the "temporary" zone)
  461. * * thumbName => the thumbnail name, including parameters (120px-Foo.png)
  462. *
  463. * Transform specific parameters are set later via wfExtractThumbParams().
  464. *
  465. * @param string $thumbRel Thumbnail path relative to the thumb zone
  466. * @return array|null Associative params array or null
  467. */
  468. function wfExtractThumbRequestInfo( $thumbRel ) {
  469. $repo = RepoGroup::singleton()->getLocalRepo();
  470. $hashDirReg = $subdirReg = '';
  471. $hashLevels = $repo->getHashLevels();
  472. for ( $i = 0; $i < $hashLevels; $i++ ) {
  473. $subdirReg .= '[0-9a-f]';
  474. $hashDirReg .= "$subdirReg/";
  475. }
  476. // Check if this is a thumbnail of an original in the local file repo
  477. if ( preg_match( "!^((archive/)?$hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
  478. list( /*all*/, $rel, $archOrTemp, $filename, $thumbname ) = $m;
  479. // Check if this is a thumbnail of an temp file in the local file repo
  480. } elseif ( preg_match( "!^(temp/)($hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
  481. list( /*all*/, $archOrTemp, $rel, $filename, $thumbname ) = $m;
  482. } else {
  483. return null; // not a valid looking thumbnail request
  484. }
  485. $params = [ 'f' => $filename, 'rel404' => $rel ];
  486. if ( $archOrTemp === 'archive/' ) {
  487. $params['archived'] = 1;
  488. } elseif ( $archOrTemp === 'temp/' ) {
  489. $params['temp'] = 1;
  490. }
  491. $params['thumbName'] = $thumbname;
  492. return $params;
  493. }
  494. /**
  495. * Convert a thumbnail name (122px-foo.png) to parameters, using
  496. * file handler.
  497. *
  498. * @param File $file File object for file in question
  499. * @param array $params Array of parameters so far
  500. * @return array Parameters array with more parameters
  501. */
  502. function wfExtractThumbParams( $file, $params ) {
  503. if ( !isset( $params['thumbName'] ) ) {
  504. throw new InvalidArgumentException( "No thumbnail name passed to wfExtractThumbParams" );
  505. }
  506. $thumbname = $params['thumbName'];
  507. unset( $params['thumbName'] );
  508. // FIXME: Files in the temp zone don't set a MIME type, which means
  509. // they don't have a handler. Which means we can't parse the param
  510. // string. However, not a big issue as what good is a param string
  511. // if you have no handler to make use of the param string and
  512. // actually generate the thumbnail.
  513. $handler = $file->getHandler();
  514. // Based on UploadStash::parseKey
  515. $fileNamePos = strrpos( $thumbname, $params['f'] );
  516. if ( $fileNamePos === false ) {
  517. // Maybe using a short filename? (see FileRepo::nameForThumb)
  518. $fileNamePos = strrpos( $thumbname, 'thumbnail' );
  519. }
  520. if ( $handler && $fileNamePos !== false ) {
  521. $paramString = substr( $thumbname, 0, $fileNamePos - 1 );
  522. $extraParams = $handler->parseParamString( $paramString );
  523. if ( $extraParams !== false ) {
  524. return $params + $extraParams;
  525. }
  526. }
  527. // As a last ditch fallback, use the traditional common parameters
  528. if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
  529. list( /* all */, /* pagefull */, $pagenum, $size ) = $matches;
  530. $params['width'] = $size;
  531. if ( $pagenum ) {
  532. $params['page'] = $pagenum;
  533. }
  534. return $params; // valid thumbnail URL
  535. }
  536. return null;
  537. }
  538. /**
  539. * Output a thumbnail generation error message
  540. *
  541. * @param int $status
  542. * @param string $msgText Plain text (will be html escaped)
  543. * @return void
  544. */
  545. function wfThumbErrorText( $status, $msgText ) {
  546. wfThumbError( $status, htmlspecialchars( $msgText, ENT_NOQUOTES ) );
  547. }
  548. /**
  549. * Output a thumbnail generation error message
  550. *
  551. * @param int $status
  552. * @param string $msgHtml HTML
  553. * @param string|null $msgText Short error description, for internal logging. Defaults to $msgHtml.
  554. * Only used for HTTP 500 errors.
  555. * @param array $context Error context, for internal logging. Only used for HTTP 500 errors.
  556. * @return void
  557. */
  558. function wfThumbError( $status, $msgHtml, $msgText = null, $context = [] ) {
  559. global $wgShowHostnames;
  560. header( 'Cache-Control: no-cache' );
  561. header( 'Content-Type: text/html; charset=utf-8' );
  562. if ( $status == 400 || $status == 404 || $status == 429 ) {
  563. HttpStatus::header( $status );
  564. } elseif ( $status == 403 ) {
  565. HttpStatus::header( 403 );
  566. header( 'Vary: Cookie' );
  567. } else {
  568. LoggerFactory::getInstance( 'thumb' )->error( $msgText ?: $msgHtml, $context );
  569. HttpStatus::header( 500 );
  570. }
  571. if ( $wgShowHostnames ) {
  572. header( 'X-MW-Thumbnail-Renderer: ' . wfHostname() );
  573. $url = htmlspecialchars(
  574. $_SERVER['REQUEST_URI'] ?? '',
  575. ENT_NOQUOTES
  576. );
  577. $hostname = htmlspecialchars( wfHostname(), ENT_NOQUOTES );
  578. $debug = "<!-- $url -->\n<!-- $hostname -->\n";
  579. } else {
  580. $debug = '';
  581. }
  582. $content = <<<EOT
  583. <!DOCTYPE html>
  584. <html><head>
  585. <meta charset="UTF-8" />
  586. <title>Error generating thumbnail</title>
  587. </head>
  588. <body>
  589. <h1>Error generating thumbnail</h1>
  590. <p>
  591. $msgHtml
  592. </p>
  593. $debug
  594. </body>
  595. </html>
  596. EOT;
  597. header( 'Content-Length: ' . strlen( $content ) );
  598. echo $content;
  599. }