52bca6e9e146c237c0eb4396dd71baddacfb11fa
[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 return $st['size'];
195 }
196
197 /**
198 * Return the type of the image
199 *
200 * - 1 GIF
201 * - 2 JPG
202 * - 3 PNG
203 * - 15 WBMP
204 * - 16 XBM
205 */
206 function getType()
207 {
208 return $this->type;
209 }
210
211 /**
212 * Return the escapeLocalURL of this image
213 * @access public
214 */
215 function getEscapeLocalURL()
216 {
217 return $this->title->escapeLocalURL();
218 }
219
220 /**
221 * Return the escapeFullURL of this image
222 * @access public
223 */
224 function getEscapeFullURL()
225 {
226 return $this->title->escapeFullURL();
227 }
228
229 /**
230 * Return the URL of an image, provided its name.
231 *
232 * @param string $name Name of the image, without the leading "Image:"
233 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
234 * @access public
235 */
236 function wfImageUrl( $name, $fromSharedDirectory = false )
237 {
238 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
239 if($fromSharedDirectory) {
240 $base = '';
241 $path = $wgSharedUploadPath;
242 } else {
243 $base = $wgUploadBaseUrl;
244 $path = $wgUploadPath;
245 }
246 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
247 return wfUrlencode( $url );
248 }
249
250 /**
251 * Returns true iff the image file exists on disk.
252 *
253 * @access public
254 */
255 function exists()
256 {
257 return $this->fileExists;
258 }
259
260 /**
261 *
262 * @access private
263 */
264 function thumbUrl( $width, $subdir='thumb') {
265 global $wgUploadPath, $wgUploadBaseUrl,
266 $wgSharedUploadPath,$wgSharedUploadDirectory,
267 $wgUseLatin1,$wgSharedLatin1;
268 $name = $this->thumbName( $width );
269 if($this->fromSharedDirectory) {
270 $base = '';
271 $path = $wgSharedUploadPath;
272 if($wgUseLatin1 && !$wgSharedLatin1) {
273 $name=utf8_encode($name);
274 }
275 } else {
276 $base = $wgUploadBaseUrl;
277 $path = $wgUploadPath;
278 }
279 $url = "{$base}{$path}/{$subdir}" .
280 wfGetHashPath($name, $this->fromSharedDirectory)
281 . "{$name}";
282 return wfUrlencode($url);
283 }
284
285 /**
286 * Return the file name of a thumbnail of the specified width
287 *
288 * @param integer $width Width of the thumbnail image
289 * @param boolean $shared Does the thumbnail come from the shared repository?
290 * @access private
291 */
292 function thumbName( $width, $shared=false ) {
293 global $wgUseLatin1,$wgSharedLatin1;
294 $thumb = $width."px-".$this->name;
295 if( $this->extension == 'svg' ) {
296 # Rasterize SVG vector images to PNG
297 $thumb .= '.png';
298 }
299 if( $shared && $wgUseLatin1 && !$wgSharedLatin1) {
300 $thumb=utf8_encode($thumb);
301 }
302 return $thumb;
303 }
304
305 /**
306 * Create a thumbnail of the image having the specified width/height.
307 * The thumbnail will not be created if the width is larger than the
308 * image's width. Let the browser do the scaling in this case.
309 * The thumbnail is stored on disk and is only computed if the thumbnail
310 * file does not exist OR if it is older than the image.
311 * Returns the URL.
312 *
313 * Keeps aspect ratio of original image. If both width and height are
314 * specified, the generated image will be no bigger than width x height,
315 * and will also have correct aspect ratio.
316 *
317 * @param integer $width maximum width of the generated thumbnail
318 * @param integer $height maximum height of the image (optional)
319 * @access public
320 */
321 function createThumb( $width, $height=-1 ) {
322 if ( $height == -1 ) {
323 return $this->renderThumb( $width );
324 }
325 if ( $width < $this->width ) {
326 $thumbheight = $this->height * $width / $this->width;
327 $thumbwidth = $width;
328 } else {
329 $thumbheight = $this->height;
330 $thumbwidth = $this->width;
331 }
332 if ( $thumbheight > $height ) {
333 $thumbwidth = $thumbwidth * $height / $thumbheight;
334 $thumbheight = $height;
335 }
336 return $this->renderThumb( $thumbwidth );
337 }
338
339 /**
340 * Create a thumbnail of the image having the specified width.
341 * The thumbnail will not be created if the width is larger than the
342 * image's width. Let the browser do the scaling in this case.
343 * The thumbnail is stored on disk and is only computed if the thumbnail
344 * file does not exist OR if it is older than the image.
345 * Returns the URL.
346 *
347 * @access private
348 */
349 function /* private */ renderThumb( $width ) {
350 global $wgImageMagickConvertCommand;
351 global $wgUseImageMagick;
352 global $wgUseSquid, $wgInternalServer;
353
354 $width = IntVal( $width );
355
356 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory );
357 $thumbPath = wfImageThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory ).'/'.$thumbName;
358 $thumbUrl = $this->thumbUrl( $width );
359 #wfDebug ( "Render name: $thumbName path: $thumbPath url: $thumbUrl\n");
360 if ( ! $this->exists() )
361 {
362 # If there is no image, there will be no thumbnail
363 return '';
364 }
365
366 # Sanity check $width
367 if( $width <= 0 ) {
368 # BZZZT
369 return '';
370 }
371
372 if( $width > $this->width && !$this->mustRender() ) {
373 # Don't make an image bigger than the source
374 return $this->getViewURL();
375 }
376
377 if ( (! file_exists( $thumbPath ) ) || ( filemtime($thumbPath) < filemtime($this->imagePath) ) ) {
378 if( $this->extension == 'svg' ) {
379 global $wgSVGConverters, $wgSVGConverter;
380 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
381 global $wgSVGConverterPath;
382 $cmd = str_replace(
383 array( '$path/', '$width', '$input', '$output' ),
384 array( $wgSVGConverterPath,
385 $width,
386 escapeshellarg( $this->imagePath ),
387 escapeshellarg( $thumbPath ) ),
388 $wgSVGConverters[$wgSVGConverter] );
389 $conv = shell_exec( $cmd );
390 } else {
391 $conv = false;
392 }
393 } elseif ( $wgUseImageMagick ) {
394 # use ImageMagick
395 # Specify white background color, will be used for transparent images
396 # in Internet Explorer/Windows instead of default black.
397 $cmd = $wgImageMagickConvertCommand .
398 " -quality 85 -background white -geometry {$width} ".
399 escapeshellarg($this->imagePath) . " " .
400 escapeshellarg($thumbPath);
401 $conv = shell_exec( $cmd );
402 } else {
403 # Use PHP's builtin GD library functions.
404 #
405 # First find out what kind of file this is, and select the correct
406 # input routine for this.
407
408 $truecolor = false;
409
410 switch( $this->type ) {
411 case 1: # GIF
412 $src_image = imagecreatefromgif( $this->imagePath );
413 break;
414 case 2: # JPG
415 $src_image = imagecreatefromjpeg( $this->imagePath );
416 $truecolor = true;
417 break;
418 case 3: # PNG
419 $src_image = imagecreatefrompng( $this->imagePath );
420 $truecolor = ( $this->bits > 8 );
421 break;
422 case 15: # WBMP for WML
423 $src_image = imagecreatefromwbmp( $this->imagePath );
424 break;
425 case 16: # XBM
426 $src_image = imagecreatefromxbm( $this->imagePath );
427 break;
428 default:
429 return 'Image type not supported';
430 break;
431 }
432 $height = floor( $this->height * ( $width/$this->width ) );
433 if ( $truecolor ) {
434 $dst_image = imagecreatetruecolor( $width, $height );
435 } else {
436 $dst_image = imagecreate( $width, $height );
437 }
438 imagecopyresampled( $dst_image, $src_image,
439 0,0,0,0,
440 $width, $height, $this->width, $this->height );
441 switch( $this->type ) {
442 case 1: # GIF
443 case 3: # PNG
444 case 15: # WBMP
445 case 16: # XBM
446 #$thumbUrl .= ".png";
447 #$thumbPath .= ".png";
448 imagepng( $dst_image, $thumbPath );
449 break;
450 case 2: # JPEG
451 #$thumbUrl .= ".jpg";
452 #$thumbPath .= ".jpg";
453 imageinterlace( $dst_image );
454 imagejpeg( $dst_image, $thumbPath, 95 );
455 break;
456 default:
457 break;
458 }
459 imagedestroy( $dst_image );
460 imagedestroy( $src_image );
461
462
463 }
464 #
465 # Check for zero-sized thumbnails. Those can be generated when
466 # no disk space is available or some other error occurs
467 #
468 $thumbstat = stat( $thumbPath );
469 if( $thumbstat['size'] == 0 )
470 {
471 unlink( $thumbPath );
472 }
473
474 # Purge squid
475 # This has to be done after the image is updated and present for all machines on NFS,
476 # or else the old version might be stored into the squid again
477 if ( $wgUseSquid ) {
478 $urlArr = Array(
479 $wgInternalServer.$thumbUrl
480 );
481 wfPurgeSquidServers($urlArr);
482 }
483 }
484 return $thumbUrl;
485 } // END OF function createThumb
486
487 /**
488 * Return the image history of this image, line by line.
489 * starts with current version, then old versions.
490 * uses $this->historyLine to check which line to return:
491 * 0 return line for current version
492 * 1 query for old versions, return first one
493 * 2, ... return next old version from above query
494 *
495 * @access public
496 */
497 function nextHistoryLine()
498 {
499 $fname = 'Image::nextHistoryLine()';
500 $dbr =& wfGetDB( DB_SLAVE );
501 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
502 $this->historyRes = $dbr->select( 'image',
503 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
504 array( 'img_name' => $this->title->getDBkey() ),
505 $fname
506 );
507 if ( 0 == wfNumRows( $this->historyRes ) ) {
508 return FALSE;
509 }
510 } else if ( $this->historyLine == 1 ) {
511 $this->historyRes = $dbr->select( 'oldimage',
512 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
513 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
514 ), array( 'oi_name' => $this->title->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
515 );
516 }
517 $this->historyLine ++;
518
519 return $dbr->fetchObject( $this->historyRes );
520 }
521
522 /**
523 * Reset the history pointer to the first element of the history
524 * @access public
525 */
526 function resetHistory()
527 {
528 $this->historyLine = 0;
529 }
530
531 /**
532 * Return true if the file is of a type that can't be directly
533 * rendered by typical browsers and needs to be re-rasterized.
534 * @return bool
535 */
536 function mustRender() {
537 return ( $this->extension == 'svg' );
538 }
539
540 /**
541 * Return the full filesystem path to the file. Note that this does
542 * not mean that a file actually exists under that location.
543 *
544 * This path depends on whether directory hashing is active or not,
545 * i.e. whether the images are all found in the same directory,
546 * or in hashed paths like /images/3/3c.
547 *
548 * @access public
549 * @param boolean $fromSharedDirectory Return the path to the file
550 * in a shared repository (see $wgUseSharedRepository and related
551 * options in DefaultSettings.php) instead of a local one.
552 *
553 */
554 function getFullPath( $fromSharedRepository = false )
555 {
556 global $wgUploadDirectory, $wgSharedUploadDirectory;
557
558 $dir = $fromSharedRepository ? $wgSharedUploadDirectory :
559 $wgUploadDirectory;
560 $ishashed = $fromSharedRepository ? $wgHashedSharedUploadDirectory :
561 $wgHashedUploadDirectory;
562 $name = $this->name;
563 $fullpath = $dir . wfGetHashPath($name) . $name;
564 return $fullpath;
565 }
566
567
568 } //class
569
570
571 /**
572 * Returns the image directory of an image
573 * If the directory does not exist, it is created.
574 * The result is an absolute path.
575 *
576 * @param string $fname file name of the image file
577 * @access public
578 */
579 function wfImageDir( $fname )
580 {
581 global $wgUploadDirectory, $wgHashedUploadDirectory;
582
583 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
584
585 $hash = md5( $fname );
586 $oldumask = umask(0);
587 $dest = $wgUploadDirectory . '/' . $hash{0};
588 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
589 $dest .= '/' . substr( $hash, 0, 2 );
590 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
591
592 umask( $oldumask );
593 return $dest;
594 }
595
596 /**
597 * Returns the image directory of an image's thubnail
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 thumbnail file, including file size prefix
602 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
603 * @param boolean $shared (optional) use the shared upload directory
604 * @access public
605 */
606 function wfImageThumbDir( $fname , $subdir='thumb', $shared=false)
607 {
608 return wfImageArchiveDir( $fname, $subdir, $shared );
609 }
610
611 /**
612 * Returns the image directory of an image's old version
613 * If the directory does not exist, it is created.
614 * The result is an absolute path.
615 *
616 * @param string $fname file name of the thumbnail file, including file size prefix
617 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
618 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
619 * @access public
620 */
621 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false )
622 {
623 global $wgUploadDirectory, $wgHashedUploadDirectory,
624 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
625 $dir = $shared ? $wgSharedUploadDirectory : $wgUploadDirectory;
626 $hashdir = $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
627 if (!$hashdir) { return $dir.'/'.$subdir; }
628 $hash = md5( $fname );
629 $oldumask = umask(0);
630 # Suppress warning messages here; if the file itself can't
631 # be written we'll worry about it then.
632 $archive = $dir.'/'.$subdir;
633 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
634 $archive .= '/' . $hash{0};
635 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
636 $archive .= '/' . substr( $hash, 0, 2 );
637 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
638
639 umask( $oldumask );
640 return $archive;
641 }
642
643
644 /*
645 * Return the hash path component of an image path (URL or filesystem),
646 * e.g. "/3/3c/", or just "/" if hashing is not used.
647 *
648 * @param $dbkey The filesystem / database name of the file
649 * @param $fromSharedDirectory Use the shared file repository? It may
650 * use different hash settings from the local one.
651 */
652 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
653 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
654
655 $ishashed = $fromSharedDirectory ? $wgHashedSharedUploadDirectory :
656 $wgSharedUploadDirectory;
657 if($ishashed) {
658 $hash = md5($dbkey);
659 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . "/";
660 } else {
661 return '/';
662 }
663 }
664
665
666 /**
667 * Record an image upload in the upload log.
668 */
669 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
670 {
671 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
672 global $wgUseCopyrightUpload;
673
674 $fname = 'wfRecordUpload';
675 $dbw =& wfGetDB( DB_MASTER );
676
677 # img_name must be unique
678 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
679 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
680 }
681
682
683 $now = wfTimestampNow();
684 $won = wfInvertTimestamp( $now );
685 $size = IntVal( $size );
686
687 if ( $wgUseCopyrightUpload )
688 {
689 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
690 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
691 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
692 }
693 else $textdesc = $desc ;
694
695 $now = wfTimestampNow();
696 $won = wfInvertTimestamp( $now );
697
698 # Test to see if the row exists using INSERT IGNORE
699 # This avoids race conditions by locking the row until the commit, and also
700 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
701 $dbw->insert( 'image',
702 array(
703 'img_name' => $name,
704 'img_size'=> $size,
705 'img_timestamp' => $dbw->timestamp($now),
706 'img_description' => $desc,
707 'img_user' => $wgUser->getID(),
708 'img_user_text' => $wgUser->getName(),
709 ), $fname, 'IGNORE'
710 );
711 $descTitle = Title::makeTitleSafe( NS_IMAGE, $name );
712
713 if ( $dbw->affectedRows() ) {
714 # Successfully inserted, this is a new image
715 $id = $descTitle->getArticleID();
716
717 if ( $id == 0 ) {
718 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
719 $dbw->insert( 'cur',
720 array(
721 'cur_id' => $seqVal,
722 'cur_namespace' => NS_IMAGE,
723 'cur_title' => $name,
724 'cur_comment' => $desc,
725 'cur_user' => $wgUser->getID(),
726 'cur_user_text' => $wgUser->getName(),
727 'cur_timestamp' => $dbw->timestamp($now),
728 'cur_is_new' => 1,
729 'cur_text' => $textdesc,
730 'inverse_timestamp' => $won,
731 'cur_touched' => $dbw->timestamp($now)
732 ), $fname
733 );
734 $id = $dbw->insertId() or 0; # We should throw an error instead
735
736 RecentChange::notifyNew( $now, $descTitle, 0, $wgUser, $desc );
737
738 $u = new SearchUpdate( $id, $name, $desc );
739 $u->doUpdate();
740 }
741 } else {
742 # Collision, this is an update of an image
743 # Get current image row for update
744 $s = $dbw->selectRow( 'image', array( 'img_name','img_size','img_timestamp','img_description',
745 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
746
747 # Insert it into oldimage
748 $dbw->insert( 'oldimage',
749 array(
750 'oi_name' => $s->img_name,
751 'oi_archive_name' => $oldver,
752 'oi_size' => $s->img_size,
753 'oi_timestamp' => $dbw->timestamp($s->img_timestamp),
754 'oi_description' => $s->img_description,
755 'oi_user' => $s->img_user,
756 'oi_user_text' => $s->img_user_text
757 ), $fname
758 );
759
760 # Update the current image row
761 $dbw->update( 'image',
762 array( /* SET */
763 'img_size' => $size,
764 'img_timestamp' => $dbw->timestamp(),
765 'img_user' => $wgUser->getID(),
766 'img_user_text' => $wgUser->getName(),
767 'img_description' => $desc,
768 ), array( /* WHERE */
769 'img_name' => $name
770 ), $fname
771 );
772
773 # Invalidate the cache for the description page
774 $descTitle->invalidateCache();
775 }
776
777 $log = new LogPage( 'upload' );
778 $log->addEntry( 'upload', $descTitle, $desc );
779 }
780
781 /**
782 * Returns the image URL of an image's old version
783 *
784 * @param string $fname file name of the image file
785 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
786 * @access public
787 */
788 function wfImageArchiveUrl( $name, $subdir='archive' )
789 {
790 global $wgUploadPath, $wgHashedUploadDirectory;
791
792 if ($wgHashedUploadDirectory) {
793 $hash = md5( substr( $name, 15) );
794 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
795 substr( $hash, 0, 2 ) . '/'.$name;
796 } else {
797 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
798 }
799 return wfUrlencode($url);
800 }
801
802 /**
803 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
804 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
805 *
806 * @param string $length
807 * @return int Length in pixels
808 */
809 function scaleSVGUnit( $length ) {
810 static $unitLength = array(
811 'px' => 1.0,
812 'pt' => 1.25,
813 'pc' => 15.0,
814 'mm' => 3.543307,
815 'cm' => 35.43307,
816 'in' => 90.0,
817 '' => 1.0, // "User units" pixels by default
818 '%' => 2.0, // Fake it!
819 );
820 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
821 $length = FloatVal( $matches[1] );
822 $unit = $matches[2];
823 return round( $length * $unitLength[$unit] );
824 } else {
825 // Assume pixels
826 return round( FloatVal( $length ) );
827 }
828 }
829
830 /**
831 * Compatible with PHP getimagesize()
832 * @todo support gzipped SVGZ
833 * @todo check XML more carefully
834 * @todo sensible defaults
835 *
836 * @param string $filename
837 * @return array
838 */
839 function getSVGsize( $filename ) {
840 $width = 256;
841 $height = 256;
842
843 // Read a chunk of the file
844 $f = fopen( $filename, "rt" );
845 if( !$f ) return false;
846 $chunk = fread( $f, 4096 );
847 fclose( $f );
848
849 // Uber-crappy hack! Run through a real XML parser.
850 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
851 return false;
852 }
853 $tag = $matches[1];
854 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
855 $width = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
856 }
857 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
858 $height = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
859 }
860
861 return array( $width, $height, 'SVG',
862 "width=\"$width\" height=\"$height\"" );
863 }
864
865 ?>