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