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