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