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