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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
|
<?php
/**
* @package MediaWiki
*/
/**
* Class to represent an image
*
* Provides methods to retrieve paths (physical, logical, URL),
* to generate thumbnails or for uploading.
* @package MediaWiki
*/
class Image
{
/**#@+
* @access private
*/
var $name, # name of the image (constructor)
$imagePath, # Path of the image (loadFromXxx)
$url, # Image URL (accessor)
$title, # Title object for this image (constructor)
$fileExists, # does the image file exist on disk? (loadFromXxx)
$fromSharedDirectory, # load this image from $wgSharedUploadDirectory (loadFromXxx)
$historyLine, # Number of line to return by nextHistoryLine() (constructor)
$historyRes, # result of the query for the image's history (nextHistoryLine)
$width, # \
$height, # |
$bits, # --- returned by getimagesize (loadFromXxx)
$type, # |
$attr, # /
$size, # Size in bytes (loadFromXxx)
$dataLoaded; # Whether or not all this has been loaded from the database (loadFromXxx)
/**#@-*/
/**
* Create an Image object from an image name
*
* @param string $name name of the image, used to create a title object using Title::makeTitleSafe
* @access public
*/
function newFromName( $name ) {
$title = Title::makeTitleSafe( NS_IMAGE, $name );
return new Image( $title );
}
/**
* Obsolete factory function, use constructor
*/
function newFromTitle( &$title ) {
return new Image( $title );
}
function Image( &$title ) {
$this->title =& $title;
$this->name = $title->getDBkey();
$n = strrpos( $this->name, '.' );
$this->extension = strtolower( $n ? substr( $this->name, $n + 1 ) : '' );
$this->historyLine = 0;
$this->dataLoaded = false;
}
/**
* Get the memcached keys
* Returns an array, first element is the local cache key, second is the shared cache key, if there is one
*/
function getCacheKeys( $shared = false ) {
global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
$foundCached = false;
$hashedName = md5($this->name);
$keys = array( "$wgDBname:Image:$hashedName" );
if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
$keys[] = "$wgSharedUploadDBname:Image:$hashedName";
}
return $keys;
}
/**
* Try to load image metadata from memcached. Returns true on success.
*/
function loadFromCache() {
global $wgUseSharedUploads, $wgMemc;
$fname = 'Image::loadFromMemcached';
wfProfileIn( $fname );
$this->dataLoaded = false;
$keys = $this->getCacheKeys();
$cachedValues = $wgMemc->get( $keys[0] );
// Check if the key existed and belongs to this version of MediaWiki
if (!empty($cachedValues) && is_array($cachedValues) && isset($cachedValues['width']) && $cachedValues['fileExists']) {
if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
# if this is shared file, we need to check if image
# in shared repository has not changed
if ( isset( $keys[1] ) ) {
$commonsCachedValues = $wgMemc->get( $keys[1] );
if (!empty($commonsCachedValues) && is_array($commonsCachedValues) && isset($commonsCachedValues['width'])) {
$this->name = $commonsCachedValues['name'];
$this->imagePath = $commonsCachedValues['imagePath'];
$this->fileExists = $commonsCachedValues['fileExists'];
$this->width = $commonsCachedValues['width'];
$this->height = $commonsCachedValues['height'];
$this->bits = $commonsCachedValues['bits'];
$this->type = $commonsCachedValues['type'];
$this->fromSharedDirectory = true;
$this->dataLoaded = true;
}
}
}
else {
$this->name = $cachedValues['name'];
$this->imagePath = $cachedValues['imagePath'];
$this->fileExists = $cachedValues['fileExists'];
$this->width = $cachedValues['width'];
$this->height = $cachedValues['height'];
$this->bits = $cachedValues['bits'];
$this->type = $cachedValues['type'];
$this->fromSharedDirectory = false;
$this->dataLoaded = true;
}
}
wfProfileOut( $fname );
return $this->dataLoaded;
}
/**
* Save the image metadata to memcached
*/
function saveToCache() {
global $wgMemc;
$this->load();
// We can't cache metadata for non-existent files, because if the file later appears
// in commons, the local keys won't be purged.
if ( $this->fileExists ) {
$keys = $this->getCacheKeys();
$cachedValues = array('name' => $this->name,
'imagePath' => $this->imagePath,
'fileExists' => $this->fileExists,
'fromShared' => $this->fromSharedDirectory,
'width' => $this->width,
'height' => $this->height,
'bits' => $this->bits,
'type' => $this->type);
$wgMemc->set( $keys[0], $cachedValues );
}
}
/**
* Load metadata from the file itself
*/
function loadFromFile() {
global $wgUseSharedUploads, $wgSharedUploadDirectory;
$fname = 'Image::loadFromFile';
wfProfileIn( $fname );
$this->imagePath = $this->getFullPath();
$this->fileExists = file_exists( $this->imagePath );
$gis = false;
# If the file is not found, and a non-wiki shared upload directory is used, look for it there.
if (!$this->fileExists && $wgUseSharedUploads && $wgSharedUploadDirectory) {
# In case we're on a wgCapitalLinks=false wiki, we
# capitalize the first letter of the filename before
# looking it up in the shared repository.
$this->name = $wgLang->ucfirst($name);
$this->imagePath = $this->getFullPath(true);
$this->fileExists = file_exists( $this->imagePath);
$this->fromSharedDirectory = true;
}
if ( $this->fileExists ) {
# Get size in bytes
$s = stat( $this->imagePath );
$this->size = $s['size'];
# Height and width
# Don't try to get the width and height of sound and video files, that's bad for performance
if ( !Image::isKnownImageExtension( $this->extension ) ) {
$gis = false;
} elseif( $this->extension == 'svg' ) {
wfSuppressWarnings();
$gis = wfGetSVGsize( $this->imagePath );
wfRestoreWarnings();
} else {
wfSuppressWarnings();
$gis = getimagesize( $this->imagePath );
wfRestoreWarnings();
}
}
if( $gis === false ) {
$this->width = 0;
$this->height = 0;
$this->bits = 0;
$this->type = 0;
} else {
$this->width = $gis[0];
$this->height = $gis[1];
$this->type = $gis[2];
if ( isset( $gis['bits'] ) ) {
$this->bits = $gis['bits'];
} else {
$this->bits = 0;
}
}
$this->dataLoaded = true;
wfProfileOut( $fname );
}
/**
* Load image metadata from the DB
*/
function loadFromDB() {
global $wgUseSharedUploads, $wgSharedUploadDBname, $wgLang;
$fname = 'Image::loadFromDB';
wfProfileIn( $fname );
$dbr =& wfGetDB( DB_SLAVE );
$row = $dbr->selectRow( 'image',
array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' ),
array( 'img_name' => $this->name ), $fname );
if ( $row ) {
$this->fromSharedDirectory = false;
$this->fileExists = true;
$this->loadFromRow( $row );
$this->imagePath = $this->getFullPath();
} elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
# In case we're on a wgCapitalLinks=false wiki, we
# capitalize the first letter of the filename before
# looking it up in the shared repository.
$name = $wgLang->ucfirst($this->name);
$row = $dbr->selectRow( "`$wgSharedUploadDBname`.image",
array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' ),
array( 'img_name' => $name ), $fname );
if ( $row ) {
$this->fromSharedDirectory = true;
$this->fileExists = true;
$this->imagePath = '';
$this->name = $name;
$this->loadFromRow( $row );
}
}
if ( !$row ) {
$this->size = 0;
$this->width = 0;
$this->height = 0;
$this->bits = 0;
$this->type = 0;
$this->fileExists = false;
$this->fromSharedDirectory = false;
}
# Unconditionally set loaded=true, we don't want the accessors constantly rechecking
$this->dataLoaded = true;
}
/*
* Load image metadata from a DB result row
*/
function loadFromRow( &$row ) {
$this->size = $row->img_size;
$this->width = $row->img_width;
$this->height = $row->img_height;
$this->bits = $row->img_bits;
$this->type = $row->img_type;
$this->dataLoaded = true;
}
/**
* Load image metadata from cache or DB, unless already loaded
*/
function load() {
if ( !$this->dataLoaded ) {
if ( !$this->loadFromCache() ) {
$this->loadFromDB();
if ( $this->fileExists ) {
$this->saveToCache();
}
}
$this->dataLoaded = true;
}
}
/**
* Return the name of this image
* @access public
*/
function getName() {
return $this->name;
}
/**
* Return the associated title object
* @access public
*/
function getTitle() {
return $this->title;
}
/**
* Return the URL of the image file
* @access public
*/
function getURL() {
if ( !$this->url ) {
$this->load();
if($this->fileExists) {
$this->url = Image::imageUrl( $this->name, $this->fromSharedDirectory );
} else {
$this->url = '';
}
}
return $this->url;
}
function getViewURL() {
if( $this->mustRender() ) {
return $this->createThumb( $this->getWidth() );
} else {
return $this->getURL();
}
}
/**
* Return the image path of the image in the
* local file system as an absolute path
* @access public
*/
function getImagePath() {
$this->load();
return $this->imagePath;
}
/**
* Return the width of the image
*
* Returns -1 if the file specified is not a known image type
* @access public
*/
function getWidth() {
$this->load();
return $this->width;
}
/**
* Return the height of the image
*
* Returns -1 if the file specified is not a known image type
* @access public
*/
function getHeight() {
$this->load();
return $this->height;
}
/**
* Return the size of the image file, in bytes
* @access public
*/
function getSize() {
$this->load();
return $this->size;
}
/**
* Return the type of the image
*
* - 1 GIF
* - 2 JPG
* - 3 PNG
* - 15 WBMP
* - 16 XBM
*/
function getType() {
$this->load();
return $this->type;
}
/**
* Return the escapeLocalURL of this image
* @access public
*/
function getEscapeLocalURL() {
$this->getTitle();
return $this->title->escapeLocalURL();
}
/**
* Return the escapeFullURL of this image
* @access public
*/
function getEscapeFullURL() {
$this->getTitle();
return $this->title->escapeFullURL();
}
/**
* Return the URL of an image, provided its name.
*
* @param string $name Name of the image, without the leading "Image:"
* @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
* @access public
* @static
*/
function imageUrl( $name, $fromSharedDirectory = false ) {
global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
if($fromSharedDirectory) {
$base = '';
$path = $wgSharedUploadPath;
} else {
$base = $wgUploadBaseUrl;
$path = $wgUploadPath;
}
$url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
return wfUrlencode( $url );
}
/**
* Returns true if the image file exists on disk.
*
* @access public
*/
function exists() {
$this->load();
return $this->fileExists;
}
/**
*
* @access private
*/
function thumbUrl( $width, $subdir='thumb') {
global $wgUploadPath, $wgUploadBaseUrl,
$wgSharedUploadPath,$wgSharedUploadDirectory;
$name = $this->thumbName( $width );
if($this->fromSharedDirectory) {
$base = '';
$path = $wgSharedUploadPath;
} else {
$base = $wgUploadBaseUrl;
$path = $wgUploadPath;
}
$url = "{$base}{$path}/{$subdir}" .
wfGetHashPath($name, $this->fromSharedDirectory)
. "{$name}";
return wfUrlencode($url);
}
/**
* Return the file name of a thumbnail of the specified width
*
* @param integer $width Width of the thumbnail image
* @param boolean $shared Does the thumbnail come from the shared repository?
* @access private
*/
function thumbName( $width, $shared=false ) {
$thumb = $width."px-".$this->name;
if( $this->extension == 'svg' ) {
# Rasterize SVG vector images to PNG
$thumb .= '.png';
}
return $thumb;
}
/**
* Create a thumbnail of the image having the specified width/height.
* The thumbnail will not be created if the width is larger than the
* image's width. Let the browser do the scaling in this case.
* The thumbnail is stored on disk and is only computed if the thumbnail
* file does not exist OR if it is older than the image.
* Returns the URL.
*
* Keeps aspect ratio of original image. If both width and height are
* specified, the generated image will be no bigger than width x height,
* and will also have correct aspect ratio.
*
* @param integer $width maximum width of the generated thumbnail
* @param integer $height maximum height of the image (optional)
* @access public
*/
function createThumb( $width, $height=-1 ) {
$thumb = $this->getThumbnail( $width, $height );
if( is_null( $thumb ) ) return '';
return $thumb->getUrl();
}
/**
* As createThumb, but returns a ThumbnailImage object. This can
* provide access to the actual file, the real size of the thumb,
* and can produce a convenient <img> tag for you.
*
* @param integer $width maximum width of the generated thumbnail
* @param integer $height maximum height of the image (optional)
* @return ThumbnailImage
* @access public
*/
function &getThumbnail( $width, $height=-1 ) {
if ( $height == -1 ) {
return $this->renderThumb( $width );
}
if ( $width < $this->width ) {
$thumbheight = $this->height * $width / $this->width;
$thumbwidth = $width;
} else {
$thumbheight = $this->height;
$thumbwidth = $this->width;
}
if ( $thumbheight > $height ) {
$thumbwidth = $thumbwidth * $height / $thumbheight;
$thumbheight = $height;
}
$thumb = $this->renderThumb( $thumbwidth );
if( is_null( $thumb ) ) {
$thumb = $this->iconThumb();
}
return $thumb;
}
/**
* @return ThumbnailImage
*/
function iconThumb() {
global $wgStylePath, $wgStyleDirectory;
$try = array( 'fileicon-' . $this->extension . '.png', 'fileicon.png' );
foreach( $try as $icon ) {
$path = '/common/images/' . $icon;
$filepath = $wgStyleDirectory . $path;
if( file_exists( $filepath ) ) {
return new ThumbnailImage( $filepath, $wgStylePath . $path );
}
}
return null;
}
/**
* Create a thumbnail of the image having the specified width.
* The thumbnail will not be created if the width is larger than the
* image's width. Let the browser do the scaling in this case.
* The thumbnail is stored on disk and is only computed if the thumbnail
* file does not exist OR if it is older than the image.
* Returns an object which can return the pathname, URL, and physical
* pixel size of the thumbnail -- or null on failure.
*
* @return ThumbnailImage
* @access private
*/
function /* private */ renderThumb( $width ) {
global $wgImageMagickConvertCommand;
global $wgUseImageMagick;
global $wgUseSquid, $wgInternalServer;
$width = IntVal( $width );
$thumbName = $this->thumbName( $width, $this->fromSharedDirectory );
$thumbPath = wfImageThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory ).'/'.$thumbName;
$thumbUrl = $this->thumbUrl( $width );
#wfDebug ( "Render name: $thumbName path: $thumbPath url: $thumbUrl\n");
if ( ! $this->exists() )
{
# If there is no image, there will be no thumbnail
return null;
}
# Sanity check $width
if( $width <= 0 ) {
# BZZZT
return null;
}
if( $width > $this->width && !$this->mustRender() ) {
# Don't make an image bigger than the source
return new ThumbnailImage( $this->getImagePath(), $this->getViewURL() );
}
if ( (! file_exists( $thumbPath ) ) || ( filemtime($thumbPath) < filemtime($this->imagePath) ) ) {
if( $this->extension == 'svg' ) {
global $wgSVGConverters, $wgSVGConverter;
if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
global $wgSVGConverterPath;
$cmd = str_replace(
array( '$path/', '$width', '$input', '$output' ),
array( $wgSVGConverterPath,
$width,
escapeshellarg( $this->imagePath ),
escapeshellarg( $thumbPath ) ),
$wgSVGConverters[$wgSVGConverter] );
$conv = shell_exec( $cmd );
} else {
$conv = false;
}
} elseif ( $wgUseImageMagick ) {
# use ImageMagick
# Specify white background color, will be used for transparent images
# in Internet Explorer/Windows instead of default black.
$cmd = $wgImageMagickConvertCommand .
" -quality 85 -background white -geometry {$width} ".
escapeshellarg($this->imagePath) . " " .
escapeshellarg($thumbPath);
$conv = shell_exec( $cmd );
} else {
# Use PHP's builtin GD library functions.
#
# First find out what kind of file this is, and select the correct
# input routine for this.
$truecolor = false;
switch( $this->type ) {
case 1: # GIF
$src_image = imagecreatefromgif( $this->imagePath );
break;
case 2: # JPG
$src_image = imagecreatefromjpeg( $this->imagePath );
$truecolor = true;
break;
case 3: # PNG
$src_image = imagecreatefrompng( $this->imagePath );
$truecolor = ( $this->bits > 8 );
break;
case 15: # WBMP for WML
$src_image = imagecreatefromwbmp( $this->imagePath );
break;
case 16: # XBM
$src_image = imagecreatefromxbm( $this->imagePath );
break;
default:
return 'Image type not supported';
break;
}
$height = floor( $this->height * ( $width/$this->width ) );
if ( $truecolor ) {
$dst_image = imagecreatetruecolor( $width, $height );
} else {
$dst_image = imagecreate( $width, $height );
}
imagecopyresampled( $dst_image, $src_image,
0,0,0,0,
$width, $height, $this->width, $this->height );
switch( $this->type ) {
case 1: # GIF
case 3: # PNG
case 15: # WBMP
case 16: # XBM
#$thumbUrl .= ".png";
#$thumbPath .= ".png";
imagepng( $dst_image, $thumbPath );
break;
case 2: # JPEG
#$thumbUrl .= ".jpg";
#$thumbPath .= ".jpg";
imageinterlace( $dst_image );
imagejpeg( $dst_image, $thumbPath, 95 );
break;
default:
break;
}
imagedestroy( $dst_image );
imagedestroy( $src_image );
}
#
# Check for zero-sized thumbnails. Those can be generated when
# no disk space is available or some other error occurs
#
if( file_exists( $thumbPath ) ) {
$thumbstat = stat( $thumbPath );
if( $thumbstat['size'] == 0 ) {
unlink( $thumbPath );
}
}
# Purge squid
# This has to be done after the image is updated and present for all machines on NFS,
# or else the old version might be stored into the squid again
if ( $wgUseSquid ) {
$urlArr = Array(
$wgInternalServer.$thumbUrl
);
wfPurgeSquidServers($urlArr);
}
}
return new ThumbnailImage( $thumbPath, $thumbUrl );
} // END OF function createThumb
/**
* Return the image history of this image, 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
*
* @access public
*/
function nextHistoryLine() {
$fname = 'Image::nextHistoryLine()';
$dbr =& wfGetDB( DB_SLAVE );
if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
$this->historyRes = $dbr->select( 'image',
array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
array( 'img_name' => $this->title->getDBkey() ),
$fname
);
if ( 0 == wfNumRows( $this->historyRes ) ) {
return FALSE;
}
} else if ( $this->historyLine == 1 ) {
$this->historyRes = $dbr->select( 'oldimage',
array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
), 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
* @access public
*/
function resetHistory() {
$this->historyLine = 0;
}
/**
* Return true if the file is of a type that can't be directly
* rendered by typical browsers and needs to be re-rasterized.
* @return bool
*/
function mustRender() {
$this->load();
return ( $this->extension == 'svg' );
}
/**
* 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 images are all found in the same directory,
* or in hashed paths like /images/3/3c.
*
* @access public
* @param boolean $fromSharedDirectory Return the path to the file
* in a shared repository (see $wgUseSharedRepository and related
* options in DefaultSettings.php) instead of a local one.
*
*/
function getFullPath( $fromSharedRepository = false ) {
global $wgUploadDirectory, $wgSharedUploadDirectory;
global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
$dir = $fromSharedRepository ? $wgSharedUploadDirectory :
$wgUploadDirectory;
$name = $this->name;
$fullpath = $dir . wfGetHashPath($name, $fromSharedRepository) . $name;
return $fullpath;
}
/**
* @return bool
* @static
*/
function isKnownImageExtension( $ext ) {
static $extensions = array( 'svg', 'png', 'jpg', 'jpeg', 'gif', 'bmp', 'xbm' );
return in_array( $ext, $extensions );
}
/**
* Record an image upload in the upload log and the image table
*/
function recordUpload( $oldver, $desc, $copyStatus = '', $source = '' ) {
global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
global $wgUseCopyrightUpload;
$fname = 'Image::recordUpload';
$dbw =& wfGetDB( DB_MASTER );
# img_name must be unique
if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
}
// Fill metadata fields by querying the file
$this->loadFromFile();
$this->saveToCache();
// Fail now if the image isn't there
if ( !$this->fileExists || $this->fromSharedDirectory ) {
return false;
}
if ( $wgUseCopyrightUpload ) {
$textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
'== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
'== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
} else {
$textdesc = $desc;
}
$now = wfTimestampNow();
# 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->name,
'img_size'=> $this->size,
'img_width' => $this->width,
'img_height' => $this->height,
'img_bits' => $this->bits,
'img_type' => $this->type,
'img_timestamp' => $dbw->timestamp($now),
'img_description' => $desc,
'img_user' => $wgUser->getID(),
'img_user_text' => $wgUser->getName(),
), $fname, 'IGNORE'
);
$descTitle = $this->getTitle();
if ( $dbw->affectedRows() ) {
# Successfully inserted, this is a new image
$id = $descTitle->getArticleID();
if ( $id == 0 ) {
$article = new Article( $descTitle );
$article->insertNewArticle( $textdesc, $desc, false, false, true );
}
} else {
# Collision, this is an update of an image
# 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_type' => 'img_type',
'oi_timestamp' => 'img_timestamp',
'oi_description' => 'img_description',
'oi_user' => 'img_user',
'oi_user_text' => 'img_user_text',
), array( 'img_name' => $this->name ), $fname
);
# Update the current image row
$dbw->update( 'image',
array( /* SET */
'img_size' => $this->size,
'img_width' => $this->width,
'img_height' => $this->height,
'img_bits' => $this->bits,
'img_type' => $this->type,
'img_timestamp' => $dbw->timestamp(),
'img_user' => $wgUser->getID(),
'img_user_text' => $wgUser->getName(),
'img_description' => $desc,
), array( /* WHERE */
'img_name' => $this->name
), $fname
);
# Invalidate the cache for the description page
$descTitle->invalidateCache();
}
$log = new LogPage( 'upload' );
$log->addEntry( 'upload', $descTitle, $desc );
return true;
}
} //class
/**
* Returns the image directory of an image
* If the directory does not exist, it is created.
* The result is an absolute path.
*
* @param string $fname file name of the image file
* @access public
*/
function wfImageDir( $fname ) {
global $wgUploadDirectory, $wgHashedUploadDirectory;
if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
$hash = md5( $fname );
$oldumask = umask(0);
$dest = $wgUploadDirectory . '/' . $hash{0};
if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
$dest .= '/' . substr( $hash, 0, 2 );
if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
umask( $oldumask );
return $dest;
}
/**
* Returns the image directory of an image's thubnail
* If the directory does not exist, it is created.
* The result is an absolute path.
*
* @param string $fname file name of the thumbnail file, including file size prefix
* @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
* @param boolean $shared (optional) use the shared upload directory
* @access public
*/
function wfImageThumbDir( $fname , $subdir='thumb', $shared=false) {
return wfImageArchiveDir( $fname, $subdir, $shared );
}
/**
* Returns the image directory of an image's old version
* If the directory does not exist, it is created.
* The result is an absolute path.
*
* @param string $fname file name of the thumbnail file, including file size prefix
* @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
* @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
* @access public
*/
function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
global $wgUploadDirectory, $wgHashedUploadDirectory,
$wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
$dir = $shared ? $wgSharedUploadDirectory : $wgUploadDirectory;
$hashdir = $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
if (!$hashdir) { return $dir.'/'.$subdir; }
$hash = md5( $fname );
$oldumask = umask(0);
# Suppress warning messages here; if the file itself can't
# be written we'll worry about it then.
$archive = $dir.'/'.$subdir;
if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
$archive .= '/' . $hash{0};
if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
$archive .= '/' . substr( $hash, 0, 2 );
if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
umask( $oldumask );
return $archive;
}
/*
* Return the hash path component of an image path (URL or filesystem),
* e.g. "/3/3c/", or just "/" if hashing is not used.
*
* @param $dbkey The filesystem / database name of the file
* @param $fromSharedDirectory Use the shared file repository? It may
* use different hash settings from the local one.
*/
function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
global $wgHashedUploadDirectory;
$ishashed = $fromSharedDirectory ? $wgHashedSharedUploadDirectory :
$wgHashedUploadDirectory;
if($ishashed) {
$hash = md5($dbkey);
return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
} else {
return '/';
}
}
/**
* Returns the image URL of an image's old version
*
* @param string $fname file name of the image file
* @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
* @access public
*/
function wfImageArchiveUrl( $name, $subdir='archive' ) {
global $wgUploadPath, $wgHashedUploadDirectory;
if ($wgHashedUploadDirectory) {
$hash = md5( substr( $name, 15) );
$url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
substr( $hash, 0, 2 ) . '/'.$name;
} else {
$url = $wgUploadPath.'/'.$subdir.'/'.$name;
}
return wfUrlencode($url);
}
/**
* Return a rounded pixel equivalent for a labeled CSS/SVG length.
* http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
*
* @param string $length
* @return int Length in pixels
*/
function wfScaleSVGUnit( $length ) {
static $unitLength = array(
'px' => 1.0,
'pt' => 1.25,
'pc' => 15.0,
'mm' => 3.543307,
'cm' => 35.43307,
'in' => 90.0,
'' => 1.0, // "User units" pixels by default
'%' => 2.0, // Fake it!
);
if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
$length = FloatVal( $matches[1] );
$unit = $matches[2];
return round( $length * $unitLength[$unit] );
} else {
// Assume pixels
return round( FloatVal( $length ) );
}
}
/**
* Compatible with PHP getimagesize()
* @todo support gzipped SVGZ
* @todo check XML more carefully
* @todo sensible defaults
*
* @param string $filename
* @return array
*/
function wfGetSVGsize( $filename ) {
$width = 256;
$height = 256;
// Read a chunk of the file
$f = fopen( $filename, "rt" );
if( !$f ) return false;
$chunk = fread( $f, 4096 );
fclose( $f );
// Uber-crappy hack! Run through a real XML parser.
if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
return false;
}
$tag = $matches[1];
if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
$width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
}
if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
$height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
}
return array( $width, $height, 'SVG',
"width=\"$width\" height=\"$height\"" );
}
/**
* Wrapper class for thumbnail images
* @package MediaWiki
*/
class ThumbnailImage {
/**
* @param string $path Filesystem path to the thumb
* @param string $url URL path to the thumb
* @access private
*/
function ThumbnailImage( $path, $url ) {
$this->url = $url;
$this->path = $path;
$size = @getimagesize( $this->path );
if( $size ) {
$this->width = $size[0];
$this->height = $size[1];
} else {
$this->width = 0;
$this->height = 0;
}
}
/**
* @return string The thumbnail URL
*/
function getUrl() {
return $this->url;
}
/**
* Return HTML <img ... /> tag for the thumbnail, will include
* width and height attributes and a blank alt text (as required).
*
* You can set or override additional attributes by passing an
* associative array of name => data pairs. The data will be escaped
* for HTML output, so should be in plaintext.
*
* @param array $attribs
* @return string
* @access public
*/
function toHtml( $attribs = array() ) {
$attribs['src'] = $this->url;
$attribs['width'] = $this->width;
$attribs['height'] = $this->height;
if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
$html = '<img ';
foreach( $attribs as $name => $data ) {
$html .= $name . '="' . htmlspecialchars( $data ) . '" ';
}
$html .= '/>';
return $html;
}
/**
* Return the size of the thumbnail file, in bytes or false if the file
* can't be stat().
* @access public
*/
function getSize() {
$st = stat( $this->path );
if( $st ) {
return $st['size'];
} else {
return false;
}
}
}
?>
|