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