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