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