-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.js
1925 lines (1803 loc) · 49.3 KB
/
main.js
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
/**
* DEep WiKi INspector (DEWKIN)
* Copyright (C) 2013-2020 Ricordisamoa
*
* https://meta.wikimedia.org/wiki/User:Ricordisamoa
* https://tools.wmflabs.org/ricordisamoa/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
( function () {
'use strict';
var util;
window.charts = {};
/**
* Comparison function for sorting arrays of timestamp-based items.
*
* @param {{timestamp: string}} a
* @param {{timestamp: string}} b
* @return {-1|0|1} -1 if a < b, 1 if a > b, 0 otherwise
*/
function compareByTimestamp( a, b ) {
var ts1 = new Date( a.timestamp ),
ts2 = new Date( b.timestamp );
return ( ( ts1 < ts2 ) ? -1 : ( ( ts1 > ts2 ) ? 1 : 0 ) );
}
/**
* Group items by edit tag.
*
* @template {{tags?: string[]}} T
* @param {T[]} array Array of items
* @return {Object<string, T[]>} Map of tag to array of items
*/
function groupByTag( array ) {
var contr = {};
array.forEach( function ( e ) {
( e.tags || [] ).forEach( function ( tag ) {
if ( contr[ tag ] ) {
contr[ tag ].push( e );
} else {
contr[ tag ] = [ e ];
}
} );
} );
return contr;
}
/**
* Group items by year & month.
*
* @template {{timestamp: string}} T
* @param {T[]} array Array of timestamped items
* @return {Object<string, T[]>} Map of year & month to array of items
*/
function groupByMonth( array ) {
var firstMonth,
contr = {},
s = {};
array.forEach( function ( e ) {
var date = new Date( e.timestamp ),
code = util.yearMonth( date );
if ( firstMonth === undefined || code < firstMonth ) {
firstMonth = code;
}
if ( contr[ code ] ) {
contr[ code ].push( e );
} else {
contr[ code ] = [ e ];
}
} );
util.allMonths( firstMonth ).forEach( function ( e ) {
if ( contr[ e ] ) {
s[ e ] = contr[ e ];
} else {
s[ e ] = [];
}
} );
return s;
}
/**
* Group items by programming language.
*
* @template {{ns: number, title: string}} T
* @param {T[]} array Array of items with namespace number and title
* @return {Object<string, T[]>} Map of language identifier to array of items
*/
function groupByProgrammingLanguage( array ) {
var contr = {};
array.forEach( function ( c ) {
var lang, m;
if ( c.ns === 828 ) { // Scribunto modules
lang = 'lua';
} else if ( [ 2, 8 ].indexOf( c.ns ) !== -1 ) {
m = c.title.toLowerCase().match( /\.(js|css)$/ );
if ( m !== null ) {
lang = m[ 1 ];
} else if ( c.ns === 2 && /\.py$/.test( c.title ) ) {
lang = 'py';
}
}
if ( lang ) {
if ( !contr[ lang ] ) {
contr[ lang ] = [];
}
contr[ lang ].push( c );
}
} );
return contr;
}
/**
* Filter items by edit summary.
*
* @template {{comment: string}} T
* @param {T[]} array Array of items with comment
* @param {string} [summary] String for exact match, undefined to match any non-empty summary
* @return {T[]} Filtered array
*/
function filterByEditSummary( array, summary ) {
return array.filter( function ( e ) {
return ( summary === undefined ? e.comment !== '' : e.comment === summary );
} );
}
/**
* Filter items by namespace number.
*
* @template {{ns: number}} T
* @param {T[]} array Array of items with namespace number
* @param {number|number[]} ns Namespace number(s)
* @return {T[]} Filtered array
*/
function filterByNamespace( array, ns ) {
return array.filter( function ( e ) {
return Array.isArray( ns ) ? ( ns.indexOf( e.ns ) !== -1 ) : ( e.ns === ns );
} );
}
/**
* Group items by namespace number.
*
* @template {{ns: number}} T
* @param {T[]} array Array of items with namespace number
* @param {number[]} nsNumbers Array of namespace numbers
* @param {boolean} alsoEmpty Whether to include namespaces with no occurrences
* @return {Object<string, T[]>} Map of namespace number to array of items
*/
function groupByNamespace( array, nsNumbers, alsoEmpty ) {
var contr = {};
nsNumbers.forEach( function ( ns ) {
var f = filterByNamespace( array, ns );
if ( f.length > 0 || alsoEmpty === true ) {
contr[ ns ] = f;
}
} );
return contr;
}
/**
* Group items by year & month, then by namespace number.
*
* @template {{ns: number, timestamp: string}} T
* @param {T[]} array Array of items with namespace number and timestamp
* @param {number[]} nsNumbers Array of namespace numbers
* @return {Object<string, Object<string, T[]>>} Map of year & month to map of
* namespace number to array of items
*/
function groupByMonthAndNamespace( array, nsNumbers ) {
var contr = {};
$.each( groupByMonth( array ), function ( k, v ) {
contr[ k ] = groupByNamespace( v, nsNumbers, true );
} );
return contr;
}
/**
* Get the (at most) 30 titles with the highest number of occurrences.
*
* @template {{title: string}} T
* @param {T[]} array Array of items with title
* @return {[Object<string, number>, boolean]} Map of title to occurrence count sorted by
* value in descending order, and whether more than 30 unique titles were found
*/
function topEdited( array ) {
var titles, occurr, sortedKeys, overflow, sortedOccurr;
titles = array.map( function ( e ) {
return e.title;
} );
occurr = {};
titles.forEach( function ( e ) {
if ( occurr[ e ] ) {
occurr[ e ] = occurr[ e ] + 1;
} else {
occurr[ e ] = 1;
}
} );
sortedKeys = Object.keys( occurr ).sort( function ( a, b ) {
return (
( occurr[ a ] > occurr[ b ] ) ? -1 : ( ( occurr[ a ] < occurr[ b ] ) ? 1 : 0 )
);
} );
overflow = false;
if ( sortedKeys.length > 30 ) {
overflow = true;
sortedKeys = sortedKeys.slice( 0, 30 );
}
sortedOccurr = {};
sortedKeys.forEach( function ( e ) {
sortedOccurr[ e ] = occurr[ e ];
} );
return [ sortedOccurr, overflow ];
}
/**
* Get data suitable for a punchcard chart.
*
* @template {{timestamp: string}} T
* @param {T[]} array Array of timestamped items
* @return {[number, number, number][]} Arrays in the form [day 0-6, hour 0-23, number of edits]
*/
function toPunchcard( array ) {
var d, h,
data = [];
for ( d = 0; d < 7; d++ ) {
for ( h = 0; h < 24; h++ ) {
data.push( [ d, h, 0 ] );
}
}
array.forEach( function ( e ) {
var date = new Date( e.timestamp );
data[ date.getUTCDay() * 24 + date.getUTCHours() ][ 2 ]++;
} );
return data;
}
/**
* Compute the longest sequence of consecutive days with at least one occurrence each.
*
* @template {{timestamp: string}} T
* @param {T[]} array Array of timestamped items
* @return {[number, number]|[]} The start and end date of one of the longest streaks,
* or empty if none can be found
*/
function longestStreak( array ) {
var prev = [],
cur = [],
cc = array.slice(),
sameOrNext = function ( d1, d2 ) {
return d1 === d2 || ( d2 - d1 === 86400000 );
};
cc.sort( compareByTimestamp );
cc.forEach( function ( ct, i ) {
var d = new Date( ct.timestamp ).setHours( 0, 0, 0, 0 );
if ( cur.length === 0 ) {
cur[ 0 ] = d;// start streak
} else if ( cur.length === 1 ) {
if ( sameOrNext( cur[ 0 ], d ) ) {
cur[ 1 ] = d;// continue streak
} else {
cur = [];
}
} else if ( cur.length === 2 ) {
if ( i < cc.length && sameOrNext( cur[ 1 ], d ) ) {
cur[ 1 ] = d;// continue streak
} else { // streak broken
if ( prev.length === 0 || cur[ 1 ] - cur[ 0 ] > prev[ 1 ] - prev[ 0 ] ) {
prev = cur;// (over)write longest streak
}
cur = [];// reset current streak anyway
}
}
} );
return prev;
}
/**
* Interface to MediaWiki's action API.
*
* @class
*
* @param {string} url
*/
function MediaWikiApi( url ) {
this.url = url;
this.defaults = {
format: 'json'
};
}
/**
* Send a GET request to the MediaWiki API.
*
* @param {Object} data Parameters for the request
* @return {JQuery.Promise}
*/
MediaWikiApi.prototype.get = function ( data ) {
return $.ajax( {
dataType: 'jsonp',
type: 'GET',
url: this.url,
data: $.extend( {}, data, this.defaults )
} );
};
/**
* @typedef {Object} Edit
* @property {number} revid Unique revision key
* @property {number} ns Namespace code
* @property {string} title Full page title
* @property {string} timestamp ISO 8601 format
* @property {string} comment Edit summary
* @property {number} sizediff Size delta in bytes against the parent (or empty) revision
* @property {string[]} tags Change tags
*/
/**
* @typedef {Object} BaseUserInfo
* @property {string|null|undefined} registration Timestamp in ISO 8601 format
* @property {number|undefined} editcount Total edits as counted by MediaWiki
*/
/**
* @typedef {Object} BlockInfo
* @property {number} blockid ID of the block
* @property {string} blockedby Name of the user who placed/changed the block
* @property {string} blockreason Reason provided for the block
* @property {string} blockexpiry Expiration time of the block (may be infinite)
*/
/**
* @typedef {BaseUserInfo & (BlockInfo | {})} UserInfo
*/
/**
* Helper class for getting data from the MediaWiki API.
*
* @class
*
* @param {Object} config Configuration options
* @param {MediaWikiApi} [config.localApi] Interface to the API of the site the
* inspector should run on
* @param {MediaWikiApi} config.globalApi Interface to the API of the site exposing the site matrix
*/
function DataGetter( config ) {
this.localApi = config.localApi;
this.globalApi = config.globalApi;
}
/**
* @typedef {Object} User
* @property {number} userid
* @property {string} name
*/
/**
* @typedef {Object} GlobalUser
* @property {string} id
* @property {string} name
*/
DataGetter.prototype = {
/**
* Fetch local accounts with editcount > 0 whose names begin with the given prefix.
*
* Names are selected in ascending order. Up to eight items will be returned.
*
* @param {string} prefix
* @return {JQuery.Promise<User[]>}
*/
allUsers: function ( prefix ) {
return this.localApi.get( {
action: 'query',
formatversion: '2',
list: 'allusers',
auwitheditsonly: 1,
auprefix: prefix,
aulimit: 8
} )
.then( function ( data ) {
return data.query.allusers;
} );
},
/**
* Fetch global accounts whose names begin with the given prefix.
*
* Names are selected in ascending order. Up to eight items will be returned.
*
* @param {string} prefix
* @return {JQuery.Promise<GlobalUser[]>}
*/
globalAllUsers: function ( prefix ) {
return this.globalApi.get( {
action: 'query',
formatversion: '2',
list: 'globalallusers',
aguprefix: prefix,
agulimit: 8
} )
.then( function ( data ) {
return data.query.globalallusers;
} );
},
siteMatrix: function () {
return this.globalApi.get( {
action: 'sitematrix',
formatversion: '2',
smsiteprop: 'dbname|url',
smlangprop: 'site'
} )
.then( function ( data ) {
var dbNames = {};
$.each( data.sitematrix, function () {
( this.site || ( Array.isArray( this ) ? this : [] ) ).forEach( function ( site ) {
if (
site.dbname &&
site.url &&
!site.private &&
!site.fishbowl
) {
dbNames[ site.dbname ] = site.url;
}
} );
} );
return dbNames;
} );
},
namespaces: function () {
return this.localApi.get( {
action: 'query',
formatversion: '2',
meta: 'siteinfo',
siprop: 'namespaces'
} )
.then( function ( b ) {
var ns = b.query.namespaces;
delete ns[ '-1' ];
return ns;
} );
},
uploads: function () {
var self = this,
uploads = [],
getUploadsRecursive = function ( continuation ) {
var params = {
action: 'query',
formatversion: '2',
list: 'allimages',
aiprop: '',
aisort: 'timestamp',
aiuser: self.user,
ailimit: 'max'
};
if ( continuation !== undefined ) {
$.extend( params, continuation );
}
return self.localApi.get( params ).then( function ( data ) {
uploads = uploads.concat( data.query.allimages.map( function ( e ) {
return e.name.replace( /_/g, ' ' );
} ) );
if ( data.continue ) {
return getUploadsRecursive( data.continue );
} else {
return uploads;
}
} );
};
return getUploadsRecursive();
},
/**
* Fetch registration timestamp, edit count, block info and all contributions.
*
* @return {JQuery.Promise<{contribs: Edit[], info: UserInfo}>}
*/
contribs: function () {
var info,
self = this,
contribs = [],
getContribsRecursive = function ( continuation ) {
var params = {
action: 'query',
formatversion: '2',
list: 'usercontribs',
ucuser: self.user,
ucprop: 'title|timestamp|comment|tags|ids|sizediff',
uclimit: 'max'
};
if ( continuation !== undefined ) {
$.extend( params, continuation );
} else {
params.list += '|users';
params.ususers = self.user;
params.usprop = 'registration|editcount|blockinfo';
}
return self.localApi.get( params ).then( function ( data ) {
contribs = contribs.concat( data.query.usercontribs );
if ( data.query.users ) {
info = data.query.users[ 0 ];
}
if ( data.continue ) {
return getContribsRecursive( data.continue );
} else {
return { contribs: contribs, info: info };
}
} );
};
return getContribsRecursive();
},
messages: function ( lang, msgs ) {
var getMessagesRecursive,
self = this,
messages = {};
msgs = msgs.slice(); // clone
getMessagesRecursive = function () {
return self.localApi.get( {
action: 'query',
formatversion: '2',
meta: 'allmessages',
amlang: lang,
ammessages: msgs.splice( 0, 50 ).join( '|' )
} )
.then( function ( data ) {
( data.query.allmessages || [] ).forEach( function ( v ) {
messages[ v.name ] = v.content;
} );
if ( msgs.length > 0 ) {
return getMessagesRecursive();
}
return messages;
} );
};
return getMessagesRecursive();
},
/**
* @return {JQuery.Promise<RightsLogEvent[]>}
*/
rightsLog: function () {
return this.localApi.get( {
action: 'query',
formatversion: '2',
list: 'logevents',
letype: 'rights',
letitle: 'User:' + this.user,
ledir: 'newer',
lelimit: 'max'
} )
.then( function ( data ) {
return data.query.logevents.filter( function ( el ) {
// hack for old log entries
return (
el.params !== undefined &&
el.params.oldgroups !== undefined &&
el.params.newgroups !== undefined
);
} );
} );
},
votes: function () {
return $.getJSON( 'https://tools.wmflabs.org/octodata/sucker.php', {
action: 'votelookup',
username: this.user,
groupby: 'ballot'
} );
},
geoData: function ( contribs ) {
var geodata, titles, getGeodataRecursive,
occurr = {},
self = this;
contribs.forEach( function ( val ) {
if ( occurr[ val.title ] ) {
if ( occurr[ val.title ].revid ) {
occurr[ val.title ] = {
count: 2,
sizediff: occurr[ val.title ].sizediff + val.sizediff
};
} else {
occurr[ val.title ].count += 1;
occurr[ val.title ].sizediff += val.sizediff;
}
} else {
occurr[ val.title ] = val;
}
} );
geodata = [];
titles = Object.keys( occurr );
if ( titles.length === 0 ) {
// Don't waste an AJAX request
return $.Deferred().resolve( [] ).promise();
}
getGeodataRecursive = function () {
// Prevent queries from exceeding the title count limit as well
// as the URL length limit for Wikimedia servers
var cut, len,
maxLength = 8070;
for ( cut = 0, len = 0; cut < titles.length && cut < 50; cut++ ) {
len += encodeURIComponent( titles[ cut ] ).length;
if ( len === maxLength ) {
// include titles up to current one
cut++;
break;
}
if ( len > maxLength ) {
// include titles up to previous one
break;
}
len += 3; // separator: %7C
}
return self.localApi.get( {
action: 'query',
formatversion: '2',
prop: 'coordinates',
titles: titles.splice( 0, cut ).join( '|' )
} )
.then( function ( data ) {
geodata = geodata.concat( data.query.pages );
if ( titles.length > 0 ) {
return getGeodataRecursive();
} else {
return geodata;
}
} );
};
return getGeodataRecursive().then( function ( coords ) {
var coordinates, edits, numedits, marker,
markers = [];
coords.forEach( function ( page ) {
if ( page.coordinates ) {
coordinates = page.coordinates;
if ( coordinates.length === 1 ) {
coordinates = coordinates[ 0 ];
edits = occurr[ page.title ];
numedits = ( edits.count || 1 );
marker = {
coords: coordinates,
title: page.title,
sizediff: edits.sizediff,
numedits: numedits
};
if ( edits.revid ) {
$.extend( marker, { revid: edits.revid } );
}
markers.push( marker );
}
}
} );
markers.sort( function ( a, b ) {
return b.numedits - a.numedits;
} );
return markers;
} );
}
};
util = {
/**
* Get the month code from a date.
*
* @param {Date} date
* @return {string} The month code in the form yyyy/mm
*/
yearMonth: function ( date ) {
var month = ( date.getUTCMonth() + 1 ).toString();
if ( month.length === 1 ) {
month = '0' + month;
}
return date.getUTCFullYear() + '/' + month;
},
/**
* Set of HEX colors by MediaWiki namespace number from Soxred93's Edit Counter
* Copyright (C) 2010 Soxred93
* Released under the terms of the GNU General Public License
* source code: <https://tools.wmflabs.org/xtools/pcount/source.php?path=index>
*/
namespaceColors: {
0: 'FF5555',
1: '55FF55',
2: 'FFFF55',
3: 'FF55FF',
4: '5555FF',
5: '55FFFF',
6: 'C00000',
7: '0000C0',
8: '008800',
9: '00C0C0',
10: 'FFAFAF',
11: '808080',
12: '00C000',
13: '404040',
14: 'C0C000',
15: 'C000C0',
100: '75A3D1',
101: 'A679D2',
102: '660000',
103: '000066',
104: 'FAFFAF',
105: '408345',
106: '5c8d20',
107: 'e1711d',
108: '94ef2b',
109: '756a4a',
110: '6f1dab',
111: '301e30',
112: '5c9d96',
113: 'a8cd8c',
114: 'f2b3f1',
115: '9b5828',
120: 'FF99FF',
121: 'CCFFFF',
122: 'CCFF00',
123: 'CCFFCC',
200: '33FF00',
201: '669900',
202: '666666',
203: '999999',
204: 'FFFFCC',
205: 'FF00CC',
206: 'FFFF00',
207: 'FFCC00',
208: 'FF0000',
209: 'FF6600',
446: '06DCFB',
447: '892EE4',
460: '99FF66',
461: '99CC66',
470: 'CCCC33',
471: 'CCFF33',
480: '6699FF',
481: '66FFFF',
710: 'FFCECE',
711: 'FFC8F2',
828: 'F7DE00',
829: 'BABA21',
866: 'FFFFFF',
867: 'FFCCFF',
1198: 'FF34B3',
1199: '8B1C62'
},
/* end of Soxred93's code */
/**
* Get the color code of a namespace, falling back to #CCC.
*
* @param {number} ns The namespace id
* @return {string} The color code
*/
colorFromNamespace: function ( ns ) {
return '#' + ( this.namespaceColors[ ns ] || 'CCC' );
},
/**
* Map of programming language codes to names and colors,
* inspired by https://github.com/github/linguist/blob/master/lib/linguist/languages.yml
*/
programmingLanguages: {
css: [ 'CSS', '563d7c' ],
js: [ 'JavaScript', 'f1e05a' ],
lua: [ 'Lua', '000080' ],
py: [ 'Python', '3572A5' ]
},
/**
* Array of colors for map markers,
* subset of https://commons.wikimedia.org/wiki/Special:PrefixIndex/File:Location_dot
*/
markerColors: [ 'bisque', 'black', 'blue', 'coral', 'cyan', 'darkslategray', 'deeppink', 'green',
'lightgrey', 'lime', 'magenta', 'orange', 'purple', 'red', 'teal', 'yellow' ],
/**
* Set of arbitrary HTML colors by MediaWiki user group
*/
groupsColors: {
autopatrolled: 'dodgerblue',
rollbacker: 'darkolivegreen',
filemover: 'orange',
translationadmin: 'orangered',
sysop: 'darkred',
bureaucrat: 'darkviolet',
checkuser: 'darkslategray',
oversight: 'navy',
steward: 'black'
},
/**
* Get an array of month codes between two months (included).
*
* @param {string} from Month code in the form yyyy/mm
* @return {string[]} Array of month codes in the form yyyy/mm
*/
allMonths: function ( from ) {
var fromSplit, fromYear, fromMonth, months, toYear, toMonth,
year, actualToYear, month, m;
fromSplit = from.split( '/' );
fromYear = parseInt( fromSplit[ 0 ] );
fromMonth = parseInt( fromSplit[ 1 ] ) - 1;
months = [];
toYear = new Date().getUTCFullYear();
toMonth = new Date().getUTCMonth();
for ( year = fromYear; year <= toYear; year++ ) {
actualToYear = ( year === toYear ? toMonth : 11 );
for ( month = ( year === fromYear ? fromMonth : 0 ); month <= actualToYear; month++ ) {
m = ( month + 1 ).toString();
months.push( year + '/' + ( m.length === 1 ? '0' : '' ) + m );
}
}
return months;
}
};
/**
* Class to handle localization.
*
* @class
*
* @param {string} language Language code of the UI
* @param {DataGetter} dataGetter To use the allmessages API
*/
function Localizer( language, dataGetter ) {
this.language = language;
this.fallback = 'en';
this.dataGetter = dataGetter;
this.messages = {};
}
/**
* Get localized messages from the wiki and from the current instance of DEWKIN.
*
* @param {string[]} messages MediaWiki message keys
* @return {JQuery.Promise<void>}
*/
Localizer.prototype.loadMessages = function ( messages ) {
var self = this;
return self.dataGetter.messages( self.language, messages )
.then( function ( data ) {
$.extend( self.messages, data );
self.harvestMonthsAndWeekdays();
return self.loadCustomMessages( self.language );
} );
};
/**
* Set some properties on the current instance as arrays of localized messages.
*
* @private
*/
Localizer.prototype.harvestMonthsAndWeekdays = function () {
var self = this;
self.months = Localizer.months.map( function ( el ) {
return self.messages[ el ];
} );
self.weekdays = Localizer.weekdays.map( function ( el ) {
return self.messages[ el ];
} );
self.weekdaysShort = Localizer.weekdaysShort.map( function ( el ) {
return self.messages[ el ];
} );
};
/**
* Get localized messages from the current instance of DEWKIN.
*
* @private
* @param {string} lang MediaWiki language code
* @return {JQuery.Promise<void>}
*/
Localizer.prototype.loadCustomMessages = function ( lang ) {
var self = this;
return $.get( 'i18n/' + lang + '.json' )
.then( function ( data ) {
self.messages = $.extend( {}, data, self.messages );
if ( lang !== self.fallback ) {
return self.loadCustomMessages( self.fallback );
}
} )
.catch( function () {
if ( lang !== self.fallback ) {
return self.loadCustomMessages( self.fallback );
}
} );
};
/**
* Apply parameter substitution and evaluate PLURAL syntax within a message.
*
* @private
* @param {string} msg The raw message
* @param {...Mixed} arguments The parameters
* @return {string} The final message
*/
Localizer.prototype.parseMsg = function ( msg ) {
var regex = /(^|[^/])\$(\d+)(?=\D|$)/g,
args = Array.prototype.slice.call( arguments, 1 );
msg = msg.replace( regex, function ( el, p1, p2 ) {
if ( args[ parseInt( p2 ) - 1 ] !== undefined ) {
return p1 + args[ parseInt( p2 ) - 1 ];
} else {
return el;
}
} );
regex = /\{\{PLURAL:(-?\d+(?:\.\d+)?)\|([^|]*)(?:\|([^|]*))?\}\}/g;
msg = msg.replace( regex, function ( el, p1, p2, p3 ) {
return parseFloat( p1 ) === 1 ? p2 : ( p3 || p2 );
} );
return msg;
};
/**
* Get an array joined with natural separators.
*
* @param {Array} array
* @return {string}
*/
Localizer.prototype.listToText = function ( array ) {
var comma = this.i18n( 'comma-separator' ),
sep = this.i18n( 'word-separator' ),
and = this.i18n( 'and' );
switch ( array.length ) {
case 0: return '';
case 1: return array[ 0 ];
case 2: return array.join( sep + and + sep );
default: return array.slice( 0, -1 ).join( comma ) + comma +
and + sep + array[ array.length - 1 ];
}
};
/**
* Get a localized percentage.
*
* @param {number} num Numerator
* @param {number} outof Denominator
* @param {number} [precision=2] Number of decimal digits to show
* @param {Mixed} [format] If provided, used instead of num for display
* @return {string}
*/
Localizer.prototype.percent = function ( num, outof, precision, format ) {
if ( precision === undefined ) {
precision = 2;
}
return ( format || num.toLocaleString() ) + this.i18n( 'word-separator' ) +
this.i18n( 'parentheses',
this.i18n( 'percent', parseFloat(
( num / outof * 100 ).toFixed( precision ) )
)
);
};
/**
* Get the name of a user group on the current project.
*
* @param {string} group
* @return {string} Can be localized and/or HTML
*/
Localizer.prototype.groupColor = function ( group ) {
var local = ( this.messages[ 'group-' + group + '-member' ] || group );
return util.groupsColors[ group ] ?
( '<span style="background-color:' + util.groupsColors[ group ] +
';color:white">' + local + '</span>' ) :
local;
};
/**
* Get a human-readable difference between two dates.
*
* @param {Date} olddate
* @param {Date} [newdate]
* @param {number|null} [precision]