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