44000e49008c65dd5700a5d1c70a66c7d40f8752
[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 if ( $timestamp === false ) {
698 $timestamp = $dbw->timestamp();
699 }
700
701 # Test to see if the row exists using INSERT IGNORE
702 # This avoids race conditions by locking the row until the commit, and also
703 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
704 $dbw->insert( 'image',
705 array(
706 'img_name' => $this->getName(),
707 'img_size'=> $this->size,
708 'img_width' => intval( $this->width ),
709 'img_height' => intval( $this->height ),
710 'img_bits' => $this->bits,
711 'img_media_type' => $this->media_type,
712 'img_major_mime' => $this->major_mime,
713 'img_minor_mime' => $this->minor_mime,
714 'img_timestamp' => $timestamp,
715 'img_description' => $comment,
716 'img_user' => $wgUser->getID(),
717 'img_user_text' => $wgUser->getName(),
718 'img_metadata' => $this->metadata,
719 'img_sha1' => $this->sha1
720 ),
721 __METHOD__,
722 'IGNORE'
723 );
724
725 if( $dbw->affectedRows() == 0 ) {
726 # Collision, this is an update of a file
727 # Insert previous contents into oldimage
728 $dbw->insertSelect( 'oldimage', 'image',
729 array(
730 'oi_name' => 'img_name',
731 'oi_archive_name' => $dbw->addQuotes( $oldver ),
732 'oi_size' => 'img_size',
733 'oi_width' => 'img_width',
734 'oi_height' => 'img_height',
735 'oi_bits' => 'img_bits',
736 'oi_timestamp' => 'img_timestamp',
737 'oi_description' => 'img_description',
738 'oi_user' => 'img_user',
739 'oi_user_text' => 'img_user_text',
740 'oi_metadata' => 'img_metadata',
741 'oi_media_type' => 'img_media_type',
742 'oi_major_mime' => 'img_major_mime',
743 'oi_minor_mime' => 'img_minor_mime',
744 'oi_sha1' => 'img_sha1',
745 ), array( 'img_name' => $this->getName() ), __METHOD__
746 );
747
748 # Update the current image row
749 $dbw->update( 'image',
750 array( /* SET */
751 'img_size' => $this->size,
752 'img_width' => intval( $this->width ),
753 'img_height' => intval( $this->height ),
754 'img_bits' => $this->bits,
755 'img_media_type' => $this->media_type,
756 'img_major_mime' => $this->major_mime,
757 'img_minor_mime' => $this->minor_mime,
758 'img_timestamp' => $timestamp,
759 'img_description' => $comment,
760 'img_user' => $wgUser->getID(),
761 'img_user_text' => $wgUser->getName(),
762 'img_metadata' => $this->metadata,
763 'img_sha1' => $this->sha1
764 ), array( /* WHERE */
765 'img_name' => $this->getName()
766 ), __METHOD__
767 );
768 } else {
769 # This is a new file
770 # Update the image count
771 $site_stats = $dbw->tableName( 'site_stats' );
772 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
773 }
774
775 $descTitle = $this->getTitle();
776 $article = new Article( $descTitle );
777
778 # Add the log entry
779 $log = new LogPage( 'upload' );
780 $log->addEntry( 'upload', $descTitle, $comment );
781
782 if( $descTitle->exists() ) {
783 # Create a null revision
784 $nullRevision = Revision::newNullRevision( $dbw, $descTitle->getArticleId(), $log->getRcComment(), false );
785 $nullRevision->insertOn( $dbw );
786
787 # Invalidate the cache for the description page
788 $descTitle->invalidateCache();
789 $descTitle->purgeSquid();
790 } else {
791 // New file; create the description page.
792 // There's already a log entry, so don't make a second RC entry
793 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC );
794 }
795
796 # Hooks, hooks, the magic of hooks...
797 wfRunHooks( 'FileUpload', array( $this ) );
798
799 # Commit the transaction now, in case something goes wrong later
800 # The most important thing is that files don't get lost, especially archives
801 $dbw->immediateCommit();
802
803 # Invalidate cache for all pages using this file
804 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
805 $update->doUpdate();
806
807 return true;
808 }
809
810 /**
811 * Move or copy a file to its public location. If a file exists at the
812 * destination, move it to an archive. Returns the archive name on success
813 * or an empty string if it was a new file, and a wikitext-formatted
814 * WikiError object on failure.
815 *
816 * The archive name should be passed through to recordUpload for database
817 * registration.
818 *
819 * @param string $sourcePath Local filesystem path to the source image
820 * @param integer $flags A bitwise combination of:
821 * File::DELETE_SOURCE Delete the source file, i.e. move
822 * rather than copy
823 * @return FileRepoStatus object. On success, the value member contains the
824 * archive name, or an empty string if it was a new file.
825 */
826 function publish( $srcPath, $flags = 0 ) {
827 $this->lock();
828 $dstRel = $this->getRel();
829 $archiveName = gmdate( 'YmdHis' ) . '!'. $this->getName();
830 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
831 $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
832 $status = $this->repo->publish( $srcPath, $dstRel, $archiveRel, $flags );
833 if ( $status->value == 'new' ) {
834 $status->value = '';
835 } else {
836 $status->value = $archiveName;
837 }
838 $this->unlock();
839 return $status;
840 }
841
842 /** getLinksTo inherited */
843 /** getExifData inherited */
844 /** isLocal inherited */
845 /** wasDeleted inherited */
846
847 /**
848 * Delete all versions of the file.
849 *
850 * Moves the files into an archive directory (or deletes them)
851 * and removes the database rows.
852 *
853 * Cache purging is done; logging is caller's responsibility.
854 *
855 * @param $reason
856 * @return FileRepoStatus object.
857 */
858 function delete( $reason ) {
859 $this->lock();
860 $batch = new LocalFileDeleteBatch( $this, $reason );
861 $batch->addCurrent();
862
863 # Get old version relative paths
864 $dbw = $this->repo->getMasterDB();
865 $result = $dbw->select( 'oldimage',
866 array( 'oi_archive_name' ),
867 array( 'oi_name' => $this->getName() ) );
868 while ( $row = $dbw->fetchObject( $result ) ) {
869 $batch->addOld( $row->oi_archive_name );
870 }
871 $status = $batch->execute();
872
873 if ( $status->ok ) {
874 // Update site_stats
875 $site_stats = $dbw->tableName( 'site_stats' );
876 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__ );
877 $this->purgeEverything();
878 }
879
880 $this->unlock();
881 return $status;
882 }
883
884 /**
885 * Delete an old version of the file.
886 *
887 * Moves the file into an archive directory (or deletes it)
888 * and removes the database row.
889 *
890 * Cache purging is done; logging is caller's responsibility.
891 *
892 * @param $reason
893 * @throws MWException or FSException on database or filestore failure
894 * @return FileRepoStatus object.
895 */
896 function deleteOld( $archiveName, $reason ) {
897 $this->lock();
898 $batch = new LocalFileDeleteBatch( $this, $reason );
899 $batch->addOld( $archiveName );
900 $status = $batch->execute();
901 $this->unlock();
902 if ( $status->ok ) {
903 $this->purgeDescription();
904 $this->purgeHistory();
905 }
906 return $status;
907 }
908
909 /**
910 * Restore all or specified deleted revisions to the given file.
911 * Permissions and logging are left to the caller.
912 *
913 * May throw database exceptions on error.
914 *
915 * @param $versions set of record ids of deleted items to restore,
916 * or empty to restore all revisions.
917 * @return FileRepoStatus
918 */
919 function restore( $versions = array(), $unsuppress = false ) {
920 $batch = new LocalFileRestoreBatch( $this );
921 if ( !$versions ) {
922 $batch->addAll();
923 } else {
924 $batch->addIds( $versions );
925 }
926 $status = $batch->execute();
927 if ( !$status->ok ) {
928 return $status;
929 }
930
931 $cleanupStatus = $batch->cleanup();
932 $cleanupStatus->successCount = 0;
933 $cleanupStatus->failCount = 0;
934 $status->merge( $cleanupStatus );
935 return $status;
936 }
937
938 /** isMultipage inherited */
939 /** pageCount inherited */
940 /** scaleHeight inherited */
941 /** getImageSize inherited */
942
943 /**
944 * Get the URL of the file description page.
945 */
946 function getDescriptionUrl() {
947 return $this->title->getLocalUrl();
948 }
949
950 /**
951 * Get the HTML text of the description page
952 * This is not used by ImagePage for local files, since (among other things)
953 * it skips the parser cache.
954 */
955 function getDescriptionText() {
956 global $wgParser;
957 $revision = Revision::newFromTitle( $this->title );
958 if ( !$revision ) return false;
959 $text = $revision->getText();
960 if ( !$text ) return false;
961 $html = $wgParser->parse( $text, new ParserOptions );
962 return $html;
963 }
964
965 function getTimestamp() {
966 $this->load();
967 return $this->timestamp;
968 }
969
970 function getSha1() {
971 $this->load();
972 return $this->sha1;
973 }
974
975 /**
976 * Start a transaction and lock the image for update
977 * Increments a reference counter if the lock is already held
978 * @return boolean True if the image exists, false otherwise
979 */
980 function lock() {
981 $dbw = $this->repo->getMasterDB();
982 if ( !$this->locked ) {
983 $dbw->begin();
984 $this->locked++;
985 }
986 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__ );
987 }
988
989 /**
990 * Decrement the lock reference count. If the reference count is reduced to zero, commits
991 * the transaction and thereby releases the image lock.
992 */
993 function unlock() {
994 if ( $this->locked ) {
995 --$this->locked;
996 if ( !$this->locked ) {
997 $dbw = $this->repo->getMasterDB();
998 $dbw->commit();
999 }
1000 }
1001 }
1002
1003 /**
1004 * Roll back the DB transaction and mark the image unlocked
1005 */
1006 function unlockAndRollback() {
1007 $this->locked = false;
1008 $dbw = $this->repo->getMasterDB();
1009 $dbw->rollback();
1010 }
1011 } // LocalFile class
1012
1013 #------------------------------------------------------------------------------
1014
1015 /**
1016 * Backwards compatibility class
1017 */
1018 class Image extends LocalFile {
1019 function __construct( $title ) {
1020 $repo = RepoGroup::singleton()->getLocalRepo();
1021 parent::__construct( $title, $repo );
1022 }
1023
1024 /**
1025 * Wrapper for wfFindFile(), for backwards-compatibility only
1026 * Do not use in core code.
1027 * @deprecated
1028 */
1029 static function newFromTitle( $title, $time = false ) {
1030 $img = wfFindFile( $title, $time );
1031 if ( !$img ) {
1032 $img = wfLocalFile( $title );
1033 }
1034 return $img;
1035 }
1036
1037 /**
1038 * Wrapper for wfFindFile(), for backwards-compatibility only.
1039 * Do not use in core code.
1040 *
1041 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
1042 * @return image object or null if invalid title
1043 * @deprecated
1044 */
1045 static function newFromName( $name ) {
1046 $title = Title::makeTitleSafe( NS_IMAGE, $name );
1047 if ( is_object( $title ) ) {
1048 $img = wfFindFile( $title );
1049 if ( !$img ) {
1050 $img = wfLocalFile( $title );
1051 }
1052 return $img;
1053 } else {
1054 return NULL;
1055 }
1056 }
1057
1058 /**
1059 * Return the URL of an image, provided its name.
1060 *
1061 * Backwards-compatibility for extensions.
1062 * Note that fromSharedDirectory will only use the shared path for files
1063 * that actually exist there now, and will return local paths otherwise.
1064 *
1065 * @param string $name Name of the image, without the leading "Image:"
1066 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
1067 * @return string URL of $name image
1068 * @deprecated
1069 */
1070 static function imageUrl( $name, $fromSharedDirectory = false ) {
1071 $image = null;
1072 if( $fromSharedDirectory ) {
1073 $image = wfFindFile( $name );
1074 }
1075 if( !$image ) {
1076 $image = wfLocalFile( $name );
1077 }
1078 return $image->getUrl();
1079 }
1080 }
1081
1082 #------------------------------------------------------------------------------
1083
1084 /**
1085 * Helper class for file deletion
1086 */
1087 class LocalFileDeleteBatch {
1088 var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch;
1089 var $status;
1090
1091 function __construct( File $file, $reason = '' ) {
1092 $this->file = $file;
1093 $this->reason = $reason;
1094 $this->status = $file->repo->newGood();
1095 }
1096
1097 function addCurrent() {
1098 $this->srcRels['.'] = $this->file->getRel();
1099 }
1100
1101 function addOld( $oldName ) {
1102 $this->srcRels[$oldName] = $this->file->getArchiveRel( $oldName );
1103 $this->archiveUrls[] = $this->file->getArchiveUrl( $oldName );
1104 }
1105
1106 function getOldRels() {
1107 if ( !isset( $this->srcRels['.'] ) ) {
1108 $oldRels =& $this->srcRels;
1109 $deleteCurrent = false;
1110 } else {
1111 $oldRels = $this->srcRels;
1112 unset( $oldRels['.'] );
1113 $deleteCurrent = true;
1114 }
1115 return array( $oldRels, $deleteCurrent );
1116 }
1117
1118 /*protected*/ function getHashes() {
1119 $hashes = array();
1120 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1121 if ( $deleteCurrent ) {
1122 $hashes['.'] = $this->file->getSha1();
1123 }
1124 if ( count( $oldRels ) ) {
1125 $dbw = $this->file->repo->getMasterDB();
1126 $res = $dbw->select( 'oldimage', array( 'oi_archive_name', 'oi_sha1' ),
1127 'oi_archive_name IN(' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1128 __METHOD__ );
1129 while ( $row = $dbw->fetchObject( $res ) ) {
1130 if ( rtrim( $row->oi_sha1, "\0" ) === '' ) {
1131 // Get the hash from the file
1132 $oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
1133 $props = $this->file->repo->getFileProps( $oldUrl );
1134 if ( $props['fileExists'] ) {
1135 // Upgrade the oldimage row
1136 $dbw->update( 'oldimage',
1137 array( 'oi_sha1' => $props['sha1'] ),
1138 array( 'oi_name' => $this->file->getName(), 'oi_archive_name' => $row->oi_archive_name ),
1139 __METHOD__ );
1140 $hashes[$row->oi_archive_name] = $props['sha1'];
1141 } else {
1142 $hashes[$row->oi_archive_name] = false;
1143 }
1144 } else {
1145 $hashes[$row->oi_archive_name] = $row->oi_sha1;
1146 }
1147 }
1148 }
1149 $missing = array_diff_key( $this->srcRels, $hashes );
1150 foreach ( $missing as $name => $rel ) {
1151 $this->status->error( 'filedelete-old-unregistered', $name );
1152 }
1153 foreach ( $hashes as $name => $hash ) {
1154 if ( !$hash ) {
1155 $this->status->error( 'filedelete-missing', $this->srcRels[$name] );
1156 unset( $hashes[$name] );
1157 }
1158 }
1159
1160 return $hashes;
1161 }
1162
1163 function doDBInserts() {
1164 global $wgUser;
1165 $dbw = $this->file->repo->getMasterDB();
1166 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1167 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1168 $encReason = $dbw->addQuotes( $this->reason );
1169 $encGroup = $dbw->addQuotes( 'deleted' );
1170 $ext = $this->file->getExtension();
1171 $dotExt = $ext === '' ? '' : ".$ext";
1172 $encExt = $dbw->addQuotes( $dotExt );
1173 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1174
1175 if ( $deleteCurrent ) {
1176 $where = array( 'img_name' => $this->file->getName() );
1177 $dbw->insertSelect( 'filearchive', 'image',
1178 array(
1179 'fa_storage_group' => $encGroup,
1180 'fa_storage_key' => "IF(img_sha1='', '', CONCAT(img_sha1,$encExt))",
1181
1182 'fa_deleted_user' => $encUserId,
1183 'fa_deleted_timestamp' => $encTimestamp,
1184 'fa_deleted_reason' => $encReason,
1185 'fa_deleted' => 0,
1186
1187 'fa_name' => 'img_name',
1188 'fa_archive_name' => 'NULL',
1189 'fa_size' => 'img_size',
1190 'fa_width' => 'img_width',
1191 'fa_height' => 'img_height',
1192 'fa_metadata' => 'img_metadata',
1193 'fa_bits' => 'img_bits',
1194 'fa_media_type' => 'img_media_type',
1195 'fa_major_mime' => 'img_major_mime',
1196 'fa_minor_mime' => 'img_minor_mime',
1197 'fa_description' => 'img_description',
1198 'fa_user' => 'img_user',
1199 'fa_user_text' => 'img_user_text',
1200 'fa_timestamp' => 'img_timestamp'
1201 ), $where, __METHOD__ );
1202 }
1203
1204 if ( count( $oldRels ) ) {
1205 $where = array(
1206 'oi_name' => $this->file->getName(),
1207 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1208
1209 $dbw->insertSelect( 'filearchive', 'oldimage',
1210 array(
1211 'fa_storage_group' => $encGroup,
1212 'fa_storage_key' => "IF(oi_sha1='', '', CONCAT(oi_sha1,$encExt))",
1213
1214 'fa_deleted_user' => $encUserId,
1215 'fa_deleted_timestamp' => $encTimestamp,
1216 'fa_deleted_reason' => $encReason,
1217 'fa_deleted' => 0,
1218
1219 'fa_name' => 'oi_name',
1220 'fa_archive_name' => 'oi_archive_name',
1221 'fa_size' => 'oi_size',
1222 'fa_width' => 'oi_width',
1223 'fa_height' => 'oi_height',
1224 'fa_metadata' => 'oi_metadata',
1225 'fa_bits' => 'oi_bits',
1226 'fa_media_type' => 'oi_media_type',
1227 'fa_major_mime' => 'oi_major_mime',
1228 'fa_minor_mime' => 'oi_minor_mime',
1229 'fa_description' => 'oi_description',
1230 'fa_user' => 'oi_user',
1231 'fa_user_text' => 'oi_user_text',
1232 'fa_timestamp' => 'oi_timestamp'
1233 ), $where, __METHOD__ );
1234 }
1235 }
1236
1237 function doDBDeletes() {
1238 $dbw = $this->file->repo->getMasterDB();
1239 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1240 if ( $deleteCurrent ) {
1241 $where = array( 'img_name' => $this->file->getName() );
1242 $dbw->delete( 'image', array( 'img_name' => $this->file->getName() ), __METHOD__ );
1243 }
1244 if ( count( $oldRels ) ) {
1245 $dbw->delete( 'oldimage',
1246 array(
1247 'oi_name' => $this->file->getName(),
1248 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')'
1249 ), __METHOD__ );
1250 }
1251 }
1252
1253 /**
1254 * Run the transaction
1255 */
1256 function execute() {
1257 global $wgUser, $wgUseSquid;
1258 wfProfileIn( __METHOD__ );
1259
1260 $this->file->lock();
1261
1262 // Prepare deletion batch
1263 $hashes = $this->getHashes();
1264 $this->deletionBatch = array();
1265 $ext = $this->file->getExtension();
1266 $dotExt = $ext === '' ? '' : ".$ext";
1267 foreach ( $this->srcRels as $name => $srcRel ) {
1268 // Skip files that have no hash (missing source)
1269 if ( isset( $hashes[$name] ) ) {
1270 $hash = $hashes[$name];
1271 $key = $hash . $dotExt;
1272 $dstRel = $this->file->repo->getDeletedHashPath( $key ) . $key;
1273 $this->deletionBatch[$name] = array( $srcRel, $dstRel );
1274 }
1275 }
1276
1277 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1278 // We acquire this lock by running the inserts now, before the file operations.
1279 //
1280 // This potentially has poor lock contention characteristics -- an alternative
1281 // scheme would be to insert stub filearchive entries with no fa_name and commit
1282 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1283 $this->doDBInserts();
1284
1285 // Execute the file deletion batch
1286 $status = $this->file->repo->deleteBatch( $this->deletionBatch );
1287 if ( !$status->isGood() ) {
1288 $this->status->merge( $status );
1289 }
1290
1291 if ( !$this->status->ok ) {
1292 // Critical file deletion error
1293 // Roll back inserts, release lock and abort
1294 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1295 $this->file->unlockAndRollback();
1296 return $this->status;
1297 }
1298
1299 // Purge squid
1300 if ( $wgUseSquid ) {
1301 $urls = array();
1302 foreach ( $this->srcRels as $srcRel ) {
1303 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1304 $urls[] = $this->repo->getZoneUrl( 'public' ) . '/' . $urlRel;
1305 }
1306 SquidUpdate::purge( $urls );
1307 }
1308
1309 // Delete image/oldimage rows
1310 $this->doDBDeletes();
1311
1312 // Commit and return
1313 $this->file->unlock();
1314 wfProfileOut( __METHOD__ );
1315 return $this->status;
1316 }
1317 }
1318
1319 #------------------------------------------------------------------------------
1320
1321 /**
1322 * Helper class for file undeletion
1323 */
1324 class LocalFileRestoreBatch {
1325 var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1326
1327 function __construct( File $file ) {
1328 $this->file = $file;
1329 $this->cleanupBatch = $this->ids = array();
1330 $this->ids = array();
1331 }
1332
1333 /**
1334 * Add a file by ID
1335 */
1336 function addId( $fa_id ) {
1337 $this->ids[] = $fa_id;
1338 }
1339
1340 /**
1341 * Add a whole lot of files by ID
1342 */
1343 function addIds( $ids ) {
1344 $this->ids = array_merge( $this->ids, $ids );
1345 }
1346
1347 /**
1348 * Add all revisions of the file
1349 */
1350 function addAll() {
1351 $this->all = true;
1352 }
1353
1354 /**
1355 * Run the transaction, except the cleanup batch.
1356 * The cleanup batch should be run in a separate transaction, because it locks different
1357 * rows and there's no need to keep the image row locked while it's acquiring those locks
1358 * The caller may have its own transaction open.
1359 * So we save the batch and let the caller call cleanup()
1360 */
1361 function execute() {
1362 global $wgUser, $wgLang;
1363 if ( !$this->all && !$this->ids ) {
1364 // Do nothing
1365 return $this->file->repo->newGood();
1366 }
1367
1368 $exists = $this->file->lock();
1369 $dbw = $this->file->repo->getMasterDB();
1370 $status = $this->file->repo->newGood();
1371
1372 // Fetch all or selected archived revisions for the file,
1373 // sorted from the most recent to the oldest.
1374 $conditions = array( 'fa_name' => $this->file->getName() );
1375 if( !$this->all ) {
1376 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids ) . ')';
1377 }
1378
1379 $result = $dbw->select( 'filearchive', '*',
1380 $conditions,
1381 __METHOD__,
1382 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
1383
1384 $idsPresent = array();
1385 $storeBatch = array();
1386 $insertBatch = array();
1387 $insertCurrent = false;
1388 $deleteIds = array();
1389 $first = true;
1390 $archiveNames = array();
1391 while( $row = $dbw->fetchObject( $result ) ) {
1392 $idsPresent[] = $row->fa_id;
1393 if ( $this->unsuppress ) {
1394 // Currently, fa_deleted flags fall off upon restore, lets be careful about this
1395 } else if ( ($row->fa_deleted & Revision::DELETED_RESTRICTED) && !$wgUser->isAllowed('hiderevision') ) {
1396 // Skip restoring file revisions that the user cannot restore
1397 continue;
1398 }
1399 if ( $row->fa_name != $this->file->getName() ) {
1400 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
1401 $status->failCount++;
1402 continue;
1403 }
1404 if ( $row->fa_storage_key == '' ) {
1405 // Revision was missing pre-deletion
1406 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
1407 $status->failCount++;
1408 continue;
1409 }
1410
1411 $deletedRel = $this->file->repo->getDeletedHashPath( $row->fa_storage_key ) . $row->fa_storage_key;
1412 $deletedUrl = $this->file->repo->getVirtualUrl() . '/deleted/' . $deletedRel;
1413
1414 $sha1 = substr( $row->fa_storage_key, 0, strcspn( $row->fa_storage_key, '.' ) );
1415 # Fix leading zero
1416 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1417 $sha1 = substr( $sha1, 1 );
1418 }
1419
1420 if ( $first && !$exists ) {
1421 // This revision will be published as the new current version
1422 $destRel = $this->file->getRel();
1423 $info = $this->file->repo->getFileProps( $deletedUrl );
1424 $insertCurrent = array(
1425 'img_name' => $row->fa_name,
1426 'img_size' => $row->fa_size,
1427 'img_width' => $row->fa_width,
1428 'img_height' => $row->fa_height,
1429 'img_metadata' => $row->fa_metadata,
1430 'img_bits' => $row->fa_bits,
1431 'img_media_type' => $row->fa_media_type,
1432 'img_major_mime' => $row->fa_major_mime,
1433 'img_minor_mime' => $row->fa_minor_mime,
1434 'img_description' => $row->fa_description,
1435 'img_user' => $row->fa_user,
1436 'img_user_text' => $row->fa_user_text,
1437 'img_timestamp' => $row->fa_timestamp,
1438 'img_sha1' => $sha1);
1439 } else {
1440 $archiveName = $row->fa_archive_name;
1441 if( $archiveName == '' ) {
1442 // This was originally a current version; we
1443 // have to devise a new archive name for it.
1444 // Format is <timestamp of archiving>!<name>
1445 $timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
1446 do {
1447 $archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
1448 $timestamp++;
1449 } while ( isset( $archiveNames[$archiveName] ) );
1450 }
1451 $archiveNames[$archiveName] = true;
1452 $destRel = $this->file->getArchiveRel( $archiveName );
1453 $insertBatch[] = array(
1454 'oi_name' => $row->fa_name,
1455 'oi_archive_name' => $archiveName,
1456 'oi_size' => $row->fa_size,
1457 'oi_width' => $row->fa_width,
1458 'oi_height' => $row->fa_height,
1459 'oi_bits' => $row->fa_bits,
1460 'oi_description' => $row->fa_description,
1461 'oi_user' => $row->fa_user,
1462 'oi_user_text' => $row->fa_user_text,
1463 'oi_timestamp' => $row->fa_timestamp,
1464 'oi_metadata' => $row->fa_metadata,
1465 'oi_media_type' => $row->fa_media_type,
1466 'oi_major_mime' => $row->fa_major_mime,
1467 'oi_minor_mime' => $row->fa_minor_mime,
1468 'oi_deleted' => $row->fa_deleted,
1469 'oi_sha1' => $sha1 );
1470 }
1471
1472 $deleteIds[] = $row->fa_id;
1473 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1474 $this->cleanupBatch[] = $row->fa_storage_key;
1475 $first = false;
1476 }
1477 unset( $result );
1478
1479 // Add a warning to the status object for missing IDs
1480 $missingIds = array_diff( $this->ids, $idsPresent );
1481 foreach ( $missingIds as $id ) {
1482 $status->error( 'undelete-missing-filearchive', $id );
1483 }
1484
1485 // Run the store batch
1486 // Use the OVERWRITE_SAME flag to smooth over a common error
1487 $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
1488 $status->merge( $storeStatus );
1489
1490 if ( !$status->ok ) {
1491 // Store batch returned a critical error -- this usually means nothing was stored
1492 // Stop now and return an error
1493 $this->file->unlock();
1494 return $status;
1495 }
1496
1497 // Run the DB updates
1498 // Because we have locked the image row, key conflicts should be rare.
1499 // If they do occur, we can roll back the transaction at this time with
1500 // no data loss, but leaving unregistered files scattered throughout the
1501 // public zone.
1502 // This is not ideal, which is why it's important to lock the image row.
1503 if ( $insertCurrent ) {
1504 $dbw->insert( 'image', $insertCurrent, __METHOD__ );
1505 }
1506 if ( $insertBatch ) {
1507 $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
1508 }
1509 if ( $deleteIds ) {
1510 $dbw->delete( 'filearchive',
1511 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1512 __METHOD__ );
1513 }
1514
1515 if( $status->successCount > 0 ) {
1516 if( !$exists ) {
1517 wfDebug( __METHOD__." restored {$status->successCount} items, creating a new current\n" );
1518
1519 // Update site_stats
1520 $site_stats = $dbw->tableName( 'site_stats' );
1521 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
1522
1523 $this->file->purgeEverything();
1524 } else {
1525 wfDebug( __METHOD__." restored {$status->successCount} as archived versions\n" );
1526 $this->file->purgeDescription();
1527 $this->file->purgeHistory();
1528 }
1529 }
1530 $this->file->unlock();
1531 return $status;
1532 }
1533
1534 /**
1535 * Delete unused files in the deleted zone.
1536 * This should be called from outside the transaction in which execute() was called.
1537 */
1538 function cleanup() {
1539 if ( !$this->cleanupBatch ) {
1540 return $this->file->repo->newGood();
1541 }
1542 $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
1543 return $status;
1544 }
1545 }