Use AutoLoader to load classes:
[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 wfDebugDieBacktrace( 'Image constructor given bogus title.' );
79 }
80 $this->title =& $title;
81 $this->name = $title->getDBkey();
82 $this->metadata = serialize ( array() ) ;
83
84 $n = strrpos( $this->name, '.' );
85 $this->extension = strtolower( $n ? substr( $this->name, $n + 1 ) : '' );
86 $this->historyLine = 0;
87
88 $this->dataLoaded = false;
89 }
90
91 /**
92 * Get the memcached keys
93 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
94 */
95 function getCacheKeys( ) {
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 wfDebugDieBacktrace( "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 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1274 }
1275
1276 #new fields must exist
1277 if ( !$db->fieldExists( 'image', 'img_media_type' )
1278 || !$db->fieldExists( 'image', 'img_metadata' )
1279 || !$db->fieldExists( 'image', 'img_width' ) ) {
1280
1281 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/update.php' );
1282 }
1283 }
1284
1285 /**
1286 * Return the image history of this image, line by line.
1287 * starts with current version, then old versions.
1288 * uses $this->historyLine to check which line to return:
1289 * 0 return line for current version
1290 * 1 query for old versions, return first one
1291 * 2, ... return next old version from above query
1292 *
1293 * @public
1294 */
1295 function nextHistoryLine() {
1296 $fname = 'Image::nextHistoryLine()';
1297 $dbr =& wfGetDB( DB_SLAVE );
1298
1299 $this->checkDBSchema($dbr);
1300
1301 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
1302 $this->historyRes = $dbr->select( 'image',
1303 array(
1304 'img_size',
1305 'img_description',
1306 'img_user','img_user_text',
1307 'img_timestamp',
1308 'img_width',
1309 'img_height',
1310 "'' AS oi_archive_name"
1311 ),
1312 array( 'img_name' => $this->title->getDBkey() ),
1313 $fname
1314 );
1315 if ( 0 == wfNumRows( $this->historyRes ) ) {
1316 return FALSE;
1317 }
1318 } else if ( $this->historyLine == 1 ) {
1319 $this->historyRes = $dbr->select( 'oldimage',
1320 array(
1321 'oi_size AS img_size',
1322 'oi_description AS img_description',
1323 'oi_user AS img_user',
1324 'oi_user_text AS img_user_text',
1325 'oi_timestamp AS img_timestamp',
1326 'oi_width as img_width',
1327 'oi_height as img_height',
1328 'oi_archive_name'
1329 ),
1330 array( 'oi_name' => $this->title->getDBkey() ),
1331 $fname,
1332 array( 'ORDER BY' => 'oi_timestamp DESC' )
1333 );
1334 }
1335 $this->historyLine ++;
1336
1337 return $dbr->fetchObject( $this->historyRes );
1338 }
1339
1340 /**
1341 * Reset the history pointer to the first element of the history
1342 * @public
1343 */
1344 function resetHistory() {
1345 $this->historyLine = 0;
1346 }
1347
1348 /**
1349 * Return the full filesystem path to the file. Note that this does
1350 * not mean that a file actually exists under that location.
1351 *
1352 * This path depends on whether directory hashing is active or not,
1353 * i.e. whether the images are all found in the same directory,
1354 * or in hashed paths like /images/3/3c.
1355 *
1356 * @public
1357 * @param boolean $fromSharedDirectory Return the path to the file
1358 * in a shared repository (see $wgUseSharedRepository and related
1359 * options in DefaultSettings.php) instead of a local one.
1360 *
1361 */
1362 function getFullPath( $fromSharedRepository = false ) {
1363 global $wgUploadDirectory, $wgSharedUploadDirectory;
1364
1365 $dir = $fromSharedRepository ? $wgSharedUploadDirectory :
1366 $wgUploadDirectory;
1367
1368 // $wgSharedUploadDirectory may be false, if thumb.php is used
1369 if ( $dir ) {
1370 $fullpath = $dir . wfGetHashPath($this->name, $fromSharedRepository) . $this->name;
1371 } else {
1372 $fullpath = false;
1373 }
1374
1375 return $fullpath;
1376 }
1377
1378 /**
1379 * @return bool
1380 * @static
1381 */
1382 function isHashed( $shared ) {
1383 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1384 return $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1385 }
1386
1387 /**
1388 * Record an image upload in the upload log and the image table
1389 */
1390 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1391 global $wgUser, $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
1392
1393 $fname = 'Image::recordUpload';
1394 $dbw =& wfGetDB( DB_MASTER );
1395
1396 $this->checkDBSchema($dbw);
1397
1398 // Delete thumbnails and refresh the metadata cache
1399 $this->purgeCache();
1400
1401 // Fail now if the image isn't there
1402 if ( !$this->fileExists || $this->fromSharedDirectory ) {
1403 wfDebug( "Image::recordUpload: File ".$this->imagePath." went missing!\n" );
1404 return false;
1405 }
1406
1407 if ( $wgUseCopyrightUpload ) {
1408 if ( $license != '' ) {
1409 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1410 }
1411 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1412 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1413 "$licensetxt" .
1414 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1415 } else {
1416 if ( $license != '' ) {
1417 $filedesc = $desc == '' ? '' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
1418 $textdesc = $filedesc .
1419 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1420 } else {
1421 $textdesc = $desc;
1422 }
1423 }
1424
1425 $now = $dbw->timestamp();
1426
1427 #split mime type
1428 if (strpos($this->mime,'/')!==false) {
1429 list($major,$minor)= explode('/',$this->mime,2);
1430 }
1431 else {
1432 $major= $this->mime;
1433 $minor= "unknown";
1434 }
1435
1436 # Test to see if the row exists using INSERT IGNORE
1437 # This avoids race conditions by locking the row until the commit, and also
1438 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1439 $dbw->insert( 'image',
1440 array(
1441 'img_name' => $this->name,
1442 'img_size'=> $this->size,
1443 'img_width' => intval( $this->width ),
1444 'img_height' => intval( $this->height ),
1445 'img_bits' => $this->bits,
1446 'img_media_type' => $this->type,
1447 'img_major_mime' => $major,
1448 'img_minor_mime' => $minor,
1449 'img_timestamp' => $now,
1450 'img_description' => $desc,
1451 'img_user' => $wgUser->getID(),
1452 'img_user_text' => $wgUser->getName(),
1453 'img_metadata' => $this->metadata,
1454 ),
1455 $fname,
1456 'IGNORE'
1457 );
1458 $descTitle = $this->getTitle();
1459 $purgeURLs = array();
1460
1461 if( $dbw->affectedRows() == 0 ) {
1462 # Collision, this is an update of an image
1463 # Insert previous contents into oldimage
1464 $dbw->insertSelect( 'oldimage', 'image',
1465 array(
1466 'oi_name' => 'img_name',
1467 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1468 'oi_size' => 'img_size',
1469 'oi_width' => 'img_width',
1470 'oi_height' => 'img_height',
1471 'oi_bits' => 'img_bits',
1472 'oi_timestamp' => 'img_timestamp',
1473 'oi_description' => 'img_description',
1474 'oi_user' => 'img_user',
1475 'oi_user_text' => 'img_user_text',
1476 ), array( 'img_name' => $this->name ), $fname
1477 );
1478
1479 # Update the current image row
1480 $dbw->update( 'image',
1481 array( /* SET */
1482 'img_size' => $this->size,
1483 'img_width' => intval( $this->width ),
1484 'img_height' => intval( $this->height ),
1485 'img_bits' => $this->bits,
1486 'img_media_type' => $this->type,
1487 'img_major_mime' => $major,
1488 'img_minor_mime' => $minor,
1489 'img_timestamp' => $now,
1490 'img_description' => $desc,
1491 'img_user' => $wgUser->getID(),
1492 'img_user_text' => $wgUser->getName(),
1493 'img_metadata' => $this->metadata,
1494 ), array( /* WHERE */
1495 'img_name' => $this->name
1496 ), $fname
1497 );
1498 } else {
1499 # This is a new image
1500 # Update the image count
1501 $site_stats = $dbw->tableName( 'site_stats' );
1502 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", $fname );
1503 }
1504
1505 $article = new Article( $descTitle );
1506 $minor = false;
1507 $watch = $watch || $wgUser->isWatched( $descTitle );
1508 $suppressRC = true; // There's already a log entry, so don't double the RC load
1509
1510 if( $descTitle->exists() ) {
1511 // TODO: insert a null revision into the page history for this update.
1512 if( $watch ) {
1513 $wgUser->addWatch( $descTitle );
1514 }
1515
1516 # Invalidate the cache for the description page
1517 $descTitle->invalidateCache();
1518 $purgeURLs[] = $descTitle->getInternalURL();
1519 } else {
1520 // New image; create the description page.
1521 $article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
1522 }
1523
1524 # Invalidate cache for all pages using this image
1525 $linksTo = $this->getLinksTo();
1526
1527 if ( $wgUseSquid ) {
1528 $u = SquidUpdate::newFromTitles( $linksTo, $purgeURLs );
1529 array_push( $wgPostCommitUpdateList, $u );
1530 }
1531 Title::touchArray( $linksTo );
1532
1533 $log = new LogPage( 'upload' );
1534 $log->addEntry( 'upload', $descTitle, $desc );
1535
1536 return true;
1537 }
1538
1539 /**
1540 * Get an array of Title objects which are articles which use this image
1541 * Also adds their IDs to the link cache
1542 *
1543 * This is mostly copied from Title::getLinksTo()
1544 */
1545 function getLinksTo( $options = '' ) {
1546 $fname = 'Image::getLinksTo';
1547 wfProfileIn( $fname );
1548
1549 if ( $options ) {
1550 $db =& wfGetDB( DB_MASTER );
1551 } else {
1552 $db =& wfGetDB( DB_SLAVE );
1553 }
1554 $linkCache =& LinkCache::singleton();
1555
1556 extract( $db->tableNames( 'page', 'imagelinks' ) );
1557 $encName = $db->addQuotes( $this->name );
1558 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1559 $res = $db->query( $sql, $fname );
1560
1561 $retVal = array();
1562 if ( $db->numRows( $res ) ) {
1563 while ( $row = $db->fetchObject( $res ) ) {
1564 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1565 $linkCache->addGoodLinkObj( $row->page_id, $titleObj );
1566 $retVal[] = $titleObj;
1567 }
1568 }
1569 }
1570 $db->freeResult( $res );
1571 wfProfileOut( $fname );
1572 return $retVal;
1573 }
1574 /**
1575 * Retrive Exif data from the database
1576 *
1577 * Retrive Exif data from the database and prune unrecognized tags
1578 * and/or tags with invalid contents
1579 *
1580 * @return array
1581 */
1582 function retrieveExifData() {
1583 if ( $this->getMimeType() !== "image/jpeg" )
1584 return array();
1585
1586 $exif = new Exif( $this->imagePath );
1587 return $exif->getFilteredData();
1588 }
1589
1590 function getExifData() {
1591 global $wgRequest;
1592 if ( $this->metadata === '0' )
1593 return array();
1594
1595 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1596 $ret = unserialize( $this->metadata );
1597
1598 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ? $ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1599 $newver = Exif::version();
1600
1601 if ( !count( $ret ) || $purge || $oldver != $newver ) {
1602 $this->purgeMetadataCache();
1603 $this->updateExifData( $newver );
1604 }
1605 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1606 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1607 $format = new FormatExif( $ret );
1608
1609 return $format->getFormattedData();
1610 }
1611
1612 function updateExifData( $version ) {
1613 $fname = 'Image:updateExifData';
1614
1615 if ( $this->getImagePath() === false ) # Not a local image
1616 return;
1617
1618 # Get EXIF data from image
1619 $exif = $this->retrieveExifData();
1620 if ( count( $exif ) ) {
1621 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1622 $this->metadata = serialize( $exif );
1623 } else {
1624 $this->metadata = '0';
1625 }
1626
1627 # Update EXIF data in database
1628 $dbw =& wfGetDB( DB_MASTER );
1629
1630 $this->checkDBSchema($dbw);
1631
1632 $dbw->update( 'image',
1633 array( 'img_metadata' => $this->metadata ),
1634 array( 'img_name' => $this->name ),
1635 $fname
1636 );
1637 }
1638
1639 /**
1640 * Returns true if the image does not come from the shared
1641 * image repository.
1642 *
1643 * @return bool
1644 */
1645 function isLocal() {
1646 return !$this->fromSharedDirectory;
1647 }
1648
1649 /**
1650 * Was this image ever deleted from the wiki?
1651 *
1652 * @return bool
1653 */
1654 function wasDeleted() {
1655 $dbw =& wfGetDB( DB_MASTER );
1656 $del = $dbw->selectField( 'archive', 'COUNT(*) AS count', array( 'ar_namespace' => NS_IMAGE, 'ar_title' => $this->title->getDBkey() ), 'Image::wasDeleted' );
1657 return $del > 0;
1658 }
1659
1660 } //class
1661
1662
1663 /**
1664 * Returns the image directory of an image
1665 * If the directory does not exist, it is created.
1666 * The result is an absolute path.
1667 *
1668 * This function is called from thumb.php before Setup.php is included
1669 *
1670 * @param $fname String: file name of the image file.
1671 * @public
1672 */
1673 function wfImageDir( $fname ) {
1674 global $wgUploadDirectory, $wgHashedUploadDirectory;
1675
1676 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1677
1678 $hash = md5( $fname );
1679 $oldumask = umask(0);
1680 $dest = $wgUploadDirectory . '/' . $hash{0};
1681 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1682 $dest .= '/' . substr( $hash, 0, 2 );
1683 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1684
1685 umask( $oldumask );
1686 return $dest;
1687 }
1688
1689 /**
1690 * Returns the image directory of an image's thubnail
1691 * If the directory does not exist, it is created.
1692 * The result is an absolute path.
1693 *
1694 * This function is called from thumb.php before Setup.php is included
1695 *
1696 * @param $fname String: file name of the original image file
1697 * @param $shared Boolean: (optional) use the shared upload directory (default: 'false').
1698 * @public
1699 */
1700 function wfImageThumbDir( $fname, $shared = false ) {
1701 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1702 if ( Image::isHashed( $shared ) ) {
1703 $dir = "$base/$fname";
1704
1705 if ( !is_dir( $base ) ) {
1706 $oldumask = umask(0);
1707 @mkdir( $base, 0777 );
1708 umask( $oldumask );
1709 }
1710
1711 if ( ! is_dir( $dir ) ) {
1712 if ( is_file( $dir ) ) {
1713 // Old thumbnail in the way of directory creation, kill it
1714 unlink( $dir );
1715 }
1716 $oldumask = umask(0);
1717 @mkdir( $dir, 0777 );
1718 umask( $oldumask );
1719 }
1720 } else {
1721 $dir = $base;
1722 }
1723
1724 return $dir;
1725 }
1726
1727 /**
1728 * Old thumbnail directory, kept for conversion
1729 */
1730 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1731 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1732 }
1733
1734 /**
1735 * Returns the image directory of an image's old version
1736 * If the directory does not exist, it is created.
1737 * The result is an absolute path.
1738 *
1739 * This function is called from thumb.php before Setup.php is included
1740 *
1741 * @param $fname String: file name of the thumbnail file, including file size prefix.
1742 * @param $subdir String: subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'.
1743 * @param $shared Boolean use the shared upload directory (only relevant for other functions which call this one). Default is 'false'.
1744 * @public
1745 */
1746 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1747 global $wgUploadDirectory, $wgHashedUploadDirectory;
1748 global $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1749 $dir = $shared ? $wgSharedUploadDirectory : $wgUploadDirectory;
1750 $hashdir = $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1751 if (!$hashdir) { return $dir.'/'.$subdir; }
1752 $hash = md5( $fname );
1753 $oldumask = umask(0);
1754
1755 # Suppress warning messages here; if the file itself can't
1756 # be written we'll worry about it then.
1757 wfSuppressWarnings();
1758
1759 $archive = $dir.'/'.$subdir;
1760 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1761 $archive .= '/' . $hash{0};
1762 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1763 $archive .= '/' . substr( $hash, 0, 2 );
1764 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1765
1766 wfRestoreWarnings();
1767 umask( $oldumask );
1768 return $archive;
1769 }
1770
1771
1772 /*
1773 * Return the hash path component of an image path (URL or filesystem),
1774 * e.g. "/3/3c/", or just "/" if hashing is not used.
1775 *
1776 * @param $dbkey The filesystem / database name of the file
1777 * @param $fromSharedDirectory Use the shared file repository? It may
1778 * use different hash settings from the local one.
1779 */
1780 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1781 if( Image::isHashed( $fromSharedDirectory ) ) {
1782 $hash = md5($dbkey);
1783 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1784 } else {
1785 return '/';
1786 }
1787 }
1788
1789 /**
1790 * Returns the image URL of an image's old version
1791 *
1792 * @param $name String: file name of the image file
1793 * @param $subdir String: (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1794 * @public
1795 */
1796 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1797 global $wgUploadPath, $wgHashedUploadDirectory;
1798
1799 if ($wgHashedUploadDirectory) {
1800 $hash = md5( substr( $name, 15) );
1801 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1802 substr( $hash, 0, 2 ) . '/'.$name;
1803 } else {
1804 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1805 }
1806 return wfUrlencode($url);
1807 }
1808
1809 /**
1810 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1811 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1812 *
1813 * @param $length String: CSS/SVG length.
1814 * @return Integer: length in pixels
1815 */
1816 function wfScaleSVGUnit( $length ) {
1817 static $unitLength = array(
1818 'px' => 1.0,
1819 'pt' => 1.25,
1820 'pc' => 15.0,
1821 'mm' => 3.543307,
1822 'cm' => 35.43307,
1823 'in' => 90.0,
1824 '' => 1.0, // "User units" pixels by default
1825 '%' => 2.0, // Fake it!
1826 );
1827 if( preg_match( '/^(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1828 $length = floatval( $matches[1] );
1829 $unit = $matches[2];
1830 return round( $length * $unitLength[$unit] );
1831 } else {
1832 // Assume pixels
1833 return round( floatval( $length ) );
1834 }
1835 }
1836
1837 /**
1838 * Compatible with PHP getimagesize()
1839 * @todo support gzipped SVGZ
1840 * @todo check XML more carefully
1841 * @todo sensible defaults
1842 *
1843 * @param $filename String: full name of the file (passed to php fopen()).
1844 * @return array
1845 */
1846 function wfGetSVGsize( $filename ) {
1847 $width = 256;
1848 $height = 256;
1849
1850 // Read a chunk of the file
1851 $f = fopen( $filename, "rt" );
1852 if( !$f ) return false;
1853 $chunk = fread( $f, 4096 );
1854 fclose( $f );
1855
1856 // Uber-crappy hack! Run through a real XML parser.
1857 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1858 return false;
1859 }
1860 $tag = $matches[1];
1861 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1862 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1863 }
1864 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1865 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1866 }
1867
1868 return array( $width, $height, 'SVG',
1869 "width=\"$width\" height=\"$height\"" );
1870 }
1871
1872 /**
1873 * Determine if an image exists on the 'bad image list'.
1874 *
1875 * @param $name String: the image name to check
1876 * @return bool
1877 */
1878 function wfIsBadImage( $name ) {
1879 static $titleList = false;
1880
1881 if( !$titleList ) {
1882 # Build the list now
1883 $titleList = array();
1884 $lines = explode( "\n", wfMsgForContent( 'bad_image_list' ) );
1885 foreach( $lines as $line ) {
1886 if( preg_match( '/^\*\s*\[\[:?(.*?)\]\]/i', $line, $matches ) ) {
1887 $title = Title::newFromText( $matches[1] );
1888 if( is_object( $title ) && $title->getNamespace() == NS_IMAGE )
1889 $titleList[ $title->getDBkey() ] = true;
1890 }
1891 }
1892 }
1893 return array_key_exists( $name, $titleList );
1894 }
1895
1896
1897
1898 /**
1899 * Wrapper class for thumbnail images
1900 * @package MediaWiki
1901 */
1902 class ThumbnailImage {
1903 /**
1904 * @param string $path Filesystem path to the thumb
1905 * @param string $url URL path to the thumb
1906 * @private
1907 */
1908 function ThumbnailImage( $url, $width, $height, $path = false ) {
1909 $this->url = $url;
1910 $this->width = round( $width );
1911 $this->height = round( $height );
1912 # These should be integers when they get here.
1913 # If not, there's a bug somewhere. But let's at
1914 # least produce valid HTML code regardless.
1915 $this->path = $path;
1916 }
1917
1918 /**
1919 * @return string The thumbnail URL
1920 */
1921 function getUrl() {
1922 return $this->url;
1923 }
1924
1925 /**
1926 * Return HTML <img ... /> tag for the thumbnail, will include
1927 * width and height attributes and a blank alt text (as required).
1928 *
1929 * You can set or override additional attributes by passing an
1930 * associative array of name => data pairs. The data will be escaped
1931 * for HTML output, so should be in plaintext.
1932 *
1933 * @param array $attribs
1934 * @return string
1935 * @public
1936 */
1937 function toHtml( $attribs = array() ) {
1938 $attribs['src'] = $this->url;
1939 $attribs['width'] = $this->width;
1940 $attribs['height'] = $this->height;
1941 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1942
1943 $html = '<img ';
1944 foreach( $attribs as $name => $data ) {
1945 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
1946 }
1947 $html .= '/>';
1948 return $html;
1949 }
1950
1951 }
1952
1953 /**
1954 * Calculate the largest thumbnail width for a given original file size
1955 * such that the thumbnail's height is at most $maxHeight.
1956 * @param $boxWidth Integer Width of the thumbnail box.
1957 * @param $boxHeight Integer Height of the thumbnail box.
1958 * @param $maxHeight Integer Maximum height expected for the thumbnail.
1959 * @return Integer.
1960 */
1961 function wfFitBoxWidth( $boxWidth, $boxHeight, $maxHeight ) {
1962 $idealWidth = $boxWidth * $maxHeight / $boxHeight;
1963 $roundedUp = ceil( $idealWidth );
1964 if( round( $roundedUp * $boxHeight / $boxWidth ) > $maxHeight )
1965 return floor( $idealWidth );
1966 else
1967 return $roundedUp;
1968 }
1969
1970 ?>