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