-
Notifications
You must be signed in to change notification settings - Fork 0
/
AWB.js
1426 lines (1352 loc) · 54.1 KB
/
AWB.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
/**<nowiki>
* Install this script by pasting the following in your personal JavaScript file:
importScriptURI('//en.wikipedia.org/w/index.php?title=User:Joeytje50/AWB.js/load.js&action=raw&ctype=text/javascript');
* Or for users on en.wikipedia.org:
{{subst:iusc|User:Joeytje50/AWB.js/load.js}}
* Note that this script will only run on the 'Project:AutoWikiBrowser/Script' page.
* This script is based on the downloadable AutoWikiBrowser.
*
* @licence
* 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 2 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, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
* @version 2.0
* @author Joeytje50
*/
window.AWB = {}; //The main global object for the script.
/***** User verification *****/
;(function() {
if (wgCanonicalNamespace+':'+wgTitle !== 'Project:AutoWikiBrowser/Script' || AWB.allowed === false) {
AWB.allowed = false;
return;
}
importStylesheetURI('//en.wikipedia.org/w/index.php?title=User:Joeytje50/AWB.css&action=raw&ctype=text/css');
mw.loader.load('mediawiki.action.history.diff');
var i18n = importScriptURI('//en.wikipedia.org/w/index.php?title=User:Joeytje50/AWB.js/i18n.js&action=raw&ctype=text/javascript');
i18n.onload = function() {
if (AWB.allowed === true) {
AWB.init(); //init if verification has already returned true
} else if (AWB.allowed === false) {
alert(AWB.msg('not-on-list'));
}
};
(new mw.Api()).get({
action: 'query',
titles: 'Project:AutoWikiBrowser/CheckPage',
prop: 'revisions',
meta: 'userinfo|siteinfo',
rvprop: 'content',
rvlimit: 1,
uiprop: 'groups',
siprop: 'namespaces',
indexpageids: true,
format: 'json',
}).done(function(response) {
if (response.error) {
alert('API error: ' + response.error.info);
AWB = false; //preventing further access. No verification => no access.
return;
}
AWB.ns = response.query.namespaces; //saving for later
AWB.username = response.query.userinfo.name; //preventing any "hacks" that change wgUserName or mw.config.wgUserName
var groups = response.query.userinfo.groups;
var page = response.query.pages[response.query.pageids[0]];
var users, bots;
if (response.query.pageids[0] !== '-1' && /<!--\s*enabledusersbegins\s*-->/.test(page.revisions[0]['*'])) {
var cont = page.revisions[0]['*'];
users = cont.substring(
cont.search(/<!--\s*enabledusersbegins\s*-->/),
cont.search(/<!--\s*enabledusersends\s*-->/)
).split('\n');
if (/<!--\s*enabledbots\s*-->/.test(cont)) {
bots = cont.substring(
cont.search(/<!--\s*enabledbots\s*-->/),
cont.search(/<!--\s*enabledbotsends\s*-->/)
).split('\n');
} else bots = [];
var i=0;
while (i<users.length) {
if (users[i].charAt(0) !== '*') {
users.splice(i,1);
} else {
users[i] = $.trim(users[i].substr(1));
i++;
}
}
i=0;
while (i<bots.length) {
if (bots[i].charAt(0) !== '*') {
bots.splice(i,1);
} else {
bots[i] = $.trim(bots[i].substr(1));
i++;
}
}
} else {
users = false; //fallback when page doesn't exist
}
AWB.bot = groups.indexOf('bot') !== -1 && (users === false || bots.indexOf(AWB.username) !== -1);
AWB.sysop = groups.indexOf('sysop') !== -1;
if (AWB.username === "Joeytje50" && response.query.userinfo.id === 13299994) {//TEMP: Dev full access to entire interface.
AWB.bot = true;
users.push("Joeytje50");
}
if (AWB.sysop || response.query.pageids[0] === '-1' || users.indexOf(AWB.username) !== -1 || users === false) {
AWB.allowed = true;
if (AWB.messages.en) AWB.init(); //init if messages have already loaded
} else {
if (AWB.messages.en) {
//run this after messages have loaded, so the message that shows is in the user's language
alert(AWB.msg('not-on-list'));
}
AWB = false; //prevent further access
}
}).fail(function(xhr, error) {
alert(AWB.msg('verify-error') + '\n' + error);
AWB = false; //preventing further access. No verification => no access.
});
})();
/***** Global object/variables *****/
var objs = ['page', 'api', 'fn', 'pl', 'messages', 'setup', 'settings', 'ns'];
for (var i=0;i<objs.length;i++) {
AWB[objs[i]] = {};
}
AWB.lang = mw.config.get('wgUserLanguage');
AWB.isStopped = true;
AWB.tooltip = window.tooltipAccessKeyPrefix || '';
/***** API functions *****/
//Main template for API calls
AWB.api.call = function(data, callback, onerror) {
data.format = 'json';
if (data.action !== 'query') data.bot = true;
$.ajax({
data: data,
dataType: 'json',
url: wgScriptPath + '/api.php',
type: 'POST',
success: function(response) {
if (response.error) {
alert('API error: ' + response.error.info);
AWB.stop();
} else {
callback(response);
}
},
error: function(xhr, error) {
alert('AJAX error: ' + error);
AWB.stop();
if (onerror) onerror();
}
});
};
//Get page diff, and process it for more interactivity
AWB.api.diff = function(callback) {
AWB.status('diff');
var editBoxInput = $('#editBoxArea').val();
var redirects = $('input.redirects:checked').val()==='follow'?'redirects':'inprop';
var data = {
'action': 'query',
'prop': 'info|revisions',
'indexpageids': true,
'titles': AWB.page.name,
'rvlimit': '1',
'rvdifftotext': editBoxInput
};
data[redirects] = 'redirect';
AWB.api.call(data, function(response) {
var pageExists = response.query.pageids[0] !== '-1';
var diff;
if (pageExists) {
var diffpage = response.query.pages[response.query.pageids[0]];
diff = diffpage.revisions[0].diff['*'];
if (diff === '') {
diff = '<h2>'+AWB.msg('no-changes-made')+'</h2>';
} else {
diff = '<table class="diff">'+
'<colgroup>'+
'<col class="diff-marker">'+
'<col class="diff-content">'+
'<col class="diff-marker">'+
'<col class="diff-content">'+
'</colgroup>'+
'<tbody>'+diff+'</tbody></table>';
}
} else {
diff = '<span style="font-weight:bold;color:red;">'+AWB.msg('page-not-exists')+'</span>';
}
$('#resultWindow').html(diff);
$('.diff-lineno').each(function() {
$(this).parent().attr('data-line',parseInt($(this).html().match(/\d+/)[0])-1).addClass('lineheader');
});
$('table.diff tr').each(function() { //add data-line attribute to every line, relative to the previous one. Used for click event.
if (!$(this).next().is('[data-line]') && !$(this).next().has('td.diff-deletedline + td.diff-empty')) {
$(this).next().attr('data-line',parseInt($(this).data('line'))+1);
} else if ($(this).next().has('td.diff-deletedline + td.diff-empty')) {
$(this).next().attr('data-line',$(this).data('line')); //copy over current data-line for deleted lines to prevent them from messing up counting.
}
});
AWB.status('done', false);
if (typeof(callback) === 'function') {
callback();
}
});
};
//Retrieve page contents/info, process them, and store information in AWB.page object.
AWB.api.get = function(pagename) {
AWB.pageCount();
if (!AWB.list[0] || AWB.isStopped) {
return AWB.stop();
}
if (pagename === '#PRE-PARSE-STOP') {
var curval = $('#articleList').val();
$('#articleList').val(curval.substr(curval.indexOf('\n') + 1));
$('#preparse').prop('checked', false);
AWB.stop();
return;
}
var redirect = $('input.redirects:checked').val();
var data = {
'action': 'query',
'prop': 'info|revisions',
'inprop': 'watched',
'intoken': 'edit|delete|protect|move|watch',
'titles': pagename,
'rvprop': 'content|timestamp|ids',
'rvlimit': '1',
'indexpageids': true,
'meta': 'userinfo',
'uiprop': 'hasmsg'
};
if (redirect=='follow'||redirect=='skip') data.redirects = true;
if (AWB.sysop) {
data.list = 'deletedrevs';
data.drprop = 'token';
}
AWB.status('load-page');
AWB.api.call(data, function(response) {
if (response.query.userinfo.hasOwnProperty('messages')) {
var view = wgScriptPath + '?title=Special:MyTalk';
var viewNew = view + '&diff=cur';
AWB.status(
'<span style="color:red;font-weight:bold;">'+
AWB.msg('status-newmsg',
'<a href="'+view+'" target="_blank">'+AWB.msg('status-talklink')+'</a>',
'<a href="'+viewNew+'" target="_blank">'+AWB.msg('status-difflink')+'</a>')+
'</span>', false);
alert(AWB.msg('new-message'));
AWB.stop();
return;
}
AWB.page = response.query.pages[response.query.pageids[0]];
AWB.page.name = AWB.list[0].split('|')[0];
AWB.page.pagevar = AWB.list[0].replace(/^.*?\|/, '');
AWB.page.content = AWB.page.revisions ? AWB.page.revisions[0]['*'] : '';
AWB.page.exists = !response.query.pages["-1"];
AWB.page.deletedrevs = response.query.deletedrevs;
AWB.page.watched = AWB.page.hasOwnProperty('watched');
if (response.query.redirects) {
AWB.page.name = response.query.redirects[0].to;
}
var newContent = AWB.replace(AWB.page.content);
if (AWB.stopped === true) return;
AWB.status('done', false);
var containRegex = $('#containRegex').prop('checked'), containFlags = $('#containFlags').val();
var skipContains = containRegex ? new RegExp($('#skipContains').val(), containFlags) : $('#skipContains').val();
var skipNotContains = containRegex ? new RegExp($('#skipNotContains').val(), containFlags) : $('#skipContains').val();
if (
($('#skipNoChange').prop('checked') && AWB.page.content === newContent) || //skip if no changes are made
($('#skipContains').val() && AWB.page.content.match(skipContains)) ||
($('#skipNotContains').val() && !AWB.page.content.match(skipNotContains)) ||
($('#exists-no').prop('checked') && !AWB.page.exists) ||
($('#exists-yes').prop('checked') && AWB.page.exists) ||
(redirect==='skip' && response.query.redirects) // variable redirect is defined outside this callback function.
) {
AWB.log('skip', AWB.page.name);
return AWB.next();
} else {
$('#editBoxArea').val(newContent);
if ($('#preparse').prop('checked')) {
$('#articleList').val($.trim($('#articleList').val()) + '\n' + AWB.list[0]); //move current page to the bottom
AWB.next();
return;
} else if (AWB.bot && $('#autosave').prop('checked')) {
AWB.api.diff(function() {
//timeout will take #throttle's value * 1000, if it's a number above 0. Currently defaults to 0.
setTimeout(AWB.api.submit, Math.max(+$('#throttle').val() || 0, 0) * 1000);
});
} else {
AWB.api.diff();
}
}
AWB.updateButtons();
});
};
//Some functions with self-explanatory names:
AWB.api.submit = function() {
AWB.status('submit');
var summary = $('#summary').val();
var data = {
'title': AWB.page.name,
'summary': summary,
'action': 'edit',
'basetimestamp': AWB.page.revisions ? AWB.page.revisions[0].timestamp : '',
'token': AWB.page.edittoken,
'text': $('#editBoxArea').val(),
'watchlist': $('#watchPage').val()
};
if ($('#minorEdit').prop('checked')) data.minor = true;
AWB.api.call(data, function(response) {
AWB.log('edit', response.edit.title, response.edit.newrevid);
AWB.status('done', false);
AWB.next();
});
};
AWB.api.preview = function() {
AWB.status('preview');
AWB.api.call({
'title': AWB.page.name,
'action': 'parse',
'text': $('#editBoxArea').val()
}, function(response) {
$('#resultWindow').html(response.parse.text['*']);
$('#resultWindow div.previewnote').remove();
AWB.status('done', false);
});
};
AWB.api.move = function() {
AWB.status('move');
var topage = $('#moveTo').val().replace(/$x/gi, AWB.page.pagevar);
var summary = $('#summary').val();
var data = {
'action':'move',
'from': AWB.page.name,
'to': topage,
'token': AWB.page.movetoken,
'reason': summary,
'ignorewarnings': 'yes'
};
if ($('#moveTalk').prop('checked')) data.movetalk = true;
if ($('#moveSubpage').prop('checked')) data.movesubpages = true;
if ($('#suppressRedir').prop('checked')) data.noredirect = true;
AWB.api.call(data, function(response) {
AWB.log('move', response.move.from, reponse.move.to);
AWB.status('done', false);
if (!$('#moveTo').val().match(/$x/i)) $('#moveTo').val('')[0].focus(); //clear entered move-to pagename if it's not based on the pagevar
AWB.next(topage);
});
};
AWB.api.delete = function() {
AWB.status(($('#deletePage').is('.undelete') ? 'un' : '') + 'delete');
var summary = $('#summary').val();
var undeltoken = AWB.page.deletedrevs ? AWB.page.deletedrevs[0].token : '';
AWB.api.call({
'action': (!AWB.page.exists ? 'un' : '') + 'delete',
'title': AWB.page.name,
'token': AWB.page.exists ? AWB.page.deletetoken : undeltoken,
'reason': summary
}, function(response) {
AWB.log((!AWB.page.exists ? 'un' : '') + 'delete', (response.delete||response.undelete).title);
AWB.status('done', false);
AWB.next(response.undelete && response.undelete.title);
});
};
AWB.api.protect = function() {
AWB.status('protect');
var summary = $('#summary').val();
var editprot = $('#editProt').val();
var moveprot = $('#moveProt').val();
AWB.api.call({
'action':'protect',
'title': AWB.page.name,
'token': AWB.page.protecttoken,
'reason': summary,
'expiry': $('#protectExpiry').val()!==''?$('#protectExpiry').val():'infinite',
'protections': (AWB.page.exists?'edit='+editprot+'|move='+moveprot:'create='+editprot)
}, function(response) {
var protactions = '';
var prots = response.protect.protections;
for (var i=0;i<prots.length;i++) {
if (typeof prots[i].edit == 'string') {
protactions += ' edit: '+(prots[i].edit?prots[i].edit:'all');
} else if (typeof prots[i].move == 'string') {
protactions += ' move: '+(prots[i].move?prots[i].move:'all');
} else if (typeof prots[i].create == 'string') {
protactions += ' create: '+(prots[i].create?prots[i].create:'all');
}
}
protactions += ' expires: '+prots[0].expiry;
AWB.log('protect', response.protect.title, protactions);
AWB.status('done', false);
AWB.next(response.protect.title);
});
};
AWB.api.watch = function() {
AWB.status('watch');
var data = {
'action':'watch',
'title':AWB.page.name,
'token':AWB.page.watchtoken
};
if (AWB.page.watched) data.unwatch = true;
AWB.api.call(data, function(response) {
AWB.status('<span style="color:green;">'+
AWB.msg('status-watch-'+(AWB.page.watched ? 'removed' : 'added'), "'"+AWB.page.name+"'")+
'</span>', false);
AWB.page.watched = !AWB.page.watched;
$('#watchNow').html( AWB.msg('watch-' + (AWB.page.watched ? 'remove' : 'add')) );
});
};
/***** Pagelist functions *****/
AWB.pl.list = [];
AWB.pl.iterations = 0;
AWB.pl.getNSpaces = function() {
var list = $('#pagelistPopup [name="namespace"]')[0];
if (list.selectedOptions.length == list.options.length) {
return ''; //return empty string if every namespace is selected; this will make the request default to having no filter
} else {
return $('#pagelistPopup [name="namespace"]').val().join('|'); //.val() returns an array of selected options.
}
};
AWB.pl.getList = function(abbrs, lists, data) {
$('#pagelistPopup button, #pagelistPopup input, #pagelistPopup select').prop('disabled', true);
AWB.pl.iterations++;
data.action = 'query';
var nspaces = AWB.pl.getNSpaces();
for (var i=0;i<abbrs.length;i++) {
if (nspaces) data[abbrs[i]+'namespace'] = nspaces;
data[abbrs[i]+'limit'] = 10000;
}
if (lists.indexOf('links') !== -1) {
data.prop = 'links';
}
data.list = lists.join('|');
AWB.api.call(data, function(response) {
if (!response.query) response.query = {};
if (response.watchlistraw) response.query.watchlistraw = response.watchlistraw; //adding some consistency
if (response.query.pages) {
var links;
for (var id in response.query.pages) {
links = response.query.pages[id].links;
for (var i=0;i<links.length;i++) {
AWB.pl.list.push(links[i].title);
}
}
}
for (var l in response.query) {
if (l === 'pages') continue;
for (var i=0;i<response.query[l].length;i++) {
AWB.pl.list.push(response.query[l][i].title);
}
}
var cont = response['query-continue'];
if (cont && AWB.pl.iterations <= 50) { //allow up to 50 consecutive requests at a time to avoid overloading the server.
var lists = [];
var abbrs = [];
for (var list in cont) {
lists.push(list); //add to the new array of &list= values
for (var abbr in cont[list]) {
abbrs.push(abbr.replace('continue',''));
data[abbr] = cont[list][abbr]; //add the &xxcontinue= value to the data
}
}
AWB.pl.getList(abbrs, lists, data); //recursive function to get every page of a list
} else {
$('#articleList').val($.trim($('#articleList').val()) + '\n' + AWB.pl.list.join('\n'));
AWB.pageCount();
AWB.pl.list = [];
if (AWB.pl.iterations > 50) {
AWB.status('exceeded-iterations', false);
} else {
AWB.status('done', false);
}
AWB.pl.iterations = 0;
//re-enable where necessary
$('#pagelistPopup [disabled]:not(fieldset [disabled]), #pagelistPopup legend input').prop('disabled', false);
$('#pagelistPopup legend input').trigger('change');
$('#pagelistPopup button img').remove();
}
}, function() { //on error, go with what we have and then reset
$('#articleList').val($.trim($('#articleList').val()) + '\n' + AWB.pl.list.join('\n'));
AWB.pl.iterations = 0;
$('#pagelistPopup [disabled]:not(fieldset [disabled]), #pagelistPopup legend input').prop('disabled', false);
$('#pagelistPopup legend input').trigger('change');
$('#pagelistPopup button img').remove();
});
};
//AWB.pl.getList(['wr'], ['watchlistraw'], {}) for watchlists
AWB.pl.generate = function() {
var $fields = $('#pagelistPopup fieldset').not('[disabled]');
var spinner = '<img src="//upload.wikimedia.org/wikipedia/commons/d/de/Ajax-loader.gif" width="15" height="15" alt="'+AWB.msg('status-alt')+'"/>';
$('#pagelistPopup').find('button[type="submit"]').append(spinner);
var abbrs = [], lists = [], data = {};
$fields.each(function() {
var list = $(this).find('legend input').attr('name');
var abbr;
if (list === 'linksto') { //Special case since this fieldset features 3 merged lists in 1 fieldset
if (!$('[name="title"]').val()) return;
$('[name="backlinks"], [name="embeddedin"], [name="imageusage"]').filter(':checked').each(function() {
var val = this.value;
abbrs.push(val);
lists.push(this.name);
data[val+'title'] = $('[name="title"]').val();
data[val+'filterredir'] = $('[name="filterredir"]:checked').val();
if ($('[name="redirect"]').prop('checked')) data[val+'redirect'] = true;
});
} else { //default input system
abbr = $(this).find('legend input').val();
lists.push(list);
abbrs.push(abbr);
$(this).find('input').not('legend input').each(function() {
if ((this.type === 'checkbox' || this.type === 'radio') && this.checked === false) return;
if ($(this).is('[name="cmtitle"]')) {
//making sure every page has a Category: prefix, in case the user left it out
$(this).val(AWB.ns[14]['*']+':'+$(this).val().replace(new RegExp(AWB.ns[14]['*']+':', 'gi'), ''));
}
var name = this.name;
var val = this.value;
if (data.hasOwnProperty(name)) {
data[name] += '|'+val;
} else {
data[name] = val;
}
});
console.log(abbrs, lists, data);
}
});
if (abbrs.length) AWB.pl.getList(abbrs, lists, data);
};
/***** Setup functions *****/
AWB.setup.save = function(name) {
name = name || prompt(AWB.msg('setup-prompt', AWB.msg('setup-prompt-store')), $('#loadSettings').val());
if (name === null) return;
var self = AWB.settings[name] = {
string: {},
bool: {},
replaces: []
};
//inputs with a text value
$('textarea, input[type="text"], input[type="number"], select').not('.replaces input, #editBoxArea, #settings *').each(function() {
if (typeof $(this).val() == 'string') {
self.string[this.id] = this.value.replace(/\n{2,}/g,'\n');
} else {
self.string[this.id] = $(this).val();
}
});
self.replaces = [];
$('.replaces').each(function() {
if ($(this).find('.replaceText').val() || $(this).find('.replaceWith').val()) {
self.replaces.push({
replaceText: $(this).find('.replaceText').val(),
replaceWith: $(this).find('.replaceWith').val(),
useRegex: $(this).find('.useRegex').prop('checked'),
regexFlags: $(this).find('.regexFlags').val(),
ignoreNowiki: $(this).find('.ignoreNowiki').prop('checked')
});
}
});
$('input[type="radio"], input[type="checkbox"]').not('.replaces input').each(function() {
self.bool[this.id] = this.checked;
});
if (!$('#loadSettings option[value="'+name+'"]').length) {
$('#loadSettings').append('<option value="'+name+'">'+name+'</option>');
}
$('#loadSettings').val(name);
console.log(self);
};
AWB.setup.apply = function(name) {
name = name && AWB.settings[name] ? name : 'default';
var self = AWB.settings[name];
$('#loadSettings').val(name);
$('.replaces + .replaces').remove(); //reset find&replace inputs
$('.replaces input[type="text"]').val('');
$('.useRegex').each(function() {this.checked = false;});
$('#pagelistPopup legend input').trigger('change'); //fix checked state of pagelist generating inputs
for (var a in self.string) {
$('#'+a).val(self.string[a]);
}
for (var b in self.bool) {
($('#'+b)[0] || {}).checked = self.bool[b];
}
var cur;
for (var c=0;c<self.replaces.length;c++) {
if ($('.replaces').length <= c) $('#moreReplaces')[0].click();
cur = self.replaces[c];
for (var d in cur) {
if (cur[d] === true || cur[d] === false) {
$('.replaces').eq(c).find('.'+d).prop('checked', cur[d]);
} else {
$('.replaces').eq(c).find('.'+d).val(cur[d]);
}
}
}
$('.useRegex, #containRegex, #pagelistPopup legend input').trigger('change'); //reset disabled inputs
};
AWB.setup.getObj = function() {
var settings = [];
for (var i in AWB.settings) {
if (i != '_blank') {
settings.push('"' + i + '": ' + JSON.stringify(AWB.settings[i]));
}
}
return '{\n\t' + settings.join(',\n\t') + '\n}';
};
AWB.setup.submit = function() {
var name = prompt(AWB.msg('setup-submit', AWB.msg('setup-prompt', AWB.msg('setup-prompt-save')) ), $('#loadSettings').val());
if (name === null) return;
if ($.trim(name) === '') name = 'default';
AWB.setup.save(name);
AWB.status('setup-submit');
AWB.api.call({
'title': 'User:'+encodeURIComponent(AWB.username)+'/AWB-settings.js',
'summary': AWB.msg(['setup-summary', mw.config.get('wgContentLanguage')]),
'action': 'edit',
'token': AWB.setup.edittoken,
'text': AWB.setup.getObj(),
'minor': true
}, function(response) {
AWB.status('done', false);
});
};
AWB.setup.download = function() {
var name = prompt(AWB.msg('setup-prompt', AWB.msg('setup-prompt-save')), $('#loadSettings').val());
if (name === null) return;
if ($.trim(name) === '') name = 'default';
AWB.setup.save(name);
AWB.status('setup-dload');
var url = 'data:application/json;base64,' + btoa(AWB.setup.getObj());
var elem = $('#download-anchor')[0];
if (elem.hasOwnProperty('download')) { //use download attribute when possible, for its ability to specify a filename
elem.href = url;
elem.click();
setTimeout(function() {elem.removeAttribute('href');}, 2000);
} else { //fallback to iframes for browsers with no support for download="" attributes
elem = $('#download-iframe')[0];
elem.src = url.replace('application/json', 'application/octet-stream');
setTimeout(function() {elem.removeAttribute('src');}, 2000);
}
AWB.status('done', false);
};
AWB.setup.import = function(e) {
e.preventDefault();
file = (e.dataTransfer||this).files[0];
if ($(this).is('#import')) { //reset input
this.outerHTML = this.outerHTML;
$('#import').change(AWB.setup.import);
}
if (!window.hasOwnProperty('FileReader')) {
alert(AWB.msg('old-browser'));
AWB.status('old-browser', '<a target="_blank" href="/index.php?title=Special:MyPage/AWB-settings.js">/AWB-settings.js</a>');
return;
}
if (file.name.split('.').pop().toLowerCase() !== 'json') {
alert(AWB.msg('not-json'));
return;
}
AWB.status('Processing file');
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(e) {
AWB.status('done', false);
try {
var data = JSON.parse(reader.result.replace(/\/\*[\w\W]*\*\/|\/\/[^\n]*/g, ''));
} catch(e) {
alert(AWB.msg('json-err', e.message, AWB.msg('json-err-upload')));
return;
}
AWB.setup.extend(data);
};
AWB.status('Processing file');
};
AWB.setup.load = function() {
AWB.status('setup-load');
AWB.api.call({
'action': 'query',
'titles': 'User:' + (AWB.username||mw.config.get('wgUserName')) + '/AWB-settings.js',
'prop': 'info|revisions',
'intoken': 'edit',
'rvprop': 'content',
'indexpageids': true
}, function(response) {
AWB.status('done', false);
if (AWB === false) return;
var firstrun = AWB.setup.edittoken ? false : true;
var page = response.query.pages[response.query.pageids[0]];
AWB.setup.edittoken = page.edittoken;
if (response.query.pageids[0] === '-1') {
if (AWB.allowed && firstrun) AWB.setup.save('default'); //this runs when this callback returns after the init has loaded.
return;
}
var data = page.revisions[0]['*'];
if (!data) {
if (AWB.allowed && firstrun) AWB.setup.save('default'); //this runs when this callback returns after the init has loaded.
return;
}
try {
data = JSON.parse(data);
} catch(e) {
alert(AWB.msg('json-err', e.message, AWB.msg('json-err-page')) || 'JSON error:\n'+e.message);
AWB.setup.save('default');
return;
}
AWB.setup.extend(data);
});
};
AWB.setup.extend = function(obj) {
$.extend(AWB.settings, obj);
if (!AWB.settings.hasOwnProperty('default')) {
AWB.setup.save('default');
}
for (var i in AWB.settings) {
if ($('#loadSettings').find('option[value="'+i+'"]').length) continue;
$('#loadSettings').append('<option value="'+i+'">'+i+'</option>');
}
AWB.setup.apply($('#loadSettings').val());
};
AWB.setup.delete = function() {
var name = $('#loadSettings').val();
if (name === '_blank') return alert(AWB.msg('setup-delete-blank'));
var temp = {};
temp[name] = AWB.settings[name];
AWB.setup.temp = $.extend({}, temp);
delete AWB.settings[name];
$('#loadSettings').val('default');
if (name === 'default') {
AWB.setup.apply('_blank');
AWB.setup.save('default');
AWB.status(AWB.msg('status-del-default', '<a href="javascript:AWB.setup.undelete();">'+AWB.msg('status-del-undo')+'</a>'), false);
} else {
$('#loadSettings').find('[value="'+name+'"]').remove();
AWB.setup.apply();
AWB.status(AWB.msg('status-del-setup', name, '<a href="javascript:AWB.setup.undelete();">'+AWB.msg('status-del-undo')+'</a>'), false);
}
};
AWB.setup.undelete = function() {
AWB.setup.extend(AWB.setup.temp);
AWB.status('done', false);
};
/***** Main other functions *****/
//Show status message
AWB.status = function(action, spinner) {
var status = AWB.msg('status-'+action);
if (status === false) return;
var spinImg = '<img src="//upload.wikimedia.org/wikipedia/commons/d/de/Ajax-loader.gif" width="15" height="15" alt="'+AWB.msg('status-alt')+'"/>';
if (status) {
if (spinner !== false) {
status += ' ' + spinImg;
}
} else {
status = action;
}
$('#status').html(status);
AWB.pageCount();
return action=='done';
};
AWB.pageCount = function() {
if (AWB.allowed === false||!$('#articleList').length) return;
$('#articleList').val(($('#articleList').val()||'').replace(/(^[ \t]*$\n)*/gm, ''));
AWB.list = $('#articleList').val().split('\n');
var count = AWB.list.length;
if (count === 1 && AWB.list[0] === '') count = 0;
$('#totPages').html(count);
};
//Perform all specified find&replace actions
AWB.replace = function(input) {
AWB.pageCount();
var varOffset = AWB.list[0].indexOf('|') !== -1 ? AWB.list[0].indexOf('|') : 0;
AWB.page.pagevar = AWB.list[0].substr(varOffset);
$('.replaces').each(function() {
var $this = $(this);
var regexFlags = $this.find('.regexFlags').val();
var replace = $this.find('.replaceText').val().replace(/$x/gi, AWB.page.pagevar) || '$';
var useRegex = replace === '$' || $this.find('.useRegex').prop('checked');
if (useRegex && regexFlags.indexOf('_') !== -1) {
replace = replace.replace(/[ _]/g, '[ _]'); //replaces any of [Space OR underscore] with a match for spaces or underscores.
replace = replace.replace(/(\[[^\]]*)\[ _\]/g, '$1 _'); //in case a [ _] was placed inside another [] match, remove the [].
regexFlags = regexFlags.replace('_', '');
}
rWith = $this.find('.replaceWith').val().replace(/$x/gi, AWB.page.pagevar).replace(/\\n/g,'\n');
try {
if ($this.find('.ignoreNowiki').prop('checked')) {
if (!useRegex) {
replace = replace.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
regexFlags = 'g';
}
input = AWB.replaceParsed(input, replace, regexFlags, rWith);
} else if (useRegex) {
replace = new RegExp(replace, regexFlags);
input = input.replace(replace, rWith);
} else {
input = input.split(replace).join(rWith); //global replacement without having to escape all special chars.
}
} catch(e) {
AWB.stop();
return AWB.status('regex-err', false);
}
});
return input;
};
//function to *only* replace the parsed wikitext (so excluding the comments, nowikified, <math>, <source>/<syntaxhighlight>, and <pre> text)
//Based on http://stackoverflow.com/a/23589204/1256925
AWB.replaceParsed = function(str, replace, flags, rwith) {
var exclude = '(<!--[\\s\\S]*?-->|<(nowiki|math|source|syntaxhighlight|pre)[^>]*?>[\\s\\S]*?<\\/\\2>)';
//add /i flag, to exclude the correct tags regardless of casing.
//This won't matter for the actual replacing, as the specified flags are used there.
var re = new RegExp(exclude + '|(' + replace + ')', flags.replace(/i|$/, 'i'));
return str.replace(re, function(match, g1, g2, g3) {
if (g3) { //continue to perform replacement if the match is the group that's supposed to be the match
return match.replace(new RegExp(replace, flags), rwith);
} else { //do nothing if the match is one of the excluded groups
return match;
}
});
};
//Adds a line to the logs tab.
AWB.log = function(action, page, info) {
var d = new Date();
var pagee = encodeURIComponent(page);
var extraInfo = '', actionStat = '';
switch (action) {
case 'edit':
if (typeof info === 'undefined') {
action = 'null-edit';
actionStat = 'nullEdits';
extraInfo = '';
} else {
extraInfo = ' (<a target="_blank" href="/index.php?title='+pagee+'&diff='+info+'">diff</a>)';
actionStat = 'pagesSaved';
}
break;
case 'skip':
actionStat = 'pagesSkipped';
break;
case 'move':
extraInfo = ' to <a target="_blank" href="/wiki/'+encodeURIComponent(info)+'" title="'+info+'">'+info+'</a>';
break;
case 'protect':
extraInfo = info;
break;
}
actionStat = '#' + (actionStat || 'otherActions');
$(actionStat).html(+$(actionStat).html() + 1);
$('#actionlog tbody')
.append('<tr>'+
'<td>'+(AWB.fn.pad0(d.getHours())+':'+AWB.fn.pad0(d.getMinutes())+':'+AWB.fn.pad0(d.getSeconds()))+'</td>'+
'<th>'+action+'</th>'+
'<td><a target="_blank" href="/wiki/'+pagee+'" title="'+page+'">'+page+'</a>'+ extraInfo +'</td>'+
'</tr>')
.parents('.AWBtabc').scrollTop($('#actionlog tbody').parents('.AWBtabc')[0].scrollHeight);
};
//Move to the next page in the list
AWB.next = function(nextPage) {
if ($.trim(nextPage) && !$('#skipAfterAction').prop('checked')) {
nextPage = $.trim(nextPage) + '\n';
} else {
nextPage = '';
}
$('#articleList').val($('#articleList').val().replace(/^.*\n?/, nextPage));
AWB.list.splice(0,1);
AWB.pageCount();
AWB.api.get(AWB.list[0].split('|')[0]);
};
//Stop everything, reset inputs and editor
AWB.stop = function() {
$('#stopbutton, .editbutton, #watchNow, .AWBtabc[data-tab="2"] button, .AWBtabc[data-tab="4"] button').prop('disabled', true);
$('#startbutton, #articleList, .AWBtabc[data-tab="1"] button, #replacesPopup button, #replacesPopup input, .AWBtabc input, select').prop('disabled', false);
$('#resultWindow').html('');
$('#editBoxArea').val('');
AWB.isStopped = true;
};
//Start AutoWikiBrowsing
AWB.start = function() {
AWB.pageCount();
if (AWB.list.length === 0 || (AWB.list.length === 1 && !AWB.list[0])) {
alert(AWB.msg('no-pages-listed'));
} else if ($('#skipNoChange').prop('checked') && !$('.replaceText').val() && !$('.replaceWith').val()) {
alert(AWB.msg('infinite-skip-notice'));
} else {
AWB.isStopped = false;
if ($('#preparse').prop('checked') && !$('#articleList').val().match('#PRE-PARSE-STOP')) {
$('#articleList').val($.trim($('#articleList').val()) + '\n#PRE-PARSE-STOP'); //mark where to stop pre-parsing
} else {
$('#preparse-reset').click();
}
$('#stopbutton, .editbutton, #watchNow, .AWBtabc[data-tab="2"] button, .AWBtabc[data-tab="4"] button').prop('disabled', false);
$('#startbutton, #articleList, .AWBtabc[data-tab="1"] button, #replacesPopup button, #replacesPopup input, .AWBtabc input, select').prop('disabled', true);
AWB.api.get(AWB.list[0].split('|')[0]);
}
};
AWB.updateButtons = function() {
if (!AWB.page.exists && $('#deletePage').is('.delete')) {
$('#deletePage').removeClass('delete').addClass('undelete').html('Undelete');
AWB.fn.blink('#deletePage'); //Indicate the button has changed
} else if (AWB.page.exists && $('#deletePage').is('.undelete')) {
$('#deletePage').removeClass('undelete').addClass('delete').html('Delete');
AWB.fn.blink('#deletePage'); //Indicate the button has changed
}
if (!AWB.page.exists) {
$('#movePage').prop('disabled', true);
} else {
$('#movePage').prop('disabled', false);
}
$('#watchNow').html( AWB.msg('watch-' + (AWB.page.watched ? 'remove' : 'add')) );
};
/***** General functions *****/
//Clear all existing timers to prevent them from getting errors
AWB.fn.clearAllTimeouts = function() {
var i = setTimeout(function() {
return void(0);
}, 1000);
for (var n=0;n<=i;n++) {
clearTimeout(n);
clearInterval(i);
}
console.log('Cleared all running intervals up to index',i);
};
//Filter an array to only contain unique values.
AWB.fn.uniques = function(arr) {
var a = [];
for (var i=0, l=arr.length; i<l; i++) {
if (a.indexOf(arr[i]) === -1 && arr[i] !== '') {
a.push(arr[i]);
}
}
return a;
};
//Prepends zeroes until the number has the desired length of len (default 2)
AWB.fn.pad0 = function(n, len) {
n = n.toString();
len = len||2;
return n.length < len ? Array(len-n.length).join('0')+n : n;
};
AWB.fn.blink = function(el,t) {
t=t?t:500;
$(el).prop('disabled', true)
.children().animate({opacity:'0.1'},t-100)
.animate({opacity:'1'},t)
.animate({opacity:'0.1'},t-100)
.animate({opacity:'1'},t);
setTimeout("$('"+el+"').prop('disabled', false)",t*4-400);
};
AWB.fn.setSelection = function(el, start, end, dir) {
dir = dir||'none'; //Default value
end = end||start; //If no end is specified, assume the caret is placed without creating text selection.
if (el.setSelectionRange) {
el.focus();
el.setSelectionRange(start, end, dir);
} else if (el.createTextRange) {
var rng = el.createTextRange();
rng.collapse(true);
rng.moveStart('character', start);