Use <i> and <b> for '' and ''' instead of <em> and <strong>. There's no
[mediawiki.git] / includes / Image.php
blob018be4610f69a483398326fcb48c82299a25f300
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;
36 $this->name = $name;
37 $this->title = Title::makeTitleSafe( NS_IMAGE, $this->name );
38 //$this->imagePath = wfImagePath( $name );
39 $hash = md5( $this->title->getDBkey() );
40 $this->imagePath = $wgUploadDirectory . '/' . $hash{0} . '/' .substr( $hash, 0, 2 ) . "/{$name}";
42 $this->url = $this->wfImageUrl( $name );
44 if ( $this->fileExists = file_exists( $this->imagePath ) ) // Sic!, "=" is intended
46 @$gis = getimagesize( $this->imagePath );
47 if( $gis !== false ) {
48 $this->width = $gis[0];
49 $this->height = $gis[1];
50 $this->type = $gis[2];
51 $this->attr = $gis[3];
52 if ( isset( $gis['bits'] ) ) {
53 $this->bits = $gis['bits'];
54 } else {
55 $this->bits = 0;
59 $this->historyLine = 0;
62 function newFromTitle( $nt )
64 $img = new Image( $nt->getDBKey() );
65 $img->title = $nt;
66 return $img;
69 function getName()
71 return $this->name;
74 function getURL()
76 return $this->url;
79 function getImagePath()
81 return $this->imagePath;
84 function getWidth()
86 return $this->width;
89 function getHeight()
91 return $this->height;
94 function getSize()
96 $st = stat( $this->getImagePath() );
97 return $st['size'];
100 function getType()
102 return $this->type;
105 function getEscapeLocalURL()
107 return $this->title->escapeLocalURL();
110 function wfImageUrl( $name )
112 global $wgUploadPath;
113 $hash = md5( $name );
115 $url = "{$wgUploadPath}/" . $hash{0} . "/" .
116 substr( $hash, 0, 2 ) . "/{$name}";
117 return wfUrlencode( $url );
121 function exists()
123 return $this->fileExists;
126 function thumbUrl( $width, $subdir='thumb' ) {
127 global $wgUploadPath;
129 $name = $this->thumbName( $width );
130 $hash = md5( $name );
131 $url = "{$wgUploadPath}/{$subdir}/" . $hash{0} . "/" . substr( $hash, 0, 2 ) . "/{$name}";
133 return wfUrlencode($url);
136 function thumbName( $width ) {
137 return $width."px-".$this->name;
141 * Create a thumbnail of the image having the specified width.
142 * The thumbnail will not be created if the width is larger than the
143 * image's width. Let the browser do the scaling in this case.
144 * The thumbnail is stored on disk and is only computed if the thumbnail
145 * file does not exist OR if it is older than the image.
146 * Returns the URL.
148 function createThumb( $width ) {
149 global $wgUploadDirectory;
150 global $wgImageMagickConvertCommand;
151 global $wgUseImageMagick;
152 global $wgUseSquid, $wgInternalServer;
154 $width = IntVal( $width );
156 $thumbName = $this->thumbName( $width );
157 $thumbPath = wfImageThumbDir( $thumbName ).'/'.$thumbName;
158 $thumbUrl = $this->thumbUrl( $width );
160 if ( ! $this->exists() )
162 # If there is no image, there will be no thumbnail
163 return '';
166 # Sanity check $width
167 if( $width <= 0 ) {
168 # BZZZT
169 return '';
172 if( $width > $this->width ) {
173 # Don't make an image bigger than the source
174 return $this->getURL();
177 if ( (! file_exists( $thumbPath ) ) || ( filemtime($thumbPath) < filemtime($this->imagePath) ) ) {
178 if ( $wgUseImageMagick ) {
179 # use ImageMagick
180 # Specify white background color, will be used for transparent images
181 # in Internet Explorer/Windows instead of default black.
182 $cmd = $wgImageMagickConvertCommand .
183 " -quality 85 -background white -geometry {$width} ".
184 escapeshellarg($this->imagePath) . " " .
185 escapeshellarg($thumbPath);
186 $conv = shell_exec( $cmd );
187 } else {
188 # Use PHP's builtin GD library functions.
190 # First find out what kind of file this is, and select the correct
191 # input routine for this.
193 $truecolor = false;
195 switch( $this->type ) {
196 case 1: # GIF
197 $src_image = imagecreatefromgif( $this->imagePath );
198 break;
199 case 2: # JPG
200 $src_image = imagecreatefromjpeg( $this->imagePath );
201 $truecolor = true;
202 break;
203 case 3: # PNG
204 $src_image = imagecreatefrompng( $this->imagePath );
205 $truecolor = ( $this->bits > 8 );
206 break;
207 case 15: # WBMP for WML
208 $src_image = imagecreatefromwbmp( $this->imagePath );
209 break;
210 case 16: # XBM
211 $src_image = imagecreatefromxbm( $this->imagePath );
212 break;
213 default:
214 return 'Image type not supported';
215 break;
217 $height = floor( $this->height * ( $width/$this->width ) );
218 if ( $truecolor ) {
219 $dst_image = imagecreatetruecolor( $width, $height );
220 } else {
221 $dst_image = imagecreate( $width, $height );
223 imagecopyresampled( $dst_image, $src_image,
224 0,0,0,0,
225 $width, $height, $this->width, $this->height );
226 switch( $this->type ) {
227 case 1: # GIF
228 case 3: # PNG
229 case 15: # WBMP
230 case 16: # XBM
231 #$thumbUrl .= ".png";
232 #$thumbPath .= ".png";
233 imagepng( $dst_image, $thumbPath );
234 break;
235 case 2: # JPEG
236 #$thumbUrl .= ".jpg";
237 #$thumbPath .= ".jpg";
238 imageinterlace( $dst_image );
239 imagejpeg( $dst_image, $thumbPath, 95 );
240 break;
241 default:
242 break;
244 imagedestroy( $dst_image );
245 imagedestroy( $src_image );
250 # Check for zero-sized thumbnails. Those can be generated when
251 # no disk space is available or some other error occurs
253 $thumbstat = stat( $thumbPath );
254 if( $thumbstat['size'] == 0 )
256 unlink( $thumbPath );
259 # Purge squid
260 # This has to be done after the image is updated and present for all machines on NFS,
261 # or else the old version might be stored into the squid again
262 if ( $wgUseSquid ) {
263 $urlArr = Array(
264 $wgInternalServer.$thumbUrl
266 wfPurgeSquidServers($urlArr);
269 return $thumbUrl;
270 } // END OF function createThumb
273 * Return the image history of this image, line by line.
274 * starts with current version, then old versions.
275 * uses $this->historyLine to check which line to return:
276 * 0 return line for current version
277 * 1 query for old versions, return first one
278 * 2, ... return next old version from above query
280 function nextHistoryLine()
282 $fname = 'Image::nextHistoryLine()';
283 $dbr =& wfGetDB( DB_SLAVE );
284 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
285 $this->historyRes = $dbr->select( 'image',
286 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
287 array( 'img_name' => $this->title->getDBkey() ),
288 $fname
290 if ( 0 == wfNumRows( $this->historyRes ) ) {
291 return FALSE;
293 } else if ( $this->historyLine == 1 ) {
294 $this->historyRes = $dbr->select( 'oldimage',
295 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
296 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
297 ), array( 'oi_name' => $this->title->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
300 $this->historyLine ++;
302 return $dbr->fetchObject( $this->historyRes );
305 function resetHistory()
307 $this->historyLine = 0;
311 } //class
314 function wfImageDir( $fname )
316 global $wgUploadDirectory;
318 $hash = md5( $fname );
319 $oldumask = umask(0);
320 $dest = $wgUploadDirectory . '/' . $hash{0};
321 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
322 $dest .= '/' . substr( $hash, 0, 2 );
323 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
325 umask( $oldumask );
326 return $dest;
329 function wfImageThumbDir( $fname , $subdir='thumb')
331 return wfImageArchiveDir( $fname, $subdir );
334 function wfImageArchiveDir( $fname , $subdir='archive')
336 global $wgUploadDirectory;
338 $hash = md5( $fname );
339 $oldumask = umask(0);
341 # Suppress warning messages here; if the file itself can't
342 # be written we'll worry about it then.
343 $archive = $wgUploadDirectory.'/'.$subdir;
344 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
345 $archive .= '/' . $hash{0};
346 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
347 $archive .= '/' . substr( $hash, 0, 2 );
348 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
350 umask( $oldumask );
351 return $archive;
354 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
356 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
357 global $wgUseCopyrightUpload;
359 $fname = 'wfRecordUpload';
360 $dbw =& wfGetDB( DB_MASTER );
362 # img_name must be unique
363 if ( !$dbw->indexUnique( 'image', 'img_name' ) ) {
364 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
368 $now = wfTimestampNow();
369 $won = wfInvertTimestamp( $now );
370 $size = IntVal( $size );
372 if ( $wgUseCopyrightUpload )
374 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
375 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
376 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
378 else $textdesc = $desc ;
380 $now = wfTimestampNow();
381 $won = wfInvertTimestamp( $now );
383 # Test to see if the row exists using INSERT IGNORE
384 # This avoids race conditions by locking the row until the commit, and also
385 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
386 $dbw->insertArray( 'image',
387 array(
388 'img_name' => $name,
389 'img_size'=> $size,
390 'img_timestamp' => $dbw->timestamp($now),
391 'img_description' => $desc,
392 'img_user' => $wgUser->getID(),
393 'img_user_text' => $wgUser->getName(),
394 ), $fname, 'IGNORE'
396 $descTitle = Title::makeTitleSafe( NS_IMAGE, $name );
398 if ( $dbw->affectedRows() ) {
399 # Successfully inserted, this is a new image
400 $id = $descTitle->getArticleID();
402 if ( $id == 0 ) {
403 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
404 $dbw->insertArray( 'cur',
405 array(
406 'cur_id' => $seqVal,
407 'cur_namespace' => NS_IMAGE,
408 'cur_title' => $name,
409 'cur_comment' => $desc,
410 'cur_user' => $wgUser->getID(),
411 'cur_user_text' => $wgUser->getName(),
412 'cur_timestamp' => $dbw->timestamp($now),
413 'cur_is_new' => 1,
414 'cur_text' => $textdesc,
415 'inverse_timestamp' => $won,
416 'cur_touched' => $dbw->timestamp($now)
417 ), $fname
419 $id = $dbw->insertId() or 0; # We should throw an error instead
421 RecentChange::notifyNew( $now, $descTitle, 0, $wgUser, $desc );
423 $u = new SearchUpdate( $id, $name, $desc );
424 $u->doUpdate();
426 } else {
427 # Collision, this is an update of an image
428 # Get current image row for update
429 $s = $dbw->getArray( 'image', array( 'img_name','img_size','img_timestamp','img_description',
430 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
432 # Insert it into oldimage
433 $dbw->insertArray( 'oldimage',
434 array(
435 'oi_name' => $s->img_name,
436 'oi_archive_name' => $oldver,
437 'oi_size' => $s->img_size,
438 'oi_timestamp' => $dbw->timestamp($s->img_timestamp),
439 'oi_description' => $s->img_description,
440 'oi_user' => $s->img_user,
441 'oi_user_text' => $s->img_user_text
442 ), $fname
445 # Update the current image row
446 $dbw->updateArray( 'image',
447 array( /* SET */
448 'img_size' => $size,
449 'img_timestamp' => $dbw->timestamp(),
450 'img_user' => $wgUser->getID(),
451 'img_user_text' => $wgUser->getName(),
452 'img_description' => $desc,
453 ), array( /* WHERE */
454 'img_name' => $name
455 ), $fname
458 # Invalidate the cache for the description page
459 $descTitle->invalidateCache();
462 $log = new LogPage( 'upload' );
463 $log->addEntry( 'upload', $descTitle, $desc );
466 function wfImageArchiveUrl( $name )
468 global $wgUploadPath;
470 $hash = md5( substr( $name, 15) );
471 $url = $wgUploadPath.'/archive/' . $hash{0} . '/' .
472 substr( $hash, 0, 2 ) . '/'.$name;
473 return wfUrlencode($url);