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