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