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