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