forked from wikimedia-gadgets/JWB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
JWB.js
2124 lines (2025 loc) · 80.6 KB
/
JWB.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:
mw.loader.load('//en.wikipedia.org/w/index.php?title=User:Joeytje50/JWB.js/load.js&action=raw&ctype=text/javascript');
* Or for users on en.wikipedia.org:
{{subst:lusc|User:Joeytje50/JWB.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 4.2.2
* @author Joeytje50
* </nowiki>
*/
window.JWBdeadman = false; // ADMINS: in case of fire, set this variable to true to disable this entire tool for all users
//TODO: more advanced pagelist-generating options
//TODO: generate page list based on images on a page
//TODO: Add feature to perform general cleanup (<table> to {|, fullurl-links to wikilinks, removing underscores from wikilinks)
//TODO: Add report button to AJAX error alert box
//Cleanup / modernize:
// .indexOf('') != -1 -> .includes()
// mw for requests, instead of ajax
// Optional?.chaining?.properties
/***** Global object/variables *****/
window.JWB = {}; //The main global object for the script.
(function() {
// Easier way to change import location for local debugging etc.
JWB.imports = {
'JWB.css': '//en.wikipedia.org/w/index.php?title=User:Joeytje50/JWB.css&action=raw&ctype=text/css',
'i18n.js': '//en.wikipedia.org/w/index.php?title=User:Joeytje50/JWB.js/i18n.js&action=raw&ctype=text/javascript',
'i18n': {},
'RETF.js': '//en.wikipedia.org/w/index.php?title=User:Joeytje50/RETF.js&action=raw&ctype=text/javascript',
'worker.js':'//en.wikipedia.org/w/index.php?title=User:Joeytje50/JWB.js/worker.js&action=raw&ctype=text/javascript',
};
let objs = ['page', 'api', 'worker', 'fn', 'pl', 'messages', 'setup', 'settings', 'ns'];
for (let i=0;i<objs.length;i++) {
JWB[objs[i]] = {};
}
JWB.summarySuffix = ' (via JWB)';
if (document.location.hostname == 'en.wikipedia.org') JWB.summarySuffix = ' (via [[WP:JWB]])';
JWB.lang = mw.config.get('wgUserLanguage').replace('-', '_');
JWB.contentLang = mw.config.get('wgContentLanguage').replace('-', '_');
JWB.index_php = mw.config.get('wgScript');
JWB.isStopped = true;
JWB.tooltip = window.tooltipAccessKeyPrefix || '';
let configext = 'js';
if (document.location.hostname.split('.').slice(-2).join('.') == 'wikia.com' || document.location.hostname.split('.').slice(-2).join('.') == 'fandom.com') {
//LEGACY: fallback to settings on css for Wikia; uses JSON now.
configext = 'css';
}
JWB.settingspage = 'JWB-settings.'+configext;
if (window.hasOwnProperty('JWBSETTINGS')) {
JWB.settingspage = JWBSETTINGS+'-settings.'+configext;
delete window.JWBSETTINGS; //clean up the global variable
}
JWB.hasJSON = false; // whether or not the wiki supports JSON userpages (mw 1.31+).
JWB.hasSMW = false; // whether or not the wiki has SMW installed.
})();
/***** User verification *****/
(function() {
if (mw.config.get('wgCanonicalNamespace')+':'+mw.config.get('wgTitle') !== 'Project:AutoWikiBrowser/Script' || JWB.allowed === false || mw.config.get('wgUserName') === null) {
JWB.allowed = false;
return;
}
mw.loader.load(JWB.imports['JWB.css'], 'text/css');
mw.loader.load('mediawiki.diff.styles');
$.getScript(JWB.imports['i18n.js'], function() {
if (JWB.allowed === false) {
alert(JWB.msg('not-on-list'));
return;
}
let langs = [];
if (JWB.lang !== 'en' && JWB.imports.i18n.hasOwnProperty(JWB.lang)) {
langs.push(JWB.imports.i18n[JWB.lang]);
}
if (JWB.contentLang !== 'en' && JWB.contentLang !== JWB.lang && JWB.imports.i18n.hasOwnProperty(JWB.contentLang)) {
langs.push(JWB.imports.i18n[JWB.contentLang]);
}
if (langs.length) {
$.when.apply($, langs.map(url => $.getScript(url))).done(function() {
if (JWB.allowed === true) {
JWB.init(); //init if verification has already returned true
} else if (JWB.allowed === false) {
alert(JWB.msg('not-on-list'));
}
});
} else if (JWB.allowed === true) { // no more languages to load.
JWB.init();
}
});
//RegEx Typo Fixing
$.getScript(JWB.imports['RETF.js'], function() {
$('#refreshRETF').click(RETF.load);
});
if (window.JWBdeadman === true) {
window.JWB = false; // disable all access
alert("This tool has been temporarily been disabled by Wikipedia admins due to issues it would otherwise cause. Please check back soon to see if it is working again.");
return false;
} else if (!window.Worker) {
// https://caniuse.com/webworkers - this should not happen for any sensible human being. Either you're on IE<10, or you're just testing my patience.
alert("Web Workers are not supported in this browser. Please use a more modern browser to use JWB. Most matching and replacing features are not supported in this browser.");
}
(new mw.Api()).get({
action: 'query',
titles: 'Project:AutoWikiBrowser/CheckPage',
prop: 'info|revisions',
meta: 'userinfo|siteinfo',
rvprop: 'content',
rvlimit: 1,
uiprop: 'groups',
siprop: 'namespaces|usergroups|extensions',
indexpageids: true,
format: 'json',
}).done(function(response) {
if (response.error) {
alert('API error: ' + response.error.info);
JWB = false; //preventing further access. No verification => no access.
return;
}
JWB.ns = response.query.namespaces; //saving for later
// This will execute before JWB.init() and therefore before JWB.setup.load() loading the user's settings.
let wikigroups = response.query.usergroups;
for (var u of wikigroups) {
if (u.rights.indexOf('edituserjson') !== -1) {
JWB.hasJSON = true;
break;
}
}
// Check if we've got SMW on this wiki
let extensions = response.query.extensions;
for (var e of extensions) {
if (e.name == "SemanticMediaWiki") {
JWB.hasSMW = true;
break;
}
}
JWB.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
}
// Temporary global debugging variables
JWB.debug = [groups.indexOf('bot'), users === false, bots && bots.indexOf(JWB.username)];
JWB.bot = groups.indexOf('bot') !== -1 && (users === false || bots.indexOf(JWB.username) !== -1);
JWB.sysop = groups.indexOf('sysop') !== -1;
if (JWB.username === "Joeytje50" && response.query.userinfo.id === 13299994) {//TEMP: Dev full access to entire interface.
JWB.bot = true;
users.push("Joeytje50");
}
if (JWB.sysop || response.query.pageids[0] === '-1' || users.indexOf(JWB.username) !== -1 || users === false) {
JWB.allowed = true;
if (JWB.messages.en) JWB.init(); //init if messages have already loaded
} else {
if (JWB.messages.en) {
//run this after messages have loaded, so the message that shows is in the user's language
alert(JWB.msg('not-on-list'));
}
JWB = false; //prevent further access
}
}).fail(function(xhr, error) {
alert(JWB.msg('verify-error') + '\n' + error);
JWB = false; //preventing further access. No verification => no access.
});
})();
/***** API functions *****/
//Main template for API calls
JWB.api.call = function(data, callback, onerror) {
data.format = 'json';
if (data.action !== 'query' && data.action !== 'compare' && data.action !== 'ask') {
data.bot = true; // mark edits as bot
}
$.ajax({
data: data,
dataType: 'json',
url: mw.config.get('wgScriptPath') + '/api.php',
type: 'POST',
success: function(response) {
if (response.error) {
if (onerror && onerror(response, 'API') === false) return;
alert('API error: ' + response.error.info);
JWB.stop();
} else {
callback(response);
}
},
// onerror: if it exists and returns false, do not show error alert. Otherwise, do show alert.
error: function(xhr, error) {
if (onerror && onerror(error, 'AJAX') === false) return;
alert('AJAX error: ' + error);
JWB.stop();
}
});
};
//Get page diff, and process it for more interactivity
JWB.api.diff = function(callback) {
if (JWB.isStopped) return; // prevent new API calls when stopped
JWB.status('diff');
var editBoxInput = $('#editBoxArea').val();
var redirect = $('input.redirects:checked').val();
var data = {
action: 'compare',
indexpageids: true,
fromtitle: JWB.page.name,
//toslots: 'main', // TODO: Once this gets supported more widely, convert to the non-deprecated toslots system.
//'totext-main': editBoxInput,
totext: editBoxInput,
topst: true,
};
if (redirect=='follow') data.redirects = true;
JWB.api.call(data, function(response) {
var diff;
diff = response.compare['*'];
if (diff === '') {
diff = '<h2>'+JWB.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>';
}
$('#resultWindow').html(diff);
$('.diff-lineno').each(function() {
var lineNumMatch = $(this).html().match(/\d+/);
if (lineNumMatch) {
$(this).parent().attr('data-line',parseInt(lineNumMatch[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.
}
});
JWB.status('done', true);
if (typeof(callback) === 'function') {
callback();
}
}, function(err, type) {
if (type == 'API' && err.error.code == 'missingtitle') {
// missingtitle is to be expected when editing a page that doesn't exist; just show a message and move on.
$('#resultWindow').html('<span style="font-weight:bold;color:red;">'+JWB.msg('page-not-exists')+'</span>');
JWB.status('done', true);
if (typeof(callback) === 'function') {
callback();
}
return false; // stop propagation of error; do not show alerts.
}
});
};
//Retrieve page contents/info, process them, and store information in JWB.page object.
JWB.api.get = function(pagename) {
if (JWB.isStopped) return; // prevent new API calls when stopped
JWB.pageCount();
if (!JWB.list[0] || JWB.isStopped) {
return JWB.stop();
}
if (pagename === '#PRE-PARSE-STOP') {
var curval = $('#articleList').val();
$('#articleList').val(curval.substr(curval.indexOf('\n') + 1));
$('#preparse').prop('checked', false);
JWB.stop();
return;
}
let cgns = JWB.ns[14]['*'];
let skipcg = $('#skipCategories').val();
// prepend Category: before all categories and turn CSV(,) into CSV(|).
skipcg = skipcg.replace(new RegExp('(^|,|\\|)('+cgns+':)?', 'gi'), '|'+cgns+':').substr(1);
var redirect = $('input.redirects:checked').val();
var data = {
action: 'query',
prop: 'info|revisions|categories',
inprop: 'watched|protection',
type: 'csrf|watch',
titles: pagename,
rvprop: 'content|timestamp|ids',
rvlimit: '1',
cllimit: 'max',
clcategories: skipcg,
indexpageids: true,
meta: 'userinfo|tokens',
uiprop: 'hasmsg'
};
if (redirect=='follow'||redirect=='skip') data.redirects = true;
if (JWB.sysop) {
data.list = 'deletedrevs';
}
JWB.status('load-page');
JWB.api.call(data, function(response) {
if (response.query.userinfo.hasOwnProperty('messages')) {
var view = mw.config.get('wgScriptPath') + '?title=Special:MyTalk';
var viewNew = view + '&diff=cur';
JWB.status(
'<span style="color:red;font-weight:bold;">'+
JWB.msg('status-newmsg',
'<a href="'+view+'" target="_blank">'+JWB.msg('status-talklink')+'</a>',
'<a href="'+viewNew+'" target="_blank">'+JWB.msg('status-difflink')+'</a>')+
'</span>', true);
alert(JWB.msg('new-message'));
JWB.stop();
return;
}
JWB.page = response.query.pages[response.query.pageids[0]];
JWB.page.token = response.query.tokens.csrftoken;
JWB.page.watchtoken = response.query.tokens.watchtoken;
JWB.page.name = JWB.list[0].split('|')[0];
var varOffset = JWB.list[0].indexOf('|') !== -1 ? JWB.list[0].indexOf('|') + 1 : 0;
JWB.page.pagevar = JWB.list[0].substr(varOffset);
JWB.page.content = JWB.page.revisions ? JWB.page.revisions[0]['*'] : '';
JWB.page.exists = !response.query.pages["-1"];
JWB.page.deletedrevs = response.query.deletedrevs;
JWB.page.watched = JWB.page.hasOwnProperty('watched');
JWB.page.protections = JWB.page.restrictiontypes;
if (response.query.redirects) {
JWB.page.name = response.query.redirects[0].to;
}
// check for skips that can be determined before replacing
if (!JWB.fn.allowBots(JWB.page.content, JWB.username) || !JWB.fn.allowBots(JWB.page.content)) {
// skip if {{bots}} template forbids editing on this page by user OR by JWB in general
JWB.log('nobots', JWB.page.name);
return JWB.next();
} else if (JWB.page.categories !== undefined || // skip because of a matching category as passed via clcategories.
($('#exists-no').prop('checked') && !JWB.page.exists) ||
($('#exists-yes').prop('checked') && JWB.page.exists) ||
(redirect==='skip' && response.query.redirects) // variable redirect is defined outside this callback function.
) {
// simple skip rules
JWB.log('skip', JWB.page.name);
return JWB.next();
}
// Check skip contains rules.
var containRegex = $('#containRegex').prop('checked'),
containFlags = $('#containFlags').val();
var skipContains, skipNotContains;
if (containRegex) {
JWB.status('check-skips');
var skipping = false; // for tracking if match is found in synchronous calls.
if ($('#skipContains').val().length) {
JWB.worker.match(JWB.page.content, $('#skipContains').val(), containFlags, function(result, err) {
console.log('Contains', result, err);
if (result !== null && err === undefined) {
JWB.log('skip', JWB.page.name);
JWB.next(); // next() also cancels the skipNotContains.
skipping = true;
return;
} // else continue with the queued worker job that checks skipNotContains
});
}
if (skipping) {
console.log('skipped page before replaces')
return;
}
if ($('#skipNotContains').val().length) {
JWB.worker.match(JWB.page.content, $('#skipNotContains').val(), containFlags, function(result, err) {
console.log('Not contains', result, err);
if (result === null && err === undefined) {
JWB.log('skip', JWB.page.name);
JWB.next(); // also cancels the replace
skipping = true;
return;
} // else move on to replacing
});
}
if (skipping) {
console.log('skipped page before replaces')
return;
}
} else {
skipContains = $('#skipContains').val();
skipNotContains = $('#skipNotContains').val();
if ((skipContains && JWB.page.content.includes(skipContains)) ||
(skipNotContains && JWB.page.content.includes(skipNotContains))) {
console.log('skipped page before replaces')
return JWB.next();
}
JWB.status('done', true);
}
JWB.replace(JWB.page.content, function(newContent) {
if (JWB.stopped === true) return;
if ($('#skipNoChange').prop('checked') && JWB.page.content === newContent) { //skip if no changes are made
JWB.log('skip', JWB.page.name);
return JWB.next();
} else {
JWB.editPage(newContent);
}
JWB.updateButtons();
});
});
};
//Some functions with self-explanatory names:
JWB.api.submit = function(page) {
if (JWB.isStopped) return; // prevent new API calls when stopped
JWB.status('submit');
var summary = $('#summary').val();
if ($('#summary').parent('label').hasClass('viaJWB')) summary += JWB.summarySuffix;
if ((typeof page === 'text' && page !== JWB.page.name) || $('#currentpage a').html().replace(/&/g, '&') !== JWB.page.name) {
console.log(page, JWB.page.name, $('#currentpage a').html())
JWB.stop();
alert(JWB.msg('autosave-error', JWB.msg('tab-log')));
$('#currentpage').html(JWB.msg('editbox-currentpage', ' ', ' '));
return;
}
var newval = $('#editBoxArea').val();
var diffsize = newval.length - JWB.page.content.length;
if ($('#sizelimit').val() != 0 && Math.abs(diffsize) > parseInt($('#sizelimit').val())){
alert(JWB.msg('size-limit-exceeded', diffsize > 0 ? '+'+diffsize : diffsize));
JWB.status('done', true);
return;
}
var data = {
title: JWB.page.name,
summary: summary,
action: 'edit',
basetimestamp: JWB.page.revisions ? JWB.page.revisions[0].timestamp : '',
token: JWB.page.token,
text: newval,
watchlist: $('#watchPage').val()
};
if ($('#minorEdit').prop('checked')) data.minor = true;
JWB.api.call(data, function(response) {
JWB.log('edit', response.edit.title, response.edit.newrevid);
}, function(error, errtype) {
var cont = false;
if (errtype == 'API') {
cont = confirm("API error: " + error.error.info + "\n" + JWB.msg('confirm-continue'));
} else {
cont = confirm("AJAX error: " + error + "\n" + JWB.msg('confirm-continue'));
}
if (!cont) {
JWB.stop();
}
return false; // do not fall back on default error handling
});
// While the edit is submitting, continue to the next page to edit.
JWB.status('done', true);
JWB.next();
};
JWB.api.preview = function() {
if (JWB.isStopped) return; // prevent new API calls when stopped
JWB.status('preview');
JWB.api.call({
title: JWB.page.name,
action: 'parse',
pst: true,
text: $('#editBoxArea').val()
}, function(response) {
$('#resultWindow').html(response.parse.text['*']);
$('#resultWindow div.previewnote').remove();
JWB.status('done', true);
});
};
JWB.api.move = function() {
if (JWB.isStopped) return; // prevent new API calls when stopped
JWB.status('move');
var topage = $('#moveTo').val().replace(/\$x/gi, JWB.page.pagevar);
var summary = $('#summary').val();
if ($('#summary').parent('label').hasClass('viaJWB')) summary += JWB.summarySuffix;
var data = {
action: 'move',
from: JWB.page.name,
to: topage,
token: JWB.page.token,
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;
JWB.api.call(data, function(response) {
JWB.log('move', response.move.from, response.move.to);
JWB.status('done', true);
if (!$('#moveTo').val().match(/\$x/i)) $('#moveTo').val('')[0].focus(); //clear entered move-to pagename if it's not based on the pagevar
JWB.next(topage);
});
};
JWB.api.del = function() {
if (JWB.isStopped) return; // prevent new API calls when stopped
JWB.status(($('#deletePage').is('.undelete') ? 'un' : '') + 'delete');
var summary = $('#summary').val();
if ($('#summary').parent('label').hasClass('viaJWB')) summary += JWB.summarySuffix;
JWB.api.call({
action: (!JWB.page.exists ? 'un' : '') + 'delete',
title: JWB.page.name,
token: JWB.page.token,
reason: summary
}, function(response) {
JWB.log((!JWB.page.exists ? 'un' : '') + 'delete', (response['delete']||response.undelete).title);
JWB.status('done', true);
JWB.next(response.undelete && response.undelete.title);
});
};
JWB.api.protect = function() {
if (JWB.isStopped) return; // prevent new API calls when stopped
JWB.status('protect');
var summary = $('#summary').val();
if ($('#summary').parent('label').hasClass('viaJWB')) summary += JWB.summarySuffix;
var editprot = $('#editProt').val();
var moveprot = $('#moveProt').val() || editprot;
var uploadprot = $('#uploadProt').val() || editprot;
var protstring = 'edit='+editprot+'|move='+moveprot;
if (!JWB.page.exists)
protstring = 'create='+editprot;
if (JWB.page.protections.includes('upload'))
protstring += '|upload='+uploadprot;
JWB.api.call({
action: 'protect',
title: JWB.page.name,
token: JWB.page.token,
reason: summary,
expiry: $('#protectExpiry').val()!==''?$('#protectExpiry').val():'infinite',
protections: protstring,
}, 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 || 'all');
} else if (typeof prots[i].move == 'string') {
protactions += ' move: '+(prots[i].move || 'all');
} else if (typeof prots[i].create == 'string') {
protactions += ' create: '+(prots[i].create || 'all');
} else if (typeof prots[i].upload == 'string') {
protactions += ' upload: '+(prots[i].upload || 'all');
}
}
protactions += ' expires: '+prots[0].expiry;
JWB.log('protect', response.protect.title, protactions);
JWB.status('done', false);
JWB.next(response.protect.title);
});
};
JWB.api.watch = function() {
JWB.status('watch');
var data = {
action: 'watch',
title: JWB.page.name,
token: JWB.page.watchtoken
};
if (JWB.page.watched) data.unwatch = true;
JWB.api.call(data, function(response) {
JWB.status('<span style="color:green;">'+
JWB.msg('status-watch-'+(JWB.page.watched ? 'removed' : 'added'), "'"+JWB.page.name+"'")+
'</span>', true);
JWB.page.watched = !JWB.page.watched;
$('#watchNow').html( JWB.msg('watch-' + (JWB.page.watched ? 'remove' : 'add')) );
});
};
/***** Pagelist functions *****/
JWB.pl.iterations = 0;
JWB.pl.done = true;
JWB.pl.stop = function() {
if (JWB.pl.done) {
JWB.pl.iterations = 0;
$('#pagelistPopup [disabled]:not(fieldset [disabled]), #pagelistPopup legend input, #pagelistPopup button').prop('disabled', false);
$('#pagelistPopup legend input').trigger('change');
$('#pagelistPopup button img').remove();
}
}
JWB.pl.getNSpaces = function() {
var list = $('#pagelistPopup [name="namespace"]')[0];
return $('#pagelistPopup [name="namespace"]').val().join('|'); //.val() returns an array of selected options.
};
JWB.pl.getList = function(abbrs, lists, data) {
$('#pagelistPopup button, #pagelistPopup input, #pagelistPopup select, #pagelistPopup button').prop('disabled', true);
JWB.pl.iterations++;
if (data.ask !== undefined) {
JWB.pl.SMW(data.ask); // execute SMW call in parallel
JWB.pl.done = false;
data.ask = undefined;
}
if (!abbrs.length) {
JWB.pl.done = true;
return; // don't execute the rest; only a SMW query was entered.
}
data.action = 'query';
var nspaces = JWB.pl.getNSpaces();
for (var i=0;i<abbrs.length;i++) {
if (nspaces) data[abbrs[i]+'namespace'] = data[abbrs[i]+'namespace'] || nspaces; // if namespaces are already set, use that instead (for apnamespace)
data[abbrs[i]+'limit'] = 'max';
}
let linksList = lists.indexOf('links')
if (linksList !== -1) {
data.prop = 'links';
lists.splice(linksList, 1)
}
data.list = lists.join('|');
console.log('generating:', data);
JWB.api.call(data, function(response) {
var maxiterate = 100; //allow up to 100 consecutive requests at a time to avoid overloading the server.
if (!response.query) response.query = {};
if (response.watchlistraw) response.query.watchlistraw = response.watchlistraw; //adding some consistency
var plist = [];
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++) {
plist.push(links[i].title);
}
}
}
for (var l in response.query) {
if (l === 'pages') continue;
for (var i=0;i<response.query[l].length;i++) {
plist.push(response.query[l][i].title);
}
}
//add the result to the pagelist immediately, as opposed to saving it all up and adding in 1 go like AWB does
$('#articleList').val($.trim($('#articleList').val()) + '\n' + plist.join('\n'));
JWB.pageCount();
var cont = response.continue;
console.log("Continue",JWB.pl.iterations, cont);
if (cont && JWB.pl.iterations <= maxiterate) {
var lists = [];
if (response.query) { //compatibility with the code I wrote for the old query-continue. TODO: make this unnecessary?
for (var list in response.query) {
lists.push(list); //add to the new array of &list= values
}
}
var abbrs = [];
for (var abbr in cont) {
data[abbr] = cont[abbr]; //add the &xxcontinue= value to the data
if (abbr != 'continue') {
abbrs.push(abbr.replace('continue','')); //find out what xx is and add it to the list of abbrs
}
}
JWB.pl.getList(abbrs, lists, data); //recursive function to get every page of a list
} else {
if (JWB.pl.iterations > maxiterate) {
JWB.status('pl-over-lim', true);
} else {
JWB.status('done', true);
}
JWB.pl.stop(); // if JWB.pl.done == true show stopped interface. Otherwise mark as done.
JWB.pl.done = true;
}
}, function() { //on error, simply reset and let the user work with what he has
JWB.status('done', true);
JWB.pl.stop();
JWB.pl.done = true;
});
};
JWB.pl.SMW = function(query) {
var data = {
action: 'ask',
query: query
};
JWB.api.call(data, function(response) {
console.log(response);
let list = response.query.results;
let pagevar = response.query.printrequests[1];
let pagevar_type = pagevar && pagevar.typeid;
if (pagevar) {
// either pagevar === undefined, or it's the first printrequest.
pagevar = pagevar.label;
}
let plist = [];
for (let l in list) {
let page = list[l];
let name = page.fulltext;
let suff;
if (pagevar) try {
let val = page.printouts[pagevar][0];
if (!val) continue; // this page does not contain this property.
switch (pagevar_type) {
case '_boo':
suff = val == 't'; // true if 't' else false;
break;
case '_wpg':
suff = val.fulltext;
break;
case '_dat':
// val.raw is also available but the unconventional format makes it a lot less convenient.
suff = val.timestamp;
break;
case '_qty':
suff = val.value + ' ' + val.unit;
break;
case '_mlt_rec':
// I doubt this is used anywhere, but it's not too hard to support.
suff = val.Text.item[0];
break;
case '_ref_rec':
// not supported; references contain too many properties.
break;
default:
suff = val;
}
} catch(e) {
console.error(e); // show error but ignore. Something is wrong in SMW query/api.
}
if (suff) {
plist.push(name + '|' + suff);
} else {
plist.push(name);
}
}
$('#articleList').val($.trim($('#articleList').val()) + '\n' + plist.join('\n'));
JWB.pageCount();
JWB.pl.stop(); // if JWB.pl.done == true show stopped interface. Otherwise mark as done.
JWB.pl.done = true;
});
}
//JWB.pl.getList(['wr'], ['watchlistraw'], {}) for watchlists
JWB.pl.generate = function() {
var $fields = $('#pagelistPopup fieldset').not('[disabled]');
$('#pagelistPopup').find('button[type="submit"]').append('<img src="//upload.wikimedia.org/wikipedia/commons/d/de/Ajax-loader.gif" width="15" height="15" alt="'+JWB.msg('status-alt')+'"/>');
var abbrs = [],
lists = [],
data = {'continue': ''};
$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 if (list === 'smwask') {
data.ask = $(this).find('#smwquery').val();
} else { //default input system
if ($(this).find('#psstrict').prop('checked')) {
// different list if prefixsearch is strict
let $input = $(this).find('#psstrict')
list = $input.attr('name');
abbr = $input.val();
} else {
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.id == 'psstrict') return; // ignore psstrict; it only affects how pssearch is handled
var name, val;
if (this.id == 'cmtitle') {
// making sure the page has a Category: prefix, in case the user left it out
let cgns = JWB.ns[14]['*']; // name for Category: namespace
if (!this.value.startsWith(cgns+':')) {
this.value = cgns+':'+this.value;
}
}
if (this.id == 'pssearch' && this.name == 'apprefix') {
// apprefix needs namespace separate from pagename
name = this.name;
let split = this.value.split(':')
val = split[1] || split[0];
let nsid = 0;
if (split[1]) { // if a namespace is given
for (let ns in JWB.ns) {
if (JWB.ns[ns]['*'] == split[0]) {
nsid = JWB.ns[ns].id;
break;
}
}
}
data.apnamespace = nsid;
} else {
name = this.name;
val = this.value;
}
if (data.hasOwnProperty(name)) {
data[name] += '|'+val;
} else {
data[name] = val;
}
});
console.log(abbrs, lists, data);
}
});
if (abbrs.length || data.ask) JWB.pl.getList(abbrs, lists, data);
else JWB.pl.stop();
};
/***** Setup functions *****/
JWB.setup.save = function(name) {
name = name || prompt(JWB.msg('setup-prompt', JWB.msg('setup-prompt-store')), $('#loadSettings').val());
if (name === null) return;
var self = JWB.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);
};
JWB.setup.apply = function(name) {
name = name && JWB.settings[name] ? name : 'default';
var self = JWB.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).prop('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,'+
'#viaJWB').trigger('change'); //reset disabled inputs
};
JWB.setup.getObj = function() {
var settings = [];
for (var i in JWB.settings) {
if (i != '_blank') {
settings.push('"' + i + '": ' + JSON.stringify(JWB.settings[i]));
}
}
return '{\n\t' + settings.join(',\n\t').split('{{subst:').join('{{#JWB-SAFESUBST:#') + '\n}';
};
JWB.setup.submit = function() {
var name = prompt(JWB.msg('setup-prompt', JWB.msg('setup-prompt-save')), $('#loadSettings').val());
if (name === null) return;
if ($.trim(name) === '') name = 'default';
JWB.setup.save(name);
JWB.status('setup-submit');
JWB.api.call({
action: 'query',
meta: 'tokens',
}, function(response) {
let edittoken = response.query.tokens.csrftoken;
JWB.api.call({
title: 'User:'+JWB.username+'/'+JWB.settingspage,
summary: JWB.msg(['setup-summary', JWB.contentLang]),
action: 'edit',
token: edittoken,
text: JWB.setup.getObj(),
minor: true
}, function(response) {
JWB.status('done', true);
JWB.log('edit', response.edit.title, response.edit.newrevid);
});
});
};
//TODO: use blob uri
JWB.setup.download = function() {
var name = prompt(JWB.msg('setup-prompt', JWB.msg('setup-prompt-save')), $('#loadSettings').val());
if (name === null) return;
if ($.trim(name) === '') name = 'default';
JWB.setup.save(name);
JWB.status('setup-dload');
var url = 'data:application/json;base64,' + btoa(unescape(encodeURIComponent(JWB.setup.getObj())));
var elem = $('#download-anchor')[0];
if (HTMLAnchorElement.prototype.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);
}
JWB.status('done', true);
};
JWB.setup.import = function(e) {
e.preventDefault();
file = (e.dataTransfer||this).files[0];
if ($(this).is('#import')) { //reset input
this.outerHTML = this.outerHTML;
$('#import').change(JWB.setup.import);
}
if (!window.hasOwnProperty('FileReader')) {
alert(JWB.msg('old-browser'));
JWB.status('old-browser', '<a target="_blank" href="'+JWB.index_php+'?title=Special:MyPage/'+JWB.settingspage+'">/'+JWB.settingspage+'</a>');
return;
}