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