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