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