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