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