correct image path hashing
[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 $name = $this->name;
587 $fullpath = $dir . wfGetHashPath($name, $fromSharedRepository) . $name;
588 return $fullpath;
589 }
590
591 } //class
592
593
594 /**
595 * Returns the image directory of an image
596 * If the directory does not exist, it is created.
597 * The result is an absolute path.
598 *
599 * @param string $fname file name of the image file
600 * @access public
601 */
602 function wfImageDir( $fname ) {
603 global $wgUploadDirectory, $wgHashedUploadDirectory;
604
605 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
606
607 $hash = md5( $fname );
608 $oldumask = umask(0);
609 $dest = $wgUploadDirectory . '/' . $hash{0};
610 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
611 $dest .= '/' . substr( $hash, 0, 2 );
612 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
613
614 umask( $oldumask );
615 return $dest;
616 }
617
618 /**
619 * Returns the image directory of an image's thubnail
620 * If the directory does not exist, it is created.
621 * The result is an absolute path.
622 *
623 * @param string $fname file name of the thumbnail file, including file size prefix
624 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
625 * @param boolean $shared (optional) use the shared upload directory
626 * @access public
627 */
628 function wfImageThumbDir( $fname , $subdir='thumb', $shared=false) {
629 return wfImageArchiveDir( $fname, $subdir, $shared );
630 }
631
632 /**
633 * Returns the image directory of an image's old version
634 * If the directory does not exist, it is created.
635 * The result is an absolute path.
636 *
637 * @param string $fname file name of the thumbnail file, including file size prefix
638 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
639 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
640 * @access public
641 */
642 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
643 global $wgUploadDirectory, $wgHashedUploadDirectory,
644 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
645 $dir = $shared ? $wgSharedUploadDirectory : $wgUploadDirectory;
646 $hashdir = $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
647 if (!$hashdir) { return $dir.'/'.$subdir; }
648 $hash = md5( $fname );
649 $oldumask = umask(0);
650 # Suppress warning messages here; if the file itself can't
651 # be written we'll worry about it then.
652 $archive = $dir.'/'.$subdir;
653 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
654 $archive .= '/' . $hash{0};
655 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
656 $archive .= '/' . substr( $hash, 0, 2 );
657 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
658
659 umask( $oldumask );
660 return $archive;
661 }
662
663
664 /*
665 * Return the hash path component of an image path (URL or filesystem),
666 * e.g. "/3/3c/", or just "/" if hashing is not used.
667 *
668 * @param $dbkey The filesystem / database name of the file
669 * @param $fromSharedDirectory Use the shared file repository? It may
670 * use different hash settings from the local one.
671 */
672 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
673 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
674
675 $ishashed = $fromSharedDirectory ? $wgHashedSharedUploadDirectory :
676 $wgHashedUploadDirectory;
677 if($ishashed) {
678 $hash = md5($dbkey);
679 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
680 } else {
681 return '/';
682 }
683 }
684
685
686 /**
687 * Record an image upload in the upload log.
688 */
689 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = '', $source = '' ) {
690 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
691 global $wgUseCopyrightUpload;
692
693 $fname = 'wfRecordUpload';
694 $dbw =& wfGetDB( DB_MASTER );
695
696 # img_name must be unique
697 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
698 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
699 }
700
701
702 $now = wfTimestampNow();
703 $won = wfInvertTimestamp( $now );
704 $size = IntVal( $size );
705
706 if ( $wgUseCopyrightUpload ) {
707 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
708 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
709 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
710 }
711 else $textdesc = $desc ;
712
713 $now = wfTimestampNow();
714 $won = wfInvertTimestamp( $now );
715
716 # Test to see if the row exists using INSERT IGNORE
717 # This avoids race conditions by locking the row until the commit, and also
718 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
719 $dbw->insert( 'image',
720 array(
721 'img_name' => $name,
722 'img_size'=> $size,
723 'img_timestamp' => $dbw->timestamp($now),
724 'img_description' => $desc,
725 'img_user' => $wgUser->getID(),
726 'img_user_text' => $wgUser->getName(),
727 ), $fname, 'IGNORE'
728 );
729 $descTitle = Title::makeTitleSafe( NS_IMAGE, $name );
730
731 if ( $dbw->affectedRows() ) {
732 # Successfully inserted, this is a new image
733 $id = $descTitle->getArticleID();
734
735 if ( $id == 0 ) {
736 $article = new Article( $descTitle );
737 $article->insertNewArticle( $textdesc, $desc, false, false );
738 }
739 } else {
740 # Collision, this is an update of an image
741 # Get current image row for update
742 $s = $dbw->selectRow( 'image', array( 'img_name','img_size','img_timestamp','img_description',
743 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
744
745 # Insert it into oldimage
746 $dbw->insert( 'oldimage',
747 array(
748 'oi_name' => $s->img_name,
749 'oi_archive_name' => $oldver,
750 'oi_size' => $s->img_size,
751 'oi_timestamp' => $dbw->timestamp($s->img_timestamp),
752 'oi_description' => $s->img_description,
753 'oi_user' => $s->img_user,
754 'oi_user_text' => $s->img_user_text
755 ), $fname
756 );
757
758 # Update the current image row
759 $dbw->update( 'image',
760 array( /* SET */
761 'img_size' => $size,
762 'img_timestamp' => $dbw->timestamp(),
763 'img_user' => $wgUser->getID(),
764 'img_user_text' => $wgUser->getName(),
765 'img_description' => $desc,
766 ), array( /* WHERE */
767 'img_name' => $name
768 ), $fname
769 );
770
771 # Invalidate the cache for the description page
772 $descTitle->invalidateCache();
773 }
774
775 $log = new LogPage( 'upload' );
776 $log->addEntry( 'upload', $descTitle, $desc );
777 }
778
779 /**
780 * Returns the image URL of an image's old version
781 *
782 * @param string $fname file name of the image file
783 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
784 * @access public
785 */
786 function wfImageArchiveUrl( $name, $subdir='archive' ) {
787 global $wgUploadPath, $wgHashedUploadDirectory;
788
789 if ($wgHashedUploadDirectory) {
790 $hash = md5( substr( $name, 15) );
791 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
792 substr( $hash, 0, 2 ) . '/'.$name;
793 } else {
794 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
795 }
796 return wfUrlencode($url);
797 }
798
799 /**
800 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
801 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
802 *
803 * @param string $length
804 * @return int Length in pixels
805 */
806 function scaleSVGUnit( $length ) {
807 static $unitLength = array(
808 'px' => 1.0,
809 'pt' => 1.25,
810 'pc' => 15.0,
811 'mm' => 3.543307,
812 'cm' => 35.43307,
813 'in' => 90.0,
814 '' => 1.0, // "User units" pixels by default
815 '%' => 2.0, // Fake it!
816 );
817 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
818 $length = FloatVal( $matches[1] );
819 $unit = $matches[2];
820 return round( $length * $unitLength[$unit] );
821 } else {
822 // Assume pixels
823 return round( FloatVal( $length ) );
824 }
825 }
826
827 /**
828 * Compatible with PHP getimagesize()
829 * @todo support gzipped SVGZ
830 * @todo check XML more carefully
831 * @todo sensible defaults
832 *
833 * @param string $filename
834 * @return array
835 */
836 function getSVGsize( $filename ) {
837 $width = 256;
838 $height = 256;
839
840 // Read a chunk of the file
841 $f = fopen( $filename, "rt" );
842 if( !$f ) return false;
843 $chunk = fread( $f, 4096 );
844 fclose( $f );
845
846 // Uber-crappy hack! Run through a real XML parser.
847 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
848 return false;
849 }
850 $tag = $matches[1];
851 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
852 $width = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
853 }
854 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
855 $height = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
856 }
857
858 return array( $width, $height, 'SVG',
859 "width=\"$width\" height=\"$height\"" );
860 }
861
862
863 /**
864 * Wrapper class for thumbnail images
865 * @package MediaWiki
866 */
867 class ThumbnailImage {
868 /**
869 * @param string $path Filesystem path to the thumb
870 * @param string $url URL path to the thumb
871 * @access private
872 */
873 function ThumbnailImage( $path, $url ) {
874 $this->url = $url;
875 $this->path = $path;
876 $size = @getimagesize( $this->path );
877 if( $size ) {
878 $this->width = $size[0];
879 $this->height = $size[1];
880 } else {
881 $this->width = 0;
882 $this->height = 0;
883 }
884 }
885
886 /**
887 * @return string The thumbnail URL
888 */
889 function getUrl() {
890 return $this->url;
891 }
892
893 /**
894 * Return HTML <img ... /> tag for the thumbnail, will include
895 * width and height attributes and a blank alt text (as required).
896 *
897 * You can set or override additional attributes by passing an
898 * associative array of name => data pairs. The data will be escaped
899 * for HTML output, so should be in plaintext.
900 *
901 * @param array $attribs
902 * @return string
903 * @access public
904 */
905 function toHtml( $attribs = array() ) {
906 $attribs['src'] = $this->url;
907 $attribs['width'] = $this->width;
908 $attribs['height'] = $this->height;
909 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
910
911 $html = '<img ';
912 foreach( $attribs as $name => $data ) {
913 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
914 }
915 $html .= '/>';
916 return $html;
917 }
918
919 /**
920 * Return the size of the thumbnail file, in bytes or false if the file
921 * can't be stat().
922 * @access public
923 */
924 function getSize() {
925 $st = stat( $this->path );
926 if( $st ) {
927 return $st['size'];
928 } else {
929 return false;
930 }
931 }
932 }
933 ?>