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