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