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