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