WARNING: HUGE COMMIT
[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 wfRunHooks( 'newRevisionFromEditComplete', array($descTitle, $nullRevision, false) );
883 $article->updateRevisionOn( $dbw, $nullRevision );
884
885 # Invalidate the cache for the description page
886 $descTitle->invalidateCache();
887 $descTitle->purgeSquid();
888 } else {
889 // New file; create the description page.
890 // There's already a log entry, so don't make a second RC entry
891 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC );
892 }
893
894 # Hooks, hooks, the magic of hooks...
895 wfRunHooks( 'FileUpload', array( $this ) );
896
897 # Commit the transaction now, in case something goes wrong later
898 # The most important thing is that files don't get lost, especially archives
899 $dbw->immediateCommit();
900
901 # Invalidate cache for all pages using this file
902 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
903 $update->doUpdate();
904 # Invalidate cache for all pages that redirects on this page
905 $redirs = $this->getTitle()->getRedirectsHere();
906 foreach( $redirs as $redir ) {
907 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
908 $update->doUpdate();
909 }
910
911 return true;
912 }
913
914 /**
915 * Move or copy a file to its public location. If a file exists at the
916 * destination, move it to an archive. Returns the archive name on success
917 * or an empty string if it was a new file, and a wikitext-formatted
918 * WikiError object on failure.
919 *
920 * The archive name should be passed through to recordUpload for database
921 * registration.
922 *
923 * @param string $sourcePath Local filesystem path to the source image
924 * @param integer $flags A bitwise combination of:
925 * File::DELETE_SOURCE Delete the source file, i.e. move
926 * rather than copy
927 * @return FileRepoStatus object. On success, the value member contains the
928 * archive name, or an empty string if it was a new file.
929 */
930 function publish( $srcPath, $flags = 0 ) {
931 $this->lock();
932 $dstRel = $this->getRel();
933 $archiveName = gmdate( 'YmdHis' ) . '!'. $this->getName();
934 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
935 $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
936 $status = $this->repo->publish( $srcPath, $dstRel, $archiveRel, $flags );
937 if ( $status->value == 'new' ) {
938 $status->value = '';
939 } else {
940 $status->value = $archiveName;
941 }
942 $this->unlock();
943 return $status;
944 }
945
946 /** getLinksTo inherited */
947 /** getExifData inherited */
948 /** isLocal inherited */
949 /** wasDeleted inherited */
950
951 /**
952 * Move file to the new title
953 *
954 * Move current, old version and all thumbnails
955 * to the new filename. Old file is deleted.
956 *
957 * Cache purging is done; checks for validity
958 * and logging are caller's responsibility
959 *
960 * @param $target Title New file name
961 * @return FileRepoStatus object.
962 */
963 function move( $target ) {
964 $this->lock();
965 $dbw = $this->repo->getMasterDB();
966 $batch = new LocalFileMoveBatch( $this, $target, $dbw );
967 $batch->addCurrent();
968 $batch->addOlds();
969 if( !$this->repo->canTransformVia404() ) {
970 $batch->addThumbs();
971 }
972
973 $status = $batch->execute();
974 $this->purgeEverything();
975 $this->unlock();
976
977 if ( $status->isOk() ) {
978 // Now switch the object
979 $this->title = $target;
980 // Force regeneration of the name and hashpath
981 unset( $this->name );
982 unset( $this->hashPath );
983 // Purge the new image
984 $this->purgeEverything();
985 }
986
987 return $status;
988 }
989
990 /**
991 * Delete all versions of the file.
992 *
993 * Moves the files into an archive directory (or deletes them)
994 * and removes the database rows.
995 *
996 * Cache purging is done; logging is caller's responsibility.
997 *
998 * @param $reason
999 * @param $suppress
1000 * @return FileRepoStatus object.
1001 */
1002 function delete( $reason, $suppress = false ) {
1003 $this->lock();
1004 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1005 $batch->addCurrent();
1006
1007 # Get old version relative paths
1008 $dbw = $this->repo->getMasterDB();
1009 $result = $dbw->select( 'oldimage',
1010 array( 'oi_archive_name' ),
1011 array( 'oi_name' => $this->getName() ) );
1012 while ( $row = $dbw->fetchObject( $result ) ) {
1013 $batch->addOld( $row->oi_archive_name );
1014 }
1015 $status = $batch->execute();
1016
1017 if ( $status->ok ) {
1018 // Update site_stats
1019 $site_stats = $dbw->tableName( 'site_stats' );
1020 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__ );
1021 $this->purgeEverything();
1022 }
1023
1024 $this->unlock();
1025 return $status;
1026 }
1027
1028 /**
1029 * Delete an old version of the file.
1030 *
1031 * Moves the file into an archive directory (or deletes it)
1032 * and removes the database row.
1033 *
1034 * Cache purging is done; logging is caller's responsibility.
1035 *
1036 * @param $reason
1037 * @param $suppress
1038 * @throws MWException or FSException on database or filestore failure
1039 * @return FileRepoStatus object.
1040 */
1041 function deleteOld( $archiveName, $reason, $suppress=false ) {
1042 $this->lock();
1043 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1044 $batch->addOld( $archiveName );
1045 $status = $batch->execute();
1046 $this->unlock();
1047 if ( $status->ok ) {
1048 $this->purgeDescription();
1049 $this->purgeHistory();
1050 }
1051 return $status;
1052 }
1053
1054 /**
1055 * Restore all or specified deleted revisions to the given file.
1056 * Permissions and logging are left to the caller.
1057 *
1058 * May throw database exceptions on error.
1059 *
1060 * @param $versions set of record ids of deleted items to restore,
1061 * or empty to restore all revisions.
1062 * @param $unuppress
1063 * @return FileRepoStatus
1064 */
1065 function restore( $versions = array(), $unsuppress = false ) {
1066 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1067 if ( !$versions ) {
1068 $batch->addAll();
1069 } else {
1070 $batch->addIds( $versions );
1071 }
1072 $status = $batch->execute();
1073 if ( !$status->ok ) {
1074 return $status;
1075 }
1076
1077 $cleanupStatus = $batch->cleanup();
1078 $cleanupStatus->successCount = 0;
1079 $cleanupStatus->failCount = 0;
1080 $status->merge( $cleanupStatus );
1081 return $status;
1082 }
1083
1084 /** isMultipage inherited */
1085 /** pageCount inherited */
1086 /** scaleHeight inherited */
1087 /** getImageSize inherited */
1088
1089 /**
1090 * Get the URL of the file description page.
1091 */
1092 function getDescriptionUrl() {
1093 return $this->title->getLocalUrl();
1094 }
1095
1096 /**
1097 * Get the HTML text of the description page
1098 * This is not used by ImagePage for local files, since (among other things)
1099 * it skips the parser cache.
1100 */
1101 function getDescriptionText() {
1102 global $wgParser;
1103 $revision = Revision::newFromTitle( $this->title );
1104 if ( !$revision ) return false;
1105 $text = $revision->getText();
1106 if ( !$text ) return false;
1107 $html = $wgParser->parse( $text, new ParserOptions );
1108 return $html;
1109 }
1110
1111 function getDescription() {
1112 $this->load();
1113 return $this->description;
1114 }
1115
1116 function getTimestamp() {
1117 $this->load();
1118 return $this->timestamp;
1119 }
1120
1121 function getSha1() {
1122 $this->load();
1123 // Initialise now if necessary
1124 if ( $this->sha1 == '' && $this->fileExists ) {
1125 $this->sha1 = File::sha1Base36( $this->getPath() );
1126 if ( strval( $this->sha1 ) != '' ) {
1127 $dbw = $this->repo->getMasterDB();
1128 $dbw->update( 'image',
1129 array( 'img_sha1' => $this->sha1 ),
1130 array( 'img_name' => $this->getName() ),
1131 __METHOD__ );
1132 $this->saveToCache();
1133 }
1134 }
1135
1136 return $this->sha1;
1137 }
1138
1139 /**
1140 * Start a transaction and lock the image for update
1141 * Increments a reference counter if the lock is already held
1142 * @return boolean True if the image exists, false otherwise
1143 */
1144 function lock() {
1145 $dbw = $this->repo->getMasterDB();
1146 if ( !$this->locked ) {
1147 $dbw->begin();
1148 $this->locked++;
1149 }
1150 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__ );
1151 }
1152
1153 /**
1154 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1155 * the transaction and thereby releases the image lock.
1156 */
1157 function unlock() {
1158 if ( $this->locked ) {
1159 --$this->locked;
1160 if ( !$this->locked ) {
1161 $dbw = $this->repo->getMasterDB();
1162 $dbw->commit();
1163 }
1164 }
1165 }
1166
1167 /**
1168 * Roll back the DB transaction and mark the image unlocked
1169 */
1170 function unlockAndRollback() {
1171 $this->locked = false;
1172 $dbw = $this->repo->getMasterDB();
1173 $dbw->rollback();
1174 }
1175 } // LocalFile class
1176
1177 #------------------------------------------------------------------------------
1178
1179 /**
1180 * Helper class for file deletion
1181 * @ingroup FileRepo
1182 */
1183 class LocalFileDeleteBatch {
1184 var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1185 var $status;
1186
1187 function __construct( File $file, $reason = '', $suppress = false ) {
1188 $this->file = $file;
1189 $this->reason = $reason;
1190 $this->suppress = $suppress;
1191 $this->status = $file->repo->newGood();
1192 }
1193
1194 function addCurrent() {
1195 $this->srcRels['.'] = $this->file->getRel();
1196 }
1197
1198 function addOld( $oldName ) {
1199 $this->srcRels[$oldName] = $this->file->getArchiveRel( $oldName );
1200 $this->archiveUrls[] = $this->file->getArchiveUrl( $oldName );
1201 }
1202
1203 function getOldRels() {
1204 if ( !isset( $this->srcRels['.'] ) ) {
1205 $oldRels =& $this->srcRels;
1206 $deleteCurrent = false;
1207 } else {
1208 $oldRels = $this->srcRels;
1209 unset( $oldRels['.'] );
1210 $deleteCurrent = true;
1211 }
1212 return array( $oldRels, $deleteCurrent );
1213 }
1214
1215 /*protected*/ function getHashes() {
1216 $hashes = array();
1217 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1218 if ( $deleteCurrent ) {
1219 $hashes['.'] = $this->file->getSha1();
1220 }
1221 if ( count( $oldRels ) ) {
1222 $dbw = $this->file->repo->getMasterDB();
1223 $res = $dbw->select( 'oldimage', array( 'oi_archive_name', 'oi_sha1' ),
1224 'oi_archive_name IN(' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1225 __METHOD__ );
1226 while ( $row = $dbw->fetchObject( $res ) ) {
1227 if ( rtrim( $row->oi_sha1, "\0" ) === '' ) {
1228 // Get the hash from the file
1229 $oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
1230 $props = $this->file->repo->getFileProps( $oldUrl );
1231 if ( $props['fileExists'] ) {
1232 // Upgrade the oldimage row
1233 $dbw->update( 'oldimage',
1234 array( 'oi_sha1' => $props['sha1'] ),
1235 array( 'oi_name' => $this->file->getName(), 'oi_archive_name' => $row->oi_archive_name ),
1236 __METHOD__ );
1237 $hashes[$row->oi_archive_name] = $props['sha1'];
1238 } else {
1239 $hashes[$row->oi_archive_name] = false;
1240 }
1241 } else {
1242 $hashes[$row->oi_archive_name] = $row->oi_sha1;
1243 }
1244 }
1245 }
1246 $missing = array_diff_key( $this->srcRels, $hashes );
1247 foreach ( $missing as $name => $rel ) {
1248 $this->status->error( 'filedelete-old-unregistered', $name );
1249 }
1250 foreach ( $hashes as $name => $hash ) {
1251 if ( !$hash ) {
1252 $this->status->error( 'filedelete-missing', $this->srcRels[$name] );
1253 unset( $hashes[$name] );
1254 }
1255 }
1256
1257 return $hashes;
1258 }
1259
1260 function doDBInserts() {
1261 global $wgUser;
1262 $dbw = $this->file->repo->getMasterDB();
1263 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1264 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1265 $encReason = $dbw->addQuotes( $this->reason );
1266 $encGroup = $dbw->addQuotes( 'deleted' );
1267 $ext = $this->file->getExtension();
1268 $dotExt = $ext === '' ? '' : ".$ext";
1269 $encExt = $dbw->addQuotes( $dotExt );
1270 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1271
1272 // Bitfields to further suppress the content
1273 if ( $this->suppress ) {
1274 $bitfield = 0;
1275 // This should be 15...
1276 $bitfield |= Revision::DELETED_TEXT;
1277 $bitfield |= Revision::DELETED_COMMENT;
1278 $bitfield |= Revision::DELETED_USER;
1279 $bitfield |= Revision::DELETED_RESTRICTED;
1280 } else {
1281 $bitfield = 'oi_deleted';
1282 }
1283
1284 if ( $deleteCurrent ) {
1285 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1286 $where = array( 'img_name' => $this->file->getName() );
1287 $dbw->insertSelect( 'filearchive', 'image',
1288 array(
1289 'fa_storage_group' => $encGroup,
1290 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1291 'fa_deleted_user' => $encUserId,
1292 'fa_deleted_timestamp' => $encTimestamp,
1293 'fa_deleted_reason' => $encReason,
1294 'fa_deleted' => $this->suppress ? $bitfield : 0,
1295
1296 'fa_name' => 'img_name',
1297 'fa_archive_name' => 'NULL',
1298 'fa_size' => 'img_size',
1299 'fa_width' => 'img_width',
1300 'fa_height' => 'img_height',
1301 'fa_metadata' => 'img_metadata',
1302 'fa_bits' => 'img_bits',
1303 'fa_media_type' => 'img_media_type',
1304 'fa_major_mime' => 'img_major_mime',
1305 'fa_minor_mime' => 'img_minor_mime',
1306 'fa_description' => 'img_description',
1307 'fa_user' => 'img_user',
1308 'fa_user_text' => 'img_user_text',
1309 'fa_timestamp' => 'img_timestamp'
1310 ), $where, __METHOD__ );
1311 }
1312
1313 if ( count( $oldRels ) ) {
1314 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1315 $where = array(
1316 'oi_name' => $this->file->getName(),
1317 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1318 $dbw->insertSelect( 'filearchive', 'oldimage',
1319 array(
1320 'fa_storage_group' => $encGroup,
1321 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1322 'fa_deleted_user' => $encUserId,
1323 'fa_deleted_timestamp' => $encTimestamp,
1324 'fa_deleted_reason' => $encReason,
1325 'fa_deleted' => $this->suppress ? $bitfield : 'oi_deleted',
1326
1327 'fa_name' => 'oi_name',
1328 'fa_archive_name' => 'oi_archive_name',
1329 'fa_size' => 'oi_size',
1330 'fa_width' => 'oi_width',
1331 'fa_height' => 'oi_height',
1332 'fa_metadata' => 'oi_metadata',
1333 'fa_bits' => 'oi_bits',
1334 'fa_media_type' => 'oi_media_type',
1335 'fa_major_mime' => 'oi_major_mime',
1336 'fa_minor_mime' => 'oi_minor_mime',
1337 'fa_description' => 'oi_description',
1338 'fa_user' => 'oi_user',
1339 'fa_user_text' => 'oi_user_text',
1340 'fa_timestamp' => 'oi_timestamp',
1341 'fa_deleted' => $bitfield
1342 ), $where, __METHOD__ );
1343 }
1344 }
1345
1346 function doDBDeletes() {
1347 $dbw = $this->file->repo->getMasterDB();
1348 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1349 if ( count( $oldRels ) ) {
1350 $dbw->delete( 'oldimage',
1351 array(
1352 'oi_name' => $this->file->getName(),
1353 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')'
1354 ), __METHOD__ );
1355 }
1356 if ( $deleteCurrent ) {
1357 $dbw->delete( 'image', array( 'img_name' => $this->file->getName() ), __METHOD__ );
1358 }
1359 }
1360
1361 /**
1362 * Run the transaction
1363 */
1364 function execute() {
1365 global $wgUser, $wgUseSquid;
1366 wfProfileIn( __METHOD__ );
1367
1368 $this->file->lock();
1369 // Leave private files alone
1370 $privateFiles = array();
1371 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1372 $dbw = $this->file->repo->getMasterDB();
1373 if( !empty( $oldRels ) ) {
1374 $res = $dbw->select( 'oldimage',
1375 array( 'oi_archive_name' ),
1376 array( 'oi_name' => $this->file->getName(),
1377 'oi_archive_name IN (' . $dbw->makeList( array_keys($oldRels) ) . ')',
1378 'oi_deleted & ' . File::DELETED_FILE => File::DELETED_FILE ),
1379 __METHOD__ );
1380 while( $row = $dbw->fetchObject( $res ) ) {
1381 $privateFiles[$row->oi_archive_name] = 1;
1382 }
1383 }
1384 // Prepare deletion batch
1385 $hashes = $this->getHashes();
1386 $this->deletionBatch = array();
1387 $ext = $this->file->getExtension();
1388 $dotExt = $ext === '' ? '' : ".$ext";
1389 foreach ( $this->srcRels as $name => $srcRel ) {
1390 // Skip files that have no hash (missing source).
1391 // Keep private files where they are.
1392 if ( isset($hashes[$name]) && !array_key_exists($name,$privateFiles) ) {
1393 $hash = $hashes[$name];
1394 $key = $hash . $dotExt;
1395 $dstRel = $this->file->repo->getDeletedHashPath( $key ) . $key;
1396 $this->deletionBatch[$name] = array( $srcRel, $dstRel );
1397 }
1398 }
1399
1400 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1401 // We acquire this lock by running the inserts now, before the file operations.
1402 //
1403 // This potentially has poor lock contention characteristics -- an alternative
1404 // scheme would be to insert stub filearchive entries with no fa_name and commit
1405 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1406 $this->doDBInserts();
1407
1408 // Execute the file deletion batch
1409 $status = $this->file->repo->deleteBatch( $this->deletionBatch );
1410 if ( !$status->isGood() ) {
1411 $this->status->merge( $status );
1412 }
1413
1414 if ( !$this->status->ok ) {
1415 // Critical file deletion error
1416 // Roll back inserts, release lock and abort
1417 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1418 $this->file->unlockAndRollback();
1419 return $this->status;
1420 }
1421
1422 // Purge squid
1423 if ( $wgUseSquid ) {
1424 $urls = array();
1425 foreach ( $this->srcRels as $srcRel ) {
1426 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1427 $urls[] = $this->file->repo->getZoneUrl( 'public' ) . '/' . $urlRel;
1428 }
1429 SquidUpdate::purge( $urls );
1430 }
1431
1432 // Delete image/oldimage rows
1433 $this->doDBDeletes();
1434
1435 // Commit and return
1436 $this->file->unlock();
1437 wfProfileOut( __METHOD__ );
1438 return $this->status;
1439 }
1440 }
1441
1442 #------------------------------------------------------------------------------
1443
1444 /**
1445 * Helper class for file undeletion
1446 * @ingroup FileRepo
1447 */
1448 class LocalFileRestoreBatch {
1449 var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1450
1451 function __construct( File $file, $unsuppress = false ) {
1452 $this->file = $file;
1453 $this->cleanupBatch = $this->ids = array();
1454 $this->ids = array();
1455 $this->unsuppress = $unsuppress;
1456 }
1457
1458 /**
1459 * Add a file by ID
1460 */
1461 function addId( $fa_id ) {
1462 $this->ids[] = $fa_id;
1463 }
1464
1465 /**
1466 * Add a whole lot of files by ID
1467 */
1468 function addIds( $ids ) {
1469 $this->ids = array_merge( $this->ids, $ids );
1470 }
1471
1472 /**
1473 * Add all revisions of the file
1474 */
1475 function addAll() {
1476 $this->all = true;
1477 }
1478
1479 /**
1480 * Run the transaction, except the cleanup batch.
1481 * The cleanup batch should be run in a separate transaction, because it locks different
1482 * rows and there's no need to keep the image row locked while it's acquiring those locks
1483 * The caller may have its own transaction open.
1484 * So we save the batch and let the caller call cleanup()
1485 */
1486 function execute() {
1487 global $wgUser, $wgLang;
1488 if ( !$this->all && !$this->ids ) {
1489 // Do nothing
1490 return $this->file->repo->newGood();
1491 }
1492
1493 $exists = $this->file->lock();
1494 $dbw = $this->file->repo->getMasterDB();
1495 $status = $this->file->repo->newGood();
1496
1497 // Fetch all or selected archived revisions for the file,
1498 // sorted from the most recent to the oldest.
1499 $conditions = array( 'fa_name' => $this->file->getName() );
1500 if( !$this->all ) {
1501 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids ) . ')';
1502 }
1503
1504 $result = $dbw->select( 'filearchive', '*',
1505 $conditions,
1506 __METHOD__,
1507 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
1508
1509 $idsPresent = array();
1510 $storeBatch = array();
1511 $insertBatch = array();
1512 $insertCurrent = false;
1513 $deleteIds = array();
1514 $first = true;
1515 $archiveNames = array();
1516 while( $row = $dbw->fetchObject( $result ) ) {
1517 $idsPresent[] = $row->fa_id;
1518
1519 if ( $row->fa_name != $this->file->getName() ) {
1520 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
1521 $status->failCount++;
1522 continue;
1523 }
1524 if ( $row->fa_storage_key == '' ) {
1525 // Revision was missing pre-deletion
1526 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
1527 $status->failCount++;
1528 continue;
1529 }
1530
1531 $deletedRel = $this->file->repo->getDeletedHashPath( $row->fa_storage_key ) . $row->fa_storage_key;
1532 $deletedUrl = $this->file->repo->getVirtualUrl() . '/deleted/' . $deletedRel;
1533
1534 $sha1 = substr( $row->fa_storage_key, 0, strcspn( $row->fa_storage_key, '.' ) );
1535 # Fix leading zero
1536 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1537 $sha1 = substr( $sha1, 1 );
1538 }
1539
1540 if( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
1541 || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime == 'unknown'
1542 || is_null( $row->fa_media_type ) || $row->fa_media_type == 'UNKNOWN'
1543 || is_null( $row->fa_metadata ) ) {
1544 // Refresh our metadata
1545 // Required for a new current revision; nice for older ones too. :)
1546 $props = RepoGroup::singleton()->getFileProps( $deletedUrl );
1547 } else {
1548 $props = array(
1549 'minor_mime' => $row->fa_minor_mime,
1550 'major_mime' => $row->fa_major_mime,
1551 'media_type' => $row->fa_media_type,
1552 'metadata' => $row->fa_metadata );
1553 }
1554
1555 if ( $first && !$exists ) {
1556 // The live (current) version cannot be hidden!
1557 if( !$this->unsuppress && $row->fa_deleted ) {
1558 $this->file->unlock();
1559 return $status;
1560 }
1561 // This revision will be published as the new current version
1562 $destRel = $this->file->getRel();
1563 $insertCurrent = array(
1564 'img_name' => $row->fa_name,
1565 'img_size' => $row->fa_size,
1566 'img_width' => $row->fa_width,
1567 'img_height' => $row->fa_height,
1568 'img_metadata' => $props['metadata'],
1569 'img_bits' => $row->fa_bits,
1570 'img_media_type' => $props['media_type'],
1571 'img_major_mime' => $props['major_mime'],
1572 'img_minor_mime' => $props['minor_mime'],
1573 'img_description' => $row->fa_description,
1574 'img_user' => $row->fa_user,
1575 'img_user_text' => $row->fa_user_text,
1576 'img_timestamp' => $row->fa_timestamp,
1577 'img_sha1' => $sha1);
1578 } else {
1579 $archiveName = $row->fa_archive_name;
1580 if( $archiveName == '' ) {
1581 // This was originally a current version; we
1582 // have to devise a new archive name for it.
1583 // Format is <timestamp of archiving>!<name>
1584 $timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
1585 do {
1586 $archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
1587 $timestamp++;
1588 } while ( isset( $archiveNames[$archiveName] ) );
1589 }
1590 $archiveNames[$archiveName] = true;
1591 $destRel = $this->file->getArchiveRel( $archiveName );
1592 $insertBatch[] = array(
1593 'oi_name' => $row->fa_name,
1594 'oi_archive_name' => $archiveName,
1595 'oi_size' => $row->fa_size,
1596 'oi_width' => $row->fa_width,
1597 'oi_height' => $row->fa_height,
1598 'oi_bits' => $row->fa_bits,
1599 'oi_description' => $row->fa_description,
1600 'oi_user' => $row->fa_user,
1601 'oi_user_text' => $row->fa_user_text,
1602 'oi_timestamp' => $row->fa_timestamp,
1603 'oi_metadata' => $props['metadata'],
1604 'oi_media_type' => $props['media_type'],
1605 'oi_major_mime' => $props['major_mime'],
1606 'oi_minor_mime' => $props['minor_mime'],
1607 'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
1608 'oi_sha1' => $sha1 );
1609 }
1610
1611 $deleteIds[] = $row->fa_id;
1612 if( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
1613 // private files can stay where they are
1614 } else {
1615 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1616 $this->cleanupBatch[] = $row->fa_storage_key;
1617 }
1618 $first = false;
1619 }
1620 unset( $result );
1621
1622 // Add a warning to the status object for missing IDs
1623 $missingIds = array_diff( $this->ids, $idsPresent );
1624 foreach ( $missingIds as $id ) {
1625 $status->error( 'undelete-missing-filearchive', $id );
1626 }
1627
1628 // Run the store batch
1629 // Use the OVERWRITE_SAME flag to smooth over a common error
1630 $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
1631 $status->merge( $storeStatus );
1632
1633 if ( !$status->ok ) {
1634 // Store batch returned a critical error -- this usually means nothing was stored
1635 // Stop now and return an error
1636 $this->file->unlock();
1637 return $status;
1638 }
1639
1640 // Run the DB updates
1641 // Because we have locked the image row, key conflicts should be rare.
1642 // If they do occur, we can roll back the transaction at this time with
1643 // no data loss, but leaving unregistered files scattered throughout the
1644 // public zone.
1645 // This is not ideal, which is why it's important to lock the image row.
1646 if ( $insertCurrent ) {
1647 $dbw->insert( 'image', $insertCurrent, __METHOD__ );
1648 }
1649 if ( $insertBatch ) {
1650 $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
1651 }
1652 if ( $deleteIds ) {
1653 $dbw->delete( 'filearchive',
1654 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1655 __METHOD__ );
1656 }
1657
1658 if( $status->successCount > 0 ) {
1659 if( !$exists ) {
1660 wfDebug( __METHOD__." restored {$status->successCount} items, creating a new current\n" );
1661
1662 // Update site_stats
1663 $site_stats = $dbw->tableName( 'site_stats' );
1664 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
1665
1666 $this->file->purgeEverything();
1667 } else {
1668 wfDebug( __METHOD__." restored {$status->successCount} as archived versions\n" );
1669 $this->file->purgeDescription();
1670 $this->file->purgeHistory();
1671 }
1672 }
1673 $this->file->unlock();
1674 return $status;
1675 }
1676
1677 /**
1678 * Delete unused files in the deleted zone.
1679 * This should be called from outside the transaction in which execute() was called.
1680 */
1681 function cleanup() {
1682 if ( !$this->cleanupBatch ) {
1683 return $this->file->repo->newGood();
1684 }
1685 $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
1686 return $status;
1687 }
1688 }
1689
1690 #------------------------------------------------------------------------------
1691
1692 /**
1693 * Helper class for file movement
1694 * @ingroup FileRepo
1695 */
1696 class LocalFileMoveBatch {
1697 var $file, $cur, $olds, $oldcount, $archive, $thumbs, $target, $db;
1698
1699 function __construct( File $file, Title $target, Database $db ) {
1700 $this->file = $file;
1701 $this->target = $target;
1702 $this->oldHash = $this->file->repo->getHashPath( $this->file->getName() );
1703 $this->newHash = $this->file->repo->getHashPath( $this->target->getDbKey() );
1704 $this->oldName = $this->file->getName();
1705 $this->newName = $this->file->repo->getNameFromTitle( $this->target );
1706 $this->oldRel = $this->oldHash . $this->oldName;
1707 $this->newRel = $this->newHash . $this->newName;
1708 $this->db = $db;
1709 }
1710
1711 function addCurrent() {
1712 $this->cur = array( $this->oldRel, $this->newRel );
1713 }
1714
1715 function addThumbs() {
1716 // Thumbnails are purged, so no need to move them
1717 $this->thumbs = array();
1718 }
1719
1720 function addOlds() {
1721 $archiveBase = 'archive';
1722 $this->olds = array();
1723 $this->oldcount = 0;
1724
1725 $result = $this->db->select( 'oldimage',
1726 array( 'oi_archive_name', 'oi_deleted' ),
1727 array( 'oi_name' => $this->oldName ),
1728 __METHOD__
1729 );
1730 while( $row = $this->db->fetchObject( $result ) ) {
1731 $oldname = $row->oi_archive_name;
1732 $bits = explode( '!', $oldname, 2 );
1733 if( count( $bits ) != 2 ) {
1734 wfDebug( 'Invalid old file name: ' . $oldname );
1735 continue;
1736 }
1737 list( $timestamp, $filename ) = $bits;
1738 if( $this->oldName != $filename ) {
1739 wfDebug( 'Invalid old file name:' . $oldName );
1740 continue;
1741 }
1742 $this->oldcount++;
1743 // Do we want to add those to oldcount?
1744 if( $row->oi_deleted & File::DELETED_FILE ) {
1745 continue;
1746 }
1747 $this->olds[] = array(
1748 "{$archiveBase}/{$this->oldHash}{$oldname}",
1749 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
1750 );
1751 }
1752 $this->db->freeResult( $result );
1753 }
1754
1755 function execute() {
1756 $repo = $this->file->repo;
1757 $status = $repo->newGood();
1758 $triplets = $this->getMoveTriplets();
1759
1760 $statusDb = $this->doDBUpdates();
1761 $statusMove = $repo->storeBatch( $triplets, FSRepo::DELETE_SOURCE );
1762 if( !$statusMove->isOk() ) {
1763 $this->db->rollback();
1764 }
1765 $status->merge( $statusDb );
1766 $status->merge( $statusMove );
1767 return $status;
1768 }
1769
1770 function doDBUpdates() {
1771 $repo = $this->file->repo;
1772 $status = $repo->newGood();
1773 $dbw = $this->db;
1774
1775 // Update current image
1776 $dbw->update(
1777 'image',
1778 array( 'img_name' => $this->newName ),
1779 array( 'img_name' => $this->oldName ),
1780 __METHOD__
1781 );
1782 if( $dbw->affectedRows() ) {
1783 $status->successCount++;
1784 } else {
1785 $status->failCount++;
1786 }
1787
1788 // Update old images
1789 $dbw->update(
1790 'oldimage',
1791 array(
1792 'oi_name' => $this->newName,
1793 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes($this->oldName), $dbw->addQuotes($this->newName) ),
1794 ),
1795 array( 'oi_name' => $this->oldName ),
1796 __METHOD__
1797 );
1798 $affected = $dbw->affectedRows();
1799 $total = $this->oldcount;
1800 $status->successCount += $affected;
1801 $status->failCount += $total - $affected;
1802
1803 return $status;
1804 }
1805
1806 // Generates triplets for FSRepo::storeBatch()
1807 function getMoveTriplets() {
1808 $moves = array_merge( array( $this->cur ), $this->olds, $this->thumbs );
1809 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
1810 foreach( $moves as $move ) {
1811 // $move: (oldRelativePath, newRelativePath)
1812 $srcUrl = $this->file->repo->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
1813 $triplets[] = array( $srcUrl, 'public', $move[1] );
1814 }
1815 return $triplets;
1816 }
1817 }