Implement #1206
[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 /**#@+
16 * @access private
17 */
18 var $name, # name of the image
19 $imagePath, # Path of the image
20 $url, # Image URL
21 $title, # Title object for this image. Initialized when needed.
22 $fileExists, # does the image file exist on disk?
23 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory
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
44 global $wgUseSharedUploads, $wgUseLatin1, $wgSharedLatin1, $wgLang;
45
46 $this->name = $name;
47 $this->title = Title::makeTitleSafe( NS_IMAGE, $this->name );
48 $this->fromSharedDirectory = false;
49 $this->imagePath = $this->getFullPath();
50 $this->fileExists = file_exists( $this->imagePath);
51
52 # If the file is not found, and a shared upload directory
53 # like the Wikimedia Commons is used, look for it there.
54 if (!$this->fileExists && $wgUseSharedUploads) {
55
56 # In case we're on a wgCapitalLinks=false wiki, we
57 # capitalize the first letter of the filename before
58 # looking it up in the shared repository.
59 $this->name= $wgLang->ucfirst($name);
60
61 # Encode the filename if we're on a Latin1 wiki and the
62 # shared repository is UTF-8
63 if($wgUseLatin1 && !$wgSharedLatin1) {
64 $this->name = utf8_encode($name);
65 }
66
67 $this->imagePath = $this->getFullPath(true);
68 $this->fileExists = file_exists( $this->imagePath);
69 $this->fromSharedDirectory = true;
70 $name=$this->name;
71
72 }
73 if($this->fileExists) {
74 $this->url = $this->wfImageUrl( $this->name, $this->fromSharedDirectory );
75 } else {
76 $this->url='';
77 }
78
79 $n = strrpos( $name, '.' );
80 $this->extension = strtolower( $n ? substr( $name, $n + 1 ) : '' );
81
82
83 if ( $this->fileExists )
84 {
85 if( $this->extension == 'svg' ) {
86 @$gis = getSVGsize( $this->imagePath );
87 } else {
88 @$gis = getimagesize( $this->imagePath );
89 }
90 if( $gis !== false ) {
91 $this->width = $gis[0];
92 $this->height = $gis[1];
93 $this->type = $gis[2];
94 $this->attr = $gis[3];
95 if ( isset( $gis['bits'] ) ) {
96 $this->bits = $gis['bits'];
97 } else {
98 $this->bits = 0;
99 }
100 }
101 }
102 $this->historyLine = 0;
103 }
104
105 /**
106 * Factory function
107 *
108 * Create a new image object from a title object.
109 *
110 * @param Title $nt Title object. Must be from namespace "image"
111 * @access public
112 */
113 function newFromTitle( $nt )
114 {
115 $img = new Image( $nt->getDBKey() );
116 $img->title = $nt;
117 return $img;
118 }
119
120 /**
121 * Return the name of this image
122 * @access public
123 */
124 function getName()
125 {
126 return $this->name;
127 }
128
129 /**
130 * Return the associated title object
131 * @access public
132 */
133 function getTitle()
134 {
135 return $this->title;
136 }
137
138 /**
139 * Return the URL of the image file
140 * @access public
141 */
142 function getURL()
143 {
144 return $this->url;
145 }
146
147 function getViewURL() {
148 if( $this->mustRender() ) {
149 return $this->createThumb( $this->getWidth() );
150 } else {
151 return $this->getURL();
152 }
153 }
154
155 /**
156 * Return the image path of the image in the
157 * local file system as an absolute path
158 * @access public
159 */
160 function getImagePath()
161 {
162 return $this->imagePath;
163 }
164
165 /**
166 * Return the width of the image
167 *
168 * Returns -1 if the file specified is not a known image type
169 * @access public
170 */
171 function getWidth()
172 {
173 return $this->width;
174 }
175
176 /**
177 * Return the height of the image
178 *
179 * Returns -1 if the file specified is not a known image type
180 * @access public
181 */
182 function getHeight()
183 {
184 return $this->height;
185 }
186
187 /**
188 * Return the size of the image file, in bytes
189 * @access public
190 */
191 function getSize()
192 {
193 $st = stat( $this->getImagePath() );
194 if( $st ) {
195 return $st['size'];
196 } else {
197 return false;
198 }
199 }
200
201 /**
202 * Return the type of the image
203 *
204 * - 1 GIF
205 * - 2 JPG
206 * - 3 PNG
207 * - 15 WBMP
208 * - 16 XBM
209 */
210 function getType()
211 {
212 return $this->type;
213 }
214
215 /**
216 * Return the escapeLocalURL of this image
217 * @access public
218 */
219 function getEscapeLocalURL()
220 {
221 return $this->title->escapeLocalURL();
222 }
223
224 /**
225 * Return the escapeFullURL of this image
226 * @access public
227 */
228 function getEscapeFullURL()
229 {
230 return $this->title->escapeFullURL();
231 }
232
233 /**
234 * Return the URL of an image, provided its name.
235 *
236 * @param string $name Name of the image, without the leading "Image:"
237 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
238 * @access public
239 */
240 function wfImageUrl( $name, $fromSharedDirectory = false )
241 {
242 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
243 if($fromSharedDirectory) {
244 $base = '';
245 $path = $wgSharedUploadPath;
246 } else {
247 $base = $wgUploadBaseUrl;
248 $path = $wgUploadPath;
249 }
250 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
251 return wfUrlencode( $url );
252 }
253
254 /**
255 * Returns true iff the image file exists on disk.
256 *
257 * @access public
258 */
259 function exists()
260 {
261 return $this->fileExists;
262 }
263
264 /**
265 *
266 * @access private
267 */
268 function thumbUrl( $width, $subdir='thumb') {
269 global $wgUploadPath, $wgUploadBaseUrl,
270 $wgSharedUploadPath,$wgSharedUploadDirectory,
271 $wgUseLatin1,$wgSharedLatin1;
272 $name = $this->thumbName( $width );
273 if($this->fromSharedDirectory) {
274 $base = '';
275 $path = $wgSharedUploadPath;
276 if($wgUseLatin1 && !$wgSharedLatin1) {
277 $name=utf8_encode($name);
278 }
279 } else {
280 $base = $wgUploadBaseUrl;
281 $path = $wgUploadPath;
282 }
283 $url = "{$base}{$path}/{$subdir}" .
284 wfGetHashPath($name, $this->fromSharedDirectory)
285 . "{$name}";
286 return wfUrlencode($url);
287 }
288
289 /**
290 * Return the file name of a thumbnail of the specified width
291 *
292 * @param integer $width Width of the thumbnail image
293 * @param boolean $shared Does the thumbnail come from the shared repository?
294 * @access private
295 */
296 function thumbName( $width, $shared=false ) {
297 global $wgUseLatin1,$wgSharedLatin1;
298 $thumb = $width."px-".$this->name;
299 if( $this->extension == 'svg' ) {
300 # Rasterize SVG vector images to PNG
301 $thumb .= '.png';
302 }
303 if( $shared && $wgUseLatin1 && !$wgSharedLatin1) {
304 $thumb=utf8_encode($thumb);
305 }
306 return $thumb;
307 }
308
309 /**
310 * Create a thumbnail of the image having the specified width/height.
311 * The thumbnail will not be created if the width is larger than the
312 * image's width. Let the browser do the scaling in this case.
313 * The thumbnail is stored on disk and is only computed if the thumbnail
314 * file does not exist OR if it is older than the image.
315 * Returns the URL.
316 *
317 * Keeps aspect ratio of original image. If both width and height are
318 * specified, the generated image will be no bigger than width x height,
319 * and will also have correct aspect ratio.
320 *
321 * @param integer $width maximum width of the generated thumbnail
322 * @param integer $height maximum height of the image (optional)
323 * @access public
324 */
325 function createThumb( $width, $height=-1 ) {
326 $thumb = $this->getThumbnail( $width, $height );
327 if( is_null( $thumb ) ) return '';
328 return $thumb->getUrl();
329 }
330
331 /**
332 * As createThumb, but returns a ThumbnailImage object. This can
333 * provide access to the actual file, the real size of the thumb,
334 * and can produce a convenient <img> tag for you.
335 *
336 * @param integer $width maximum width of the generated thumbnail
337 * @param integer $height maximum height of the image (optional)
338 * @return ThumbnailImage
339 * @access public
340 */
341 function &getThumbnail( $width, $height=-1 ) {
342 if ( $height == -1 ) {
343 return $this->renderThumb( $width );
344 }
345 if ( $width < $this->width ) {
346 $thumbheight = $this->height * $width / $this->width;
347 $thumbwidth = $width;
348 } else {
349 $thumbheight = $this->height;
350 $thumbwidth = $this->width;
351 }
352 if ( $thumbheight > $height ) {
353 $thumbwidth = $thumbwidth * $height / $thumbheight;
354 $thumbheight = $height;
355 }
356 $thumb = $this->renderThumb( $thumbwidth );
357 if( is_null( $thumb ) ) {
358 $thumb = $this->iconThumb();
359 }
360 return $thumb;
361 }
362
363 /**
364 * @return ThumbnailImage
365 */
366 function iconThumb() {
367 global $wgStylePath, $wgStyleDirectory;
368
369 $try = array( 'fileicon-' . $this->extension . '.png', 'fileicon.png' );
370 foreach( $try as $icon ) {
371 $path = '/common/images/' . $icon;
372 $filepath = $wgStyleDirectory . $path;
373 if( file_exists( $filepath ) ) {
374 return new ThumbnailImage( $filepath, $wgStylePath . $path );
375 }
376 }
377 return null;
378 }
379
380 /**
381 * Create a thumbnail of the image having the specified width.
382 * The thumbnail will not be created if the width is larger than the
383 * image's width. Let the browser do the scaling in this case.
384 * The thumbnail is stored on disk and is only computed if the thumbnail
385 * file does not exist OR if it is older than the image.
386 * Returns an object which can return the pathname, URL, and physical
387 * pixel size of the thumbnail -- or null on failure.
388 *
389 * @return ThumbnailImage
390 * @access private
391 */
392 function /* private */ renderThumb( $width ) {
393 global $wgImageMagickConvertCommand;
394 global $wgUseImageMagick;
395 global $wgUseSquid, $wgInternalServer;
396
397 $width = IntVal( $width );
398
399 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory );
400 $thumbPath = wfImageThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory ).'/'.$thumbName;
401 $thumbUrl = $this->thumbUrl( $width );
402 #wfDebug ( "Render name: $thumbName path: $thumbPath url: $thumbUrl\n");
403 if ( ! $this->exists() )
404 {
405 # If there is no image, there will be no thumbnail
406 return null;
407 }
408
409 # Sanity check $width
410 if( $width <= 0 ) {
411 # BZZZT
412 return null;
413 }
414
415 if( $width > $this->width && !$this->mustRender() ) {
416 # Don't make an image bigger than the source
417 return new ThumbnailImage( $this->getImagePath(), $this->getViewURL() );
418 }
419
420 if ( (! file_exists( $thumbPath ) ) || ( filemtime($thumbPath) < filemtime($this->imagePath) ) ) {
421 if( $this->extension == 'svg' ) {
422 global $wgSVGConverters, $wgSVGConverter;
423 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
424 global $wgSVGConverterPath;
425 $cmd = str_replace(
426 array( '$path/', '$width', '$input', '$output' ),
427 array( $wgSVGConverterPath,
428 $width,
429 escapeshellarg( $this->imagePath ),
430 escapeshellarg( $thumbPath ) ),
431 $wgSVGConverters[$wgSVGConverter] );
432 $conv = shell_exec( $cmd );
433 } else {
434 $conv = false;
435 }
436 } elseif ( $wgUseImageMagick ) {
437 # use ImageMagick
438 # Specify white background color, will be used for transparent images
439 # in Internet Explorer/Windows instead of default black.
440 $cmd = $wgImageMagickConvertCommand .
441 " -quality 85 -background white -geometry {$width} ".
442 escapeshellarg($this->imagePath) . " " .
443 escapeshellarg($thumbPath);
444 $conv = shell_exec( $cmd );
445 } else {
446 # Use PHP's builtin GD library functions.
447 #
448 # First find out what kind of file this is, and select the correct
449 # input routine for this.
450
451 $truecolor = false;
452
453 switch( $this->type ) {
454 case 1: # GIF
455 $src_image = imagecreatefromgif( $this->imagePath );
456 break;
457 case 2: # JPG
458 $src_image = imagecreatefromjpeg( $this->imagePath );
459 $truecolor = true;
460 break;
461 case 3: # PNG
462 $src_image = imagecreatefrompng( $this->imagePath );
463 $truecolor = ( $this->bits > 8 );
464 break;
465 case 15: # WBMP for WML
466 $src_image = imagecreatefromwbmp( $this->imagePath );
467 break;
468 case 16: # XBM
469 $src_image = imagecreatefromxbm( $this->imagePath );
470 break;
471 default:
472 return 'Image type not supported';
473 break;
474 }
475 $height = floor( $this->height * ( $width/$this->width ) );
476 if ( $truecolor ) {
477 $dst_image = imagecreatetruecolor( $width, $height );
478 } else {
479 $dst_image = imagecreate( $width, $height );
480 }
481 imagecopyresampled( $dst_image, $src_image,
482 0,0,0,0,
483 $width, $height, $this->width, $this->height );
484 switch( $this->type ) {
485 case 1: # GIF
486 case 3: # PNG
487 case 15: # WBMP
488 case 16: # XBM
489 #$thumbUrl .= ".png";
490 #$thumbPath .= ".png";
491 imagepng( $dst_image, $thumbPath );
492 break;
493 case 2: # JPEG
494 #$thumbUrl .= ".jpg";
495 #$thumbPath .= ".jpg";
496 imageinterlace( $dst_image );
497 imagejpeg( $dst_image, $thumbPath, 95 );
498 break;
499 default:
500 break;
501 }
502 imagedestroy( $dst_image );
503 imagedestroy( $src_image );
504 }
505 #
506 # Check for zero-sized thumbnails. Those can be generated when
507 # no disk space is available or some other error occurs
508 #
509 if( file_exists( $thumbPath ) ) {
510 $thumbstat = stat( $thumbPath );
511 if( $thumbstat['size'] == 0 ) {
512 unlink( $thumbPath );
513 }
514 }
515
516 # Purge squid
517 # This has to be done after the image is updated and present for all machines on NFS,
518 # or else the old version might be stored into the squid again
519 if ( $wgUseSquid ) {
520 $urlArr = Array(
521 $wgInternalServer.$thumbUrl
522 );
523 wfPurgeSquidServers($urlArr);
524 }
525 }
526 return new ThumbnailImage( $thumbPath, $thumbUrl );
527 } // END OF function createThumb
528
529 /**
530 * Return the image history of this image, line by line.
531 * starts with current version, then old versions.
532 * uses $this->historyLine to check which line to return:
533 * 0 return line for current version
534 * 1 query for old versions, return first one
535 * 2, ... return next old version from above query
536 *
537 * @access public
538 */
539 function nextHistoryLine()
540 {
541 $fname = 'Image::nextHistoryLine()';
542 $dbr =& wfGetDB( DB_SLAVE );
543 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
544 $this->historyRes = $dbr->select( 'image',
545 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
546 array( 'img_name' => $this->title->getDBkey() ),
547 $fname
548 );
549 if ( 0 == wfNumRows( $this->historyRes ) ) {
550 return FALSE;
551 }
552 } else if ( $this->historyLine == 1 ) {
553 $this->historyRes = $dbr->select( 'oldimage',
554 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
555 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
556 ), array( 'oi_name' => $this->title->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
557 );
558 }
559 $this->historyLine ++;
560
561 return $dbr->fetchObject( $this->historyRes );
562 }
563
564 /**
565 * Reset the history pointer to the first element of the history
566 * @access public
567 */
568 function resetHistory()
569 {
570 $this->historyLine = 0;
571 }
572
573 /**
574 * Return true if the file is of a type that can't be directly
575 * rendered by typical browsers and needs to be re-rasterized.
576 * @return bool
577 */
578 function mustRender() {
579 return ( $this->extension == 'svg' );
580 }
581
582 /**
583 * Return the full filesystem path to the file. Note that this does
584 * not mean that a file actually exists under that location.
585 *
586 * This path depends on whether directory hashing is active or not,
587 * i.e. whether the images are all found in the same directory,
588 * or in hashed paths like /images/3/3c.
589 *
590 * @access public
591 * @param boolean $fromSharedDirectory Return the path to the file
592 * in a shared repository (see $wgUseSharedRepository and related
593 * options in DefaultSettings.php) instead of a local one.
594 *
595 */
596 function getFullPath( $fromSharedRepository = false )
597 {
598 global $wgUploadDirectory, $wgSharedUploadDirectory;
599 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
600
601 $dir = $fromSharedRepository ? $wgSharedUploadDirectory :
602 $wgUploadDirectory;
603 $ishashed = $fromSharedRepository ? $wgHashedSharedUploadDirectory :
604 $wgHashedUploadDirectory;
605 $name = $this->name;
606 $fullpath = $dir . wfGetHashPath($name) . $name;
607 return $fullpath;
608 }
609
610
611 } //class
612
613
614 /**
615 * Returns the image directory of an image
616 * If the directory does not exist, it is created.
617 * The result is an absolute path.
618 *
619 * @param string $fname file name of the image file
620 * @access public
621 */
622 function wfImageDir( $fname )
623 {
624 global $wgUploadDirectory, $wgHashedUploadDirectory;
625
626 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
627
628 $hash = md5( $fname );
629 $oldumask = umask(0);
630 $dest = $wgUploadDirectory . '/' . $hash{0};
631 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
632 $dest .= '/' . substr( $hash, 0, 2 );
633 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
634
635 umask( $oldumask );
636 return $dest;
637 }
638
639 /**
640 * Returns the image directory of an image's thubnail
641 * If the directory does not exist, it is created.
642 * The result is an absolute path.
643 *
644 * @param string $fname file name of the thumbnail file, including file size prefix
645 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
646 * @param boolean $shared (optional) use the shared upload directory
647 * @access public
648 */
649 function wfImageThumbDir( $fname , $subdir='thumb', $shared=false)
650 {
651 return wfImageArchiveDir( $fname, $subdir, $shared );
652 }
653
654 /**
655 * Returns the image directory of an image's old version
656 * If the directory does not exist, it is created.
657 * The result is an absolute path.
658 *
659 * @param string $fname file name of the thumbnail file, including file size prefix
660 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
661 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
662 * @access public
663 */
664 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false )
665 {
666 global $wgUploadDirectory, $wgHashedUploadDirectory,
667 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
668 $dir = $shared ? $wgSharedUploadDirectory : $wgUploadDirectory;
669 $hashdir = $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
670 if (!$hashdir) { return $dir.'/'.$subdir; }
671 $hash = md5( $fname );
672 $oldumask = umask(0);
673 # Suppress warning messages here; if the file itself can't
674 # be written we'll worry about it then.
675 $archive = $dir.'/'.$subdir;
676 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
677 $archive .= '/' . $hash{0};
678 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
679 $archive .= '/' . substr( $hash, 0, 2 );
680 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
681
682 umask( $oldumask );
683 return $archive;
684 }
685
686
687 /*
688 * Return the hash path component of an image path (URL or filesystem),
689 * e.g. "/3/3c/", or just "/" if hashing is not used.
690 *
691 * @param $dbkey The filesystem / database name of the file
692 * @param $fromSharedDirectory Use the shared file repository? It may
693 * use different hash settings from the local one.
694 */
695 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
696 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
697
698 $ishashed = $fromSharedDirectory ? $wgHashedSharedUploadDirectory :
699 $wgSharedUploadDirectory;
700 if($ishashed) {
701 $hash = md5($dbkey);
702 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . "/";
703 } else {
704 return '/';
705 }
706 }
707
708
709 /**
710 * Record an image upload in the upload log.
711 */
712 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
713 {
714 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
715 global $wgUseCopyrightUpload;
716
717 $fname = 'wfRecordUpload';
718 $dbw =& wfGetDB( DB_MASTER );
719
720 # img_name must be unique
721 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
722 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
723 }
724
725
726 $now = wfTimestampNow();
727 $won = wfInvertTimestamp( $now );
728 $size = IntVal( $size );
729
730 if ( $wgUseCopyrightUpload )
731 {
732 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
733 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
734 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
735 }
736 else $textdesc = $desc ;
737
738 $now = wfTimestampNow();
739 $won = wfInvertTimestamp( $now );
740
741 # Test to see if the row exists using INSERT IGNORE
742 # This avoids race conditions by locking the row until the commit, and also
743 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
744 $dbw->insert( 'image',
745 array(
746 'img_name' => $name,
747 'img_size'=> $size,
748 'img_timestamp' => $dbw->timestamp($now),
749 'img_description' => $desc,
750 'img_user' => $wgUser->getID(),
751 'img_user_text' => $wgUser->getName(),
752 ), $fname, 'IGNORE'
753 );
754 $descTitle = Title::makeTitleSafe( NS_IMAGE, $name );
755
756 if ( $dbw->affectedRows() ) {
757 # Successfully inserted, this is a new image
758 $id = $descTitle->getArticleID();
759
760 if ( $id == 0 ) {
761 $now = wfTimestampNow();
762 $won = wfInvertTimestamp( $now );
763
764 $text_old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
765 $dbw->insert( 'text',
766 array(
767 'old_id' => $text_old_id,
768 'old_text' => $textdesc,
769 'old_flags' => '' ),
770 $fname );
771 if ( is_null( $text_old_id ) ) $text_old_id = $dbw->insertId();
772
773 $page_page_id = $dbw->nextSequenceValue( 'page_page_id' );
774 $dbw->insert( 'page',
775 array(
776 'page_id' => $page_page_id,
777 'page_namespace' => NS_IMAGE,
778 'page_title' => $name,
779 'page_restrictions' => '',
780 'page_counter' => 0,
781 'page_is_redirect' => 0,
782 'page_is_new' => 1,
783 'page_random' => 0.5,
784 'page_touched' => $now,
785 'page_latest' => $text_old_id ),
786 $fname );
787 if ( is_null( $page_page_id ) ) $page_page_id = $dbw->insertId();
788
789 $dbw->insert( 'revision',
790 array(
791 'rev_id' => $text_old_id,
792 'rev_page' => $page_page_id,
793 'rev_comment' => $desc,
794 'rev_user' => $wgUser->getID(),
795 'rev_user_text' => $wgUser->getName(),
796 'rev_timestamp' => $now,
797 'inverse_timestamp' => $won,
798 'rev_minor_edit' => 0 ),
799 $fname );
800
801 RecentChange::notifyNew( $now, $descTitle, 0, $wgUser, $desc );
802
803 $u = new SearchUpdate( $page_page_id, $name, $desc );
804 $u->doUpdate();
805 }
806 } else {
807 # Collision, this is an update of an image
808 # Get current image row for update
809 $s = $dbw->selectRow( 'image', array( 'img_name','img_size','img_timestamp','img_description',
810 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
811
812 # Insert it into oldimage
813 $dbw->insert( 'oldimage',
814 array(
815 'oi_name' => $s->img_name,
816 'oi_archive_name' => $oldver,
817 'oi_size' => $s->img_size,
818 'oi_timestamp' => $dbw->timestamp($s->img_timestamp),
819 'oi_description' => $s->img_description,
820 'oi_user' => $s->img_user,
821 'oi_user_text' => $s->img_user_text
822 ), $fname
823 );
824
825 # Update the current image row
826 $dbw->update( 'image',
827 array( /* SET */
828 'img_size' => $size,
829 'img_timestamp' => $dbw->timestamp(),
830 'img_user' => $wgUser->getID(),
831 'img_user_text' => $wgUser->getName(),
832 'img_description' => $desc,
833 ), array( /* WHERE */
834 'img_name' => $name
835 ), $fname
836 );
837
838 # Invalidate the cache for the description page
839 $descTitle->invalidateCache();
840 }
841
842 $log = new LogPage( 'upload' );
843 $log->addEntry( 'upload', $descTitle, $desc );
844 }
845
846 /**
847 * Returns the image URL of an image's old version
848 *
849 * @param string $fname file name of the image file
850 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
851 * @access public
852 */
853 function wfImageArchiveUrl( $name, $subdir='archive' )
854 {
855 global $wgUploadPath, $wgHashedUploadDirectory;
856
857 if ($wgHashedUploadDirectory) {
858 $hash = md5( substr( $name, 15) );
859 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
860 substr( $hash, 0, 2 ) . '/'.$name;
861 } else {
862 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
863 }
864 return wfUrlencode($url);
865 }
866
867 /**
868 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
869 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
870 *
871 * @param string $length
872 * @return int Length in pixels
873 */
874 function scaleSVGUnit( $length ) {
875 static $unitLength = array(
876 'px' => 1.0,
877 'pt' => 1.25,
878 'pc' => 15.0,
879 'mm' => 3.543307,
880 'cm' => 35.43307,
881 'in' => 90.0,
882 '' => 1.0, // "User units" pixels by default
883 '%' => 2.0, // Fake it!
884 );
885 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
886 $length = FloatVal( $matches[1] );
887 $unit = $matches[2];
888 return round( $length * $unitLength[$unit] );
889 } else {
890 // Assume pixels
891 return round( FloatVal( $length ) );
892 }
893 }
894
895 /**
896 * Compatible with PHP getimagesize()
897 * @todo support gzipped SVGZ
898 * @todo check XML more carefully
899 * @todo sensible defaults
900 *
901 * @param string $filename
902 * @return array
903 */
904 function getSVGsize( $filename ) {
905 $width = 256;
906 $height = 256;
907
908 // Read a chunk of the file
909 $f = fopen( $filename, "rt" );
910 if( !$f ) return false;
911 $chunk = fread( $f, 4096 );
912 fclose( $f );
913
914 // Uber-crappy hack! Run through a real XML parser.
915 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
916 return false;
917 }
918 $tag = $matches[1];
919 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
920 $width = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
921 }
922 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
923 $height = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
924 }
925
926 return array( $width, $height, 'SVG',
927 "width=\"$width\" height=\"$height\"" );
928 }
929
930
931 /**
932 * Wrapper class for thumbnail images
933 */
934 class ThumbnailImage {
935 /**
936 * @param string $path Filesystem path to the thumb
937 * @param string $url URL path to the thumb
938 * @access private
939 */
940 function ThumbnailImage( $path, $url ) {
941 $this->url = $url;
942 $this->path = $path;
943 $size = @getimagesize( $this->path );
944 if( $size ) {
945 $this->width = $size[0];
946 $this->height = $size[1];
947 } else {
948 $this->width = 0;
949 $this->height = 0;
950 }
951 }
952
953 function getUrl() {
954 return $this->url;
955 }
956
957 /**
958 * Return HTML <img ... /> tag for the thumbnail, will include
959 * width and height attributes and a blank alt text (as required).
960 *
961 * You can set or override additional attributes by passing an
962 * associative array of name => data pairs. The data will be escaped
963 * for HTML output, so should be in plaintext.
964 *
965 * @param array $attribs
966 * @return string
967 * @access public
968 */
969 function toHtml( $attribs = array() ) {
970 $attribs['src'] = $this->url;
971 $attribs['width'] = $this->width;
972 $attribs['height'] = $this->height;
973 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
974
975 $html = '<img ';
976 foreach( $attribs as $name => $data ) {
977 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
978 }
979 $html .= '/>';
980 return $html;
981 }
982
983 /**
984 * Return the size of the thumbnail file, in bytes
985 * @access public
986 */
987 function getSize()
988 {
989 $st = stat( $this->path );
990 if( $st ) {
991 return $st['size'];
992 } else {
993 return false; }
994 }
995
996 }
997
998 ?>