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