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