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