forked from antonydandrea/LocalS3Repo2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LocalS3File.php
2521 lines (2206 loc) · 73.9 KB
/
LocalS3File.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
/*
Modified to work with 1.21 and CloudFront.
Owen Borseth - owen at borseth dot us
*/
/**
* Bump this number when serialized cache records may be incompatible.
*/
define( 'MW_FILE_VERSION', 8 );
/**
* Class to represent a file located in the Amazon S3 system, in the wiki's own database
*
* Based on LocalFile.php, LocalRepo.php, FSRepo.php and OldLocalFile.php (ver 1.16-alpha, r69121)
*
* Provides methods to retrieve paths (physical, logical, URL),
* to generate image thumbnails or for uploading.
*
* Note that only the repo object knows what its file class is called. You should
* never name a file class explictly outside of the repo class. Instead use the
* repo's factory functions to generate file objects, for example:
*
* RepoGroup::singleton()->getLocalRepo()->newFile($title);
*
* The convenience functions wfLocalFile() and wfFindFile() should be sufficient
* in most cases.
*
* @ingroup FileRepo
*/
class LocalS3File extends File {
var $thumbTempPath = NULL;
/**#@+
* @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
/**#@-*/
/**
* 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) {
global $s3;
return $s3->getAuthenticatedURL($bucket, $uri, $lifetime, $hostBucket, $https);
}
/** 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->url, 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;
if(! $this->repo->AWS_S3_PUBLIC) {
$path = self::getAuthenticatedURL($this->repo->AWS_S3_BUCKET, $this->repo->getZonePath('public') . $path, 60*60*24*7 /*week*/, false, $this->repo->AWS_S3_SSL);
} else {
$path = $this->repo->getZoneUrl('public') . $path;
}
}
wfDebug( __METHOD__ . " return: $path \n".print_r($this,true)."\n" );
return $path;
}
/**
* Create a LocalS3File 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 LocalS3File 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 LocalS3File 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',
);
}
/**
* 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->metadata = '';
$this->historyLine = 0;
$this->historyRes = null;
$this->dataLoaded = false;
}
/**
* 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() )/*, FSs3Repo::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 */
function getLocalRefPath()
{
if($this->thumbTempPath)
return($this->thumbTempPath);
else
return(parent::getetLocalRefPath());
}
/**
* 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
* Key to s3 Uploads
*/
function transform( $params, $flags = 0 ) {
global $wgUseSquid, $wgIgnoreImageErrors;
global $s3;
wfDebug( __METHOD__ . ": ".print_r($params,true)."\n" );
wfProfileIn( __METHOD__ );
do {
if ( !$this->canRender() ) {
// not a bitmap or renderable image, don't try.
$thumb = $this->iconThumb();
break;
}
$script = $this->getTransformScript();
if ( $script && !($flags & self::RENDER_NOW) ) {
// Use a script to transform on client request, if possible
$thumb = $this->handler->getScriptedTransform( $this, $script, $params );
if( $thumb ) {
break;
}
}
//I believe the issue is here due to public conversion works but without a key private does not.
$normalisedParams = $params;
$this->handler->normaliseParams( $this, $normalisedParams );
$thumbName = $this->thumbName( $normalisedParams );
$thumbPath = $this->getThumbPath( $thumbName );
$thumbUrl = $this->getThumbUrl( $thumbPath );
wfDebug( __METHOD__.": thumbName: $thumbName, thumbPath: $thumbPath\n thumbUrl: $thumbUrl\n" );
if ( $this->repo->canTransformVia404() && !($flags & self::RENDER_NOW ) ) {
$thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
break;
}
wfDebug( __METHOD__.": Doing stat for $thumbPath\n ($thumbUrl)\n" );
$this->migrateThumbFile( $thumbName );
//$thumbPath - is the full path of the image on s3
$info = $s3->getObjectInfo($this->repo->AWS_S3_BUCKET, $thumbPath);
//thumbTempPath
//This makes the temp file and then attempts to put contents in to the temp file
$this->thumbTempPath = tempnam(wfTempDir(), "s3thumb-");
//copy($this->getUrl(), $this->thumbTempPath);
//Get Full Path of Original Uploaded Image
$fullPath = str_replace("thumb/", "", $thumbPath);
$fullPath = explode("/",$fullPath);
unset( $fullPath[ count($fullPath) - 1]);
$fullPath = implode("/",$fullPath);
//echo $fullPath."<br>";
//echo $thumbPath."<br>";
//echo $this->thumbTempPath."<br><br><br>";
//This is where it request the file and put it in the thumbTempPath
$s3->getObject(
$this->repo->AWS_S3_BUCKET,
$fullPath,
$this->thumbTempPath
);
if(!file_exists($this->thumbTempPath)){
$tmpImg = file_get_contents($this->getUrl());
if(!empty($tmpImg) && !is_object($tmpImg)){
file_put_contents($this->thumbTempPath, $tmpImg);
}
}
//copy($this->thumbTempPath, $thumbPath);
/*
//if private then it needs to try again with key
if(!preg_match("/AWSAccessKeyId/",$thumbUrl) && $this->repo->AWS_S3_PUBLIC ){
//public static function getAuthenticatedURL($bucket, $uri, $lifetime, $hostBucket = false, $https = false) {
$thumbUrl = self::getAuthenticatedURL($this->repo->AWS_S3_BUCKET, $thumbPath, 60*60*24*7, false, $this->repo->AWS_S3_SSL);
}
*/
wfDebug(__METHOD__." thumbPath: $thumbPath\ninfo:".print_r($info,true)."\n");
//Gets the transformed file, not sure where it transformed it though.
if ( $info /*file_exists( $thumbPath )*/ ) {
$thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
break;
}
//This makes the thumb from the temp file
$thumb = $this->handler->doTransform( $this, $this->thumbTempPath, $thumbUrl, $params );
wfDebug( __METHOD__. " thumb: ".print_r($thumb->getUrl(),true)."\n" );
$s3path = $thumbPath;
//This puts the file to the temp location
$info = $s3->putObjectFile($this->thumbTempPath, $this->repo->AWS_S3_BUCKET, $s3path,
($this->repo->AWS_S3_PUBLIC ? S3::ACL_PUBLIC_READ : S3::ACL_PRIVATE));
wfDebug(__METHOD__." thumbTempPath: $this->thumbTempPath, dest: $s3path\ninfo:".print_r($info,true)."\n");
// Ignore errors if requested
if ( !$thumb ) {
$thumb = null;
} elseif ( $thumb->isError() ) {
$this->lastError = $thumb->toText();
if ( $wgIgnoreImageErrors && !($flags & self::RENDER_NOW) ) {
$thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
}
}
// Purge. Useful in the event of Core -> Squid connection failure or squid
// purge collisions from elsewhere during failure. Don't keep triggering for
// "thumbs" which have the main image URL though (bug 13776)
if ( $wgUseSquid && ( !$thumb || $thumb->isError() || $thumb->getUrl() != $this->getURL()) ) {
SquidUpdate::purge( array( $thumbUrl ) );
}
} while (false);
wfProfileOut( __METHOD__ );
wfDebug( __METHOD__. " return thumb: ".print_r($thumb,true)."\n" );
return is_object( $thumb ) ? $thumb : false;
}
public function generateAndSaveThumb( $tmpFile, $transformParams, $flags ) {
global $IP, $wgUploadDirectory, $wgAWS_S3_BUCKET, $wgAWS_BucketDir, $aws_s3_client, $wgUploadBaseUrl;
global $wgIgnoreImageErrors;
$stats = RequestContext::getMain()->getStats();
$handler = $this->getHandler();
$normalisedParams = $transformParams;
$handler->normaliseParams( $this, $normalisedParams );
$thumbName = $this->thumbName( $normalisedParams );
$thumbUrl = $this->getThumbUrl( $thumbName );
$thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
//S3 determine if thumb is on S3 if not use original
//$this->file_existsS3();
$this->thumbTempPath = tempnam(wfTempDir(), "s3thumb-");
$s3->getObject(
$this->repo->AWS_S3_BUCKET,
$thumbPath,
$this->thumbTempPath
);
//$tmpThumbPath = $tmpFile->getPath();
/**/
//This only can be activated once the sync is complete and the delete files have been deleted.
//This section searches for the thumbpath and if it does not exists
if(!file_exists($tmpThumbPath) || filesize($tmpThumbPath) == 0){
//Get Path
//$s3ThumbPath = str_replace("https://".$wgAWS_S3_BUCKET.".s3.amazonaws.com/","",$thumbUrl);
//$temps3 = explode("?",$s3ThumbPath);
//$s3ThumbPath = $temps3[0];
$s3ThumbPath = str_replace("images/", "", $wgUploadDirectory)."/thumb".str_replace("mwstore://local-backend/local-thumb", "", $thumbPath);
$s3FullPath = explode("/", str_replace("images/", "", $wgUploadDirectory)."".str_replace("mwstore://local-backend/local-thumb", "", $thumbPath));
unset( $s3FullPath[ count($s3FullPath)-1 ] );
$s3FullPath = implode("/", $s3FullPath);
if($this->file_existsS3($s3ThumbPath)){
//$tmpThumbPath = $this->getS3Url($s3ThumbPath); //$thumbUrl;
//$thumbUrl = $this->getS3Url($s3ThumbPath);
} else if($this->file_existsS3($s3FullPath)){
//$tmpThumbPath = $this->getS3Url($s3FullPath); //$thumbUrl;
//$thumbUrl = $this->getS3Url($s3FullPath);
}
}
/**/
if ( $handler->supportsBucketing() ) {
$this->generateBucketsIfNeeded( $normalisedParams, $flags );
}
$starttime = microtime( true );
// Actually render the thumbnail...
//Add the s3 capability of getting the s3 url to generate new thumbnail if it didnt exists
/*
$thumbUrl = "/opt/bitnami/apache2/htdocs/images/noaccess.png";
$thumb = $handler->doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0);
*/
//echo $thumbUrl."<br>";
$thumb = $handler->doTransform( $this , $tmpThumbPath, $thumbUrl, $transformParams );
/*ß
if(preg_match("/120px/",$thumbUrl)){
echo "<br><pre>";
print_r($thumb);
echo $tmpThumbPath."<br>";
echo $thumbUrl."<br>";
echo "</pre>";
}
*/
$tmpFile->bind( $thumb ); // keep alive with $thumb
$statTiming = microtime( true ) - $starttime;
$stats->timing( 'media.thumbnail.generate.transform', 1000 * $statTiming );
/*
Kelvin
*/
if ( !$thumb ) { // bad params?
$thumb = false;
} elseif ( $thumb->isError() ) { // transform error
/** @var $thumb MediaTransformError */
$this->lastError = $thumb->toText();
// Ignore errors if requested
if ( $wgIgnoreImageErrors && !( $flags & self::RENDER_NOW ) ) {
$thumb = $handler->getTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
}
} elseif ( $this->repo && $thumb->hasFile() && !$thumb->fileIsSource() ) {
// Copy the thumbnail from the file system into storage...
$starttime = microtime( true );
$disposition = $this->getThumbDisposition( $thumbName );
$status = $this->repo->quickImport( $tmpThumbPath, $thumbPath, $disposition );
if ( $status->isOK() ) {
$thumb->setStoragePath( $thumbPath );
} else {
$thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $transformParams, $flags );
}
$statTiming = microtime( true ) - $starttime;
$stats->timing( 'media.thumbnail.generate.store', 1000 * $statTiming );
// Give extensions a chance to do something with this thumbnail...
Hooks::run( 'FileTransformed', [ $this, $thumb, $tmpThumbPath, $thumbPath ] );
}
return $thumb;
}
/** 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 ) {
if($this->repo->cloudFrontUrl)
$path = $this->repo->cloudFrontUrl . "$suffix";
else
$path = $this->repo->getUrlBase() . "/$suffix";
if(!$this->repo->AWS_S3_PUBLIC){
$this->url = self::getAuthenticatedURL($this->repo->AWS_S3_BUCKET,
$suffix, 60*60*24*7, false,
$this->repo->AWS_S3_SSL);
}
$path = self::getAuthenticatedURL($this->repo->AWS_S3_BUCKET,
$suffix, 60*60*24*7, false,
$this->repo->AWS_S3_SSL);
return $path;
}
/**
* 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 ) {
global $s3;
if ( !isset( $this->tempPath ) ) {
$this->tempPath = tempnam(wfTempDir(), "s3file-");
//This is not getting private files - kelvin
$info = $s3->getObject(
$this->repo->AWS_S3_BUCKET,
$this->repo->directory . '/' . $this->getUrlRel(),
$this->tempPath
);
if(!$info) $this->tempPath = false;
}
return $this->tempPath;
}
/**
* 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 (OldLocalS3File) 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