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