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