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