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