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