90c4a9f745c96eb3cb74c68fb4a17071497917f7
[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 $thumbstat = stat( $thumbPath );
510 if( $thumbstat['size'] == 0 )
511 {
512 unlink( $thumbPath );
513 }
514
515 # Purge squid
516 # This has to be done after the image is updated and present for all machines on NFS,
517 # or else the old version might be stored into the squid again
518 if ( $wgUseSquid ) {
519 $urlArr = Array(
520 $wgInternalServer.$thumbUrl
521 );
522 wfPurgeSquidServers($urlArr);
523 }
524 }
525 return new ThumbnailImage( $thumbPath, $thumbUrl );
526 } // END OF function createThumb
527
528 /**
529 * Return the image history of this image, line by line.
530 * starts with current version, then old versions.
531 * uses $this->historyLine to check which line to return:
532 * 0 return line for current version
533 * 1 query for old versions, return first one
534 * 2, ... return next old version from above query
535 *
536 * @access public
537 */
538 function nextHistoryLine()
539 {
540 $fname = 'Image::nextHistoryLine()';
541 $dbr =& wfGetDB( DB_SLAVE );
542 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
543 $this->historyRes = $dbr->select( 'image',
544 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
545 array( 'img_name' => $this->title->getDBkey() ),
546 $fname
547 );
548 if ( 0 == wfNumRows( $this->historyRes ) ) {
549 return FALSE;
550 }
551 } else if ( $this->historyLine == 1 ) {
552 $this->historyRes = $dbr->select( 'oldimage',
553 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
554 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
555 ), array( 'oi_name' => $this->title->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
556 );
557 }
558 $this->historyLine ++;
559
560 return $dbr->fetchObject( $this->historyRes );
561 }
562
563 /**
564 * Reset the history pointer to the first element of the history
565 * @access public
566 */
567 function resetHistory()
568 {
569 $this->historyLine = 0;
570 }
571
572 /**
573 * Return true if the file is of a type that can't be directly
574 * rendered by typical browsers and needs to be re-rasterized.
575 * @return bool
576 */
577 function mustRender() {
578 return ( $this->extension == 'svg' );
579 }
580
581 /**
582 * Return the full filesystem path to the file. Note that this does
583 * not mean that a file actually exists under that location.
584 *
585 * This path depends on whether directory hashing is active or not,
586 * i.e. whether the images are all found in the same directory,
587 * or in hashed paths like /images/3/3c.
588 *
589 * @access public
590 * @param boolean $fromSharedDirectory Return the path to the file
591 * in a shared repository (see $wgUseSharedRepository and related
592 * options in DefaultSettings.php) instead of a local one.
593 *
594 */
595 function getFullPath( $fromSharedRepository = false )
596 {
597 global $wgUploadDirectory, $wgSharedUploadDirectory;
598 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
599
600 $dir = $fromSharedRepository ? $wgSharedUploadDirectory :
601 $wgUploadDirectory;
602 $ishashed = $fromSharedRepository ? $wgHashedSharedUploadDirectory :
603 $wgHashedUploadDirectory;
604 $name = $this->name;
605 $fullpath = $dir . wfGetHashPath($name) . $name;
606 return $fullpath;
607 }
608
609
610 } //class
611
612
613 /**
614 * Returns the image directory of an image
615 * If the directory does not exist, it is created.
616 * The result is an absolute path.
617 *
618 * @param string $fname file name of the image file
619 * @access public
620 */
621 function wfImageDir( $fname )
622 {
623 global $wgUploadDirectory, $wgHashedUploadDirectory;
624
625 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
626
627 $hash = md5( $fname );
628 $oldumask = umask(0);
629 $dest = $wgUploadDirectory . '/' . $hash{0};
630 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
631 $dest .= '/' . substr( $hash, 0, 2 );
632 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
633
634 umask( $oldumask );
635 return $dest;
636 }
637
638 /**
639 * Returns the image directory of an image's thubnail
640 * If the directory does not exist, it is created.
641 * The result is an absolute path.
642 *
643 * @param string $fname file name of the thumbnail file, including file size prefix
644 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
645 * @param boolean $shared (optional) use the shared upload directory
646 * @access public
647 */
648 function wfImageThumbDir( $fname , $subdir='thumb', $shared=false)
649 {
650 return wfImageArchiveDir( $fname, $subdir, $shared );
651 }
652
653 /**
654 * Returns the image directory of an image's old version
655 * If the directory does not exist, it is created.
656 * The result is an absolute path.
657 *
658 * @param string $fname file name of the thumbnail file, including file size prefix
659 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
660 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
661 * @access public
662 */
663 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false )
664 {
665 global $wgUploadDirectory, $wgHashedUploadDirectory,
666 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
667 $dir = $shared ? $wgSharedUploadDirectory : $wgUploadDirectory;
668 $hashdir = $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
669 if (!$hashdir) { return $dir.'/'.$subdir; }
670 $hash = md5( $fname );
671 $oldumask = umask(0);
672 # Suppress warning messages here; if the file itself can't
673 # be written we'll worry about it then.
674 $archive = $dir.'/'.$subdir;
675 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
676 $archive .= '/' . $hash{0};
677 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
678 $archive .= '/' . substr( $hash, 0, 2 );
679 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
680
681 umask( $oldumask );
682 return $archive;
683 }
684
685
686 /*
687 * Return the hash path component of an image path (URL or filesystem),
688 * e.g. "/3/3c/", or just "/" if hashing is not used.
689 *
690 * @param $dbkey The filesystem / database name of the file
691 * @param $fromSharedDirectory Use the shared file repository? It may
692 * use different hash settings from the local one.
693 */
694 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
695 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
696
697 $ishashed = $fromSharedDirectory ? $wgHashedSharedUploadDirectory :
698 $wgSharedUploadDirectory;
699 if($ishashed) {
700 $hash = md5($dbkey);
701 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . "/";
702 } else {
703 return '/';
704 }
705 }
706
707
708 /**
709 * Record an image upload in the upload log.
710 */
711 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
712 {
713 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
714 global $wgUseCopyrightUpload;
715
716 $fname = 'wfRecordUpload';
717 $dbw =& wfGetDB( DB_MASTER );
718
719 # img_name must be unique
720 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
721 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
722 }
723
724
725 $now = wfTimestampNow();
726 $won = wfInvertTimestamp( $now );
727 $size = IntVal( $size );
728
729 if ( $wgUseCopyrightUpload )
730 {
731 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
732 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
733 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
734 }
735 else $textdesc = $desc ;
736
737 $now = wfTimestampNow();
738 $won = wfInvertTimestamp( $now );
739
740 # Test to see if the row exists using INSERT IGNORE
741 # This avoids race conditions by locking the row until the commit, and also
742 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
743 $dbw->insert( 'image',
744 array(
745 'img_name' => $name,
746 'img_size'=> $size,
747 'img_timestamp' => $dbw->timestamp($now),
748 'img_description' => $desc,
749 'img_user' => $wgUser->getID(),
750 'img_user_text' => $wgUser->getName(),
751 ), $fname, 'IGNORE'
752 );
753 $descTitle = Title::makeTitleSafe( NS_IMAGE, $name );
754
755 if ( $dbw->affectedRows() ) {
756 # Successfully inserted, this is a new image
757 $id = $descTitle->getArticleID();
758
759 if ( $id == 0 ) {
760 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
761 $dbw->insert( 'cur',
762 array(
763 'cur_id' => $seqVal,
764 'cur_namespace' => NS_IMAGE,
765 'cur_title' => $name,
766 'cur_comment' => $desc,
767 'cur_user' => $wgUser->getID(),
768 'cur_user_text' => $wgUser->getName(),
769 'cur_timestamp' => $dbw->timestamp($now),
770 'cur_is_new' => 1,
771 'cur_text' => $textdesc,
772 'inverse_timestamp' => $won,
773 'cur_touched' => $dbw->timestamp($now)
774 ), $fname
775 );
776 $id = $dbw->insertId() or 0; # We should throw an error instead
777
778 RecentChange::notifyNew( $now, $descTitle, 0, $wgUser, $desc );
779
780 $u = new SearchUpdate( $id, $name, $desc );
781 $u->doUpdate();
782 }
783 } else {
784 # Collision, this is an update of an image
785 # Get current image row for update
786 $s = $dbw->selectRow( 'image', array( 'img_name','img_size','img_timestamp','img_description',
787 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
788
789 # Insert it into oldimage
790 $dbw->insert( 'oldimage',
791 array(
792 'oi_name' => $s->img_name,
793 'oi_archive_name' => $oldver,
794 'oi_size' => $s->img_size,
795 'oi_timestamp' => $dbw->timestamp($s->img_timestamp),
796 'oi_description' => $s->img_description,
797 'oi_user' => $s->img_user,
798 'oi_user_text' => $s->img_user_text
799 ), $fname
800 );
801
802 # Update the current image row
803 $dbw->update( 'image',
804 array( /* SET */
805 'img_size' => $size,
806 'img_timestamp' => $dbw->timestamp(),
807 'img_user' => $wgUser->getID(),
808 'img_user_text' => $wgUser->getName(),
809 'img_description' => $desc,
810 ), array( /* WHERE */
811 'img_name' => $name
812 ), $fname
813 );
814
815 # Invalidate the cache for the description page
816 $descTitle->invalidateCache();
817 }
818
819 $log = new LogPage( 'upload' );
820 $log->addEntry( 'upload', $descTitle, $desc );
821 }
822
823 /**
824 * Returns the image URL of an image's old version
825 *
826 * @param string $fname file name of the image file
827 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
828 * @access public
829 */
830 function wfImageArchiveUrl( $name, $subdir='archive' )
831 {
832 global $wgUploadPath, $wgHashedUploadDirectory;
833
834 if ($wgHashedUploadDirectory) {
835 $hash = md5( substr( $name, 15) );
836 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
837 substr( $hash, 0, 2 ) . '/'.$name;
838 } else {
839 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
840 }
841 return wfUrlencode($url);
842 }
843
844 /**
845 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
846 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
847 *
848 * @param string $length
849 * @return int Length in pixels
850 */
851 function scaleSVGUnit( $length ) {
852 static $unitLength = array(
853 'px' => 1.0,
854 'pt' => 1.25,
855 'pc' => 15.0,
856 'mm' => 3.543307,
857 'cm' => 35.43307,
858 'in' => 90.0,
859 '' => 1.0, // "User units" pixels by default
860 '%' => 2.0, // Fake it!
861 );
862 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
863 $length = FloatVal( $matches[1] );
864 $unit = $matches[2];
865 return round( $length * $unitLength[$unit] );
866 } else {
867 // Assume pixels
868 return round( FloatVal( $length ) );
869 }
870 }
871
872 /**
873 * Compatible with PHP getimagesize()
874 * @todo support gzipped SVGZ
875 * @todo check XML more carefully
876 * @todo sensible defaults
877 *
878 * @param string $filename
879 * @return array
880 */
881 function getSVGsize( $filename ) {
882 $width = 256;
883 $height = 256;
884
885 // Read a chunk of the file
886 $f = fopen( $filename, "rt" );
887 if( !$f ) return false;
888 $chunk = fread( $f, 4096 );
889 fclose( $f );
890
891 // Uber-crappy hack! Run through a real XML parser.
892 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
893 return false;
894 }
895 $tag = $matches[1];
896 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
897 $width = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
898 }
899 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
900 $height = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
901 }
902
903 return array( $width, $height, 'SVG',
904 "width=\"$width\" height=\"$height\"" );
905 }
906
907
908 /**
909 * Wrapper class for thumbnail images
910 */
911 class ThumbnailImage {
912 /**
913 * @param string $path Filesystem path to the thumb
914 * @param string $url URL path to the thumb
915 * @access private
916 */
917 function ThumbnailImage( $path, $url ) {
918 $this->url = $url;
919 $this->path = $path;
920 $size = @getimagesize( $this->path );
921 if( $size ) {
922 $this->width = $size[0];
923 $this->height = $size[1];
924 } else {
925 $this->width = 0;
926 $this->height = 0;
927 }
928 }
929
930 function getUrl() {
931 return $this->url;
932 }
933
934 /**
935 * Return HTML <img ... /> tag for the thumbnail, will include
936 * width and height attributes and a blank alt text (as required).
937 *
938 * You can set or override additional attributes by passing an
939 * associative array of name => data pairs. The data will be escaped
940 * for HTML output, so should be in plaintext.
941 *
942 * @param array $attribs
943 * @return string
944 * @access public
945 */
946 function toHtml( $attribs = array() ) {
947 $attribs['src'] = $this->url;
948 $attribs['width'] = $this->width;
949 $attribs['height'] = $this->height;
950 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
951
952 $html = '<img ';
953 foreach( $attribs as $name => $data ) {
954 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
955 }
956 $html .= '/>';
957 return $html;
958 }
959 }
960
961 ?>