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