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