2dfd6069aed9227b27c915cc914da5542343174e
[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 scurity risc.
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 contain viruses
646 * or malicious content. It uses the global $wgTrustedMediaFormats list to determine
647 * 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 can be
675 * linked to directly, even if that is not allowed for this type of file normally.
676 *
677 * This is a dummy function right now and always returns false. It could be implemented
678 * to extract a flag from the database. The trusted flag could be set on upload, if the
679 * user has sufficient privileges, to bypass script- and html-filters. It may even be
680 * coupeled with cryptographics signatures or such.
681 */
682 function isTrustedFile() {
683 #this could be implemented to check a flag in the databas,
684 #look for signatures, etc
685 return false;
686 }
687
688 /**
689 * Return the escapeLocalURL of this image
690 * @access public
691 */
692 function getEscapeLocalURL() {
693 $this->getTitle();
694 return $this->title->escapeLocalURL();
695 }
696
697 /**
698 * Return the escapeFullURL of this image
699 * @access public
700 */
701 function getEscapeFullURL() {
702 $this->getTitle();
703 return $this->title->escapeFullURL();
704 }
705
706 /**
707 * Return the URL of an image, provided its name.
708 *
709 * @param string $name Name of the image, without the leading "Image:"
710 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
711 * @access public
712 * @static
713 */
714 function imageUrl( $name, $fromSharedDirectory = false ) {
715 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
716 if($fromSharedDirectory) {
717 $base = '';
718 $path = $wgSharedUploadPath;
719 } else {
720 $base = $wgUploadBaseUrl;
721 $path = $wgUploadPath;
722 }
723 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
724 return wfUrlencode( $url );
725 }
726
727 /**
728 * Returns true if the image file exists on disk.
729 *
730 * @access public
731 */
732 function exists() {
733 $this->load();
734 return $this->fileExists;
735 }
736
737 /**
738 *
739 * @access private
740 */
741 function thumbUrl( $width, $subdir='thumb') {
742 global $wgUploadPath, $wgUploadBaseUrl,
743 $wgSharedUploadPath,$wgSharedUploadDirectory,
744 $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
745
746 // Generate thumb.php URL if possible
747 $script = false;
748 $url = false;
749
750 if ( $this->fromSharedDirectory ) {
751 if ( $wgSharedThumbnailScriptPath ) {
752 $script = $wgSharedThumbnailScriptPath;
753 }
754 } else {
755 if ( $wgThumbnailScriptPath ) {
756 $script = $wgThumbnailScriptPath;
757 }
758 }
759 if ( $script ) {
760 $url = $script . '?f=' . urlencode( $this->name ) . '&w=' . urlencode( $width );
761 if( $this->mustRender() ) {
762 $url.= '&r=1';
763 }
764 } else {
765 $name = $this->thumbName( $width );
766 if($this->fromSharedDirectory) {
767 $base = '';
768 $path = $wgSharedUploadPath;
769 } else {
770 $base = $wgUploadBaseUrl;
771 $path = $wgUploadPath;
772 }
773 if ( Image::isHashed( $this->fromSharedDirectory ) ) {
774 $url = "{$base}{$path}/{$subdir}" .
775 wfGetHashPath($this->name, $this->fromSharedDirectory)
776 . $this->name.'/'.$name;
777 $url = wfUrlencode( $url );
778 } else {
779 $url = "{$base}{$path}/{$subdir}/{$name}";
780 }
781 }
782 return array( $script !== false, $url );
783 }
784
785 /**
786 * Return the file name of a thumbnail of the specified width
787 *
788 * @param integer $width Width of the thumbnail image
789 * @param boolean $shared Does the thumbnail come from the shared repository?
790 * @access private
791 */
792 function thumbName( $width ) {
793 $thumb = $width."px-".$this->name;
794
795 if( $this->mustRender() ) {
796 if( $this->canRender() ) {
797 # Rasterize to PNG (for SVG vector images, etc)
798 $thumb .= '.png';
799 }
800 else {
801 #should we use iconThumb here to get a symbolic thumbnail?
802 #or should we fail with an internal error?
803 return NULL; //can't make bitmap
804 }
805 }
806 return $thumb;
807 }
808
809 /**
810 * Create a thumbnail of the image having the specified width/height.
811 * The thumbnail will not be created if the width is larger than the
812 * image's width. Let the browser do the scaling in this case.
813 * The thumbnail is stored on disk and is only computed if the thumbnail
814 * file does not exist OR if it is older than the image.
815 * Returns the URL.
816 *
817 * Keeps aspect ratio of original image. If both width and height are
818 * specified, the generated image will be no bigger than width x height,
819 * and will also have correct aspect ratio.
820 *
821 * @param integer $width maximum width of the generated thumbnail
822 * @param integer $height maximum height of the image (optional)
823 * @access public
824 */
825 function createThumb( $width, $height=-1 ) {
826 $thumb = $this->getThumbnail( $width, $height );
827 if( is_null( $thumb ) ) return '';
828 return $thumb->getUrl();
829 }
830
831 /**
832 * As createThumb, but returns a ThumbnailImage object. This can
833 * provide access to the actual file, the real size of the thumb,
834 * and can produce a convenient <img> tag for you.
835 *
836 * @param integer $width maximum width of the generated thumbnail
837 * @param integer $height maximum height of the image (optional)
838 * @return ThumbnailImage
839 * @access public
840 */
841 function &getThumbnail( $width, $height=-1 ) {
842 if ( $height == -1 ) {
843 return $this->renderThumb( $width );
844 }
845 $this->load();
846
847 if ($this->canRender()) {
848 if ( $width < $this->width ) {
849 $thumbheight = $this->height * $width / $this->width;
850 $thumbwidth = $width;
851 } else {
852 $thumbheight = $this->height;
853 $thumbwidth = $this->width;
854 }
855 if ( $thumbheight > $height ) {
856 $thumbwidth = $thumbwidth * $height / $thumbheight;
857 $thumbheight = $height;
858 }
859
860 $thumb = $this->renderThumb( $thumbwidth );
861 }
862 else $thumb= NULL; #not a bitmap or renderable image, don't try.
863
864 if( is_null( $thumb ) ) {
865 $thumb = $this->iconThumb();
866 }
867 return $thumb;
868 }
869
870 /**
871 * @return ThumbnailImage
872 */
873 function iconThumb() {
874 global $wgStylePath, $wgStyleDirectory;
875
876 $try = array( 'fileicon-' . $this->extension . '.png', 'fileicon.png' );
877 foreach( $try as $icon ) {
878 $path = '/common/images/icons/' . $icon;
879 $filepath = $wgStyleDirectory . $path;
880 if( file_exists( $filepath ) ) {
881 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
882 }
883 }
884 return null;
885 }
886
887 /**
888 * Create a thumbnail of the image having the specified width.
889 * The thumbnail will not be created if the width is larger than the
890 * image's width. Let the browser do the scaling in this case.
891 * The thumbnail is stored on disk and is only computed if the thumbnail
892 * file does not exist OR if it is older than the image.
893 * Returns an object which can return the pathname, URL, and physical
894 * pixel size of the thumbnail -- or null on failure.
895 *
896 * @return ThumbnailImage
897 * @access private
898 */
899 function renderThumb( $width, $useScript = true ) {
900 global $wgUseSquid, $wgInternalServer;
901 global $wgThumbnailScriptPath, $wgSharedThumbnailScriptPath;
902
903 $width = IntVal( $width );
904
905 $this->load();
906 if ( ! $this->exists() )
907 {
908 # If there is no image, there will be no thumbnail
909 return null;
910 }
911
912 # Sanity check $width
913 if( $width <= 0 || $this->width <= 0) {
914 # BZZZT
915 return null;
916 }
917
918 if( $width >= $this->width && !$this->mustRender() ) {
919 # Don't make an image bigger than the source
920 return new ThumbnailImage( $this->getViewURL(), $this->getWidth(), $this->getHeight() );
921 }
922
923 $height = floor( $this->height * ( $width/$this->width ) );
924
925 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
926 if ( $isScriptUrl && $useScript ) {
927 // Use thumb.php to render the image
928 return new ThumbnailImage( $url, $width, $height );
929 }
930
931 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory );
932 $thumbPath = wfImageThumbDir( $this->name, $this->fromSharedDirectory ).'/'.$thumbName;
933
934 if ( !file_exists( $thumbPath ) ) {
935 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory ).
936 '/'.$thumbName;
937 $done = false;
938 if ( file_exists( $oldThumbPath ) ) {
939 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath) ) {
940 rename( $oldThumbPath, $thumbPath );
941 $done = true;
942 } else {
943 unlink( $oldThumbPath );
944 }
945 }
946 if ( !$done ) {
947 $this->reallyRenderThumb( $thumbPath, $width, $height );
948
949 # Purge squid
950 # This has to be done after the image is updated and present for all machines on NFS,
951 # or else the old version might be stored into the squid again
952 if ( $wgUseSquid ) {
953 if ( substr( $url, 0, 4 ) == 'http' ) {
954 $urlArr = array( $url );
955 } else {
956 $urlArr = array( $wgInternalServer.$url );
957 }
958 wfPurgeSquidServers($urlArr);
959 }
960 }
961 }
962
963 return new ThumbnailImage( $url, $width, $height, $thumbPath );
964 } // END OF function renderThumb
965
966 /**
967 * Really render a thumbnail
968 * Call this only for images for which canRender() returns true.
969 *
970 * @access private
971 */
972 function reallyRenderThumb( $thumbPath, $width, $height ) {
973 global $wgSVGConverters, $wgSVGConverter,
974 $wgUseImageMagick, $wgImageMagickConvertCommand;
975
976 $this->load();
977
978 if( $this->mime === "image/svg" ) {
979 #Right now we have only SVG
980
981 global $wgSVGConverters, $wgSVGConverter;
982 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
983 global $wgSVGConverterPath;
984 $cmd = str_replace(
985 array( '$path/', '$width', '$input', '$output' ),
986 array( $wgSVGConverterPath,
987 $width,
988 wfEscapeShellArg( $this->imagePath ),
989 wfEscapeShellArg( $thumbPath ) ),
990 $wgSVGConverters[$wgSVGConverter] );
991 $conv = shell_exec( $cmd );
992 } else {
993 $conv = false;
994 }
995 } elseif ( $wgUseImageMagick ) {
996 # use ImageMagick
997 # Specify white background color, will be used for transparent images
998 # in Internet Explorer/Windows instead of default black.
999 $cmd = $wgImageMagickConvertCommand .
1000 " -quality 85 -background white -geometry {$width} ".
1001 wfEscapeShellArg($this->imagePath) . " " .
1002 wfEscapeShellArg($thumbPath);
1003 wfDebug("reallyRenderThumb: running ImageMagick: $cmd");
1004 $conv = shell_exec( $cmd );
1005 } else {
1006 # Use PHP's builtin GD library functions.
1007 #
1008 # First find out what kind of file this is, and select the correct
1009 # input routine for this.
1010
1011 $truecolor = false;
1012
1013 switch( $this->type ) {
1014 case 1: # GIF
1015 $src_image = imagecreatefromgif( $this->imagePath );
1016 break;
1017 case 2: # JPG
1018 $src_image = imagecreatefromjpeg( $this->imagePath );
1019 $truecolor = true;
1020 break;
1021 case 3: # PNG
1022 $src_image = imagecreatefrompng( $this->imagePath );
1023 $truecolor = ( $this->bits > 8 );
1024 break;
1025 case 15: # WBMP for WML
1026 $src_image = imagecreatefromwbmp( $this->imagePath );
1027 break;
1028 case 16: # XBM
1029 $src_image = imagecreatefromxbm( $this->imagePath );
1030 break;
1031 default:
1032 return 'Image type not supported';
1033 break;
1034 }
1035 if ( $truecolor ) {
1036 $dst_image = imagecreatetruecolor( $width, $height );
1037 } else {
1038 $dst_image = imagecreate( $width, $height );
1039 }
1040 imagecopyresampled( $dst_image, $src_image,
1041 0,0,0,0,
1042 $width, $height, $this->width, $this->height );
1043 switch( $this->type ) {
1044 case 1: # GIF
1045 case 3: # PNG
1046 case 15: # WBMP
1047 case 16: # XBM
1048 imagepng( $dst_image, $thumbPath );
1049 break;
1050 case 2: # JPEG
1051 imageinterlace( $dst_image );
1052 imagejpeg( $dst_image, $thumbPath, 95 );
1053 break;
1054 default:
1055 break;
1056 }
1057 imagedestroy( $dst_image );
1058 imagedestroy( $src_image );
1059 }
1060
1061 #
1062 # Check for zero-sized thumbnails. Those can be generated when
1063 # no disk space is available or some other error occurs
1064 #
1065 if( file_exists( $thumbPath ) ) {
1066 $thumbstat = stat( $thumbPath );
1067 if( $thumbstat['size'] == 0 ) {
1068 unlink( $thumbPath );
1069 }
1070 }
1071 }
1072
1073 /**
1074 * Get all thumbnail names previously generated for this image
1075 */
1076 function getThumbnails( $shared = false ) {
1077 if ( Image::isHashed( $shared ) ) {
1078 $this->load();
1079 $files = array();
1080 $dir = wfImageThumbDir( $this->name, $shared );
1081
1082 // This generates an error on failure, hence the @
1083 $handle = @opendir( $dir );
1084
1085 if ( $handle ) {
1086 while ( false !== ( $file = readdir($handle) ) ) {
1087 if ( $file{0} != '.' ) {
1088 $files[] = $file;
1089 }
1090 }
1091 closedir( $handle );
1092 }
1093 } else {
1094 $files = array();
1095 }
1096
1097 return $files;
1098 }
1099
1100 /**
1101 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1102 */
1103 function purgeCache( $archiveFiles = array(), $shared = false ) {
1104 global $wgInternalServer, $wgUseSquid;
1105
1106 // Refresh metadata cache
1107 clearstatcache();
1108 $this->loadFromFile();
1109 $this->saveToCache();
1110
1111 // Delete thumbnails
1112 $files = $this->getThumbnails( $shared );
1113 $dir = wfImageThumbDir( $this->name, $shared );
1114 $urls = array();
1115 foreach ( $files as $file ) {
1116 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1117 $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory );
1118 @unlink( "$dir/$file" );
1119 }
1120 }
1121
1122 // Purge the squid
1123 if ( $wgUseSquid ) {
1124 $urls[] = $wgInternalServer . $this->getViewURL();
1125 foreach ( $archiveFiles as $file ) {
1126 $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
1127 }
1128 wfPurgeSquidServers( $urls );
1129 }
1130 }
1131
1132 function checkDBSchema(&$db) {
1133 # img_name must be unique
1134 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1135 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1136 }
1137
1138 #new fields must exist
1139 if ( !$db->fieldExists( 'image', 'img_media_type' )
1140 || !$db->fieldExists( 'image', 'img_metadata' )
1141 || !$db->fieldExists( 'image', 'img_width' ) ) {
1142
1143 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/update.php' );
1144 }
1145 }
1146
1147 /**
1148 * Return the image history of this image, line by line.
1149 * starts with current version, then old versions.
1150 * uses $this->historyLine to check which line to return:
1151 * 0 return line for current version
1152 * 1 query for old versions, return first one
1153 * 2, ... return next old version from above query
1154 *
1155 * @access public
1156 */
1157 function nextHistoryLine() {
1158 $fname = 'Image::nextHistoryLine()';
1159 $dbr =& wfGetDB( DB_SLAVE );
1160
1161 $this->checkDBSchema($dbr);
1162
1163 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
1164 $this->historyRes = $dbr->select( 'image',
1165 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
1166 array( 'img_name' => $this->title->getDBkey() ),
1167 $fname
1168 );
1169 if ( 0 == wfNumRows( $this->historyRes ) ) {
1170 return FALSE;
1171 }
1172 } else if ( $this->historyLine == 1 ) {
1173 $this->historyRes = $dbr->select( 'oldimage',
1174 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
1175 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
1176 ), array( 'oi_name' => $this->title->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
1177 );
1178 }
1179 $this->historyLine ++;
1180
1181 return $dbr->fetchObject( $this->historyRes );
1182 }
1183
1184 /**
1185 * Reset the history pointer to the first element of the history
1186 * @access public
1187 */
1188 function resetHistory() {
1189 $this->historyLine = 0;
1190 }
1191
1192 /**
1193 * Return the full filesystem path to the file. Note that this does
1194 * not mean that a file actually exists under that location.
1195 *
1196 * This path depends on whether directory hashing is active or not,
1197 * i.e. whether the images are all found in the same directory,
1198 * or in hashed paths like /images/3/3c.
1199 *
1200 * @access public
1201 * @param boolean $fromSharedDirectory Return the path to the file
1202 * in a shared repository (see $wgUseSharedRepository and related
1203 * options in DefaultSettings.php) instead of a local one.
1204 *
1205 */
1206 function getFullPath( $fromSharedRepository = false ) {
1207 global $wgUploadDirectory, $wgSharedUploadDirectory;
1208 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1209
1210 $dir = $fromSharedRepository ? $wgSharedUploadDirectory :
1211 $wgUploadDirectory;
1212
1213 // $wgSharedUploadDirectory may be false, if thumb.php is used
1214 if ( $dir ) {
1215 $fullpath = $dir . wfGetHashPath($this->name, $fromSharedRepository) . $this->name;
1216 } else {
1217 $fullpath = false;
1218 }
1219
1220 return $fullpath;
1221 }
1222
1223 /**
1224 * @return bool
1225 * @static
1226 */
1227 function isHashed( $shared ) {
1228 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1229 return $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1230 }
1231
1232 /**
1233 * Record an image upload in the upload log and the image table
1234 */
1235 function recordUpload( $oldver, $desc, $copyStatus = '', $source = '' ) {
1236 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
1237 global $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
1238
1239 $fname = 'Image::recordUpload';
1240 $dbw =& wfGetDB( DB_MASTER );
1241
1242 $this->checkDBSchema($dbw);
1243
1244 // Delete thumbnails and refresh the metadata cache
1245 $this->purgeCache();
1246
1247 // Fail now if the image isn't there
1248 if ( !$this->fileExists || $this->fromSharedDirectory ) {
1249 wfDebug( "Image::recordUpload: File ".$this->imagePath." went missing!\n" );
1250 return false;
1251 }
1252
1253 if ( $wgUseCopyrightUpload ) {
1254 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1255 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1256 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
1257 } else {
1258 $textdesc = $desc;
1259 }
1260
1261 $now = $dbw->timestamp();
1262
1263 #split mime type
1264 if (strpos($this->mime,'/')!==false) {
1265 list($major,$minor)= explode('/',$this->mime,2);
1266 }
1267 else {
1268 $major= $this->mime;
1269 $minor= "unknown";
1270 }
1271
1272 # Test to see if the row exists using INSERT IGNORE
1273 # This avoids race conditions by locking the row until the commit, and also
1274 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1275 $dbw->insert( 'image',
1276 array(
1277 'img_name' => $this->name,
1278 'img_size'=> $this->size,
1279 'img_width' => IntVal( $this->width ),
1280 'img_height' => IntVal( $this->height ),
1281 'img_bits' => $this->bits,
1282 'img_media_type' => $this->type,
1283 'img_major_mime' => $major,
1284 'img_minor_mime' => $minor,
1285 'img_timestamp' => $now,
1286 'img_description' => $desc,
1287 'img_user' => $wgUser->getID(),
1288 'img_user_text' => $wgUser->getName(),
1289 'img_metadata' => $this->metadata,
1290 ), $fname, 'IGNORE'
1291 );
1292 $descTitle = $this->getTitle();
1293 $purgeURLs = array();
1294
1295 if ( $dbw->affectedRows() ) {
1296 # Successfully inserted, this is a new image
1297 $id = $descTitle->getArticleID();
1298
1299 if ( $id == 0 ) {
1300 $article = new Article( $descTitle );
1301 $article->insertNewArticle( $textdesc, $desc, false, false, true );
1302 }
1303 } else {
1304 # Collision, this is an update of an image
1305 # Insert previous contents into oldimage
1306 $dbw->insertSelect( 'oldimage', 'image',
1307 array(
1308 'oi_name' => 'img_name',
1309 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1310 'oi_size' => 'img_size',
1311 'oi_width' => 'img_width',
1312 'oi_height' => 'img_height',
1313 'oi_bits' => 'img_bits',
1314 'oi_timestamp' => 'img_timestamp',
1315 'oi_description' => 'img_description',
1316 'oi_user' => 'img_user',
1317 'oi_user_text' => 'img_user_text',
1318 ), array( 'img_name' => $this->name ), $fname
1319 );
1320
1321 # Update the current image row
1322 $dbw->update( 'image',
1323 array( /* SET */
1324 'img_size' => $this->size,
1325 'img_width' => intval( $this->width ),
1326 'img_height' => intval( $this->height ),
1327 'img_bits' => $this->bits,
1328 'img_media_type' => $this->type,
1329 'img_major_mime' => $major,
1330 'img_minor_mime' => $minor,
1331 'img_timestamp' => $now,
1332 'img_description' => $desc,
1333 'img_user' => $wgUser->getID(),
1334 'img_user_text' => $wgUser->getName(),
1335 'img_metadata' => $this->metadata,
1336 ), array( /* WHERE */
1337 'img_name' => $this->name
1338 ), $fname
1339 );
1340
1341 # Invalidate the cache for the description page
1342 $descTitle->invalidateCache();
1343 $purgeURLs[] = $descTitle->getInternalURL();
1344 }
1345
1346 # Invalidate cache for all pages using this image
1347 $linksTo = $this->getLinksTo();
1348
1349 if ( $wgUseSquid ) {
1350 $u = SquidUpdate::newFromTitles( $linksTo, $purgeURLs );
1351 array_push( $wgPostCommitUpdateList, $u );
1352 }
1353 Title::touchArray( $linksTo );
1354
1355 $log = new LogPage( 'upload' );
1356 $log->addEntry( 'upload', $descTitle, $desc );
1357
1358 return true;
1359 }
1360
1361 /**
1362 * Get an array of Title objects which are articles which use this image
1363 * Also adds their IDs to the link cache
1364 *
1365 * This is mostly copied from Title::getLinksTo()
1366 */
1367 function getLinksTo( $options = '' ) {
1368 global $wgLinkCache;
1369 $fname = 'Image::getLinksTo';
1370 wfProfileIn( $fname );
1371
1372 if ( $options ) {
1373 $db =& wfGetDB( DB_MASTER );
1374 } else {
1375 $db =& wfGetDB( DB_SLAVE );
1376 }
1377
1378 extract( $db->tableNames( 'page', 'imagelinks' ) );
1379 $encName = $db->addQuotes( $this->name );
1380 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1381 $res = $db->query( $sql, $fname );
1382
1383 $retVal = array();
1384 if ( $db->numRows( $res ) ) {
1385 while ( $row = $db->fetchObject( $res ) ) {
1386 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1387 $wgLinkCache->addGoodLinkObj( $row->page_id, $titleObj );
1388 $retVal[] = $titleObj;
1389 }
1390 }
1391 }
1392 $db->freeResult( $res );
1393 return $retVal;
1394 }
1395 /**
1396 * Retrive Exif data from the database
1397 *
1398 * Retrive Exif data from the database and prune unrecognized tags
1399 * and/or tags with invalid contents
1400 *
1401 * @return array
1402 */
1403 function retrieveExifData () {
1404 if ( $this->getMimeType() !== "image/jpeg" ) return array ();
1405
1406 wfSuppressWarnings();
1407 $exif = exif_read_data( $this->imagePath );
1408 wfRestoreWarnings();
1409
1410 foreach($exif as $k => $v) {
1411 if ( !in_array($k, array_keys($this->exif->mFlatExif)) ) {
1412 wfDebug( "Image::retrieveExifData: '$k' is not a valid Exif tag (type: '" . gettype($v) . "'; data: '$v')\n");
1413 unset($exif[$k]);
1414 }
1415 }
1416
1417 foreach($exif as $k => $v) {
1418 if ( !$this->exif->validate($k, $v) ) {
1419 wfDebug( "Image::retrieveExifData: '$k' contained invalid data (type: '" . gettype($v) . "'; data: '$v')\n");
1420 unset($exif[$k]);
1421 }
1422 }
1423 return $exif;
1424 }
1425
1426 function getExifData () {
1427 global $wgRequest;
1428 if ( $this->metadata === '0' )
1429 return array();
1430
1431 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1432 $ret = unserialize ( $this->metadata );
1433
1434 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ? $ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1435 $newver = $this->exif->version();
1436
1437 if ( !count( $ret ) || $purge || $oldver != $newver ) {
1438 $this->updateExifData( $newver );
1439 }
1440 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1441 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1442
1443 foreach($ret as $k => $v) {
1444 $ret[$k] = $this->exif->format($k, $v);
1445 }
1446
1447 return $ret;
1448 }
1449
1450 function updateExifData( $version ) {
1451 $fname = 'Image:updateExifData';
1452
1453 if ( $this->getImagePath() === false ) # Not a local image
1454 return;
1455
1456 # Get EXIF data from image
1457 $exif = $this->retrieveExifData();
1458 if ( count( $exif ) ) {
1459 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1460 $this->metadata = serialize( $exif );
1461 } else {
1462 $this->metadata = '0';
1463 }
1464
1465 # Update EXIF data in database
1466 $dbw =& wfGetDB( DB_MASTER );
1467
1468 $this->checkDBSchema($dbw);
1469
1470 $dbw->update( 'image',
1471 array( 'img_metadata' => $this->metadata ),
1472 array( 'img_name' => $this->name ),
1473 $fname
1474 );
1475 }
1476
1477 } //class
1478
1479
1480 /**
1481 * Returns the image directory of an image
1482 * If the directory does not exist, it is created.
1483 * The result is an absolute path.
1484 *
1485 * This function is called from thumb.php before Setup.php is included
1486 *
1487 * @param string $fname file name of the image file
1488 * @access public
1489 */
1490 function wfImageDir( $fname ) {
1491 global $wgUploadDirectory, $wgHashedUploadDirectory;
1492
1493 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1494
1495 $hash = md5( $fname );
1496 $oldumask = umask(0);
1497 $dest = $wgUploadDirectory . '/' . $hash{0};
1498 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1499 $dest .= '/' . substr( $hash, 0, 2 );
1500 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1501
1502 umask( $oldumask );
1503 return $dest;
1504 }
1505
1506 /**
1507 * Returns the image directory of an image's thubnail
1508 * If the directory does not exist, it is created.
1509 * The result is an absolute path.
1510 *
1511 * This function is called from thumb.php before Setup.php is included
1512 *
1513 * @param string $fname file name of the original image file
1514 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
1515 * @param boolean $shared (optional) use the shared upload directory
1516 * @access public
1517 */
1518 function wfImageThumbDir( $fname, $shared = false ) {
1519 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1520 if ( Image::isHashed( $shared ) ) {
1521 $dir = "$base/$fname";
1522
1523 if ( !is_dir( $base ) ) {
1524 $oldumask = umask(0);
1525 @mkdir( $base, 0777 );
1526 umask( $oldumask );
1527 }
1528
1529 if ( ! is_dir( $dir ) ) {
1530 $oldumask = umask(0);
1531 @mkdir( $dir, 0777 );
1532 umask( $oldumask );
1533 }
1534 } else {
1535 $dir = $base;
1536 }
1537
1538 return $dir;
1539 }
1540
1541 /**
1542 * Old thumbnail directory, kept for conversion
1543 */
1544 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1545 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1546 }
1547
1548 /**
1549 * Returns the image directory of an image's old version
1550 * If the directory does not exist, it is created.
1551 * The result is an absolute path.
1552 *
1553 * This function is called from thumb.php before Setup.php is included
1554 *
1555 * @param string $fname file name of the thumbnail file, including file size prefix
1556 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
1557 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
1558 * @access public
1559 */
1560 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1561 global $wgUploadDirectory, $wgHashedUploadDirectory,
1562 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1563 $dir = $shared ? $wgSharedUploadDirectory : $wgUploadDirectory;
1564 $hashdir = $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1565 if (!$hashdir) { return $dir.'/'.$subdir; }
1566 $hash = md5( $fname );
1567 $oldumask = umask(0);
1568
1569 # Suppress warning messages here; if the file itself can't
1570 # be written we'll worry about it then.
1571 wfSuppressWarnings();
1572
1573 $archive = $dir.'/'.$subdir;
1574 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1575 $archive .= '/' . $hash{0};
1576 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1577 $archive .= '/' . substr( $hash, 0, 2 );
1578 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1579
1580 wfRestoreWarnings();
1581 umask( $oldumask );
1582 return $archive;
1583 }
1584
1585
1586 /*
1587 * Return the hash path component of an image path (URL or filesystem),
1588 * e.g. "/3/3c/", or just "/" if hashing is not used.
1589 *
1590 * @param $dbkey The filesystem / database name of the file
1591 * @param $fromSharedDirectory Use the shared file repository? It may
1592 * use different hash settings from the local one.
1593 */
1594 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1595 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
1596 global $wgHashedUploadDirectory;
1597
1598 if( Image::isHashed( $fromSharedDirectory ) ) {
1599 $hash = md5($dbkey);
1600 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1601 } else {
1602 return '/';
1603 }
1604 }
1605
1606 /**
1607 * Returns the image URL of an image's old version
1608 *
1609 * @param string $fname file name of the image file
1610 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1611 * @access public
1612 */
1613 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1614 global $wgUploadPath, $wgHashedUploadDirectory;
1615
1616 if ($wgHashedUploadDirectory) {
1617 $hash = md5( substr( $name, 15) );
1618 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1619 substr( $hash, 0, 2 ) . '/'.$name;
1620 } else {
1621 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1622 }
1623 return wfUrlencode($url);
1624 }
1625
1626 /**
1627 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1628 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1629 *
1630 * @param string $length
1631 * @return int Length in pixels
1632 */
1633 function wfScaleSVGUnit( $length ) {
1634 static $unitLength = array(
1635 'px' => 1.0,
1636 'pt' => 1.25,
1637 'pc' => 15.0,
1638 'mm' => 3.543307,
1639 'cm' => 35.43307,
1640 'in' => 90.0,
1641 '' => 1.0, // "User units" pixels by default
1642 '%' => 2.0, // Fake it!
1643 );
1644 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1645 $length = FloatVal( $matches[1] );
1646 $unit = $matches[2];
1647 return round( $length * $unitLength[$unit] );
1648 } else {
1649 // Assume pixels
1650 return round( FloatVal( $length ) );
1651 }
1652 }
1653
1654 /**
1655 * Compatible with PHP getimagesize()
1656 * @todo support gzipped SVGZ
1657 * @todo check XML more carefully
1658 * @todo sensible defaults
1659 *
1660 * @param string $filename
1661 * @return array
1662 */
1663 function wfGetSVGsize( $filename ) {
1664 $width = 256;
1665 $height = 256;
1666
1667 // Read a chunk of the file
1668 $f = fopen( $filename, "rt" );
1669 if( !$f ) return false;
1670 $chunk = fread( $f, 4096 );
1671 fclose( $f );
1672
1673 // Uber-crappy hack! Run through a real XML parser.
1674 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1675 return false;
1676 }
1677 $tag = $matches[1];
1678 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1679 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1680 }
1681 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1682 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1683 }
1684
1685 return array( $width, $height, 'SVG',
1686 "width=\"$width\" height=\"$height\"" );
1687 }
1688
1689 /**
1690 * Determine if an image exists on the 'bad image list'
1691 *
1692 * @param string $name The image to check
1693 * @return bool
1694 */
1695 function wfIsBadImage( $name ) {
1696 global $wgContLang;
1697 static $titleList = false;
1698 if ( $titleList === false ) {
1699 $titleList = array();
1700
1701 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1702 foreach ( $lines as $line ) {
1703 if ( preg_match( '/^\*\s*\[{2}:(' . $wgContLang->getNsText( NS_IMAGE ) . ':.*?)\]{2}/', $line, $m ) ) {
1704 $t = Title::newFromText( $m[1] );
1705 $titleList[$t->getDBkey()] = 1;
1706 }
1707 }
1708 }
1709
1710 return array_key_exists( $name, $titleList );
1711 }
1712
1713
1714
1715 /**
1716 * Wrapper class for thumbnail images
1717 * @package MediaWiki
1718 */
1719 class ThumbnailImage {
1720 /**
1721 * @param string $path Filesystem path to the thumb
1722 * @param string $url URL path to the thumb
1723 * @access private
1724 */
1725 function ThumbnailImage( $url, $width, $height, $path = false ) {
1726 $this->url = $url;
1727 $this->width = $width;
1728 $this->height = $height;
1729 $this->path = $path;
1730 }
1731
1732 /**
1733 * @return string The thumbnail URL
1734 */
1735 function getUrl() {
1736 return $this->url;
1737 }
1738
1739 /**
1740 * Return HTML <img ... /> tag for the thumbnail, will include
1741 * width and height attributes and a blank alt text (as required).
1742 *
1743 * You can set or override additional attributes by passing an
1744 * associative array of name => data pairs. The data will be escaped
1745 * for HTML output, so should be in plaintext.
1746 *
1747 * @param array $attribs
1748 * @return string
1749 * @access public
1750 */
1751 function toHtml( $attribs = array() ) {
1752 $attribs['src'] = $this->url;
1753 $attribs['width'] = $this->width;
1754 $attribs['height'] = $this->height;
1755 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1756
1757 $html = '<img ';
1758 foreach( $attribs as $name => $data ) {
1759 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
1760 }
1761 $html .= '/>';
1762 return $html;
1763 }
1764
1765 }
1766 ?>