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