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