Documentation
[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 /**#@+
17 * @access private
18 */
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; # /
31
32 /**#@-*/
33
34
35 /**
36 * Create an Image object from an image name
37 *
38 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
39 * @access public
40 */
41 function Image( $name )
42 {
43 global $wgUploadDirectory,$wgHashedUploadDirectory;
44
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;
54 }
55
56 $this->url = $this->wfImageUrl( $name );
57
58 if ( $this->fileExists = file_exists( $this->imagePath ) ) // Sic!, "=" is intended
59 {
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;
70 }
71 }
72 }
73 $this->historyLine = 0;
74 }
75
76 /**
77 * Factory function
78 *
79 * Create a new image object from a title object.
80 *
81 * @param Title $nt Title object. Must be from namespace "image"
82 * @access public
83 */
84 function newFromTitle( $nt )
85 {
86 $img = new Image( $nt->getDBKey() );
87 $img->title = $nt;
88 return $img;
89 }
90
91 /**
92 * Return the name of this image
93 * @access public
94 */
95 function getName()
96 {
97 return $this->name;
98 }
99
100 /**
101 * Return the associated title object
102 * @access public
103 */
104 function getTitle()
105 {
106 return $this->title;
107 }
108
109 /**
110 * Return the URL of the image file
111 * @access public
112 */
113 function getURL()
114 {
115 return $this->url;
116 }
117
118 /**
119 * Return the image path of the image in the
120 * local file system as an absolute path
121 * @access public
122 */
123 function getImagePath()
124 {
125 return $this->imagePath;
126 }
127
128 /**
129 * Return the width of the image
130 *
131 * Returns -1 if the file specified is not a known image type
132 * @access public
133 */
134 function getWidth()
135 {
136 return $this->width;
137 }
138
139 /**
140 * Return the height of the image
141 *
142 * Returns -1 if the file specified is not a known image type
143 * @access public
144 */
145 function getHeight()
146 {
147 return $this->height;
148 }
149
150 /**
151 * Return the size of the image file, in bytes
152 * @access public
153 */
154 function getSize()
155 {
156 $st = stat( $this->getImagePath() );
157 return $st['size'];
158 }
159
160 /**
161 * Return the type of the image
162 *
163 * - 1 GIF
164 * - 2 JPG
165 * - 3 PNG
166 * - 15 WBMP
167 * - 16 XBM
168 */
169 function getType()
170 {
171 return $this->type;
172 }
173
174 /**
175 * Return the escapeLocalURL of this image
176 * @access public
177 */
178 function getEscapeLocalURL()
179 {
180 return $this->title->escapeLocalURL();
181 }
182
183 /**
184 * Return the URL of an image, provided its name.
185 *
186 * @param string $name Name of the image, without the leading Image:
187 * @access public
188 */
189 function wfImageUrl( $name )
190 {
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}";
198 }
199 return wfUrlencode( $url );
200 }
201
202 /**
203 * Returns true iff the image file exists on disk.
204 *
205 * @access public
206 */
207 function exists()
208 {
209 return $this->fileExists;
210 }
211
212 /**
213 *
214 * @access private
215 */
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}";
225 }
226
227 return wfUrlencode($url);
228 }
229
230 /**
231 * Return the file name of a thumbnail of the specified width
232 *
233 * @param integer $width Width of the thumbnail image
234 * @access private
235 */
236 function thumbName( $width ) {
237 return $width."px-".$this->name;
238 }
239
240 /**
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.
247 *
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.
251 *
252 * @param integer $width maximum width of the generated thumbnail
253 * @param integer $height maximum height of the image (optional)
254 * @access public
255 */
256 function createThumb( $width, $height=-1 ) {
257 if ( $height == -1 ) {
258 return $this->renderThumb( $width );
259 }
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;
266 }
267 if ( $thumbheight > $height ) {
268 $thumbwidth = $thumbwidth * $height / $thumbheight;
269 $thumbheight = $height;
270 }
271 return $this->renderThumb( $thumbwidth );
272 }
273
274 /**
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.
281 *
282 * @access private
283 */
284 function /* private */ renderThumb( $width ) {
285 global $wgUploadDirectory;
286 global $wgImageMagickConvertCommand;
287 global $wgUseImageMagick;
288 global $wgUseSquid, $wgInternalServer;
289
290 $width = IntVal( $width );
291
292 $thumbName = $this->thumbName( $width );
293 $thumbPath = wfImageThumbDir( $thumbName ).'/'.$thumbName;
294 $thumbUrl = $this->thumbUrl( $width );
295
296 if ( ! $this->exists() )
297 {
298 # If there is no image, there will be no thumbnail
299 return '';
300 }
301
302 # Sanity check $width
303 if( $width <= 0 ) {
304 # BZZZT
305 return '';
306 }
307
308 if( $width > $this->width ) {
309 # Don't make an image bigger than the source
310 return $this->getURL();
311 }
312
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.
325 #
326 # First find out what kind of file this is, and select the correct
327 # input routine for this.
328
329 $truecolor = false;
330
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;
352 }
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 );
358 }
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;
379 }
380 imagedestroy( $dst_image );
381 imagedestroy( $src_image );
382
383
384 }
385 #
386 # Check for zero-sized thumbnails. Those can be generated when
387 # no disk space is available or some other error occurs
388 #
389 $thumbstat = stat( $thumbPath );
390 if( $thumbstat['size'] == 0 )
391 {
392 unlink( $thumbPath );
393 }
394
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
401 );
402 wfPurgeSquidServers($urlArr);
403 }
404 }
405 return $thumbUrl;
406 } // END OF function createThumb
407
408 /**
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
415 *
416 * @access public
417 */
418 function nextHistoryLine()
419 {
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
427 );
428 if ( 0 == wfNumRows( $this->historyRes ) ) {
429 return FALSE;
430 }
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' )
436 );
437 }
438 $this->historyLine ++;
439
440 return $dbr->fetchObject( $this->historyRes );
441 }
442
443 /**
444 * Reset the history pointer to the first element of the history
445 * @access public
446 */
447 function resetHistory()
448 {
449 $this->historyLine = 0;
450 }
451
452
453 } //class
454
455
456 /**
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.
460 *
461 * @param string $fname file name of the image file
462 * @access public
463 */
464 function wfImageDir( $fname )
465 {
466 global $wgUploadDirectory, $wgHashedUploadDirectory;
467
468 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
469
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 ); }
476
477 umask( $oldumask );
478 return $dest;
479 }
480
481 /**
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.
485 *
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
489 */
490 function wfImageThumbDir( $fname , $subdir='thumb')
491 {
492 return wfImageArchiveDir( $fname, $subdir );
493 }
494
495 /**
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.
499 *
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
503 */
504 function wfImageArchiveDir( $fname , $subdir='archive')
505 {
506 global $wgUploadDirectory, $wgHashedUploadDirectory;
507
508 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory.'/'.$subdir; }
509
510 $hash = md5( $fname );
511 $oldumask = umask(0);
512
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 ); }
521
522 umask( $oldumask );
523 return $archive;
524 }
525
526 /**
527 * Record an image upload in the upload log.
528 */
529 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
530 {
531 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
532 global $wgUseCopyrightUpload;
533
534 $fname = 'wfRecordUpload';
535 $dbw =& wfGetDB( DB_MASTER );
536
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' );
540 }
541
542
543 $now = wfTimestampNow();
544 $won = wfInvertTimestamp( $now );
545 $size = IntVal( $size );
546
547 if ( $wgUseCopyrightUpload )
548 {
549 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
550 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
551 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
552 }
553 else $textdesc = $desc ;
554
555 $now = wfTimestampNow();
556 $won = wfInvertTimestamp( $now );
557
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'
570 );
571 $descTitle = Title::makeTitleSafe( NS_IMAGE, $name );
572
573 if ( $dbw->affectedRows() ) {
574 # Successfully inserted, this is a new image
575 $id = $descTitle->getArticleID();
576
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
593 );
594 $id = $dbw->insertId() or 0; # We should throw an error instead
595
596 RecentChange::notifyNew( $now, $descTitle, 0, $wgUser, $desc );
597
598 $u = new SearchUpdate( $id, $name, $desc );
599 $u->doUpdate();
600 }
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' );
606
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
618 );
619
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
631 );
632
633 # Invalidate the cache for the description page
634 $descTitle->invalidateCache();
635 }
636
637 $log = new LogPage( 'upload' );
638 $log->addEntry( 'upload', $descTitle, $desc );
639 }
640
641 /**
642 * Returns the image URL of an image's old version
643 *
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
647 */
648 function wfImageArchiveUrl( $name, $subdir='archive' )
649 {
650 global $wgUploadPath, $wgHashedUploadDirectory;
651
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;
658 }
659 return wfUrlencode($url);
660 }
661
662 ?>