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