Adjust spacing, and fix the disclaimer link again so it's separated from the printabl...
[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 $n = strrpos( $name, '.' );
59 $this->extension = strtolower( $n ? substr( $name, $n + 1 ) : '' );
60
61 if ( $this->fileExists = file_exists( $this->imagePath ) ) // Sic!, "=" is intended
62 {
63 if( $this->extension == 'svg' ) {
64 @$gis = getSVGsize( $this->imagePath );
65 } else {
66 @$gis = getimagesize( $this->imagePath );
67 }
68 if( $gis !== false ) {
69 $this->width = $gis[0];
70 $this->height = $gis[1];
71 $this->type = $gis[2];
72 $this->attr = $gis[3];
73 if ( isset( $gis['bits'] ) ) {
74 $this->bits = $gis['bits'];
75 } else {
76 $this->bits = 0;
77 }
78 }
79 }
80 $this->historyLine = 0;
81 }
82
83 /**
84 * Factory function
85 *
86 * Create a new image object from a title object.
87 *
88 * @param Title $nt Title object. Must be from namespace "image"
89 * @access public
90 */
91 function newFromTitle( $nt )
92 {
93 $img = new Image( $nt->getDBKey() );
94 $img->title = $nt;
95 return $img;
96 }
97
98 /**
99 * Return the name of this image
100 * @access public
101 */
102 function getName()
103 {
104 return $this->name;
105 }
106
107 /**
108 * Return the associated title object
109 * @access public
110 */
111 function getTitle()
112 {
113 return $this->title;
114 }
115
116 /**
117 * Return the URL of the image file
118 * @access public
119 */
120 function getURL()
121 {
122 return $this->url;
123 }
124
125 function getViewURL() {
126 if( $this->mustRender() ) {
127 return $this->createThumb( $this->getWidth() );
128 } else {
129 return $this->getURL();
130 }
131 }
132
133 /**
134 * Return the image path of the image in the
135 * local file system as an absolute path
136 * @access public
137 */
138 function getImagePath()
139 {
140 return $this->imagePath;
141 }
142
143 /**
144 * Return the width of the image
145 *
146 * Returns -1 if the file specified is not a known image type
147 * @access public
148 */
149 function getWidth()
150 {
151 return $this->width;
152 }
153
154 /**
155 * Return the height of the image
156 *
157 * Returns -1 if the file specified is not a known image type
158 * @access public
159 */
160 function getHeight()
161 {
162 return $this->height;
163 }
164
165 /**
166 * Return the size of the image file, in bytes
167 * @access public
168 */
169 function getSize()
170 {
171 $st = stat( $this->getImagePath() );
172 return $st['size'];
173 }
174
175 /**
176 * Return the type of the image
177 *
178 * - 1 GIF
179 * - 2 JPG
180 * - 3 PNG
181 * - 15 WBMP
182 * - 16 XBM
183 */
184 function getType()
185 {
186 return $this->type;
187 }
188
189 /**
190 * Return the escapeLocalURL of this image
191 * @access public
192 */
193 function getEscapeLocalURL()
194 {
195 return $this->title->escapeLocalURL();
196 }
197
198 /**
199 * Return the URL of an image, provided its name.
200 *
201 * @param string $name Name of the image, without the leading Image:
202 * @access public
203 */
204 function wfImageUrl( $name )
205 {
206 global $wgUploadPath,$wgUploadBaseUrl,$wgHashedUploadDirectory;
207 if ($wgHashedUploadDirectory) {
208 $hash = md5( $name );
209 $url = "{$wgUploadBaseUrl}{$wgUploadPath}/" . $hash{0} . "/" .
210 substr( $hash, 0, 2 ) . "/{$name}";
211 } else {
212 $url = "{$wgUploadBaseUrl}{$wgUploadPath}/{$name}";
213 }
214 return wfUrlencode( $url );
215 }
216
217 /**
218 * Returns true iff the image file exists on disk.
219 *
220 * @access public
221 */
222 function exists()
223 {
224 return $this->fileExists;
225 }
226
227 /**
228 *
229 * @access private
230 */
231 function thumbUrl( $width, $subdir='thumb' ) {
232 global $wgUploadPath,$wgHashedUploadDirectory;
233 $name = $this->thumbName( $width );
234 if ($wgHashedUploadDirectory) {
235 $hash = md5( $name );
236 $url = "{$wgUploadPath}/{$subdir}/" . $hash{0} . "/" .
237 substr( $hash, 0, 2 ) . "/{$name}";
238 } else {
239 $url = "{$wgUploadPath}/{$subdir}/{$name}";
240 }
241
242 return wfUrlencode($url);
243 }
244
245 /**
246 * Return the file name of a thumbnail of the specified width
247 *
248 * @param integer $width Width of the thumbnail image
249 * @access private
250 */
251 function thumbName( $width ) {
252 $thumb = $width."px-".$this->name;
253 if( $this->extension == 'svg' ) {
254 # Rasterize SVG vector images to PNG
255 $thumb .= '.png';
256 }
257 return $thumb;
258 }
259
260 /**
261 * Create a thumbnail of the image having the specified width/height.
262 * The thumbnail will not be created if the width is larger than the
263 * image's width. Let the browser do the scaling in this case.
264 * The thumbnail is stored on disk and is only computed if the thumbnail
265 * file does not exist OR if it is older than the image.
266 * Returns the URL.
267 *
268 * Keeps aspect ratio of original image. If both width and height are
269 * specified, the generated image will be no bigger than width x height,
270 * and will also have correct aspect ratio.
271 *
272 * @param integer $width maximum width of the generated thumbnail
273 * @param integer $height maximum height of the image (optional)
274 * @access public
275 */
276 function createThumb( $width, $height=-1 ) {
277 if ( $height == -1 ) {
278 return $this->renderThumb( $width );
279 }
280 if ( $width < $this->width ) {
281 $thumbheight = $this->height * $width / $this->width;
282 $thumbwidth = $width;
283 } else {
284 $thumbheight = $this->height;
285 $thumbwidth = $this->width;
286 }
287 if ( $thumbheight > $height ) {
288 $thumbwidth = $thumbwidth * $height / $thumbheight;
289 $thumbheight = $height;
290 }
291 return $this->renderThumb( $thumbwidth );
292 }
293
294 /**
295 * Create a thumbnail of the image having the specified width.
296 * The thumbnail will not be created if the width is larger than the
297 * image's width. Let the browser do the scaling in this case.
298 * The thumbnail is stored on disk and is only computed if the thumbnail
299 * file does not exist OR if it is older than the image.
300 * Returns the URL.
301 *
302 * @access private
303 */
304 function /* private */ renderThumb( $width ) {
305 global $wgUploadDirectory;
306 global $wgImageMagickConvertCommand;
307 global $wgUseImageMagick;
308 global $wgUseSquid, $wgInternalServer;
309
310 $width = IntVal( $width );
311
312 $thumbName = $this->thumbName( $width );
313 $thumbPath = wfImageThumbDir( $thumbName ).'/'.$thumbName;
314 $thumbUrl = $this->thumbUrl( $width );
315
316 if ( ! $this->exists() )
317 {
318 # If there is no image, there will be no thumbnail
319 return '';
320 }
321
322 # Sanity check $width
323 if( $width <= 0 ) {
324 # BZZZT
325 return '';
326 }
327
328 if( $width > $this->width && !$this->mustRender() ) {
329 # Don't make an image bigger than the source
330 return $this->getViewURL();
331 }
332
333 if ( (! file_exists( $thumbPath ) ) || ( filemtime($thumbPath) < filemtime($this->imagePath) ) ) {
334 if( $this->extension == 'svg' ) {
335 global $wgSVGConverters, $wgSVGConverter;
336 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
337 global $wgSVGConverterPath;
338 $cmd = str_replace(
339 array( '$path/', '$width', '$input', '$output' ),
340 array( $wgSVGConverterPath,
341 $width,
342 escapeshellarg( $this->imagePath ),
343 escapeshellarg( $thumbPath ) ),
344 $wgSVGConverters[$wgSVGConverter] );
345 $conv = shell_exec( $cmd );
346 } else {
347 $conv = false;
348 }
349 } elseif ( $wgUseImageMagick ) {
350 # use ImageMagick
351 # Specify white background color, will be used for transparent images
352 # in Internet Explorer/Windows instead of default black.
353 $cmd = $wgImageMagickConvertCommand .
354 " -quality 85 -background white -geometry {$width} ".
355 escapeshellarg($this->imagePath) . " " .
356 escapeshellarg($thumbPath);
357 $conv = shell_exec( $cmd );
358 } else {
359 # Use PHP's builtin GD library functions.
360 #
361 # First find out what kind of file this is, and select the correct
362 # input routine for this.
363
364 $truecolor = false;
365
366 switch( $this->type ) {
367 case 1: # GIF
368 $src_image = imagecreatefromgif( $this->imagePath );
369 break;
370 case 2: # JPG
371 $src_image = imagecreatefromjpeg( $this->imagePath );
372 $truecolor = true;
373 break;
374 case 3: # PNG
375 $src_image = imagecreatefrompng( $this->imagePath );
376 $truecolor = ( $this->bits > 8 );
377 break;
378 case 15: # WBMP for WML
379 $src_image = imagecreatefromwbmp( $this->imagePath );
380 break;
381 case 16: # XBM
382 $src_image = imagecreatefromxbm( $this->imagePath );
383 break;
384 default:
385 return 'Image type not supported';
386 break;
387 }
388 $height = floor( $this->height * ( $width/$this->width ) );
389 if ( $truecolor ) {
390 $dst_image = imagecreatetruecolor( $width, $height );
391 } else {
392 $dst_image = imagecreate( $width, $height );
393 }
394 imagecopyresampled( $dst_image, $src_image,
395 0,0,0,0,
396 $width, $height, $this->width, $this->height );
397 switch( $this->type ) {
398 case 1: # GIF
399 case 3: # PNG
400 case 15: # WBMP
401 case 16: # XBM
402 #$thumbUrl .= ".png";
403 #$thumbPath .= ".png";
404 imagepng( $dst_image, $thumbPath );
405 break;
406 case 2: # JPEG
407 #$thumbUrl .= ".jpg";
408 #$thumbPath .= ".jpg";
409 imageinterlace( $dst_image );
410 imagejpeg( $dst_image, $thumbPath, 95 );
411 break;
412 default:
413 break;
414 }
415 imagedestroy( $dst_image );
416 imagedestroy( $src_image );
417
418
419 }
420 #
421 # Check for zero-sized thumbnails. Those can be generated when
422 # no disk space is available or some other error occurs
423 #
424 $thumbstat = stat( $thumbPath );
425 if( $thumbstat['size'] == 0 )
426 {
427 unlink( $thumbPath );
428 }
429
430 # Purge squid
431 # This has to be done after the image is updated and present for all machines on NFS,
432 # or else the old version might be stored into the squid again
433 if ( $wgUseSquid ) {
434 $urlArr = Array(
435 $wgInternalServer.$thumbUrl
436 );
437 wfPurgeSquidServers($urlArr);
438 }
439 }
440 return $thumbUrl;
441 } // END OF function createThumb
442
443 /**
444 * Return the image history of this image, line by line.
445 * starts with current version, then old versions.
446 * uses $this->historyLine to check which line to return:
447 * 0 return line for current version
448 * 1 query for old versions, return first one
449 * 2, ... return next old version from above query
450 *
451 * @access public
452 */
453 function nextHistoryLine()
454 {
455 $fname = 'Image::nextHistoryLine()';
456 $dbr =& wfGetDB( DB_SLAVE );
457 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
458 $this->historyRes = $dbr->select( 'image',
459 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
460 array( 'img_name' => $this->title->getDBkey() ),
461 $fname
462 );
463 if ( 0 == wfNumRows( $this->historyRes ) ) {
464 return FALSE;
465 }
466 } else if ( $this->historyLine == 1 ) {
467 $this->historyRes = $dbr->select( 'oldimage',
468 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
469 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
470 ), array( 'oi_name' => $this->title->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
471 );
472 }
473 $this->historyLine ++;
474
475 return $dbr->fetchObject( $this->historyRes );
476 }
477
478 /**
479 * Reset the history pointer to the first element of the history
480 * @access public
481 */
482 function resetHistory()
483 {
484 $this->historyLine = 0;
485 }
486
487 /**
488 * Return true if the file is of a type that can't be directly
489 * rendered by typical browsers and needs to be re-rasterized.
490 * @return bool
491 */
492 function mustRender() {
493 return ( $this->extension == 'svg' );
494 }
495
496 } //class
497
498
499 /**
500 * Returns the image directory of an image
501 * If the directory does not exist, it is created.
502 * The result is an absolute path.
503 *
504 * @param string $fname file name of the image file
505 * @access public
506 */
507 function wfImageDir( $fname )
508 {
509 global $wgUploadDirectory, $wgHashedUploadDirectory;
510
511 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
512
513 $hash = md5( $fname );
514 $oldumask = umask(0);
515 $dest = $wgUploadDirectory . '/' . $hash{0};
516 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
517 $dest .= '/' . substr( $hash, 0, 2 );
518 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
519
520 umask( $oldumask );
521 return $dest;
522 }
523
524 /**
525 * Returns the image directory of an image's thubnail
526 * If the directory does not exist, it is created.
527 * The result is an absolute path.
528 *
529 * @param string $fname file name of the thumbnail file, including file size prefix
530 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
531 * @access public
532 */
533 function wfImageThumbDir( $fname , $subdir='thumb')
534 {
535 return wfImageArchiveDir( $fname, $subdir );
536 }
537
538 /**
539 * Returns the image directory of an image's old version
540 * If the directory does not exist, it is created.
541 * The result is an absolute path.
542 *
543 * @param string $fname file name of the thumbnail file, including file size prefix
544 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
545 * @access public
546 */
547 function wfImageArchiveDir( $fname , $subdir='archive')
548 {
549 global $wgUploadDirectory, $wgHashedUploadDirectory;
550
551 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory.'/'.$subdir; }
552
553 $hash = md5( $fname );
554 $oldumask = umask(0);
555
556 # Suppress warning messages here; if the file itself can't
557 # be written we'll worry about it then.
558 $archive = $wgUploadDirectory.'/'.$subdir;
559 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
560 $archive .= '/' . $hash{0};
561 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
562 $archive .= '/' . substr( $hash, 0, 2 );
563 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
564
565 umask( $oldumask );
566 return $archive;
567 }
568
569 /**
570 * Record an image upload in the upload log.
571 */
572 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
573 {
574 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
575 global $wgUseCopyrightUpload;
576
577 $fname = 'wfRecordUpload';
578 $dbw =& wfGetDB( DB_MASTER );
579
580 # img_name must be unique
581 if ( !$dbw->indexUnique( 'image', 'img_name' ) ) {
582 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
583 }
584
585
586 $now = wfTimestampNow();
587 $won = wfInvertTimestamp( $now );
588 $size = IntVal( $size );
589
590 if ( $wgUseCopyrightUpload )
591 {
592 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
593 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
594 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
595 }
596 else $textdesc = $desc ;
597
598 $now = wfTimestampNow();
599 $won = wfInvertTimestamp( $now );
600
601 # Test to see if the row exists using INSERT IGNORE
602 # This avoids race conditions by locking the row until the commit, and also
603 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
604 $dbw->insertArray( 'image',
605 array(
606 'img_name' => $name,
607 'img_size'=> $size,
608 'img_timestamp' => $dbw->timestamp($now),
609 'img_description' => $desc,
610 'img_user' => $wgUser->getID(),
611 'img_user_text' => $wgUser->getName(),
612 ), $fname, 'IGNORE'
613 );
614 $descTitle = Title::makeTitleSafe( NS_IMAGE, $name );
615
616 if ( $dbw->affectedRows() ) {
617 # Successfully inserted, this is a new image
618 $id = $descTitle->getArticleID();
619
620 if ( $id == 0 ) {
621 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
622 $dbw->insertArray( 'cur',
623 array(
624 'cur_id' => $seqVal,
625 'cur_namespace' => NS_IMAGE,
626 'cur_title' => $name,
627 'cur_comment' => $desc,
628 'cur_user' => $wgUser->getID(),
629 'cur_user_text' => $wgUser->getName(),
630 'cur_timestamp' => $dbw->timestamp($now),
631 'cur_is_new' => 1,
632 'cur_text' => $textdesc,
633 'inverse_timestamp' => $won,
634 'cur_touched' => $dbw->timestamp($now)
635 ), $fname
636 );
637 $id = $dbw->insertId() or 0; # We should throw an error instead
638
639 RecentChange::notifyNew( $now, $descTitle, 0, $wgUser, $desc );
640
641 $u = new SearchUpdate( $id, $name, $desc );
642 $u->doUpdate();
643 }
644 } else {
645 # Collision, this is an update of an image
646 # Get current image row for update
647 $s = $dbw->getArray( 'image', array( 'img_name','img_size','img_timestamp','img_description',
648 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
649
650 # Insert it into oldimage
651 $dbw->insertArray( 'oldimage',
652 array(
653 'oi_name' => $s->img_name,
654 'oi_archive_name' => $oldver,
655 'oi_size' => $s->img_size,
656 'oi_timestamp' => $dbw->timestamp($s->img_timestamp),
657 'oi_description' => $s->img_description,
658 'oi_user' => $s->img_user,
659 'oi_user_text' => $s->img_user_text
660 ), $fname
661 );
662
663 # Update the current image row
664 $dbw->updateArray( 'image',
665 array( /* SET */
666 'img_size' => $size,
667 'img_timestamp' => $dbw->timestamp(),
668 'img_user' => $wgUser->getID(),
669 'img_user_text' => $wgUser->getName(),
670 'img_description' => $desc,
671 ), array( /* WHERE */
672 'img_name' => $name
673 ), $fname
674 );
675
676 # Invalidate the cache for the description page
677 $descTitle->invalidateCache();
678 }
679
680 $log = new LogPage( 'upload' );
681 $log->addEntry( 'upload', $descTitle, $desc );
682 }
683
684 /**
685 * Returns the image URL of an image's old version
686 *
687 * @param string $fname file name of the image file
688 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
689 * @access public
690 */
691 function wfImageArchiveUrl( $name, $subdir='archive' )
692 {
693 global $wgUploadPath, $wgHashedUploadDirectory;
694
695 if ($wgHashedUploadDirectory) {
696 $hash = md5( substr( $name, 15) );
697 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
698 substr( $hash, 0, 2 ) . '/'.$name;
699 } else {
700 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
701 }
702 return wfUrlencode($url);
703 }
704
705 /**
706 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
707 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
708 *
709 * @param string $length
710 * @return int Length in pixels
711 */
712 function scaleSVGUnit( $length ) {
713 static $unitLength = array(
714 'px' => 1.0,
715 'pt' => 1.25,
716 'pc' => 15.0,
717 'mm' => 3.543307,
718 'cm' => 35.43307,
719 'in' => 90.0,
720 '' => 1.0, // "User units" pixels by default
721 '%' => 2.0, // Fake it!
722 );
723 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
724 $length = FloatVal( $matches[1] );
725 $unit = $matches[2];
726 return round( $length * $unitLength[$unit] );
727 } else {
728 // Assume pixels
729 return round( FloatVal( $length ) );
730 }
731 }
732
733 /**
734 * Compatible with PHP getimagesize()
735 * @todo support gzipped SVGZ
736 * @todo check XML more carefully
737 * @todo sensible defaults
738 *
739 * @param string $filename
740 * @return array
741 */
742 function getSVGsize( $filename ) {
743 $width = 256;
744 $height = 256;
745
746 // Read a chunk of the file
747 $f = fopen( $filename, "rt" );
748 if( !$f ) return false;
749 $chunk = fread( $f, 4096 );
750 fclose( $f );
751
752 // Uber-crappy hack! Run through a real XML parser.
753 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
754 return false;
755 }
756 $tag = $matches[1];
757 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
758 $width = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
759 }
760 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
761 $height = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
762 }
763
764 return array( $width, $height, 'SVG',
765 "width=\"$width\" height=\"$height\"" );
766 }
767
768 ?>