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