-
Notifications
You must be signed in to change notification settings - Fork 0
/
CloudStorageFile.php
executable file
·2037 lines (1841 loc) · 58.7 KB
/
CloudStorageFile.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
*/
/**
* Class to represent a file located in the cloud storage file system, in the wiki's own database
*
*/
class CloudStorageFile extends LocalFile {
protected $repoClass = 'CloudStorageRepo';
/**#@+
* @private
*/
var $fileExists, # does the file file exist on disk? (loadFromXxx)
$historyLine, # Number of line to return by nextHistoryLine() (constructor)
$historyRes, # result of the query for the file's history (nextHistoryLine)
$width, # \
$height, # |
$bits, # --- returned by getimagesize (loadFromXxx)
$attr, # /
$media_type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
$mime, # MIME type, determined by MimeMagic::guessMimeType
$major_mime, # Major mime type
$minor_mime, # Minor mime type
$size, # Size in bytes (loadFromXxx)
$metadata, # Handler-specific metadata
$timestamp, # Upload timestamp
$sha1, # SHA-1 base 36 content hash
$user, $user_text, # User, who uploaded the file
$description, # Description of current revision of the file
$dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
$upgraded, # Whether the row was upgraded on load
$locked, # True if the image row is locked
$tempPath, # path on Windows/Linux server of temporary file, copy of S3 file
$missing, # True if file is not present in file system. Not to be cached in memcached
$deleted; # Bitfield akin to rev_deleted
/**
* Constructor.
* Do not call this except from inside a repo class.
*/
function __construct( $title, $repo ) {
if( !is_object( $title ) ) {
throw new MWException( __CLASS__ . ' constructor given bogus title.' );
}
parent::__construct( $title, $repo );
// $this->repoClass = 'CloudStorageRepo';
$this->metadata = '';
$this->historyLine = 0;
$this->historyRes = null;
$this->dataLoaded = false;
}
/**#@-*/
/**
* Get a query string authenticated URL
*
* @param string $bucket Bucket name
* @param string $uri Object URI
* @param integer $lifetime Lifetime in seconds
* @param boolean $hostBucket Use the bucket name as the hostname
* @param boolean $https Use HTTPS ($hostBucket should be false for SSL verification)
* @return string
*/
public static function getAuthenticatedURL($bucket, $uri, $lifetime, $hostBucket = false, $https = false) {
// virutal
return false;
}
/** Get the URL of the archive directory, or a particular file if $suffix is specified */
function getArchiveUrl( $suffix = false ) {
wfDebug( __METHOD__ . " suffix: $suffix, url:".print_r($this->getUrl(), true)."\n" );
if ( $suffix === false ) {
$path = $this->repo->getZoneUrl('public') . '/archive/' . $this->getHashPath();
$path = substr( $path, 0, -1 );
} else {
$path = '/archive/' . $this->getHashPath($suffix) . $suffix;
}
wfDebug( __METHOD__ . " return: $path \n".print_r($this,true)."\n" );
return $path;
}
/**
* Create a CloudStorage from a title
* Do not call this except from inside a repo class.
*
* Note: $unused param is only here to avoid an E_STRICT
*/
static function newFromTitle( $title, $repo, $unused = null ) {
return new self( $title, $repo );
}
/**
* Create a CloudStorage from a row
* Do not call this except from inside a repo class.
*/
static function newFromRow( $row, $repo ) {
$title = Title::makeTitle( NS_FILE, $row->img_name );
$file = new self( $title, $repo );
$file->loadFromRow( $row );
return $file;
}
/**
* Create a CloudStorage from a SHA-1 key
* Do not call this except from inside a repo class.
*/
static function newFromKey( $sha1, $repo, $timestamp = false ) {
# Polymorphic function name to distinguish foreign and local fetches
$fname = get_class( $this ) . '::' . __FUNCTION__;
$conds = array( 'img_sha1' => $sha1 );
if( $timestamp ) {
$conds['img_timestamp'] = $timestamp;
}
$row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ), $conds, $fname );
if( $row ) {
return self::newFromRow( $row, $repo );
} else {
return false;
}
}
/**
* Fields in the image table
*/
static function selectFields() {
return array(
'img_name',
'img_size',
'img_width',
'img_height',
'img_metadata',
'img_bits',
'img_media_type',
'img_major_mime',
'img_minor_mime',
'img_description',
'img_user',
'img_user_text',
'img_timestamp',
'img_sha1',
);
}
/**
* Get the memcached key for the main data for this file, or false if
* there is no access to the shared cache.
*/
function getCacheKey() {
$hashedName = md5( $this->getName() );
return $this->repo->getSharedCacheKey( 'file', $hashedName );
}
/**
* Try to load file metadata from memcached. Returns true on success.
*/
function loadFromCache() {
global $wgMemc;
wfProfileIn( __METHOD__ );
$this->dataLoaded = false;
$key = $this->getCacheKey();
if ( !$key ) {
wfProfileOut( __METHOD__ );
return false;
}
$cachedValues = $wgMemc->get( $key );
// Check if the key existed and belongs to this version of MediaWiki
if ( isset( $cachedValues['version'] ) && ( $cachedValues['version'] == MW_FILE_VERSION ) ) {
wfDebug( "Pulling file metadata from cache key $key\n" );
$this->fileExists = $cachedValues['fileExists'];
if ( $this->fileExists ) {
$this->setProps( $cachedValues );
}
$this->dataLoaded = true;
}
if ( $this->dataLoaded ) {
wfIncrStats( 'image_cache_hit' );
} else {
wfIncrStats( 'image_cache_miss' );
}
wfProfileOut( __METHOD__ );
return $this->dataLoaded;
}
/**
* Save the file metadata to memcached
*/
function saveToCache() {
global $wgMemc;
$this->load();
$key = $this->getCacheKey();
if ( !$key ) {
return;
}
$fields = $this->getCacheFields( '' );
$cache = array( 'version' => MW_FILE_VERSION );
$cache['fileExists'] = $this->fileExists;
if ( $this->fileExists ) {
foreach ( $fields as $field ) {
$cache[$field] = $this->$field;
}
}
$wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
}
/**
* Load metadata from the file itself
*/
function loadFromFile() {
$this->setProps( self::getPropsFromPath( $this->getPath() ) );
}
function getCacheFields( $prefix = 'img_' ) {
static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
static $results = array();
if ( $prefix == '' ) {
return $fields;
}
if ( !isset( $results[$prefix] ) ) {
$prefixedFields = array();
foreach ( $fields as $field ) {
$prefixedFields[] = $prefix . $field;
}
$results[$prefix] = $prefixedFields;
}
return $results[$prefix];
}
/**
* Load file metadata from the DB
*/
function loadFromDB() {
# Polymorphic function name to distinguish foreign and local fetches
$fname = get_class( $this ) . '::' . __FUNCTION__;
wfProfileIn( $fname );
# Unconditionally set loaded=true, we don't want the accessors constantly rechecking
$this->dataLoaded = true;
$dbr = $this->repo->getMasterDB();
$row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
array( 'img_name' => $this->getName() ), $fname );
if ( $row ) {
$this->loadFromRow( $row );
} else {
$this->fileExists = false;
}
wfProfileOut( $fname );
}
/**
* Decode a row from the database (either object or array) to an array
* with timestamps and MIME types decoded, and the field prefix removed.
*/
function decodeRow( $row, $prefix = 'img_' ) {
$array = (array)$row;
$prefixLength = strlen( $prefix );
// Sanity check prefix once
if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
throw new MWException( __METHOD__ . ': incorrect $prefix parameter' );
}
$decoded = array();
foreach ( $array as $name => $value ) {
$decoded[substr( $name, $prefixLength )] = $value;
}
$decoded['timestamp'] = wfTimestamp( TS_MW, $decoded['timestamp'] );
if ( empty( $decoded['major_mime'] ) ) {
$decoded['mime'] = 'unknown/unknown';
} else {
if ( !$decoded['minor_mime'] ) {
$decoded['minor_mime'] = 'unknown';
}
$decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
}
# Trim zero padding from char/binary field
$decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
return $decoded;
}
/**
* Load file metadata from a DB result row
*/
function loadFromRow( $row, $prefix = 'img_' ) {
$this->dataLoaded = true;
$array = $this->decodeRow( $row, $prefix );
foreach ( $array as $name => $value ) {
$this->$name = $value;
}
$this->fileExists = true;
$this->maybeUpgradeRow();
}
/**
* Load file metadata from cache or DB, unless already loaded
*/
function load() {
if ( !$this->dataLoaded ) {
if ( !$this->loadFromCache() ) {
$this->loadFromDB();
$this->saveToCache();
}
$this->dataLoaded = true;
}
}
/**
* Upgrade a row if it needs it
*/
function maybeUpgradeRow() {
if ( wfReadOnly() ) {
return;
}
if ( is_null( $this->media_type ) ||
$this->mime == 'image/svg'
) {
$this->upgradeRow();
$this->upgraded = true;
} else {
$handler = $this->getHandler();
if ( $handler && !$handler->isMetadataValid( $this, $this->metadata ) ) {
$this->upgradeRow();
$this->upgraded = true;
}
}
}
function getUpgraded() {
return $this->upgraded;
}
/**
* Fix assorted version-related problems with the image row by reloading it from the file
*/
function upgradeRow() {
wfProfileIn( __METHOD__ );
$this->loadFromFile();
# Don't destroy file info of missing files
if ( !$this->fileExists ) {
wfDebug( __METHOD__ . ": file does not exist, aborting\n" );
wfProfileOut( __METHOD__ );
return;
}
$dbw = $this->repo->getMasterDB();
list( $major, $minor ) = self::splitMime( $this->mime );
if ( wfReadOnly() ) {
wfProfileOut( __METHOD__ );
return;
}
wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema\n" );
$dbw->update( 'image',
array(
'img_width' => $this->width,
'img_height' => $this->height,
'img_bits' => $this->bits,
'img_media_type' => $this->media_type,
'img_major_mime' => $major,
'img_minor_mime' => $minor,
'img_metadata' => $this->metadata,
'img_sha1' => $this->sha1,
), array( 'img_name' => $this->getName() ),
__METHOD__
);
$this->saveToCache();
wfProfileOut( __METHOD__ );
}
/**
* Set properties in this object to be equal to those given in the
* associative array $info. Only cacheable fields can be set.
*
* If 'mime' is given, it will be split into major_mime/minor_mime.
* If major_mime/minor_mime are given, $this->mime will also be set.
*/
function setProps( $info ) {
$this->dataLoaded = true;
$fields = $this->getCacheFields( '' );
$fields[] = 'fileExists';
foreach ( $fields as $field ) {
if ( isset( $info[$field] ) ) {
$this->$field = $info[$field];
}
}
// Fix up mime fields
if ( isset( $info['major_mime'] ) ) {
$this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
} elseif ( isset( $info['mime'] ) ) {
list( $this->major_mime, $this->minor_mime ) = self::splitMime( $this->mime );
}
}
/** splitMime inherited */
/** getName inherited */
/** getTitle inherited */
/** getURL inherited */
/** getViewURL inherited */
/** getPath WAS inherited */
/** isVisible inhereted */
function isMissing() {
if( $this->missing === null ) {
list( $fileExists ) = $this->repo->fileExistsBatch( array( $this->getVirtualUrl() )/*, CloudStorageRepo::FILES_ONLY*/ );
$this->missing = !$fileExists;
}
return $this->missing;
}
/**
* Return the width of the image
*
* Returns false on error
*/
public function getWidth( $page = 1 ) {
$this->load();
if ( $this->isMultipage() ) {
$dim = $this->getHandler()->getPageDimensions( $this, $page );
if ( $dim ) {
return $dim['width'];
} else {
return false;
}
} else {
return $this->width;
}
}
/**
* Return the height of the image
*
* Returns false on error
*/
public function getHeight( $page = 1 ) {
$this->load();
if ( $this->isMultipage() ) {
$dim = $this->getHandler()->getPageDimensions( $this, $page );
if ( $dim ) {
return $dim['height'];
} else {
return false;
}
} else {
return $this->height;
}
}
/**
* Returns ID or name of user who uploaded the file
*
* @param $type string 'text' or 'id'
*/
function getUser( $type = 'text' ) {
$this->load();
if( $type == 'text' ) {
return $this->user_text;
} elseif( $type == 'id' ) {
return $this->user;
}
}
/**
* Get handler-specific metadata
*/
function getMetadata() {
$this->load();
return $this->metadata;
}
function getBitDepth() {
$this->load();
return $this->bits;
}
/**
* Return the size of the image file, in bytes
*/
public function getSize() {
$this->load();
return $this->size;
}
/**
* Returns the mime type of the file.
*/
function getMimeType() {
$this->load();
return $this->mime;
}
/**
* Return the type of the media in the file.
* Use the value returned by this function with the MEDIATYPE_xxx constants.
*/
function getMediaType() {
$this->load();
return $this->media_type;
}
/** canRender inherited */
/** mustRender inherited */
/** allowInlineDisplay inherited */
/** isSafeFile inherited */
/** isTrustedFile inherited */
/**
* Returns true if the file file exists on disk.
* @return boolean Whether file file exist on disk.
*/
public function exists() {
$this->load();
return $this->fileExists;
}
/**
* Returns true if the file comes from the local file repository.
*
* @return bool
*/
function isLocal() {
return true; // s3 is considered local for these purposes
}
/** getTransformScript inherited */
/** getUnscaledThumb inherited */
/** thumbName inherited */
/** createThumb inherited */
/** getThumbnail inherited */
/** transform WAS inherited */
/**
* Transform a media file
*
* @param array $params An associative array of handler-specific parameters. Typical
* keys are width, height and page.
* @param integer $flags A bitfield, may contain self::RENDER_NOW to force rendering
* @return MediaTransformOutput
*/
function transform( $params, $flags = 0 ) {
return parent::transform($params, $flags);
}
/**
* get the storage file url
* @see CloudStorageFile::getUrl()
*/
public function getUrl() {
global $wgCss;
$url = parent::getUrl();
return $wgCss->getImageServingUrl($url);
}
/** Get the URL of the thumbnail directory, or a particular file if $suffix is specified.
* $suffix is a path relative to the S3 bucket, and includes the upload directory
*/
function getThumbUrl( $suffix = false ) {
global $wgCss;
$path = parent::getThumbUrl($suffix); //'images/thumb/' . $this->getThumbRel();
$thumbFileStr = $wgCss->getImageServingUrl($path);
return $thumbFileStr;
}
function getThumbPath( $suffix = false ) {
global $wgCss;
$thumbFileStr = $wgCss->getBucketUrl() . 'images/thumb/' . $this->getThumbRel( $suffix );
return $thumbFileStr;
}
/**
* Return the full filesystem path to the file. Note that this does
* not mean that a file actually exists under that location.
*
* This path depends on whether directory hashing is active or not,
* i.e. whether the files are all found in the same directory,
* or in hashed paths like /images/3/3c.
*
*
* If forceExist is true, will copy file from S3 and put it in a temp file.
* The temp filename will be returned.
*
* May return false if the file is not locally accessible.
*/
public function getPath( $forceExist=true ) {
return parent::getPath($forceExist);
}
/**
* Fix thumbnail files from 1.4 or before, with extreme prejudice
*/
function migrateThumbFile( $thumbName ) {
// can't do this in S3, files and directories are conceptually different than Linux
return; /***************/
$thumbDir = $this->getThumbPath();
$thumbPath = "$thumbDir/$thumbName";
if ( is_dir( $thumbPath ) ) {
// Directory where file should be
// This happened occasionally due to broken migration code in 1.5
// Rename to broken-*
for ( $i = 0; $i < 100 ; $i++ ) {
$broken = $this->repo->getZonePath( 'public' ) . "/broken-$i-$thumbName";
if ( !file_exists( $broken ) ) {
rename( $thumbPath, $broken );
break;
}
}
// Doesn't exist anymore
clearstatcache();
}
if ( is_file( $thumbDir ) ) {
// File where directory should be
unlink( $thumbDir );
// Doesn't exist anymore
clearstatcache();
}
}
/** getHandler inherited */
/** iconThumb inherited */
/** getLastError inherited */
/**
* Get all thumbnail names previously generated for this file
*/
function getThumbnails() {
$this->load();
$files = array();
$dir = $this->getThumbPath();
if ( is_dir( $dir ) ) {
$handle = opendir( $dir );
if ( $handle ) {
while ( false !== ( $file = readdir( $handle ) ) ) {
if ( $file{0} != '.' ) {
$files[] = $file;
}
}
closedir( $handle );
}
}
return $files;
}
/**
* Refresh metadata in memcached, but don't touch thumbnails or squid
*/
function purgeMetadataCache() {
$this->loadFromDB();
$this->saveToCache();
$this->purgeHistory();
}
/**
* Purge the shared history (CloudStorageFileArchive) cache
*/
function purgeHistory() {
global $wgMemc;
$hashedName = md5( $this->getName() );
$oldKey = $this->repo->getSharedCacheKey( 'oldfile', $hashedName );
if ( $oldKey ) {
$wgMemc->delete( $oldKey );
}
}
/**
* Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
*/
function purgeCache() {
// Refresh metadata cache
$this->purgeMetadataCache();
// Delete thumbnails
$this->purgeThumbnails();
// Purge squid cache for this file
SquidUpdate::purge( array( $this->getURL() ) );
}
/**
* Delete cached transformed files
*/
function purgeThumbnails() {
global $wgUseSquid;
// Delete thumbnails
$files = $this->getThumbnails();
$dir = $this->getThumbPath();
$urls = array();
foreach ( $files as $file ) {
# Check that the base file name is part of the thumb name
# This is a basic sanity check to avoid erasing unrelated directories
if ( strpos( $file, $this->getName() ) !== false ) {
$url = $this->getThumbUrl( $file );
$urls[] = $url;
@unlink( "$dir/$file" );
}
}
// Purge the squid
if ( $wgUseSquid ) {
SquidUpdate::purge( $urls );
}
}
/** purgeDescription inherited */
/** purgeEverything inherited */
function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
$dbr = $this->repo->getSlaveDB();
$tables = array( 'oldimage' );
$fields = CloudStorageFileArchive::selectFields();
$conds = $opts = $join_conds = array();
$eq = $inc ? '=' : '';
$conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
if( $start ) {
$conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
}
if( $end ) {
$conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
}
if( $limit ) {
$opts['LIMIT'] = $limit;
}
// Search backwards for time > x queries
$order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
$opts['ORDER BY'] = "oi_timestamp $order";
$opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
wfRunHooks( 'CloudStorage::getHistory', array( &$this, &$tables, &$fields,
&$conds, &$opts, &$join_conds ) );
$res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
$r = array();
while( $row = $dbr->fetchObject( $res ) ) {
if ( $this->repo->oldFileFromRowFactory ) {
$r[] = call_user_func( $this->repo->oldFileFromRowFactory, $row, $this->repo );
} else {
$r[] = CloudStorageFileArchive::newFromRow( $row, $this->repo );
}
}
if( $order == 'ASC' ) {
$r = array_reverse( $r ); // make sure it ends up descending
}
return $r;
}
/**
* Return the history of this file, line by line.
* starts with current version, then old versions.
* uses $this->historyLine to check which line to return:
* 0 return line for current version
* 1 query for old versions, return first one
* 2, ... return next old version from above query
*/
public function nextHistoryLine() {
# Polymorphic function name to distinguish foreign and local fetches
$fname = get_class( $this ) . '::' . __FUNCTION__;
$dbr = $this->repo->getSlaveDB();
if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
$this->historyRes = $dbr->select( 'image',
array(
'*',
"'' AS oi_archive_name",
'0 as oi_deleted',
'img_sha1'
),
array( 'img_name' => $this->title->getDBkey() ),
$fname
);
if ( 0 == $dbr->numRows( $this->historyRes ) ) {
$dbr->freeResult( $this->historyRes );
$this->historyRes = null;
return false;
}
} elseif ( $this->historyLine == 1 ) {
$dbr->freeResult( $this->historyRes );
$this->historyRes = $dbr->select( 'oldimage', '*',
array( 'oi_name' => $this->title->getDBkey() ),
$fname,
array( 'ORDER BY' => 'oi_timestamp DESC' )
);
}
$this->historyLine ++;
return $dbr->fetchObject( $this->historyRes );
}
/**
* Reset the history pointer to the first element of the history
*/
public function resetHistory() {
$this->historyLine = 0;
if ( !is_null( $this->historyRes ) ) {
$this->repo->getSlaveDB()->freeResult( $this->historyRes );
$this->historyRes = null;
}
}
/** getFullPath inherited */
/** getHashPath inherited */
/** getRel inherited */
/** getUrlRel inherited */
/** getArchiveRel inherited */
/** getThumbRel inherited */
/** getArchivePath inherited */
/** getThumbPath inherited */
/** getArchiveUrl inherited */
/** getThumbUrl inherited */
/** getArchiveVirtualUrl inherited */
/** getThumbVirtualUrl inherited */
/** isHashed inherited */
/**
* Upload a file and record it in the DB
* @param $srcPath String: source path or virtual URL
* @param $comment String: upload description
* @param $pageText String: text to use for the new description page,
* if a new description page is created
* @param $flags Integer: flags for publish()
* @param $props Array: File properties, if known. This can be used to reduce the
* upload time when uploading virtual URLs for which the file info
* is already known
* @param $timestamp String: timestamp for img_timestamp, or false to use the current time
* @param $user Mixed: User object or null to use $wgUser
*
* @return FileRepoStatus object. On success, the value member contains the
* archive name, or an empty string if it was a new file.
*/
function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
$this->lock();
$status = $this->publish( $srcPath, $flags );
if ( $status->ok ) {
if ( !$this->recordUpload2( $status->value, $comment, $pageText, $props, $timestamp, $user ) ) {
$status->fatal( 'filenotfound', $srcPath );
}
}
$this->unlock();
return $status;
}
/**
* Record a file upload in the upload log and the image table
* @deprecated use upload()
*/
function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
$watch = false, $timestamp = false )
{
$pageText = SpecialUpload::getInitialPageText( $desc, $license, $copyStatus, $source );
if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
return false;
}
if ( $watch ) {
global $wgUser;
$wgUser->addWatch( $this->getTitle() );
}
return true;
}
/**
* Record a file upload in the upload log and the image table
*/
function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null )
{
if( is_null( $user ) ) {
global $wgUser;
$user = $wgUser;
}
$dbw = $this->repo->getMasterDB();
$dbw->begin();
if ( !$props ) {
$props = $this->repo->getFileProps( $this->getVirtualUrl() );
}
$props['description'] = $comment;
$props['user'] = $user->getId();
$props['user_text'] = $user->getName();
$props['timestamp'] = wfTimestamp( TS_MW );
$this->setProps( $props );
// Delete thumbnails and refresh the metadata cache
$this->purgeThumbnails();
$this->saveToCache();
SquidUpdate::purge( array( $this->getURL() ) );
// Fail now if the file isn't there
if ( !$this->fileExists ) {
wfDebug( __METHOD__ . ": File " . $this->getPath() . " went missing!\n" );
return false;
}
$reupload = false;
if ( $timestamp === false ) {
$timestamp = $dbw->timestamp();
}
# Test to see if the row exists using INSERT IGNORE
# This avoids race conditions by locking the row until the commit, and also
# doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
$dbw->insert( 'image',
array(
'img_name' => $this->getName(),
'img_size'=> $this->size,
'img_width' => intval( $this->width ),
'img_height' => intval( $this->height ),
'img_bits' => $this->bits,
'img_media_type' => $this->media_type,
'img_major_mime' => $this->major_mime,
'img_minor_mime' => $this->minor_mime,
'img_timestamp' => $timestamp,
'img_description' => $comment,
'img_user' => $user->getId(),
'img_user_text' => $user->getName(),
'img_metadata' => $this->metadata,
'img_sha1' => $this->sha1
),
__METHOD__,
'IGNORE'
);
if( $dbw->affectedRows() == 0 ) {
$reupload = true;
# Collision, this is an update of a file
# Insert previous contents into oldimage
$dbw->insertSelect( 'oldimage', 'image',
array(
'oi_name' => 'img_name',
'oi_archive_name' => $dbw->addQuotes( $oldver ),
'oi_size' => 'img_size',
'oi_width' => 'img_width',
'oi_height' => 'img_height',
'oi_bits' => 'img_bits',
'oi_timestamp' => 'img_timestamp',
'oi_description' => 'img_description',
'oi_user' => 'img_user',
'oi_user_text' => 'img_user_text',
'oi_metadata' => 'img_metadata',
'oi_media_type' => 'img_media_type',
'oi_major_mime' => 'img_major_mime',
'oi_minor_mime' => 'img_minor_mime',
'oi_sha1' => 'img_sha1'
), array( 'img_name' => $this->getName() ), __METHOD__
);
# Update the current image row
$dbw->update( 'image',
array( /* SET */
'img_size' => $this->size,
'img_width' => intval( $this->width ),
'img_height' => intval( $this->height ),
'img_bits' => $this->bits,
'img_media_type' => $this->media_type,
'img_major_mime' => $this->major_mime,
'img_minor_mime' => $this->minor_mime,
'img_timestamp' => $timestamp,
'img_description' => $comment,
'img_user' => $user->getId(),
'img_user_text' => $user->getName(),
'img_metadata' => $this->metadata,
'img_sha1' => $this->sha1
), array( /* WHERE */
'img_name' => $this->getName()
), __METHOD__
);
} else {
# This is a new file
# Update the image count
$site_stats = $dbw->tableName( 'site_stats' );
$dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
}
$descTitle = $this->getTitle();
$article = new ImagePage( $descTitle );
$article->setFile( $this );
# Add the log entry
$log = new LogPage( 'upload' );
$action = $reupload ? 'overwrite' : 'upload';
$log->addEntry( $action, $descTitle, $comment, array(), $user );
if( $descTitle->exists() ) {
# Create a null revision