PageRenderTime 51ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/thumb.php

https://github.com/spenser-roark/OOUG-Wiki
PHP | 329 lines | 227 code | 35 blank | 67 comment | 50 complexity | 13a4e6cb713da0159acca0976ae6032e MD5 | raw file
Possible License(s): GPL-2.0, Apache-2.0, LGPL-3.0
  1. <?php
  2. /**
  3. * PHP script to stream out an image thumbnail.
  4. *
  5. * @file
  6. * @ingroup Media
  7. */
  8. define( 'MW_NO_OUTPUT_COMPRESSION', 1 );
  9. if ( isset( $_SERVER['MW_COMPILED'] ) ) {
  10. require( 'phase3/includes/WebStart.php' );
  11. } else {
  12. require( dirname( __FILE__ ) . '/includes/WebStart.php' );
  13. }
  14. // Don't use fancy mime detection, just check the file extension for jpg/gif/png
  15. $wgTrivialMimeDetection = true;
  16. if ( defined( 'THUMB_HANDLER' ) ) {
  17. // Called from thumb_handler.php via 404; extract params from the URI...
  18. wfThumbHandle404();
  19. } else {
  20. // Called directly, use $_REQUEST params
  21. wfThumbHandleRequest();
  22. }
  23. wfLogProfilingData();
  24. //--------------------------------------------------------------------------
  25. /**
  26. * Handle a thumbnail request via query parameters
  27. *
  28. * @return void
  29. */
  30. function wfThumbHandleRequest() {
  31. $params = get_magic_quotes_gpc()
  32. ? array_map( 'stripslashes', $_REQUEST )
  33. : $_REQUEST;
  34. wfStreamThumb( $params ); // stream the thumbnail
  35. }
  36. /**
  37. * Handle a thumbnail request via thumbnail file URL
  38. *
  39. * @return void
  40. */
  41. function wfThumbHandle404() {
  42. # lighttpd puts the original request in REQUEST_URI, while sjs sets
  43. # that to the 404 handler, and puts the original request in REDIRECT_URL.
  44. if ( isset( $_SERVER['REDIRECT_URL'] ) ) {
  45. # The URL is un-encoded, so put it back how it was
  46. $uri = str_replace( "%2F", "/", urlencode( $_SERVER['REDIRECT_URL'] ) );
  47. # Just get the URI path (REDIRECT_URL is either a full URL or a path)
  48. if ( $uri[0] !== '/' ) {
  49. $bits = wfParseUrl( $uri );
  50. if ( $bits && isset( $bits['path'] ) ) {
  51. $uri = $bits['path'];
  52. }
  53. }
  54. } else {
  55. $uri = $_SERVER['REQUEST_URI'];
  56. }
  57. $params = wfExtractThumbParams( $uri ); // basic wiki URL param extracting
  58. if ( $params == null ) {
  59. wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
  60. return;
  61. }
  62. wfStreamThumb( $params ); // stream the thumbnail
  63. }
  64. /**
  65. * Stream a thumbnail specified by parameters
  66. *
  67. * @param $params Array
  68. * @return void
  69. */
  70. function wfStreamThumb( array $params ) {
  71. wfProfileIn( __METHOD__ );
  72. $headers = array(); // HTTP headers to send
  73. $fileName = isset( $params['f'] ) ? $params['f'] : '';
  74. unset( $params['f'] );
  75. // Backwards compatibility parameters
  76. if ( isset( $params['w'] ) ) {
  77. $params['width'] = $params['w'];
  78. unset( $params['w'] );
  79. }
  80. if ( isset( $params['p'] ) ) {
  81. $params['page'] = $params['p'];
  82. }
  83. unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
  84. // Is this a thumb of an archived file?
  85. $isOld = ( isset( $params['archived'] ) && $params['archived'] );
  86. unset( $params['archived'] );
  87. // Some basic input validation
  88. $fileName = strtr( $fileName, '\\/', '__' );
  89. // Actually fetch the image. Method depends on whether it is archived or not.
  90. if ( $isOld ) {
  91. // Format is <timestamp>!<name>
  92. $bits = explode( '!', $fileName, 2 );
  93. if ( count( $bits ) != 2 ) {
  94. wfThumbError( 404, wfMsg( 'badtitletext' ) );
  95. wfProfileOut( __METHOD__ );
  96. return;
  97. }
  98. $title = Title::makeTitleSafe( NS_FILE, $bits[1] );
  99. if ( !$title ) {
  100. wfThumbError( 404, wfMsg( 'badtitletext' ) );
  101. wfProfileOut( __METHOD__ );
  102. return;
  103. }
  104. $img = RepoGroup::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
  105. } else {
  106. $img = wfLocalFile( $fileName );
  107. }
  108. // Check permissions if there are read restrictions
  109. if ( !in_array( 'read', User::getGroupPermissions( array( '*' ) ), true ) ) {
  110. if ( !$img->getTitle()->userCan( 'read' ) ) {
  111. wfThumbError( 403, 'Access denied. You do not have permission to access ' .
  112. 'the source file.' );
  113. wfProfileOut( __METHOD__ );
  114. return;
  115. }
  116. $headers[] = 'Cache-Control: private';
  117. $headers[] = 'Vary: Cookie';
  118. }
  119. // Check the source file storage path
  120. if ( !$img ) {
  121. wfThumbError( 404, wfMsg( 'badtitletext' ) );
  122. wfProfileOut( __METHOD__ );
  123. return;
  124. }
  125. if ( !$img->exists() ) {
  126. wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
  127. wfProfileOut( __METHOD__ );
  128. return;
  129. }
  130. $sourcePath = $img->getPath();
  131. if ( $sourcePath === false ) {
  132. wfThumbError( 500, 'The source file is not locally accessible.' );
  133. wfProfileOut( __METHOD__ );
  134. return;
  135. }
  136. // Check IMS against the source file
  137. // This means that clients can keep a cached copy even after it has been deleted on the server
  138. if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
  139. // Fix IE brokenness
  140. $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
  141. // Calculate time
  142. wfSuppressWarnings();
  143. $imsUnix = strtotime( $imsString );
  144. wfRestoreWarnings();
  145. $sourceTsUnix = wfTimestamp( TS_UNIX, $img->getTimestamp() );
  146. if ( $sourceTsUnix <= $imsUnix ) {
  147. header( 'HTTP/1.1 304 Not Modified' );
  148. wfProfileOut( __METHOD__ );
  149. return;
  150. }
  151. }
  152. // Stream the file if it exists already...
  153. try {
  154. $thumbName = $img->thumbName( $params );
  155. if ( strlen( $thumbName ) ) { // valid params?
  156. // For 404 handled thumbnails, we only use the the base name of the URI
  157. // for the thumb params and the parent directory for the source file name.
  158. // Check that the zone relative path matches up so squid caches won't pick
  159. // up thumbs that would not be purged on source file deletion (bug 34231).
  160. if ( isset( $params['rel404'] ) // thumbnail was handled via 404
  161. && urldecode( $params['rel404'] ) !== $img->getThumbRel( $thumbName ) )
  162. {
  163. wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
  164. wfProfileOut( __METHOD__ );
  165. return;
  166. }
  167. $thumbPath = $img->getThumbPath( $thumbName );
  168. if ( $img->getRepo()->fileExists( $thumbPath ) ) {
  169. $img->getRepo()->streamFile( $thumbPath, $headers );
  170. wfProfileOut( __METHOD__ );
  171. return;
  172. }
  173. }
  174. } catch ( MWException $e ) {
  175. wfThumbError( 500, $e->getHTML() );
  176. wfProfileOut( __METHOD__ );
  177. return;
  178. }
  179. // Thumbnail isn't already there, so create the new thumbnail...
  180. try {
  181. $thumb = $img->transform( $params, File::RENDER_NOW );
  182. } catch ( Exception $ex ) {
  183. // Tried to select a page on a non-paged file?
  184. $thumb = false;
  185. }
  186. // Check for thumbnail generation errors...
  187. $errorMsg = false;
  188. if ( !$thumb ) {
  189. $errorMsg = wfMsgHtml( 'thumbnail_error', 'File::transform() returned false' );
  190. } elseif ( $thumb->isError() ) {
  191. $errorMsg = $thumb->getHtmlMsg();
  192. } elseif ( !$thumb->hasFile() ) {
  193. $errorMsg = wfMsgHtml( 'thumbnail_error', 'No path supplied in thumbnail object' );
  194. } elseif ( $thumb->fileIsSource() ) {
  195. $errorMsg = wfMsgHtml( 'thumbnail_error',
  196. 'Image was not scaled, is the requested width bigger than the source?' );
  197. }
  198. if ( $errorMsg !== false ) {
  199. wfThumbError( 500, $errorMsg );
  200. } else {
  201. // Stream the file if there were no errors
  202. $thumb->streamFile( $headers );
  203. }
  204. wfProfileOut( __METHOD__ );
  205. }
  206. /**
  207. * Extract the required params for thumb.php from the thumbnail request URI.
  208. * At least 'width' and 'f' should be set if the result is an array.
  209. *
  210. * @param $uri String Thumbnail request URI path
  211. * @return Array|null associative params array or null
  212. */
  213. function wfExtractThumbParams( $uri ) {
  214. $repo = RepoGroup::singleton()->getLocalRepo();
  215. $zoneURI = $repo->getZoneUrl( 'thumb' );
  216. if ( substr( $zoneURI, 0, 1 ) !== '/' ) {
  217. $bits = wfParseUrl( $zoneURI );
  218. if ( $bits && isset( $bits['path'] ) ) {
  219. $zoneURI = $bits['path'];
  220. } else {
  221. return null;
  222. }
  223. }
  224. $zoneUrlRegex = preg_quote( $zoneURI );
  225. $hashDirRegex = $subdirRegex = '';
  226. for ( $i = 0; $i < $repo->getHashLevels(); $i++ ) {
  227. $subdirRegex .= '[0-9a-f]';
  228. $hashDirRegex .= "$subdirRegex/";
  229. }
  230. $thumbUrlRegex = "!^$zoneUrlRegex/((archive/|temp/)?$hashDirRegex([^/]*)/([^/]*))$!";
  231. // Check if this is a valid looking thumbnail request...
  232. if ( preg_match( $thumbUrlRegex, $uri, $matches ) ) {
  233. list( /* all */, $rel, $archOrTemp, $filename, $thumbname ) = $matches;
  234. $filename = urldecode( $filename );
  235. $thumbname = urldecode( $thumbname );
  236. $params = array( 'f' => $filename, 'rel404' => $rel );
  237. if ( $archOrTemp == 'archive/' ) {
  238. $params['archived'] = 1;
  239. } elseif ( $archOrTemp == 'temp/' ) {
  240. $params['temp'] = 1;
  241. }
  242. // Check if the parameters can be extracted from the thumbnail name...
  243. if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
  244. list( /* all */, $pagefull, $pagenum, $size ) = $matches;
  245. $params['width'] = $size;
  246. if ( $pagenum ) {
  247. $params['page'] = $pagenum;
  248. }
  249. return $params; // valid thumbnail URL
  250. // Hooks return false if they manage to *resolve* the parameters
  251. } elseif ( !wfRunHooks( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
  252. return $params; // valid thumbnail URL (via extension or config)
  253. }
  254. }
  255. return null; // not a valid thumbnail URL
  256. }
  257. /**
  258. * Output a thumbnail generation error message
  259. *
  260. * @param $status integer
  261. * @param $msg string
  262. * @return void
  263. */
  264. function wfThumbError( $status, $msg ) {
  265. global $wgShowHostnames;
  266. header( 'Cache-Control: no-cache' );
  267. header( 'Content-Type: text/html; charset=utf-8' );
  268. if ( $status == 404 ) {
  269. header( 'HTTP/1.1 404 Not found' );
  270. } elseif ( $status == 403 ) {
  271. header( 'HTTP/1.1 403 Forbidden' );
  272. header( 'Vary: Cookie' );
  273. } else {
  274. header( 'HTTP/1.1 500 Internal server error' );
  275. }
  276. if ( $wgShowHostnames ) {
  277. $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '' );
  278. $hostname = htmlspecialchars( wfHostname() );
  279. $debug = "<!-- $url -->\n<!-- $hostname -->\n";
  280. } else {
  281. $debug = "";
  282. }
  283. echo <<<EOT
  284. <html><head><title>Error generating thumbnail</title></head>
  285. <body>
  286. <h1>Error generating thumbnail</h1>
  287. <p>
  288. $msg
  289. </p>
  290. $debug
  291. </body>
  292. </html>
  293. EOT;
  294. }