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