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