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