allow turning off image path hashing. there was a feature request for that somewhere.
[mediawiki.git] / includes / Image.php
blob036c1e76dae4c823fc49791d6a2d5482fe0eff27
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 /* private */
17 var $name, # name of the image
18 $imagePath, # Path of the image
19 $url, # Image URL
20 $title, # Title object for this image. Initialized when needed.
21 $fileExists, # does the image file exist on disk?
22 $historyLine, # Number of line to return by nextHistoryLine()
23 $historyRes, # result of the query for the image's history
24 $width, # \
25 $height, # |
26 $bits, # --- returned by getimagesize, see http://de3.php.net/manual/en/function.getimagesize.php
27 $type, # |
28 $attr; # /
32 function Image( $name )
34 global $wgUploadDirectory,$wgHashedUploadDirectory;
36 $this->name = $name;
37 $this->title = Title::makeTitleSafe( NS_IMAGE, $this->name );
38 //$this->imagePath = wfImagePath( $name );
39 if ($wgHashedUploadDirectory) {
40 $hash = md5( $this->title->getDBkey() );
41 $this->imagePath = $wgUploadDirectory . '/' . $hash{0} . '/' .
42 substr( $hash, 0, 2 ) . "/{$name}";
43 } else {
44 $this->imagePath = $wgUploadDirectory . '/' . $name;
47 $this->url = $this->wfImageUrl( $name );
49 if ( $this->fileExists = file_exists( $this->imagePath ) ) // Sic!, "=" is intended
51 @$gis = getimagesize( $this->imagePath );
52 if( $gis !== false ) {
53 $this->width = $gis[0];
54 $this->height = $gis[1];
55 $this->type = $gis[2];
56 $this->attr = $gis[3];
57 if ( isset( $gis['bits'] ) ) {
58 $this->bits = $gis['bits'];
59 } else {
60 $this->bits = 0;
64 $this->historyLine = 0;
67 function newFromTitle( $nt )
69 $img = new Image( $nt->getDBKey() );
70 $img->title = $nt;
71 return $img;
74 function getName()
76 return $this->name;
79 function getTitle()
81 return $this->title;
84 function getURL()
86 return $this->url;
89 function getImagePath()
91 return $this->imagePath;
94 function getWidth()
96 return $this->width;
99 function getHeight()
101 return $this->height;
104 function getSize()
106 $st = stat( $this->getImagePath() );
107 return $st['size'];
110 function getType()
112 return $this->type;
115 function getEscapeLocalURL()
117 return $this->title->escapeLocalURL();
120 function wfImageUrl( $name )
122 global $wgUploadPath,$wgUploadBaseUrl,$wgHashedUploadDirectory;
123 if ($wgHashedUploadDirectory) {
124 $hash = md5( $name );
125 $url = "{$wgUploadBaseUrl}{$wgUploadPath}/" . $hash{0} . "/" .
126 substr( $hash, 0, 2 ) . "/{$name}";
127 } else {
128 $url = "{$wgUploadBaseUrl}{$wgUploadPath}/{$name}";
130 return wfUrlencode( $url );
133 function exists()
135 return $this->fileExists;
138 function thumbUrl( $width, $subdir='thumb' ) {
139 global $wgUploadPath,$wgHashedUploadDirectory;
140 $name = $this->thumbName( $width );
141 if ($wgHashedUploadDirectory) {
142 $hash = md5( $name );
143 $url = "{$wgUploadPath}/{$subdir}/" . $hash{0} . "/" .
144 substr( $hash, 0, 2 ) . "/{$name}";
145 } else {
146 $url = "{$wgUploadPath}/{$subdir}/{$name}";
149 return wfUrlencode($url);
152 function thumbName( $width ) {
153 return $width."px-".$this->name;
156 function createThumb( $width, $height=-1 ) {
157 if ( $height == -1 ) {
158 return $this->renderThumb( $width );
160 if ( $width < $this->width ) {
161 $thumbheight = $this->height * $width / $this->width;
162 $thumbwidth = $width;
163 } else {
164 $thumbheight = $this->height;
165 $thumbwidth = $this->width;
167 if ( $thumbheight > $height ) {
168 $thumbwidth = $thumbwidth * $height / $thumbheight;
169 $thumbheight = $height;
171 return $this->renderThumb( $thumbwidth );
175 * Create a thumbnail of the image having the specified width.
176 * The thumbnail will not be created if the width is larger than the
177 * image's width. Let the browser do the scaling in this case.
178 * The thumbnail is stored on disk and is only computed if the thumbnail
179 * file does not exist OR if it is older than the image.
180 * Returns the URL.
182 function /* private */ renderThumb( $width ) {
183 global $wgUploadDirectory;
184 global $wgImageMagickConvertCommand;
185 global $wgUseImageMagick;
186 global $wgUseSquid, $wgInternalServer;
188 $width = IntVal( $width );
190 $thumbName = $this->thumbName( $width );
191 $thumbPath = wfImageThumbDir( $thumbName ).'/'.$thumbName;
192 $thumbUrl = $this->thumbUrl( $width );
194 if ( ! $this->exists() )
196 # If there is no image, there will be no thumbnail
197 return '';
200 # Sanity check $width
201 if( $width <= 0 ) {
202 # BZZZT
203 return '';
206 if( $width > $this->width ) {
207 # Don't make an image bigger than the source
208 return $this->getURL();
211 if ( (! file_exists( $thumbPath ) ) || ( filemtime($thumbPath) < filemtime($this->imagePath) ) ) {
212 if ( $wgUseImageMagick ) {
213 # use ImageMagick
214 # Specify white background color, will be used for transparent images
215 # in Internet Explorer/Windows instead of default black.
216 $cmd = $wgImageMagickConvertCommand .
217 " -quality 85 -background white -geometry {$width} ".
218 escapeshellarg($this->imagePath) . " " .
219 escapeshellarg($thumbPath);
220 $conv = shell_exec( $cmd );
221 } else {
222 # Use PHP's builtin GD library functions.
224 # First find out what kind of file this is, and select the correct
225 # input routine for this.
227 $truecolor = false;
229 switch( $this->type ) {
230 case 1: # GIF
231 $src_image = imagecreatefromgif( $this->imagePath );
232 break;
233 case 2: # JPG
234 $src_image = imagecreatefromjpeg( $this->imagePath );
235 $truecolor = true;
236 break;
237 case 3: # PNG
238 $src_image = imagecreatefrompng( $this->imagePath );
239 $truecolor = ( $this->bits > 8 );
240 break;
241 case 15: # WBMP for WML
242 $src_image = imagecreatefromwbmp( $this->imagePath );
243 break;
244 case 16: # XBM
245 $src_image = imagecreatefromxbm( $this->imagePath );
246 break;
247 default:
248 return 'Image type not supported';
249 break;
251 $height = floor( $this->height * ( $width/$this->width ) );
252 if ( $truecolor ) {
253 $dst_image = imagecreatetruecolor( $width, $height );
254 } else {
255 $dst_image = imagecreate( $width, $height );
257 imagecopyresampled( $dst_image, $src_image,
258 0,0,0,0,
259 $width, $height, $this->width, $this->height );
260 switch( $this->type ) {
261 case 1: # GIF
262 case 3: # PNG
263 case 15: # WBMP
264 case 16: # XBM
265 #$thumbUrl .= ".png";
266 #$thumbPath .= ".png";
267 imagepng( $dst_image, $thumbPath );
268 break;
269 case 2: # JPEG
270 #$thumbUrl .= ".jpg";
271 #$thumbPath .= ".jpg";
272 imageinterlace( $dst_image );
273 imagejpeg( $dst_image, $thumbPath, 95 );
274 break;
275 default:
276 break;
278 imagedestroy( $dst_image );
279 imagedestroy( $src_image );
284 # Check for zero-sized thumbnails. Those can be generated when
285 # no disk space is available or some other error occurs
287 $thumbstat = stat( $thumbPath );
288 if( $thumbstat['size'] == 0 )
290 unlink( $thumbPath );
293 # Purge squid
294 # This has to be done after the image is updated and present for all machines on NFS,
295 # or else the old version might be stored into the squid again
296 if ( $wgUseSquid ) {
297 $urlArr = Array(
298 $wgInternalServer.$thumbUrl
300 wfPurgeSquidServers($urlArr);
303 return $thumbUrl;
304 } // END OF function createThumb
307 * Return the image history of this image, line by line.
308 * starts with current version, then old versions.
309 * uses $this->historyLine to check which line to return:
310 * 0 return line for current version
311 * 1 query for old versions, return first one
312 * 2, ... return next old version from above query
314 function nextHistoryLine()
316 $fname = 'Image::nextHistoryLine()';
317 $dbr =& wfGetDB( DB_SLAVE );
318 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
319 $this->historyRes = $dbr->select( 'image',
320 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
321 array( 'img_name' => $this->title->getDBkey() ),
322 $fname
324 if ( 0 == wfNumRows( $this->historyRes ) ) {
325 return FALSE;
327 } else if ( $this->historyLine == 1 ) {
328 $this->historyRes = $dbr->select( 'oldimage',
329 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
330 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
331 ), array( 'oi_name' => $this->title->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
334 $this->historyLine ++;
336 return $dbr->fetchObject( $this->historyRes );
339 function resetHistory()
341 $this->historyLine = 0;
345 } //class
348 function wfImageDir( $fname )
350 global $wgUploadDirectory, $wgHashedUploadDirectory;
352 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
354 $hash = md5( $fname );
355 $oldumask = umask(0);
356 $dest = $wgUploadDirectory . '/' . $hash{0};
357 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
358 $dest .= '/' . substr( $hash, 0, 2 );
359 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
361 umask( $oldumask );
362 return $dest;
365 function wfImageThumbDir( $fname , $subdir='thumb')
367 return wfImageArchiveDir( $fname, $subdir );
370 function wfImageArchiveDir( $fname , $subdir='archive')
372 global $wgUploadDirectory, $wgHashedUploadDirectory;
374 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory.'/'.$subdir; }
376 $hash = md5( $fname );
377 $oldumask = umask(0);
379 # Suppress warning messages here; if the file itself can't
380 # be written we'll worry about it then.
381 $archive = $wgUploadDirectory.'/'.$subdir;
382 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
383 $archive .= '/' . $hash{0};
384 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
385 $archive .= '/' . substr( $hash, 0, 2 );
386 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
388 umask( $oldumask );
389 return $archive;
392 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
394 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
395 global $wgUseCopyrightUpload;
397 $fname = 'wfRecordUpload';
398 $dbw =& wfGetDB( DB_MASTER );
400 # img_name must be unique
401 if ( !$dbw->indexUnique( 'image', 'img_name' ) ) {
402 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
406 $now = wfTimestampNow();
407 $won = wfInvertTimestamp( $now );
408 $size = IntVal( $size );
410 if ( $wgUseCopyrightUpload )
412 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
413 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
414 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
416 else $textdesc = $desc ;
418 $now = wfTimestampNow();
419 $won = wfInvertTimestamp( $now );
421 # Test to see if the row exists using INSERT IGNORE
422 # This avoids race conditions by locking the row until the commit, and also
423 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
424 $dbw->insertArray( 'image',
425 array(
426 'img_name' => $name,
427 'img_size'=> $size,
428 'img_timestamp' => $dbw->timestamp($now),
429 'img_description' => $desc,
430 'img_user' => $wgUser->getID(),
431 'img_user_text' => $wgUser->getName(),
432 ), $fname, 'IGNORE'
434 $descTitle = Title::makeTitleSafe( NS_IMAGE, $name );
436 if ( $dbw->affectedRows() ) {
437 # Successfully inserted, this is a new image
438 $id = $descTitle->getArticleID();
440 if ( $id == 0 ) {
441 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
442 $dbw->insertArray( 'cur',
443 array(
444 'cur_id' => $seqVal,
445 'cur_namespace' => NS_IMAGE,
446 'cur_title' => $name,
447 'cur_comment' => $desc,
448 'cur_user' => $wgUser->getID(),
449 'cur_user_text' => $wgUser->getName(),
450 'cur_timestamp' => $dbw->timestamp($now),
451 'cur_is_new' => 1,
452 'cur_text' => $textdesc,
453 'inverse_timestamp' => $won,
454 'cur_touched' => $dbw->timestamp($now)
455 ), $fname
457 $id = $dbw->insertId() or 0; # We should throw an error instead
459 RecentChange::notifyNew( $now, $descTitle, 0, $wgUser, $desc );
461 $u = new SearchUpdate( $id, $name, $desc );
462 $u->doUpdate();
464 } else {
465 # Collision, this is an update of an image
466 # Get current image row for update
467 $s = $dbw->getArray( 'image', array( 'img_name','img_size','img_timestamp','img_description',
468 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
470 # Insert it into oldimage
471 $dbw->insertArray( 'oldimage',
472 array(
473 'oi_name' => $s->img_name,
474 'oi_archive_name' => $oldver,
475 'oi_size' => $s->img_size,
476 'oi_timestamp' => $dbw->timestamp($s->img_timestamp),
477 'oi_description' => $s->img_description,
478 'oi_user' => $s->img_user,
479 'oi_user_text' => $s->img_user_text
480 ), $fname
483 # Update the current image row
484 $dbw->updateArray( 'image',
485 array( /* SET */
486 'img_size' => $size,
487 'img_timestamp' => $dbw->timestamp(),
488 'img_user' => $wgUser->getID(),
489 'img_user_text' => $wgUser->getName(),
490 'img_description' => $desc,
491 ), array( /* WHERE */
492 'img_name' => $name
493 ), $fname
496 # Invalidate the cache for the description page
497 $descTitle->invalidateCache();
500 $log = new LogPage( 'upload' );
501 $log->addEntry( 'upload', $descTitle, $desc );
504 function wfImageArchiveUrl( $name, $subdir='archive' )
506 global $wgUploadPath, $wgHashedUploadDirectory;
508 if ($wgHashedUploadDirectory) {
509 $hash = md5( substr( $name, 15) );
510 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
511 substr( $hash, 0, 2 ) . '/'.$name;
512 } else {
513 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
515 return wfUrlencode($url);