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