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