static function
[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 /**
16 * Bump this number when serialized cache records may be incompatible.
17 */
18 define( 'MW_IMAGE_VERSION', 1 );
19
20 /**
21 * Class to represent an image
22 *
23 * Provides methods to retrieve paths (physical, logical, URL),
24 * to generate thumbnails or for uploading.
25 * @package MediaWiki
26 */
27 class Image
28 {
29 /**#@+
30 * @private
31 */
32 var $name, # name of the image (constructor)
33 $imagePath, # Path of the image (loadFromXxx)
34 $url, # Image URL (accessor)
35 $title, # Title object for this image (constructor)
36 $fileExists, # does the image file exist on disk? (loadFromXxx)
37 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory (loadFromXxx)
38 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
39 $historyRes, # result of the query for the image's history (nextHistoryLine)
40 $width, # \
41 $height, # |
42 $bits, # --- returned by getimagesize (loadFromXxx)
43 $attr, # /
44 $type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
45 $mime, # MIME type, determined by MimeMagic::guessMimeType
46 $size, # Size in bytes (loadFromXxx)
47 $metadata, # Metadata
48 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
49 $lastError; # Error string associated with a thumbnail display error
50
51
52 /**#@-*/
53
54 /**
55 * Create an Image object from an image name
56 *
57 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
58 * @public
59 */
60 function newFromName( $name ) {
61 $title = Title::makeTitleSafe( NS_IMAGE, $name );
62 if ( is_object( $title ) ) {
63 return new Image( $title );
64 } else {
65 return NULL;
66 }
67 }
68
69 /**
70 * Obsolete factory function, use constructor
71 * @deprecated
72 */
73 function newFromTitle( $title ) {
74 return new Image( $title );
75 }
76
77 function Image( $title ) {
78 if( !is_object( $title ) ) {
79 throw new MWException( 'Image constructor given bogus title.' );
80 }
81 $this->title =& $title;
82 $this->name = $title->getDBkey();
83 $this->metadata = serialize ( array() ) ;
84
85 $n = strrpos( $this->name, '.' );
86 $this->extension = Image::normalizeExtension( $n ?
87 substr( $this->name, $n + 1 ) : '' );
88 $this->historyLine = 0;
89
90 $this->dataLoaded = false;
91 }
92
93
94 /**
95 * Normalize a file extension to the common form, and ensure it's clean.
96 * Extensions with non-alphanumeric characters will be discarded.
97 *
98 * @param $ext string (without the .)
99 * @return string
100 */
101 static function normalizeExtension( $ext ) {
102 $lower = strtolower( $ext );
103 $squish = array(
104 'htm' => 'html',
105 'jpeg' => 'jpg',
106 'mpeg' => 'mpg',
107 'tiff' => 'tif' );
108 if( isset( $squish[$lower] ) ) {
109 return $squish[$lower];
110 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
111 return $lower;
112 } else {
113 return '';
114 }
115 }
116
117 /**
118 * Get the memcached keys
119 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
120 */
121 function getCacheKeys( ) {
122 global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
123
124 $hashedName = md5($this->name);
125 $keys = array( "$wgDBname:Image:$hashedName" );
126 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
127 $keys[] = "$wgSharedUploadDBname:Image:$hashedName";
128 }
129 return $keys;
130 }
131
132 /**
133 * Try to load image metadata from memcached. Returns true on success.
134 */
135 function loadFromCache() {
136 global $wgUseSharedUploads, $wgMemc;
137 wfProfileIn( __METHOD__ );
138 $this->dataLoaded = false;
139 $keys = $this->getCacheKeys();
140 $cachedValues = $wgMemc->get( $keys[0] );
141
142 // Check if the key existed and belongs to this version of MediaWiki
143 if (!empty($cachedValues) && is_array($cachedValues)
144 && isset($cachedValues['version']) && ( $cachedValues['version'] == MW_IMAGE_VERSION )
145 && $cachedValues['fileExists'] && isset( $cachedValues['mime'] ) && isset( $cachedValues['metadata'] ) )
146 {
147 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
148 # if this is shared file, we need to check if image
149 # in shared repository has not changed
150 if ( isset( $keys[1] ) ) {
151 $commonsCachedValues = $wgMemc->get( $keys[1] );
152 if (!empty($commonsCachedValues) && is_array($commonsCachedValues)
153 && isset($commonsCachedValues['version'])
154 && ( $commonsCachedValues['version'] == MW_IMAGE_VERSION )
155 && isset($commonsCachedValues['mime'])) {
156 wfDebug( "Pulling image metadata from shared repository cache\n" );
157 $this->name = $commonsCachedValues['name'];
158 $this->imagePath = $commonsCachedValues['imagePath'];
159 $this->fileExists = $commonsCachedValues['fileExists'];
160 $this->width = $commonsCachedValues['width'];
161 $this->height = $commonsCachedValues['height'];
162 $this->bits = $commonsCachedValues['bits'];
163 $this->type = $commonsCachedValues['type'];
164 $this->mime = $commonsCachedValues['mime'];
165 $this->metadata = $commonsCachedValues['metadata'];
166 $this->size = $commonsCachedValues['size'];
167 $this->fromSharedDirectory = true;
168 $this->dataLoaded = true;
169 $this->imagePath = $this->getFullPath(true);
170 }
171 }
172 } else {
173 wfDebug( "Pulling image metadata from local cache\n" );
174 $this->name = $cachedValues['name'];
175 $this->imagePath = $cachedValues['imagePath'];
176 $this->fileExists = $cachedValues['fileExists'];
177 $this->width = $cachedValues['width'];
178 $this->height = $cachedValues['height'];
179 $this->bits = $cachedValues['bits'];
180 $this->type = $cachedValues['type'];
181 $this->mime = $cachedValues['mime'];
182 $this->metadata = $cachedValues['metadata'];
183 $this->size = $cachedValues['size'];
184 $this->fromSharedDirectory = false;
185 $this->dataLoaded = true;
186 $this->imagePath = $this->getFullPath();
187 }
188 }
189 if ( $this->dataLoaded ) {
190 wfIncrStats( 'image_cache_hit' );
191 } else {
192 wfIncrStats( 'image_cache_miss' );
193 }
194
195 wfProfileOut( __METHOD__ );
196 return $this->dataLoaded;
197 }
198
199 /**
200 * Save the image metadata to memcached
201 */
202 function saveToCache() {
203 global $wgMemc;
204 $this->load();
205 $keys = $this->getCacheKeys();
206 if ( $this->fileExists ) {
207 // We can't cache negative metadata for non-existent files,
208 // because if the file later appears in commons, the local
209 // keys won't be purged.
210 $cachedValues = array(
211 'version' => MW_IMAGE_VERSION,
212 'name' => $this->name,
213 'imagePath' => $this->imagePath,
214 'fileExists' => $this->fileExists,
215 'fromShared' => $this->fromSharedDirectory,
216 'width' => $this->width,
217 'height' => $this->height,
218 'bits' => $this->bits,
219 'type' => $this->type,
220 'mime' => $this->mime,
221 'metadata' => $this->metadata,
222 'size' => $this->size );
223
224 $wgMemc->set( $keys[0], $cachedValues, 60 * 60 * 24 * 7 ); // A week
225 } else {
226 // However we should clear them, so they aren't leftover
227 // if we've deleted the file.
228 $wgMemc->delete( $keys[0] );
229 }
230 }
231
232 /**
233 * Load metadata from the file itself
234 */
235 function loadFromFile() {
236 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgContLang, $wgShowEXIF;
237 wfProfileIn( __METHOD__ );
238 $this->imagePath = $this->getFullPath();
239 $this->fileExists = file_exists( $this->imagePath );
240 $this->fromSharedDirectory = false;
241 $gis = array();
242
243 if (!$this->fileExists) wfDebug(__METHOD__.': '.$this->imagePath." not found locally!\n");
244
245 # If the file is not found, and a shared upload directory is used, look for it there.
246 if (!$this->fileExists && $wgUseSharedUploads && $wgSharedUploadDirectory) {
247 # In case we're on a wgCapitalLinks=false wiki, we
248 # capitalize the first letter of the filename before
249 # looking it up in the shared repository.
250 $sharedImage = Image::newFromName( $wgContLang->ucfirst($this->name) );
251 $this->fileExists = $sharedImage && file_exists( $sharedImage->getFullPath(true) );
252 if ( $this->fileExists ) {
253 $this->name = $sharedImage->name;
254 $this->imagePath = $this->getFullPath(true);
255 $this->fromSharedDirectory = true;
256 }
257 }
258
259
260 if ( $this->fileExists ) {
261 $magic=& wfGetMimeMagic();
262
263 $this->mime = $magic->guessMimeType($this->imagePath,true);
264 $this->type = $magic->getMediaType($this->imagePath,$this->mime);
265
266 # Get size in bytes
267 $this->size = filesize( $this->imagePath );
268
269 $magic=& wfGetMimeMagic();
270
271 # Height and width
272 wfSuppressWarnings();
273 if( $this->mime == 'image/svg' ) {
274 $gis = wfGetSVGsize( $this->imagePath );
275 } elseif( $this->mime == 'image/vnd.djvu' ) {
276 $deja = new DjVuImage( $this->imagePath );
277 $gis = $deja->getImageSize();
278 } elseif ( !$magic->isPHPImageType( $this->mime ) ) {
279 # Don't try to get the width and height of sound and video files, that's bad for performance
280 $gis = false;
281 } else {
282 $gis = getimagesize( $this->imagePath );
283 }
284 wfRestoreWarnings();
285
286 wfDebug(__METHOD__.': '.$this->imagePath." loaded, ".$this->size." bytes, ".$this->mime.".\n");
287 }
288 else {
289 $this->mime = NULL;
290 $this->type = MEDIATYPE_UNKNOWN;
291 wfDebug(__METHOD__.': '.$this->imagePath." NOT FOUND!\n");
292 }
293
294 if( $gis ) {
295 $this->width = $gis[0];
296 $this->height = $gis[1];
297 } else {
298 $this->width = 0;
299 $this->height = 0;
300 }
301
302 #NOTE: $gis[2] contains a code for the image type. This is no longer used.
303
304 #NOTE: we have to set this flag early to avoid load() to be called
305 # be some of the functions below. This may lead to recursion or other bad things!
306 # as ther's only one thread of execution, this should be safe anyway.
307 $this->dataLoaded = true;
308
309
310 $this->metadata = serialize( $this->retrieveExifData( $this->imagePath ) );
311
312 if ( isset( $gis['bits'] ) ) $this->bits = $gis['bits'];
313 else $this->bits = 0;
314
315 wfProfileOut( __METHOD__ );
316 }
317
318 /**
319 * Load image metadata from the DB
320 */
321 function loadFromDB() {
322 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgSharedUploadDBprefix, $wgContLang;
323 wfProfileIn( __METHOD__ );
324
325 $dbr =& wfGetDB( DB_SLAVE );
326
327 $this->checkDBSchema($dbr);
328
329 $row = $dbr->selectRow( 'image',
330 array( 'img_size', 'img_width', 'img_height', 'img_bits',
331 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
332 array( 'img_name' => $this->name ), __METHOD__ );
333 if ( $row ) {
334 $this->fromSharedDirectory = false;
335 $this->fileExists = true;
336 $this->loadFromRow( $row );
337 $this->imagePath = $this->getFullPath();
338 // Check for rows from a previous schema, quietly upgrade them
339 if ( is_null($this->type) ) {
340 $this->upgradeRow();
341 }
342 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
343 # In case we're on a wgCapitalLinks=false wiki, we
344 # capitalize the first letter of the filename before
345 # looking it up in the shared repository.
346 $name = $wgContLang->ucfirst($this->name);
347 $dbc =& wfGetDB( DB_SLAVE, 'commons' );
348
349 $row = $dbc->selectRow( "`$wgSharedUploadDBname`.{$wgSharedUploadDBprefix}image",
350 array(
351 'img_size', 'img_width', 'img_height', 'img_bits',
352 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
353 array( 'img_name' => $name ), __METHOD__ );
354 if ( $row ) {
355 $this->fromSharedDirectory = true;
356 $this->fileExists = true;
357 $this->imagePath = $this->getFullPath(true);
358 $this->name = $name;
359 $this->loadFromRow( $row );
360
361 // Check for rows from a previous schema, quietly upgrade them
362 if ( is_null($this->type) ) {
363 $this->upgradeRow();
364 }
365 }
366 }
367
368 if ( !$row ) {
369 $this->size = 0;
370 $this->width = 0;
371 $this->height = 0;
372 $this->bits = 0;
373 $this->type = 0;
374 $this->fileExists = false;
375 $this->fromSharedDirectory = false;
376 $this->metadata = serialize ( array() ) ;
377 }
378
379 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
380 $this->dataLoaded = true;
381 wfProfileOut( __METHOD__ );
382 }
383
384 /*
385 * Load image metadata from a DB result row
386 */
387 function loadFromRow( &$row ) {
388 $this->size = $row->img_size;
389 $this->width = $row->img_width;
390 $this->height = $row->img_height;
391 $this->bits = $row->img_bits;
392 $this->type = $row->img_media_type;
393
394 $major= $row->img_major_mime;
395 $minor= $row->img_minor_mime;
396
397 if (!$major) $this->mime = "unknown/unknown";
398 else {
399 if (!$minor) $minor= "unknown";
400 $this->mime = $major.'/'.$minor;
401 }
402
403 $this->metadata = $row->img_metadata;
404 if ( $this->metadata == "" ) $this->metadata = serialize ( array() ) ;
405
406 $this->dataLoaded = true;
407 }
408
409 /**
410 * Load image metadata from cache or DB, unless already loaded
411 */
412 function load() {
413 global $wgSharedUploadDBname, $wgUseSharedUploads;
414 if ( !$this->dataLoaded ) {
415 if ( !$this->loadFromCache() ) {
416 $this->loadFromDB();
417 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
418 $this->loadFromFile();
419 } elseif ( $this->fileExists ) {
420 $this->saveToCache();
421 }
422 }
423 $this->dataLoaded = true;
424 }
425 }
426
427 /**
428 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
429 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
430 */
431 function upgradeRow() {
432 global $wgDBname, $wgSharedUploadDBname;
433 wfProfileIn( __METHOD__ );
434
435 $this->loadFromFile();
436
437 if ( $this->fromSharedDirectory ) {
438 if ( !$wgSharedUploadDBname ) {
439 wfProfileOut( __METHOD__ );
440 return;
441 }
442
443 // Write to the other DB using selectDB, not database selectors
444 // This avoids breaking replication in MySQL
445 $dbw =& wfGetDB( DB_MASTER, 'commons' );
446 $dbw->selectDB( $wgSharedUploadDBname );
447 } else {
448 $dbw =& wfGetDB( DB_MASTER );
449 }
450
451 $this->checkDBSchema($dbw);
452
453 list( $major, $minor ) = self::splitMime( $this->mime );
454
455 wfDebug(__METHOD__.': upgrading '.$this->name." to 1.5 schema\n");
456
457 $dbw->update( 'image',
458 array(
459 'img_width' => $this->width,
460 'img_height' => $this->height,
461 'img_bits' => $this->bits,
462 'img_media_type' => $this->type,
463 'img_major_mime' => $major,
464 'img_minor_mime' => $minor,
465 'img_metadata' => $this->metadata,
466 ), array( 'img_name' => $this->name ), __METHOD__
467 );
468 if ( $this->fromSharedDirectory ) {
469 $dbw->selectDB( $wgDBname );
470 }
471 wfProfileOut( __METHOD__ );
472 }
473
474 /**
475 * Split an internet media type into its two components; if not
476 * a two-part name, set the minor type to 'unknown'.
477 *
478 * @param $mime "text/html" etc
479 * @return array ("text", "html") etc
480 */
481 static function splitMime( $mime ) {
482 if( strpos( $mime, '/' ) !== false ) {
483 return explode( '/', $mime, 2 );
484 } else {
485 return array( $mime, 'unknown' );
486 }
487 }
488
489 /**
490 * Return the name of this image
491 * @public
492 */
493 function getName() {
494 return $this->name;
495 }
496
497 /**
498 * Return the associated title object
499 * @public
500 */
501 function getTitle() {
502 return $this->title;
503 }
504
505 /**
506 * Return the URL of the image file
507 * @public
508 */
509 function getURL() {
510 if ( !$this->url ) {
511 $this->load();
512 if($this->fileExists) {
513 $this->url = Image::imageUrl( $this->name, $this->fromSharedDirectory );
514 } else {
515 $this->url = '';
516 }
517 }
518 return $this->url;
519 }
520
521 function getViewURL() {
522 if( $this->mustRender()) {
523 if( $this->canRender() ) {
524 return $this->createThumb( $this->getWidth() );
525 }
526 else {
527 wfDebug('Image::getViewURL(): supposed to render '.$this->name.' ('.$this->mime."), but can't!\n");
528 return $this->getURL(); #hm... return NULL?
529 }
530 } else {
531 return $this->getURL();
532 }
533 }
534
535 /**
536 * Return the image path of the image in the
537 * local file system as an absolute path
538 * @public
539 */
540 function getImagePath() {
541 $this->load();
542 return $this->imagePath;
543 }
544
545 /**
546 * Return the width of the image
547 *
548 * Returns -1 if the file specified is not a known image type
549 * @public
550 */
551 function getWidth() {
552 $this->load();
553 return $this->width;
554 }
555
556 /**
557 * Return the height of the image
558 *
559 * Returns -1 if the file specified is not a known image type
560 * @public
561 */
562 function getHeight() {
563 $this->load();
564 return $this->height;
565 }
566
567 /**
568 * Return the size of the image file, in bytes
569 * @public
570 */
571 function getSize() {
572 $this->load();
573 return $this->size;
574 }
575
576 /**
577 * Returns the mime type of the file.
578 */
579 function getMimeType() {
580 $this->load();
581 return $this->mime;
582 }
583
584 /**
585 * Return the type of the media in the file.
586 * Use the value returned by this function with the MEDIATYPE_xxx constants.
587 */
588 function getMediaType() {
589 $this->load();
590 return $this->type;
591 }
592
593 /**
594 * Checks if the file can be presented to the browser as a bitmap.
595 *
596 * Currently, this checks if the file is an image format
597 * that can be converted to a format
598 * supported by all browsers (namely GIF, PNG and JPEG),
599 * or if it is an SVG image and SVG conversion is enabled.
600 *
601 * @todo remember the result of this check.
602 */
603 function canRender() {
604 global $wgUseImageMagick;
605
606 if( $this->getWidth()<=0 || $this->getHeight()<=0 ) return false;
607
608 $mime= $this->getMimeType();
609
610 if (!$mime || $mime==='unknown' || $mime==='unknown/unknown') return false;
611
612 #if it's SVG, check if there's a converter enabled
613 if ($mime === 'image/svg') {
614 global $wgSVGConverters, $wgSVGConverter;
615
616 if ($wgSVGConverter && isset( $wgSVGConverters[$wgSVGConverter])) {
617 wfDebug( "Image::canRender: SVG is ready!\n" );
618 return true;
619 } else {
620 wfDebug( "Image::canRender: SVG renderer missing\n" );
621 }
622 }
623
624 #image formats available on ALL browsers
625 if ( $mime === 'image/gif'
626 || $mime === 'image/png'
627 || $mime === 'image/jpeg' ) return true;
628
629 #image formats that can be converted to the above formats
630 if ($wgUseImageMagick) {
631 #convertable by ImageMagick (there are more...)
632 if ( $mime === 'image/vnd.wap.wbmp'
633 || $mime === 'image/x-xbitmap'
634 || $mime === 'image/x-xpixmap'
635 #|| $mime === 'image/x-icon' #file may be split into multiple parts
636 || $mime === 'image/x-portable-anymap'
637 || $mime === 'image/x-portable-bitmap'
638 || $mime === 'image/x-portable-graymap'
639 || $mime === 'image/x-portable-pixmap'
640 #|| $mime === 'image/x-photoshop' #this takes a lot of CPU and RAM!
641 || $mime === 'image/x-rgb'
642 || $mime === 'image/x-bmp'
643 || $mime === 'image/tiff' ) return true;
644 }
645 else {
646 #convertable by the PHP GD image lib
647 if ( $mime === 'image/vnd.wap.wbmp'
648 || $mime === 'image/x-xbitmap' ) return true;
649 }
650
651 return false;
652 }
653
654
655 /**
656 * Return true if the file is of a type that can't be directly
657 * rendered by typical browsers and needs to be re-rasterized.
658 *
659 * This returns true for everything but the bitmap types
660 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
661 * also return true for any non-image formats.
662 *
663 * @return bool
664 */
665 function mustRender() {
666 $mime= $this->getMimeType();
667
668 if ( $mime === "image/gif"
669 || $mime === "image/png"
670 || $mime === "image/jpeg" ) return false;
671
672 return true;
673 }
674
675 /**
676 * Determines if this media file may be shown inline on a page.
677 *
678 * This is currently synonymous to canRender(), but this could be
679 * extended to also allow inline display of other media,
680 * like flash animations or videos. If you do so, please keep in mind that
681 * that could be a security risk.
682 */
683 function allowInlineDisplay() {
684 return $this->canRender();
685 }
686
687 /**
688 * Determines if this media file is in a format that is unlikely to
689 * contain viruses or malicious content. It uses the global
690 * $wgTrustedMediaFormats list to determine if the file is safe.
691 *
692 * This is used to show a warning on the description page of non-safe files.
693 * It may also be used to disallow direct [[media:...]] links to such files.
694 *
695 * Note that this function will always return true if allowInlineDisplay()
696 * or isTrustedFile() is true for this file.
697 */
698 function isSafeFile() {
699 if ($this->allowInlineDisplay()) return true;
700 if ($this->isTrustedFile()) return true;
701
702 global $wgTrustedMediaFormats;
703
704 $type= $this->getMediaType();
705 $mime= $this->getMimeType();
706 #wfDebug("Image::isSafeFile: type= $type, mime= $mime\n");
707
708 if (!$type || $type===MEDIATYPE_UNKNOWN) return false; #unknown type, not trusted
709 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
710
711 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
712 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
713
714 return false;
715 }
716
717 /** Returns true if the file is flagged as trusted. Files flagged that way
718 * can be linked to directly, even if that is not allowed for this type of
719 * file normally.
720 *
721 * This is a dummy function right now and always returns false. It could be
722 * implemented to extract a flag from the database. The trusted flag could be
723 * set on upload, if the user has sufficient privileges, to bypass script-
724 * and html-filters. It may even be coupled with cryptographics signatures
725 * or such.
726 */
727 function isTrustedFile() {
728 #this could be implemented to check a flag in the databas,
729 #look for signatures, etc
730 return false;
731 }
732
733 /**
734 * Return the escapeLocalURL of this image
735 * @public
736 */
737 function getEscapeLocalURL() {
738 $this->getTitle();
739 return $this->title->escapeLocalURL();
740 }
741
742 /**
743 * Return the escapeFullURL of this image
744 * @public
745 */
746 function getEscapeFullURL() {
747 $this->getTitle();
748 return $this->title->escapeFullURL();
749 }
750
751 /**
752 * Return the URL of an image, provided its name.
753 *
754 * @param string $name Name of the image, without the leading "Image:"
755 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
756 * @return string URL of $name image
757 * @public
758 * @static
759 */
760 function imageUrl( $name, $fromSharedDirectory = false ) {
761 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
762 if($fromSharedDirectory) {
763 $base = '';
764 $path = $wgSharedUploadPath;
765 } else {
766 $base = $wgUploadBaseUrl;
767 $path = $wgUploadPath;
768 }
769 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
770 return wfUrlencode( $url );
771 }
772
773 /**
774 * Returns true if the image file exists on disk.
775 * @return boolean Whether image file exist on disk.
776 * @public
777 */
778 function exists() {
779 $this->load();
780 return $this->fileExists;
781 }
782
783 /**
784 * @todo document
785 * @private
786 */
787 function thumbUrl( $width, $subdir='thumb') {
788 global $wgUploadPath, $wgUploadBaseUrl, $wgSharedUploadPath;
789 global $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
790
791 // Generate thumb.php URL if possible
792 $script = false;
793 $url = false;
794
795 if ( $this->fromSharedDirectory ) {
796 if ( $wgSharedThumbnailScriptPath ) {
797 $script = $wgSharedThumbnailScriptPath;
798 }
799 } else {
800 if ( $wgThumbnailScriptPath ) {
801 $script = $wgThumbnailScriptPath;
802 }
803 }
804 if ( $script ) {
805 $url = $script . '?f=' . urlencode( $this->name ) . '&w=' . urlencode( $width );
806 if( $this->mustRender() ) {
807 $url.= '&r=1';
808 }
809 } else {
810 $name = $this->thumbName( $width );
811 if($this->fromSharedDirectory) {
812 $base = '';
813 $path = $wgSharedUploadPath;
814 } else {
815 $base = $wgUploadBaseUrl;
816 $path = $wgUploadPath;
817 }
818 if ( Image::isHashed( $this->fromSharedDirectory ) ) {
819 $url = "{$base}{$path}/{$subdir}" .
820 wfGetHashPath($this->name, $this->fromSharedDirectory)
821 . $this->name.'/'.$name;
822 $url = wfUrlencode( $url );
823 } else {
824 $url = "{$base}{$path}/{$subdir}/{$name}";
825 }
826 }
827 return array( $script !== false, $url );
828 }
829
830 /**
831 * Return the file name of a thumbnail of the specified width
832 *
833 * @param integer $width Width of the thumbnail image
834 * @param boolean $shared Does the thumbnail come from the shared repository?
835 * @private
836 */
837 function thumbName( $width ) {
838 $thumb = $width."px-".$this->name;
839
840 if( $this->mustRender() ) {
841 if( $this->canRender() ) {
842 # Rasterize to PNG (for SVG vector images, etc)
843 $thumb .= '.png';
844 }
845 else {
846 #should we use iconThumb here to get a symbolic thumbnail?
847 #or should we fail with an internal error?
848 return NULL; //can't make bitmap
849 }
850 }
851 return $thumb;
852 }
853
854 /**
855 * Create a thumbnail of the image having the specified width/height.
856 * The thumbnail will not be created if the width is larger than the
857 * image's width. Let the browser do the scaling in this case.
858 * The thumbnail is stored on disk and is only computed if the thumbnail
859 * file does not exist OR if it is older than the image.
860 * Returns the URL.
861 *
862 * Keeps aspect ratio of original image. If both width and height are
863 * specified, the generated image will be no bigger than width x height,
864 * and will also have correct aspect ratio.
865 *
866 * @param integer $width maximum width of the generated thumbnail
867 * @param integer $height maximum height of the image (optional)
868 * @public
869 */
870 function createThumb( $width, $height=-1 ) {
871 $thumb = $this->getThumbnail( $width, $height );
872 if( is_null( $thumb ) ) return '';
873 return $thumb->getUrl();
874 }
875
876 /**
877 * As createThumb, but returns a ThumbnailImage object. This can
878 * provide access to the actual file, the real size of the thumb,
879 * and can produce a convenient <img> tag for you.
880 *
881 * For non-image formats, this may return a filetype-specific icon.
882 *
883 * @param integer $width maximum width of the generated thumbnail
884 * @param integer $height maximum height of the image (optional)
885 * @param boolean $render True to render the thumbnail if it doesn't exist,
886 * false to just return the URL
887 *
888 * @return ThumbnailImage or null on failure
889 * @public
890 */
891 function getThumbnail( $width, $height=-1, $render = true ) {
892 wfProfileIn( __METHOD__ );
893 if ($this->canRender()) {
894 if ( $height > 0 ) {
895 $this->load();
896 if ( $width > $this->width * $height / $this->height ) {
897 $width = wfFitBoxWidth( $this->width, $this->height, $height );
898 }
899 }
900 if ( $render ) {
901 $thumb = $this->renderThumb( $width );
902 } else {
903 // Don't render, just return the URL
904 if ( $this->validateThumbParams( $width, $height ) ) {
905 if ( !$this->mustRender() && $width == $this->width && $height == $this->height ) {
906 $url = $this->getURL();
907 } else {
908 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
909 }
910 $thumb = new ThumbnailImage( $url, $width, $height );
911 } else {
912 $thumb = null;
913 }
914 }
915 } else {
916 // not a bitmap or renderable image, don't try.
917 $thumb = $this->iconThumb();
918 }
919 wfProfileOut( __METHOD__ );
920 return $thumb;
921 }
922
923 /**
924 * @return ThumbnailImage
925 */
926 function iconThumb() {
927 global $wgStylePath, $wgStyleDirectory;
928
929 $try = array( 'fileicon-' . $this->extension . '.png', 'fileicon.png' );
930 foreach( $try as $icon ) {
931 $path = '/common/images/icons/' . $icon;
932 $filepath = $wgStyleDirectory . $path;
933 if( file_exists( $filepath ) ) {
934 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
935 }
936 }
937 return null;
938 }
939
940 /**
941 * Validate thumbnail parameters and fill in the correct height
942 *
943 * @param integer &$width Specified width (input/output)
944 * @param integer &$height Height (output only)
945 * @return false to indicate that an error should be returned to the user.
946 */
947 function validateThumbParams( &$width, &$height ) {
948 global $wgSVGMaxSize, $wgMaxImageArea;
949
950 $this->load();
951
952 if ( ! $this->exists() )
953 {
954 # If there is no image, there will be no thumbnail
955 return false;
956 }
957
958 $width = intval( $width );
959
960 # Sanity check $width
961 if( $width <= 0 || $this->width <= 0) {
962 # BZZZT
963 return false;
964 }
965
966 # Don't thumbnail an image so big that it will fill hard drives and send servers into swap
967 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
968 # an exception for it.
969 if ( $this->getMediaType() == MEDIATYPE_BITMAP &&
970 $this->getMimeType() !== 'image/jpeg' &&
971 $this->width * $this->height > $wgMaxImageArea )
972 {
973 return false;
974 }
975
976 # Don't make an image bigger than the source, or wgMaxSVGSize for SVGs
977 if ( $this->mustRender() ) {
978 $width = min( $width, $wgSVGMaxSize );
979 } elseif ( $width > $this->width - 1 ) {
980 $width = $this->width;
981 $height = $this->height;
982 return true;
983 }
984
985 $height = round( $this->height * $width / $this->width );
986 return true;
987 }
988
989 /**
990 * Create a thumbnail of the image having the specified width.
991 * The thumbnail will not be created if the width is larger than the
992 * image's width. Let the browser do the scaling in this case.
993 * The thumbnail is stored on disk and is only computed if the thumbnail
994 * file does not exist OR if it is older than the image.
995 * Returns an object which can return the pathname, URL, and physical
996 * pixel size of the thumbnail -- or null on failure.
997 *
998 * @return ThumbnailImage or null on failure
999 * @private
1000 */
1001 function renderThumb( $width, $useScript = true ) {
1002 global $wgUseSquid, $wgThumbnailEpoch;
1003
1004 wfProfileIn( __METHOD__ );
1005
1006 $this->load();
1007 $height = -1;
1008 if ( !$this->validateThumbParams( $width, $height ) ) {
1009 # Validation error
1010 wfProfileOut( __METHOD__ );
1011 return null;
1012 }
1013
1014 if ( !$this->mustRender() && $width == $this->width && $height == $this->height ) {
1015 # validateThumbParams (or the user) wants us to return the unscaled image
1016 $thumb = new ThumbnailImage( $this->getURL(), $width, $height );
1017 wfProfileOut( __METHOD__ );
1018 return $thumb;
1019 }
1020
1021 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
1022 if ( $isScriptUrl && $useScript ) {
1023 // Use thumb.php to render the image
1024 $thumb = new ThumbnailImage( $url, $width, $height );
1025 wfProfileOut( __METHOD__ );
1026 return $thumb;
1027 }
1028
1029 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory );
1030 $thumbDir = wfImageThumbDir( $this->name, $this->fromSharedDirectory );
1031 $thumbPath = $thumbDir.'/'.$thumbName;
1032
1033 if ( is_dir( $thumbPath ) ) {
1034 // Directory where file should be
1035 // This happened occasionally due to broken migration code in 1.5
1036 // Rename to broken-*
1037 global $wgUploadDirectory;
1038 for ( $i = 0; $i < 100 ; $i++ ) {
1039 $broken = "$wgUploadDirectory/broken-$i-$thumbName";
1040 if ( !file_exists( $broken ) ) {
1041 rename( $thumbPath, $broken );
1042 break;
1043 }
1044 }
1045 // Code below will ask if it exists, and the answer is now no
1046 clearstatcache();
1047 }
1048
1049 $done = true;
1050 if ( !file_exists( $thumbPath ) ||
1051 filemtime( $thumbPath ) < wfTimestamp( TS_UNIX, $wgThumbnailEpoch ) )
1052 {
1053 // Create the directory if it doesn't exist
1054 if ( is_file( $thumbDir ) ) {
1055 // File where thumb directory should be, destroy if possible
1056 @unlink( $thumbDir );
1057 }
1058 wfMkdirParents( $thumbDir );
1059
1060 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory ).
1061 '/'.$thumbName;
1062 $done = false;
1063
1064 // Migration from old directory structure
1065 if ( is_file( $oldThumbPath ) ) {
1066 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath) ) {
1067 if ( file_exists( $thumbPath ) ) {
1068 if ( !is_dir( $thumbPath ) ) {
1069 // Old image in the way of rename
1070 unlink( $thumbPath );
1071 } else {
1072 // This should have been dealt with already
1073 throw new MWException( "Directory where image should be: $thumbPath" );
1074 }
1075 }
1076 // Rename the old image into the new location
1077 rename( $oldThumbPath, $thumbPath );
1078 $done = true;
1079 } else {
1080 unlink( $oldThumbPath );
1081 }
1082 }
1083 if ( !$done ) {
1084 $this->lastError = $this->reallyRenderThumb( $thumbPath, $width, $height );
1085 if ( $this->lastError === true ) {
1086 $done = true;
1087 } elseif( $GLOBALS['wgIgnoreImageErrors'] ) {
1088 // Log the error but output anyway.
1089 // With luck it's a transitory error...
1090 $done = true;
1091 }
1092
1093 # Purge squid
1094 # This has to be done after the image is updated and present for all machines on NFS,
1095 # or else the old version might be stored into the squid again
1096 if ( $wgUseSquid ) {
1097 $urlArr = array( $url );
1098 wfPurgeSquidServers($urlArr);
1099 }
1100 }
1101 }
1102
1103 if ( $done ) {
1104 $thumb = new ThumbnailImage( $url, $width, $height, $thumbPath );
1105 } else {
1106 $thumb = null;
1107 }
1108 wfProfileOut( __METHOD__ );
1109 return $thumb;
1110 } // END OF function renderThumb
1111
1112 /**
1113 * Really render a thumbnail
1114 * Call this only for images for which canRender() returns true.
1115 *
1116 * @param string $thumbPath Path to thumbnail
1117 * @param int $width Desired width in pixels
1118 * @param int $height Desired height in pixels
1119 * @return bool True on error, false or error string on failure.
1120 * @private
1121 */
1122 function reallyRenderThumb( $thumbPath, $width, $height ) {
1123 global $wgSVGConverters, $wgSVGConverter;
1124 global $wgUseImageMagick, $wgImageMagickConvertCommand;
1125 global $wgCustomConvertCommand;
1126
1127 $this->load();
1128
1129 $err = false;
1130 $cmd = "";
1131 $retval = 0;
1132
1133 if( $this->mime === "image/svg" ) {
1134 #Right now we have only SVG
1135
1136 global $wgSVGConverters, $wgSVGConverter;
1137 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
1138 global $wgSVGConverterPath;
1139 $cmd = str_replace(
1140 array( '$path/', '$width', '$height', '$input', '$output' ),
1141 array( $wgSVGConverterPath ? "$wgSVGConverterPath/" : "",
1142 intval( $width ),
1143 intval( $height ),
1144 wfEscapeShellArg( $this->imagePath ),
1145 wfEscapeShellArg( $thumbPath ) ),
1146 $wgSVGConverters[$wgSVGConverter] );
1147 wfProfileIn( 'rsvg' );
1148 wfDebug( "reallyRenderThumb SVG: $cmd\n" );
1149 $err = wfShellExec( $cmd, $retval );
1150 wfProfileOut( 'rsvg' );
1151 }
1152 } elseif ( $wgUseImageMagick ) {
1153 # use ImageMagick
1154
1155 if ( $this->mime == 'image/jpeg' ) {
1156 $quality = "-quality 80"; // 80%
1157 } elseif ( $this->mime == 'image/png' ) {
1158 $quality = "-quality 95"; // zlib 9, adaptive filtering
1159 } else {
1160 $quality = ''; // default
1161 }
1162
1163 # Specify white background color, will be used for transparent images
1164 # in Internet Explorer/Windows instead of default black.
1165
1166 # Note, we specify "-size {$width}" and NOT "-size {$width}x{$height}".
1167 # It seems that ImageMagick has a bug wherein it produces thumbnails of
1168 # the wrong size in the second case.
1169
1170 $cmd = wfEscapeShellArg($wgImageMagickConvertCommand) .
1171 " {$quality} -background white -size {$width} ".
1172 wfEscapeShellArg($this->imagePath) .
1173 // Coalesce is needed to scale animated GIFs properly (bug 1017).
1174 ' -coalesce ' .
1175 // For the -resize option a "!" is needed to force exact size,
1176 // or ImageMagick may decide your ratio is wrong and slice off
1177 // a pixel.
1178 " -resize " . wfEscapeShellArg( "{$width}x{$height}!" ) .
1179 " -depth 8 " .
1180 wfEscapeShellArg($thumbPath) . " 2>&1";
1181 wfDebug("reallyRenderThumb: running ImageMagick: $cmd\n");
1182 wfProfileIn( 'convert' );
1183 $err = wfShellExec( $cmd, $retval );
1184 wfProfileOut( 'convert' );
1185 } elseif( $wgCustomConvertCommand ) {
1186 # Use a custom convert command
1187 # Variables: %s %d %w %h
1188 $src = wfEscapeShellArg( $this->imagePath );
1189 $dst = wfEscapeShellArg( $thumbPath );
1190 $cmd = $wgCustomConvertCommand;
1191 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
1192 $cmd = str_replace( '%h', $height, str_replace( '%w', $width, $cmd ) ); # Size
1193 wfDebug( "reallyRenderThumb: Running custom convert command $cmd\n" );
1194 wfProfileIn( 'convert' );
1195 $err = wfShellExec( $cmd, $retval );
1196 wfProfileOut( 'convert' );
1197 } else {
1198 # Use PHP's builtin GD library functions.
1199 #
1200 # First find out what kind of file this is, and select the correct
1201 # input routine for this.
1202
1203 $typemap = array(
1204 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
1205 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( &$this, 'imageJpegWrapper' ) ),
1206 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
1207 'image/vnd.wap.wmbp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
1208 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
1209 );
1210 if( !isset( $typemap[$this->mime] ) ) {
1211 $err = 'Image type not supported';
1212 wfDebug( "$err\n" );
1213 return $err;
1214 }
1215 list( $loader, $colorStyle, $saveType ) = $typemap[$this->mime];
1216
1217 if( !function_exists( $loader ) ) {
1218 $err = "Incomplete GD library configuration: missing function $loader";
1219 wfDebug( "$err\n" );
1220 return $err;
1221 }
1222 if( $colorStyle == 'palette' ) {
1223 $truecolor = false;
1224 } elseif( $colorStyle == 'truecolor' ) {
1225 $truecolor = true;
1226 } elseif( $colorStyle == 'bits' ) {
1227 $truecolor = ( $this->bits > 8 );
1228 }
1229
1230 $src_image = call_user_func( $loader, $this->imagePath );
1231 if ( $truecolor ) {
1232 $dst_image = imagecreatetruecolor( $width, $height );
1233 } else {
1234 $dst_image = imagecreate( $width, $height );
1235 }
1236 imagecopyresampled( $dst_image, $src_image,
1237 0,0,0,0,
1238 $width, $height, $this->width, $this->height );
1239 call_user_func( $saveType, $dst_image, $thumbPath );
1240 imagedestroy( $dst_image );
1241 imagedestroy( $src_image );
1242 }
1243
1244 #
1245 # Check for zero-sized thumbnails. Those can be generated when
1246 # no disk space is available or some other error occurs
1247 #
1248 if( file_exists( $thumbPath ) ) {
1249 $thumbstat = stat( $thumbPath );
1250 if( $thumbstat['size'] == 0 || $retval != 0 ) {
1251 wfDebugLog( 'thumbnail',
1252 sprintf( 'Removing bad %d-byte thumbnail "%s"',
1253 $thumbstat['size'], $thumbPath ) );
1254 unlink( $thumbPath );
1255 }
1256 }
1257 if ( $retval != 0 ) {
1258 wfDebugLog( 'thumbnail',
1259 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
1260 wfHostname(), $retval, trim($err), $cmd ) );
1261 return wfMsg( 'thumbnail_error', $err );
1262 } else {
1263 return true;
1264 }
1265 }
1266
1267 function getLastError() {
1268 return $this->lastError;
1269 }
1270
1271 function imageJpegWrapper( $dst_image, $thumbPath ) {
1272 imageinterlace( $dst_image );
1273 imagejpeg( $dst_image, $thumbPath, 95 );
1274 }
1275
1276 /**
1277 * Get all thumbnail names previously generated for this image
1278 */
1279 function getThumbnails( $shared = false ) {
1280 if ( Image::isHashed( $shared ) ) {
1281 $this->load();
1282 $files = array();
1283 $dir = wfImageThumbDir( $this->name, $shared );
1284
1285 // This generates an error on failure, hence the @
1286 $handle = @opendir( $dir );
1287
1288 if ( $handle ) {
1289 while ( false !== ( $file = readdir($handle) ) ) {
1290 if ( $file{0} != '.' ) {
1291 $files[] = $file;
1292 }
1293 }
1294 closedir( $handle );
1295 }
1296 } else {
1297 $files = array();
1298 }
1299
1300 return $files;
1301 }
1302
1303 /**
1304 * Refresh metadata in memcached, but don't touch thumbnails or squid
1305 */
1306 function purgeMetadataCache() {
1307 clearstatcache();
1308 $this->loadFromFile();
1309 $this->saveToCache();
1310 }
1311
1312 /**
1313 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1314 */
1315 function purgeCache( $archiveFiles = array(), $shared = false ) {
1316 global $wgUseSquid;
1317
1318 // Refresh metadata cache
1319 $this->purgeMetadataCache();
1320
1321 // Delete thumbnails
1322 $files = $this->getThumbnails( $shared );
1323 $dir = wfImageThumbDir( $this->name, $shared );
1324 $urls = array();
1325 foreach ( $files as $file ) {
1326 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1327 $urls[] = $this->thumbUrl( $m[1], $this->fromSharedDirectory );
1328 @unlink( "$dir/$file" );
1329 }
1330 }
1331
1332 // Purge the squid
1333 if ( $wgUseSquid ) {
1334 $urls[] = $this->getViewURL();
1335 foreach ( $archiveFiles as $file ) {
1336 $urls[] = wfImageArchiveUrl( $file );
1337 }
1338 wfPurgeSquidServers( $urls );
1339 }
1340 }
1341
1342 /**
1343 * Purge the image description page, but don't go after
1344 * pages using the image. Use when modifying file history
1345 * but not the current data.
1346 */
1347 function purgeDescription() {
1348 $page = Title::makeTitle( NS_IMAGE, $this->name );
1349 $page->invalidateCache();
1350 $page->purgeSquid();
1351 }
1352
1353 /**
1354 * Purge metadata and all affected pages when the image is created,
1355 * deleted, or majorly updated. A set of additional URLs may be
1356 * passed to purge, such as specific image files which have changed.
1357 * @param $urlArray array
1358 */
1359 function purgeEverything( $urlArr=array() ) {
1360 // Delete thumbnails and refresh image metadata cache
1361 $this->purgeCache();
1362 $this->purgeDescription();
1363
1364 // Purge cache of all pages using this image
1365 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1366 $update->doUpdate();
1367 }
1368
1369 function checkDBSchema(&$db) {
1370 global $wgCheckDBSchema;
1371 if (!$wgCheckDBSchema) {
1372 return;
1373 }
1374 # img_name must be unique
1375 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1376 throw new MWException( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1377 }
1378
1379 # new fields must exist
1380 #
1381 # Not really, there's hundreds of checks like this that we could do and they're all pointless, because
1382 # if the fields are missing, the database will loudly report a query error, the first time you try to do
1383 # something. The only reason I put the above schema check in was because the absence of that particular
1384 # index would lead to an annoying subtle bug. No error message, just some very odd behaviour on duplicate
1385 # uploads. -- TS
1386 /*
1387 if ( !$db->fieldExists( 'image', 'img_media_type' )
1388 || !$db->fieldExists( 'image', 'img_metadata' )
1389 || !$db->fieldExists( 'image', 'img_width' ) ) {
1390
1391 throw new MWException( 'Database schema not up to date, please run maintenance/update.php' );
1392 }
1393 */
1394 }
1395
1396 /**
1397 * Return the image history of this image, line by line.
1398 * starts with current version, then old versions.
1399 * uses $this->historyLine to check which line to return:
1400 * 0 return line for current version
1401 * 1 query for old versions, return first one
1402 * 2, ... return next old version from above query
1403 *
1404 * @public
1405 */
1406 function nextHistoryLine() {
1407 $dbr =& wfGetDB( DB_SLAVE );
1408
1409 $this->checkDBSchema($dbr);
1410
1411 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
1412 $this->historyRes = $dbr->select( 'image',
1413 array(
1414 'img_size',
1415 'img_description',
1416 'img_user','img_user_text',
1417 'img_timestamp',
1418 'img_width',
1419 'img_height',
1420 "'' AS oi_archive_name"
1421 ),
1422 array( 'img_name' => $this->title->getDBkey() ),
1423 __METHOD__
1424 );
1425 if ( 0 == wfNumRows( $this->historyRes ) ) {
1426 return FALSE;
1427 }
1428 } else if ( $this->historyLine == 1 ) {
1429 $this->historyRes = $dbr->select( 'oldimage',
1430 array(
1431 'oi_size AS img_size',
1432 'oi_description AS img_description',
1433 'oi_user AS img_user',
1434 'oi_user_text AS img_user_text',
1435 'oi_timestamp AS img_timestamp',
1436 'oi_width as img_width',
1437 'oi_height as img_height',
1438 'oi_archive_name'
1439 ),
1440 array( 'oi_name' => $this->title->getDBkey() ),
1441 __METHOD__,
1442 array( 'ORDER BY' => 'oi_timestamp DESC' )
1443 );
1444 }
1445 $this->historyLine ++;
1446
1447 return $dbr->fetchObject( $this->historyRes );
1448 }
1449
1450 /**
1451 * Reset the history pointer to the first element of the history
1452 * @public
1453 */
1454 function resetHistory() {
1455 $this->historyLine = 0;
1456 }
1457
1458 /**
1459 * Return the full filesystem path to the file. Note that this does
1460 * not mean that a file actually exists under that location.
1461 *
1462 * This path depends on whether directory hashing is active or not,
1463 * i.e. whether the images are all found in the same directory,
1464 * or in hashed paths like /images/3/3c.
1465 *
1466 * @public
1467 * @param boolean $fromSharedDirectory Return the path to the file
1468 * in a shared repository (see $wgUseSharedRepository and related
1469 * options in DefaultSettings.php) instead of a local one.
1470 *
1471 */
1472 function getFullPath( $fromSharedRepository = false ) {
1473 global $wgUploadDirectory, $wgSharedUploadDirectory;
1474
1475 $dir = $fromSharedRepository ? $wgSharedUploadDirectory :
1476 $wgUploadDirectory;
1477
1478 // $wgSharedUploadDirectory may be false, if thumb.php is used
1479 if ( $dir ) {
1480 $fullpath = $dir . wfGetHashPath($this->name, $fromSharedRepository) . $this->name;
1481 } else {
1482 $fullpath = false;
1483 }
1484
1485 return $fullpath;
1486 }
1487
1488 /**
1489 * @return bool
1490 * @static
1491 */
1492 public static function isHashed( $shared ) {
1493 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1494 return $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1495 }
1496
1497 /**
1498 * Record an image upload in the upload log and the image table
1499 */
1500 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1501 global $wgUser, $wgUseCopyrightUpload;
1502
1503 $dbw =& wfGetDB( DB_MASTER );
1504
1505 $this->checkDBSchema($dbw);
1506
1507 // Delete thumbnails and refresh the metadata cache
1508 $this->purgeCache();
1509
1510 // Fail now if the image isn't there
1511 if ( !$this->fileExists || $this->fromSharedDirectory ) {
1512 wfDebug( "Image::recordUpload: File ".$this->imagePath." went missing!\n" );
1513 return false;
1514 }
1515
1516 if ( $wgUseCopyrightUpload ) {
1517 if ( $license != '' ) {
1518 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1519 }
1520 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1521 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1522 "$licensetxt" .
1523 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1524 } else {
1525 if ( $license != '' ) {
1526 $filedesc = $desc == '' ? '' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
1527 $textdesc = $filedesc .
1528 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1529 } else {
1530 $textdesc = $desc;
1531 }
1532 }
1533
1534 $now = $dbw->timestamp();
1535
1536 #split mime type
1537 if (strpos($this->mime,'/')!==false) {
1538 list($major,$minor)= explode('/',$this->mime,2);
1539 }
1540 else {
1541 $major= $this->mime;
1542 $minor= "unknown";
1543 }
1544
1545 # Test to see if the row exists using INSERT IGNORE
1546 # This avoids race conditions by locking the row until the commit, and also
1547 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1548 $dbw->insert( 'image',
1549 array(
1550 'img_name' => $this->name,
1551 'img_size'=> $this->size,
1552 'img_width' => intval( $this->width ),
1553 'img_height' => intval( $this->height ),
1554 'img_bits' => $this->bits,
1555 'img_media_type' => $this->type,
1556 'img_major_mime' => $major,
1557 'img_minor_mime' => $minor,
1558 'img_timestamp' => $now,
1559 'img_description' => $desc,
1560 'img_user' => $wgUser->getID(),
1561 'img_user_text' => $wgUser->getName(),
1562 'img_metadata' => $this->metadata,
1563 ),
1564 __METHOD__,
1565 'IGNORE'
1566 );
1567
1568 if( $dbw->affectedRows() == 0 ) {
1569 # Collision, this is an update of an image
1570 # Insert previous contents into oldimage
1571 $dbw->insertSelect( 'oldimage', 'image',
1572 array(
1573 'oi_name' => 'img_name',
1574 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1575 'oi_size' => 'img_size',
1576 'oi_width' => 'img_width',
1577 'oi_height' => 'img_height',
1578 'oi_bits' => 'img_bits',
1579 'oi_timestamp' => 'img_timestamp',
1580 'oi_description' => 'img_description',
1581 'oi_user' => 'img_user',
1582 'oi_user_text' => 'img_user_text',
1583 ), array( 'img_name' => $this->name ), __METHOD__
1584 );
1585
1586 # Update the current image row
1587 $dbw->update( 'image',
1588 array( /* SET */
1589 'img_size' => $this->size,
1590 'img_width' => intval( $this->width ),
1591 'img_height' => intval( $this->height ),
1592 'img_bits' => $this->bits,
1593 'img_media_type' => $this->type,
1594 'img_major_mime' => $major,
1595 'img_minor_mime' => $minor,
1596 'img_timestamp' => $now,
1597 'img_description' => $desc,
1598 'img_user' => $wgUser->getID(),
1599 'img_user_text' => $wgUser->getName(),
1600 'img_metadata' => $this->metadata,
1601 ), array( /* WHERE */
1602 'img_name' => $this->name
1603 ), __METHOD__
1604 );
1605 } else {
1606 # This is a new image
1607 # Update the image count
1608 $site_stats = $dbw->tableName( 'site_stats' );
1609 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
1610 }
1611
1612 $descTitle = $this->getTitle();
1613 $article = new Article( $descTitle );
1614 $minor = false;
1615 $watch = $watch || $wgUser->isWatched( $descTitle );
1616 $suppressRC = true; // There's already a log entry, so don't double the RC load
1617
1618 if( $descTitle->exists() ) {
1619 // TODO: insert a null revision into the page history for this update.
1620 if( $watch ) {
1621 $wgUser->addWatch( $descTitle );
1622 }
1623
1624 # Invalidate the cache for the description page
1625 $descTitle->invalidateCache();
1626 $descTitle->purgeSquid();
1627 } else {
1628 // New image; create the description page.
1629 $article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
1630 }
1631
1632 # Add the log entry
1633 $log = new LogPage( 'upload' );
1634 $log->addEntry( 'upload', $descTitle, $desc );
1635
1636 # Commit the transaction now, in case something goes wrong later
1637 # The most important thing is that images don't get lost, especially archives
1638 $dbw->immediateCommit();
1639
1640 # Invalidate cache for all pages using this image
1641 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1642 $update->doUpdate();
1643
1644 return true;
1645 }
1646
1647 /**
1648 * Get an array of Title objects which are articles which use this image
1649 * Also adds their IDs to the link cache
1650 *
1651 * This is mostly copied from Title::getLinksTo()
1652 *
1653 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
1654 */
1655 function getLinksTo( $options = '' ) {
1656 wfProfileIn( __METHOD__ );
1657
1658 if ( $options ) {
1659 $db =& wfGetDB( DB_MASTER );
1660 } else {
1661 $db =& wfGetDB( DB_SLAVE );
1662 }
1663 $linkCache =& LinkCache::singleton();
1664
1665 extract( $db->tableNames( 'page', 'imagelinks' ) );
1666 $encName = $db->addQuotes( $this->name );
1667 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1668 $res = $db->query( $sql, __METHOD__ );
1669
1670 $retVal = array();
1671 if ( $db->numRows( $res ) ) {
1672 while ( $row = $db->fetchObject( $res ) ) {
1673 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1674 $linkCache->addGoodLinkObj( $row->page_id, $titleObj );
1675 $retVal[] = $titleObj;
1676 }
1677 }
1678 }
1679 $db->freeResult( $res );
1680 wfProfileOut( __METHOD__ );
1681 return $retVal;
1682 }
1683
1684 /**
1685 * Retrive Exif data from the file and prune unrecognized tags
1686 * and/or tags with invalid contents
1687 *
1688 * @param $filename
1689 * @return array
1690 */
1691 private function retrieveExifData( $filename ) {
1692 global $wgShowEXIF;
1693
1694 /*
1695 if ( $this->getMimeType() !== "image/jpeg" )
1696 return array();
1697 */
1698
1699 if( $wgShowEXIF && file_exists( $filename ) ) {
1700 $exif = new Exif( $filename );
1701 return $exif->getFilteredData();
1702 }
1703
1704 return array();
1705 }
1706
1707 function getExifData() {
1708 global $wgRequest;
1709 if ( $this->metadata === '0' )
1710 return array();
1711
1712 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1713 $ret = unserialize( $this->metadata );
1714
1715 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ? $ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1716 $newver = Exif::version();
1717
1718 if ( !count( $ret ) || $purge || $oldver != $newver ) {
1719 $this->purgeMetadataCache();
1720 $this->updateExifData( $newver );
1721 }
1722 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1723 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1724 $format = new FormatExif( $ret );
1725
1726 return $format->getFormattedData();
1727 }
1728
1729 function updateExifData( $version ) {
1730 if ( $this->getImagePath() === false ) # Not a local image
1731 return;
1732
1733 # Get EXIF data from image
1734 $exif = $this->retrieveExifData( $this->imagePath );
1735 if ( count( $exif ) ) {
1736 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1737 $this->metadata = serialize( $exif );
1738 } else {
1739 $this->metadata = '0';
1740 }
1741
1742 # Update EXIF data in database
1743 $dbw =& wfGetDB( DB_MASTER );
1744
1745 $this->checkDBSchema($dbw);
1746
1747 $dbw->update( 'image',
1748 array( 'img_metadata' => $this->metadata ),
1749 array( 'img_name' => $this->name ),
1750 __METHOD__
1751 );
1752 }
1753
1754 /**
1755 * Returns true if the image does not come from the shared
1756 * image repository.
1757 *
1758 * @return bool
1759 */
1760 function isLocal() {
1761 return !$this->fromSharedDirectory;
1762 }
1763
1764 /**
1765 * Was this image ever deleted from the wiki?
1766 *
1767 * @return bool
1768 */
1769 function wasDeleted() {
1770 $title = Title::makeTitle( NS_IMAGE, $this->name );
1771 return ( $title->isDeleted() > 0 );
1772 }
1773
1774 /**
1775 * Delete all versions of the image.
1776 *
1777 * Moves the files into an archive directory (or deletes them)
1778 * and removes the database rows.
1779 *
1780 * Cache purging is done; logging is caller's responsibility.
1781 *
1782 * @param $reason
1783 * @return true on success, false on some kind of failure
1784 */
1785 function delete( $reason ) {
1786 $transaction = new FSTransaction();
1787 $urlArr = array( $this->getURL() );
1788
1789 if( !FileStore::lock() ) {
1790 wfDebug( __METHOD__.": failed to acquire file store lock, aborting\n" );
1791 return false;
1792 }
1793
1794 try {
1795 $dbw = wfGetDB( DB_MASTER );
1796 $dbw->begin();
1797
1798 // Delete old versions
1799 $result = $dbw->select( 'oldimage',
1800 array( 'oi_archive_name' ),
1801 array( 'oi_name' => $this->name ) );
1802
1803 while( $row = $dbw->fetchObject( $result ) ) {
1804 $oldName = $row->oi_archive_name;
1805
1806 $transaction->add( $this->prepareDeleteOld( $oldName, $reason ) );
1807
1808 // We'll need to purge this URL from caches...
1809 $urlArr[] = wfImageArchiveUrl( $oldName );
1810 }
1811 $dbw->freeResult( $result );
1812
1813 // And the current version...
1814 $transaction->add( $this->prepareDeleteCurrent( $reason ) );
1815
1816 $dbw->immediateCommit();
1817 } catch( MWException $e ) {
1818 wfDebug( __METHOD__.": db error, rolling back file transactions\n" );
1819 $transaction->rollback();
1820 FileStore::unlock();
1821 throw $e;
1822 }
1823
1824 wfDebug( __METHOD__.": deleted db items, applying file transactions\n" );
1825 $transaction->commit();
1826 FileStore::unlock();
1827
1828
1829 // Update site_stats
1830 $site_stats = $dbw->tableName( 'site_stats' );
1831 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__ );
1832
1833 $this->purgeEverything( $urlArr );
1834
1835 return true;
1836 }
1837
1838
1839 /**
1840 * Delete an old version of the image.
1841 *
1842 * Moves the file into an archive directory (or deletes it)
1843 * and removes the database row.
1844 *
1845 * Cache purging is done; logging is caller's responsibility.
1846 *
1847 * @param $reason
1848 * @throws MWException or FSException on database or filestore failure
1849 * @return true on success, false on some kind of failure
1850 */
1851 function deleteOld( $archiveName, $reason ) {
1852 $transaction = new FSTransaction();
1853 $urlArr = array();
1854
1855 if( !FileStore::lock() ) {
1856 wfDebug( __METHOD__.": failed to acquire file store lock, aborting\n" );
1857 return false;
1858 }
1859
1860 $transaction = new FSTransaction();
1861 try {
1862 $dbw = wfGetDB( DB_MASTER );
1863 $dbw->begin();
1864 $transaction->add( $this->prepareDeleteOld( $archiveName, $reason ) );
1865 $dbw->immediateCommit();
1866 } catch( MWException $e ) {
1867 wfDebug( __METHOD__.": db error, rolling back file transaction\n" );
1868 $transaction->rollback();
1869 FileStore::unlock();
1870 throw $e;
1871 }
1872
1873 wfDebug( __METHOD__.": deleted db items, applying file transaction\n" );
1874 $transaction->commit();
1875 FileStore::unlock();
1876
1877 $this->purgeDescription();
1878
1879 // Squid purging
1880 global $wgUseSquid;
1881 if ( $wgUseSquid ) {
1882 $urlArr = array(
1883 wfImageArchiveUrl( $archiveName ),
1884 );
1885 wfPurgeSquidServers( $urlArr );
1886 }
1887 return true;
1888 }
1889
1890 /**
1891 * Delete the current version of a file.
1892 * May throw a database error.
1893 * @return true on success, false on failure
1894 */
1895 private function prepareDeleteCurrent( $reason ) {
1896 return $this->prepareDeleteVersion(
1897 $this->getFullPath(),
1898 $reason,
1899 'image',
1900 array(
1901 'fa_name' => 'img_name',
1902 'fa_archive_name' => 'NULL',
1903 'fa_size' => 'img_size',
1904 'fa_width' => 'img_width',
1905 'fa_height' => 'img_height',
1906 'fa_metadata' => 'img_metadata',
1907 'fa_bits' => 'img_bits',
1908 'fa_media_type' => 'img_media_type',
1909 'fa_major_mime' => 'img_major_mime',
1910 'fa_minor_mime' => 'img_minor_mime',
1911 'fa_description' => 'img_description',
1912 'fa_user' => 'img_user',
1913 'fa_user_text' => 'img_user_text',
1914 'fa_timestamp' => 'img_timestamp' ),
1915 array( 'img_name' => $this->name ),
1916 __METHOD__ );
1917 }
1918
1919 /**
1920 * Delete a given older version of a file.
1921 * May throw a database error.
1922 * @return true on success, false on failure
1923 */
1924 private function prepareDeleteOld( $archiveName, $reason ) {
1925 $oldpath = wfImageArchiveDir( $this->name ) .
1926 DIRECTORY_SEPARATOR . $archiveName;
1927 return $this->prepareDeleteVersion(
1928 $oldpath,
1929 $reason,
1930 'oldimage',
1931 array(
1932 'fa_name' => 'oi_name',
1933 'fa_archive_name' => 'oi_archive_name',
1934 'fa_size' => 'oi_size',
1935 'fa_width' => 'oi_width',
1936 'fa_height' => 'oi_height',
1937 'fa_metadata' => 'NULL',
1938 'fa_bits' => 'oi_bits',
1939 'fa_media_type' => 'NULL',
1940 'fa_major_mime' => 'NULL',
1941 'fa_minor_mime' => 'NULL',
1942 'fa_description' => 'oi_description',
1943 'fa_user' => 'oi_user',
1944 'fa_user_text' => 'oi_user_text',
1945 'fa_timestamp' => 'oi_timestamp' ),
1946 array(
1947 'oi_name' => $this->name,
1948 'oi_archive_name' => $archiveName ),
1949 __METHOD__ );
1950 }
1951
1952 /**
1953 * Do the dirty work of backing up an image row and its file
1954 * (if $wgSaveDeletedFiles is on) and removing the originals.
1955 *
1956 * Must be run while the file store is locked and a database
1957 * transaction is open to avoid race conditions.
1958 *
1959 * @return FSTransaction
1960 */
1961 private function prepareDeleteVersion( $path, $reason, $table, $fieldMap, $where, $fname ) {
1962 global $wgUser, $wgSaveDeletedFiles;
1963
1964 // Dupe the file into the file store
1965 if( file_exists( $path ) ) {
1966 if( $wgSaveDeletedFiles ) {
1967 $group = 'deleted';
1968
1969 $store = FileStore::get( $group );
1970 $key = FileStore::calculateKey( $path, $this->extension );
1971 $transaction = $store->insert( $key, $path,
1972 FileStore::DELETE_ORIGINAL );
1973 } else {
1974 $group = null;
1975 $key = null;
1976 $transaction = FileStore::deleteFile( $path );
1977 }
1978 } else {
1979 wfDebug( __METHOD__." deleting already-missing '$path'; moving on to database\n" );
1980 $group = null;
1981 $key = null;
1982 $transaction = new FSTransaction(); // empty
1983 }
1984
1985 if( $transaction === false ) {
1986 // Fail to restore?
1987 wfDebug( __METHOD__.": import to file store failed, aborting\n" );
1988 throw new MWException( "Could not archive and delete file $path" );
1989 return false;
1990 }
1991
1992 $dbw = wfGetDB( DB_MASTER );
1993 $storageMap = array(
1994 'fa_storage_group' => $dbw->addQuotes( $group ),
1995 'fa_storage_key' => $dbw->addQuotes( $key ),
1996
1997 'fa_deleted_user' => $dbw->addQuotes( $wgUser->getId() ),
1998 'fa_deleted_timestamp' => $dbw->timestamp(),
1999 'fa_deleted_reason' => $dbw->addQuotes( $reason ) );
2000 $allFields = array_merge( $storageMap, $fieldMap );
2001
2002 try {
2003 if( $wgSaveDeletedFiles ) {
2004 $dbw->insertSelect( 'filearchive', $table, $allFields, $where, $fname );
2005 }
2006 $dbw->delete( $table, $where, $fname );
2007 } catch( DBQueryError $e ) {
2008 // Something went horribly wrong!
2009 // Leave the file as it was...
2010 wfDebug( __METHOD__.": database error, rolling back file transaction\n" );
2011 $transaction->rollback();
2012 throw $e;
2013 }
2014
2015 return $transaction;
2016 }
2017
2018 /**
2019 * Restore all or specified deleted revisions to the given file.
2020 * Permissions and logging are left to the caller.
2021 *
2022 * May throw database exceptions on error.
2023 *
2024 * @param $versions set of record ids of deleted items to restore,
2025 * or empty to restore all revisions.
2026 * @return the number of file revisions restored if successful,
2027 * or false on failure
2028 */
2029 function restore( $versions=array() ) {
2030 if( !FileStore::lock() ) {
2031 wfDebug( __METHOD__." could not acquire filestore lock\n" );
2032 return false;
2033 }
2034
2035 $transaction = new FSTransaction();
2036 try {
2037 $dbw = wfGetDB( DB_MASTER );
2038 $dbw->begin();
2039
2040 // Re-confirm whether this image presently exists;
2041 // if no we'll need to create an image record for the
2042 // first item we restore.
2043 $exists = $dbw->selectField( 'image', '1',
2044 array( 'img_name' => $this->name ),
2045 __METHOD__ );
2046
2047 // Fetch all or selected archived revisions for the file,
2048 // sorted from the most recent to the oldest.
2049 $conditions = array( 'fa_name' => $this->name );
2050 if( $versions ) {
2051 $conditions['fa_id'] = $versions;
2052 }
2053
2054 $result = $dbw->select( 'filearchive', '*',
2055 $conditions,
2056 __METHOD__,
2057 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
2058
2059 if( $dbw->numRows( $result ) < count( $versions ) ) {
2060 // There's some kind of conflict or confusion;
2061 // we can't restore everything we were asked to.
2062 wfDebug( __METHOD__.": couldn't find requested items\n" );
2063 $dbw->rollback();
2064 FileStore::unlock();
2065 return false;
2066 }
2067
2068 if( $dbw->numRows( $result ) == 0 ) {
2069 // Nothing to do.
2070 wfDebug( __METHOD__.": nothing to do\n" );
2071 $dbw->rollback();
2072 FileStore::unlock();
2073 return true;
2074 }
2075
2076 $revisions = 0;
2077 while( $row = $dbw->fetchObject( $result ) ) {
2078 $revisions++;
2079 $store = FileStore::get( $row->fa_storage_group );
2080 if( !$store ) {
2081 wfDebug( __METHOD__.": skipping row with no file.\n" );
2082 continue;
2083 }
2084
2085 if( $revisions == 1 && !$exists ) {
2086 $destDir = wfImageDir( $row->fa_name );
2087 if ( !is_dir( $destDir ) ) {
2088 wfMkdirParents( $destDir );
2089 }
2090 $destPath = $destDir . DIRECTORY_SEPARATOR . $row->fa_name;
2091
2092 // We may have to fill in data if this was originally
2093 // an archived file revision.
2094 if( is_null( $row->fa_metadata ) ) {
2095 $tempFile = $store->filePath( $row->fa_storage_key );
2096 $metadata = serialize( $this->retrieveExifData( $tempFile ) );
2097
2098 $magic = wfGetMimeMagic();
2099 $mime = $magic->guessMimeType( $tempFile, true );
2100 $media_type = $magic->getMediaType( $tempFile, $mime );
2101 list( $major_mime, $minor_mime ) = self::splitMime( $mime );
2102 } else {
2103 $metadata = $row->fa_metadata;
2104 $major_mime = $row->fa_major_mime;
2105 $minor_mime = $row->fa_minor_mime;
2106 $media_type = $row->fa_media_type;
2107 }
2108
2109 $table = 'image';
2110 $fields = array(
2111 'img_name' => $row->fa_name,
2112 'img_size' => $row->fa_size,
2113 'img_width' => $row->fa_width,
2114 'img_height' => $row->fa_height,
2115 'img_metadata' => $metadata,
2116 'img_bits' => $row->fa_bits,
2117 'img_media_type' => $media_type,
2118 'img_major_mime' => $major_mime,
2119 'img_minor_mime' => $minor_mime,
2120 'img_description' => $row->fa_description,
2121 'img_user' => $row->fa_user,
2122 'img_user_text' => $row->fa_user_text,
2123 'img_timestamp' => $row->fa_timestamp );
2124 } else {
2125 $archiveName = $row->fa_archive_name;
2126 if( $archiveName == '' ) {
2127 // This was originally a current version; we
2128 // have to devise a new archive name for it.
2129 // Format is <timestamp of archiving>!<name>
2130 $archiveName =
2131 wfTimestamp( TS_MW, $row->fa_deleted_timestamp ) .
2132 '!' . $row->fa_name;
2133 }
2134 $destDir = wfImageArchiveDir( $row->fa_name );
2135 if ( !is_dir( $destDir ) ) {
2136 wfMkdirParents( $destDir );
2137 }
2138 $destPath = $destDir . DIRECTORY_SEPARATOR . $archiveName;
2139
2140 $table = 'oldimage';
2141 $fields = array(
2142 'oi_name' => $row->fa_name,
2143 'oi_archive_name' => $archiveName,
2144 'oi_size' => $row->fa_size,
2145 'oi_width' => $row->fa_width,
2146 'oi_height' => $row->fa_height,
2147 'oi_bits' => $row->fa_bits,
2148 'oi_description' => $row->fa_description,
2149 'oi_user' => $row->fa_user,
2150 'oi_user_text' => $row->fa_user_text,
2151 'oi_timestamp' => $row->fa_timestamp );
2152 }
2153
2154 $dbw->insert( $table, $fields, __METHOD__ );
2155 /// @fixme this delete is not totally safe, potentially
2156 $dbw->delete( 'filearchive',
2157 array( 'fa_id' => $row->fa_id ),
2158 __METHOD__ );
2159
2160 // Check if any other stored revisions use this file;
2161 // if so, we shouldn't remove the file from the deletion
2162 // archives so they will still work.
2163 $useCount = $dbw->selectField( 'filearchive',
2164 'COUNT(*)',
2165 array(
2166 'fa_storage_group' => $row->fa_storage_group,
2167 'fa_storage_key' => $row->fa_storage_key ),
2168 __METHOD__ );
2169 if( $useCount == 0 ) {
2170 wfDebug( __METHOD__.": nothing else using {$row->fa_storage_key}, will deleting after\n" );
2171 $flags = FileStore::DELETE_ORIGINAL;
2172 } else {
2173 $flags = 0;
2174 }
2175
2176 $transaction->add( $store->export( $row->fa_storage_key,
2177 $destPath, $flags ) );
2178 }
2179
2180 $dbw->immediateCommit();
2181 } catch( MWException $e ) {
2182 wfDebug( __METHOD__." caught error, aborting\n" );
2183 $transaction->rollback();
2184 throw $e;
2185 }
2186
2187 $transaction->commit();
2188 FileStore::unlock();
2189
2190 if( $revisions > 0 ) {
2191 if( !$exists ) {
2192 wfDebug( __METHOD__." restored $revisions items, creating a new current\n" );
2193
2194 // Update site_stats
2195 $site_stats = $dbw->tableName( 'site_stats' );
2196 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
2197
2198 $this->purgeEverything();
2199 } else {
2200 wfDebug( __METHOD__." restored $revisions as archived versions\n" );
2201 $this->purgeDescription();
2202 }
2203 }
2204
2205 return $revisions;
2206 }
2207
2208 } //class
2209
2210 /**
2211 * Wrapper class for thumbnail images
2212 * @package MediaWiki
2213 */
2214 class ThumbnailImage {
2215 /**
2216 * @param string $path Filesystem path to the thumb
2217 * @param string $url URL path to the thumb
2218 * @private
2219 */
2220 function ThumbnailImage( $url, $width, $height, $path = false ) {
2221 $this->url = $url;
2222 $this->width = round( $width );
2223 $this->height = round( $height );
2224 # These should be integers when they get here.
2225 # If not, there's a bug somewhere. But let's at
2226 # least produce valid HTML code regardless.
2227 $this->path = $path;
2228 }
2229
2230 /**
2231 * @return string The thumbnail URL
2232 */
2233 function getUrl() {
2234 return $this->url;
2235 }
2236
2237 /**
2238 * Return HTML <img ... /> tag for the thumbnail, will include
2239 * width and height attributes and a blank alt text (as required).
2240 *
2241 * You can set or override additional attributes by passing an
2242 * associative array of name => data pairs. The data will be escaped
2243 * for HTML output, so should be in plaintext.
2244 *
2245 * @param array $attribs
2246 * @return string
2247 * @public
2248 */
2249 function toHtml( $attribs = array() ) {
2250 $attribs['src'] = $this->url;
2251 $attribs['width'] = $this->width;
2252 $attribs['height'] = $this->height;
2253 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
2254
2255 $html = '<img ';
2256 foreach( $attribs as $name => $data ) {
2257 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
2258 }
2259 $html .= '/>';
2260 return $html;
2261 }
2262
2263 }
2264
2265 ?>