3631a07d15977857e0737bced49b0f587cd0c76a
[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 $exif, # EXIF data
33 $dataLoaded; # Whether or not all this has been loaded from the database (loadFromXxx)
34
35
36 /**#@-*/
37
38 /**
39 * Create an Image object from an image name
40 *
41 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
42 * @access public
43 */
44 function newFromName( $name ) {
45 $title = Title::makeTitleSafe( NS_IMAGE, $name );
46 return new Image( $title );
47 }
48
49 /**
50 * Obsolete factory function, use constructor
51 */
52 function newFromTitle( $title ) {
53 return new Image( $title );
54 }
55
56 function Image( $title ) {
57 $this->title =& $title;
58 $this->name = $title->getDBkey();
59 $this->exif = serialize ( array() ) ;
60
61 $n = strrpos( $this->name, '.' );
62 $this->extension = strtolower( $n ? substr( $this->name, $n + 1 ) : '' );
63 $this->historyLine = 0;
64
65 $this->dataLoaded = false;
66 }
67
68 /**
69 * Get the memcached keys
70 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
71 */
72 function getCacheKeys( $shared = false ) {
73 global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
74
75 $foundCached = false;
76 $hashedName = md5($this->name);
77 $keys = array( "$wgDBname:Image:$hashedName" );
78 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
79 $keys[] = "$wgSharedUploadDBname:Image:$hashedName";
80 }
81 return $keys;
82 }
83
84 /**
85 * Try to load image metadata from memcached. Returns true on success.
86 */
87 function loadFromCache() {
88 global $wgUseSharedUploads, $wgMemc;
89 $fname = 'Image::loadFromMemcached';
90 wfProfileIn( $fname );
91 $this->dataLoaded = false;
92 $keys = $this->getCacheKeys();
93 $cachedValues = $wgMemc->get( $keys[0] );
94
95 // Check if the key existed and belongs to this version of MediaWiki
96 if (!empty($cachedValues) && is_array($cachedValues) && isset($cachedValues['width']) && $cachedValues['fileExists']) {
97 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
98 # if this is shared file, we need to check if image
99 # in shared repository has not changed
100 if ( isset( $keys[1] ) ) {
101 $commonsCachedValues = $wgMemc->get( $keys[1] );
102 if (!empty($commonsCachedValues) && is_array($commonsCachedValues) && isset($commonsCachedValues['width'])) {
103 $this->name = $commonsCachedValues['name'];
104 $this->imagePath = $commonsCachedValues['imagePath'];
105 $this->fileExists = $commonsCachedValues['fileExists'];
106 $this->width = $commonsCachedValues['width'];
107 $this->height = $commonsCachedValues['height'];
108 $this->bits = $commonsCachedValues['bits'];
109 $this->type = $commonsCachedValues['type'];
110 $this->exif = $commonsCachedValues['exif'];
111 $this->size = $commonsCachedValues['size'];
112 $this->fromSharedDirectory = true;
113 $this->dataLoaded = true;
114 $this->imagePath = $this->getFullPath(true);
115 }
116 }
117 }
118 else {
119 $this->name = $cachedValues['name'];
120 $this->imagePath = $cachedValues['imagePath'];
121 $this->fileExists = $cachedValues['fileExists'];
122 $this->width = $cachedValues['width'];
123 $this->height = $cachedValues['height'];
124 $this->bits = $cachedValues['bits'];
125 $this->type = $cachedValues['type'];
126 $this->exif = $cachedValues['exif'];
127 $this->size = $cachedValues['size'];
128 $this->fromSharedDirectory = false;
129 $this->dataLoaded = true;
130 $this->imagePath = $this->getFullPath();
131 }
132 }
133
134 wfProfileOut( $fname );
135 return $this->dataLoaded;
136 }
137
138 /**
139 * Save the image metadata to memcached
140 */
141 function saveToCache() {
142 global $wgMemc;
143 $this->load();
144 // We can't cache metadata for non-existent files, because if the file later appears
145 // in commons, the local keys won't be purged.
146 if ( $this->fileExists ) {
147 $keys = $this->getCacheKeys();
148
149 $cachedValues = array('name' => $this->name,
150 'imagePath' => $this->imagePath,
151 'fileExists' => $this->fileExists,
152 'fromShared' => $this->fromSharedDirectory,
153 'width' => $this->width,
154 'height' => $this->height,
155 'bits' => $this->bits,
156 'type' => $this->type,
157 'exif' => $this->exif,
158 'size' => $this->size);
159
160 $wgMemc->set( $keys[0], $cachedValues );
161 }
162 }
163
164 /**
165 * Load metadata from the file itself
166 */
167 function loadFromFile() {
168 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgLang;
169 $fname = 'Image::loadFromFile';
170 wfProfileIn( $fname );
171 $this->imagePath = $this->getFullPath();
172 $this->fileExists = file_exists( $this->imagePath );
173 $this->fromSharedDirectory = false;
174 $gis = false;
175
176 # If the file is not found, and a shared upload directory is used, look for it there.
177 if (!$this->fileExists && $wgUseSharedUploads && $wgSharedUploadDirectory) {
178 # In case we're on a wgCapitalLinks=false wiki, we
179 # capitalize the first letter of the filename before
180 # looking it up in the shared repository.
181 $sharedImage = Image::newFromName( $wgLang->ucfirst($this->name) );
182 $this->fileExists = file_exists( $sharedImage->getFullPath(true) );
183 if ( $this->fileExists ) {
184 $this->name = $sharedImage->name;
185 $this->imagePath = $this->getFullPath(true);
186 $this->fromSharedDirectory = true;
187 }
188 }
189
190 if ( $this->fileExists ) {
191 # Get size in bytes
192 $this->size = filesize( $this->imagePath );
193
194 # Height and width
195 # Don't try to get the width and height of sound and video files, that's bad for performance
196 if ( !Image::isKnownImageExtension( $this->extension ) ) {
197 $gis = false;
198 } elseif( $this->extension == 'svg' ) {
199 wfSuppressWarnings();
200 $gis = wfGetSVGsize( $this->imagePath );
201 wfRestoreWarnings();
202 } else {
203 wfSuppressWarnings();
204 $gis = getimagesize( $this->imagePath );
205 wfRestoreWarnings();
206 }
207 }
208 if( $gis === false ) {
209 $this->width = 0;
210 $this->height = 0;
211 $this->bits = 0;
212 $this->type = 0;
213 $this->exif = serialize ( array() ) ;
214 } else {
215 $this->width = $gis[0];
216 $this->height = $gis[1];
217 $this->type = $gis[2];
218 $this->exif = serialize ( $this->retrieveExifData() ) ;
219 if ( isset( $gis['bits'] ) ) {
220 $this->bits = $gis['bits'];
221 } else {
222 $this->bits = 0;
223 }
224 }
225 $this->dataLoaded = true;
226 wfProfileOut( $fname );
227 }
228
229 /**
230 * Load image metadata from the DB
231 */
232 function loadFromDB() {
233 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgLang;
234 $fname = 'Image::loadFromDB';
235 wfProfileIn( $fname );
236
237 $dbr =& wfGetDB( DB_SLAVE );
238 $row = $dbr->selectRow( 'image',
239 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' , 'img_metadata' ),
240 array( 'img_name' => $this->name ), $fname );
241 if ( $row ) {
242 $this->fromSharedDirectory = false;
243 $this->fileExists = true;
244 $this->loadFromRow( $row );
245 $this->imagePath = $this->getFullPath();
246 // Check for rows from a previous schema, quietly upgrade them
247 if ( $this->type == -1 ) {
248 $this->upgradeRow();
249 }
250 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
251 # In case we're on a wgCapitalLinks=false wiki, we
252 # capitalize the first letter of the filename before
253 # looking it up in the shared repository.
254 $name = $wgLang->ucfirst($this->name);
255
256 $row = $dbr->selectRow( "`$wgSharedUploadDBname`.image",
257 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' ),
258 array( 'img_name' => $name ), $fname );
259 if ( $row ) {
260 $this->fromSharedDirectory = true;
261 $this->fileExists = true;
262 $this->imagePath = $this->getFullPath(true);
263 $this->name = $name;
264 $this->loadFromRow( $row );
265
266 // Check for rows from a previous schema, quietly upgrade them
267 if ( $this->type == -1 ) {
268 $this->upgradeRow();
269 }
270 }
271 }
272
273 if ( !$row ) {
274 $this->size = 0;
275 $this->width = 0;
276 $this->height = 0;
277 $this->bits = 0;
278 $this->type = 0;
279 $this->fileExists = false;
280 $this->fromSharedDirectory = false;
281 $this->exif = serialize ( array() ) ;
282 }
283
284 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
285 $this->dataLoaded = true;
286 }
287
288 /*
289 * Load image metadata from a DB result row
290 */
291 function loadFromRow( &$row ) {
292 $this->size = $row->img_size;
293 $this->width = $row->img_width;
294 $this->height = $row->img_height;
295 $this->bits = $row->img_bits;
296 $this->type = $row->img_type;
297 $this->exif = $row->img_metadata;
298 if ( $this->exif == "" ) $this->exif = serialize ( array() ) ;
299 $this->dataLoaded = true;
300 }
301
302 /**
303 * Load image metadata from cache or DB, unless already loaded
304 */
305 function load() {
306 global $wgSharedUploadDBname, $wgUseSharedUploads;
307 if ( !$this->dataLoaded ) {
308 if ( !$this->loadFromCache() ) {
309 $this->loadFromDB();
310 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
311 $this->loadFromFile();
312 } elseif ( $this->fileExists ) {
313 $this->saveToCache();
314 }
315 }
316 $this->dataLoaded = true;
317 }
318 }
319
320 /**
321 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
322 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
323 */
324 function upgradeRow() {
325 global $wgDBname, $wgSharedUploadDBname;
326 $fname = 'Image::upgradeRow';
327 $this->loadFromFile();
328 $dbw =& wfGetDB( DB_MASTER );
329
330 if ( $this->fromSharedDirectory ) {
331 if ( !$wgSharedUploadDBname ) {
332 return;
333 }
334
335 // Write to the other DB using selectDB, not database selectors
336 // This avoids breaking replication in MySQL
337 $dbw->selectDB( $wgSharedUploadDBname );
338 }
339 $dbw->update( '`image`',
340 array(
341 'img_width' => $this->width,
342 'img_height' => $this->height,
343 'img_bits' => $this->bits,
344 'img_type' => $this->type,
345 'img_metadata' => $this->exif,
346 ), array( 'img_name' => $this->name ), $fname
347 );
348 if ( $this->fromSharedDirectory ) {
349 $dbw->selectDB( $wgDBname );
350 }
351 }
352
353 /**
354 * Return the name of this image
355 * @access public
356 */
357 function getName() {
358 return $this->name;
359 }
360
361 /**
362 * Return the associated title object
363 * @access public
364 */
365 function getTitle() {
366 return $this->title;
367 }
368
369 /**
370 * Return the URL of the image file
371 * @access public
372 */
373 function getURL() {
374 if ( !$this->url ) {
375 $this->load();
376 if($this->fileExists) {
377 $this->url = Image::imageUrl( $this->name, $this->fromSharedDirectory );
378 } else {
379 $this->url = '';
380 }
381 }
382 return $this->url;
383 }
384
385 function getViewURL() {
386 if( $this->mustRender() ) {
387 return $this->createThumb( $this->getWidth() );
388 } else {
389 return $this->getURL();
390 }
391 }
392
393 /**
394 * Return the image path of the image in the
395 * local file system as an absolute path
396 * @access public
397 */
398 function getImagePath() {
399 $this->load();
400 return $this->imagePath;
401 }
402
403 /**
404 * Return the width of the image
405 *
406 * Returns -1 if the file specified is not a known image type
407 * @access public
408 */
409 function getWidth() {
410 $this->load();
411 return $this->width;
412 }
413
414 /**
415 * Return the height of the image
416 *
417 * Returns -1 if the file specified is not a known image type
418 * @access public
419 */
420 function getHeight() {
421 $this->load();
422 return $this->height;
423 }
424
425 /**
426 * Return the size of the image file, in bytes
427 * @access public
428 */
429 function getSize() {
430 $this->load();
431 return $this->size;
432 }
433
434 /**
435 * Return the type of the image
436 *
437 * - 1 GIF
438 * - 2 JPG
439 * - 3 PNG
440 * - 15 WBMP
441 * - 16 XBM
442 */
443 function getType() {
444 $this->load();
445 return $this->type;
446 }
447
448 /**
449 * Return the escapeLocalURL of this image
450 * @access public
451 */
452 function getEscapeLocalURL() {
453 $this->getTitle();
454 return $this->title->escapeLocalURL();
455 }
456
457 /**
458 * Return the escapeFullURL of this image
459 * @access public
460 */
461 function getEscapeFullURL() {
462 $this->getTitle();
463 return $this->title->escapeFullURL();
464 }
465
466 /**
467 * Return the URL of an image, provided its name.
468 *
469 * @param string $name Name of the image, without the leading "Image:"
470 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
471 * @access public
472 * @static
473 */
474 function imageUrl( $name, $fromSharedDirectory = false ) {
475 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
476 if($fromSharedDirectory) {
477 $base = '';
478 $path = $wgSharedUploadPath;
479 } else {
480 $base = $wgUploadBaseUrl;
481 $path = $wgUploadPath;
482 }
483 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
484 return wfUrlencode( $url );
485 }
486
487 /**
488 * Returns true if the image file exists on disk.
489 *
490 * @access public
491 */
492 function exists() {
493 $this->load();
494 return $this->fileExists;
495 }
496
497 /**
498 *
499 * @access private
500 */
501 function thumbUrl( $width, $subdir='thumb') {
502 global $wgUploadPath, $wgUploadBaseUrl,
503 $wgSharedUploadPath,$wgSharedUploadDirectory,
504 $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
505
506 // Generate thumb.php URL if possible
507 $script = false;
508 $url = false;
509
510 if ( $this->fromSharedDirectory ) {
511 if ( $wgSharedThumbnailScriptPath ) {
512 $script = $wgSharedThumbnailScriptPath;
513 }
514 } else {
515 if ( $wgThumbnailScriptPath ) {
516 $script = $wgThumbnailScriptPath;
517 }
518 }
519 if ( $script ) {
520 $url = $script . '?f=' . urlencode( $this->name ) . '&w=' . urlencode( $width );
521 } else {
522 $name = $this->thumbName( $width );
523 if($this->fromSharedDirectory) {
524 $base = '';
525 $path = $wgSharedUploadPath;
526 } else {
527 $base = $wgUploadBaseUrl;
528 $path = $wgUploadPath;
529 }
530 if ( Image::isHashed( $this->fromSharedDirectory ) ) {
531 $url = "{$base}{$path}/{$subdir}" .
532 wfGetHashPath($this->name, $this->fromSharedDirectory)
533 . $this->name.'/'.$name;
534 $url = wfUrlencode( $url );
535 } else {
536 $url = "{$base}{$path}/{$subdir}/{$name}";
537 }
538 }
539 return array( $script !== false, $url );
540 }
541
542 /**
543 * Return the file name of a thumbnail of the specified width
544 *
545 * @param integer $width Width of the thumbnail image
546 * @param boolean $shared Does the thumbnail come from the shared repository?
547 * @access private
548 */
549 function thumbName( $width ) {
550 $thumb = $width."px-".$this->name;
551 if( $this->extension == 'svg' ) {
552 # Rasterize SVG vector images to PNG
553 $thumb .= '.png';
554 }
555 return $thumb;
556 }
557
558 /**
559 * Create a thumbnail of the image having the specified width/height.
560 * The thumbnail will not be created if the width is larger than the
561 * image's width. Let the browser do the scaling in this case.
562 * The thumbnail is stored on disk and is only computed if the thumbnail
563 * file does not exist OR if it is older than the image.
564 * Returns the URL.
565 *
566 * Keeps aspect ratio of original image. If both width and height are
567 * specified, the generated image will be no bigger than width x height,
568 * and will also have correct aspect ratio.
569 *
570 * @param integer $width maximum width of the generated thumbnail
571 * @param integer $height maximum height of the image (optional)
572 * @access public
573 */
574 function createThumb( $width, $height=-1 ) {
575 $thumb = $this->getThumbnail( $width, $height );
576 if( is_null( $thumb ) ) return '';
577 return $thumb->getUrl();
578 }
579
580 /**
581 * As createThumb, but returns a ThumbnailImage object. This can
582 * provide access to the actual file, the real size of the thumb,
583 * and can produce a convenient <img> tag for you.
584 *
585 * @param integer $width maximum width of the generated thumbnail
586 * @param integer $height maximum height of the image (optional)
587 * @return ThumbnailImage
588 * @access public
589 */
590 function &getThumbnail( $width, $height=-1 ) {
591 if ( $height == -1 ) {
592 return $this->renderThumb( $width );
593 }
594 $this->load();
595 if ( $width < $this->width ) {
596 $thumbheight = $this->height * $width / $this->width;
597 $thumbwidth = $width;
598 } else {
599 $thumbheight = $this->height;
600 $thumbwidth = $this->width;
601 }
602 if ( $thumbheight > $height ) {
603 $thumbwidth = $thumbwidth * $height / $thumbheight;
604 $thumbheight = $height;
605 }
606 $thumb = $this->renderThumb( $thumbwidth );
607 if( is_null( $thumb ) ) {
608 $thumb = $this->iconThumb();
609 }
610 return $thumb;
611 }
612
613 /**
614 * @return ThumbnailImage
615 */
616 function iconThumb() {
617 global $wgStylePath, $wgStyleDirectory;
618
619 $try = array( 'fileicon-' . $this->extension . '.png', 'fileicon.png' );
620 foreach( $try as $icon ) {
621 $path = '/common/images/' . $icon;
622 $filepath = $wgStyleDirectory . $path;
623 if( file_exists( $filepath ) ) {
624 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
625 }
626 }
627 return null;
628 }
629
630 /**
631 * Create a thumbnail of the image having the specified width.
632 * The thumbnail will not be created if the width is larger than the
633 * image's width. Let the browser do the scaling in this case.
634 * The thumbnail is stored on disk and is only computed if the thumbnail
635 * file does not exist OR if it is older than the image.
636 * Returns an object which can return the pathname, URL, and physical
637 * pixel size of the thumbnail -- or null on failure.
638 *
639 * @return ThumbnailImage
640 * @access private
641 */
642 function /* private */ renderThumb( $width, $useScript = true ) {
643 global $wgUseSquid, $wgInternalServer;
644 global $wgThumbnailScriptPath, $wgSharedThumbnailScriptPath;
645
646 $width = IntVal( $width );
647
648 $this->load();
649 if ( ! $this->exists() )
650 {
651 # If there is no image, there will be no thumbnail
652 return null;
653 }
654
655 # Sanity check $width
656 if( $width <= 0 ) {
657 # BZZZT
658 return null;
659 }
660
661 if( $width > $this->width && !$this->mustRender() ) {
662 # Don't make an image bigger than the source
663 return new ThumbnailImage( $this->getViewURL(), $this->getWidth(), $this->getHeight() );
664 }
665
666 $height = floor( $this->height * ( $width/$this->width ) );
667
668 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
669 if ( $isScriptUrl && $useScript ) {
670 // Use thumb.php to render the image
671 return new ThumbnailImage( $url, $width, $height );
672 }
673
674 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory );
675 $thumbPath = wfImageThumbDir( $this->name, $this->fromSharedDirectory ).'/'.$thumbName;
676
677 if ( !file_exists( $thumbPath ) ) {
678 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory ).
679 '/'.$thumbName;
680 $done = false;
681 if ( file_exists( $oldThumbPath ) ) {
682 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath) ) {
683 rename( $oldThumbPath, $thumbPath );
684 $done = true;
685 } else {
686 unlink( $oldThumbPath );
687 }
688 }
689 if ( !$done ) {
690 $this->reallyRenderThumb( $thumbPath, $width, $height );
691
692 # Purge squid
693 # This has to be done after the image is updated and present for all machines on NFS,
694 # or else the old version might be stored into the squid again
695 if ( $wgUseSquid ) {
696 if ( substr( $url, 0, 4 ) == 'http' ) {
697 $urlArr = array( $url );
698 } else {
699 $urlArr = array( $wgInternalServer.$url );
700 }
701 wfPurgeSquidServers($urlArr);
702 }
703 }
704 }
705 return new ThumbnailImage( $url, $width, $height, $thumbPath );
706 } // END OF function renderThumb
707
708 /**
709 * Really render a thumbnail
710 *
711 * @access private
712 */
713 function /*private*/ reallyRenderThumb( $thumbPath, $width, $height ) {
714 global $wgSVGConverters, $wgSVGConverter,
715 $wgUseImageMagick, $wgImageMagickConvertCommand;
716
717 $this->load();
718
719 if( $this->extension == 'svg' ) {
720 global $wgSVGConverters, $wgSVGConverter;
721 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
722 global $wgSVGConverterPath;
723 $cmd = str_replace(
724 array( '$path/', '$width', '$input', '$output' ),
725 array( $wgSVGConverterPath,
726 $width,
727 escapeshellarg( $this->imagePath ),
728 escapeshellarg( $thumbPath ) ),
729 $wgSVGConverters[$wgSVGConverter] );
730 $conv = shell_exec( $cmd );
731 } else {
732 $conv = false;
733 }
734 } elseif ( $wgUseImageMagick ) {
735 # use ImageMagick
736 # Specify white background color, will be used for transparent images
737 # in Internet Explorer/Windows instead of default black.
738 $cmd = $wgImageMagickConvertCommand .
739 " -quality 85 -background white -geometry {$width} ".
740 escapeshellarg($this->imagePath) . " " .
741 escapeshellarg($thumbPath);
742 $conv = shell_exec( $cmd );
743 } else {
744 # Use PHP's builtin GD library functions.
745 #
746 # First find out what kind of file this is, and select the correct
747 # input routine for this.
748
749 $truecolor = false;
750
751 switch( $this->type ) {
752 case 1: # GIF
753 $src_image = imagecreatefromgif( $this->imagePath );
754 break;
755 case 2: # JPG
756 $src_image = imagecreatefromjpeg( $this->imagePath );
757 $truecolor = true;
758 break;
759 case 3: # PNG
760 $src_image = imagecreatefrompng( $this->imagePath );
761 $truecolor = ( $this->bits > 8 );
762 break;
763 case 15: # WBMP for WML
764 $src_image = imagecreatefromwbmp( $this->imagePath );
765 break;
766 case 16: # XBM
767 $src_image = imagecreatefromxbm( $this->imagePath );
768 break;
769 default:
770 return 'Image type not supported';
771 break;
772 }
773 if ( $truecolor ) {
774 $dst_image = imagecreatetruecolor( $width, $height );
775 } else {
776 $dst_image = imagecreate( $width, $height );
777 }
778 imagecopyresampled( $dst_image, $src_image,
779 0,0,0,0,
780 $width, $height, $this->width, $this->height );
781 switch( $this->type ) {
782 case 1: # GIF
783 case 3: # PNG
784 case 15: # WBMP
785 case 16: # XBM
786 imagepng( $dst_image, $thumbPath );
787 break;
788 case 2: # JPEG
789 imageinterlace( $dst_image );
790 imagejpeg( $dst_image, $thumbPath, 95 );
791 break;
792 default:
793 break;
794 }
795 imagedestroy( $dst_image );
796 imagedestroy( $src_image );
797 }
798 #
799 # Check for zero-sized thumbnails. Those can be generated when
800 # no disk space is available or some other error occurs
801 #
802 if( file_exists( $thumbPath ) ) {
803 $thumbstat = stat( $thumbPath );
804 if( $thumbstat['size'] == 0 ) {
805 unlink( $thumbPath );
806 }
807 }
808 }
809
810 /**
811 * Get all thumbnail names previously generated for this image
812 */
813 function getThumbnails( $shared = false ) {
814 if ( Image::isHashed( $shared ) ) {
815 $this->load();
816 $files = array();
817 $dir = wfImageThumbDir( $this->name, $shared );
818
819 // This generates an error on failure, hence the @
820 $handle = @opendir( $dir );
821
822 if ( $handle ) {
823 while ( false !== ( $file = readdir($handle) ) ) {
824 if ( $file{0} != '.' ) {
825 $files[] = $file;
826 }
827 }
828 closedir( $handle );
829 }
830 } else {
831 $files = array();
832 }
833
834 return $files;
835 }
836
837 /**
838 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
839 */
840 function purgeCache( $archiveFiles = array(), $shared = false ) {
841 global $wgInternalServer, $wgUseSquid;
842
843 // Refresh metadata cache
844 clearstatcache();
845 $this->loadFromFile();
846 $this->saveToCache();
847
848 // Delete thumbnails
849 $files = $this->getThumbnails( $shared );
850 $dir = wfImageThumbDir( $this->name, $shared );
851 $urls = array();
852 foreach ( $files as $file ) {
853 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
854 $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory );
855 @unlink( "$dir/$file" );
856 }
857 }
858
859 // Purge the squid
860 if ( $wgUseSquid ) {
861 $urls[] = $wgInternalServer . $this->getViewURL();
862 foreach ( $archiveFiles as $file ) {
863 $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
864 }
865 wfPurgeSquidServers( $urls );
866 }
867 }
868
869 /**
870 * Return the image history of this image, line by line.
871 * starts with current version, then old versions.
872 * uses $this->historyLine to check which line to return:
873 * 0 return line for current version
874 * 1 query for old versions, return first one
875 * 2, ... return next old version from above query
876 *
877 * @access public
878 */
879 function nextHistoryLine() {
880 $fname = 'Image::nextHistoryLine()';
881 $dbr =& wfGetDB( DB_SLAVE );
882 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
883 $this->historyRes = $dbr->select( 'image',
884 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
885 array( 'img_name' => $this->title->getDBkey() ),
886 $fname
887 );
888 if ( 0 == wfNumRows( $this->historyRes ) ) {
889 return FALSE;
890 }
891 } else if ( $this->historyLine == 1 ) {
892 $this->historyRes = $dbr->select( 'oldimage',
893 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
894 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
895 ), array( 'oi_name' => $this->title->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
896 );
897 }
898 $this->historyLine ++;
899
900 return $dbr->fetchObject( $this->historyRes );
901 }
902
903 /**
904 * Reset the history pointer to the first element of the history
905 * @access public
906 */
907 function resetHistory() {
908 $this->historyLine = 0;
909 }
910
911 /**
912 * Return true if the file is of a type that can't be directly
913 * rendered by typical browsers and needs to be re-rasterized.
914 * @return bool
915 */
916 function mustRender() {
917 $this->load();
918 return ( $this->extension == 'svg' );
919 }
920
921 /**
922 * Return the full filesystem path to the file. Note that this does
923 * not mean that a file actually exists under that location.
924 *
925 * This path depends on whether directory hashing is active or not,
926 * i.e. whether the images are all found in the same directory,
927 * or in hashed paths like /images/3/3c.
928 *
929 * @access public
930 * @param boolean $fromSharedDirectory Return the path to the file
931 * in a shared repository (see $wgUseSharedRepository and related
932 * options in DefaultSettings.php) instead of a local one.
933 *
934 */
935 function getFullPath( $fromSharedRepository = false ) {
936 global $wgUploadDirectory, $wgSharedUploadDirectory;
937 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
938
939 $dir = $fromSharedRepository ? $wgSharedUploadDirectory :
940 $wgUploadDirectory;
941
942 // $wgSharedUploadDirectory may be false, if thumb.php is used
943 if ( $dir ) {
944 $fullpath = $dir . wfGetHashPath($this->name, $fromSharedRepository) . $this->name;
945 } else {
946 $fullpath = false;
947 }
948
949 return $fullpath;
950 }
951
952 /**
953 * @return bool
954 * @static
955 */
956 function isHashed( $shared ) {
957 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
958 return $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
959 }
960
961 /**
962 * @return bool
963 * @static
964 */
965 function isKnownImageExtension( $ext ) {
966 static $extensions = array( 'svg', 'png', 'jpg', 'jpeg', 'gif', 'bmp', 'xbm' );
967 return in_array( $ext, $extensions );
968 }
969
970 /**
971 * Record an image upload in the upload log and the image table
972 */
973 function recordUpload( $oldver, $desc, $copyStatus = '', $source = '' ) {
974 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
975 global $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
976
977 $fname = 'Image::recordUpload';
978 $dbw =& wfGetDB( DB_MASTER );
979
980 # img_name must be unique
981 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
982 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
983 }
984
985 // Delete thumbnails and refresh the metadata cache
986 $this->purgeCache();
987
988 // Fail now if the image isn't there
989 if ( !$this->fileExists || $this->fromSharedDirectory ) {
990 return false;
991 }
992
993 if ( $wgUseCopyrightUpload ) {
994 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
995 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
996 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
997 } else {
998 $textdesc = $desc;
999 }
1000
1001 $now = $dbw->timestamp();
1002
1003 # Test to see if the row exists using INSERT IGNORE
1004 # This avoids race conditions by locking the row until the commit, and also
1005 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1006 $dbw->insert( 'image',
1007 array(
1008 'img_name' => $this->name,
1009 'img_size'=> $this->size,
1010 'img_width' => $this->width,
1011 'img_height' => $this->height,
1012 'img_bits' => $this->bits,
1013 'img_type' => $this->type,
1014 'img_timestamp' => $now,
1015 'img_description' => $desc,
1016 'img_user' => $wgUser->getID(),
1017 'img_user_text' => $wgUser->getName(),
1018 'img_metadata' => $this->exif,
1019 ), $fname, 'IGNORE'
1020 );
1021 $descTitle = $this->getTitle();
1022 $purgeURLs = array();
1023
1024 if ( $dbw->affectedRows() ) {
1025 # Successfully inserted, this is a new image
1026 $id = $descTitle->getArticleID();
1027
1028 if ( $id == 0 ) {
1029 $article = new Article( $descTitle );
1030 $article->insertNewArticle( $textdesc, $desc, false, false, true );
1031 }
1032 } else {
1033 # Collision, this is an update of an image
1034 # Insert previous contents into oldimage
1035 $dbw->insertSelect( 'oldimage', 'image',
1036 array(
1037 'oi_name' => 'img_name',
1038 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1039 'oi_size' => 'img_size',
1040 'oi_width' => 'img_width',
1041 'oi_height' => 'img_height',
1042 'oi_bits' => 'img_bits',
1043 'oi_type' => 'img_type',
1044 'oi_timestamp' => 'img_timestamp',
1045 'oi_description' => 'img_description',
1046 'oi_user' => 'img_user',
1047 'oi_user_text' => 'img_user_text',
1048 ), array( 'img_name' => $this->name ), $fname
1049 );
1050
1051 # Update the current image row
1052 $dbw->update( 'image',
1053 array( /* SET */
1054 'img_size' => $this->size,
1055 'img_width' => $this->width,
1056 'img_height' => $this->height,
1057 'img_bits' => $this->bits,
1058 'img_type' => $this->type,
1059 'img_timestamp' => $now,
1060 'img_user' => $wgUser->getID(),
1061 'img_user_text' => $wgUser->getName(),
1062 'img_description' => $desc,
1063 'img_metadata' => $this->exif,
1064 ), array( /* WHERE */
1065 'img_name' => $this->name
1066 ), $fname
1067 );
1068
1069 # Invalidate the cache for the description page
1070 $descTitle->invalidateCache();
1071 $purgeURLs[] = $descTitle->getInternalURL();
1072 }
1073
1074 # Invalidate cache for all pages using this image
1075 $linksTo = $this->getLinksTo();
1076
1077 if ( $wgUseSquid ) {
1078 $u = SquidUpdate::newFromTitles( $linksTo, $purgeURLs );
1079 array_push( $wgPostCommitUpdateList, $u );
1080 }
1081 Title::touchArray( $linksTo );
1082
1083 $log = new LogPage( 'upload' );
1084 $log->addEntry( 'upload', $descTitle, $desc );
1085
1086 return true;
1087 }
1088
1089 /**
1090 * Get an array of Title objects which are articles which use this image
1091 * Also adds their IDs to the link cache
1092 *
1093 * This is mostly copied from Title::getLinksTo()
1094 */
1095 function getLinksTo( $options = '' ) {
1096 global $wgLinkCache;
1097 $fname = 'Image::getLinksTo';
1098 wfProfileIn( $fname );
1099
1100 if ( $options ) {
1101 $db =& wfGetDB( DB_MASTER );
1102 } else {
1103 $db =& wfGetDB( DB_SLAVE );
1104 }
1105
1106 extract( $db->tableNames( 'page', 'imagelinks' ) );
1107 $encName = $db->addQuotes( $this->name );
1108 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1109 $res = $db->query( $sql, $fname );
1110
1111 $retVal = array();
1112 if ( $db->numRows( $res ) ) {
1113 while ( $row = $db->fetchObject( $res ) ) {
1114 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1115 $wgLinkCache->addGoodLink( $row->page_id, $titleObj->getPrefixedDBkey() );
1116 $retVal[] = $titleObj;
1117 }
1118 }
1119 }
1120 $db->freeResult( $res );
1121 return $retVal;
1122 }
1123
1124 function retrieveExifData () {
1125 global $wgShowEXIF ;
1126 if ( ! $wgShowEXIF ) return array ();
1127 if ( $this->type !== '2' ) return array ();
1128
1129 $exif = exif_read_data( $this->imagePath );
1130 $exif = $this->stripExifData( $exif );
1131 return $exif ;
1132 }
1133
1134 function getExifData () {
1135 global $wgRequest, $wgShowEXIF;
1136
1137 if ( ! $wgShowEXIF ) return array ();
1138
1139 $action = $wgRequest->getVal( 'action' ); # Allow forced updates
1140
1141 $ret = unserialize ( $this->exif );
1142
1143 if ( count( $ret) == 0 || $action == 'purge' ) { # No EXIF data was stored for this image
1144 $this->updateExifData() ;
1145 $ret = unserialize ( $this->exif ) ;
1146 }
1147
1148 return $ret ;
1149 }
1150
1151 function updateExifData () {
1152 global $wgShowEXIF ;
1153 if ( ! $wgShowEXIF ) return ;
1154 if ( false === $this->getImagePath() ) return ; # Not a local image
1155
1156 $fname = "Image:updateExifData" ;
1157
1158 # Get EXIF data from image
1159 $exif = $this->retrieveExifData () ;
1160 $this->exif = serialize ( $exif ) ;
1161
1162 # Update EXIF data in database
1163 $dbw =& wfGetDB( DB_MASTER );
1164 $dbw->update( '`image`',
1165 array( 'img_metadata' => $this->exif ),
1166 array( 'img_name' => $this->name ),
1167 $fname
1168 );
1169 }
1170
1171 /**
1172 * Strip out potentially nasty exif data such as raw binaries
1173 * (thumbnails), these values are from version 2.2 of the EXIF
1174 * specification, note that I've commented some of them out, this is
1175 * because their Type is "UNDEFINED", meaning that they potentially
1176 * contain binary data.
1177 *
1178 * @author Ævar Arnfjörð Bjarmason <avarab@gmail.com>
1179 * @link http://exif.org/specifications.html
1180 * @link http://exif.org/Exif2-2.PDF (see page 22 and 30)
1181 *
1182 * @param array $exif
1183 * @return array
1184 */
1185 function stripExifData( $exif = array() ) {
1186 $whitelist = array(
1187 # Other tags
1188 'Make', # Image input equipment manufacturer
1189 'Model', # Image input equipment model
1190 'Software', # Software used
1191 'Artist', # Person who created the image
1192 'Copyright', # Copyright holder
1193
1194 # Tags relating to image structure
1195 'ImageWidth', # Image width
1196 'ImageLength', # Image height
1197 'Orientation', # Orientation of image
1198 'SamplesPerPixel', # Number of components
1199 'PlanarConfiguration', # Image data arrangement
1200 'YCbCrSubSampling', # Subsampling ratio of Y to C
1201 'YCbCrPositioning', # Y and C positioning
1202 'XResolution', # Image resolution in width direction
1203 'YResolution', # Image resolution in height direction
1204 'ResolutionUnit', # Unit of X and Y resolution
1205
1206 # Tags relating to recording offset
1207 'StripOffsets', # Image data location
1208 'RowsPerStrip', # Number of rows per strip
1209 'StripByteCounts', # Bytes per compressed strip
1210 'JPEGInterchangeFormat', # Offset to JPEG SOI
1211 'JPEGInterchangeFormatLength', # Bytes of JPEG data
1212
1213 # Tags relating to image data characteristics
1214 'TransferFunction', # Transfer function
1215 'WhitePoint', # White point chromaticity
1216 'PrimaryChromaticities', # Chromaticities of primarities
1217 'YCbCrCoefficients', # Color space transformation matrix coefficients
1218 'ReferenceBlackWhite', # Pair of black and white reference values
1219
1220 # Tags relating to version
1221 #'ExifVersion', # Exif version
1222 #'FlashpixVersion', # Supported Flashpix version
1223
1224 # Tags relating to Image Data Characteristics
1225 'ColorSpace', # Color space information
1226 #'ComponentsConfiguration', # Meaning of each component
1227 'CompressedBitsPerPixel', # Image compression mode
1228 'PixelYDimension', # Valid image width
1229 'PixelXDimension', # Valind image height
1230
1231 # Tags relating to User Information
1232 #'MakerNote', # Manufacturer notes
1233 #'UserComment', # User commentss
1234
1235 # Tag relating to related file information
1236 #'RelatedSoundFile', # Related audio file
1237
1238 # Other tags
1239 'ImageUniqueID', # Unique image ID
1240
1241 # Tags relating to picture-taking conditions
1242 'ExposureTime', # Exposure time
1243 'FNumber', # F Number
1244 'ExposureProgram', # Exposure Program
1245 'SpectralSensitivity', # Spectral sensitivity
1246 'ISOSpeedRatings', # ISO speed rating
1247 #'OECF', # Optoelectronic conversion factor
1248 'ShutterSpeedValue', # Shutter speed
1249 'ApertureValue', # Aperture
1250 'BrightnessValue', # Brightness
1251 'ExposureBiasValue', # Exposure bias
1252 'MaxApertureValue', # Maximum land aperture
1253 'SubjectDistance', # Subject distance
1254 'MeteringMode', # Metering mode
1255 'LightSource', # Light source
1256 'Flash', # Flash
1257 'FocalLength', # Lens focal length
1258 'SubjectArea', # Subject area
1259 'FlashEnergy', # Flash energy
1260 #'SpartialFrequencyResponse', # Spartial frequency response
1261 'FocalPlaneXRessolution', # Focal plane X resolution
1262 'FocalPlaneYRessolution', # Focal plane Y resolution
1263 'FocalPlaneResolutionUnit', # Focal plane resolution unit
1264 'SubjectLocation', # Subject location
1265 'ExposureIndex', # Exposure index
1266 'SensingMethod', # Sensing method
1267 #'FileSource', # File source
1268 #'SceneType', # Scene type
1269 #'CFAPattern', # CFA pattern
1270 'CustomRendered', # Custom image processing
1271 'ExposureMode', # Exposure mode
1272 'WhiteBalance', # White Balance
1273 'DigitalZoomRatio', # Digital zoom ration
1274 'FocalLengthIn35mmFilm', # Focal length in 35 mm film
1275 'SceneCaptureType', # Scene capture type
1276 'GainControl', # Scene control
1277 'Contrast', # Contrast
1278 'Saturation', # Saturation
1279 'Sharpness', # Sharpness
1280 #'DeviceSettingDescription', # Desice settings description
1281 'SubjectDistanceRange', # Subject distance range
1282
1283 # TODO: GPS attribute information on page 52 of the spec
1284 );
1285
1286 $new = array();
1287 foreach ($whitelist as $tag) {
1288 if ( array_key_exists($tag, $exif) ) {
1289 $new[$tag] = $exif[$tag];
1290 }
1291 }
1292 unset($exif);
1293 return $new;
1294 }
1295
1296
1297 } //class
1298
1299
1300 /**
1301 * Returns the image directory of an image
1302 * If the directory does not exist, it is created.
1303 * The result is an absolute path.
1304 *
1305 * This function is called from thumb.php before Setup.php is included
1306 *
1307 * @param string $fname file name of the image file
1308 * @access public
1309 */
1310 function wfImageDir( $fname ) {
1311 global $wgUploadDirectory, $wgHashedUploadDirectory;
1312
1313 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1314
1315 $hash = md5( $fname );
1316 $oldumask = umask(0);
1317 $dest = $wgUploadDirectory . '/' . $hash{0};
1318 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1319 $dest .= '/' . substr( $hash, 0, 2 );
1320 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1321
1322 umask( $oldumask );
1323 return $dest;
1324 }
1325
1326 /**
1327 * Returns the image directory of an image's thubnail
1328 * If the directory does not exist, it is created.
1329 * The result is an absolute path.
1330 *
1331 * This function is called from thumb.php before Setup.php is included
1332 *
1333 * @param string $fname file name of the original image file
1334 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
1335 * @param boolean $shared (optional) use the shared upload directory
1336 * @access public
1337 */
1338 function wfImageThumbDir( $fname, $shared = false ) {
1339 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1340 if ( Image::isHashed( $shared ) ) {
1341 $dir = "$base/$fname";
1342
1343 if ( !is_dir( $base ) ) {
1344 $oldumask = umask(0);
1345 @mkdir( $base, 0777 );
1346 umask( $oldumask );
1347 }
1348
1349 if ( ! is_dir( $dir ) ) {
1350 $oldumask = umask(0);
1351 @mkdir( $dir, 0777 );
1352 umask( $oldumask );
1353 }
1354 } else {
1355 $dir = $base;
1356 }
1357
1358 return $dir;
1359 }
1360
1361 /**
1362 * Old thumbnail directory, kept for conversion
1363 */
1364 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1365 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1366 }
1367
1368 /**
1369 * Returns the image directory of an image's old version
1370 * If the directory does not exist, it is created.
1371 * The result is an absolute path.
1372 *
1373 * This function is called from thumb.php before Setup.php is included
1374 *
1375 * @param string $fname file name of the thumbnail file, including file size prefix
1376 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
1377 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
1378 * @access public
1379 */
1380 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1381 global $wgUploadDirectory, $wgHashedUploadDirectory,
1382 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1383 $dir = $shared ? $wgSharedUploadDirectory : $wgUploadDirectory;
1384 $hashdir = $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1385 if (!$hashdir) { return $dir.'/'.$subdir; }
1386 $hash = md5( $fname );
1387 $oldumask = umask(0);
1388
1389 # Suppress warning messages here; if the file itself can't
1390 # be written we'll worry about it then.
1391 wfSuppressWarnings();
1392
1393 $archive = $dir.'/'.$subdir;
1394 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1395 $archive .= '/' . $hash{0};
1396 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1397 $archive .= '/' . substr( $hash, 0, 2 );
1398 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1399
1400 wfRestoreWarnings();
1401 umask( $oldumask );
1402 return $archive;
1403 }
1404
1405
1406 /*
1407 * Return the hash path component of an image path (URL or filesystem),
1408 * e.g. "/3/3c/", or just "/" if hashing is not used.
1409 *
1410 * @param $dbkey The filesystem / database name of the file
1411 * @param $fromSharedDirectory Use the shared file repository? It may
1412 * use different hash settings from the local one.
1413 */
1414 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1415 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
1416 global $wgHashedUploadDirectory;
1417
1418 if( Image::isHashed( $fromSharedDirectory ) ) {
1419 $hash = md5($dbkey);
1420 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1421 } else {
1422 return '/';
1423 }
1424 }
1425
1426 /**
1427 * Returns the image URL of an image's old version
1428 *
1429 * @param string $fname file name of the image file
1430 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1431 * @access public
1432 */
1433 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1434 global $wgUploadPath, $wgHashedUploadDirectory;
1435
1436 if ($wgHashedUploadDirectory) {
1437 $hash = md5( substr( $name, 15) );
1438 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1439 substr( $hash, 0, 2 ) . '/'.$name;
1440 } else {
1441 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1442 }
1443 return wfUrlencode($url);
1444 }
1445
1446 /**
1447 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1448 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1449 *
1450 * @param string $length
1451 * @return int Length in pixels
1452 */
1453 function wfScaleSVGUnit( $length ) {
1454 static $unitLength = array(
1455 'px' => 1.0,
1456 'pt' => 1.25,
1457 'pc' => 15.0,
1458 'mm' => 3.543307,
1459 'cm' => 35.43307,
1460 'in' => 90.0,
1461 '' => 1.0, // "User units" pixels by default
1462 '%' => 2.0, // Fake it!
1463 );
1464 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1465 $length = FloatVal( $matches[1] );
1466 $unit = $matches[2];
1467 return round( $length * $unitLength[$unit] );
1468 } else {
1469 // Assume pixels
1470 return round( FloatVal( $length ) );
1471 }
1472 }
1473
1474 /**
1475 * Compatible with PHP getimagesize()
1476 * @todo support gzipped SVGZ
1477 * @todo check XML more carefully
1478 * @todo sensible defaults
1479 *
1480 * @param string $filename
1481 * @return array
1482 */
1483 function wfGetSVGsize( $filename ) {
1484 $width = 256;
1485 $height = 256;
1486
1487 // Read a chunk of the file
1488 $f = fopen( $filename, "rt" );
1489 if( !$f ) return false;
1490 $chunk = fread( $f, 4096 );
1491 fclose( $f );
1492
1493 // Uber-crappy hack! Run through a real XML parser.
1494 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1495 return false;
1496 }
1497 $tag = $matches[1];
1498 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1499 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1500 }
1501 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1502 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1503 }
1504
1505 return array( $width, $height, 'SVG',
1506 "width=\"$width\" height=\"$height\"" );
1507 }
1508
1509 /**
1510 * Is an image on the bad image list?
1511 */
1512 function wfIsBadImage( $name ) {
1513 global $wgLang;
1514
1515 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1516 foreach ( $lines as $line ) {
1517 if ( preg_match( '/^\*\s*\[\[:(' . $wgLang->getNsText( NS_IMAGE ) . ':.*(?=]]))\]\]/', $line, $m ) ) {
1518 $t = Title::newFromText( $m[1] );
1519 if ( $t->getDBkey() == $name ) {
1520 return true;
1521 }
1522 }
1523 }
1524 return false;
1525 }
1526
1527
1528
1529 /**
1530 * Wrapper class for thumbnail images
1531 * @package MediaWiki
1532 */
1533 class ThumbnailImage {
1534 /**
1535 * @param string $path Filesystem path to the thumb
1536 * @param string $url URL path to the thumb
1537 * @access private
1538 */
1539 function ThumbnailImage( $url, $width, $height, $path = false ) {
1540 $this->url = $url;
1541 $this->width = $width;
1542 $this->height = $height;
1543 $this->path = $path;
1544 }
1545
1546 /**
1547 * @return string The thumbnail URL
1548 */
1549 function getUrl() {
1550 return $this->url;
1551 }
1552
1553 /**
1554 * Return HTML <img ... /> tag for the thumbnail, will include
1555 * width and height attributes and a blank alt text (as required).
1556 *
1557 * You can set or override additional attributes by passing an
1558 * associative array of name => data pairs. The data will be escaped
1559 * for HTML output, so should be in plaintext.
1560 *
1561 * @param array $attribs
1562 * @return string
1563 * @access public
1564 */
1565 function toHtml( $attribs = array() ) {
1566 $attribs['src'] = $this->url;
1567 $attribs['width'] = $this->width;
1568 $attribs['height'] = $this->height;
1569 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1570
1571 $html = '<img ';
1572 foreach( $attribs as $name => $data ) {
1573 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
1574 }
1575 $html .= '/>';
1576 return $html;
1577 }
1578
1579 }
1580 ?>