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