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