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