7aa408afddea529c5b5ed6dbe58366f396060082
[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 * @param bool $recache if true, ignores anything in memcached and sets the updated metadata
40 * @access public
41 */
42 function Image( $name, $recache = false ) {
43
44 global $wgUseSharedUploads, $wgLang, $wgMemc, $wgDBname,
45 $wgSharedUploadDBname;
46
47 $this->name = $name;
48 $this->title = Title::makeTitleSafe( NS_IMAGE, $this->name );
49 $this->fromSharedDirectory = false;
50 $this->imagePath = $this->getFullPath();
51
52 $n = strrpos( $name, '.' );
53 $this->extension = strtolower( $n ? substr( $name, $n + 1 ) : '' );
54 $gis = false;
55 $hashedName = md5($this->name);
56 $cacheKey = "$wgDBname:Image:".$hashedName;
57 $foundCached = false;
58
59 if ( !$recache ) {
60 $cachedValues = $wgMemc->get( $cacheKey );
61
62 if (!empty($cachedValues) && is_array($cachedValues)) {
63 if ($wgUseSharedUploads && $cachedValues['fromShared']) {
64 # if this is shared file, we need to check if image
65 # in shared repository has not changed
66 $commonsCachedValues = $wgMemc->get( "$wgSharedUploadDBname:Image:".$hashedName );
67 if (!empty($commonsCachedValues) && is_array($commonsCachedValues)) {
68 $this->name = $commonsCachedValues['name'];
69 $this->imagePath = $commonsCachedValues['imagePath'];
70 $this->fileExists = $commonsCachedValues['fileExists'];
71 $this->fromSharedDirectory = true;
72 $gis = $commonsCachedValues['gis'];
73 $foundCached = true;
74 }
75 }
76 else {
77 $this->name = $cachedValues['name'];
78 $this->imagePath = $cachedValues['imagePath'];
79 $this->fileExists = $cachedValues['fileExists'];
80 $this->fromSharedDirectory = false;
81 $gis = $cachedValues['gis'];
82 $foundCached = true;
83 }
84 }
85 }
86
87 if (!$foundCached) {
88 $this->fileExists = file_exists( $this->imagePath);
89
90 # If the file is not found, and a shared upload directory
91 # like the Wikimedia Commons is used, look for it there.
92 if (!$this->fileExists && $wgUseSharedUploads) {
93
94 # In case we're on a wgCapitalLinks=false wiki, we
95 # capitalize the first letter of the filename before
96 # looking it up in the shared repository.
97 $this->name= $wgLang->ucfirst($name);
98
99 $this->imagePath = $this->getFullPath(true);
100 $this->fileExists = file_exists( $this->imagePath);
101 $this->fromSharedDirectory = true;
102 $name=$this->name;
103 }
104
105 if ( $this->fileExists ) {
106 # Don't try to get the size of sound and video files, that's bad for performance
107 if ( !Image::isKnownImageExtension( $this->extension ) ) {
108 $gis = false;
109 } elseif( $this->extension == 'svg' ) {
110 wfSuppressWarnings();
111 $gis = getSVGsize( $this->imagePath );
112 wfRestoreWarnings();
113 } else {
114 wfSuppressWarnings();
115 $gis = getimagesize( $this->imagePath );
116 wfRestoreWarnings();
117 }
118 }
119
120 $cachedValues = array('name' => $this->name,
121 'imagePath' => $this->imagePath,
122 'fileExists' => $this->fileExists,
123 'fromShared' => $this->fromSharedDirectory,
124 'gis' => $gis);
125
126 $wgMemc->set( $cacheKey, $cachedValues );
127
128 if ($wgUseSharedUploads && $this->fromSharedDirectory) {
129 $cachedValues['fromShared'] = false;
130 $wgMemc->set( "$wgSharedUploadDBname:Image:".$hashedName, $cachedValues );
131 }
132 }
133
134 if( $gis !== false ) {
135 $this->width = $gis[0];
136 $this->height = $gis[1];
137 $this->type = $gis[2];
138 $this->attr = $gis[3];
139 if ( isset( $gis['bits'] ) ) {
140 $this->bits = $gis['bits'];
141 } else {
142 $this->bits = 0;
143 }
144 }
145
146 if($this->fileExists) {
147 $this->url = $this->wfImageUrl( $this->name, $this->fromSharedDirectory );
148 } else {
149 $this->url='';
150 }
151 $this->historyLine = 0;
152 }
153
154 /**
155 * Remove image metadata from cache if any
156 *
157 * Don't call this, use the $recache parameter of Image::Image() instead
158 *
159 * @param string $name the title of an image
160 * @static
161 */
162 function invalidateMetadataCache( $name ) {
163 global $wgMemc, $wgDBname;
164 $wgMemc->delete("$wgDBname:Image:".md5($name));
165 }
166
167 /**
168 * Factory function
169 *
170 * Create a new image object from a title object.
171 *
172 * @param Title $nt Title object. Must be from namespace "image"
173 * @access public
174 */
175 function newFromTitle( $nt ) {
176 $img = new Image( $nt->getDBKey() );
177 $img->title = $nt;
178 return $img;
179 }
180
181 /**
182 * Return the name of this image
183 * @access public
184 */
185 function getName() {
186 return $this->name;
187 }
188
189 /**
190 * Return the associated title object
191 * @access public
192 */
193 function getTitle() {
194 return $this->title;
195 }
196
197 /**
198 * Return the URL of the image file
199 * @access public
200 */
201 function getURL() {
202 return $this->url;
203 }
204
205 function getViewURL() {
206 if( $this->mustRender() ) {
207 return $this->createThumb( $this->getWidth() );
208 } else {
209 return $this->getURL();
210 }
211 }
212
213 /**
214 * Return the image path of the image in the
215 * local file system as an absolute path
216 * @access public
217 */
218 function getImagePath()
219 {
220 return $this->imagePath;
221 }
222
223 /**
224 * Return the width of the image
225 *
226 * Returns -1 if the file specified is not a known image type
227 * @access public
228 */
229 function getWidth() {
230 return $this->width;
231 }
232
233 /**
234 * Return the height of the image
235 *
236 * Returns -1 if the file specified is not a known image type
237 * @access public
238 */
239 function getHeight() {
240 return $this->height;
241 }
242
243 /**
244 * Return the size of the image file, in bytes
245 * @access public
246 */
247 function getSize() {
248 $st = stat( $this->getImagePath() );
249 if( $st ) {
250 return $st['size'];
251 } else {
252 return false;
253 }
254 }
255
256 /**
257 * Return the type of the image
258 *
259 * - 1 GIF
260 * - 2 JPG
261 * - 3 PNG
262 * - 15 WBMP
263 * - 16 XBM
264 */
265 function getType() {
266 return $this->type;
267 }
268
269 /**
270 * Return the escapeLocalURL of this image
271 * @access public
272 */
273 function getEscapeLocalURL() {
274 return $this->title->escapeLocalURL();
275 }
276
277 /**
278 * Return the escapeFullURL of this image
279 * @access public
280 */
281 function getEscapeFullURL() {
282 return $this->title->escapeFullURL();
283 }
284
285 /**
286 * Return the URL of an image, provided its name.
287 *
288 * @param string $name Name of the image, without the leading "Image:"
289 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
290 * @access public
291 */
292 function wfImageUrl( $name, $fromSharedDirectory = false ) {
293 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
294 if($fromSharedDirectory) {
295 $base = '';
296 $path = $wgSharedUploadPath;
297 } else {
298 $base = $wgUploadBaseUrl;
299 $path = $wgUploadPath;
300 }
301 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
302 return wfUrlencode( $url );
303 }
304
305 /**
306 * Returns true iff the image file exists on disk.
307 *
308 * @access public
309 */
310 function exists() {
311 return $this->fileExists;
312 }
313
314 /**
315 *
316 * @access private
317 */
318 function thumbUrl( $width, $subdir='thumb') {
319 global $wgUploadPath, $wgUploadBaseUrl,
320 $wgSharedUploadPath,$wgSharedUploadDirectory;
321 $name = $this->thumbName( $width );
322 if($this->fromSharedDirectory) {
323 $base = '';
324 $path = $wgSharedUploadPath;
325 } else {
326 $base = $wgUploadBaseUrl;
327 $path = $wgUploadPath;
328 }
329 $url = "{$base}{$path}/{$subdir}" .
330 wfGetHashPath($name, $this->fromSharedDirectory)
331 . "{$name}";
332 return wfUrlencode($url);
333 }
334
335 /**
336 * Return the file name of a thumbnail of the specified width
337 *
338 * @param integer $width Width of the thumbnail image
339 * @param boolean $shared Does the thumbnail come from the shared repository?
340 * @access private
341 */
342 function thumbName( $width, $shared=false ) {
343 $thumb = $width."px-".$this->name;
344 if( $this->extension == 'svg' ) {
345 # Rasterize SVG vector images to PNG
346 $thumb .= '.png';
347 }
348 return $thumb;
349 }
350
351 /**
352 * Create a thumbnail of the image having the specified width/height.
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 * Keeps aspect ratio of original image. If both width and height are
360 * specified, the generated image will be no bigger than width x height,
361 * and will also have correct aspect ratio.
362 *
363 * @param integer $width maximum width of the generated thumbnail
364 * @param integer $height maximum height of the image (optional)
365 * @access public
366 */
367 function createThumb( $width, $height=-1 ) {
368 $thumb = $this->getThumbnail( $width, $height );
369 if( is_null( $thumb ) ) return '';
370 return $thumb->getUrl();
371 }
372
373 /**
374 * As createThumb, but returns a ThumbnailImage object. This can
375 * provide access to the actual file, the real size of the thumb,
376 * and can produce a convenient <img> tag for you.
377 *
378 * @param integer $width maximum width of the generated thumbnail
379 * @param integer $height maximum height of the image (optional)
380 * @return ThumbnailImage
381 * @access public
382 */
383 function &getThumbnail( $width, $height=-1 ) {
384 if ( $height == -1 ) {
385 return $this->renderThumb( $width );
386 }
387 if ( $width < $this->width ) {
388 $thumbheight = $this->height * $width / $this->width;
389 $thumbwidth = $width;
390 } else {
391 $thumbheight = $this->height;
392 $thumbwidth = $this->width;
393 }
394 if ( $thumbheight > $height ) {
395 $thumbwidth = $thumbwidth * $height / $thumbheight;
396 $thumbheight = $height;
397 }
398 $thumb = $this->renderThumb( $thumbwidth );
399 if( is_null( $thumb ) ) {
400 $thumb = $this->iconThumb();
401 }
402 return $thumb;
403 }
404
405 /**
406 * @return ThumbnailImage
407 */
408 function iconThumb() {
409 global $wgStylePath, $wgStyleDirectory;
410
411 $try = array( 'fileicon-' . $this->extension . '.png', 'fileicon.png' );
412 foreach( $try as $icon ) {
413 $path = '/common/images/' . $icon;
414 $filepath = $wgStyleDirectory . $path;
415 if( file_exists( $filepath ) ) {
416 return new ThumbnailImage( $filepath, $wgStylePath . $path );
417 }
418 }
419 return null;
420 }
421
422 /**
423 * Create a thumbnail of the image having the specified width.
424 * The thumbnail will not be created if the width is larger than the
425 * image's width. Let the browser do the scaling in this case.
426 * The thumbnail is stored on disk and is only computed if the thumbnail
427 * file does not exist OR if it is older than the image.
428 * Returns an object which can return the pathname, URL, and physical
429 * pixel size of the thumbnail -- or null on failure.
430 *
431 * @return ThumbnailImage
432 * @access private
433 */
434 function /* private */ renderThumb( $width ) {
435 global $wgImageMagickConvertCommand;
436 global $wgUseImageMagick;
437 global $wgUseSquid, $wgInternalServer;
438
439 $width = IntVal( $width );
440
441 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory );
442 $thumbPath = wfImageThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory ).'/'.$thumbName;
443 $thumbUrl = $this->thumbUrl( $width );
444 #wfDebug ( "Render name: $thumbName path: $thumbPath url: $thumbUrl\n");
445 if ( ! $this->exists() )
446 {
447 # If there is no image, there will be no thumbnail
448 return null;
449 }
450
451 # Sanity check $width
452 if( $width <= 0 ) {
453 # BZZZT
454 return null;
455 }
456
457 if( $width > $this->width && !$this->mustRender() ) {
458 # Don't make an image bigger than the source
459 return new ThumbnailImage( $this->getImagePath(), $this->getViewURL() );
460 }
461
462 if ( (! file_exists( $thumbPath ) ) || ( filemtime($thumbPath) < filemtime($this->imagePath) ) ) {
463 if( $this->extension == 'svg' ) {
464 global $wgSVGConverters, $wgSVGConverter;
465 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
466 global $wgSVGConverterPath;
467 $cmd = str_replace(
468 array( '$path/', '$width', '$input', '$output' ),
469 array( $wgSVGConverterPath,
470 $width,
471 escapeshellarg( $this->imagePath ),
472 escapeshellarg( $thumbPath ) ),
473 $wgSVGConverters[$wgSVGConverter] );
474 $conv = shell_exec( $cmd );
475 } else {
476 $conv = false;
477 }
478 } elseif ( $wgUseImageMagick ) {
479 # use ImageMagick
480 # Specify white background color, will be used for transparent images
481 # in Internet Explorer/Windows instead of default black.
482 $cmd = $wgImageMagickConvertCommand .
483 " -quality 85 -background white -geometry {$width} ".
484 escapeshellarg($this->imagePath) . " " .
485 escapeshellarg($thumbPath);
486 $conv = shell_exec( $cmd );
487 } else {
488 # Use PHP's builtin GD library functions.
489 #
490 # First find out what kind of file this is, and select the correct
491 # input routine for this.
492
493 $truecolor = false;
494
495 switch( $this->type ) {
496 case 1: # GIF
497 $src_image = imagecreatefromgif( $this->imagePath );
498 break;
499 case 2: # JPG
500 $src_image = imagecreatefromjpeg( $this->imagePath );
501 $truecolor = true;
502 break;
503 case 3: # PNG
504 $src_image = imagecreatefrompng( $this->imagePath );
505 $truecolor = ( $this->bits > 8 );
506 break;
507 case 15: # WBMP for WML
508 $src_image = imagecreatefromwbmp( $this->imagePath );
509 break;
510 case 16: # XBM
511 $src_image = imagecreatefromxbm( $this->imagePath );
512 break;
513 default:
514 return 'Image type not supported';
515 break;
516 }
517 $height = floor( $this->height * ( $width/$this->width ) );
518 if ( $truecolor ) {
519 $dst_image = imagecreatetruecolor( $width, $height );
520 } else {
521 $dst_image = imagecreate( $width, $height );
522 }
523 imagecopyresampled( $dst_image, $src_image,
524 0,0,0,0,
525 $width, $height, $this->width, $this->height );
526 switch( $this->type ) {
527 case 1: # GIF
528 case 3: # PNG
529 case 15: # WBMP
530 case 16: # XBM
531 #$thumbUrl .= ".png";
532 #$thumbPath .= ".png";
533 imagepng( $dst_image, $thumbPath );
534 break;
535 case 2: # JPEG
536 #$thumbUrl .= ".jpg";
537 #$thumbPath .= ".jpg";
538 imageinterlace( $dst_image );
539 imagejpeg( $dst_image, $thumbPath, 95 );
540 break;
541 default:
542 break;
543 }
544 imagedestroy( $dst_image );
545 imagedestroy( $src_image );
546 }
547 #
548 # Check for zero-sized thumbnails. Those can be generated when
549 # no disk space is available or some other error occurs
550 #
551 if( file_exists( $thumbPath ) ) {
552 $thumbstat = stat( $thumbPath );
553 if( $thumbstat['size'] == 0 ) {
554 unlink( $thumbPath );
555 }
556 }
557
558 # Purge squid
559 # This has to be done after the image is updated and present for all machines on NFS,
560 # or else the old version might be stored into the squid again
561 if ( $wgUseSquid ) {
562 $urlArr = Array(
563 $wgInternalServer.$thumbUrl
564 );
565 wfPurgeSquidServers($urlArr);
566 }
567 }
568 return new ThumbnailImage( $thumbPath, $thumbUrl );
569 } // END OF function createThumb
570
571 /**
572 * Return the image history of this image, line by line.
573 * starts with current version, then old versions.
574 * uses $this->historyLine to check which line to return:
575 * 0 return line for current version
576 * 1 query for old versions, return first one
577 * 2, ... return next old version from above query
578 *
579 * @access public
580 */
581 function nextHistoryLine() {
582 $fname = 'Image::nextHistoryLine()';
583 $dbr =& wfGetDB( DB_SLAVE );
584 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
585 $this->historyRes = $dbr->select( 'image',
586 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
587 array( 'img_name' => $this->title->getDBkey() ),
588 $fname
589 );
590 if ( 0 == wfNumRows( $this->historyRes ) ) {
591 return FALSE;
592 }
593 } else if ( $this->historyLine == 1 ) {
594 $this->historyRes = $dbr->select( 'oldimage',
595 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
596 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
597 ), array( 'oi_name' => $this->title->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
598 );
599 }
600 $this->historyLine ++;
601
602 return $dbr->fetchObject( $this->historyRes );
603 }
604
605 /**
606 * Reset the history pointer to the first element of the history
607 * @access public
608 */
609 function resetHistory() {
610 $this->historyLine = 0;
611 }
612
613 /**
614 * Return true if the file is of a type that can't be directly
615 * rendered by typical browsers and needs to be re-rasterized.
616 * @return bool
617 */
618 function mustRender() {
619 return ( $this->extension == 'svg' );
620 }
621
622 /**
623 * Return the full filesystem path to the file. Note that this does
624 * not mean that a file actually exists under that location.
625 *
626 * This path depends on whether directory hashing is active or not,
627 * i.e. whether the images are all found in the same directory,
628 * or in hashed paths like /images/3/3c.
629 *
630 * @access public
631 * @param boolean $fromSharedDirectory Return the path to the file
632 * in a shared repository (see $wgUseSharedRepository and related
633 * options in DefaultSettings.php) instead of a local one.
634 *
635 */
636 function getFullPath( $fromSharedRepository = false ) {
637 global $wgUploadDirectory, $wgSharedUploadDirectory;
638 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
639
640 $dir = $fromSharedRepository ? $wgSharedUploadDirectory :
641 $wgUploadDirectory;
642 $name = $this->name;
643 $fullpath = $dir . wfGetHashPath($name, $fromSharedRepository) . $name;
644 return $fullpath;
645 }
646
647 /**
648 * @return bool
649 * @static
650 */
651 function isKnownImageExtension( $ext ) {
652 static $extensions = array( 'svg', 'png', 'jpg', 'jpeg', 'gif', 'bmp', 'xbm' );
653 return in_array( $ext, $extensions );
654 }
655
656 } //class
657
658
659 /**
660 * Returns the image directory of an image
661 * If the directory does not exist, it is created.
662 * The result is an absolute path.
663 *
664 * @param string $fname file name of the image file
665 * @access public
666 */
667 function wfImageDir( $fname ) {
668 global $wgUploadDirectory, $wgHashedUploadDirectory;
669
670 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
671
672 $hash = md5( $fname );
673 $oldumask = umask(0);
674 $dest = $wgUploadDirectory . '/' . $hash{0};
675 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
676 $dest .= '/' . substr( $hash, 0, 2 );
677 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
678
679 umask( $oldumask );
680 return $dest;
681 }
682
683 /**
684 * Returns the image directory of an image's thubnail
685 * If the directory does not exist, it is created.
686 * The result is an absolute path.
687 *
688 * @param string $fname file name of the thumbnail file, including file size prefix
689 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
690 * @param boolean $shared (optional) use the shared upload directory
691 * @access public
692 */
693 function wfImageThumbDir( $fname , $subdir='thumb', $shared=false) {
694 return wfImageArchiveDir( $fname, $subdir, $shared );
695 }
696
697 /**
698 * Returns the image directory of an image's old version
699 * If the directory does not exist, it is created.
700 * The result is an absolute path.
701 *
702 * @param string $fname file name of the thumbnail file, including file size prefix
703 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
704 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
705 * @access public
706 */
707 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
708 global $wgUploadDirectory, $wgHashedUploadDirectory,
709 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
710 $dir = $shared ? $wgSharedUploadDirectory : $wgUploadDirectory;
711 $hashdir = $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
712 if (!$hashdir) { return $dir.'/'.$subdir; }
713 $hash = md5( $fname );
714 $oldumask = umask(0);
715 # Suppress warning messages here; if the file itself can't
716 # be written we'll worry about it then.
717 $archive = $dir.'/'.$subdir;
718 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
719 $archive .= '/' . $hash{0};
720 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
721 $archive .= '/' . substr( $hash, 0, 2 );
722 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
723
724 umask( $oldumask );
725 return $archive;
726 }
727
728
729 /*
730 * Return the hash path component of an image path (URL or filesystem),
731 * e.g. "/3/3c/", or just "/" if hashing is not used.
732 *
733 * @param $dbkey The filesystem / database name of the file
734 * @param $fromSharedDirectory Use the shared file repository? It may
735 * use different hash settings from the local one.
736 */
737 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
738 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
739 global $wgHashedUploadDirectory;
740
741 $ishashed = $fromSharedDirectory ? $wgHashedSharedUploadDirectory :
742 $wgHashedUploadDirectory;
743 if($ishashed) {
744 $hash = md5($dbkey);
745 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
746 } else {
747 return '/';
748 }
749 }
750
751
752 /**
753 * Record an image upload in the upload log.
754 */
755 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = '', $source = '' ) {
756 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
757 global $wgUseCopyrightUpload;
758
759 $fname = 'wfRecordUpload';
760 $dbw =& wfGetDB( DB_MASTER );
761
762 # img_name must be unique
763 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
764 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
765 }
766
767
768 $now = wfTimestampNow();
769 $size = IntVal( $size );
770
771 if ( $wgUseCopyrightUpload ) {
772 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
773 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
774 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
775 }
776 else $textdesc = $desc ;
777
778 $now = wfTimestampNow();
779
780 # Test to see if the row exists using INSERT IGNORE
781 # This avoids race conditions by locking the row until the commit, and also
782 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
783 $dbw->insert( 'image',
784 array(
785 'img_name' => $name,
786 'img_size'=> $size,
787 'img_timestamp' => $dbw->timestamp($now),
788 'img_description' => $desc,
789 'img_user' => $wgUser->getID(),
790 'img_user_text' => $wgUser->getName(),
791 ), $fname, 'IGNORE'
792 );
793 $descTitle = Title::makeTitleSafe( NS_IMAGE, $name );
794
795 if ( $dbw->affectedRows() ) {
796 # Successfully inserted, this is a new image
797 $id = $descTitle->getArticleID();
798
799 if ( $id == 0 ) {
800 $article = new Article( $descTitle );
801 $article->insertNewArticle( $textdesc, $desc, false, false, true );
802 }
803 } else {
804 # Collision, this is an update of an image
805 # Get current image row for update
806 $s = $dbw->selectRow( 'image', array( 'img_name','img_size','img_timestamp','img_description',
807 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
808
809 # Insert it into oldimage
810 $dbw->insert( 'oldimage',
811 array(
812 'oi_name' => $s->img_name,
813 'oi_archive_name' => $oldver,
814 'oi_size' => $s->img_size,
815 'oi_timestamp' => $dbw->timestamp($s->img_timestamp),
816 'oi_description' => $s->img_description,
817 'oi_user' => $s->img_user,
818 'oi_user_text' => $s->img_user_text
819 ), $fname
820 );
821
822 # Update the current image row
823 $dbw->update( 'image',
824 array( /* SET */
825 'img_size' => $size,
826 'img_timestamp' => $dbw->timestamp(),
827 'img_user' => $wgUser->getID(),
828 'img_user_text' => $wgUser->getName(),
829 'img_description' => $desc,
830 ), array( /* WHERE */
831 'img_name' => $name
832 ), $fname
833 );
834
835 # Invalidate the cache for the description page
836 $descTitle->invalidateCache();
837 }
838
839 $log = new LogPage( 'upload' );
840 $log->addEntry( 'upload', $descTitle, $desc );
841 }
842
843 /**
844 * Returns the image URL of an image's old version
845 *
846 * @param string $fname file name of the image file
847 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
848 * @access public
849 */
850 function wfImageArchiveUrl( $name, $subdir='archive' ) {
851 global $wgUploadPath, $wgHashedUploadDirectory;
852
853 if ($wgHashedUploadDirectory) {
854 $hash = md5( substr( $name, 15) );
855 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
856 substr( $hash, 0, 2 ) . '/'.$name;
857 } else {
858 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
859 }
860 return wfUrlencode($url);
861 }
862
863 /**
864 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
865 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
866 *
867 * @param string $length
868 * @return int Length in pixels
869 */
870 function scaleSVGUnit( $length ) {
871 static $unitLength = array(
872 'px' => 1.0,
873 'pt' => 1.25,
874 'pc' => 15.0,
875 'mm' => 3.543307,
876 'cm' => 35.43307,
877 'in' => 90.0,
878 '' => 1.0, // "User units" pixels by default
879 '%' => 2.0, // Fake it!
880 );
881 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
882 $length = FloatVal( $matches[1] );
883 $unit = $matches[2];
884 return round( $length * $unitLength[$unit] );
885 } else {
886 // Assume pixels
887 return round( FloatVal( $length ) );
888 }
889 }
890
891 /**
892 * Compatible with PHP getimagesize()
893 * @todo support gzipped SVGZ
894 * @todo check XML more carefully
895 * @todo sensible defaults
896 *
897 * @param string $filename
898 * @return array
899 */
900 function getSVGsize( $filename ) {
901 $width = 256;
902 $height = 256;
903
904 // Read a chunk of the file
905 $f = fopen( $filename, "rt" );
906 if( !$f ) return false;
907 $chunk = fread( $f, 4096 );
908 fclose( $f );
909
910 // Uber-crappy hack! Run through a real XML parser.
911 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
912 return false;
913 }
914 $tag = $matches[1];
915 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
916 $width = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
917 }
918 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
919 $height = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
920 }
921
922 return array( $width, $height, 'SVG',
923 "width=\"$width\" height=\"$height\"" );
924 }
925
926
927 /**
928 * Wrapper class for thumbnail images
929 * @package MediaWiki
930 */
931 class ThumbnailImage {
932 /**
933 * @param string $path Filesystem path to the thumb
934 * @param string $url URL path to the thumb
935 * @access private
936 */
937 function ThumbnailImage( $path, $url ) {
938 $this->url = $url;
939 $this->path = $path;
940 $size = @getimagesize( $this->path );
941 if( $size ) {
942 $this->width = $size[0];
943 $this->height = $size[1];
944 } else {
945 $this->width = 0;
946 $this->height = 0;
947 }
948 }
949
950 /**
951 * @return string The thumbnail URL
952 */
953 function getUrl() {
954 return $this->url;
955 }
956
957 /**
958 * Return HTML <img ... /> tag for the thumbnail, will include
959 * width and height attributes and a blank alt text (as required).
960 *
961 * You can set or override additional attributes by passing an
962 * associative array of name => data pairs. The data will be escaped
963 * for HTML output, so should be in plaintext.
964 *
965 * @param array $attribs
966 * @return string
967 * @access public
968 */
969 function toHtml( $attribs = array() ) {
970 $attribs['src'] = $this->url;
971 $attribs['width'] = $this->width;
972 $attribs['height'] = $this->height;
973 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
974
975 $html = '<img ';
976 foreach( $attribs as $name => $data ) {
977 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
978 }
979 $html .= '/>';
980 return $html;
981 }
982
983 /**
984 * Return the size of the thumbnail file, in bytes or false if the file
985 * can't be stat().
986 * @access public
987 */
988 function getSize() {
989 $st = stat( $this->path );
990 if( $st ) {
991 return $st['size'];
992 } else {
993 return false;
994 }
995 }
996 }
997 ?>