Revert last change, which breaks the only usage of the upload license selector
[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 );
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 ther'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 if( $width >= $this->width && !$this->mustRender() ) {
938 # Don't make an image bigger than the source
939 $thumb = new ThumbnailImage( $this->getViewURL(), $this->getWidth(), $this->getHeight() );
940 wfProfileOut( $fname );
941 return $thumb;
942 }
943
944 $height = floor( $this->height * ( $width/$this->width ) );
945
946 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
947 if ( $isScriptUrl && $useScript ) {
948 // Use thumb.php to render the image
949 $thumb = new ThumbnailImage( $url, $width, $height );
950 wfProfileOut( $fname );
951 return $thumb;
952 }
953
954 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory );
955 $thumbPath = wfImageThumbDir( $this->name, $this->fromSharedDirectory ).'/'.$thumbName;
956
957 if ( !file_exists( $thumbPath ) ) {
958 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory ).
959 '/'.$thumbName;
960 $done = false;
961 if ( file_exists( $oldThumbPath ) ) {
962 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath) ) {
963 rename( $oldThumbPath, $thumbPath );
964 $done = true;
965 } else {
966 unlink( $oldThumbPath );
967 }
968 }
969 if ( !$done ) {
970 $this->reallyRenderThumb( $thumbPath, $width, $height );
971
972 # Purge squid
973 # This has to be done after the image is updated and present for all machines on NFS,
974 # or else the old version might be stored into the squid again
975 if ( $wgUseSquid ) {
976 if ( substr( $url, 0, 4 ) == 'http' ) {
977 $urlArr = array( $url );
978 } else {
979 $urlArr = array( $wgInternalServer.$url );
980 }
981 wfPurgeSquidServers($urlArr);
982 }
983 }
984 }
985
986 $thumb = new ThumbnailImage( $url, $width, $height, $thumbPath );
987 wfProfileOut( $fname );
988 return $thumb;
989 } // END OF function renderThumb
990
991 /**
992 * Really render a thumbnail
993 * Call this only for images for which canRender() returns true.
994 *
995 * @access private
996 */
997 function reallyRenderThumb( $thumbPath, $width, $height ) {
998 global $wgSVGConverters, $wgSVGConverter,
999 $wgUseImageMagick, $wgImageMagickConvertCommand;
1000
1001 $this->load();
1002
1003 if( $this->mime === "image/svg" ) {
1004 #Right now we have only SVG
1005
1006 global $wgSVGConverters, $wgSVGConverter;
1007 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
1008 global $wgSVGConverterPath;
1009 $cmd = str_replace(
1010 array( '$path/', '$width', '$input', '$output' ),
1011 array( $wgSVGConverterPath,
1012 $width,
1013 wfEscapeShellArg( $this->imagePath ),
1014 wfEscapeShellArg( $thumbPath ) ),
1015 $wgSVGConverters[$wgSVGConverter] );
1016 $conv = shell_exec( $cmd );
1017 } else {
1018 $conv = false;
1019 }
1020 } elseif ( $wgUseImageMagick ) {
1021 # use ImageMagick
1022 # Specify white background color, will be used for transparent images
1023 # in Internet Explorer/Windows instead of default black.
1024 $cmd = $wgImageMagickConvertCommand .
1025 " -quality 85 -background white -geometry {$width} ".
1026 wfEscapeShellArg($this->imagePath) . " " .
1027 wfEscapeShellArg($thumbPath);
1028 wfDebug("reallyRenderThumb: running ImageMagick: $cmd");
1029 $conv = shell_exec( $cmd );
1030 } else {
1031 # Use PHP's builtin GD library functions.
1032 #
1033 # First find out what kind of file this is, and select the correct
1034 # input routine for this.
1035
1036 $typemap = array(
1037 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
1038 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( &$this, 'imageJpegWrapper' ) ),
1039 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
1040 'image/vnd.wap.wmbp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
1041 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
1042 );
1043 if( !isset( $typemap[$this->mime] ) ) {
1044 $err = 'Image type not supported';
1045 wfDebug( "$err\n" );
1046 return $err;
1047 }
1048 list( $loader, $colorStyle, $saveType ) = $typemap[$this->mime];
1049
1050 if( !function_exists( $loader ) ) {
1051 $err = "Incomplete GD library configuration: missing function $loader";
1052 wfDebug( "$err\n" );
1053 return $err;
1054 }
1055 if( $colorStyle == 'palette' ) {
1056 $truecolor = false;
1057 } elseif( $colorStyle == 'truecolor' ) {
1058 $truecolor = true;
1059 } elseif( $colorStyle == 'bits' ) {
1060 $truecolor = ( $this->bits > 8 );
1061 }
1062
1063 $src_image = call_user_func( $loader, $this->imagePath );
1064 if ( $truecolor ) {
1065 $dst_image = imagecreatetruecolor( $width, $height );
1066 } else {
1067 $dst_image = imagecreate( $width, $height );
1068 }
1069 imagecopyresampled( $dst_image, $src_image,
1070 0,0,0,0,
1071 $width, $height, $this->width, $this->height );
1072 call_user_func( $saveType, $dst_image, $thumbPath );
1073 imagedestroy( $dst_image );
1074 imagedestroy( $src_image );
1075 }
1076
1077 #
1078 # Check for zero-sized thumbnails. Those can be generated when
1079 # no disk space is available or some other error occurs
1080 #
1081 if( file_exists( $thumbPath ) ) {
1082 $thumbstat = stat( $thumbPath );
1083 if( $thumbstat['size'] == 0 ) {
1084 unlink( $thumbPath );
1085 }
1086 }
1087 }
1088
1089 function imageJpegWrapper( $dst_image, $thumbPath ) {
1090 imageinterlace( $dst_image );
1091 imagejpeg( $dst_image, $thumbPath, 95 );
1092 }
1093
1094 /**
1095 * Get all thumbnail names previously generated for this image
1096 */
1097 function getThumbnails( $shared = false ) {
1098 if ( Image::isHashed( $shared ) ) {
1099 $this->load();
1100 $files = array();
1101 $dir = wfImageThumbDir( $this->name, $shared );
1102
1103 // This generates an error on failure, hence the @
1104 $handle = @opendir( $dir );
1105
1106 if ( $handle ) {
1107 while ( false !== ( $file = readdir($handle) ) ) {
1108 if ( $file{0} != '.' ) {
1109 $files[] = $file;
1110 }
1111 }
1112 closedir( $handle );
1113 }
1114 } else {
1115 $files = array();
1116 }
1117
1118 return $files;
1119 }
1120
1121 /**
1122 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1123 */
1124 function purgeCache( $archiveFiles = array(), $shared = false ) {
1125 global $wgInternalServer, $wgUseSquid;
1126
1127 // Refresh metadata cache
1128 clearstatcache();
1129 $this->loadFromFile();
1130 $this->saveToCache();
1131
1132 // Delete thumbnails
1133 $files = $this->getThumbnails( $shared );
1134 $dir = wfImageThumbDir( $this->name, $shared );
1135 $urls = array();
1136 foreach ( $files as $file ) {
1137 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1138 $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory );
1139 @unlink( "$dir/$file" );
1140 }
1141 }
1142
1143 // Purge the squid
1144 if ( $wgUseSquid ) {
1145 $urls[] = $wgInternalServer . $this->getViewURL();
1146 foreach ( $archiveFiles as $file ) {
1147 $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
1148 }
1149 wfPurgeSquidServers( $urls );
1150 }
1151 }
1152
1153 function checkDBSchema(&$db) {
1154 # img_name must be unique
1155 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1156 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1157 }
1158
1159 #new fields must exist
1160 if ( !$db->fieldExists( 'image', 'img_media_type' )
1161 || !$db->fieldExists( 'image', 'img_metadata' )
1162 || !$db->fieldExists( 'image', 'img_width' ) ) {
1163
1164 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/update.php' );
1165 }
1166 }
1167
1168 /**
1169 * Return the image history of this image, line by line.
1170 * starts with current version, then old versions.
1171 * uses $this->historyLine to check which line to return:
1172 * 0 return line for current version
1173 * 1 query for old versions, return first one
1174 * 2, ... return next old version from above query
1175 *
1176 * @access public
1177 */
1178 function nextHistoryLine() {
1179 $fname = 'Image::nextHistoryLine()';
1180 $dbr =& wfGetDB( DB_SLAVE );
1181
1182 $this->checkDBSchema($dbr);
1183
1184 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
1185 $this->historyRes = $dbr->select( 'image',
1186 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
1187 array( 'img_name' => $this->title->getDBkey() ),
1188 $fname
1189 );
1190 if ( 0 == wfNumRows( $this->historyRes ) ) {
1191 return FALSE;
1192 }
1193 } else if ( $this->historyLine == 1 ) {
1194 $this->historyRes = $dbr->select( 'oldimage',
1195 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
1196 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
1197 ), array( 'oi_name' => $this->title->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
1198 );
1199 }
1200 $this->historyLine ++;
1201
1202 return $dbr->fetchObject( $this->historyRes );
1203 }
1204
1205 /**
1206 * Reset the history pointer to the first element of the history
1207 * @access public
1208 */
1209 function resetHistory() {
1210 $this->historyLine = 0;
1211 }
1212
1213 /**
1214 * Return the full filesystem path to the file. Note that this does
1215 * not mean that a file actually exists under that location.
1216 *
1217 * This path depends on whether directory hashing is active or not,
1218 * i.e. whether the images are all found in the same directory,
1219 * or in hashed paths like /images/3/3c.
1220 *
1221 * @access public
1222 * @param boolean $fromSharedDirectory Return the path to the file
1223 * in a shared repository (see $wgUseSharedRepository and related
1224 * options in DefaultSettings.php) instead of a local one.
1225 *
1226 */
1227 function getFullPath( $fromSharedRepository = false ) {
1228 global $wgUploadDirectory, $wgSharedUploadDirectory;
1229 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1230
1231 $dir = $fromSharedRepository ? $wgSharedUploadDirectory :
1232 $wgUploadDirectory;
1233
1234 // $wgSharedUploadDirectory may be false, if thumb.php is used
1235 if ( $dir ) {
1236 $fullpath = $dir . wfGetHashPath($this->name, $fromSharedRepository) . $this->name;
1237 } else {
1238 $fullpath = false;
1239 }
1240
1241 return $fullpath;
1242 }
1243
1244 /**
1245 * @return bool
1246 * @static
1247 */
1248 function isHashed( $shared ) {
1249 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1250 return $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1251 }
1252
1253 /**
1254 * Record an image upload in the upload log and the image table
1255 */
1256 function recordUpload( $oldver, $desc, $license, $copyStatus = '', $source = '' ) {
1257 global $wgUser, $wgLang, $wgTitle, $wgDeferredUpdateList;
1258 global $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
1259
1260 $fname = 'Image::recordUpload';
1261 $dbw =& wfGetDB( DB_MASTER );
1262
1263 $this->checkDBSchema($dbw);
1264
1265 // Delete thumbnails and refresh the metadata cache
1266 $this->purgeCache();
1267
1268 // Fail now if the image isn't there
1269 if ( !$this->fileExists || $this->fromSharedDirectory ) {
1270 wfDebug( "Image::recordUpload: File ".$this->imagePath." went missing!\n" );
1271 return false;
1272 }
1273
1274 if ( $wgUseCopyrightUpload ) {
1275 if ( $license != '' ) {
1276 $licensetxt = '== ' . wfMsg( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1277 }
1278 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1279 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1280 "$licensetxt" .
1281 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
1282 } else {
1283 if ( $license != '' ) {
1284 $filedesc = $desc == '' ? '' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
1285 $textdesc = $filedesc .
1286 '== ' . wfMsg ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1287 } else {
1288 $textdesc = $desc;
1289 }
1290 }
1291
1292 $now = $dbw->timestamp();
1293
1294 #split mime type
1295 if (strpos($this->mime,'/')!==false) {
1296 list($major,$minor)= explode('/',$this->mime,2);
1297 }
1298 else {
1299 $major= $this->mime;
1300 $minor= "unknown";
1301 }
1302
1303 # Test to see if the row exists using INSERT IGNORE
1304 # This avoids race conditions by locking the row until the commit, and also
1305 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1306 $dbw->insert( 'image',
1307 array(
1308 'img_name' => $this->name,
1309 'img_size'=> $this->size,
1310 'img_width' => intval( $this->width ),
1311 'img_height' => intval( $this->height ),
1312 'img_bits' => $this->bits,
1313 'img_media_type' => $this->type,
1314 'img_major_mime' => $major,
1315 'img_minor_mime' => $minor,
1316 'img_timestamp' => $now,
1317 'img_description' => $desc,
1318 'img_user' => $wgUser->getID(),
1319 'img_user_text' => $wgUser->getName(),
1320 'img_metadata' => $this->metadata,
1321 ), $fname, 'IGNORE'
1322 );
1323 $descTitle = $this->getTitle();
1324 $purgeURLs = array();
1325
1326 if ( $dbw->affectedRows() ) {
1327 # Successfully inserted, this is a new image
1328 $id = $descTitle->getArticleID();
1329
1330 if ( $id == 0 ) {
1331 $article = new Article( $descTitle );
1332 $article->insertNewArticle( $textdesc, $desc, false, false, true );
1333 }
1334 } else {
1335 # Collision, this is an update of an image
1336 # Insert previous contents into oldimage
1337 $dbw->insertSelect( 'oldimage', 'image',
1338 array(
1339 'oi_name' => 'img_name',
1340 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1341 'oi_size' => 'img_size',
1342 'oi_width' => 'img_width',
1343 'oi_height' => 'img_height',
1344 'oi_bits' => 'img_bits',
1345 'oi_timestamp' => 'img_timestamp',
1346 'oi_description' => 'img_description',
1347 'oi_user' => 'img_user',
1348 'oi_user_text' => 'img_user_text',
1349 ), array( 'img_name' => $this->name ), $fname
1350 );
1351
1352 # Update the current image row
1353 $dbw->update( 'image',
1354 array( /* SET */
1355 'img_size' => $this->size,
1356 'img_width' => intval( $this->width ),
1357 'img_height' => intval( $this->height ),
1358 'img_bits' => $this->bits,
1359 'img_media_type' => $this->type,
1360 'img_major_mime' => $major,
1361 'img_minor_mime' => $minor,
1362 'img_timestamp' => $now,
1363 'img_description' => $desc,
1364 'img_user' => $wgUser->getID(),
1365 'img_user_text' => $wgUser->getName(),
1366 'img_metadata' => $this->metadata,
1367 ), array( /* WHERE */
1368 'img_name' => $this->name
1369 ), $fname
1370 );
1371
1372 # Invalidate the cache for the description page
1373 $descTitle->invalidateCache();
1374 $purgeURLs[] = $descTitle->getInternalURL();
1375 }
1376
1377 # Invalidate cache for all pages using this image
1378 $linksTo = $this->getLinksTo();
1379
1380 if ( $wgUseSquid ) {
1381 $u = SquidUpdate::newFromTitles( $linksTo, $purgeURLs );
1382 array_push( $wgPostCommitUpdateList, $u );
1383 }
1384 Title::touchArray( $linksTo );
1385
1386 $log = new LogPage( 'upload' );
1387 $log->addEntry( 'upload', $descTitle, $desc );
1388
1389 return true;
1390 }
1391
1392 /**
1393 * Get an array of Title objects which are articles which use this image
1394 * Also adds their IDs to the link cache
1395 *
1396 * This is mostly copied from Title::getLinksTo()
1397 */
1398 function getLinksTo( $options = '' ) {
1399 global $wgLinkCache;
1400 $fname = 'Image::getLinksTo';
1401 wfProfileIn( $fname );
1402
1403 if ( $options ) {
1404 $db =& wfGetDB( DB_MASTER );
1405 } else {
1406 $db =& wfGetDB( DB_SLAVE );
1407 }
1408
1409 extract( $db->tableNames( 'page', 'imagelinks' ) );
1410 $encName = $db->addQuotes( $this->name );
1411 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1412 $res = $db->query( $sql, $fname );
1413
1414 $retVal = array();
1415 if ( $db->numRows( $res ) ) {
1416 while ( $row = $db->fetchObject( $res ) ) {
1417 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1418 $wgLinkCache->addGoodLinkObj( $row->page_id, $titleObj );
1419 $retVal[] = $titleObj;
1420 }
1421 }
1422 }
1423 $db->freeResult( $res );
1424 return $retVal;
1425 }
1426 /**
1427 * Retrive Exif data from the database
1428 *
1429 * Retrive Exif data from the database and prune unrecognized tags
1430 * and/or tags with invalid contents
1431 *
1432 * @return array
1433 */
1434 function retrieveExifData () {
1435 if ( $this->getMimeType() !== "image/jpeg" ) return array ();
1436
1437 $exif = new Exif( $this->imagePath );
1438 return $exif->getFilteredData();
1439 }
1440
1441 function getExifData () {
1442 global $wgRequest;
1443 if ( $this->metadata === '0' )
1444 return array();
1445
1446 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1447 $ret = unserialize ( $this->metadata );
1448
1449 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ? $ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1450 $newver = Exif::version();
1451
1452 if ( !count( $ret ) || $purge || $oldver != $newver ) {
1453 $this->updateExifData( $newver );
1454 }
1455 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1456 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1457 $format = new FormatExif( $ret );
1458 return $format->getFormattedData();
1459 }
1460
1461 function updateExifData( $version ) {
1462 $fname = 'Image:updateExifData';
1463
1464 if ( $this->getImagePath() === false ) # Not a local image
1465 return;
1466
1467 # Get EXIF data from image
1468 $exif = $this->retrieveExifData();
1469 if ( count( $exif ) ) {
1470 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1471 $this->metadata = serialize( $exif );
1472 } else {
1473 $this->metadata = '0';
1474 }
1475
1476 # Update EXIF data in database
1477 $dbw =& wfGetDB( DB_MASTER );
1478
1479 $this->checkDBSchema($dbw);
1480
1481 $dbw->update( 'image',
1482 array( 'img_metadata' => $this->metadata ),
1483 array( 'img_name' => $this->name ),
1484 $fname
1485 );
1486 }
1487
1488 } //class
1489
1490
1491 /**
1492 * Returns the image directory of an image
1493 * If the directory does not exist, it is created.
1494 * The result is an absolute path.
1495 *
1496 * This function is called from thumb.php before Setup.php is included
1497 *
1498 * @param string $fname file name of the image file
1499 * @access public
1500 */
1501 function wfImageDir( $fname ) {
1502 global $wgUploadDirectory, $wgHashedUploadDirectory;
1503
1504 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1505
1506 $hash = md5( $fname );
1507 $oldumask = umask(0);
1508 $dest = $wgUploadDirectory . '/' . $hash{0};
1509 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1510 $dest .= '/' . substr( $hash, 0, 2 );
1511 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1512
1513 umask( $oldumask );
1514 return $dest;
1515 }
1516
1517 /**
1518 * Returns the image directory of an image's thubnail
1519 * If the directory does not exist, it is created.
1520 * The result is an absolute path.
1521 *
1522 * This function is called from thumb.php before Setup.php is included
1523 *
1524 * @param string $fname file name of the original image file
1525 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
1526 * @param boolean $shared (optional) use the shared upload directory
1527 * @access public
1528 */
1529 function wfImageThumbDir( $fname, $shared = false ) {
1530 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1531 if ( Image::isHashed( $shared ) ) {
1532 $dir = "$base/$fname";
1533
1534 if ( !is_dir( $base ) ) {
1535 $oldumask = umask(0);
1536 @mkdir( $base, 0777 );
1537 umask( $oldumask );
1538 }
1539
1540 if ( ! is_dir( $dir ) ) {
1541 $oldumask = umask(0);
1542 @mkdir( $dir, 0777 );
1543 umask( $oldumask );
1544 }
1545 } else {
1546 $dir = $base;
1547 }
1548
1549 return $dir;
1550 }
1551
1552 /**
1553 * Old thumbnail directory, kept for conversion
1554 */
1555 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1556 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1557 }
1558
1559 /**
1560 * Returns the image directory of an image's old version
1561 * If the directory does not exist, it is created.
1562 * The result is an absolute path.
1563 *
1564 * This function is called from thumb.php before Setup.php is included
1565 *
1566 * @param string $fname file name of the thumbnail file, including file size prefix
1567 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
1568 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
1569 * @access public
1570 */
1571 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1572 global $wgUploadDirectory, $wgHashedUploadDirectory,
1573 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1574 $dir = $shared ? $wgSharedUploadDirectory : $wgUploadDirectory;
1575 $hashdir = $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1576 if (!$hashdir) { return $dir.'/'.$subdir; }
1577 $hash = md5( $fname );
1578 $oldumask = umask(0);
1579
1580 # Suppress warning messages here; if the file itself can't
1581 # be written we'll worry about it then.
1582 wfSuppressWarnings();
1583
1584 $archive = $dir.'/'.$subdir;
1585 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1586 $archive .= '/' . $hash{0};
1587 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1588 $archive .= '/' . substr( $hash, 0, 2 );
1589 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1590
1591 wfRestoreWarnings();
1592 umask( $oldumask );
1593 return $archive;
1594 }
1595
1596
1597 /*
1598 * Return the hash path component of an image path (URL or filesystem),
1599 * e.g. "/3/3c/", or just "/" if hashing is not used.
1600 *
1601 * @param $dbkey The filesystem / database name of the file
1602 * @param $fromSharedDirectory Use the shared file repository? It may
1603 * use different hash settings from the local one.
1604 */
1605 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1606 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
1607 global $wgHashedUploadDirectory;
1608
1609 if( Image::isHashed( $fromSharedDirectory ) ) {
1610 $hash = md5($dbkey);
1611 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1612 } else {
1613 return '/';
1614 }
1615 }
1616
1617 /**
1618 * Returns the image URL of an image's old version
1619 *
1620 * @param string $fname file name of the image file
1621 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1622 * @access public
1623 */
1624 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1625 global $wgUploadPath, $wgHashedUploadDirectory;
1626
1627 if ($wgHashedUploadDirectory) {
1628 $hash = md5( substr( $name, 15) );
1629 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1630 substr( $hash, 0, 2 ) . '/'.$name;
1631 } else {
1632 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1633 }
1634 return wfUrlencode($url);
1635 }
1636
1637 /**
1638 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1639 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1640 *
1641 * @param string $length
1642 * @return int Length in pixels
1643 */
1644 function wfScaleSVGUnit( $length ) {
1645 static $unitLength = array(
1646 'px' => 1.0,
1647 'pt' => 1.25,
1648 'pc' => 15.0,
1649 'mm' => 3.543307,
1650 'cm' => 35.43307,
1651 'in' => 90.0,
1652 '' => 1.0, // "User units" pixels by default
1653 '%' => 2.0, // Fake it!
1654 );
1655 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1656 $length = floatval( $matches[1] );
1657 $unit = $matches[2];
1658 return round( $length * $unitLength[$unit] );
1659 } else {
1660 // Assume pixels
1661 return round( floatval( $length ) );
1662 }
1663 }
1664
1665 /**
1666 * Compatible with PHP getimagesize()
1667 * @todo support gzipped SVGZ
1668 * @todo check XML more carefully
1669 * @todo sensible defaults
1670 *
1671 * @param string $filename
1672 * @return array
1673 */
1674 function wfGetSVGsize( $filename ) {
1675 $width = 256;
1676 $height = 256;
1677
1678 // Read a chunk of the file
1679 $f = fopen( $filename, "rt" );
1680 if( !$f ) return false;
1681 $chunk = fread( $f, 4096 );
1682 fclose( $f );
1683
1684 // Uber-crappy hack! Run through a real XML parser.
1685 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1686 return false;
1687 }
1688 $tag = $matches[1];
1689 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1690 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1691 }
1692 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1693 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1694 }
1695
1696 return array( $width, $height, 'SVG',
1697 "width=\"$width\" height=\"$height\"" );
1698 }
1699
1700 /**
1701 * Determine if an image exists on the 'bad image list'
1702 *
1703 * @param string $name The image to check
1704 * @return bool
1705 */
1706 function wfIsBadImage( $name ) {
1707 global $wgContLang;
1708 static $titleList = false;
1709 if ( $titleList === false ) {
1710 $titleList = array();
1711
1712 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1713 foreach ( $lines as $line ) {
1714 if ( preg_match( '/^\*\s*\[{2}:(' . $wgContLang->getNsText( NS_IMAGE ) . ':.*?)\]{2}/', $line, $m ) ) {
1715 $t = Title::newFromText( $m[1] );
1716 $titleList[$t->getDBkey()] = 1;
1717 }
1718 }
1719 }
1720
1721 return array_key_exists( $name, $titleList );
1722 }
1723
1724
1725
1726 /**
1727 * Wrapper class for thumbnail images
1728 * @package MediaWiki
1729 */
1730 class ThumbnailImage {
1731 /**
1732 * @param string $path Filesystem path to the thumb
1733 * @param string $url URL path to the thumb
1734 * @access private
1735 */
1736 function ThumbnailImage( $url, $width, $height, $path = false ) {
1737 $this->url = $url;
1738 $this->width = $width;
1739 $this->height = $height;
1740 $this->path = $path;
1741 }
1742
1743 /**
1744 * @return string The thumbnail URL
1745 */
1746 function getUrl() {
1747 return $this->url;
1748 }
1749
1750 /**
1751 * Return HTML <img ... /> tag for the thumbnail, will include
1752 * width and height attributes and a blank alt text (as required).
1753 *
1754 * You can set or override additional attributes by passing an
1755 * associative array of name => data pairs. The data will be escaped
1756 * for HTML output, so should be in plaintext.
1757 *
1758 * @param array $attribs
1759 * @return string
1760 * @access public
1761 */
1762 function toHtml( $attribs = array() ) {
1763 $attribs['src'] = $this->url;
1764 $attribs['width'] = $this->width;
1765 $attribs['height'] = $this->height;
1766 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1767
1768 $html = '<img ';
1769 foreach( $attribs as $name => $data ) {
1770 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
1771 }
1772 $html .= '/>';
1773 return $html;
1774 }
1775
1776 }
1777 ?>