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