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