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