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