* Fix notice & blank text on nogomatch
[mediawiki.git] / includes / Image.php
blobe6fbb19ebbf4f729b482f429abccc600e5f8cf43
1 <?php
2 /**
3 * @package MediaWiki
4 * $Id$
5 */
7 /**
8 * Class to represent an image
9 *
10 * Provides methods to retrieve paths (physical, logical, URL),
11 * to generate thumbnails or for uploading.
12 * @package MediaWiki
14 class Image
16 /**#@+
17 * @access private
19 var $name, # name of the image
20 $imagePath, # Path of the image
21 $url, # Image URL
22 $title, # Title object for this image. Initialized when needed.
23 $fileExists, # does the image file exist on disk?
24 $historyLine, # Number of line to return by nextHistoryLine()
25 $historyRes, # result of the query for the image's history
26 $width, # \
27 $height, # |
28 $bits, # --- returned by getimagesize, see http://de3.php.net/manual/en/function.getimagesize.php
29 $type, # |
30 $attr; # /
32 /**#@-*/
35 /**
36 * Create an Image object from an image name
38 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
39 * @access public
41 function Image( $name )
43 global $wgUploadDirectory,$wgHashedUploadDirectory;
45 $this->name = $name;
46 $this->title = Title::makeTitleSafe( NS_IMAGE, $this->name );
47 //$this->imagePath = wfImagePath( $name );
48 if ($wgHashedUploadDirectory) {
49 $hash = md5( $this->title->getDBkey() );
50 $this->imagePath = $wgUploadDirectory . '/' . $hash{0} . '/' .
51 substr( $hash, 0, 2 ) . "/{$name}";
52 } else {
53 $this->imagePath = $wgUploadDirectory . '/' . $name;
56 $this->url = $this->wfImageUrl( $name );
58 if ( $this->fileExists = file_exists( $this->imagePath ) ) // Sic!, "=" is intended
60 @$gis = getimagesize( $this->imagePath );
61 if( $gis !== false ) {
62 $this->width = $gis[0];
63 $this->height = $gis[1];
64 $this->type = $gis[2];
65 $this->attr = $gis[3];
66 if ( isset( $gis['bits'] ) ) {
67 $this->bits = $gis['bits'];
68 } else {
69 $this->bits = 0;
73 $this->historyLine = 0;
76 /**
77 * Factory function
79 * Create a new image object from a title object.
81 * @param Title $nt Title object. Must be from namespace "image"
82 * @access public
84 function newFromTitle( $nt )
86 $img = new Image( $nt->getDBKey() );
87 $img->title = $nt;
88 return $img;
91 /**
92 * Return the name of this image
93 * @access public
95 function getName()
97 return $this->name;
101 * Return the associated title object
102 * @access public
104 function getTitle()
106 return $this->title;
110 * Return the URL of the image file
111 * @access public
113 function getURL()
115 return $this->url;
119 * Return the image path of the image in the
120 * local file system as an absolute path
121 * @access public
123 function getImagePath()
125 return $this->imagePath;
129 * Return the width of the image
131 * Returns -1 if the file specified is not a known image type
132 * @access public
134 function getWidth()
136 return $this->width;
140 * Return the height of the image
142 * Returns -1 if the file specified is not a known image type
143 * @access public
145 function getHeight()
147 return $this->height;
151 * Return the size of the image file, in bytes
152 * @access public
154 function getSize()
156 $st = stat( $this->getImagePath() );
157 return $st['size'];
161 * Return the type of the image
163 * - 1 GIF
164 * - 2 JPG
165 * - 3 PNG
166 * - 15 WBMP
167 * - 16 XBM
169 function getType()
171 return $this->type;
175 * Return the escapeLocalURL of this image
176 * @access public
178 function getEscapeLocalURL()
180 return $this->title->escapeLocalURL();
184 * Return the URL of an image, provided its name.
186 * @param string $name Name of the image, without the leading Image:
187 * @access public
189 function wfImageUrl( $name )
191 global $wgUploadPath,$wgUploadBaseUrl,$wgHashedUploadDirectory;
192 if ($wgHashedUploadDirectory) {
193 $hash = md5( $name );
194 $url = "{$wgUploadBaseUrl}{$wgUploadPath}/" . $hash{0} . "/" .
195 substr( $hash, 0, 2 ) . "/{$name}";
196 } else {
197 $url = "{$wgUploadBaseUrl}{$wgUploadPath}/{$name}";
199 return wfUrlencode( $url );
203 * Returns true iff the image file exists on disk.
205 * @access public
207 function exists()
209 return $this->fileExists;
214 * @access private
216 function thumbUrl( $width, $subdir='thumb' ) {
217 global $wgUploadPath,$wgHashedUploadDirectory;
218 $name = $this->thumbName( $width );
219 if ($wgHashedUploadDirectory) {
220 $hash = md5( $name );
221 $url = "{$wgUploadPath}/{$subdir}/" . $hash{0} . "/" .
222 substr( $hash, 0, 2 ) . "/{$name}";
223 } else {
224 $url = "{$wgUploadPath}/{$subdir}/{$name}";
227 return wfUrlencode($url);
231 * Return the file name of a thumbnail of the specified width
233 * @param integer $width Width of the thumbnail image
234 * @access private
236 function thumbName( $width ) {
237 return $width."px-".$this->name;
241 * Create a thumbnail of the image having the specified width/height.
242 * The thumbnail will not be created if the width is larger than the
243 * image's width. Let the browser do the scaling in this case.
244 * The thumbnail is stored on disk and is only computed if the thumbnail
245 * file does not exist OR if it is older than the image.
246 * Returns the URL.
248 * Keeps aspect ratio of original image. If both width and height are
249 * specified, the generated image will be no bigger than width x height,
250 * and will also have correct aspect ratio.
252 * @param integer $width maximum width of the generated thumbnail
253 * @param integer $height maximum height of the image (optional)
254 * @access public
256 function createThumb( $width, $height=-1 ) {
257 if ( $height == -1 ) {
258 return $this->renderThumb( $width );
260 if ( $width < $this->width ) {
261 $thumbheight = $this->height * $width / $this->width;
262 $thumbwidth = $width;
263 } else {
264 $thumbheight = $this->height;
265 $thumbwidth = $this->width;
267 if ( $thumbheight > $height ) {
268 $thumbwidth = $thumbwidth * $height / $thumbheight;
269 $thumbheight = $height;
271 return $this->renderThumb( $thumbwidth );
275 * Create a thumbnail of the image having the specified width.
276 * The thumbnail will not be created if the width is larger than the
277 * image's width. Let the browser do the scaling in this case.
278 * The thumbnail is stored on disk and is only computed if the thumbnail
279 * file does not exist OR if it is older than the image.
280 * Returns the URL.
282 * @access private
284 function /* private */ renderThumb( $width ) {
285 global $wgUploadDirectory;
286 global $wgImageMagickConvertCommand;
287 global $wgUseImageMagick;
288 global $wgUseSquid, $wgInternalServer;
290 $width = IntVal( $width );
292 $thumbName = $this->thumbName( $width );
293 $thumbPath = wfImageThumbDir( $thumbName ).'/'.$thumbName;
294 $thumbUrl = $this->thumbUrl( $width );
296 if ( ! $this->exists() )
298 # If there is no image, there will be no thumbnail
299 return '';
302 # Sanity check $width
303 if( $width <= 0 ) {
304 # BZZZT
305 return '';
308 if( $width > $this->width ) {
309 # Don't make an image bigger than the source
310 return $this->getURL();
313 if ( (! file_exists( $thumbPath ) ) || ( filemtime($thumbPath) < filemtime($this->imagePath) ) ) {
314 if ( $wgUseImageMagick ) {
315 # use ImageMagick
316 # Specify white background color, will be used for transparent images
317 # in Internet Explorer/Windows instead of default black.
318 $cmd = $wgImageMagickConvertCommand .
319 " -quality 85 -background white -geometry {$width} ".
320 escapeshellarg($this->imagePath) . " " .
321 escapeshellarg($thumbPath);
322 $conv = shell_exec( $cmd );
323 } else {
324 # Use PHP's builtin GD library functions.
326 # First find out what kind of file this is, and select the correct
327 # input routine for this.
329 $truecolor = false;
331 switch( $this->type ) {
332 case 1: # GIF
333 $src_image = imagecreatefromgif( $this->imagePath );
334 break;
335 case 2: # JPG
336 $src_image = imagecreatefromjpeg( $this->imagePath );
337 $truecolor = true;
338 break;
339 case 3: # PNG
340 $src_image = imagecreatefrompng( $this->imagePath );
341 $truecolor = ( $this->bits > 8 );
342 break;
343 case 15: # WBMP for WML
344 $src_image = imagecreatefromwbmp( $this->imagePath );
345 break;
346 case 16: # XBM
347 $src_image = imagecreatefromxbm( $this->imagePath );
348 break;
349 default:
350 return 'Image type not supported';
351 break;
353 $height = floor( $this->height * ( $width/$this->width ) );
354 if ( $truecolor ) {
355 $dst_image = imagecreatetruecolor( $width, $height );
356 } else {
357 $dst_image = imagecreate( $width, $height );
359 imagecopyresampled( $dst_image, $src_image,
360 0,0,0,0,
361 $width, $height, $this->width, $this->height );
362 switch( $this->type ) {
363 case 1: # GIF
364 case 3: # PNG
365 case 15: # WBMP
366 case 16: # XBM
367 #$thumbUrl .= ".png";
368 #$thumbPath .= ".png";
369 imagepng( $dst_image, $thumbPath );
370 break;
371 case 2: # JPEG
372 #$thumbUrl .= ".jpg";
373 #$thumbPath .= ".jpg";
374 imageinterlace( $dst_image );
375 imagejpeg( $dst_image, $thumbPath, 95 );
376 break;
377 default:
378 break;
380 imagedestroy( $dst_image );
381 imagedestroy( $src_image );
386 # Check for zero-sized thumbnails. Those can be generated when
387 # no disk space is available or some other error occurs
389 $thumbstat = stat( $thumbPath );
390 if( $thumbstat['size'] == 0 )
392 unlink( $thumbPath );
395 # Purge squid
396 # This has to be done after the image is updated and present for all machines on NFS,
397 # or else the old version might be stored into the squid again
398 if ( $wgUseSquid ) {
399 $urlArr = Array(
400 $wgInternalServer.$thumbUrl
402 wfPurgeSquidServers($urlArr);
405 return $thumbUrl;
406 } // END OF function createThumb
409 * Return the image history of this image, line by line.
410 * starts with current version, then old versions.
411 * uses $this->historyLine to check which line to return:
412 * 0 return line for current version
413 * 1 query for old versions, return first one
414 * 2, ... return next old version from above query
416 * @access public
418 function nextHistoryLine()
420 $fname = 'Image::nextHistoryLine()';
421 $dbr =& wfGetDB( DB_SLAVE );
422 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
423 $this->historyRes = $dbr->select( 'image',
424 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
425 array( 'img_name' => $this->title->getDBkey() ),
426 $fname
428 if ( 0 == wfNumRows( $this->historyRes ) ) {
429 return FALSE;
431 } else if ( $this->historyLine == 1 ) {
432 $this->historyRes = $dbr->select( 'oldimage',
433 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
434 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
435 ), array( 'oi_name' => $this->title->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
438 $this->historyLine ++;
440 return $dbr->fetchObject( $this->historyRes );
444 * Reset the history pointer to the first element of the history
445 * @access public
447 function resetHistory()
449 $this->historyLine = 0;
453 } //class
457 * Returns the image directory of an image
458 * If the directory does not exist, it is created.
459 * The result is an absolute path.
461 * @param string $fname file name of the image file
462 * @access public
464 function wfImageDir( $fname )
466 global $wgUploadDirectory, $wgHashedUploadDirectory;
468 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
470 $hash = md5( $fname );
471 $oldumask = umask(0);
472 $dest = $wgUploadDirectory . '/' . $hash{0};
473 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
474 $dest .= '/' . substr( $hash, 0, 2 );
475 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
477 umask( $oldumask );
478 return $dest;
482 * Returns the image directory of an image's thubnail
483 * If the directory does not exist, it is created.
484 * The result is an absolute path.
486 * @param string $fname file name of the thumbnail file, including file size prefix
487 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
488 * @access public
490 function wfImageThumbDir( $fname , $subdir='thumb')
492 return wfImageArchiveDir( $fname, $subdir );
496 * Returns the image directory of an image's old version
497 * If the directory does not exist, it is created.
498 * The result is an absolute path.
500 * @param string $fname file name of the thumbnail file, including file size prefix
501 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
502 * @access public
504 function wfImageArchiveDir( $fname , $subdir='archive')
506 global $wgUploadDirectory, $wgHashedUploadDirectory;
508 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory.'/'.$subdir; }
510 $hash = md5( $fname );
511 $oldumask = umask(0);
513 # Suppress warning messages here; if the file itself can't
514 # be written we'll worry about it then.
515 $archive = $wgUploadDirectory.'/'.$subdir;
516 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
517 $archive .= '/' . $hash{0};
518 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
519 $archive .= '/' . substr( $hash, 0, 2 );
520 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
522 umask( $oldumask );
523 return $archive;
527 * Record an image upload in the upload log.
529 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
531 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
532 global $wgUseCopyrightUpload;
534 $fname = 'wfRecordUpload';
535 $dbw =& wfGetDB( DB_MASTER );
537 # img_name must be unique
538 if ( !$dbw->indexUnique( 'image', 'img_name' ) ) {
539 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
543 $now = wfTimestampNow();
544 $won = wfInvertTimestamp( $now );
545 $size = IntVal( $size );
547 if ( $wgUseCopyrightUpload )
549 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
550 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
551 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
553 else $textdesc = $desc ;
555 $now = wfTimestampNow();
556 $won = wfInvertTimestamp( $now );
558 # Test to see if the row exists using INSERT IGNORE
559 # This avoids race conditions by locking the row until the commit, and also
560 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
561 $dbw->insertArray( 'image',
562 array(
563 'img_name' => $name,
564 'img_size'=> $size,
565 'img_timestamp' => $dbw->timestamp($now),
566 'img_description' => $desc,
567 'img_user' => $wgUser->getID(),
568 'img_user_text' => $wgUser->getName(),
569 ), $fname, 'IGNORE'
571 $descTitle = Title::makeTitleSafe( NS_IMAGE, $name );
573 if ( $dbw->affectedRows() ) {
574 # Successfully inserted, this is a new image
575 $id = $descTitle->getArticleID();
577 if ( $id == 0 ) {
578 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
579 $dbw->insertArray( 'cur',
580 array(
581 'cur_id' => $seqVal,
582 'cur_namespace' => NS_IMAGE,
583 'cur_title' => $name,
584 'cur_comment' => $desc,
585 'cur_user' => $wgUser->getID(),
586 'cur_user_text' => $wgUser->getName(),
587 'cur_timestamp' => $dbw->timestamp($now),
588 'cur_is_new' => 1,
589 'cur_text' => $textdesc,
590 'inverse_timestamp' => $won,
591 'cur_touched' => $dbw->timestamp($now)
592 ), $fname
594 $id = $dbw->insertId() or 0; # We should throw an error instead
596 RecentChange::notifyNew( $now, $descTitle, 0, $wgUser, $desc );
598 $u = new SearchUpdate( $id, $name, $desc );
599 $u->doUpdate();
601 } else {
602 # Collision, this is an update of an image
603 # Get current image row for update
604 $s = $dbw->getArray( 'image', array( 'img_name','img_size','img_timestamp','img_description',
605 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
607 # Insert it into oldimage
608 $dbw->insertArray( 'oldimage',
609 array(
610 'oi_name' => $s->img_name,
611 'oi_archive_name' => $oldver,
612 'oi_size' => $s->img_size,
613 'oi_timestamp' => $dbw->timestamp($s->img_timestamp),
614 'oi_description' => $s->img_description,
615 'oi_user' => $s->img_user,
616 'oi_user_text' => $s->img_user_text
617 ), $fname
620 # Update the current image row
621 $dbw->updateArray( 'image',
622 array( /* SET */
623 'img_size' => $size,
624 'img_timestamp' => $dbw->timestamp(),
625 'img_user' => $wgUser->getID(),
626 'img_user_text' => $wgUser->getName(),
627 'img_description' => $desc,
628 ), array( /* WHERE */
629 'img_name' => $name
630 ), $fname
633 # Invalidate the cache for the description page
634 $descTitle->invalidateCache();
637 $log = new LogPage( 'upload' );
638 $log->addEntry( 'upload', $descTitle, $desc );
642 * Returns the image URL of an image's old version
644 * @param string $fname file name of the image file
645 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
646 * @access public
648 function wfImageArchiveUrl( $name, $subdir='archive' )
650 global $wgUploadPath, $wgHashedUploadDirectory;
652 if ($wgHashedUploadDirectory) {
653 $hash = md5( substr( $name, 15) );
654 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
655 substr( $hash, 0, 2 ) . '/'.$name;
656 } else {
657 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
659 return wfUrlencode($url);