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