-
Notifications
You must be signed in to change notification settings - Fork 21
/
utilities.js
1888 lines (1686 loc) · 59.4 KB
/
utilities.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
/*
***** BEGIN LICENSE BLOCK *****
Copyright © 2009 Center for History and New Media
George Mason University, Fairfax, Virginia, USA
http://zotero.org
This file is part of Zotero.
Zotero is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Zotero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Zotero. If not, see <http://www.gnu.org/licenses/>.
Utilities based in part on code taken from Piggy Bank 2.1.1 (BSD-licensed)
***** END LICENSE BLOCK *****
*/
(function() {
function movedToUtilitiesInternal(fnName) {
return function () {
if (Zotero.Utilities && Zotero.Utilities.Internal) {
Zotero.debug(`Zotero.Utilities.${fnName}() is deprecated -- use Zotero.Utilities.Internal.${fnName}() instead`);
return Zotero.Utilities.Internal[fnName].apply(Zotero.Utilities.Internal, arguments);
} else {
throw new Error(`Zotero.Utilities.${fnName}() is only available in the zotero-client codebase`)
}
}
}
/**
* @class Functions for text manipulation and other miscellaneous purposes
*/
var Utilities = {
/**
* Returns a function which will execute `fn` with provided arguments after `delay` milliseconds and not more
* than once, if called multiple times. See
* http://stackoverflow.com/questions/24004791/can-someone-explain-the-debounce-function-in-javascript
* @param fn {Function} function to debounce
* @param delay {Integer} number of milliseconds to delay the function execution
* @returns {Function}
*/
debounce: function(fn, delay=500) {
var timer = null;
return function () {
let args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(this, args);
}.bind(this), delay);
};
},
/**
* Creates and returns a new, throttled version of the
* passed function, that, when invoked repeatedly,
* will only actually call the original function at most
* once per every wait milliseconds
*
* By default, throttle will execute the function as soon
* as you call it for the first time, and, if you call it
* again any number of times during the wait period, as soon
* as that period is over. If you'd like to disable the
* leading-edge call, pass {leading: false}, and if you'd
* like to disable the execution on the trailing-edge,
* pass {trailing: false}. See
* https://underscorejs.org/#throttle
* https://github.com/jashkenas/underscore/blob/master/underscore.js
* (c) 2009-2018 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Underscore may be freely distributed under the MIT license.
*
* @param {Function} func Function to throttle
* @param {Integer} wait Wait period in milliseconds
* @param {Boolean} [options.leading] Call at the beginning of the wait period
* @param {Boolean} [options.trailing] Call at the end of the wait period
*/
throttle: function (func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
if (!options) options = {};
var later = function () {
previous = options.leading === false ? 0 : Date.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function () {
var now = Date.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
}
else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
},
sentenceCase: function (text) {
const preserve = [];
const allcaps = text === text.toUpperCase()
// sub-sentence start
text.replace(/([.?!][\s]+)(<[^>]+>)?([\p{Lu}])/ug, (match, end, markup, char, i) => {
markup = markup || "";
if (!text.substring(0, i + 1).match(/(\p{Lu}[.]){2,}$/u)) { // prevent "U.S. Taxes" from starting a new sub-sentence
preserve.push({ start: i + end.length + markup.length, end: i + end.length + markup.length + char.length });
}
});
// protect leading capital
text.replace(/^(<[^>]+>)?([\p{Lu}])/u, (match, markup, char) => {
markup = markup || "";
preserve.push({ start: markup.length, end: markup.length + char.length });
});
// protect nocase
text.replace(/<span class="nocase">.*?<\/span>|<nc>.*?<\/nc>/gi, (match, i) => {
preserve.push({ start: i, end: i + match.length, description: 'nocase' });
});
// mask html tags with characters so the sentence-casing can deal with them as simple words
let masked = text.replace(/<[^>]+>/g, (match, i) => {
preserve.push({ start: i, end: i + match.length, description: 'markup' });
return '\uFFFD'.repeat(match.length);
});
masked = masked
.replace(/[;:]\uFFFD*\s+\uFFFD*A\s/g, match => match.toLowerCase())
.replace(/[–—]\uFFFD*\s*\uFFFD*A\s/g, match => match.toLowerCase())
// words, compound words, and acronyms (latter also catches U.S.A.)
.replace(/([\u{FFFD}\p{L}\p{N}\p{No}]+([\u{FFFD}\p{L}\p{N}\p{No}\p{Pc}]*))|(\s(\p{Lu}+[.]){2,})?/ug, word => {
if (allcaps) return word.toLowerCase()
const unmasked = word.replace(/\uFFFD/g, '');
if (unmasked.length === 1) {
return unmasked === 'A' ? word.toLowerCase() : word
}
// inner capital somewhere
if (unmasked.match(/.\p{Lu}/u)) {
return word
}
// identifiers or allcaps
if (unmasked.match(/^\p{L}\p{L}*[\p{N}\p{No}][\p{L}\p{N}\p{No}]*$/u) || unmasked.match(/^[\p{Lu}\p{N}\p{No}]+$/u)) {
return word
}
return word.toLowerCase()
});
for (const { start, end } of preserve) {
masked = masked.substring(0, start) + text.substring(start, end) + masked.substring(end);
}
return masked;
},
/**
* Fixes author name capitalization.
* Splits names into space-separated parts and only changes parts either in all uppercase
* or all lowercase.
*
* JOHN -> John
* GUTIÉRREZ-ALBILLA -> Gutiérrez-Albilla
* O'NEAL -> O'Neal
* o'neal -> O'Neal
* O'neal -> O'neal
* John MacGregor O'NEILL -> John MacGregor O'Neill
* martha McMiddlename WASHINGTON -> Martha McMiddlename Washington
*
* @param {String} string Uppercase author name
* @return {String} Title-cased author name
*/
capitalizeName: function (string) {
if (!(typeof string === 'string')) {
return string;
}
return string.split(' ')
.map((part) => {
if (part.toUpperCase() === part || part.toLowerCase() === part) {
return Utilities.XRegExp.replace(
part.toLowerCase(),
Utilities.XRegExp('(^|[^\\pL])\\pL', 'g'),
m => m.toUpperCase()
);
}
else {
return part;
}
})
.join(' ');
},
/**
* Cleans extraneous punctuation off a creator name and parse into first and last name
*
* @param {String} author Creator string
* @param {String} type Creator type string (e.g., "author" or "editor")
* @param {Boolean} useComma Whether the creator string is in inverted (Last, First) format
* @return {Object} firstName, lastName, and creatorType
*/
cleanAuthor: function(author, type, useComma) {
var allCaps = 'A-Z' +
'\u0400-\u042f'; //cyrilic
var allCapsRe = new RegExp('^[' + allCaps + ']+$');
var initialRe = new RegExp('^-?[' + allCaps + ']$');
if(typeof(author) != "string") {
throw new Error("cleanAuthor: author must be a string");
}
author = author.replace(/^[\s\u00A0\.\,\/\[\]\:]+/, '')
.replace(/[\s\u00A0\.\,\/\[\]\:]+$/, '')
.replace(/[\s\u00A0]+/, ' ');
if(useComma) {
// Add spaces between periods
author = author.replace(/\.([^ ])/, ". $1");
var splitNames = author.split(/[,،] ?/);
if(splitNames.length > 1) {
var lastName = splitNames[0];
var firstName = splitNames[1];
} else {
var lastName = author;
}
} else {
// Don't parse "Firstname Lastname [Country]" as "[Country], Firstname Lastname"
var spaceIndex = author.length;
do {
spaceIndex = author.lastIndexOf(" ", spaceIndex-1);
var lastName = author.substring(spaceIndex + 1);
var firstName = author.substring(0, spaceIndex);
} while (!Utilities.XRegExp('\\pL').test(lastName[0]) && spaceIndex > 0)
}
if(firstName && allCapsRe.test(firstName) &&
firstName.length < 4 &&
(firstName.length == 1 || lastName.toUpperCase() != lastName)) {
// first name is probably initials
var newFirstName = "";
for(var i=0; i<firstName.length; i++) {
newFirstName += " "+firstName[i]+".";
}
firstName = newFirstName.substr(1);
}
//add periods after all the initials
if(firstName) {
var names = firstName.replace(/^[\s\.]+/,'')
.replace(/[\s\,]+$/,'')
//remove spaces surronding any dashes
.replace(/\s*([\u002D\u00AD\u2010-\u2015\u2212\u2E3A\u2E3B])\s*/,'-')
.split(/(?:[\s\.]+|(?=-))/);
var newFirstName = '';
for(var i=0, n=names.length; i<n; i++) {
newFirstName += names[i];
if(initialRe.test(names[i])) newFirstName += '.';
newFirstName += ' ';
}
firstName = newFirstName.replace(/ -/g,'-').trim();
}
return {firstName:firstName, lastName:lastName, creatorType:type};
},
/**
* Removes leading and trailing whitespace from a string
* @type String
*/
trim: function(/**String*/ s) {
if (typeof(s) != "string") {
throw new Error("trim: argument must be a string");
}
s = s.replace(/^\s+/, "");
return s.replace(/\s+$/, "");
},
/**
* Cleans whitespace off a string and replaces multiple spaces with one
* @type String
*/
trimInternal: function(/**String*/ s) {
if (typeof(s) != "string") {
throw new Error("trimInternal: argument must be a string");
}
s = s.replace(/[\xA0\r\n\s]+/g, " ");
return this.trim(s);
},
/**
* Cleans any non-word non-parenthesis characters off the ends of a string
* @type String
*/
superCleanString: function(/**String*/ x) {
if(typeof(x) != "string") {
throw new Error("superCleanString: argument must be a string");
}
var x = x.replace(/^[\x00-\x27\x29-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F\s]+/, "");
return x.replace(/[\x00-\x28\x2A-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F\s]+$/, "");
},
isHTTPURL: function (url, allowNoScheme = false) {
// From https://stackoverflow.com/a/3809435
var noSchemeRE = /^[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/;
return /^https?:\/\//.test(url)
|| (allowNoScheme && !url.startsWith('mailto:') && noSchemeRE.test(url));
},
/**
* Cleans a http url string
* @param url {String}
* @params tryHttp {Boolean} Attempt prepending 'http://' to the url
* @returns {String}
*/
cleanURL: function(url, tryHttp=false) {
url = url.trim();
if (!url) return false;
try {
return Services.io.newURI(url, null, null).spec; // Valid URI if succeeds
} catch (e) {
if (e instanceof Components.Exception
&& e.result == Components.results.NS_ERROR_MALFORMED_URI
) {
if (tryHttp && /\w\.\w/.test(url)) {
// Assume it's a URL missing "http://" part
try {
return Services.io.newURI('http://' + url, null, null).spec;
} catch (e) {}
}
Zotero.debug('cleanURL: Invalid URI: ' + url, 2);
return false;
}
throw e;
}
},
/**
* Eliminates HTML tags, replacing <br>s with newlines
* @type String
*/
cleanTags: function(/**String*/ x) {
if(typeof(x) != "string") {
throw new Error("cleanTags: argument must be a string");
}
x = x.replace(/<br[^>]*>/gi, "\n");
x = x.replace(/<\/p>/gi, "\n\n");
return x.replace(/<[^>]+>/g, "");
},
extractIdentifiers: function (text) {
var identifiers = [];
var foundIDs = new Set(); // keep track of identifiers to avoid duplicates
// First look for DOIs
var ids = text.split(/[\s\u00A0]+/); // whitespace + non-breaking space
var doi;
for (let id of ids) {
if ((doi = Zotero.Utilities.cleanDOI(id)) && !foundIDs.has(doi)) {
identifiers.push({
DOI: doi
});
foundIDs.add(doi);
}
}
// Then try ISBNs
if (!identifiers.length) {
// First try replacing dashes
let ids = text.replace(/[\u002D\u00AD\u2010-\u2015\u2212]+/g, "") // hyphens and dashes
.toUpperCase();
let ISBN_RE = /(?:\D|^)(97[89]\d{10}|\d{9}[\dX])(?!\d)/g;
let isbn;
while (isbn = ISBN_RE.exec(ids)) {
isbn = Zotero.Utilities.cleanISBN(isbn[1]);
if (isbn && !foundIDs.has(isbn)) {
identifiers.push({
ISBN: isbn
});
foundIDs.add(isbn);
}
}
// Next try spaces
if (!identifiers.length) {
ids = ids.replace(/[ \u00A0]+/g, ""); // space + non-breaking space
while (isbn = ISBN_RE.exec(ids)) {
isbn = Zotero.Utilities.cleanISBN(isbn[1]);
if(isbn && !foundIDs.has(isbn)) {
identifiers.push({
ISBN: isbn
});
foundIDs.add(isbn);
}
}
}
}
// Next try arXiv
if (!identifiers.length) {
// arXiv identifiers are extracted without version number
// i.e. 0706.0044v1 is extracted as 0706.0044,
// because arXiv OAI API doesn't allow to access individual versions
let arXiv_RE = /((?:[^A-Za-z]|^)([\-A-Za-z\.]+\/\d{7})(?:(v[0-9]+)|)(?!\d))|((?:\D|^)(\d{4}\.\d{4,5})(?:(v[0-9]+)|)(?!\d))/g;
let m;
while ((m = arXiv_RE.exec(text))) {
let arXiv = m[2] || m[5];
if (arXiv && !foundIDs.has(arXiv)) {
identifiers.push({arXiv: arXiv});
foundIDs.add(arXiv);
}
}
}
// Next, try ADS Bibcodes
if (!identifiers.length) {
// regex as in the ADS Bibcode translator
let adsBibcode_RE = /\b(\d{4}\D\S{13}[A-Z.:])\b/g;
let adsBibcode;
while ((adsBibcode = adsBibcode_RE.exec(text)) && !foundIDs.has(adsBibcode)) {
identifiers.push({
adsBibcode: adsBibcode[1]
});
foundIDs.add(adsBibcode);
}
}
// Finally, try PMID
if (!identifiers.length) {
// PMID; right now, the longest PMIDs are 8 digits, so it doesn't seem like we'll
// need to discriminate for a fairly long time
let PMID_RE = /(^|\s|,|:)(\d{1,9})(?=\s|,|$)/g;
let pmid;
while ((pmid = PMID_RE.exec(text)) && !foundIDs.has(pmid)) {
identifiers.push({
PMID: pmid[2]
});
foundIDs.add(pmid);
}
}
return identifiers;
},
/**
* Strip info:doi prefix and any suffixes from a DOI
* @type String
*/
cleanDOI: function(/**String**/ x) {
if(typeof(x) != "string") {
throw new Error("cleanDOI: argument must be a string");
}
// If it's a URL, try to decode it
if (/^https?:/.test(x)) {
try {
x = decodeURIComponent(x);
}
catch (e) {
// URI contains an invalid escape sequence
Zotero.debug("Not decoding URL-like DOI because of invalid escape sequence: " + x);
}
}
// Even if it's not a URL, decode %3C followed by %3E as < >
var openingPos = x.indexOf("%3C");
if (openingPos != -1 && openingPos < x.indexOf("%3E")) {
x = x.replace(/%3C/g, "<");
x = x.replace(/%3E/g, ">");
}
var doi = x.match(/10(?:\.[0-9]{4,})?\/[^\s]*[^\s\.,]/);
if (!doi) {
return null;
}
var result = doi[0];
// Check if the DOI ends with a bracket
var trailingBracket = result.slice(-1);
if ([']', ')', '}'].includes(trailingBracket)) {
// Check the portion of the string before the matched DOI for an unclosed bracket
let beforeDOI = x.slice(0, doi.index);
let openingBracket = {
']': '[',
')': '(',
'}': '{'
}[trailingBracket];
if (beforeDOI.lastIndexOf(openingBracket) > beforeDOI.lastIndexOf(trailingBracket)) {
// Remove the trailing bracket from the DOI
result = result.slice(0, -1);
}
}
return result;
},
/**
* Clean and validate ISBN.
* Return isbn if valid, otherwise return false
* @param {String} isbn
* @param {Boolean} [dontValidate=false] Do not validate check digit
* @return {String|Boolean} Valid ISBN or false
*/
cleanISBN: function(isbnStr, dontValidate) {
isbnStr = isbnStr.toUpperCase()
.replace(/[\x2D\xAD\u2010-\u2015\u2043\u2212]+/g, ''); // Ignore dashes
var isbnRE = /\b(?:97[89]\s*(?:\d\s*){9}\d|(?:\d\s*){9}[\dX])\b/g,
isbnMatch;
while(isbnMatch = isbnRE.exec(isbnStr)) {
var isbn = isbnMatch[0].replace(/\s+/g, '');
if (dontValidate) {
return isbn;
}
if(isbn.length == 10) {
// Verify ISBN-10 checksum
var sum = 0;
for (var i = 0; i < 9; i++) {
sum += isbn[i] * (10-i);
}
//check digit might be 'X'
sum += (isbn[9] == 'X')? 10 : isbn[9]*1;
if (sum % 11 == 0) return isbn;
} else {
// Verify ISBN 13 checksum
var sum = 0;
for (var i = 0; i < 12; i+=2) sum += isbn[i]*1; //to make sure it's int
for (var i = 1; i < 12; i+=2) sum += isbn[i]*3;
sum += isbn[12]*1; //add the check digit
if (sum % 10 == 0 ) return isbn;
}
isbnRE.lastIndex = isbnMatch.index + 1; // Retry the same spot + 1
}
return false;
},
/*
* Convert ISBN 10 to ISBN 13
* @param {String} isbn ISBN 10 or ISBN 13
* cleanISBN
* @return {String} ISBN-13
*/
toISBN13: function(isbnStr) {
var isbn;
if (!(isbn = Utilities.cleanISBN(isbnStr, true))) {
throw new Error('ISBN not found in "' + isbnStr + '"');
}
if (isbn.length == 13) {
isbn = isbn.substr(0,12); // Strip off check digit and re-calculate it
} else {
isbn = '978' + isbn.substr(0,9);
}
var sum = 0;
for (var i = 0; i < 12; i++) {
sum += isbn[i] * (i%2 ? 3 : 1);
}
var checkDigit = 10 - (sum % 10);
if (checkDigit == 10) checkDigit = 0;
return isbn + checkDigit;
},
/**
* Clean and validate ISSN.
* Return issn if valid, otherwise return false
*/
cleanISSN: function(/**String*/ issnStr) {
issnStr = issnStr.toUpperCase()
.replace(/[\x2D\xAD\u2010-\u2015\u2043\u2212]+/g, ''); // Ignore dashes
var issnRE = /\b(?:\d\s*){7}[\dX]\b/g,
issnMatch;
while (issnMatch = issnRE.exec(issnStr)) {
var issn = issnMatch[0].replace(/\s+/g, '');
// Verify ISSN checksum
var sum = 0;
for (var i = 0; i < 7; i++) {
sum += issn[i] * (8-i);
}
//check digit might be 'X'
sum += (issn[7] == 'X')? 10 : issn[7]*1;
if (sum % 11 == 0) {
return issn.substring(0,4) + '-' + issn.substring(4);
}
issnRE.lastIndex = issnMatch.index + 1; // Retry same spot + 1
}
return false;
},
/**
* Convert plain text to HTML by replacing special characters and replacing newlines with BRs or
* P tags
* @param {String} str Plain text string
* @param {Boolean} singleNewlineIsParagraph Whether single newlines should be considered as
* paragraphs. If true, each newline is replaced with a P tag. If false, double newlines
* are replaced with P tags, while single newlines are replaced with BR tags.
* @type String
*/
text2html: function (/**String**/ str, /**Boolean**/ singleNewlineIsParagraph) {
str = Utilities.htmlSpecialChars(str);
// \n => <p>
if (singleNewlineIsParagraph) {
str = '<p>'
+ str.replace(/\n/g, '</p><p>')
.replace(/ /g, ' ')
+ '</p>';
}
// \n\n => <p>, \n => <br/>
else {
str = '<p>'
+ str.replace(/\n\n/g, '</p><p>')
.replace(/\n/g, '<br/>')
.replace(/ /g, ' ')
+ '</p>';
}
return str.replace(/<p>\s*<\/p>/g, '<p> </p>');
},
/**
* Encode special XML/HTML characters
* Certain entities can be inserted manually:
* <ZOTEROBREAK/> => <br/>
* <ZOTEROHELLIP/> => …
*
* @param {String} str
* @return {String}
*/
htmlSpecialChars: function(str) {
if (str && typeof str != 'string') {
Zotero.debug('#htmlSpecialChars: non-string arguments are deprecated. Update your code',
1, undefined, true);
str = str.toString();
}
if (!str) return '';
return str
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/<ZOTERO([^\/]+)\/>/g, function (str, p1, offset, s) {
switch (p1) {
case 'BREAK':
return '<br/>';
case 'HELLIP':
return '…';
default:
return p1;
}
});
},
/**
* Decodes HTML entities within a string, returning plain text
* @type String
*/
"unescapeHTML":new function() {
var nsIScriptableUnescapeHTML, node;
return function(/**String*/ str) {
// If no tags, no need to unescape
if(str.indexOf("<") === -1 && str.indexOf("&") === -1) return str;
if(Zotero.isFx && !Zotero.isBookmarklet) {
// Create a node and use the textContent property to do unescaping where
// possible, because this approach preserves line endings in the HTML
if(node === undefined) {
node = Utilities.Internal.getDOMDocument().createElement("div");
}
node.innerHTML = str;
return node.textContent.replace(/ {2,}/g, " ");
} else if(Zotero.isNode) {
let {JSDOM} = require('jsdom');
let document = (new JSDOM(str)).window.document;
return document.documentElement.textContent.replace(/ {2,}/g, " ");
} else {
if(!node) node = document.createElement("div");
node.innerHTML = str;
return ("textContent" in node ? node.textContent : node.innerText).replace(/ {2,}/g, " ");
}
};
},
/**
* Wrap URLs and DOIs in <a href=""> links in plain text
*
* Ignore URLs preceded by '>', just in case there are already links
* @type String
*/
autoLink: function (/**String**/ str) {
// "http://www.google.com."
// "http://www.google.com. "
// "<http://www.google.com>" (and other characters, with or without a space after)
str = str.replace(/([^>])(https?:\/\/[^\s]+)([\."'>:\]\)](\s|$))/g, '$1<a href="$2">$2</a>$3');
// "http://www.google.com"
// "http://www.google.com "
str = str.replace(/([^">])(https?:\/\/[^\s]+)(\s|$)/g, '$1<a href="$2">$2</a>$3');
// DOI
str = str.replace(/(doi:[ ]*)(10\.[^\s]+[0-9a-zA-Z])/g, '$1<a href="http://dx.doi.org/$2">$2</a>');
return str;
},
/**
* Parses a text string for HTML/XUL markup and returns an array of parts. Currently only finds
* HTML links (<a> tags)
*
* @return {Array} An array of objects with the following form:<br>
* <pre> {
* type: 'text'|'link',
* text: "text content",
* [ attributes: { key1: val [ , key2: val, ...] }
* }</pre>
*/
parseMarkup: function(/**String*/ str) {
var parts = [];
var splits = str.split(/(<a [^>]+>[^<]*<\/a>)/);
for(var i=0; i<splits.length; i++) {
// Link
if (splits[i].indexOf('<a ') == 0) {
var matches = splits[i].match(/<a ([^>]+)>([^<]*)<\/a>/);
if (matches) {
// Attribute pairs
var attributes = {};
var pairs = matches[1].match(/([^ =]+)="([^"]+")/g);
for(var j=0; j<pairs.length; j++) {
var keyVal = pairs[j].split(/=/);
attributes[keyVal[0]] = keyVal[1].substr(1, keyVal[1].length - 2);
}
parts.push({
type: 'link',
text: matches[2],
attributes: attributes
});
continue;
}
}
parts.push({
type: 'text',
text: splits[i]
});
}
return parts;
},
/**
* Calculates the Levenshtein distance between two strings
* @type Number
*/
levenshtein: function (/**String*/ a, /**String**/ b) {
var aLen = a.length;
var bLen = b.length;
var arr = new Array(aLen+1);
var i, j, cost;
for (i = 0; i <= aLen; i++) {
arr[i] = new Array(bLen);
arr[i][0] = i;
}
for (j = 0; j <= bLen; j++) {
arr[0][j] = j;
}
for (i = 1; i <= aLen; i++) {
for (j = 1; j <= bLen; j++) {
cost = (a[i-1] == b[j-1]) ? 0 : 1;
arr[i][j] = Math.min(arr[i-1][j] + 1, Math.min(arr[i][j-1] + 1, arr[i-1][j-1] + cost));
}
}
return arr[aLen][bLen];
},
/**
* Test if an object is empty
*
* @param {Object} obj
* @type Boolean
*/
isEmpty: function (obj) {
for (var i in obj) {
return false;
}
return true;
},
/**
* Compares an array with another and returns an array with
* the values from array1 that don't exist in array2
*
* @param {Array} array1
* @param {Array} array2
* @param {Boolean} useIndex If true, return an array containing just
* the index of array2's elements;
* otherwise return the values
*/
arrayDiff: function(array1, array2, useIndex) {
if (!Array.isArray(array1)) {
throw new Error("array1 is not an array (" + array1 + ")");
}
if (!Array.isArray(array2)) {
throw new Error("array2 is not an array (" + array2 + ")");
}
var val, pos, vals = [];
for (var i=0; i<array1.length; i++) {
val = array1[i];
pos = array2.indexOf(val);
if (pos == -1) {
vals.push(useIndex ? pos : val);
}
}
return vals;
},
/**
* Determine whether two arrays are identical
*
* Modified from http://stackoverflow.com/a/14853974
*
* @return {Boolean}
*/
arrayEquals: function (array1, array2) {
// If either array is a falsy value, return
if (!array1 || !array2)
return false;
// Compare lengths - can save a lot of time
if (array1.length != array2.length)
return false;
for (var i = 0, l=array1.length; i < l; i++) {
// Check if we have nested arrays
if (array1[i] instanceof Array && array2[i] instanceof Array) {
// Recurse into the nested arrays
if (!this.arrayEquals(array1[i], array2[i])) {
return false;
}
}
else if (array1[i] != array2[i]) {
// Warning - two different object instances will never be equal: {x:20} != {x:20}
return false;
}
}
return true;
},
/**
* Return new array with values shuffled
*
* From http://stackoverflow.com/a/6274398
*
* @param {Array} arr
* @return {Array}
*/
arrayShuffle: function (array) {
var counter = array.length, temp, index;
// While there are elements in the array
while (counter--) {
// Pick a random index
index = (Math.random() * counter) | 0;
// And swap the last element with it
temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
},
/**
* Return new array with duplicate values removed
*
* @param {Array} array
* @return {Array}
*/
arrayUnique: function (arr) {
return [...new Set(arr)];
},
/**
* Generate a random integer between min and max inclusive
*
* @param {Integer} min
* @param {Integer} max
* @return {Integer}
*/
rand: function (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
},
/**
* Parse a page range
*
* @param {String} Page range to parse
* @return {Integer[]} Start and end pages
*/
getPageRange: function(pages) {
const pageRangeRegexp = /^\s*([0-9]+) ?[-\u2013] ?([0-9]+)\s*$/
var pageNumbers;
var m = pageRangeRegexp.exec(pages);
if(m) {
// A page range
pageNumbers = [m[1], m[2]];
} else {
// Assume start and end are the same
pageNumbers = [pages, pages];
}
return pageNumbers;
},
/**
* Pads a number or other string with a given string on the left
*
* @param {String} string String to pad
* @param {String} pad String to use as padding
* @length {Integer} length Length of new padded string
* @type String
*/
lpad: function(string, pad, length) {
string = string ? string + '' : '';
while(string.length < length) {
string = pad + string;
}
return string;
},
/**
* Shorten and add an ellipsis to a string if necessary
*
* @param {String} str
* @param {Integer} len
* @param {Boolean} [wordBoundary=false]
* @param {Boolean} [countChars=false]
*/
ellipsize: function (str, len, wordBoundary = false, countChars) {
if (!len) {
throw ("Length not specified in Utilities.ellipsize()");
}
if (str.length <= len) {
return str;
}
var origLen = str.length;
let radius = Math.min(len, 5);
if (wordBoundary) {