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