]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/filerepo/LocalFile.php
MediaWiki 1.16.0
[autoinstalls/mediawiki.git] / includes / filerepo / LocalFile.php
1 <?php
2 /**
3  */
4
5 /**
6  * Bump this number when serialized cache records may be incompatible.
7  */
8 define( 'MW_FILE_VERSION', 8 );
9
10 /**
11  * Class to represent a local file in the wiki's own database
12  *
13  * Provides methods to retrieve paths (physical, logical, URL),
14  * to generate image thumbnails or for uploading.
15  *
16  * Note that only the repo object knows what its file class is called. You should
17  * never name a file class explictly outside of the repo class. Instead use the
18  * repo's factory functions to generate file objects, for example:
19  *
20  * RepoGroup::singleton()->getLocalRepo()->newFile($title);
21  *
22  * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
23  * in most cases.
24  *
25  * @ingroup FileRepo
26  */
27 class LocalFile extends File {
28         /**#@+
29          * @private
30          */
31         var     $fileExists,       # does the file file exist on disk? (loadFromXxx)
32                 $historyLine,      # Number of line to return by nextHistoryLine() (constructor)
33                 $historyRes,       # result of the query for the file's history (nextHistoryLine)
34                 $width,            # \
35                 $height,           #  |
36                 $bits,             #   --- returned by getimagesize (loadFromXxx)
37                 $attr,             # /
38                 $media_type,       # MEDIATYPE_xxx (bitmap, drawing, audio...)
39                 $mime,             # MIME type, determined by MimeMagic::guessMimeType
40                 $major_mime,       # Major mime type
41                 $minor_mime,       # Minor mime type
42                 $size,             # Size in bytes (loadFromXxx)
43                 $metadata,         # Handler-specific metadata
44                 $timestamp,        # Upload timestamp
45                 $sha1,             # SHA-1 base 36 content hash
46                 $user, $user_text, # User, who uploaded the file
47                 $description,      # Description of current revision of the file
48                 $dataLoaded,       # Whether or not all this has been loaded from the database (loadFromXxx)
49                 $upgraded,         # Whether the row was upgraded on load
50                 $locked,           # True if the image row is locked
51                 $missing,          # True if file is not present in file system. Not to be cached in memcached
52                 $deleted;       # Bitfield akin to rev_deleted
53
54         /**#@-*/
55
56         /**
57          * Create a LocalFile from a title
58          * Do not call this except from inside a repo class.
59          *
60          * Note: $unused param is only here to avoid an E_STRICT
61          */
62         static function newFromTitle( $title, $repo, $unused = null ) {
63                 return new self( $title, $repo );
64         }
65
66         /**
67          * Create a LocalFile from a title
68          * Do not call this except from inside a repo class.
69          */
70         static function newFromRow( $row, $repo ) {
71                 $title = Title::makeTitle( NS_FILE, $row->img_name );
72                 $file = new self( $title, $repo );
73                 $file->loadFromRow( $row );
74                 return $file;
75         }
76         
77         /**
78          * Create a LocalFile from a SHA-1 key
79          * Do not call this except from inside a repo class.
80          */
81         static function newFromKey( $sha1, $repo, $timestamp = false ) {
82                 # Polymorphic function name to distinguish foreign and local fetches
83                 $fname = get_class( $this ) . '::' . __FUNCTION__;
84
85                 $conds = array( 'img_sha1' => $sha1 );
86                 if( $timestamp ) {
87                         $conds['img_timestamp'] = $timestamp;
88                 }
89                 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ), $conds, $fname );
90                 if( $row ) {
91                         return self::newFromRow( $row, $repo );
92                 } else {
93                         return false;
94                 }
95         }
96         
97         /**
98          * Fields in the image table
99          */
100         static function selectFields() {
101                 return array(
102                         'img_name',
103                         'img_size',
104                         'img_width',
105                         'img_height',
106                         'img_metadata',
107                         'img_bits',
108                         'img_media_type',
109                         'img_major_mime',
110                         'img_minor_mime',
111                         'img_description',
112                         'img_user',
113                         'img_user_text',
114                         'img_timestamp',
115                         'img_sha1',
116                 );
117         }
118
119         /**
120          * Constructor.
121          * Do not call this except from inside a repo class.
122          */
123         function __construct( $title, $repo ) {
124                 if( !is_object( $title ) ) {
125                         throw new MWException( __CLASS__ . ' constructor given bogus title.' );
126                 }
127                 parent::__construct( $title, $repo );
128                 $this->metadata = '';
129                 $this->historyLine = 0;
130                 $this->historyRes = null;
131                 $this->dataLoaded = false;
132         }
133
134         /**
135          * Get the memcached key for the main data for this file, or false if 
136          * there is no access to the shared cache.
137          */
138         function getCacheKey() {
139                 $hashedName = md5( $this->getName() );
140                 return $this->repo->getSharedCacheKey( 'file', $hashedName );
141         }
142
143         /**
144          * Try to load file metadata from memcached. Returns true on success.
145          */
146         function loadFromCache() {
147                 global $wgMemc;
148                 wfProfileIn( __METHOD__ );
149                 $this->dataLoaded = false;
150                 $key = $this->getCacheKey();
151                 if ( !$key ) {
152                         wfProfileOut( __METHOD__ );
153                         return false;
154                 }
155                 $cachedValues = $wgMemc->get( $key );
156
157                 // Check if the key existed and belongs to this version of MediaWiki
158                 if ( isset( $cachedValues['version'] ) && ( $cachedValues['version'] == MW_FILE_VERSION ) ) {
159                         wfDebug( "Pulling file metadata from cache key $key\n" );
160                         $this->fileExists = $cachedValues['fileExists'];
161                         if ( $this->fileExists ) {
162                                 $this->setProps( $cachedValues );
163                         }
164                         $this->dataLoaded = true;
165                 }
166                 if ( $this->dataLoaded ) {
167                         wfIncrStats( 'image_cache_hit' );
168                 } else {
169                         wfIncrStats( 'image_cache_miss' );
170                 }
171
172                 wfProfileOut( __METHOD__ );
173                 return $this->dataLoaded;
174         }
175
176         /**
177          * Save the file metadata to memcached
178          */
179         function saveToCache() {
180                 global $wgMemc;
181                 $this->load();
182                 $key = $this->getCacheKey();
183                 if ( !$key ) {
184                         return;
185                 }
186                 $fields = $this->getCacheFields( '' );
187                 $cache = array( 'version' => MW_FILE_VERSION );
188                 $cache['fileExists'] = $this->fileExists;
189                 if ( $this->fileExists ) {
190                         foreach ( $fields as $field ) {
191                                 $cache[$field] = $this->$field;
192                         }
193                 }
194
195                 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
196         }
197
198         /**
199          * Load metadata from the file itself
200          */
201         function loadFromFile() {
202                 $this->setProps( self::getPropsFromPath( $this->getPath() ) );
203         }
204
205         function getCacheFields( $prefix = 'img_' ) {
206                 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
207                         'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
208                 static $results = array();
209                 if ( $prefix == '' ) {
210                         return $fields;
211                 }
212                 if ( !isset( $results[$prefix] ) ) {
213                         $prefixedFields = array();
214                         foreach ( $fields as $field ) {
215                                 $prefixedFields[] = $prefix . $field;
216                         }
217                         $results[$prefix] = $prefixedFields;
218                 }
219                 return $results[$prefix];
220         }
221
222         /**
223          * Load file metadata from the DB
224          */
225         function loadFromDB() {
226                 # Polymorphic function name to distinguish foreign and local fetches
227                 $fname = get_class( $this ) . '::' . __FUNCTION__;
228                 wfProfileIn( $fname );
229
230                 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
231                 $this->dataLoaded = true;
232
233                 $dbr = $this->repo->getMasterDB();
234
235                 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
236                         array( 'img_name' => $this->getName() ), $fname );
237                 if ( $row ) {
238                         $this->loadFromRow( $row );
239                 } else {
240                         $this->fileExists = false;
241                 }
242
243                 wfProfileOut( $fname );
244         }
245
246         /**
247          * Decode a row from the database (either object or array) to an array
248          * with timestamps and MIME types decoded, and the field prefix removed.
249          */
250         function decodeRow( $row, $prefix = 'img_' ) {
251                 $array = (array)$row;
252                 $prefixLength = strlen( $prefix );
253                 // Sanity check prefix once
254                 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
255                         throw new MWException( __METHOD__ .  ': incorrect $prefix parameter' );
256                 }
257                 $decoded = array();
258                 foreach ( $array as $name => $value ) {
259                         $decoded[substr( $name, $prefixLength )] = $value;
260                 }
261                 $decoded['timestamp'] = wfTimestamp( TS_MW, $decoded['timestamp'] );
262                 if ( empty( $decoded['major_mime'] ) ) {
263                         $decoded['mime'] = 'unknown/unknown';
264                 } else {
265                         if ( !$decoded['minor_mime'] ) {
266                                 $decoded['minor_mime'] = 'unknown';
267                         }
268                         $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
269                 }
270                 # Trim zero padding from char/binary field
271                 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
272                 return $decoded;
273         }
274
275         /**
276          * Load file metadata from a DB result row
277          */
278         function loadFromRow( $row, $prefix = 'img_' ) {
279                 $this->dataLoaded = true;
280                 $array = $this->decodeRow( $row, $prefix );
281                 foreach ( $array as $name => $value ) {
282                         $this->$name = $value;
283                 }
284                 $this->fileExists = true;
285                 $this->maybeUpgradeRow();
286         }
287
288         /**
289          * Load file metadata from cache or DB, unless already loaded
290          */
291         function load() {
292                 if ( !$this->dataLoaded ) {
293                         if ( !$this->loadFromCache() ) {
294                                 $this->loadFromDB();
295                                 $this->saveToCache();
296                         }
297                         $this->dataLoaded = true;
298                 }
299         }
300
301         /**
302          * Upgrade a row if it needs it
303          */
304         function maybeUpgradeRow() {
305                 if ( wfReadOnly() ) {
306                         return;
307                 }
308                 if ( is_null( $this->media_type ) ||
309                         $this->mime == 'image/svg'
310                 ) {
311                         $this->upgradeRow();
312                         $this->upgraded = true;
313                 } else {
314                         $handler = $this->getHandler();
315                         if ( $handler && !$handler->isMetadataValid( $this, $this->metadata ) ) {
316                                 $this->upgradeRow();
317                                 $this->upgraded = true;
318                         }
319                 }
320         }
321
322         function getUpgraded() {
323                 return $this->upgraded;
324         }
325
326         /**
327          * Fix assorted version-related problems with the image row by reloading it from the file
328          */
329         function upgradeRow() {
330                 wfProfileIn( __METHOD__ );
331
332                 $this->loadFromFile();
333
334                 # Don't destroy file info of missing files
335                 if ( !$this->fileExists ) {
336                         wfDebug( __METHOD__ . ": file does not exist, aborting\n" );
337                         wfProfileOut( __METHOD__ );
338                         return;
339                 }
340                 $dbw = $this->repo->getMasterDB();
341                 list( $major, $minor ) = self::splitMime( $this->mime );
342
343                 if ( wfReadOnly() ) {
344                         wfProfileOut( __METHOD__ );
345                         return;
346                 }
347                 wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema\n" );
348
349                 $dbw->update( 'image',
350                         array(
351                                 'img_width' => $this->width,
352                                 'img_height' => $this->height,
353                                 'img_bits' => $this->bits,
354                                 'img_media_type' => $this->media_type,
355                                 'img_major_mime' => $major,
356                                 'img_minor_mime' => $minor,
357                                 'img_metadata' => $this->metadata,
358                                 'img_sha1' => $this->sha1,
359                         ), array( 'img_name' => $this->getName() ),
360                         __METHOD__
361                 );
362                 $this->saveToCache();
363                 wfProfileOut( __METHOD__ );
364         }
365
366         /**
367          * Set properties in this object to be equal to those given in the
368          * associative array $info. Only cacheable fields can be set.
369          *
370          * If 'mime' is given, it will be split into major_mime/minor_mime.
371          * If major_mime/minor_mime are given, $this->mime will also be set.
372          */
373         function setProps( $info ) {
374                 $this->dataLoaded = true;
375                 $fields = $this->getCacheFields( '' );
376                 $fields[] = 'fileExists';
377                 foreach ( $fields as $field ) {
378                         if ( isset( $info[$field] ) ) {
379                                 $this->$field = $info[$field];
380                         }
381                 }
382                 // Fix up mime fields
383                 if ( isset( $info['major_mime'] ) ) {
384                         $this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
385                 } elseif ( isset( $info['mime'] ) ) {
386                         list( $this->major_mime, $this->minor_mime ) = self::splitMime( $this->mime );
387                 }
388         }
389
390         /** splitMime inherited */
391         /** getName inherited */
392         /** getTitle inherited */
393         /** getURL inherited */
394         /** getViewURL inherited */
395         /** getPath inherited */
396         /** isVisible inhereted */
397
398         function isMissing() {
399                 if( $this->missing === null ) {
400                         list( $fileExists ) = $this->repo->fileExistsBatch( array( $this->getVirtualUrl() ), FileRepo::FILES_ONLY );
401                         $this->missing = !$fileExists;
402                 }
403                 return $this->missing;
404         }
405
406         /**
407          * Return the width of the image
408          *
409          * Returns false on error
410          */
411         public function getWidth( $page = 1 ) {
412                 $this->load();
413                 if ( $this->isMultipage() ) {
414                         $dim = $this->getHandler()->getPageDimensions( $this, $page );
415                         if ( $dim ) {
416                                 return $dim['width'];
417                         } else {
418                                 return false;
419                         }
420                 } else {
421                         return $this->width;
422                 }
423         }
424
425         /**
426          * Return the height of the image
427          *
428          * Returns false on error
429          */
430         public function getHeight( $page = 1 ) {
431                 $this->load();
432                 if ( $this->isMultipage() ) {
433                         $dim = $this->getHandler()->getPageDimensions( $this, $page );
434                         if ( $dim ) {
435                                 return $dim['height'];
436                         } else {
437                                 return false;
438                         }
439                 } else {
440                         return $this->height;
441                 }
442         }
443
444         /**
445          * Returns ID or name of user who uploaded the file
446          *
447          * @param $type string 'text' or 'id'
448          */
449         function getUser( $type = 'text' ) {
450                 $this->load();
451                 if( $type == 'text' ) {
452                         return $this->user_text;
453                 } elseif( $type == 'id' ) {
454                         return $this->user;
455                 }
456         }
457
458         /**
459          * Get handler-specific metadata
460          */
461         function getMetadata() {
462                 $this->load();
463                 return $this->metadata;
464         }
465
466         function getBitDepth() {
467                 $this->load();
468                 return $this->bits;
469         }
470
471         /**
472          * Return the size of the image file, in bytes
473          */
474         public function getSize() {
475                 $this->load();
476                 return $this->size;
477         }
478
479         /**
480          * Returns the mime type of the file.
481          */
482         function getMimeType() {
483                 $this->load();
484                 return $this->mime;
485         }
486
487         /**
488          * Return the type of the media in the file.
489          * Use the value returned by this function with the MEDIATYPE_xxx constants.
490          */
491         function getMediaType() {
492                 $this->load();
493                 return $this->media_type;
494         }
495
496         /** canRender inherited */
497         /** mustRender inherited */
498         /** allowInlineDisplay inherited */
499         /** isSafeFile inherited */
500         /** isTrustedFile inherited */
501
502         /**
503          * Returns true if the file file exists on disk.
504          * @return boolean Whether file file exist on disk.
505          */
506         public function exists() {
507                 $this->load();
508                 return $this->fileExists;
509         }
510
511         /** getTransformScript inherited */
512         /** getUnscaledThumb inherited */
513         /** thumbName inherited */
514         /** createThumb inherited */
515         /** getThumbnail inherited */
516         /** transform inherited */
517
518         /**
519          * Fix thumbnail files from 1.4 or before, with extreme prejudice
520          */
521         function migrateThumbFile( $thumbName ) {
522                 $thumbDir = $this->getThumbPath();
523                 $thumbPath = "$thumbDir/$thumbName";
524                 if ( is_dir( $thumbPath ) ) {
525                         // Directory where file should be
526                         // This happened occasionally due to broken migration code in 1.5
527                         // Rename to broken-*
528                         for ( $i = 0; $i < 100 ; $i++ ) {
529                                 $broken = $this->repo->getZonePath( 'public' ) . "/broken-$i-$thumbName";
530                                 if ( !file_exists( $broken ) ) {
531                                         rename( $thumbPath, $broken );
532                                         break;
533                                 }
534                         }
535                         // Doesn't exist anymore
536                         clearstatcache();
537                 }
538                 if ( is_file( $thumbDir ) ) {
539                         // File where directory should be
540                         unlink( $thumbDir );
541                         // Doesn't exist anymore
542                         clearstatcache();
543                 }
544         }
545
546         /** getHandler inherited */
547         /** iconThumb inherited */
548         /** getLastError inherited */
549
550         /**
551          * Get all thumbnail names previously generated for this file
552          */
553         function getThumbnails() {
554                 $this->load();
555                 $files = array();
556                 $dir = $this->getThumbPath();
557
558                 if ( is_dir( $dir ) ) {
559                         $handle = opendir( $dir );
560
561                         if ( $handle ) {
562                                 while ( false !== ( $file = readdir( $handle ) ) ) {
563                                         if ( $file{0} != '.' ) {
564                                                 $files[] = $file;
565                                         }
566                                 }
567                                 closedir( $handle );
568                         }
569                 }
570
571                 return $files;
572         }
573
574         /**
575          * Refresh metadata in memcached, but don't touch thumbnails or squid
576          */
577         function purgeMetadataCache() {
578                 $this->loadFromDB();
579                 $this->saveToCache();
580                 $this->purgeHistory();
581         }
582
583         /**
584          * Purge the shared history (OldLocalFile) cache
585          */
586         function purgeHistory() {
587                 global $wgMemc;
588                 $hashedName = md5( $this->getName() );
589                 $oldKey = $this->repo->getSharedCacheKey( 'oldfile', $hashedName );
590                 if ( $oldKey ) {
591                         $wgMemc->delete( $oldKey );
592                 }
593         }
594
595         /**
596          * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
597          */
598         function purgeCache() {
599                 // Refresh metadata cache
600                 $this->purgeMetadataCache();
601
602                 // Delete thumbnails
603                 $this->purgeThumbnails();
604
605                 // Purge squid cache for this file
606                 SquidUpdate::purge( array( $this->getURL() ) );
607         }
608
609         /**
610          * Delete cached transformed files
611          */
612         function purgeThumbnails() {
613                 global $wgUseSquid;
614                 // Delete thumbnails
615                 $files = $this->getThumbnails();
616                 $dir = $this->getThumbPath();
617                 $urls = array();
618                 foreach ( $files as $file ) {
619                         # Check that the base file name is part of the thumb name
620                         # This is a basic sanity check to avoid erasing unrelated directories
621                         if ( strpos( $file, $this->getName() ) !== false ) {
622                                 $url = $this->getThumbUrl( $file );
623                                 $urls[] = $url;
624                                 @unlink( "$dir/$file" );
625                         }
626                 }
627
628                 // Purge the squid
629                 if ( $wgUseSquid ) {
630                         SquidUpdate::purge( $urls );
631                 }
632         }
633
634         /** purgeDescription inherited */
635         /** purgeEverything inherited */
636
637         function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
638                 $dbr = $this->repo->getSlaveDB();
639                 $tables = array( 'oldimage' );
640                 $fields = OldLocalFile::selectFields();
641                 $conds = $opts = $join_conds = array();
642                 $eq = $inc ? '=' : '';
643                 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
644                 if( $start ) {
645                         $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
646                 }
647                 if( $end ) {
648                         $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
649                 }
650                 if( $limit ) {
651                         $opts['LIMIT'] = $limit;
652                 }
653                 // Search backwards for time > x queries
654                 $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
655                 $opts['ORDER BY'] = "oi_timestamp $order";
656                 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
657
658                 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields, 
659                         &$conds, &$opts, &$join_conds ) );
660
661                 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
662                 $r = array();
663                 while( $row = $dbr->fetchObject( $res ) ) {
664                         $r[] = OldLocalFile::newFromRow( $row, $this->repo );
665                 }
666                 if( $order == 'ASC' ) {
667                         $r = array_reverse( $r ); // make sure it ends up descending
668                 }
669                 return $r;
670         }
671
672         /**
673          * Return the history of this file, line by line.
674          * starts with current version, then old versions.
675          * uses $this->historyLine to check which line to return:
676          *  0      return line for current version
677          *  1      query for old versions, return first one
678          *  2, ... return next old version from above query
679          */
680         public function nextHistoryLine() {
681                 # Polymorphic function name to distinguish foreign and local fetches
682                 $fname = get_class( $this ) . '::' . __FUNCTION__;
683
684                 $dbr = $this->repo->getSlaveDB();
685
686                 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
687                         $this->historyRes = $dbr->select( 'image',
688                                 array(
689                                         '*',
690                                         "'' AS oi_archive_name",
691                                         '0 as oi_deleted',
692                                         'img_sha1'
693                                 ),
694                                 array( 'img_name' => $this->title->getDBkey() ),
695                                 $fname
696                         );
697                         if ( 0 == $dbr->numRows( $this->historyRes ) ) {
698                                 $dbr->freeResult( $this->historyRes );
699                                 $this->historyRes = null;
700                                 return false;
701                         }
702                 } elseif ( $this->historyLine == 1 ) {
703                         $dbr->freeResult( $this->historyRes );
704                         $this->historyRes = $dbr->select( 'oldimage', '*',
705                                 array( 'oi_name' => $this->title->getDBkey() ),
706                                 $fname,
707                                 array( 'ORDER BY' => 'oi_timestamp DESC' )
708                         );
709                 }
710                 $this->historyLine ++;
711
712                 return $dbr->fetchObject( $this->historyRes );
713         }
714
715         /**
716          * Reset the history pointer to the first element of the history
717          */
718         public function resetHistory() {
719                 $this->historyLine = 0;
720                 if ( !is_null( $this->historyRes ) ) {
721                         $this->repo->getSlaveDB()->freeResult( $this->historyRes );
722                         $this->historyRes = null;
723                 }
724         }
725
726         /** getFullPath inherited */
727         /** getHashPath inherited */
728         /** getRel inherited */
729         /** getUrlRel inherited */
730         /** getArchiveRel inherited */
731         /** getThumbRel inherited */
732         /** getArchivePath inherited */
733         /** getThumbPath inherited */
734         /** getArchiveUrl inherited */
735         /** getThumbUrl inherited */
736         /** getArchiveVirtualUrl inherited */
737         /** getThumbVirtualUrl inherited */
738         /** isHashed inherited */
739
740         /**
741          * Upload a file and record it in the DB
742          * @param string $srcPath Source path or virtual URL
743          * @param string $comment Upload description
744          * @param string $pageText Text to use for the new description page, if a new description page is created
745          * @param integer $flags Flags for publish()
746          * @param array $props File properties, if known. This can be used to reduce the
747          *                         upload time when uploading virtual URLs for which the file info
748          *                         is already known
749          * @param string $timestamp Timestamp for img_timestamp, or false to use the current time
750          *
751          * @return FileRepoStatus object. On success, the value member contains the
752          *     archive name, or an empty string if it was a new file.
753          */
754         function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
755                 $this->lock();
756                 $status = $this->publish( $srcPath, $flags );
757                 if ( $status->ok ) {
758                         if ( !$this->recordUpload2( $status->value, $comment, $pageText, $props, $timestamp, $user ) ) {
759                                 $status->fatal( 'filenotfound', $srcPath );
760                         }
761                 }
762                 $this->unlock();
763                 return $status;
764         }
765
766         /**
767          * Record a file upload in the upload log and the image table
768          * @deprecated use upload()
769          */
770         function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
771                 $watch = false, $timestamp = false )
772         {
773                 $pageText = SpecialUpload::getInitialPageText( $desc, $license, $copyStatus, $source );
774                 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
775                         return false;
776                 }
777                 if ( $watch ) {
778                         global $wgUser;
779                         $wgUser->addWatch( $this->getTitle() );
780                 }
781                 return true;
782
783         }
784
785         /**
786          * Record a file upload in the upload log and the image table
787          */
788         function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null )
789         {
790                 if( is_null( $user ) ) {
791                         global $wgUser;
792                         $user = $wgUser; 
793                 }
794
795                 $dbw = $this->repo->getMasterDB();
796                 $dbw->begin();
797
798                 if ( !$props ) {
799                         $props = $this->repo->getFileProps( $this->getVirtualUrl() );
800                 }
801                 $props['description'] = $comment;
802                 $props['user'] = $user->getId();
803                 $props['user_text'] = $user->getName();
804                 $props['timestamp'] = wfTimestamp( TS_MW );
805                 $this->setProps( $props );
806
807                 // Delete thumbnails and refresh the metadata cache
808                 $this->purgeThumbnails();
809                 $this->saveToCache();
810                 SquidUpdate::purge( array( $this->getURL() ) );
811
812                 // Fail now if the file isn't there
813                 if ( !$this->fileExists ) {
814                         wfDebug( __METHOD__ . ": File " . $this->getPath() . " went missing!\n" );
815                         return false;
816                 }
817
818                 $reupload = false;
819                 if ( $timestamp === false ) {
820                         $timestamp = $dbw->timestamp();
821                 }
822
823                 # Test to see if the row exists using INSERT IGNORE
824                 # This avoids race conditions by locking the row until the commit, and also
825                 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
826                 $dbw->insert( 'image',
827                         array(
828                                 'img_name' => $this->getName(),
829                                 'img_size'=> $this->size,
830                                 'img_width' => intval( $this->width ),
831                                 'img_height' => intval( $this->height ),
832                                 'img_bits' => $this->bits,
833                                 'img_media_type' => $this->media_type,
834                                 'img_major_mime' => $this->major_mime,
835                                 'img_minor_mime' => $this->minor_mime,
836                                 'img_timestamp' => $timestamp,
837                                 'img_description' => $comment,
838                                 'img_user' => $user->getId(),
839                                 'img_user_text' => $user->getName(),
840                                 'img_metadata' => $this->metadata,
841                                 'img_sha1' => $this->sha1
842                         ),
843                         __METHOD__,
844                         'IGNORE'
845                 );
846
847                 if( $dbw->affectedRows() == 0 ) {
848                         $reupload = true;
849
850                         # Collision, this is an update of a file
851                         # Insert previous contents into oldimage
852                         $dbw->insertSelect( 'oldimage', 'image',
853                                 array(
854                                         'oi_name' => 'img_name',
855                                         'oi_archive_name' => $dbw->addQuotes( $oldver ),
856                                         'oi_size' => 'img_size',
857                                         'oi_width' => 'img_width',
858                                         'oi_height' => 'img_height',
859                                         'oi_bits' => 'img_bits',
860                                         'oi_timestamp' => 'img_timestamp',
861                                         'oi_description' => 'img_description',
862                                         'oi_user' => 'img_user',
863                                         'oi_user_text' => 'img_user_text',
864                                         'oi_metadata' => 'img_metadata',
865                                         'oi_media_type' => 'img_media_type',
866                                         'oi_major_mime' => 'img_major_mime',
867                                         'oi_minor_mime' => 'img_minor_mime',
868                                         'oi_sha1' => 'img_sha1'
869                                 ), array( 'img_name' => $this->getName() ), __METHOD__
870                         );
871
872                         # Update the current image row
873                         $dbw->update( 'image',
874                                 array( /* SET */
875                                         'img_size' => $this->size,
876                                         'img_width' => intval( $this->width ),
877                                         'img_height' => intval( $this->height ),
878                                         'img_bits' => $this->bits,
879                                         'img_media_type' => $this->media_type,
880                                         'img_major_mime' => $this->major_mime,
881                                         'img_minor_mime' => $this->minor_mime,
882                                         'img_timestamp' => $timestamp,
883                                         'img_description' => $comment,
884                                         'img_user' => $user->getId(),
885                                         'img_user_text' => $user->getName(),
886                                         'img_metadata' => $this->metadata,
887                                         'img_sha1' => $this->sha1
888                                 ), array( /* WHERE */
889                                         'img_name' => $this->getName()
890                                 ), __METHOD__
891                         );
892                 } else {
893                         # This is a new file
894                         # Update the image count
895                         $site_stats = $dbw->tableName( 'site_stats' );
896                         $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
897                 }
898
899                 $descTitle = $this->getTitle();
900                 $article = new ImagePage( $descTitle );
901                 $article->setFile( $this );
902
903                 # Add the log entry
904                 $log = new LogPage( 'upload' );
905                 $action = $reupload ? 'overwrite' : 'upload';
906                 $log->addEntry( $action, $descTitle, $comment, array(), $user );
907
908                 if( $descTitle->exists() ) {
909                         # Create a null revision
910                         $latest = $descTitle->getLatestRevID();
911                         $nullRevision = Revision::newNullRevision( $dbw, $descTitle->getArticleId(),
912                                 $log->getRcComment(), false );
913                         $nullRevision->insertOn( $dbw );
914                         
915                         wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $user ) );
916                         $article->updateRevisionOn( $dbw, $nullRevision );
917
918                         # Invalidate the cache for the description page
919                         $descTitle->invalidateCache();
920                         $descTitle->purgeSquid();
921                 } else {
922                         // New file; create the description page.
923                         // There's already a log entry, so don't make a second RC entry
924                         $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC );
925                 }
926
927                 # Hooks, hooks, the magic of hooks...
928                 wfRunHooks( 'FileUpload', array( $this ) );
929
930                 # Commit the transaction now, in case something goes wrong later
931                 # The most important thing is that files don't get lost, especially archives
932                 $dbw->commit();
933
934                 # Invalidate cache for all pages using this file
935                 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
936                 $update->doUpdate();
937                 # Invalidate cache for all pages that redirects on this page
938                 $redirs = $this->getTitle()->getRedirectsHere();
939                 foreach( $redirs as $redir ) {
940                         $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
941                         $update->doUpdate();
942                 }
943
944                 return true;
945         }
946
947         /**
948          * Move or copy a file to its public location. If a file exists at the
949          * destination, move it to an archive. Returns the archive name on success
950          * or an empty string if it was a new file, and a wikitext-formatted
951          * WikiError object on failure.
952          *
953          * The archive name should be passed through to recordUpload for database
954          * registration.
955          *
956          * @param string $sourcePath Local filesystem path to the source image
957          * @param integer $flags A bitwise combination of:
958          *     File::DELETE_SOURCE    Delete the source file, i.e. move
959          *         rather than copy
960          * @return FileRepoStatus object. On success, the value member contains the
961          *     archive name, or an empty string if it was a new file.
962          */
963         function publish( $srcPath, $flags = 0 ) {
964                 $this->lock();
965                 $dstRel = $this->getRel();
966                 $archiveName = gmdate( 'YmdHis' ) . '!'. $this->getName();
967                 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
968                 $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
969                 $status = $this->repo->publish( $srcPath, $dstRel, $archiveRel, $flags );
970                 if ( $status->value == 'new' ) {
971                         $status->value = '';
972                 } else {
973                         $status->value = $archiveName;
974                 }
975                 $this->unlock();
976                 return $status;
977         }
978
979         /** getLinksTo inherited */
980         /** getExifData inherited */
981         /** isLocal inherited */
982         /** wasDeleted inherited */
983
984         /**
985          * Move file to the new title
986          *
987          * Move current, old version and all thumbnails
988          * to the new filename. Old file is deleted.
989          *
990          * Cache purging is done; checks for validity
991          * and logging are caller's responsibility
992          *
993          * @param $target Title New file name
994          * @return FileRepoStatus object.
995          */
996         function move( $target ) {
997                 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
998                 $this->lock();
999                 $batch = new LocalFileMoveBatch( $this, $target );
1000                 $batch->addCurrent();
1001                 $batch->addOlds();
1002
1003                 $status = $batch->execute();
1004                 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1005                 $this->purgeEverything();
1006                 $this->unlock();
1007
1008                 if ( $status->isOk() ) {
1009                         // Now switch the object
1010                         $this->title = $target;
1011                         // Force regeneration of the name and hashpath
1012                         unset( $this->name );
1013                         unset( $this->hashPath );
1014                         // Purge the new image
1015                         $this->purgeEverything();
1016                 }
1017                 
1018                 return $status;
1019         }
1020
1021         /**
1022          * Delete all versions of the file.
1023          *
1024          * Moves the files into an archive directory (or deletes them)
1025          * and removes the database rows.
1026          *
1027          * Cache purging is done; logging is caller's responsibility.
1028          *
1029          * @param $reason
1030          * @param $suppress
1031          * @return FileRepoStatus object.
1032          */
1033         function delete( $reason, $suppress = false ) {
1034                 $this->lock();
1035                 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1036                 $batch->addCurrent();
1037
1038                 # Get old version relative paths
1039                 $dbw = $this->repo->getMasterDB();
1040                 $result = $dbw->select( 'oldimage',
1041                         array( 'oi_archive_name' ),
1042                         array( 'oi_name' => $this->getName() ) );
1043                 while ( $row = $dbw->fetchObject( $result ) ) {
1044                         $batch->addOld( $row->oi_archive_name );
1045                 }
1046                 $status = $batch->execute();
1047
1048                 if ( $status->ok ) {
1049                         // Update site_stats
1050                         $site_stats = $dbw->tableName( 'site_stats' );
1051                         $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__ );
1052                         $this->purgeEverything();
1053                 }
1054
1055                 $this->unlock();
1056                 return $status;
1057         }
1058
1059         /**
1060          * Delete an old version of the file.
1061          *
1062          * Moves the file into an archive directory (or deletes it)
1063          * and removes the database row.
1064          *
1065          * Cache purging is done; logging is caller's responsibility.
1066          *
1067          * @param $reason
1068          * @param $suppress
1069          * @throws MWException or FSException on database or file store failure
1070          * @return FileRepoStatus object.
1071          */
1072         function deleteOld( $archiveName, $reason, $suppress=false ) {
1073                 $this->lock();
1074                 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1075                 $batch->addOld( $archiveName );
1076                 $status = $batch->execute();
1077                 $this->unlock();
1078                 if ( $status->ok ) {
1079                         $this->purgeDescription();
1080                         $this->purgeHistory();
1081                 }
1082                 return $status;
1083         }
1084
1085         /**
1086          * Restore all or specified deleted revisions to the given file.
1087          * Permissions and logging are left to the caller.
1088          *
1089          * May throw database exceptions on error.
1090          *
1091          * @param $versions set of record ids of deleted items to restore,
1092          *                    or empty to restore all revisions.
1093          * @param $unuppress
1094          * @return FileRepoStatus
1095          */
1096         function restore( $versions = array(), $unsuppress = false ) {
1097                 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1098                 if ( !$versions ) {
1099                         $batch->addAll();
1100                 } else {
1101                         $batch->addIds( $versions );
1102                 }
1103                 $status = $batch->execute();
1104                 if ( !$status->ok ) {
1105                         return $status;
1106                 }
1107
1108                 $cleanupStatus = $batch->cleanup();
1109                 $cleanupStatus->successCount = 0;
1110                 $cleanupStatus->failCount = 0;
1111                 $status->merge( $cleanupStatus );
1112                 return $status;
1113         }
1114
1115         /** isMultipage inherited */
1116         /** pageCount inherited */
1117         /** scaleHeight inherited */
1118         /** getImageSize inherited */
1119
1120         /**
1121          * Get the URL of the file description page.
1122          */
1123         function getDescriptionUrl() {
1124                 return $this->title->getLocalUrl();
1125         }
1126
1127         /**
1128          * Get the HTML text of the description page
1129          * This is not used by ImagePage for local files, since (among other things)
1130          * it skips the parser cache.
1131          */
1132         function getDescriptionText() {
1133                 global $wgParser;
1134                 $revision = Revision::newFromTitle( $this->title );
1135                 if ( !$revision ) return false;
1136                 $text = $revision->getText();
1137                 if ( !$text ) return false;
1138                 $pout = $wgParser->parse( $text, $this->title, new ParserOptions() );
1139                 return $pout->getText();
1140         }
1141
1142         function getDescription() {
1143                 $this->load();
1144                 return $this->description;
1145         }
1146
1147         function getTimestamp() {
1148                 $this->load();
1149                 return $this->timestamp;
1150         }
1151
1152         function getSha1() {
1153                 $this->load();
1154                 // Initialise now if necessary
1155                 if ( $this->sha1 == '' && $this->fileExists ) {
1156                         $this->sha1 = File::sha1Base36( $this->getPath() );
1157                         if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
1158                                 $dbw = $this->repo->getMasterDB();
1159                                 $dbw->update( 'image',
1160                                         array( 'img_sha1' => $this->sha1 ),
1161                                         array( 'img_name' => $this->getName() ),
1162                                         __METHOD__ );
1163                                 $this->saveToCache();
1164                         }
1165                 }
1166
1167                 return $this->sha1;
1168         }
1169
1170         /**
1171          * Start a transaction and lock the image for update
1172          * Increments a reference counter if the lock is already held
1173          * @return boolean True if the image exists, false otherwise
1174          */
1175         function lock() {
1176                 $dbw = $this->repo->getMasterDB();
1177                 if ( !$this->locked ) {
1178                         $dbw->begin();
1179                         $this->locked++;
1180                 }
1181                 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__ );
1182         }
1183
1184         /**
1185          * Decrement the lock reference count. If the reference count is reduced to zero, commits
1186          * the transaction and thereby releases the image lock.
1187          */
1188         function unlock() {
1189                 if ( $this->locked ) {
1190                         --$this->locked;
1191                         if ( !$this->locked ) {
1192                                 $dbw = $this->repo->getMasterDB();
1193                                 $dbw->commit();
1194                         }
1195                 }
1196         }
1197
1198         /**
1199          * Roll back the DB transaction and mark the image unlocked
1200          */
1201         function unlockAndRollback() {
1202                 $this->locked = false;
1203                 $dbw = $this->repo->getMasterDB();
1204                 $dbw->rollback();
1205         }
1206 } // LocalFile class
1207
1208 #------------------------------------------------------------------------------
1209
1210 /**
1211  * Helper class for file deletion
1212  * @ingroup FileRepo
1213  */
1214 class LocalFileDeleteBatch {
1215         var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1216         var $status;
1217
1218         function __construct( File $file, $reason = '', $suppress = false ) {
1219                 $this->file = $file;
1220                 $this->reason = $reason;
1221                 $this->suppress = $suppress;
1222                 $this->status = $file->repo->newGood();
1223         }
1224
1225         function addCurrent() {
1226                 $this->srcRels['.'] = $this->file->getRel();
1227         }
1228
1229         function addOld( $oldName ) {
1230                 $this->srcRels[$oldName] = $this->file->getArchiveRel( $oldName );
1231                 $this->archiveUrls[] = $this->file->getArchiveUrl( $oldName );
1232         }
1233
1234         function getOldRels() {
1235                 if ( !isset( $this->srcRels['.'] ) ) {
1236                         $oldRels =& $this->srcRels;
1237                         $deleteCurrent = false;
1238                 } else {
1239                         $oldRels = $this->srcRels;
1240                         unset( $oldRels['.'] );
1241                         $deleteCurrent = true;
1242                 }
1243                 return array( $oldRels, $deleteCurrent );
1244         }
1245
1246         /*protected*/ function getHashes() {
1247                 $hashes = array();
1248                 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1249                 if ( $deleteCurrent ) {
1250                         $hashes['.'] = $this->file->getSha1();
1251                 }
1252                 if ( count( $oldRels ) ) {
1253                         $dbw = $this->file->repo->getMasterDB();
1254                         $res = $dbw->select( 'oldimage', array( 'oi_archive_name', 'oi_sha1' ),
1255                                 'oi_archive_name IN(' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1256                                 __METHOD__ );
1257                         while ( $row = $dbw->fetchObject( $res ) ) {
1258                                 if ( rtrim( $row->oi_sha1, "\0" ) === '' ) {
1259                                         // Get the hash from the file
1260                                         $oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
1261                                         $props = $this->file->repo->getFileProps( $oldUrl );
1262                                         if ( $props['fileExists'] ) {
1263                                                 // Upgrade the oldimage row
1264                                                 $dbw->update( 'oldimage',
1265                                                         array( 'oi_sha1' => $props['sha1'] ),
1266                                                         array( 'oi_name' => $this->file->getName(), 'oi_archive_name' => $row->oi_archive_name ),
1267                                                         __METHOD__ );
1268                                                 $hashes[$row->oi_archive_name] = $props['sha1'];
1269                                         } else {
1270                                                 $hashes[$row->oi_archive_name] = false;
1271                                         }
1272                                 } else {
1273                                         $hashes[$row->oi_archive_name] = $row->oi_sha1;
1274                                 }
1275                         }
1276                 }
1277                 $missing = array_diff_key( $this->srcRels, $hashes );
1278                 foreach ( $missing as $name => $rel ) {
1279                         $this->status->error( 'filedelete-old-unregistered', $name );
1280                 }
1281                 foreach ( $hashes as $name => $hash ) {
1282                         if ( !$hash ) {
1283                                 $this->status->error( 'filedelete-missing', $this->srcRels[$name] );
1284                                 unset( $hashes[$name] );
1285                         }
1286                 }
1287
1288                 return $hashes;
1289         }
1290
1291         function doDBInserts() {
1292                 global $wgUser;
1293                 $dbw = $this->file->repo->getMasterDB();
1294                 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1295                 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1296                 $encReason = $dbw->addQuotes( $this->reason );
1297                 $encGroup = $dbw->addQuotes( 'deleted' );
1298                 $ext = $this->file->getExtension();
1299                 $dotExt = $ext === '' ? '' : ".$ext";
1300                 $encExt = $dbw->addQuotes( $dotExt );
1301                 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1302
1303                 // Bitfields to further suppress the content
1304                 if ( $this->suppress ) {
1305                         $bitfield = 0;
1306                         // This should be 15...
1307                         $bitfield |= Revision::DELETED_TEXT;
1308                         $bitfield |= Revision::DELETED_COMMENT;
1309                         $bitfield |= Revision::DELETED_USER;
1310                         $bitfield |= Revision::DELETED_RESTRICTED;
1311                 } else {
1312                         $bitfield = 'oi_deleted';
1313                 }
1314
1315                 if ( $deleteCurrent ) {
1316                         $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1317                         $where = array( 'img_name' => $this->file->getName() );
1318                         $dbw->insertSelect( 'filearchive', 'image',
1319                                 array(
1320                                         'fa_storage_group' => $encGroup,
1321                                         'fa_storage_key'   => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1322                                         'fa_deleted_user'      => $encUserId,
1323                                         'fa_deleted_timestamp' => $encTimestamp,
1324                                         'fa_deleted_reason'    => $encReason,
1325                                         'fa_deleted'               => $this->suppress ? $bitfield : 0,
1326
1327                                         'fa_name'         => 'img_name',
1328                                         'fa_archive_name' => 'NULL',
1329                                         'fa_size'         => 'img_size',
1330                                         'fa_width'        => 'img_width',
1331                                         'fa_height'       => 'img_height',
1332                                         'fa_metadata'     => 'img_metadata',
1333                                         'fa_bits'         => 'img_bits',
1334                                         'fa_media_type'   => 'img_media_type',
1335                                         'fa_major_mime'   => 'img_major_mime',
1336                                         'fa_minor_mime'   => 'img_minor_mime',
1337                                         'fa_description'  => 'img_description',
1338                                         'fa_user'         => 'img_user',
1339                                         'fa_user_text'    => 'img_user_text',
1340                                         'fa_timestamp'    => 'img_timestamp'
1341                                 ), $where, __METHOD__ );
1342                 }
1343
1344                 if ( count( $oldRels ) ) {
1345                         $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1346                         $where = array(
1347                                 'oi_name' => $this->file->getName(),
1348                                 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1349                         $dbw->insertSelect( 'filearchive', 'oldimage',
1350                                 array(
1351                                         'fa_storage_group' => $encGroup,
1352                                         'fa_storage_key'   => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1353                                         'fa_deleted_user'      => $encUserId,
1354                                         'fa_deleted_timestamp' => $encTimestamp,
1355                                         'fa_deleted_reason'    => $encReason,
1356                                         'fa_deleted'               => $this->suppress ? $bitfield : 'oi_deleted',
1357
1358                                         'fa_name'         => 'oi_name',
1359                                         'fa_archive_name' => 'oi_archive_name',
1360                                         'fa_size'         => 'oi_size',
1361                                         'fa_width'        => 'oi_width',
1362                                         'fa_height'       => 'oi_height',
1363                                         'fa_metadata'     => 'oi_metadata',
1364                                         'fa_bits'         => 'oi_bits',
1365                                         'fa_media_type'   => 'oi_media_type',
1366                                         'fa_major_mime'   => 'oi_major_mime',
1367                                         'fa_minor_mime'   => 'oi_minor_mime',
1368                                         'fa_description'  => 'oi_description',
1369                                         'fa_user'         => 'oi_user',
1370                                         'fa_user_text'    => 'oi_user_text',
1371                                         'fa_timestamp'    => 'oi_timestamp',
1372                                         'fa_deleted'      => $bitfield
1373                                 ), $where, __METHOD__ );
1374                 }
1375         }
1376
1377         function doDBDeletes() {
1378                 $dbw = $this->file->repo->getMasterDB();
1379                 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1380                 if ( count( $oldRels ) ) {
1381                         $dbw->delete( 'oldimage',
1382                                 array(
1383                                         'oi_name' => $this->file->getName(),
1384                                         'oi_archive_name' => array_keys( $oldRels )
1385                                 ), __METHOD__ );
1386                 }
1387                 if ( $deleteCurrent ) {
1388                         $dbw->delete( 'image', array( 'img_name' => $this->file->getName() ), __METHOD__ );
1389                 }
1390         }
1391
1392         /**
1393          * Run the transaction
1394          */
1395         function execute() {
1396                 global $wgUseSquid;
1397                 wfProfileIn( __METHOD__ );
1398
1399                 $this->file->lock();
1400                 // Leave private files alone
1401                 $privateFiles = array();
1402                 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1403                 $dbw = $this->file->repo->getMasterDB();
1404                 if( !empty( $oldRels ) ) {
1405                         $res = $dbw->select( 'oldimage',
1406                                 array( 'oi_archive_name' ),
1407                                 array( 'oi_name' => $this->file->getName(),
1408                                         'oi_archive_name IN (' . $dbw->makeList( array_keys($oldRels) ) . ')',
1409                                         $dbw->bitAnd('oi_deleted', File::DELETED_FILE) => File::DELETED_FILE ),
1410                                 __METHOD__ );
1411                         while( $row = $dbw->fetchObject( $res ) ) {
1412                                 $privateFiles[$row->oi_archive_name] = 1;
1413                         }
1414                 }
1415                 // Prepare deletion batch
1416                 $hashes = $this->getHashes();
1417                 $this->deletionBatch = array();
1418                 $ext = $this->file->getExtension();
1419                 $dotExt = $ext === '' ? '' : ".$ext";
1420                 foreach ( $this->srcRels as $name => $srcRel ) {
1421                         // Skip files that have no hash (missing source).
1422                         // Keep private files where they are.
1423                         if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1424                                 $hash = $hashes[$name];
1425                                 $key = $hash . $dotExt;
1426                                 $dstRel = $this->file->repo->getDeletedHashPath( $key ) . $key;
1427                                 $this->deletionBatch[$name] = array( $srcRel, $dstRel );
1428                         }
1429                 }
1430
1431                 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1432                 // We acquire this lock by running the inserts now, before the file operations.
1433                 //
1434                 // This potentially has poor lock contention characteristics -- an alternative
1435                 // scheme would be to insert stub filearchive entries with no fa_name and commit
1436                 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1437                 $this->doDBInserts();
1438
1439                 // Removes non-existent file from the batch, so we don't get errors.
1440                 $this->deletionBatch = $this->removeNonexistentFiles( $this->deletionBatch );
1441
1442                 // Execute the file deletion batch
1443                 $status = $this->file->repo->deleteBatch( $this->deletionBatch );
1444                 if ( !$status->isGood() ) {
1445                         $this->status->merge( $status );
1446                 }
1447
1448                 if ( !$this->status->ok ) {
1449                         // Critical file deletion error
1450                         // Roll back inserts, release lock and abort
1451                         // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1452                         $this->file->unlockAndRollback();
1453                         wfProfileOut( __METHOD__ );
1454                         return $this->status;
1455                 }
1456
1457                 // Purge squid
1458                 if ( $wgUseSquid ) {
1459                         $urls = array();
1460                         foreach ( $this->srcRels as $srcRel ) {
1461                                 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1462                                 $urls[] = $this->file->repo->getZoneUrl( 'public' ) . '/' . $urlRel;
1463                         }
1464                         SquidUpdate::purge( $urls );
1465                 }
1466
1467                 // Delete image/oldimage rows
1468                 $this->doDBDeletes();
1469
1470                 // Commit and return
1471                 $this->file->unlock();
1472                 wfProfileOut( __METHOD__ );
1473                 return $this->status;
1474         }
1475
1476         /**
1477          * Removes non-existent files from a deletion batch.
1478          */
1479         function removeNonexistentFiles( $batch ) {
1480                 $files = $newBatch = array();
1481                 foreach( $batch as $batchItem ) {
1482                         list( $src, $dest ) = $batchItem;
1483                         $files[$src] = $this->file->repo->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1484                 }
1485                 $result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
1486                 foreach( $batch as $batchItem )
1487                         if( $result[$batchItem[0]] )
1488                                 $newBatch[] = $batchItem;
1489                 return $newBatch;
1490         }
1491 }
1492
1493 #------------------------------------------------------------------------------
1494
1495 /**
1496  * Helper class for file undeletion
1497  * @ingroup FileRepo
1498  */
1499 class LocalFileRestoreBatch {
1500         var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1501
1502         function __construct( File $file, $unsuppress = false ) {
1503                 $this->file = $file;
1504                 $this->cleanupBatch = $this->ids = array();
1505                 $this->ids = array();
1506                 $this->unsuppress = $unsuppress;
1507         }
1508
1509         /**
1510          * Add a file by ID
1511          */
1512         function addId( $fa_id ) {
1513                 $this->ids[] = $fa_id;
1514         }
1515
1516         /**
1517          * Add a whole lot of files by ID
1518          */
1519         function addIds( $ids ) {
1520                 $this->ids = array_merge( $this->ids, $ids );
1521         }
1522
1523         /**
1524          * Add all revisions of the file
1525          */
1526         function addAll() {
1527                 $this->all = true;
1528         }
1529
1530         /**
1531          * Run the transaction, except the cleanup batch.
1532          * The cleanup batch should be run in a separate transaction, because it locks different
1533          * rows and there's no need to keep the image row locked while it's acquiring those locks
1534          * The caller may have its own transaction open.
1535          * So we save the batch and let the caller call cleanup()
1536          */
1537         function execute() {
1538                 global $wgLang;
1539                 if ( !$this->all && !$this->ids ) {
1540                         // Do nothing
1541                         return $this->file->repo->newGood();
1542                 }
1543
1544                 $exists = $this->file->lock();
1545                 $dbw = $this->file->repo->getMasterDB();
1546                 $status = $this->file->repo->newGood();
1547
1548                 // Fetch all or selected archived revisions for the file,
1549                 // sorted from the most recent to the oldest.
1550                 $conditions = array( 'fa_name' => $this->file->getName() );
1551                 if( !$this->all ) {
1552                         $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids ) . ')';
1553                 }
1554
1555                 $result = $dbw->select( 'filearchive', '*',
1556                         $conditions,
1557                         __METHOD__,
1558                         array( 'ORDER BY' => 'fa_timestamp DESC' )
1559                 );
1560
1561                 $idsPresent = array();
1562                 $storeBatch = array();
1563                 $insertBatch = array();
1564                 $insertCurrent = false;
1565                 $deleteIds = array();
1566                 $first = true;
1567                 $archiveNames = array();
1568                 while( $row = $dbw->fetchObject( $result ) ) {
1569                         $idsPresent[] = $row->fa_id;
1570
1571                         if ( $row->fa_name != $this->file->getName() ) {
1572                                 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
1573                                 $status->failCount++;
1574                                 continue;
1575                         }
1576                         if ( $row->fa_storage_key == '' ) {
1577                                 // Revision was missing pre-deletion
1578                                 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
1579                                 $status->failCount++;
1580                                 continue;
1581                         }
1582
1583                         $deletedRel = $this->file->repo->getDeletedHashPath( $row->fa_storage_key ) . $row->fa_storage_key;
1584                         $deletedUrl = $this->file->repo->getVirtualUrl() . '/deleted/' . $deletedRel;
1585
1586                         $sha1 = substr( $row->fa_storage_key, 0, strcspn( $row->fa_storage_key, '.' ) );
1587                         # Fix leading zero
1588                         if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1589                                 $sha1 = substr( $sha1, 1 );
1590                         }
1591
1592                         if( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
1593                                 || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime == 'unknown'
1594                                 || is_null( $row->fa_media_type ) || $row->fa_media_type == 'UNKNOWN'
1595                                 || is_null( $row->fa_metadata ) ) {
1596                                 // Refresh our metadata
1597                                 // Required for a new current revision; nice for older ones too. :)
1598                                 $props = RepoGroup::singleton()->getFileProps( $deletedUrl );
1599                         } else {
1600                                 $props = array(
1601                                         'minor_mime' => $row->fa_minor_mime,
1602                                         'major_mime' => $row->fa_major_mime,
1603                                         'media_type' => $row->fa_media_type,
1604                                         'metadata'   => $row->fa_metadata
1605                                 );
1606                         }
1607
1608                         if ( $first && !$exists ) {
1609                                 // This revision will be published as the new current version
1610                                 $destRel = $this->file->getRel();
1611                                 $insertCurrent = array(
1612                                         'img_name'        => $row->fa_name,
1613                                         'img_size'        => $row->fa_size,
1614                                         'img_width'       => $row->fa_width,
1615                                         'img_height'      => $row->fa_height,
1616                                         'img_metadata'    => $props['metadata'],
1617                                         'img_bits'        => $row->fa_bits,
1618                                         'img_media_type'  => $props['media_type'],
1619                                         'img_major_mime'  => $props['major_mime'],
1620                                         'img_minor_mime'  => $props['minor_mime'],
1621                                         'img_description' => $row->fa_description,
1622                                         'img_user'        => $row->fa_user,
1623                                         'img_user_text'   => $row->fa_user_text,
1624                                         'img_timestamp'   => $row->fa_timestamp,
1625                                         'img_sha1'        => $sha1
1626                                 );
1627                                 // The live (current) version cannot be hidden!
1628                                 if( !$this->unsuppress && $row->fa_deleted ) {
1629                                         $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1630                                         $this->cleanupBatch[] = $row->fa_storage_key;
1631                                 }
1632                         } else {
1633                                 $archiveName = $row->fa_archive_name;
1634                                 if( $archiveName == '' ) {
1635                                         // This was originally a current version; we
1636                                         // have to devise a new archive name for it.
1637                                         // Format is <timestamp of archiving>!<name>
1638                                         $timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
1639                                         do {
1640                                                 $archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
1641                                                 $timestamp++;
1642                                         } while ( isset( $archiveNames[$archiveName] ) );
1643                                 }
1644                                 $archiveNames[$archiveName] = true;
1645                                 $destRel = $this->file->getArchiveRel( $archiveName );
1646                                 $insertBatch[] = array(
1647                                         'oi_name'         => $row->fa_name,
1648                                         'oi_archive_name' => $archiveName,
1649                                         'oi_size'         => $row->fa_size,
1650                                         'oi_width'        => $row->fa_width,
1651                                         'oi_height'       => $row->fa_height,
1652                                         'oi_bits'         => $row->fa_bits,
1653                                         'oi_description'  => $row->fa_description,
1654                                         'oi_user'         => $row->fa_user,
1655                                         'oi_user_text'    => $row->fa_user_text,
1656                                         'oi_timestamp'    => $row->fa_timestamp,
1657                                         'oi_metadata'     => $props['metadata'],
1658                                         'oi_media_type'   => $props['media_type'],
1659                                         'oi_major_mime'   => $props['major_mime'],
1660                                         'oi_minor_mime'   => $props['minor_mime'],
1661                                         'oi_deleted'      => $this->unsuppress ? 0 : $row->fa_deleted,
1662                                         'oi_sha1'         => $sha1 );
1663                         }
1664
1665                         $deleteIds[] = $row->fa_id;
1666                         if( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
1667                                 // private files can stay where they are
1668                                 $status->successCount++;
1669                         } else {
1670                                 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1671                                 $this->cleanupBatch[] = $row->fa_storage_key;
1672                         }
1673                         $first = false;
1674                 }
1675                 unset( $result );
1676
1677                 // Add a warning to the status object for missing IDs
1678                 $missingIds = array_diff( $this->ids, $idsPresent );
1679                 foreach ( $missingIds as $id ) {
1680                         $status->error( 'undelete-missing-filearchive', $id );
1681                 }
1682
1683                 // Remove missing files from batch, so we don't get errors when undeleting them
1684                 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
1685
1686                 // Run the store batch
1687                 // Use the OVERWRITE_SAME flag to smooth over a common error
1688                 $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
1689                 $status->merge( $storeStatus );
1690
1691                 if ( !$status->ok ) {
1692                         // Store batch returned a critical error -- this usually means nothing was stored
1693                         // Stop now and return an error
1694                         $this->file->unlock();
1695                         return $status;
1696                 }
1697
1698                 // Run the DB updates
1699                 // Because we have locked the image row, key conflicts should be rare.
1700                 // If they do occur, we can roll back the transaction at this time with
1701                 // no data loss, but leaving unregistered files scattered throughout the
1702                 // public zone.
1703                 // This is not ideal, which is why it's important to lock the image row.
1704                 if ( $insertCurrent ) {
1705                         $dbw->insert( 'image', $insertCurrent, __METHOD__ );
1706                 }
1707                 if ( $insertBatch ) {
1708                         $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
1709                 }
1710                 if ( $deleteIds ) {
1711                         $dbw->delete( 'filearchive',
1712                                 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1713                                 __METHOD__ );
1714                 }
1715
1716                 // If store batch is empty (all files are missing), deletion is to be considered successful
1717                 if( $status->successCount > 0 || !$storeBatch ) {
1718                         if( !$exists ) {
1719                                 wfDebug( __METHOD__ . " restored {$status->successCount} items, creating a new current\n" );
1720
1721                                 // Update site_stats
1722                                 $site_stats = $dbw->tableName( 'site_stats' );
1723                                 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
1724
1725                                 $this->file->purgeEverything();
1726                         } else {
1727                                 wfDebug( __METHOD__ . " restored {$status->successCount} as archived versions\n" );
1728                                 $this->file->purgeDescription();
1729                                 $this->file->purgeHistory();
1730                         }
1731                 }
1732                 $this->file->unlock();
1733                 return $status;
1734         }
1735
1736         /**
1737          * Removes non-existent files from a store batch.
1738          */
1739         function removeNonexistentFiles( $triplets ) {
1740                 $files = $filteredTriplets = array();
1741                 foreach( $triplets as $file )
1742                         $files[$file[0]] = $file[0];
1743                 $result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
1744                 foreach( $triplets as $file )
1745                         if( $result[$file[0]] )
1746                                 $filteredTriplets[] = $file;
1747                 return $filteredTriplets;
1748         }
1749
1750         /**
1751          * Removes non-existent files from a cleanup batch.
1752          */
1753         function removeNonexistentFromCleanup( $batch ) {
1754                 $files = $newBatch = array();
1755                 $repo = $this->file->repo;
1756                 foreach( $batch as $file ) {
1757                         $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
1758                                 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
1759                 }
1760
1761                 $result = $repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
1762                 foreach( $batch as $file )
1763                         if( $result[$file] )
1764                                 $newBatch[] = $file;
1765                 return $newBatch;
1766         }
1767
1768         /**
1769          * Delete unused files in the deleted zone.
1770          * This should be called from outside the transaction in which execute() was called.
1771          */
1772         function cleanup() {
1773                 if ( !$this->cleanupBatch ) {
1774                         return $this->file->repo->newGood();
1775                 }
1776                 $this->cleanupBatch = $this->removeNonexistentFromCleanup( $this->cleanupBatch );
1777                 $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
1778                 return $status;
1779         }
1780 }
1781
1782 #------------------------------------------------------------------------------
1783
1784 /**
1785  * Helper class for file movement
1786  * @ingroup FileRepo
1787  */
1788 class LocalFileMoveBatch {
1789         var $file, $cur, $olds, $oldCount, $archive, $target, $db;
1790
1791         function __construct( File $file, Title $target ) {
1792                 $this->file = $file;
1793                 $this->target = $target;
1794                 $this->oldHash = $this->file->repo->getHashPath( $this->file->getName() );
1795                 $this->newHash = $this->file->repo->getHashPath( $this->target->getDBkey() );
1796                 $this->oldName = $this->file->getName();
1797                 $this->newName = $this->file->repo->getNameFromTitle( $this->target );
1798                 $this->oldRel = $this->oldHash . $this->oldName;
1799                 $this->newRel = $this->newHash . $this->newName;
1800                 $this->db = $file->repo->getMasterDb();
1801         }
1802
1803         /**
1804          * Add the current image to the batch
1805          */
1806         function addCurrent() {
1807                 $this->cur = array( $this->oldRel, $this->newRel );
1808         }
1809
1810         /**
1811          * Add the old versions of the image to the batch
1812          */
1813         function addOlds() {
1814                 $archiveBase = 'archive';
1815                 $this->olds = array();
1816                 $this->oldCount = 0;
1817
1818                 $result = $this->db->select( 'oldimage',
1819                         array( 'oi_archive_name', 'oi_deleted' ),
1820                         array( 'oi_name' => $this->oldName ),
1821                         __METHOD__
1822                 );
1823                 while( $row = $this->db->fetchObject( $result ) ) {
1824                         $oldName = $row->oi_archive_name;
1825                         $bits = explode( '!', $oldName, 2 );
1826                         if( count( $bits ) != 2 ) {
1827                                 wfDebug( "Invalid old file name: $oldName \n" );
1828                                 continue;
1829                         }
1830                         list( $timestamp, $filename ) = $bits;
1831                         if( $this->oldName != $filename ) {
1832                                 wfDebug( "Invalid old file name: $oldName \n" );
1833                                 continue;
1834                         }
1835                         $this->oldCount++;
1836                         // Do we want to add those to oldCount?
1837                         if( $row->oi_deleted & File::DELETED_FILE ) {
1838                                 continue;
1839                         }
1840                         $this->olds[] = array(
1841                                 "{$archiveBase}/{$this->oldHash}{$oldName}",
1842                                 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
1843                         );
1844                 }
1845                 $this->db->freeResult( $result );
1846         }
1847
1848         /**
1849          * Perform the move.
1850          */
1851         function execute() {
1852                 $repo = $this->file->repo;
1853                 $status = $repo->newGood();
1854                 $triplets = $this->getMoveTriplets();
1855
1856                 $triplets = $this->removeNonexistentFiles( $triplets );
1857                 $statusDb = $this->doDBUpdates();
1858                 wfDebugLog( 'imagemove', "Renamed {$this->file->name} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
1859                 $statusMove = $repo->storeBatch( $triplets, FSRepo::DELETE_SOURCE );
1860                 wfDebugLog( 'imagemove', "Moved files for {$this->file->name}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
1861                 if( !$statusMove->isOk() ) {
1862                         wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
1863                         $this->db->rollback();
1864                 }
1865
1866                 $status->merge( $statusDb );
1867                 $status->merge( $statusMove );
1868                 return $status;
1869         }
1870
1871         /**
1872          * Do the database updates and return a new WikiError indicating how many
1873          * rows where updated.
1874          */
1875         function doDBUpdates() {
1876                 $repo = $this->file->repo;
1877                 $status = $repo->newGood();
1878                 $dbw = $this->db;
1879
1880                 // Update current image
1881                 $dbw->update( 
1882                         'image',
1883                         array( 'img_name' => $this->newName ),
1884                         array( 'img_name' => $this->oldName ),
1885                         __METHOD__
1886                 );
1887                 if( $dbw->affectedRows() ) {
1888                         $status->successCount++;
1889                 } else {
1890                         $status->failCount++;
1891                 }
1892
1893                 // Update old images
1894                 $dbw->update(
1895                         'oldimage',
1896                         array(
1897                                 'oi_name' => $this->newName,
1898                                 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes($this->oldName), $dbw->addQuotes($this->newName) ),
1899                         ),
1900                         array( 'oi_name' => $this->oldName ),
1901                         __METHOD__
1902                 );
1903                 $affected = $dbw->affectedRows();
1904                 $total = $this->oldCount;
1905                 $status->successCount += $affected;
1906                 $status->failCount += $total - $affected;
1907
1908                 return $status;
1909         }
1910
1911         /**
1912          * Generate triplets for FSRepo::storeBatch().
1913          */ 
1914         function getMoveTriplets() {
1915                 $moves = array_merge( array( $this->cur ), $this->olds );
1916                 $triplets = array();    // The format is: (srcUrl, destZone, destUrl)
1917                 foreach( $moves as $move ) {
1918                         // $move: (oldRelativePath, newRelativePath)
1919                         $srcUrl = $this->file->repo->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
1920                         $triplets[] = array( $srcUrl, 'public', $move[1] );
1921                         wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->name}: {$srcUrl} :: public :: {$move[1]}" );
1922                 }
1923                 return $triplets;
1924         }
1925
1926         /**
1927          * Removes non-existent files from move batch.
1928          */ 
1929         function removeNonexistentFiles( $triplets ) {
1930                 $files = array();
1931                 foreach( $triplets as $file )
1932                         $files[$file[0]] = $file[0];
1933                 $result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
1934                 $filteredTriplets = array();
1935                 foreach( $triplets as $file )
1936                         if( $result[$file[0]] ) {
1937                                 $filteredTriplets[] = $file;
1938                         } else {
1939                                 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
1940                         }
1941                 return $filteredTriplets;
1942         }
1943 }