capitalize filename so that wikis with $wgCapitalLinks=false can access
[lhc/web/wiklou.git] / includes / Image.php
1 <?php
2 /**
3 * @package MediaWiki
4 * $Id$
5 */
6
7 /**
8 * Class to represent an image
9 *
10 * Provides methods to retrieve paths (physical, logical, URL),
11 * to generate thumbnails or for uploading.
12 * @package MediaWiki
13 */
14 class Image
15 {
16 /**#@+
17 * @access private
18 */
19 var $name, # name of the image
20 $imagePath, # Path of the image
21 $url, # Image URL
22 $title, # Title object for this image. Initialized when needed.
23 $fileExists, # does the image file exist on disk?
24 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory
25 $historyLine, # Number of line to return by nextHistoryLine()
26 $historyRes, # result of the query for the image's history
27 $width, # \
28 $height, # |
29 $bits, # --- returned by getimagesize, see http://de3.php.net/manual/en/function.getimagesize.php
30 $type, # |
31 $attr; # /
32
33 /**#@-*/
34
35
36 /**
37 * Create an Image object from an image name
38 *
39 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
40 * @access public
41 */
42 function Image( $name )
43 {
44 global $wgUploadDirectory,$wgHashedUploadDirectory,
45 $wgUseSharedUploads, $wgSharedUploadDirectory,
46 $wgHashedSharedUploadDirectory;
47
48 $this->name = $name;
49 $this->title = Title::makeTitleSafe( NS_IMAGE, $this->name );
50 $this->fromSharedDirectory = false;
51
52 if ($wgHashedUploadDirectory) {
53 $hash = md5( $this->title->getDBkey() );
54 $this->imagePath = $wgUploadDirectory . '/' . $hash{0} . '/' .
55 substr( $hash, 0, 2 ) . "/{$name}";
56 } else {
57 $this->imagePath = $wgUploadDirectory . '/' . $name;
58 }
59 $this->fileExists = file_exists( $this->imagePath);
60
61 # If the file is not found, and a shared upload directory
62 # like the Wikimedia Commons is used, look for it there.
63 if (!$this->fileExists && $wgUseSharedUploads) {
64 # in case we're running a capitallinks=false wiki
65 $sharedname=ucfirst($name);
66
67 if($wgHashedSharedUploadDirectory) {
68 $hash = md5( $this->title->getDBkey() );
69 $this->imagePath = $wgSharedUploadDirectory . '/' . $hash{0} . '/' .
70 substr( $hash, 0, 2 ) . "/".$sharedname;
71 } else {
72 $this->imagePath = $wgSharedUploadDirectory . '/' . $sharedname;
73 }
74 $this->fileExists = file_exists( $this->imagePath);
75 $this->fromSharedDirectory = true;
76 #wfDebug ("File from shared directory: ".$this->imagePath."\n");
77 }
78 if($this->fileExists) {
79 $this->url = $this->wfImageUrl( $name, $this->fromSharedDirectory );
80 } else {
81 $this->url='';
82 }
83
84 $n = strrpos( $name, '.' );
85 $this->extension = strtolower( $n ? substr( $name, $n + 1 ) : '' );
86
87
88 if ( $this->fileExists )
89 {
90 if( $this->extension == 'svg' ) {
91 @$gis = getSVGsize( $this->imagePath );
92 } else {
93 @$gis = getimagesize( $this->imagePath );
94 }
95 if( $gis !== false ) {
96 $this->width = $gis[0];
97 $this->height = $gis[1];
98 $this->type = $gis[2];
99 $this->attr = $gis[3];
100 if ( isset( $gis['bits'] ) ) {
101 $this->bits = $gis['bits'];
102 } else {
103 $this->bits = 0;
104 }
105 }
106 }
107 $this->historyLine = 0;
108 }
109
110 /**
111 * Factory function
112 *
113 * Create a new image object from a title object.
114 *
115 * @param Title $nt Title object. Must be from namespace "image"
116 * @access public
117 */
118 function newFromTitle( $nt )
119 {
120 $img = new Image( $nt->getDBKey() );
121 $img->title = $nt;
122 return $img;
123 }
124
125 /**
126 * Return the name of this image
127 * @access public
128 */
129 function getName()
130 {
131 return $this->name;
132 }
133
134 /**
135 * Return the associated title object
136 * @access public
137 */
138 function getTitle()
139 {
140 return $this->title;
141 }
142
143 /**
144 * Return the URL of the image file
145 * @access public
146 */
147 function getURL()
148 {
149 return $this->url;
150 }
151
152 function getViewURL() {
153 if( $this->mustRender() ) {
154 return $this->createThumb( $this->getWidth() );
155 } else {
156 return $this->getURL();
157 }
158 }
159
160 /**
161 * Return the image path of the image in the
162 * local file system as an absolute path
163 * @access public
164 */
165 function getImagePath()
166 {
167 return $this->imagePath;
168 }
169
170 /**
171 * Return the width of the image
172 *
173 * Returns -1 if the file specified is not a known image type
174 * @access public
175 */
176 function getWidth()
177 {
178 return $this->width;
179 }
180
181 /**
182 * Return the height of the image
183 *
184 * Returns -1 if the file specified is not a known image type
185 * @access public
186 */
187 function getHeight()
188 {
189 return $this->height;
190 }
191
192 /**
193 * Return the size of the image file, in bytes
194 * @access public
195 */
196 function getSize()
197 {
198 $st = stat( $this->getImagePath() );
199 return $st['size'];
200 }
201
202 /**
203 * Return the type of the image
204 *
205 * - 1 GIF
206 * - 2 JPG
207 * - 3 PNG
208 * - 15 WBMP
209 * - 16 XBM
210 */
211 function getType()
212 {
213 return $this->type;
214 }
215
216 /**
217 * Return the escapeLocalURL of this image
218 * @access public
219 */
220 function getEscapeLocalURL()
221 {
222 return $this->title->escapeLocalURL();
223 }
224
225 /**
226 * Return the escapeFullURL of this image
227 * @access public
228 */
229 function getEscapeFullURL()
230 {
231 return $this->title->escapeFullURL();
232 }
233
234 /**
235 * Return the URL of an image, provided its name.
236 *
237 * @param string $name Name of the image, without the leading "Image:"
238 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
239 * @access public
240 */
241 function wfImageUrl( $name, $fromSharedDirectory = false )
242 {
243 global $wgUploadPath,$wgUploadBaseUrl,$wgHashedUploadDirectory,
244 $wgHashedSharedUploadDirectory,$wgSharedUploadPath;
245 if($fromSharedDirectory) {
246 $hash = $wgHashedSharedUploadDirectory;
247 $base = '';
248 $path = $wgSharedUploadPath;
249 } else {
250 $hash = $wgHashedUploadDirectory;
251 $base = $wgUploadBaseUrl;
252 $path = $wgUploadPath;
253 }
254 if ( $hash ) {
255 $hash = md5( $name );
256 $url = "{$base}{$path}/" . $hash{0} . "/" .
257 substr( $hash, 0, 2 ) . "/{$name}";
258 } else {
259 $url = "{$base}{$path}/{$name}";
260 }
261 return wfUrlencode( $url );
262 }
263
264 /**
265 * Returns true iff the image file exists on disk.
266 *
267 * @access public
268 */
269 function exists()
270 {
271 return $this->fileExists;
272 }
273
274 /**
275 *
276 * @access private
277 */
278 function thumbUrl( $width, $subdir='thumb') {
279 global $wgUploadPath,$wgHashedUploadDirectory, $wgUploadBaseUrl,
280 $wgSharedUploadPath,$wgSharedUploadDirectory,
281 $wgHashedSharedUploadDirectory;
282 $name = $this->thumbName( $width );
283 if($this->fromSharedDirectory) {
284 $hashdir = $wgHashedSharedUploadDirectory;
285 $base = '';
286 $path = $wgSharedUploadPath;
287 } else {
288 $hashdir = $wgHashedUploadDirectory;
289 $base = $wgUploadBaseUrl;
290 $path = $wgUploadPath;
291 }
292 if ($hashdir) {
293 $hash = md5( $name );
294 $url = "{$base}{$path}/{$subdir}/" . $hash{0} . "/" .
295 substr( $hash, 0, 2 ) . "/{$name}";
296 } else {
297 $url = "{$base}{$path}/{$subdir}/{$name}";
298 }
299
300 return wfUrlencode($url);
301 }
302
303 /**
304 * Return the file name of a thumbnail of the specified width
305 *
306 * @param integer $width Width of the thumbnail image
307 * @access private
308 */
309 function thumbName( $width ) {
310 $thumb = $width."px-".$this->name;
311 if( $this->extension == 'svg' ) {
312 # Rasterize SVG vector images to PNG
313 $thumb .= '.png';
314 }
315 return $thumb;
316 }
317
318 /**
319 * Create a thumbnail of the image having the specified width/height.
320 * The thumbnail will not be created if the width is larger than the
321 * image's width. Let the browser do the scaling in this case.
322 * The thumbnail is stored on disk and is only computed if the thumbnail
323 * file does not exist OR if it is older than the image.
324 * Returns the URL.
325 *
326 * Keeps aspect ratio of original image. If both width and height are
327 * specified, the generated image will be no bigger than width x height,
328 * and will also have correct aspect ratio.
329 *
330 * @param integer $width maximum width of the generated thumbnail
331 * @param integer $height maximum height of the image (optional)
332 * @access public
333 */
334 function createThumb( $width, $height=-1 ) {
335 if ( $height == -1 ) {
336 return $this->renderThumb( $width );
337 }
338 if ( $width < $this->width ) {
339 $thumbheight = $this->height * $width / $this->width;
340 $thumbwidth = $width;
341 } else {
342 $thumbheight = $this->height;
343 $thumbwidth = $this->width;
344 }
345 if ( $thumbheight > $height ) {
346 $thumbwidth = $thumbwidth * $height / $thumbheight;
347 $thumbheight = $height;
348 }
349 return $this->renderThumb( $thumbwidth );
350 }
351
352 /**
353 * Create a thumbnail of the image having the specified width.
354 * The thumbnail will not be created if the width is larger than the
355 * image's width. Let the browser do the scaling in this case.
356 * The thumbnail is stored on disk and is only computed if the thumbnail
357 * file does not exist OR if it is older than the image.
358 * Returns the URL.
359 *
360 * @access private
361 */
362 function /* private */ renderThumb( $width ) {
363 global $wgImageMagickConvertCommand;
364 global $wgUseImageMagick;
365 global $wgUseSquid, $wgInternalServer;
366
367 $width = IntVal( $width );
368
369 $thumbName = $this->thumbName( $width );
370 $thumbPath = wfImageThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory ).'/'.$thumbName;
371 $thumbUrl = $this->thumbUrl( $width );
372 #wfDebug ( "Render name: $thumbName path: $thumbPath url: $thumbUrl\n");
373 if ( ! $this->exists() )
374 {
375 # If there is no image, there will be no thumbnail
376 return '';
377 }
378
379 # Sanity check $width
380 if( $width <= 0 ) {
381 # BZZZT
382 return '';
383 }
384
385 if( $width > $this->width && !$this->mustRender() ) {
386 # Don't make an image bigger than the source
387 return $this->getViewURL();
388 }
389
390 if ( (! file_exists( $thumbPath ) ) || ( filemtime($thumbPath) < filemtime($this->imagePath) ) ) {
391 if( $this->extension == 'svg' ) {
392 global $wgSVGConverters, $wgSVGConverter;
393 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
394 global $wgSVGConverterPath;
395 $cmd = str_replace(
396 array( '$path/', '$width', '$input', '$output' ),
397 array( $wgSVGConverterPath,
398 $width,
399 escapeshellarg( $this->imagePath ),
400 escapeshellarg( $thumbPath ) ),
401 $wgSVGConverters[$wgSVGConverter] );
402 $conv = shell_exec( $cmd );
403 } else {
404 $conv = false;
405 }
406 } elseif ( $wgUseImageMagick ) {
407 # use ImageMagick
408 # Specify white background color, will be used for transparent images
409 # in Internet Explorer/Windows instead of default black.
410 $cmd = $wgImageMagickConvertCommand .
411 " -quality 85 -background white -geometry {$width} ".
412 escapeshellarg($this->imagePath) . " " .
413 escapeshellarg($thumbPath);
414 $conv = shell_exec( $cmd );
415 } else {
416 # Use PHP's builtin GD library functions.
417 #
418 # First find out what kind of file this is, and select the correct
419 # input routine for this.
420
421 $truecolor = false;
422
423 switch( $this->type ) {
424 case 1: # GIF
425 $src_image = imagecreatefromgif( $this->imagePath );
426 break;
427 case 2: # JPG
428 $src_image = imagecreatefromjpeg( $this->imagePath );
429 $truecolor = true;
430 break;
431 case 3: # PNG
432 $src_image = imagecreatefrompng( $this->imagePath );
433 $truecolor = ( $this->bits > 8 );
434 break;
435 case 15: # WBMP for WML
436 $src_image = imagecreatefromwbmp( $this->imagePath );
437 break;
438 case 16: # XBM
439 $src_image = imagecreatefromxbm( $this->imagePath );
440 break;
441 default:
442 return 'Image type not supported';
443 break;
444 }
445 $height = floor( $this->height * ( $width/$this->width ) );
446 if ( $truecolor ) {
447 $dst_image = imagecreatetruecolor( $width, $height );
448 } else {
449 $dst_image = imagecreate( $width, $height );
450 }
451 imagecopyresampled( $dst_image, $src_image,
452 0,0,0,0,
453 $width, $height, $this->width, $this->height );
454 switch( $this->type ) {
455 case 1: # GIF
456 case 3: # PNG
457 case 15: # WBMP
458 case 16: # XBM
459 #$thumbUrl .= ".png";
460 #$thumbPath .= ".png";
461 imagepng( $dst_image, $thumbPath );
462 break;
463 case 2: # JPEG
464 #$thumbUrl .= ".jpg";
465 #$thumbPath .= ".jpg";
466 imageinterlace( $dst_image );
467 imagejpeg( $dst_image, $thumbPath, 95 );
468 break;
469 default:
470 break;
471 }
472 imagedestroy( $dst_image );
473 imagedestroy( $src_image );
474
475
476 }
477 #
478 # Check for zero-sized thumbnails. Those can be generated when
479 # no disk space is available or some other error occurs
480 #
481 $thumbstat = stat( $thumbPath );
482 if( $thumbstat['size'] == 0 )
483 {
484 unlink( $thumbPath );
485 }
486
487 # Purge squid
488 # This has to be done after the image is updated and present for all machines on NFS,
489 # or else the old version might be stored into the squid again
490 if ( $wgUseSquid ) {
491 $urlArr = Array(
492 $wgInternalServer.$thumbUrl
493 );
494 wfPurgeSquidServers($urlArr);
495 }
496 }
497 return $thumbUrl;
498 } // END OF function createThumb
499
500 /**
501 * Return the image history of this image, line by line.
502 * starts with current version, then old versions.
503 * uses $this->historyLine to check which line to return:
504 * 0 return line for current version
505 * 1 query for old versions, return first one
506 * 2, ... return next old version from above query
507 *
508 * @access public
509 */
510 function nextHistoryLine()
511 {
512 $fname = 'Image::nextHistoryLine()';
513 $dbr =& wfGetDB( DB_SLAVE );
514 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
515 $this->historyRes = $dbr->select( 'image',
516 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
517 array( 'img_name' => $this->title->getDBkey() ),
518 $fname
519 );
520 if ( 0 == wfNumRows( $this->historyRes ) ) {
521 return FALSE;
522 }
523 } else if ( $this->historyLine == 1 ) {
524 $this->historyRes = $dbr->select( 'oldimage',
525 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
526 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
527 ), array( 'oi_name' => $this->title->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
528 );
529 }
530 $this->historyLine ++;
531
532 return $dbr->fetchObject( $this->historyRes );
533 }
534
535 /**
536 * Reset the history pointer to the first element of the history
537 * @access public
538 */
539 function resetHistory()
540 {
541 $this->historyLine = 0;
542 }
543
544 /**
545 * Return true if the file is of a type that can't be directly
546 * rendered by typical browsers and needs to be re-rasterized.
547 * @return bool
548 */
549 function mustRender() {
550 return ( $this->extension == 'svg' );
551 }
552
553 } //class
554
555
556 /**
557 * Returns the image directory of an image
558 * If the directory does not exist, it is created.
559 * The result is an absolute path.
560 *
561 * @param string $fname file name of the image file
562 * @access public
563 */
564 function wfImageDir( $fname )
565 {
566 global $wgUploadDirectory, $wgHashedUploadDirectory;
567
568 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
569
570 $hash = md5( $fname );
571 $oldumask = umask(0);
572 $dest = $wgUploadDirectory . '/' . $hash{0};
573 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
574 $dest .= '/' . substr( $hash, 0, 2 );
575 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
576
577 umask( $oldumask );
578 return $dest;
579 }
580
581 /**
582 * Returns the image directory of an image's thubnail
583 * If the directory does not exist, it is created.
584 * The result is an absolute path.
585 *
586 * @param string $fname file name of the thumbnail file, including file size prefix
587 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
588 * @param boolean $shared (optional) use the shared upload directory
589 * @access public
590 */
591 function wfImageThumbDir( $fname , $subdir='thumb', $shared=false)
592 {
593 return wfImageArchiveDir( $fname, $subdir, $shared );
594 }
595
596 /**
597 * Returns the image directory of an image's old version
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 old version. Default is 'archive'
603 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
604 * @access public
605 */
606 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false )
607 {
608 global $wgUploadDirectory, $wgHashedUploadDirectory,
609 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
610 $dir = $shared ? $wgSharedUploadDirectory : $wgUploadDirectory;
611 $hashdir = $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
612 if (!$hashdir) { return $dir.'/'.$subdir; }
613
614 $hash = md5( $fname );
615 $oldumask = umask(0);
616 # Suppress warning messages here; if the file itself can't
617 # be written we'll worry about it then.
618 $archive = $dir.'/'.$subdir;
619 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
620 $archive .= '/' . $hash{0};
621 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
622 $archive .= '/' . substr( $hash, 0, 2 );
623 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
624
625 umask( $oldumask );
626 return $archive;
627 }
628
629 /**
630 * Record an image upload in the upload log.
631 */
632 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
633 {
634 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
635 global $wgUseCopyrightUpload;
636
637 $fname = 'wfRecordUpload';
638 $dbw =& wfGetDB( DB_MASTER );
639
640 # img_name must be unique
641 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
642 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
643 }
644
645
646 $now = wfTimestampNow();
647 $won = wfInvertTimestamp( $now );
648 $size = IntVal( $size );
649
650 if ( $wgUseCopyrightUpload )
651 {
652 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
653 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
654 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
655 }
656 else $textdesc = $desc ;
657
658 $now = wfTimestampNow();
659 $won = wfInvertTimestamp( $now );
660
661 # Test to see if the row exists using INSERT IGNORE
662 # This avoids race conditions by locking the row until the commit, and also
663 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
664 $dbw->insert( 'image',
665 array(
666 'img_name' => $name,
667 'img_size'=> $size,
668 'img_timestamp' => $dbw->timestamp($now),
669 'img_description' => $desc,
670 'img_user' => $wgUser->getID(),
671 'img_user_text' => $wgUser->getName(),
672 ), $fname, 'IGNORE'
673 );
674 $descTitle = Title::makeTitleSafe( NS_IMAGE, $name );
675
676 if ( $dbw->affectedRows() ) {
677 # Successfully inserted, this is a new image
678 $id = $descTitle->getArticleID();
679
680 if ( $id == 0 ) {
681 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
682 $dbw->insert( 'cur',
683 array(
684 'cur_id' => $seqVal,
685 'cur_namespace' => NS_IMAGE,
686 'cur_title' => $name,
687 'cur_comment' => $desc,
688 'cur_user' => $wgUser->getID(),
689 'cur_user_text' => $wgUser->getName(),
690 'cur_timestamp' => $dbw->timestamp($now),
691 'cur_is_new' => 1,
692 'cur_text' => $textdesc,
693 'inverse_timestamp' => $won,
694 'cur_touched' => $dbw->timestamp($now)
695 ), $fname
696 );
697 $id = $dbw->insertId() or 0; # We should throw an error instead
698
699 RecentChange::notifyNew( $now, $descTitle, 0, $wgUser, $desc );
700
701 $u = new SearchUpdate( $id, $name, $desc );
702 $u->doUpdate();
703 }
704 } else {
705 # Collision, this is an update of an image
706 # Get current image row for update
707 $s = $dbw->selectRow( 'image', array( 'img_name','img_size','img_timestamp','img_description',
708 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
709
710 # Insert it into oldimage
711 $dbw->insert( 'oldimage',
712 array(
713 'oi_name' => $s->img_name,
714 'oi_archive_name' => $oldver,
715 'oi_size' => $s->img_size,
716 'oi_timestamp' => $dbw->timestamp($s->img_timestamp),
717 'oi_description' => $s->img_description,
718 'oi_user' => $s->img_user,
719 'oi_user_text' => $s->img_user_text
720 ), $fname
721 );
722
723 # Update the current image row
724 $dbw->update( 'image',
725 array( /* SET */
726 'img_size' => $size,
727 'img_timestamp' => $dbw->timestamp(),
728 'img_user' => $wgUser->getID(),
729 'img_user_text' => $wgUser->getName(),
730 'img_description' => $desc,
731 ), array( /* WHERE */
732 'img_name' => $name
733 ), $fname
734 );
735
736 # Invalidate the cache for the description page
737 $descTitle->invalidateCache();
738 }
739
740 $log = new LogPage( 'upload' );
741 $log->addEntry( 'upload', $descTitle, $desc );
742 }
743
744 /**
745 * Returns the image URL of an image's old version
746 *
747 * @param string $fname file name of the image file
748 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
749 * @access public
750 */
751 function wfImageArchiveUrl( $name, $subdir='archive' )
752 {
753 global $wgUploadPath, $wgHashedUploadDirectory;
754
755 if ($wgHashedUploadDirectory) {
756 $hash = md5( substr( $name, 15) );
757 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
758 substr( $hash, 0, 2 ) . '/'.$name;
759 } else {
760 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
761 }
762 return wfUrlencode($url);
763 }
764
765 /**
766 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
767 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
768 *
769 * @param string $length
770 * @return int Length in pixels
771 */
772 function scaleSVGUnit( $length ) {
773 static $unitLength = array(
774 'px' => 1.0,
775 'pt' => 1.25,
776 'pc' => 15.0,
777 'mm' => 3.543307,
778 'cm' => 35.43307,
779 'in' => 90.0,
780 '' => 1.0, // "User units" pixels by default
781 '%' => 2.0, // Fake it!
782 );
783 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
784 $length = FloatVal( $matches[1] );
785 $unit = $matches[2];
786 return round( $length * $unitLength[$unit] );
787 } else {
788 // Assume pixels
789 return round( FloatVal( $length ) );
790 }
791 }
792
793 /**
794 * Compatible with PHP getimagesize()
795 * @todo support gzipped SVGZ
796 * @todo check XML more carefully
797 * @todo sensible defaults
798 *
799 * @param string $filename
800 * @return array
801 */
802 function getSVGsize( $filename ) {
803 $width = 256;
804 $height = 256;
805
806 // Read a chunk of the file
807 $f = fopen( $filename, "rt" );
808 if( !$f ) return false;
809 $chunk = fread( $f, 4096 );
810 fclose( $f );
811
812 // Uber-crappy hack! Run through a real XML parser.
813 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
814 return false;
815 }
816 $tag = $matches[1];
817 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
818 $width = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
819 }
820 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
821 $height = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
822 }
823
824 return array( $width, $height, 'SVG',
825 "width=\"$width\" height=\"$height\"" );
826 }
827
828 ?>