BUG#76 For categories, don't use the Category:-prefix for the sortkey.
[lhc/web/wiklou.git] / includes / Image.php
1 <?php
2 /**
3 * @package MediaWiki
4 */
5
6 /**
7 * Class to represent an image
8 *
9 * Provides methods to retrieve paths (physical, logical, URL),
10 * to generate thumbnails or for uploading.
11 * @package MediaWiki
12 */
13 class Image
14 {
15 /* private */
16 var $name, # name of the image
17 $imagePath, # Path of the image
18 $url, # Image URL
19 $title, # Title object for this image. Initialized when needed.
20 $fileExists, # does the image file exist on disk?
21 $historyLine, # Number of line to return by nextHistoryLine()
22 $historyRes, # result of the query for the image's history
23 $width, # \
24 $height, # |
25 $bits, # --- returned by getimagesize, see http://de3.php.net/manual/en/function.getimagesize.php
26 $type, # |
27 $attr; # /
28
29
30
31 function Image( $name )
32 {
33 global $wgUploadDirectory;
34
35 $this->name = $name;
36 $this->title = Title::makeTitleSafe( NS_IMAGE, $this->name );
37 //$this->imagePath = wfImagePath( $name );
38 $hash = md5( $this->title->getDBkey() );
39 $this->imagePath = $wgUploadDirectory . '/' . $hash{0} . '/' .substr( $hash, 0, 2 ) . "/{$name}";
40
41 $this->url = $this->wfImageUrl( $name );
42
43 if ( $this->fileExists = file_exists( $this->imagePath ) ) // Sic!, "=" is intended
44 {
45 @$gis = getimagesize( $this->imagePath );
46 if( $gis !== false ) {
47 $this->width = $gis[0];
48 $this->height = $gis[1];
49 $this->type = $gis[2];
50 $this->attr = $gis[3];
51 if ( isset( $gis['bits'] ) ) {
52 $this->bits = $gis['bits'];
53 } else {
54 $this->bits = 0;
55 }
56 }
57 }
58 $this->historyLine = 0;
59 }
60
61 function newFromTitle( $nt )
62 {
63 $img = new Image( $nt->getDBKey() );
64 $img->title = $nt;
65 return $img;
66 }
67
68 function getName()
69 {
70 return $this->name;
71 }
72
73 function getURL()
74 {
75 return $this->url;
76 }
77
78 function getImagePath()
79 {
80 return $this->imagePath;
81 }
82
83 function getWidth()
84 {
85 return $this->width;
86 }
87
88 function getHeight()
89 {
90 return $this->height;
91 }
92
93 function getType()
94 {
95 return $this->type;
96 }
97
98 function getEscapeLocalURL()
99 {
100 return $this->title->escapeLocalURL();
101 }
102
103 function wfImageUrl( $name )
104 {
105 global $wgUploadPath;
106 $hash = md5( $name );
107
108 $url = "{$wgUploadPath}/" . $hash{0} . "/" .
109 substr( $hash, 0, 2 ) . "/{$name}";
110 return wfUrlencode( $url );
111 }
112
113
114 function exists()
115 {
116 return $this->fileExists;
117 }
118
119 function thumbUrl( $width, $subdir='thumb' ) {
120 global $wgUploadPath;
121
122 $name = $this->thumbName( $width );
123 $hash = md5( $name );
124 $url = "{$wgUploadPath}/{$subdir}/" . $hash{0} . "/" . substr( $hash, 0, 2 ) . "/{$name}";
125
126 return wfUrlencode($url);
127 }
128
129 function thumbName( $width ) {
130 return $width."px-".$this->name;
131 }
132
133 /**
134 * Create a thumbnail of the image having the specified width.
135 * The thumbnail will not be created if the width is larger than the
136 * image's width. Let the browser do the scaling in this case.
137 * The thumbnail is stored on disk and is only computed if the thumbnail
138 * file does not exist OR if it is older than the image.
139 * Returns the URL.
140 */
141 function createThumb( $width ) {
142 global $wgUploadDirectory;
143 global $wgImageMagickConvertCommand;
144 global $wgUseImageMagick;
145 global $wgUseSquid, $wgInternalServer;
146
147 $width = IntVal( $width );
148
149 $thumbName = $this->thumbName( $width );
150 $thumbPath = wfImageThumbDir( $thumbName ).'/'.$thumbName;
151 $thumbUrl = $this->thumbUrl( $width );
152
153 if ( ! $this->exists() )
154 {
155 # If there is no image, there will be no thumbnail
156 return '';
157 }
158
159 # Sanity check $width
160 if( $width <= 0 ) {
161 # BZZZT
162 return '';
163 }
164
165 if( $width > $this->width ) {
166 # Don't make an image bigger than the source
167 return $this->getURL();
168 }
169
170 if ( (! file_exists( $thumbPath ) ) || ( filemtime($thumbPath) < filemtime($this->imagePath) ) ) {
171 if ( $wgUseImageMagick ) {
172 # use ImageMagick
173 # Specify white background color, will be used for transparent images
174 # in Internet Explorer/Windows instead of default black.
175 $cmd = $wgImageMagickConvertCommand .
176 " -quality 85 -background white -geometry {$width} ".
177 escapeshellarg($this->imagePath) . " " .
178 escapeshellarg($thumbPath);
179 $conv = shell_exec( $cmd );
180 } else {
181 # Use PHP's builtin GD library functions.
182 #
183 # First find out what kind of file this is, and select the correct
184 # input routine for this.
185
186 $truecolor = false;
187
188 switch( $this->type ) {
189 case 1: # GIF
190 $src_image = imagecreatefromgif( $this->imagePath );
191 break;
192 case 2: # JPG
193 $src_image = imagecreatefromjpeg( $this->imagePath );
194 $truecolor = true;
195 break;
196 case 3: # PNG
197 $src_image = imagecreatefrompng( $this->imagePath );
198 $truecolor = ( $this->bits > 8 );
199 break;
200 case 15: # WBMP for WML
201 $src_image = imagecreatefromwbmp( $this->imagePath );
202 break;
203 case 16: # XBM
204 $src_image = imagecreatefromxbm( $this->imagePath );
205 break;
206 default:
207 return 'Image type not supported';
208 break;
209 }
210 $height = floor( $this->height * ( $width/$this->width ) );
211 if ( $truecolor ) {
212 $dst_image = imagecreatetruecolor( $width, $height );
213 } else {
214 $dst_image = imagecreate( $width, $height );
215 }
216 imagecopyresampled( $dst_image, $src_image,
217 0,0,0,0,
218 $width, $height, $this->width, $this->height );
219 switch( $this->type ) {
220 case 1: # GIF
221 case 3: # PNG
222 case 15: # WBMP
223 case 16: # XBM
224 #$thumbUrl .= ".png";
225 #$thumbPath .= ".png";
226 imagepng( $dst_image, $thumbPath );
227 break;
228 case 2: # JPEG
229 #$thumbUrl .= ".jpg";
230 #$thumbPath .= ".jpg";
231 imageinterlace( $dst_image );
232 imagejpeg( $dst_image, $thumbPath, 95 );
233 break;
234 default:
235 break;
236 }
237 imagedestroy( $dst_image );
238 imagedestroy( $src_image );
239
240
241 }
242 #
243 # Check for zero-sized thumbnails. Those can be generated when
244 # no disk space is available or some other error occurs
245 #
246 $thumbstat = stat( $thumbPath );
247 if( $thumbstat['size'] == 0 )
248 {
249 unlink( $thumbPath );
250 }
251
252 # Purge squid
253 # This has to be done after the image is updated and present for all machines on NFS,
254 # or else the old version might be stored into the squid again
255 if ( $wgUseSquid ) {
256 $urlArr = Array(
257 $wgInternalServer.$thumbUrl
258 );
259 wfPurgeSquidServers($urlArr);
260 }
261 }
262 return $thumbUrl;
263 } // END OF function createThumb
264
265 /**
266 * Return the image history of this image, line by line.
267 * starts with current version, then old versions.
268 * uses $this->historyLine to check which line to return:
269 * 0 return line for current version
270 * 1 query for old versions, return first one
271 * 2, ... return next old version from above query
272 */
273 function nextHistoryLine()
274 {
275 $fname = 'Image::nextHistoryLine()';
276 $dbr =& wfGetDB( DB_SLAVE );
277 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
278 $this->historyRes = $dbr->select( 'image',
279 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
280 array( 'img_name' => $this->title->getDBkey() ),
281 $fname
282 );
283 if ( 0 == wfNumRows( $this->historyRes ) ) {
284 return FALSE;
285 }
286 } else if ( $this->historyLine == 1 ) {
287 $this->historyRes = $dbr->select( 'oldimage',
288 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
289 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
290 ), array( 'oi_name' => $this->title->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
291 );
292 }
293 $this->historyLine ++;
294
295 return $dbr->fetchObject( $this->historyRes );
296 }
297
298 function resetHistory()
299 {
300 $this->historyLine = 0;
301 }
302
303
304 } //class
305
306
307 function wfImageDir( $fname )
308 {
309 global $wgUploadDirectory;
310
311 $hash = md5( $fname );
312 $oldumask = umask(0);
313 $dest = $wgUploadDirectory . '/' . $hash{0};
314 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
315 $dest .= '/' . substr( $hash, 0, 2 );
316 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
317
318 umask( $oldumask );
319 return $dest;
320 }
321
322 function wfImageThumbDir( $fname , $subdir='thumb')
323 {
324 return wfImageArchiveDir( $fname, $subdir );
325 }
326
327 function wfImageArchiveDir( $fname , $subdir='archive')
328 {
329 global $wgUploadDirectory;
330
331 $hash = md5( $fname );
332 $oldumask = umask(0);
333
334 # Suppress warning messages here; if the file itself can't
335 # be written we'll worry about it then.
336 $archive = $wgUploadDirectory.'/'.$subdir;
337 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
338 $archive .= '/' . $hash{0};
339 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
340 $archive .= '/' . substr( $hash, 0, 2 );
341 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
342
343 umask( $oldumask );
344 return $archive;
345 }
346
347 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
348 {
349 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
350 global $wgUseCopyrightUpload;
351
352 $fname = 'wfRecordUpload';
353 $dbw =& wfGetDB( DB_MASTER );
354
355 # img_name must be unique
356 if ( !$dbw->indexUnique( 'image', 'img_name' ) ) {
357 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
358 }
359
360
361 $now = wfTimestampNow();
362 $won = wfInvertTimestamp( $now );
363 $size = IntVal( $size );
364
365 if ( $wgUseCopyrightUpload )
366 {
367 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
368 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
369 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
370 }
371 else $textdesc = $desc ;
372
373 $now = wfTimestampNow();
374 $won = wfInvertTimestamp( $now );
375
376 # Test to see if the row exists using INSERT IGNORE
377 # This avoids race conditions by locking the row until the commit, and also
378 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
379 $dbw->insert( 'image',
380 array(
381 'img_name' => $name,
382 'img_size'=> $size,
383 'img_timestamp' => $now,
384 'img_description' => $desc,
385 'img_user' => $wgUser->getID(),
386 'img_user_text' => $wgUser->getName(),
387 ), $fname, 'IGNORE'
388 );
389 $descTitle = Title::makeTitleSafe( NS_IMAGE, $name );
390
391 if ( $dbw->affectedRows() ) {
392 # Successfully inserted, this is a new image
393 $id = $descTitle->getArticleID();
394
395 if ( $id == 0 ) {
396 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
397 $dbw->insertArray( 'cur',
398 array(
399 'cur_id' => $seqVal,
400 'cur_namespace' => NS_IMAGE,
401 'cur_title' => $name,
402 'cur_comment' => $desc,
403 'cur_user' => $wgUser->getID(),
404 'cur_user_text' => $wgUser->getName(),
405 'cur_timestamp' => $now,
406 'cur_is_new' => 1,
407 'cur_text' => $textdesc,
408 'inverse_timestamp' => $won,
409 'cur_touched' => $now
410 ), $fname
411 );
412 $id = $dbw->insertId() or 0; # We should throw an error instead
413
414 RecentChange::notifyNew( $now, $descTitle, 0, $wgUser, $desc );
415
416 $u = new SearchUpdate( $id, $name, $desc );
417 $u->doUpdate();
418 }
419 } else {
420 # Collision, this is an update of an image
421 # Get current image row for update
422 $s = $dbw->getArray( 'image', array( 'img_name','img_size','img_timestamp','img_description',
423 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
424
425 # Insert it into oldimage
426 $dbw->insertArray( 'oldimage',
427 array(
428 'oi_name' => $s->img_name,
429 'oi_archive_name' => $oldver,
430 'oi_size' => $s->img_size,
431 'oi_timestamp' => $s->img_timestamp,
432 'oi_description' => $s->img_description,
433 'oi_user' => $s->img_user,
434 'oi_user_text' => $s->img_user_text
435 ), $fname
436 );
437
438 # Update the current image row
439 $dbw->updateArray( 'image',
440 array( /* SET */
441 'img_size' => $size,
442 'img_timestamp' => wfTimestampNow(),
443 'img_user' => $wgUser->getID(),
444 'img_user_text' => $wgUser->getName(),
445 'img_description' => $desc,
446 ), array( /* WHERE */
447 'img_name' => $name
448 ), $fname
449 );
450
451 # Invalidate the cache for the description page
452 $descTitle->invalidateCache();
453 }
454
455 $log = new LogPage( 'upload' );
456 $log->addEntry( 'upload', $descTitle, $desc );
457 }
458
459 function wfImageArchiveUrl( $name )
460 {
461 global $wgUploadPath;
462
463 $hash = md5( substr( $name, 15) );
464 $url = $wgUploadPath.'/archive/' . $hash{0} . '/' .
465 substr( $hash, 0, 2 ) . '/'.$name;
466 return wfUrlencode($url);
467 }
468
469 ?>