MediaWiki
REL1_23
|
00001 <?php 00024 define( 'MW_NO_OUTPUT_COMPRESSION', 1 ); 00025 require __DIR__ . '/includes/WebStart.php'; 00026 00027 // Don't use fancy mime detection, just check the file extension for jpg/gif/png 00028 $wgTrivialMimeDetection = true; 00029 00030 if ( defined( 'THUMB_HANDLER' ) ) { 00031 // Called from thumb_handler.php via 404; extract params from the URI... 00032 wfThumbHandle404(); 00033 } else { 00034 // Called directly, use $_GET params 00035 wfThumbHandleRequest(); 00036 } 00037 00038 wfLogProfilingData(); 00039 // Commit and close up! 00040 $factory = wfGetLBFactory(); 00041 $factory->commitMasterChanges(); 00042 $factory->shutdown(); 00043 00044 //-------------------------------------------------------------------------- 00045 00051 function wfThumbHandleRequest() { 00052 $params = get_magic_quotes_gpc() 00053 ? array_map( 'stripslashes', $_GET ) 00054 : $_GET; 00055 00056 wfStreamThumb( $params ); // stream the thumbnail 00057 } 00058 00064 function wfThumbHandle404() { 00065 global $wgArticlePath; 00066 00067 # Set action base paths so that WebRequest::getPathInfo() 00068 # recognizes the "X" as the 'title' in ../thumb_handler.php/X urls. 00069 # Note: If Custom per-extension repo paths are set, this may break. 00070 $repo = RepoGroup::singleton()->getLocalRepo(); 00071 $oldArticlePath = $wgArticlePath; 00072 $wgArticlePath = $repo->getZoneUrl( 'thumb' ) . '/$1'; 00073 00074 $matches = WebRequest::getPathInfo(); 00075 00076 $wgArticlePath = $oldArticlePath; 00077 00078 if ( !isset( $matches['title'] ) ) { 00079 wfThumbError( 404, 'Could not determine the name of the requested thumbnail.' ); 00080 return; 00081 } 00082 00083 $params = wfExtractThumbRequestInfo( $matches['title'] ); // basic wiki URL param extracting 00084 if ( $params == null ) { 00085 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' ); 00086 return; 00087 } 00088 00089 wfStreamThumb( $params ); // stream the thumbnail 00090 } 00091 00105 function wfStreamThumb( array $params ) { 00106 global $wgVaryOnXFP; 00107 00108 $section = new ProfileSection( __METHOD__ ); 00109 00110 $headers = array(); // HTTP headers to send 00111 00112 $fileName = isset( $params['f'] ) ? $params['f'] : ''; 00113 00114 // Backwards compatibility parameters 00115 if ( isset( $params['w'] ) ) { 00116 $params['width'] = $params['w']; 00117 unset( $params['w'] ); 00118 } 00119 if ( isset( $params['p'] ) ) { 00120 $params['page'] = $params['p']; 00121 } 00122 00123 // Is this a thumb of an archived file? 00124 $isOld = ( isset( $params['archived'] ) && $params['archived'] ); 00125 unset( $params['archived'] ); // handlers don't care 00126 00127 // Is this a thumb of a temp file? 00128 $isTemp = ( isset( $params['temp'] ) && $params['temp'] ); 00129 unset( $params['temp'] ); // handlers don't care 00130 00131 // Some basic input validation 00132 $fileName = strtr( $fileName, '\\/', '__' ); 00133 00134 // Actually fetch the image. Method depends on whether it is archived or not. 00135 if ( $isTemp ) { 00136 $repo = RepoGroup::singleton()->getLocalRepo()->getTempRepo(); 00137 $img = new UnregisteredLocalFile( null, $repo, 00138 # Temp files are hashed based on the name without the timestamp. 00139 # The thumbnails will be hashed based on the entire name however. 00140 # @todo fix this convention to actually be reasonable. 00141 $repo->getZonePath( 'public' ) . '/' . $repo->getTempHashPath( $fileName ) . $fileName 00142 ); 00143 } elseif ( $isOld ) { 00144 // Format is <timestamp>!<name> 00145 $bits = explode( '!', $fileName, 2 ); 00146 if ( count( $bits ) != 2 ) { 00147 wfThumbError( 404, wfMessage( 'badtitletext' )->text() ); 00148 return; 00149 } 00150 $title = Title::makeTitleSafe( NS_FILE, $bits[1] ); 00151 if ( !$title ) { 00152 wfThumbError( 404, wfMessage( 'badtitletext' )->text() ); 00153 return; 00154 } 00155 $img = RepoGroup::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName ); 00156 } else { 00157 $img = wfLocalFile( $fileName ); 00158 } 00159 00160 // Check the source file title 00161 if ( !$img ) { 00162 wfThumbError( 404, wfMessage( 'badtitletext' )->text() ); 00163 return; 00164 } 00165 00166 // Check permissions if there are read restrictions 00167 $varyHeader = array(); 00168 if ( !in_array( 'read', User::getGroupPermissions( array( '*' ) ), true ) ) { 00169 if ( !$img->getTitle() || !$img->getTitle()->userCan( 'read' ) ) { 00170 wfThumbError( 403, 'Access denied. You do not have permission to access ' . 00171 'the source file.' ); 00172 return; 00173 } 00174 $headers[] = 'Cache-Control: private'; 00175 $varyHeader[] = 'Cookie'; 00176 } 00177 00178 // Do rendering parameters extraction from thumbnail name. 00179 if ( isset( $params['thumbName'] ) ) { 00180 $params = wfExtractThumbParams( $img, $params ); 00181 } 00182 if ( $params == null ) { 00183 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' ); 00184 return; 00185 } 00186 00187 // Check the source file storage path 00188 if ( !$img->exists() ) { 00189 $redirectedLocation = false; 00190 if ( !$isTemp ) { 00191 // Check for file redirect 00192 // Since redirects are associated with pages, not versions of files, 00193 // we look for the most current version to see if its a redirect. 00194 $possRedirFile = RepoGroup::singleton()->getLocalRepo()->findFile( $img->getName() ); 00195 if ( $possRedirFile && !is_null( $possRedirFile->getRedirected() ) ) { 00196 $redirTarget = $possRedirFile->getName(); 00197 $targetFile = wfLocalFile( Title::makeTitleSafe( NS_FILE, $redirTarget ) ); 00198 if ( $targetFile->exists() ) { 00199 $newThumbName = $targetFile->thumbName( $params ); 00200 if ( $isOld ) { 00201 $newThumbUrl = $targetFile->getArchiveThumbUrl( 00202 $bits[0] . '!' . $targetFile->getName(), $newThumbName ); 00203 } else { 00204 $newThumbUrl = $targetFile->getThumbUrl( $newThumbName ); 00205 } 00206 $redirectedLocation = wfExpandUrl( $newThumbUrl, PROTO_CURRENT ); 00207 } 00208 } 00209 } 00210 00211 if ( $redirectedLocation ) { 00212 // File has been moved. Give redirect. 00213 $response = RequestContext::getMain()->getRequest()->response(); 00214 $response->header( "HTTP/1.1 302 " . HttpStatus::getMessage( 302 ) ); 00215 $response->header( 'Location: ' . $redirectedLocation ); 00216 $response->header( 'Expires: ' . 00217 gmdate( 'D, d M Y H:i:s', time() + 12 * 3600 ) . ' GMT' ); 00218 if ( $wgVaryOnXFP ) { 00219 $varyHeader[] = 'X-Forwarded-Proto'; 00220 } 00221 if ( count( $varyHeader ) ) { 00222 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) ); 00223 } 00224 return; 00225 } 00226 00227 // If its not a redirect that has a target as a local file, give 404. 00228 wfThumbError( 404, "The source file '$fileName' does not exist." ); 00229 return; 00230 } elseif ( $img->getPath() === false ) { 00231 wfThumbError( 500, "The source file '$fileName' is not locally accessible." ); 00232 return; 00233 } 00234 00235 // Check IMS against the source file 00236 // This means that clients can keep a cached copy even after it has been deleted on the server 00237 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) { 00238 // Fix IE brokenness 00239 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] ); 00240 // Calculate time 00241 wfSuppressWarnings(); 00242 $imsUnix = strtotime( $imsString ); 00243 wfRestoreWarnings(); 00244 if ( wfTimestamp( TS_UNIX, $img->getTimestamp() ) <= $imsUnix ) { 00245 header( 'HTTP/1.1 304 Not Modified' ); 00246 return; 00247 } 00248 } 00249 00250 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER 00251 unset( $params['f'] ); // We're done with 'f' parameter. 00252 00253 // Get the normalized thumbnail name from the parameters... 00254 try { 00255 $thumbName = $img->thumbName( $params ); 00256 if ( !strlen( $thumbName ) ) { // invalid params? 00257 wfThumbError( 400, 'The specified thumbnail parameters are not valid.' ); 00258 return; 00259 } 00260 $thumbName2 = $img->thumbName( $params, File::THUMB_FULL_NAME ); // b/c; "long" style 00261 } catch ( MWException $e ) { 00262 wfThumbError( 500, $e->getHTML() ); 00263 return; 00264 } 00265 00266 // For 404 handled thumbnails, we only use the the base name of the URI 00267 // for the thumb params and the parent directory for the source file name. 00268 // Check that the zone relative path matches up so squid caches won't pick 00269 // up thumbs that would not be purged on source file deletion (bug 34231). 00270 if ( isset( $params['rel404'] ) ) { // thumbnail was handled via 404 00271 if ( rawurldecode( $params['rel404'] ) === $img->getThumbRel( $thumbName ) ) { 00272 // Request for the canonical thumbnail name 00273 } elseif ( rawurldecode( $params['rel404'] ) === $img->getThumbRel( $thumbName2 ) ) { 00274 // Request for the "long" thumbnail name; redirect to canonical name 00275 $response = RequestContext::getMain()->getRequest()->response(); 00276 $response->header( "HTTP/1.1 301 " . HttpStatus::getMessage( 301 ) ); 00277 $response->header( 'Location: ' . 00278 wfExpandUrl( $img->getThumbUrl( $thumbName ), PROTO_CURRENT ) ); 00279 $response->header( 'Expires: ' . 00280 gmdate( 'D, d M Y H:i:s', time() + 7 * 86400 ) . ' GMT' ); 00281 if ( $wgVaryOnXFP ) { 00282 $varyHeader[] = 'X-Forwarded-Proto'; 00283 } 00284 if ( count( $varyHeader ) ) { 00285 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) ); 00286 } 00287 return; 00288 } else { 00289 wfThumbError( 404, "The given path of the specified thumbnail is incorrect; 00290 expected '" . $img->getThumbRel( $thumbName ) . "' but got '" . 00291 rawurldecode( $params['rel404'] ) . "'." ); 00292 return; 00293 } 00294 } 00295 00296 $dispositionType = isset( $params['download'] ) ? 'attachment' : 'inline'; 00297 00298 // Suggest a good name for users downloading this thumbnail 00299 $headers[] = "Content-Disposition: {$img->getThumbDisposition( $thumbName, $dispositionType )}"; 00300 00301 if ( count( $varyHeader ) ) { 00302 $headers[] = 'Vary: ' . implode( ', ', $varyHeader ); 00303 } 00304 00305 // Stream the file if it exists already... 00306 $thumbPath = $img->getThumbPath( $thumbName ); 00307 if ( $img->getRepo()->fileExists( $thumbPath ) ) { 00308 $img->getRepo()->streamFile( $thumbPath, $headers ); 00309 return; 00310 } 00311 00312 $user = RequestContext::getMain()->getUser(); 00313 if ( $user->pingLimiter( 'renderfile' ) ) { 00314 wfThumbError( 500, wfMessage( 'actionthrottledtext' ) ); 00315 return; 00316 } elseif ( wfThumbIsAttemptThrottled( $img, $thumbName, 5 ) ) { 00317 wfThumbError( 500, wfMessage( 'thumbnail_image-failure-limit', 5 ) ); 00318 return; 00319 } 00320 00321 // Thumbnail isn't already there, so create the new thumbnail... 00322 try { 00323 $thumb = $img->transform( $params, File::RENDER_NOW ); 00324 } catch ( Exception $ex ) { 00325 // Tried to select a page on a non-paged file? 00326 $thumb = false; 00327 } 00328 00329 // Check for thumbnail generation errors... 00330 $errorMsg = false; 00331 $msg = wfMessage( 'thumbnail_error' ); 00332 if ( !$thumb ) { 00333 $errorMsg = $msg->rawParams( 'File::transform() returned false' )->escaped(); 00334 } elseif ( $thumb->isError() ) { 00335 $errorMsg = $thumb->getHtmlMsg(); 00336 } elseif ( !$thumb->hasFile() ) { 00337 $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped(); 00338 } elseif ( $thumb->fileIsSource() ) { 00339 $errorMsg = $msg-> 00340 rawParams( 'Image was not scaled, is the requested width bigger than the source?' )->escaped(); 00341 } 00342 00343 if ( $errorMsg !== false ) { 00344 wfThumbIncrAttemptFailures( $img, $thumbName ); 00345 wfThumbError( 500, $errorMsg ); 00346 } else { 00347 // Stream the file if there were no errors 00348 $thumb->streamFile( $headers ); 00349 } 00350 } 00351 00358 function wfThumbIsAttemptThrottled( File $img, $thumbName, $limit ) { 00359 global $wgMemc; 00360 00361 return ( $wgMemc->get( wfThumbAttemptKey( $img, $thumbName ) ) >= $limit ); 00362 } 00363 00368 function wfThumbIncrAttemptFailures( File $img, $thumbName ) { 00369 global $wgMemc; 00370 00371 $key = wfThumbAttemptKey( $img, $thumbName ); 00372 if ( !$wgMemc->incr( $key, 1 ) ) { 00373 if ( !$wgMemc->add( $key, 1, 3600 ) ) { 00374 $wgMemc->incr( $key, 1 ); 00375 } 00376 } 00377 } 00378 00384 function wfThumbAttemptKey( File $img, $thumbName ) { 00385 global $wgAttemptFailureEpoch; 00386 00387 return wfMemcKey( 'attempt-failures', $wgAttemptFailureEpoch, 00388 $img->getRepo()->getName(), md5( $img->getName() ), md5( $thumbName ) ); 00389 } 00390 00410 function wfExtractThumbRequestInfo( $thumbRel ) { 00411 $repo = RepoGroup::singleton()->getLocalRepo(); 00412 00413 $hashDirReg = $subdirReg = ''; 00414 for ( $i = 0; $i < $repo->getHashLevels(); $i++ ) { 00415 $subdirReg .= '[0-9a-f]'; 00416 $hashDirReg .= "$subdirReg/"; 00417 } 00418 00419 // Check if this is a thumbnail of an original in the local file repo 00420 if ( preg_match( "!^((archive/)?$hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) { 00421 list( /*all*/, $rel, $archOrTemp, $filename, $thumbname ) = $m; 00422 // Check if this is a thumbnail of an temp file in the local file repo 00423 } elseif ( preg_match( "!^(temp/)($hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) { 00424 list( /*all*/, $archOrTemp, $rel, $filename, $thumbname ) = $m; 00425 } else { 00426 return null; // not a valid looking thumbnail request 00427 } 00428 00429 $params = array( 'f' => $filename, 'rel404' => $rel ); 00430 if ( $archOrTemp === 'archive/' ) { 00431 $params['archived'] = 1; 00432 } elseif ( $archOrTemp === 'temp/' ) { 00433 $params['temp'] = 1; 00434 } 00435 00436 $params['thumbName'] = $thumbname; 00437 return $params; 00438 } 00439 00448 function wfExtractThumbParams( $file, $params ) { 00449 if ( !isset( $params['thumbName'] ) ) { 00450 throw new MWException( "No thumbnail name passed to wfExtractThumbParams" ); 00451 } 00452 00453 $thumbname = $params['thumbName']; 00454 unset( $params['thumbName'] ); 00455 00456 // Do the hook first for older extensions that rely on it. 00457 if ( !wfRunHooks( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) { 00458 // Check hooks if parameters can be extracted 00459 // Hooks return false if they manage to *resolve* the parameters 00460 // This hook should be considered deprecated 00461 wfDeprecated( 'ExtractThumbParameters', '1.22' ); 00462 return $params; // valid thumbnail URL (via extension or config) 00463 } 00464 00465 // FIXME: Files in the temp zone don't set a mime type, which means 00466 // they don't have a handler. Which means we can't parse the param 00467 // string. However, not a big issue as what good is a param string 00468 // if you have no handler to make use of the param string and 00469 // actually generate the thumbnail. 00470 $handler = $file->getHandler(); 00471 00472 // Based on UploadStash::parseKey 00473 $fileNamePos = strrpos( $thumbname, $params['f'] ); 00474 if ( $fileNamePos === false ) { 00475 // Maybe using a short filename? (see FileRepo::nameForThumb) 00476 $fileNamePos = strrpos( $thumbname, 'thumbnail' ); 00477 } 00478 00479 if ( $handler && $fileNamePos !== false ) { 00480 $paramString = substr( $thumbname, 0, $fileNamePos - 1 ); 00481 $extraParams = $handler->parseParamString( $paramString ); 00482 if ( $extraParams !== false ) { 00483 return $params + $extraParams; 00484 } 00485 } 00486 00487 // As a last ditch fallback, use the traditional common parameters 00488 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) { 00489 list( /* all */, $pagefull, $pagenum, $size ) = $matches; 00490 $params['width'] = $size; 00491 if ( $pagenum ) { 00492 $params['page'] = $pagenum; 00493 } 00494 return $params; // valid thumbnail URL 00495 } 00496 return null; 00497 } 00498 00506 function wfThumbError( $status, $msg ) { 00507 global $wgShowHostnames; 00508 00509 header( 'Cache-Control: no-cache' ); 00510 header( 'Content-Type: text/html; charset=utf-8' ); 00511 if ( $status == 404 ) { 00512 header( 'HTTP/1.1 404 Not found' ); 00513 } elseif ( $status == 403 ) { 00514 header( 'HTTP/1.1 403 Forbidden' ); 00515 header( 'Vary: Cookie' ); 00516 } else { 00517 header( 'HTTP/1.1 500 Internal server error' ); 00518 } 00519 if ( $wgShowHostnames ) { 00520 header( 'X-MW-Thumbnail-Renderer: ' . wfHostname() ); 00521 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '' ); 00522 $hostname = htmlspecialchars( wfHostname() ); 00523 $debug = "<!-- $url -->\n<!-- $hostname -->\n"; 00524 } else { 00525 $debug = ''; 00526 } 00527 echo <<<EOT 00528 <html><head><title>Error generating thumbnail</title></head> 00529 <body> 00530 <h1>Error generating thumbnail</h1> 00531 <p> 00532 $msg 00533 </p> 00534 $debug 00535 </body> 00536 </html> 00537 00538 EOT; 00539 }