-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
Wikipedia.gs.js
1743 lines (1692 loc) · 56.2 KB
/
Wikipedia.gs.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
/**
* @license
* Copyright 2016 Thomas Steiner (@tomayac). All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Make requests traceable in case of any issues
var HEADERS = {headers: {
'X-User-Agent': 'Wikipedia Tools for Google Spreadsheets'
}};
// Set default language to 'en' for simpler method chaining
var DEFAULT_LANGUAGE = 'en';
/**
* Returns Wikipedia synonyms (redirects) for a Wikipedia article.
*
* @param {string} article The Wikipedia article in the format "language:Article_Title" ("de:Berlin") to get synonyms for.
* @param {string=} opt_namespaces Only include pages in these namespaces (optional).
* @return {Array<string>} The list of synonyms.
* @customfunction
*/
function WIKISYNONYMS(article, opt_namespaces) {
'use strict';
if (!article) {
return '';
}
var results = [];
try {
var language;
var title;
if (article.indexOf(':') !== -1) {
language = article.split(/:(.+)?/)[0];
title = article.split(/:(.+)?/)[1];
} else {
language = DEFAULT_LANGUAGE;
title = article;
}
if (!title) {
return '';
}
var url = 'https://' + language + '.wikipedia.org/w/api.php' +
'?action=query' +
'&blnamespace=' + (opt_namespaces ?
encodeURIComponent(opt_namespaces) : '0') +
'&list=backlinks' +
'&blfilterredir=redirects' +
'&bllimit=max' +
'&format=xml' +
'&bltitle=' + encodeURIComponent(title.replace(/\s/g, '_'));
var xml = UrlFetchApp.fetch(url, HEADERS).getContentText();
var document = XmlService.parse(xml);
var entries = document.getRootElement().getChild('query')
.getChild('backlinks').getChildren('bl');
for (var i = 0; i < entries.length; i++) {
var text = entries[i].getAttribute('title').getValue();
results[i] = text;
}
} catch (e) {
// no-op
}
return results.length > 0 ? results : '';
}
/**
* Returns Wikipedia articles around a Wikipedia article or around a point.
*
* @param {string} articleOrPoint The Wikipedia article in the format "language:Article_Title" ("de:Berlin") or the point in the format "language:Latitude,Longitude" ("en:37.786971,-122.399677") to get articles around for.
* @param {number} radius The search radius in meters.
* @param {boolean=} opt_includeDistance Whether to include the distance in the output, defaults to false (optional).
* @param {string=} opt_namespaces Only include pages in these namespaces (optional).
* @return {Array<string>} The list of articles around the given article or point.
* @customfunction
*/
function WIKIARTICLESAROUND(articleOrPoint, radius, opt_includeDistance,
opt_namespaces) {
'use strict';
if (!articleOrPoint) {
return '';
}
var results = [];
try {
var language;
var rest;
var title;
var latitude;
var longitude;
if (articleOrPoint.indexOf(':') !== -1) {
language = articleOrPoint.split(/:(.+)?/)[0];
rest = articleOrPoint.split(/:(.+)?/)[1];
title = false;
latitude = false;
longitude = false;
if (/^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/.test(rest)) {
latitude = rest.split(',')[0];
longitude = rest.split(',')[1];
} else {
title = rest;
}
} else {
language = DEFAULT_LANGUAGE;
rest = articleOrPoint;
title = false;
latitude = false;
longitude = false;
if (/^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/.test(rest)) {
latitude = rest.split(',')[0];
longitude = rest.split(',')[1];
} else {
title = rest;
}
}
if ((!title) && !(latitude && longitude)) {
return;
}
var url = 'https://' + language + '.wikipedia.org/w/api.php';
if (title) {
url += '?action=query' +
'&list=geosearch' +
'&format=xml' +
'&gslimit=max' +
'&gsradius=' + radius +
'&gspage=' + encodeURIComponent(title.replace(/\s/g, '_'));
} else {
url += '?action=query' +
'&list=geosearch' +
'&format=xml&gslimit=max' +
'&gsradius=' + radius +
'&gscoord=' + latitude + '%7C' + longitude;
}
url += '&gsnamespace=' + (opt_namespaces ?
encodeURIComponent(opt_namespaces) : '0');
var xml = UrlFetchApp.fetch(url, HEADERS).getContentText();
var document = XmlService.parse(xml);
var entries = document.getRootElement().getChild('query')
.getChild('geosearch').getChildren('gs');
for (var i = 0; i < entries.length; i++) {
var title = entries[i].getAttribute('title').getValue();
var lat = entries[i].getAttribute('lat').getValue();
var lon = entries[i].getAttribute('lon').getValue();
if (opt_includeDistance) {
var dist = entries[i].getAttribute('dist').getValue();
results[i] = [title, lat, lon, dist];
} else {
results[i] = [title, lat, lon];
}
}
} catch (e) {
// no-op
}
return results.length > 0 ? results : '';
}
/**
* Returns Wikipedia translations (language links) for a Wikipedia article.
*
* @param {string} article The Wikipedia article in the format "language:Article_Title" ("de:Berlin") to get translations for.
* @param {Array<string>=} opt_targetLanguages The list of languages to limit the results to (optional).
* @param {boolean=} opt_skipHeader Whether to skip the header, defaults to false (optional).
* @return {Array<string>} The list of translations.
* @customfunction
*/
function WIKITRANSLATE(article, opt_targetLanguages, opt_skipHeader,
_opt_returnAsObject) {
'use strict';
if (!article) {
return '';
}
var results = {};
opt_targetLanguages = opt_targetLanguages || [];
opt_targetLanguages = Array.isArray(opt_targetLanguages) ?
opt_targetLanguages : [opt_targetLanguages];
var temp = {};
opt_targetLanguages.forEach(function(lang) {
temp[lang] = true;
});
opt_targetLanguages = Object.keys(temp);
try {
var language;
var title;
if (article.indexOf(':') !== -1) {
language = article.split(/:(.+)?/)[0];
title = article.split(/:(.+)?/)[1];
} else {
language = DEFAULT_LANGUAGE;
title = article;
}
if (!title) {
return '';
}
opt_targetLanguages.forEach(function(targetLanguage) {
if (targetLanguage) {
results[targetLanguage] = title.replace(/_/g, ' ');
}
});
var url = 'https://' + language + '.wikipedia.org/w/api.php' +
'?action=query' +
'&prop=langlinks' +
'&format=xml' +
'&lllimit=max' +
'&titles=' + encodeURIComponent(title.replace(/\s/g, '_'));
var xml = UrlFetchApp.fetch(url, HEADERS).getContentText();
var document = XmlService.parse(xml);
var entries = document.getRootElement().getChild('query').getChild('pages')
.getChild('page').getChild('langlinks').getChildren('ll');
var targetLanguagesSet = opt_targetLanguages.length > 0;
for (var i = 0; i < entries.length; i++) {
var text = entries[i].getText();
var lang = entries[i].getAttribute('lang').getValue();
if ((targetLanguagesSet) && (opt_targetLanguages.indexOf(lang) === -1)) {
continue;
}
results[lang] = text;
}
title = title.replace(/_/g, ' ');
results[language] = title;
} catch (e) {
// no-op
}
if (_opt_returnAsObject) {
return results;
}
var arrayResults = [];
for (var lang in results) {
if (opt_skipHeader) {
arrayResults.push(results[lang]);
} else {
arrayResults.push([lang, results[lang]]);
}
}
return arrayResults.length > 0 ? arrayResults : '';
}
/**
* Returns Wikipedia translations (language links) and synonyms (redirects) for a Wikipedia article.
*
* @param {string} article The Wikipedia article in the format "language:Article_Title" ("de:Berlin") to get translations and synonyms for.
* @param {Array<string>=} opt_targetLanguages The list of languages to limit the results to (optional).
* @return {Array<string>} The list of translations and synonyms.
* @customfunction
*/
function WIKIEXPAND(article, opt_targetLanguages) {
'use strict';
if (!article) {
return '';
}
var results = [];
try {
var language;
var title;
if (article.indexOf(':') !== -1) {
language = article.split(/:(.+)?/)[0];
title = article.split(/:(.+)?/)[1];
} else {
language = DEFAULT_LANGUAGE;
title = article;
}
if (!title) {
return '';
}
opt_targetLanguages = opt_targetLanguages || [];
opt_targetLanguages = Array.isArray(opt_targetLanguages) ?
opt_targetLanguages : [opt_targetLanguages];
var temp = {};
opt_targetLanguages.forEach(function(lang) {
temp[lang] = true;
});
opt_targetLanguages = Object.keys(temp);
var translations = WIKITRANSLATE(article, opt_targetLanguages, false, true);
var i = 0;
for (var lang in translations) {
var synonyms = WIKISYNONYMS(lang + ':' + translations[lang]);
results[i] = [lang].concat(([translations[lang]].concat(synonyms)));
i++;
}
} catch (e) {
// no-op
}
return results;
}
/**
* Returns the Wikimedia Commons link for a file.
*
* @param {string} fileName The Wikimedia Commons file name in the format "language:File_Name" ("en:Flag of Berlin.svg") to get the link for.
* @return {string} The link of the Wikimedia Commons file.
* @customfunction
*/
function WIKICOMMONSLINK(fileName) {
'use strict';
if (!fileName) {
return '';
}
var results = [];
try {
var language;
var title;
if (fileName.indexOf(':') !== -1) {
language = fileName.split(/:(.+)?/)[0];
title = fileName.split(/:(.+)?/)[1];
} else {
language = DEFAULT_LANGUAGE;
title = fileName;
}
if (!title) {
return '';
}
var url = 'https://' + language + '.wikipedia.org/w/api.php' +
'?action=query' +
'&prop=imageinfo' +
'&iiprop=url' +
'&format=xml' +
'&titles=File:' + encodeURIComponent(title.replace(/\s/g, '_'));
var xml = UrlFetchApp.fetch(url, HEADERS).getContentText();
var document = XmlService.parse(xml);
var entry = document.getRootElement().getChild('query').getChild('pages')
.getChild('page').getChild('imageinfo').getChild('ii');
var fileUrl = entry.getAttribute('url').getValue();
results[0] = fileUrl;
} catch (e) {
// no-op
}
return results.length > 0 ? results : '';
}
/**
* Returns Wikipedia category members for a Wikipedia category.
*
* @param {string} category The Wikipedia category in the format "language:Category_Title" ("en:Category:Visitor_attractions_in_Berlin") to get members for.
* @param {string=} opt_namespaces Only include pages in these namespaces (optional).
* @return {Array<string>} The list of category members.
* @customfunction
*/
function WIKICATEGORYMEMBERS(category, opt_namespaces) {
'use strict';
if (!category) {
return '';
}
var results = [];
try {
var language;
var title;
if ((category.match(/:/g) || []).length > 1) {
language = category.split(/:(.+)?/)[0];
title = category.split(/:(.+)?/)[1];
} else {
language = DEFAULT_LANGUAGE;
title = category;
}
if (!title) {
return '';
}
var url = 'https://' + language + '.wikipedia.org/w/api.php' +
'?action=query' +
'&list=categorymembers' +
'&cmlimit=max' +
'&cmprop=title' +
'&cmtype=subcat%7Cpage' +
'&format=xml' +
'&cmnamespace=' + (opt_namespaces ?
encodeURIComponent(opt_namespaces) : '0') +
'&cmtitle=' + encodeURIComponent(title.replace(/\s/g, '_'));
var xml = UrlFetchApp.fetch(url, HEADERS).getContentText();
var document = XmlService.parse(xml);
var entries = document.getRootElement().getChild('query')
.getChild('categorymembers').getChildren('cm');
for (var i = 0; i < entries.length; i++) {
var text = entries[i].getAttribute('title').getValue();
results[i] = text;
}
} catch (e) {
// no-op
}
return results.length > 0 ? results : '';
}
/**
* Returns Wikipedia subcategories for a Wikipedia category.
*
* @param {string} category The Wikipedia category in the format "language:Category_Title" ("en:Category:Visitor_attractions_in_Berlin") to get subcategories for.
* @param {string=} opt_namespaces Only include pages in these namespaces (optional).
* @return {Array<string>} The list of subcategories.
* @customfunction
*/
function WIKISUBCATEGORIES(category, opt_namespaces) {
'use strict';
if (!category) {
return '';
}
var results = [];
try {
var language;
var title;
if ((category.match(/:/g) || []).length > 1) {
language = category.split(/:(.+)?/)[0];
title = category.split(/:(.+)?/)[1];
} else {
language = DEFAULT_LANGUAGE;
title = category;
}
if (!title) {
return '';
}
var url = 'https://' + language + '.wikipedia.org/w/api.php' +
'?action=query' +
'&list=categorymembers' +
'&cmlimit=max' +
'&cmprop=title' +
'&cmtype=subcat%7Cpage' +
'&format=xml' +
'&cmnamespace=' + (opt_namespaces ?
encodeURIComponent(opt_namespaces) : '14') +
'&cmtitle=' + encodeURIComponent(title.replace(/\s/g, '_'));
var xml = UrlFetchApp.fetch(url, HEADERS).getContentText();
var document = XmlService.parse(xml);
var entries = document.getRootElement().getChild('query')
.getChild('categorymembers').getChildren('cm');
for (var i = 0; i < entries.length; i++) {
var text = entries[i].getAttribute('title').getValue();
results[i] = text;
}
} catch (e) {
// no-op
}
return results.length > 0 ? results : '';
}
/**
* Returns Wikipedia categories for a Wikipedia article.
*
* @param {string} article The Wikipedia article in the format "language:Article_Title" ("en:Berlin") to get categories for.
* @return {Array<string>} The list of categories.
* @customfunction
*/
function WIKICATEGORIES(article) {
'use strict';
if (!article) {
return '';
}
var results = [];
try {
var language;
var title;
if (article.indexOf(':') !== -1) {
language = article.split(/:(.+)?/)[0];
title = article.split(/:(.+)?/)[1];
} else {
language = DEFAULT_LANGUAGE;
title = article;
}
if (!title) {
return '';
}
var url = 'https://' + language + '.wikipedia.org/w/api.php' +
'?action=query' +
'&prop=categories' +
'&format=xml' +
'&cllimit=max' +
'&titles=' + encodeURIComponent(title.replace(/\s/g, '_'));
var xml = UrlFetchApp.fetch(url, HEADERS).getContentText();
var document = XmlService.parse(xml);
var entries = document.getRootElement().getChild('query').getChild('pages')
.getChild('page').getChild('categories').getChildren('cl');
for (var i = 0; i < entries.length; i++) {
var text = entries[i].getAttribute('title').getValue();
results[i] = text;
}
} catch (e) {
// no-op
}
return results.length > 0 ? results : '';
}
/**
* Returns Wikipedia inbound links for a Wikipedia article.
*
* @param {string} article The Wikipedia article in the format "language:Article_Title" ("de:Berlin") to get inbound links for.
* @param {string=} opt_namespaces Only include pages in these namespaces (optional).
* @return {Array<string>} The list of inbound links.
* @customfunction
*/
function WIKIINBOUNDLINKS(article, opt_namespaces) {
'use strict';
if (!article) {
return '';
}
var results = [];
try {
var language;
var title;
if (article.indexOf(':') !== -1) {
language = article.split(/:(.+)?/)[0];
title = article.split(/:(.+)?/)[1];
} else {
language = DEFAULT_LANGUAGE;
title = article;
}
if (!title) {
return '';
}
var url = 'https://' + language + '.wikipedia.org/w/api.php' +
'?action=query' +
'&list=backlinks' +
'&bllimit=max' +
'&blnamespace=' + (opt_namespaces ?
encodeURIComponent(opt_namespaces) : '0') +
'&format=xml' +
'&bltitle=' + encodeURIComponent(title.replace(/\s/g, '_'));
var xml = UrlFetchApp.fetch(url, HEADERS).getContentText();
var document = XmlService.parse(xml);
var entries = document.getRootElement().getChild('query')
.getChild('backlinks').getChildren('bl');
for (var i = 0; i < entries.length; i++) {
var text = entries[i].getAttribute('title').getValue();
results[i] = text;
}
} catch (e) {
// no-op
}
return results.length > 0 ? results : '';
}
/**
* Returns Wikipedia outbound links for a Wikipedia article.
*
* @param {string} article The Wikipedia article in the format "language:Article_Title" ("de:Berlin") to get outbound links for.
* @param {string=} opt_namespaces Only include pages in these namespaces (optional).
* @return {Array<string>} The list of outbound links.
* @customfunction
*/
function WIKIOUTBOUNDLINKS(article, opt_namespaces) {
'use strict';
if (!article) {
return '';
}
var results = [];
try {
var language;
var title;
if (article.indexOf(':') !== -1) {
language = article.split(/:(.+)?/)[0];
title = article.split(/:(.+)?/)[1];
} else {
language = DEFAULT_LANGUAGE;
title = article;
}
if (!title) {
return '';
}
var url = 'https://' + language + '.wikipedia.org/w/api.php' +
'?action=query' +
'&prop=links' +
'&plnamespace=' + (opt_namespaces ?
encodeURIComponent(opt_namespaces) : '0') +
'&format=xml' +
'&pllimit=max' +
'&titles=' + encodeURIComponent(title.replace(/\s/g, '_'));
var xml = UrlFetchApp.fetch(url, HEADERS).getContentText();
var document = XmlService.parse(xml);
var entries = document.getRootElement().getChild('query').getChild('pages')
.getChild('page').getChild('links').getChildren('pl');
for (var i = 0; i < entries.length; i++) {
var text = entries[i].getAttribute('title').getValue();
results[i] = text;
}
} catch (e) {
// no-op
}
return results.length > 0 ? results : '';
}
/**
* Returns Wikipedia mutual links, i.e, the intersection of inbound and outbound links for a Wikipedia article.
*
* @param {string} article The Wikipedia article in the format "language:Article_Title" ("de:Berlin") to get mutual links for.
* @param {string=} opt_namespaces Only include pages in these namespaces (optional).
* @return {Array<string>} The list of mutual links.
* @customfunction
*/
function WIKIMUTUALLINKS(article, opt_namespaces) {
'use strict';
var inboundLinks = WIKIINBOUNDLINKS(article, opt_namespaces);
var outboundLinks = WIKIOUTBOUNDLINKS(article, opt_namespaces);
var mutualLinks = inboundLinks.filter(function(link) {
return outboundLinks.indexOf(link) > -1;
});
return mutualLinks;
}
/**
* Returns Wikipedia geocoordinates for a Wikipedia article.
*
* @param {string} article The Wikipedia article in the format "language:Article_Title" ("de:Berlin") to get geocoordinates for.
* @return {Array<number>} The latitude and longitude.
* @customfunction
*/
function WIKIGEOCOORDINATES(article) {
'use strict';
if (!article) {
return '';
}
var results = [];
try {
var language;
var title;
if (article.indexOf(':') !== -1) {
language = article.split(/:(.+)?/)[0];
title = article.split(/:(.+)?/)[1];
} else {
language = DEFAULT_LANGUAGE;
title = article;
}
if (!title) {
return '';
}
var url = 'https://' + language + '.wikipedia.org/w/api.php' +
'?action=query' +
'&prop=coordinates' +
'&format=xml' +
'&colimit=max' +
'&coprimary=primary' +
'&titles=' + encodeURIComponent(title.replace(/\s/g, '_'));
var xml = UrlFetchApp.fetch(url, HEADERS).getContentText();
var document = XmlService.parse(xml);
var coordinates = document.getRootElement().getChild('query')
.getChild('pages').getChild('page').getChild('coordinates')
.getChild('co');
var latitude = coordinates.getAttribute('lat').getValue();
var longitude = coordinates.getAttribute('lon').getValue();
results = [[latitude, longitude]];
} catch (e) {
// no-op
}
return results.length > 0 ? results : '';
}
/**
* Returns Wikipedia articles that have a link that matches a given link pattern.
*
* @param {string} linkPattern The link pattern to search for in the format "language:example.com" or "language:*.example.com".
* @param {string=} opt_protocol Protocol of the link, defaults to "http" (optional).
* @param {string=} opt_namespaces Only include pages in these namespaces (optional).
* @return {Array<string>} The list of articles that match the link pattern and the concrete link.
* @customfunction
*/
function WIKILINKSEARCH(linkPattern, opt_protocol, opt_namespaces) {
'use strict';
if (!linkPattern) {
return '';
}
var results = [];
try {
var language;
var title;
if (linkPattern.indexOf(':') !== -1) {
language = linkPattern.split(/:(.+)?/)[0];
title = linkPattern.split(/:(.+)?/)[1];
} else {
language = DEFAULT_LANGUAGE;
title = linkPattern;
}
if (!title) {
return '';
}
var url = 'https://' + language + '.wikipedia.org/w/api.php' +
'?action=query' +
'&format=xml' +
'&list=exturlusage' +
'&eulimit=max' +
'&euprop=title%7Curl' +
'&euprotocol=' + (opt_protocol ? opt_protocol : 'http') +
'&euquery=' + encodeURIComponent(title) +
'&eunamespace=' + (opt_namespaces ?
encodeURIComponent(opt_namespaces) : '0');
var xml = UrlFetchApp.fetch(url, HEADERS).getContentText();
var document = XmlService.parse(xml);
var entries = document.getRootElement().getChild('query')
.getChild('exturlusage').getChildren('eu');
for (var i = 0; i < entries.length; i++) {
var title = entries[i].getAttribute('title').getValue();
var url = entries[i].getAttribute('url').getValue();
results[i] = [title, url];
}
} catch (e) {
// no-op
}
return results.length > 0 ? results : '';
}
/**
* Returns Wikidata facts for a Wikipedia article.
*
* @param {string} article The Wikipedia article in the format "language:Article_Title" ("de:Berlin") or the Wikidata entity in the format "qid" ("Q42") to get Wikidata facts for.
* @param {string=} opt_multiObjectMode Whether to return all object values (pass "all") or just the first (pass "first") when there are more than one object values (optional).
* @param {Array<string>} opt_properties Limit the resulting facts to a list of properties (optional).
* @return {Array<string>} The list of Wikidata facts.
* @customfunction
*/
function WIKIDATAFACTS(article, opt_multiObjectMode, opt_properties) {
'use strict';
var simplifyClaims = function(claims) {
var simpleClaims = {};
for (var id in claims) {
var claim = claims[id];
simpleClaims[id] = simpifyClaim(claim);
}
return simpleClaims;
};
var simpifyClaim = function(claim) {
var simplifiedClaim = [];
var len = claim.length;
for (var i = 0; i < len; i++) {
var statement = claim[i];
var simpifiedStatement = simpifyStatement(statement);
if (simpifiedStatement !== null) {
simplifiedClaim.push(simpifiedStatement);
}
}
return simplifiedClaim;
};
var simpifyStatement = function(statement) {
var mainsnak = statement.mainsnak;
if (mainsnak === null) {
return null;
}
var datatype = mainsnak.datatype;
var datavalue = mainsnak.datavalue;
if (datavalue === null || datavalue === undefined) {
return null;
}
switch (datatype) {
case 'string':
case 'commonsMedia':
case 'url':
case 'math':
case 'external-id':
return datavalue.value;
case 'monolingualtext':
return datavalue.value.text;
case 'wikibase-item':
var qid = 'Q' + datavalue.value['numeric-id'];
qids.push(qid);
return qid;
case 'time':
return datavalue.value.time;
case 'quantity':
return datavalue.value.amount;
default:
return null;
}
};
var getPropertyAndEntityLabels = function(propertiesAndEntities) {
var labels = {};
try {
var size = 50;
var j = propertiesAndEntities.length;
for (var i = 0; i < j; i += size) {
var chunk = propertiesAndEntities.slice(i, i + size);
var url = 'https://www.wikidata.org/w/api.php' +
'?action=wbgetentities' +
'&languages=en' +
'&format=json' +
'&props=labels' +
'&ids=' + chunk.join('%7C');
var json = JSON.parse(UrlFetchApp.fetch(url, HEADERS).getContentText());
var entities = json.entities;
chunk.forEach(function(item) {
if ((entities[item]) &&
(entities[item].labels) &&
(entities[item].labels.en) &&
(entities[item].labels.en.value)) {
labels[item] = entities[item].labels.en.value;
} else {
labels[item] = false;
}
});
}
} catch (e) {
// no-op
}
return labels;
};
if (!article) {
return '';
}
opt_properties = opt_properties || [];
opt_properties = Array.isArray(opt_properties) ?
opt_properties : [opt_properties];
var temp = {};
opt_properties.forEach(function(prop) {
temp[prop] = true;
});
opt_properties = Object.keys(temp);
var results = [];
try {
var language;
var title;
if (article.indexOf(':') !== -1) {
language = article.split(/:(.+)?/)[0];
title = article.split(/:(.+)?/)[1];
} else {
language = DEFAULT_LANGUAGE;
title = article;
}
if (!title) {
return '';
}
var url;
if (/^Q\d+$/.test(title)) {
url = 'https://www.wikidata.org/w/api.php' +
'?action=wbgetentities' +
'&format=json' +
'&props=claims' +
'&ids=' + title;
} else {
url = 'https://wikidata.org/w/api.php' +
'?action=wbgetentities' +
'&sites=' + language + 'wiki' +
'&format=json' +
'&props=claims' +
'&titles=' + encodeURIComponent(title.replace(/\s/g, '_'));
}
var json = JSON.parse(UrlFetchApp.fetch(url, HEADERS).getContentText());
var entity = Object.keys(json.entities)[0];
var qids = [];
var simplifiedClaims = simplifyClaims(json.entities[entity].claims);
var properties = Object.keys(simplifiedClaims);
if (opt_properties.length) {
properties = properties.filter(function(property) {
return opt_properties.indexOf(property) !== -1;
});
}
var labels = getPropertyAndEntityLabels(properties.concat(qids));
for (var claim in simplifiedClaims) {
var claims = simplifiedClaims[claim].filter(function(value) {
return value !== null;
});
// Only return single-object facts
if (claims.length === 1) {
var label = labels[claim];
var value = /^Q\d+$/.test(claims[0]) ? labels[claims[0]] : claims[0];
if (label && value) {
results.push([label, value]);
}
}
// Optionally return multi-object facts
if ((
(/^first$/i.test(opt_multiObjectMode)) ||
(/^all$/i.test(opt_multiObjectMode))
) && (claims.length > 1)) {
var label = labels[claim];
claims.forEach(function(claimObject, i) {
if (i > 0 && /^first$/i.test(opt_multiObjectMode)) {
return;
}
var value = /^Q\d+$/.test(claimObject) ?
labels[claimObject] : claimObject;
if (label && value) {
results.push([label, value]);
}
});
}
}
} catch (e) {
// no-op
}
return results.length > 0 ? results : '';
}
/**
* Returns the Wikipedia site links for a given Wikidata item.
*
* @param {string} qid The Wikidata item QID to get the Wikipedia site links for.
* @param {Array<string>=} opt_sitefilter The list of Wikipedia sites to limit the results to (optional).
* @return {Array<string>} The list of site links.
* @customfunction
*/
function WIKIDATASITELINKS(qid, opt_sitefilter) {
'use strict';
if (!qid) {
return '';
}
var results = [];
try {
opt_sitefilter = opt_sitefilter || [];
opt_sitefilter = Array.isArray(opt_sitefilter) ? opt_sitefilter : [opt_sitefilter];
var sitefilterQuery = opt_sitefilter.length ? '&sitefilter=' + opt_sitefilter.map(site => site + 'wiki').join('%7C') : '';
var url = 'https://www.wikidata.org/w/api.php' +
'?format=json' +
'&action=wbgetentities' +
'&props=sitelinks' +
'&ids=' + qid +
sitefilterQuery;
var json = JSON.parse(UrlFetchApp.fetch(url, HEADERS).getContentText());
var sitelinks = json.entities[qid].sitelinks;
var availableSites = Object.keys(sitelinks).sort();
availableSites.forEach(function(site) {
var link = sitelinks[site].title;
results.push([site.replace(/wiki$/, ''), link]);
});
} catch (e) {
// no-op
}
return results.length > 0 ? results : '';
}
/**
* Returns Wikipedia pageviews statistics for a Wikipedia article.
*
* @param {string} article The Wikipedia article in the format "language:Article_Title" ("de:Berlin") to get pageviews statistics for.
* @param {string=} opt_start The start date in the format "YYYYMMDD" ("20070608") since when pageviews statistics should be retrieved from (optional).
* @param {string=} opt_end The end date in the format "YYYYMMDD" ("20070608") until when pageviews statistics should be retrieved to (optional).
* @param {boolean=} opt_sumOnly Whether to only return the sum of all pageviews in the requested period (optional).
* @return {Array<number>} The list of pageviews between start and end per day.
* @customfunction
*/
function WIKIPAGEVIEWS(article, opt_start, opt_end, opt_sumOnly) {
'use strict';
var getIsoDate = function(date) {
var date = new Date(date);
var year = date.getFullYear().toString();
var month = (date.getMonth() + 1) < 10 ?
'0' + (date.getMonth() + 1) :
(date.getMonth() + 1).toString();
var day = date.getDate() < 10 ?
'0' + date.getDate() :
date.getDate().toString();
return year + month + day;
};
if (!article) {
return '';
}
var results = [];
var sum = 0;
try {
var language;
var title;
if (article.indexOf(':') !== -1) {
language = article.split(/:(.+)?/)[0];
title = article.split(/:(.+)?/)[1];
} else {
language = DEFAULT_LANGUAGE;
title = article;
}
if (!title) {
return '';
}
opt_start = opt_start || new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
if (typeof opt_start === 'object') {
opt_start = getIsoDate(opt_start);
}
opt_end = opt_end || new Date(Date.now() - 1 * 24 * 60 * 60 * 1000);
if (typeof opt_end === 'object') {
opt_end = getIsoDate(opt_end);
}
var url = 'https://wikimedia.org/api/rest_v1/metrics/pageviews/' +
'per-article' +
'/' + language + '.wikipedia' +
'/all-access' +
'/user' +
'/' + encodeURIComponent(title.replace(/\s/g, '_')) +
'/daily' +
'/' + opt_start +
'/' + opt_end;
var json = JSON.parse(UrlFetchApp.fetch(url, HEADERS).getContentText());
json.items.forEach(function(item) {
if (opt_sumOnly) {
sum += item.views;
} else {
var timestamp = item.timestamp.replace(/^(\d{4})(\d{2})(\d{2})(\d{2})$/,
'$1-$2-$3-$4').split('-');
timestamp = new Date(Date.UTC(
parseInt(timestamp[0], 10), // Year
parseInt(timestamp[1], 10) - 1, // Month
parseInt(timestamp[2], 10), // Day
parseInt(timestamp[3], 10), // Hour
0, // Minute
0)); // Second))
results.push([
timestamp,
item.views
]);