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