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