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