thumb.php 22 KB

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