* GROUP BY support in makeSelectOptions()
[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, $wgSharedUploadDBprefix, $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`.{$wgSharedUploadDBprefix}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 $typemap = array(
1032 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
1033 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( &$this, 'imageJpegWrapper' ) ),
1034 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
1035 'image/vnd.wap.wmbp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
1036 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
1037 );
1038 if( !isset( $typemap[$this->mime] ) ) {
1039 $err = 'Image type not supported';
1040 wfDebug( "$err\n" );
1041 return $err;
1042 }
1043 list( $loader, $colorStyle, $saveType ) = $typemap[$this->mime];
1044
1045 if( !function_exists( $loader ) ) {
1046 $err = "Incomplete GD library configuration: missing function $loader";
1047 wfDebug( "$err\n" );
1048 return $err;
1049 }
1050 if( $colorStyle == 'palette' ) {
1051 $truecolor = false;
1052 } elseif( $colorStyle == 'truecolor' ) {
1053 $truecolor = true;
1054 } elseif( $colorStyle == 'bits' ) {
1055 $truecolor = ( $this->bits > 8 );
1056 }
1057
1058 $src_image = call_user_func( $loader, $this->imagePath );
1059 if ( $truecolor ) {
1060 $dst_image = imagecreatetruecolor( $width, $height );
1061 } else {
1062 $dst_image = imagecreate( $width, $height );
1063 }
1064 imagecopyresampled( $dst_image, $src_image,
1065 0,0,0,0,
1066 $width, $height, $this->width, $this->height );
1067 call_user_func( $saveType, $dst_image, $thumbPath );
1068 imagedestroy( $dst_image );
1069 imagedestroy( $src_image );
1070 }
1071
1072 #
1073 # Check for zero-sized thumbnails. Those can be generated when
1074 # no disk space is available or some other error occurs
1075 #
1076 if( file_exists( $thumbPath ) ) {
1077 $thumbstat = stat( $thumbPath );
1078 if( $thumbstat['size'] == 0 ) {
1079 unlink( $thumbPath );
1080 }
1081 }
1082 }
1083
1084 function imageJpegWrapper( $dst_image, $thumbPath ) {
1085 imageinterlace( $dst_image );
1086 imagejpeg( $dst_image, $thumbPath, 95 );
1087 }
1088
1089 /**
1090 * Get all thumbnail names previously generated for this image
1091 */
1092 function getThumbnails( $shared = false ) {
1093 if ( Image::isHashed( $shared ) ) {
1094 $this->load();
1095 $files = array();
1096 $dir = wfImageThumbDir( $this->name, $shared );
1097
1098 // This generates an error on failure, hence the @
1099 $handle = @opendir( $dir );
1100
1101 if ( $handle ) {
1102 while ( false !== ( $file = readdir($handle) ) ) {
1103 if ( $file{0} != '.' ) {
1104 $files[] = $file;
1105 }
1106 }
1107 closedir( $handle );
1108 }
1109 } else {
1110 $files = array();
1111 }
1112
1113 return $files;
1114 }
1115
1116 /**
1117 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1118 */
1119 function purgeCache( $archiveFiles = array(), $shared = false ) {
1120 global $wgInternalServer, $wgUseSquid;
1121
1122 // Refresh metadata cache
1123 clearstatcache();
1124 $this->loadFromFile();
1125 $this->saveToCache();
1126
1127 // Delete thumbnails
1128 $files = $this->getThumbnails( $shared );
1129 $dir = wfImageThumbDir( $this->name, $shared );
1130 $urls = array();
1131 foreach ( $files as $file ) {
1132 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1133 $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory );
1134 @unlink( "$dir/$file" );
1135 }
1136 }
1137
1138 // Purge the squid
1139 if ( $wgUseSquid ) {
1140 $urls[] = $wgInternalServer . $this->getViewURL();
1141 foreach ( $archiveFiles as $file ) {
1142 $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
1143 }
1144 wfPurgeSquidServers( $urls );
1145 }
1146 }
1147
1148 function checkDBSchema(&$db) {
1149 # img_name must be unique
1150 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1151 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1152 }
1153
1154 #new fields must exist
1155 if ( !$db->fieldExists( 'image', 'img_media_type' )
1156 || !$db->fieldExists( 'image', 'img_metadata' )
1157 || !$db->fieldExists( 'image', 'img_width' ) ) {
1158
1159 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/update.php' );
1160 }
1161 }
1162
1163 /**
1164 * Return the image history of this image, line by line.
1165 * starts with current version, then old versions.
1166 * uses $this->historyLine to check which line to return:
1167 * 0 return line for current version
1168 * 1 query for old versions, return first one
1169 * 2, ... return next old version from above query
1170 *
1171 * @access public
1172 */
1173 function nextHistoryLine() {
1174 $fname = 'Image::nextHistoryLine()';
1175 $dbr =& wfGetDB( DB_SLAVE );
1176
1177 $this->checkDBSchema($dbr);
1178
1179 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
1180 $this->historyRes = $dbr->select( 'image',
1181 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
1182 array( 'img_name' => $this->title->getDBkey() ),
1183 $fname
1184 );
1185 if ( 0 == wfNumRows( $this->historyRes ) ) {
1186 return FALSE;
1187 }
1188 } else if ( $this->historyLine == 1 ) {
1189 $this->historyRes = $dbr->select( 'oldimage',
1190 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
1191 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
1192 ), array( 'oi_name' => $this->title->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
1193 );
1194 }
1195 $this->historyLine ++;
1196
1197 return $dbr->fetchObject( $this->historyRes );
1198 }
1199
1200 /**
1201 * Reset the history pointer to the first element of the history
1202 * @access public
1203 */
1204 function resetHistory() {
1205 $this->historyLine = 0;
1206 }
1207
1208 /**
1209 * Return the full filesystem path to the file. Note that this does
1210 * not mean that a file actually exists under that location.
1211 *
1212 * This path depends on whether directory hashing is active or not,
1213 * i.e. whether the images are all found in the same directory,
1214 * or in hashed paths like /images/3/3c.
1215 *
1216 * @access public
1217 * @param boolean $fromSharedDirectory Return the path to the file
1218 * in a shared repository (see $wgUseSharedRepository and related
1219 * options in DefaultSettings.php) instead of a local one.
1220 *
1221 */
1222 function getFullPath( $fromSharedRepository = false ) {
1223 global $wgUploadDirectory, $wgSharedUploadDirectory;
1224 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1225
1226 $dir = $fromSharedRepository ? $wgSharedUploadDirectory :
1227 $wgUploadDirectory;
1228
1229 // $wgSharedUploadDirectory may be false, if thumb.php is used
1230 if ( $dir ) {
1231 $fullpath = $dir . wfGetHashPath($this->name, $fromSharedRepository) . $this->name;
1232 } else {
1233 $fullpath = false;
1234 }
1235
1236 return $fullpath;
1237 }
1238
1239 /**
1240 * @return bool
1241 * @static
1242 */
1243 function isHashed( $shared ) {
1244 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1245 return $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1246 }
1247
1248 /**
1249 * Record an image upload in the upload log and the image table
1250 */
1251 function recordUpload( $oldver, $desc, $copyStatus = '', $source = '' ) {
1252 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
1253 global $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
1254
1255 $fname = 'Image::recordUpload';
1256 $dbw =& wfGetDB( DB_MASTER );
1257
1258 $this->checkDBSchema($dbw);
1259
1260 // Delete thumbnails and refresh the metadata cache
1261 $this->purgeCache();
1262
1263 // Fail now if the image isn't there
1264 if ( !$this->fileExists || $this->fromSharedDirectory ) {
1265 wfDebug( "Image::recordUpload: File ".$this->imagePath." went missing!\n" );
1266 return false;
1267 }
1268
1269 if ( $wgUseCopyrightUpload ) {
1270 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1271 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1272 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
1273 } else {
1274 $textdesc = $desc;
1275 }
1276
1277 $now = $dbw->timestamp();
1278
1279 #split mime type
1280 if (strpos($this->mime,'/')!==false) {
1281 list($major,$minor)= explode('/',$this->mime,2);
1282 }
1283 else {
1284 $major= $this->mime;
1285 $minor= "unknown";
1286 }
1287
1288 # Test to see if the row exists using INSERT IGNORE
1289 # This avoids race conditions by locking the row until the commit, and also
1290 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1291 $dbw->insert( 'image',
1292 array(
1293 'img_name' => $this->name,
1294 'img_size'=> $this->size,
1295 'img_width' => IntVal( $this->width ),
1296 'img_height' => IntVal( $this->height ),
1297 'img_bits' => $this->bits,
1298 'img_media_type' => $this->type,
1299 'img_major_mime' => $major,
1300 'img_minor_mime' => $minor,
1301 'img_timestamp' => $now,
1302 'img_description' => $desc,
1303 'img_user' => $wgUser->getID(),
1304 'img_user_text' => $wgUser->getName(),
1305 'img_metadata' => $this->metadata,
1306 ), $fname, 'IGNORE'
1307 );
1308 $descTitle = $this->getTitle();
1309 $purgeURLs = array();
1310
1311 if ( $dbw->affectedRows() ) {
1312 # Successfully inserted, this is a new image
1313 $id = $descTitle->getArticleID();
1314
1315 if ( $id == 0 ) {
1316 $article = new Article( $descTitle );
1317 $article->insertNewArticle( $textdesc, $desc, false, false, true );
1318 }
1319 } else {
1320 # Collision, this is an update of an image
1321 # Insert previous contents into oldimage
1322 $dbw->insertSelect( 'oldimage', 'image',
1323 array(
1324 'oi_name' => 'img_name',
1325 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1326 'oi_size' => 'img_size',
1327 'oi_width' => 'img_width',
1328 'oi_height' => 'img_height',
1329 'oi_bits' => 'img_bits',
1330 'oi_timestamp' => 'img_timestamp',
1331 'oi_description' => 'img_description',
1332 'oi_user' => 'img_user',
1333 'oi_user_text' => 'img_user_text',
1334 ), array( 'img_name' => $this->name ), $fname
1335 );
1336
1337 # Update the current image row
1338 $dbw->update( 'image',
1339 array( /* SET */
1340 'img_size' => $this->size,
1341 'img_width' => intval( $this->width ),
1342 'img_height' => intval( $this->height ),
1343 'img_bits' => $this->bits,
1344 'img_media_type' => $this->type,
1345 'img_major_mime' => $major,
1346 'img_minor_mime' => $minor,
1347 'img_timestamp' => $now,
1348 'img_description' => $desc,
1349 'img_user' => $wgUser->getID(),
1350 'img_user_text' => $wgUser->getName(),
1351 'img_metadata' => $this->metadata,
1352 ), array( /* WHERE */
1353 'img_name' => $this->name
1354 ), $fname
1355 );
1356
1357 # Invalidate the cache for the description page
1358 $descTitle->invalidateCache();
1359 $purgeURLs[] = $descTitle->getInternalURL();
1360 }
1361
1362 # Invalidate cache for all pages using this image
1363 $linksTo = $this->getLinksTo();
1364
1365 if ( $wgUseSquid ) {
1366 $u = SquidUpdate::newFromTitles( $linksTo, $purgeURLs );
1367 array_push( $wgPostCommitUpdateList, $u );
1368 }
1369 Title::touchArray( $linksTo );
1370
1371 $log = new LogPage( 'upload' );
1372 $log->addEntry( 'upload', $descTitle, $desc );
1373
1374 return true;
1375 }
1376
1377 /**
1378 * Get an array of Title objects which are articles which use this image
1379 * Also adds their IDs to the link cache
1380 *
1381 * This is mostly copied from Title::getLinksTo()
1382 */
1383 function getLinksTo( $options = '' ) {
1384 global $wgLinkCache;
1385 $fname = 'Image::getLinksTo';
1386 wfProfileIn( $fname );
1387
1388 if ( $options ) {
1389 $db =& wfGetDB( DB_MASTER );
1390 } else {
1391 $db =& wfGetDB( DB_SLAVE );
1392 }
1393
1394 extract( $db->tableNames( 'page', 'imagelinks' ) );
1395 $encName = $db->addQuotes( $this->name );
1396 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1397 $res = $db->query( $sql, $fname );
1398
1399 $retVal = array();
1400 if ( $db->numRows( $res ) ) {
1401 while ( $row = $db->fetchObject( $res ) ) {
1402 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1403 $wgLinkCache->addGoodLinkObj( $row->page_id, $titleObj );
1404 $retVal[] = $titleObj;
1405 }
1406 }
1407 }
1408 $db->freeResult( $res );
1409 return $retVal;
1410 }
1411 /**
1412 * Retrive Exif data from the database
1413 *
1414 * Retrive Exif data from the database and prune unrecognized tags
1415 * and/or tags with invalid contents
1416 *
1417 * @return array
1418 */
1419 function retrieveExifData () {
1420 if ( $this->getMimeType() !== "image/jpeg" ) return array ();
1421
1422 wfSuppressWarnings();
1423 $exif = exif_read_data( $this->imagePath );
1424 wfRestoreWarnings();
1425
1426 foreach($exif as $k => $v) {
1427 if ( !in_array($k, array_keys($this->exif->mFlatExif)) ) {
1428 wfDebug( "Image::retrieveExifData: '$k' is not a valid Exif tag (type: '" . gettype($v) . "'; data: '$v')\n");
1429 unset($exif[$k]);
1430 }
1431 }
1432
1433 foreach($exif as $k => $v) {
1434 if ( !$this->exif->validate($k, $v) ) {
1435 wfDebug( "Image::retrieveExifData: '$k' contained invalid data (type: '" . gettype($v) . "'; data: '$v')\n");
1436 unset($exif[$k]);
1437 }
1438 }
1439 return $exif;
1440 }
1441
1442 function getExifData () {
1443 global $wgRequest;
1444 if ( $this->metadata === '0' )
1445 return array();
1446
1447 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1448 $ret = unserialize ( $this->metadata );
1449
1450 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ? $ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1451 $newver = $this->exif->version();
1452
1453 if ( !count( $ret ) || $purge || $oldver != $newver ) {
1454 $this->updateExifData( $newver );
1455 }
1456 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1457 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1458
1459 foreach($ret as $k => $v) {
1460 $ret[$k] = $this->exif->format($k, $v);
1461 }
1462
1463 return $ret;
1464 }
1465
1466 function updateExifData( $version ) {
1467 $fname = 'Image:updateExifData';
1468
1469 if ( $this->getImagePath() === false ) # Not a local image
1470 return;
1471
1472 # Get EXIF data from image
1473 $exif = $this->retrieveExifData();
1474 if ( count( $exif ) ) {
1475 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1476 $this->metadata = serialize( $exif );
1477 } else {
1478 $this->metadata = '0';
1479 }
1480
1481 # Update EXIF data in database
1482 $dbw =& wfGetDB( DB_MASTER );
1483
1484 $this->checkDBSchema($dbw);
1485
1486 $dbw->update( 'image',
1487 array( 'img_metadata' => $this->metadata ),
1488 array( 'img_name' => $this->name ),
1489 $fname
1490 );
1491 }
1492
1493 } //class
1494
1495
1496 /**
1497 * Returns the image directory of an image
1498 * If the directory does not exist, it is created.
1499 * The result is an absolute path.
1500 *
1501 * This function is called from thumb.php before Setup.php is included
1502 *
1503 * @param string $fname file name of the image file
1504 * @access public
1505 */
1506 function wfImageDir( $fname ) {
1507 global $wgUploadDirectory, $wgHashedUploadDirectory;
1508
1509 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1510
1511 $hash = md5( $fname );
1512 $oldumask = umask(0);
1513 $dest = $wgUploadDirectory . '/' . $hash{0};
1514 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1515 $dest .= '/' . substr( $hash, 0, 2 );
1516 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1517
1518 umask( $oldumask );
1519 return $dest;
1520 }
1521
1522 /**
1523 * Returns the image directory of an image's thubnail
1524 * If the directory does not exist, it is created.
1525 * The result is an absolute path.
1526 *
1527 * This function is called from thumb.php before Setup.php is included
1528 *
1529 * @param string $fname file name of the original image file
1530 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
1531 * @param boolean $shared (optional) use the shared upload directory
1532 * @access public
1533 */
1534 function wfImageThumbDir( $fname, $shared = false ) {
1535 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1536 if ( Image::isHashed( $shared ) ) {
1537 $dir = "$base/$fname";
1538
1539 if ( !is_dir( $base ) ) {
1540 $oldumask = umask(0);
1541 @mkdir( $base, 0777 );
1542 umask( $oldumask );
1543 }
1544
1545 if ( ! is_dir( $dir ) ) {
1546 $oldumask = umask(0);
1547 @mkdir( $dir, 0777 );
1548 umask( $oldumask );
1549 }
1550 } else {
1551 $dir = $base;
1552 }
1553
1554 return $dir;
1555 }
1556
1557 /**
1558 * Old thumbnail directory, kept for conversion
1559 */
1560 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1561 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1562 }
1563
1564 /**
1565 * Returns the image directory of an image's old version
1566 * If the directory does not exist, it is created.
1567 * The result is an absolute path.
1568 *
1569 * This function is called from thumb.php before Setup.php is included
1570 *
1571 * @param string $fname file name of the thumbnail file, including file size prefix
1572 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
1573 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
1574 * @access public
1575 */
1576 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1577 global $wgUploadDirectory, $wgHashedUploadDirectory,
1578 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1579 $dir = $shared ? $wgSharedUploadDirectory : $wgUploadDirectory;
1580 $hashdir = $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1581 if (!$hashdir) { return $dir.'/'.$subdir; }
1582 $hash = md5( $fname );
1583 $oldumask = umask(0);
1584
1585 # Suppress warning messages here; if the file itself can't
1586 # be written we'll worry about it then.
1587 wfSuppressWarnings();
1588
1589 $archive = $dir.'/'.$subdir;
1590 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1591 $archive .= '/' . $hash{0};
1592 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1593 $archive .= '/' . substr( $hash, 0, 2 );
1594 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1595
1596 wfRestoreWarnings();
1597 umask( $oldumask );
1598 return $archive;
1599 }
1600
1601
1602 /*
1603 * Return the hash path component of an image path (URL or filesystem),
1604 * e.g. "/3/3c/", or just "/" if hashing is not used.
1605 *
1606 * @param $dbkey The filesystem / database name of the file
1607 * @param $fromSharedDirectory Use the shared file repository? It may
1608 * use different hash settings from the local one.
1609 */
1610 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1611 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
1612 global $wgHashedUploadDirectory;
1613
1614 if( Image::isHashed( $fromSharedDirectory ) ) {
1615 $hash = md5($dbkey);
1616 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1617 } else {
1618 return '/';
1619 }
1620 }
1621
1622 /**
1623 * Returns the image URL of an image's old version
1624 *
1625 * @param string $fname file name of the image file
1626 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1627 * @access public
1628 */
1629 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1630 global $wgUploadPath, $wgHashedUploadDirectory;
1631
1632 if ($wgHashedUploadDirectory) {
1633 $hash = md5( substr( $name, 15) );
1634 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1635 substr( $hash, 0, 2 ) . '/'.$name;
1636 } else {
1637 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1638 }
1639 return wfUrlencode($url);
1640 }
1641
1642 /**
1643 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1644 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1645 *
1646 * @param string $length
1647 * @return int Length in pixels
1648 */
1649 function wfScaleSVGUnit( $length ) {
1650 static $unitLength = array(
1651 'px' => 1.0,
1652 'pt' => 1.25,
1653 'pc' => 15.0,
1654 'mm' => 3.543307,
1655 'cm' => 35.43307,
1656 'in' => 90.0,
1657 '' => 1.0, // "User units" pixels by default
1658 '%' => 2.0, // Fake it!
1659 );
1660 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1661 $length = FloatVal( $matches[1] );
1662 $unit = $matches[2];
1663 return round( $length * $unitLength[$unit] );
1664 } else {
1665 // Assume pixels
1666 return round( FloatVal( $length ) );
1667 }
1668 }
1669
1670 /**
1671 * Compatible with PHP getimagesize()
1672 * @todo support gzipped SVGZ
1673 * @todo check XML more carefully
1674 * @todo sensible defaults
1675 *
1676 * @param string $filename
1677 * @return array
1678 */
1679 function wfGetSVGsize( $filename ) {
1680 $width = 256;
1681 $height = 256;
1682
1683 // Read a chunk of the file
1684 $f = fopen( $filename, "rt" );
1685 if( !$f ) return false;
1686 $chunk = fread( $f, 4096 );
1687 fclose( $f );
1688
1689 // Uber-crappy hack! Run through a real XML parser.
1690 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1691 return false;
1692 }
1693 $tag = $matches[1];
1694 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1695 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1696 }
1697 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1698 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1699 }
1700
1701 return array( $width, $height, 'SVG',
1702 "width=\"$width\" height=\"$height\"" );
1703 }
1704
1705 /**
1706 * Determine if an image exists on the 'bad image list'
1707 *
1708 * @param string $name The image to check
1709 * @return bool
1710 */
1711 function wfIsBadImage( $name ) {
1712 global $wgContLang;
1713 static $titleList = false;
1714 if ( $titleList === false ) {
1715 $titleList = array();
1716
1717 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1718 foreach ( $lines as $line ) {
1719 if ( preg_match( '/^\*\s*\[{2}:(' . $wgContLang->getNsText( NS_IMAGE ) . ':.*?)\]{2}/', $line, $m ) ) {
1720 $t = Title::newFromText( $m[1] );
1721 $titleList[$t->getDBkey()] = 1;
1722 }
1723 }
1724 }
1725
1726 return array_key_exists( $name, $titleList );
1727 }
1728
1729
1730
1731 /**
1732 * Wrapper class for thumbnail images
1733 * @package MediaWiki
1734 */
1735 class ThumbnailImage {
1736 /**
1737 * @param string $path Filesystem path to the thumb
1738 * @param string $url URL path to the thumb
1739 * @access private
1740 */
1741 function ThumbnailImage( $url, $width, $height, $path = false ) {
1742 $this->url = $url;
1743 $this->width = $width;
1744 $this->height = $height;
1745 $this->path = $path;
1746 }
1747
1748 /**
1749 * @return string The thumbnail URL
1750 */
1751 function getUrl() {
1752 return $this->url;
1753 }
1754
1755 /**
1756 * Return HTML <img ... /> tag for the thumbnail, will include
1757 * width and height attributes and a blank alt text (as required).
1758 *
1759 * You can set or override additional attributes by passing an
1760 * associative array of name => data pairs. The data will be escaped
1761 * for HTML output, so should be in plaintext.
1762 *
1763 * @param array $attribs
1764 * @return string
1765 * @access public
1766 */
1767 function toHtml( $attribs = array() ) {
1768 $attribs['src'] = $this->url;
1769 $attribs['width'] = $this->width;
1770 $attribs['height'] = $this->height;
1771 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1772
1773 $html = '<img ';
1774 foreach( $attribs as $name => $data ) {
1775 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
1776 }
1777 $html .= '/>';
1778 return $html;
1779 }
1780
1781 }
1782 ?>