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