This repository has been archived by the owner on Jan 3, 2020. It is now read-only.
forked from zotero/translators
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRIS.js
6898 lines (6730 loc) · 253 KB
/
RIS.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
{
"translatorID": "32d59d2d-b65a-4da4-b0a3-bdd3cfb979e7",
"label": "RIS",
"creator": "Simon Kornblith and Aurimas Vinckevicius",
"target": "ris",
"minVersion": "3.0.4",
"maxVersion": "",
"priority": 100,
"configOptions": {
"getCollections": "true"
},
"displayOptions": {
"exportCharset": "UTF-8",
"exportNotes": true,
"exportFileData": false
},
"inRepository": true,
"translatorType": 3,
"browserSupport": "gcsv",
"lastUpdated": "2015-06-19 19:24:24"
}
function detectImport() {
var line;
var i = 0;
while((line = Zotero.read()) !== false) {
line = line.replace(/^\s+/, "");
if(line != "") {
if(line.substr(0, 6).match(/^TY {1,2}- /)) {
return true;
} else {
if(i++ > 3) {
return false;
}
}
}
}
}
/********************
* Exported options *
********************/
//exported as translatorObject.options
var exportedOptions = {
itemType: false, //allows translators to override item type
defaultItemType: false, //item type to default to
typeMap: false,
fieldMap: false
};
/************************
* TY <-> itemType maps *
************************/
var DEFAULT_EXPORT_TYPE = 'GEN';
var DEFAULT_IMPORT_TYPE = 'journalArticle';
var exportTypeMap = {
artwork:"ART",
audioRecording:"SOUND", //consider MUSIC
bill:"BILL",
blogPost:"BLOG",
book:"BOOK",
bookSection:"CHAP",
"case":"CASE",
computerProgram:"COMP",
conferencePaper:"CONF",
dictionaryEntry:"DICT",
encyclopediaArticle:"ENCYC",
email:"ICOMM",
film:"MPCT",
hearing:"HEAR",
journalArticle:"JOUR",
letter:"PCOMM",
magazineArticle:"MGZN",
manuscript:"MANSCPT",
map:"MAP",
newspaperArticle:"NEWS",
patent:"PAT",
presentation:"SLIDE",
report:"RPRT",
statute:"STAT",
thesis:"THES",
videoRecording:"VIDEO",
webpage:"ELEC"
};
//These export type maps are degenerate
//They will cause loss of information when exported and reimported
//These should either be duplicates of some of the RIS types above
// or be different from the importTypeMap mappings
var degenerateExportTypeMap = {
interview:"PCOMM",
instantMessage:"ICOMM",
forumPost:"ICOMM",
tvBroadcast:"MPCT",
radioBroadcast:"SOUND",
podcast:"SOUND",
document:"GEN" //imported as journalArticle
};
//These are degenerate types that are not exported as the same TY value
//These should not include any types from exportTypeMap
//We add the rest from exportTypeMap
var importTypeMap = {
ABST:"journalArticle",
ADVS:"film",
AGGR:"document", //how can we handle "database" citations?
ANCIENT:"document",
CHART:"artwork",
CLSWK:"book",
CPAPER:"conferencePaper",
CTLG:"magazineArticle",
DATA:"document", //dataset
DBASE:"document", //database
EBOOK:"book",
ECHAP:"bookSection",
EDBOOK:"book",
EJOUR:"journalArticle",
EQUA:"document", //what's a good way to handle this?
FIGURE:"artwork",
GEN:"journalArticle",
GOVDOC:"report",
GRNT:"document",
INPR:"manuscript",
JFULL:"journalArticle",
LEGAL:"case", //is this what they mean?
MULTI:"videoRecording", //maybe?
MUSIC:"audioRecording",
PAMP:"manuscript",
SER:"book",
STAND:"report",
UNBILL:"manuscript",
UNPD:"manuscript",
WEB:"webpage" //not in spec, but used by EndNote
};
//supplement input map with export
var ty;
for(ty in exportTypeMap) {
importTypeMap[exportTypeMap[ty]] = ty;
}
//merge degenerate export type map into main list
for(ty in degenerateExportTypeMap) {
exportTypeMap[ty] = degenerateExportTypeMap[ty];
}
/*****************************
* Tag <-> zotero field maps *
*****************************/
/** Syntax
* {
* RIS-TAG:
* String, Zotero field used for any item type
* List, item-type dependent mapping
* {
* Zotero field: Zotero item type array. Map RIS tag to the specified Zotero field for indicated item types
* "__ignore": Zotero item type array. Ignore this RIS tag for indicated item types. Do not place it in a note
* "__default": Zotero field. If not matched by above, map RIS tag to this field, unless...
* "__exclude": Zotero item type array. Do not use the __default mapping for these item types
* }
* }
*
* Special "Zotero fields"
* "attachments/[PDF|HTML|other]": import as attachment with a provided path/url
* "creators/...": map to a specified creator type
* "unsupported/...": there is no corresponding Zotero field, but we can provide a human-readable label for the data and attach it as note
*/
//used for exporting and importing
//this ensures that we can mostly reimport everything the same way
//(except for item types that do not have unique RIS types, see above)
var fieldMap = {
//same for all itemTypes
AB:"abstractNote",
AN:"archiveLocation",
CN:"callNumber",
DB:"archive",
DO:"DOI",
DP:"libraryCatalog",
J2:"journalAbbreviation",
KW:"tags",
L1:"attachments/PDF",
L2:"attachments/HTML",
L4:"attachments/other",
N1:"notes",
ST:"shortTitle",
UR:"url",
Y2:"accessDate",
//type specific
//tag => field:itemTypes
//if itemType not explicitly given, __default field is used
// unless itemType is excluded in __exclude
TI: {
"__default":"title",
subject:["email"],
caseName:["case"],
nameOfAct:["statute"]
},
T2: {
code:["bill", "statute"],
bookTitle:["bookSection"],
blogTitle:["blogPost"],
conferenceName:["conferencePaper"],
dictionaryTitle:["dictionaryEntry"],
encyclopediaTitle:["encyclopediaArticle"],
committee:["hearing"],
forumTitle:["forumPost"],
websiteTitle:["webpage"],
programTitle:["radioBroadcast", "tvBroadcast"],
meetingName:["presentation"],
seriesTitle:["computerProgram", "map", "report"],
series: ["book"],
publicationTitle:["journalArticle", "magazineArticle", "newspaperArticle"]
},
T3: {
legislativeBody:["hearing", "bill"],
series:["bookSection", "conferencePaper", "journalArticle"],
seriesTitle:["audioRecording"]
},
//NOT HANDLED: reviewedAuthor, scriptwriter, contributor, guest
AU: {
"__default":"creators/author",
"creators/artist":["artwork"],
"creators/cartographer":["map"],
"creators/composer":["audioRecording"],
"creators/director":["film", "radioBroadcast", "tvBroadcast", "videoRecording"], //this clashes with audioRecording
"creators/interviewee":["interview"],
"creators/inventor":["patent"],
"creators/podcaster":["podcast"],
"creators/programmer":["computerProgram"]
},
A2: {
"creators/sponsor":["bill"],
"creators/performer":["audioRecording"],
"creators/presenter":["presentation"],
"creators/interviewer":["interview"],
"creators/editor":["journalArticle", "bookSection", "conferencePaper", "dictionaryEntry", "document", "encyclopediaArticle"],
"creators/seriesEditor":["book", "report"],
"creators/recipient":["email", "instantMessage", "letter"],
reporter:["case"],
issuingAuthority:["patent"]
},
A3: {
"creators/cosponsor":["bill"],
"creators/producer":["film", "tvBroadcast", "videoRecording", "radioBroadcast"],
"creators/editor":["book"],
"creators/seriesEditor":["bookSection", "conferencePaper", "dictionaryEntry", "encyclopediaArticle", "map"]
},
A4: {
"__default":"creators/translator",
"creators/counsel":["case"],
"creators/contributor":["conferencePaper", "film"] //translator does not fit these
},
C1: {
filingDate:["patent"], //not in spec
"creators/castMember":["radioBroadcast", "tvBroadcast", "videoRecording"],
scale:["map"],
place:["conferencePaper"]
},
C2: {
issueDate:["patent"], //not in spec
"creators/bookAuthor":["bookSection"],
"creators/commenter":["blogPost"]
},
C3: {
artworkSize:["artwork"],
proceedingsTitle:["conferencePaper"],
country:["patent"]
},
C4: {
"creators/wordsBy":["audioRecording"], //not in spec
"creators/attorneyAgent":["patent"],
genre:["film"]
},
C5: {
references:["patent"],
audioRecordingFormat:["audioRecording", "radioBroadcast"],
videoRecordingFormat:["film", "tvBroadcast", "videoRecording"]
},
C6: {
legalStatus:["patent"],
},
CY: {
"__default":"place",
"__exclude":["conferencePaper"] //should be exported as C1
},
DA: { //also see PY when editing
"__default":"date",
dateEnacted:["statute"],
dateDecided:["case"],
issueDate:["patent"]
},
ET: {
"__default":"edition",
// "__ignore":["journalArticle"], //EPubDate
session:["bill", "hearing", "statute"],
version:["computerProgram"]
},
IS: {
"__default":"issue",
numberOfVolumes: ["bookSection"]
},
LA: {
"__default":"language",
programmingLanguage: ["computerProgram"]
},
M1: {
seriesNumber:["book"],
billNumber:["bill"],
system:["computerProgram"],
documentNumber:["hearing"],
applicationNumber:["patent"],
publicLawNumber:["statute"],
episodeNumber:["podcast", "radioBroadcast", "tvBroadcast"]
},
M3: {
manuscriptType:["manuscript"],
mapType:["map"],
reportType:["report"],
thesisType:["thesis"],
websiteType:["blogPost", "webpage"],
postType:["forumPost"],
letterType:["letter"],
interviewMedium:["interview"],
presentationType:["presentation"],
artworkMedium:["artwork"],
audioFileType:["podcast"]
},
NV: {
"__default": "numberOfVolumes",
"__exclude": ["bookSection"] //IS
},
OP: {
history:["hearing", "statute", "bill", "case"],
priorityNumbers:["patent"]
},
PB: {
"__default":"publisher",
label:["audioRecording"],
court:["case"],
distributor:["film"],
assignee:["patent"],
institution:["report"],
university:["thesis"],
company:["computerProgram"],
studio:["videoRecording"],
network:["radioBroadcast", "tvBroadcast"]
},
PY: { //duplicate of DA, but this will only output year
"__default":"date",
dateEnacted:["statute"],
dateDecided:["case"],
issueDate:["patent"]
},
SE: {
"__default": "section", //though this can refer to pages, start page, etc. for some types. Zotero does not support any of those combinations, however.
"__exclude": ["case"]
},
SN: {
"__default":"ISBN",
ISSN:["journalArticle", "magazineArticle", "newspaperArticle"],
patentNumber:["patent"],
reportNumber:["report"],
},
SP: {
"__default":"pages", //needs extra processing
codePages:["bill"], //bill
numPages:["book", "thesis", "manuscript"], //manuscript not really in spec
firstPage:["case"],
runningTime:["film"]
},
SV: {
seriesNumber: ["bookSection"],
docketNumber: ["case"] //not in spec. EndNote exports this way
},
VL: {
"__default":"volume",
codeNumber:["statute"],
codeVolume:["bill"],
reporterVolume:["case"],
"__exclude":["patent", "webpage"]
}
};
//non-standard or degenerate field maps
//used ONLY for importing and only if these fields are not specified above (e.g. M3)
//these are not exported the same way
var degenerateImportFieldMap = {
A1: fieldMap["AU"],
AD: {
"__default": "unsupported/Author Address",
"unsupported/Inventor Address": ["patent"]
},
AV: "archiveLocation", //REFMAN
BT: {
title: ["book", "manuscript"],
bookTitle: ["bookSection"],
"__default": "backupPublicationTitle" //we do more filtering on this later
},
CA: "unsupported/Caption",
CR: "rights",
CT: "title",
ED: "creators/editor",
EP: "pages",
H1: "unsupported/Library Catalog", //Citavi specific (possibly multiple occurences)
H2: "unsupported/Call Number", //Citavi specific (possibly multiple occurences)
ID: "__ignore",
JA: "journalAbbreviation",
JF: "publicationTitle",
JO: {
"__default": "journalAbbreviation",
conferenceName: ["conferencePaper"]
},
LB: "unsupported/Label",
M1: {
"__default":"extra",
issue: ["journalArticle"], //EndNote hack
numberOfVolumes: ["bookSection"], //EndNote exports here instead of IS
accessDate: ["webpage"] //this is access date when coming from EndNote
},
M2: "extra", //not in spec
M3: "DOI",
N2: "abstractNote",
NV: "numberOfVolumes",
OP: {
"__default": "unsupported/Original Publication",
"unsupported/Content": ["blogPost", "computerProgram", "film", "presentation", "report", "videoRecording", "webpage"]
},
RI: {
"__default":"unsupported/Reviewed Item",
"unsupported/Article Number": ["statute"]
},
RN: "notes",
SE: {
"unsupported/File Date": ["case"]
},
T1: fieldMap["TI"],
T2: "backupPublicationTitle", //most item types should be covered above
T3: {
series: ["book"]
},
TA: "unsupported/Translated Author",
TT: "unsupported/Translated Title",
VL: {
"unsupported/Patent Version Number":['patent'],
accessDate: ["webpage"] //technically access year according to EndNote
},
Y1: fieldMap["DA"] // Old RIS spec
};
/**
* @class Generic tag mapping with caching
*
* @param {Tag <-> zotero field map []} mapList An array of field map lists as
* described above. Lists are matched in order they are supplied. If a tag is
* not present in the list, the next list is checked. If the RIS tag is
* present, but an item type does not match (no __default) or is explicit
* excluded from matching (__exclude), the next list is checked.
*/
var TagMapper = function(mapList) {
this.cache = {};
this.reverseCache = {};
this.mapList = mapList;
};
/**
* Given an item type and a RIS tag, return Zotero field data should be mapped to.
* Mappings are cached.
*
* @param {String} itemType Zotero item type
* @param {String} tag RIS tag
* @return {String} Zotero field
*/
TagMapper.prototype.getField = function(itemType, tag) {
if(!this.cache[itemType]) this.cache[itemType] = {};
//retrieve from cache if available
//it can be false if previous search did not find a mapping
if(this.cache[itemType][tag] !== undefined) {
return this.cache[itemType][tag];
}
var field = false;
for(var i=0, n=this.mapList.length; i<n; i++) {
var map = this.mapList[i];
if(typeof(map[tag]) == 'object') {
var def, exclude = false;
for(var f in map[tag]) {
//__ignore is not handled here. It's returned as a Zotero field so it
//can be explicitly excluded from the note attachment
if(f == "__default") {
//store default mapping in case we can't find anything explicit
def = map[tag][f];
continue;
}
if(f == "__exclude") {
if(map[tag][f].indexOf(itemType) != -1) {
exclude = true; //don't break. Let explicit mapping override this
}
continue;
}
if(map[tag][f].indexOf(itemType) != -1) {
field = f;
break;
}
}
//assign default value if not excluded
if(!field && def && !exclude) field = def;
} else if(typeof(map[tag]) == 'string') {
field = map[tag];
}
if(field) break; //no need to go on
}
this.cache[itemType][tag] = field;
return field;
};
/**
* Given a Zotero item type and field, return a RIS tag.
* Mappings are cached.
* Not used for export, but for ProCite tag re-mapping
*
* @param {String} itemType Zotero item type
* @param {String} zField Zotero field
* @return {String} RIS tag
*/
TagMapper.prototype.reverseLookup = function(itemType, zField) {
if(!this.reverseCache[itemType]) this.reverseCache[itemType] = {};
if(this.reverseCache[itemType][zField] !== undefined) {
return this.reverseCache[itemType][zField];
}
for(var i=0, n=this.mapList.length; i<n; i++) {
var risTag;
for(risTag in this.mapList[i]) {
var typeMap = this.mapList[i][risTag];
if(typeMap == zField) {
// item type indepndent
this.reverseCache[itemType][zField] = risTag;
return risTag;
} else if(typeof(typeMap) == 'object') {
if (typeMap[zField] && typeMap[zField].indexOf(itemType) !== -1) {
//explicitly mapped
this.reverseCache[itemType][zField] = risTag;
return risTag;
}
if(!(typeMap.__exclude && typeMap.__exclude.indexOf(itemType) !== -1)
&& typeMap.__default == zField
) {
// may be mapped via default, but make sure this item type is not
// explicitly mapped somewhere else
var preventDefault = false;
for(var field in typeMap) {
if(typeMap[field].indexOf(itemType) != -1) {
// mapped to something else
preventDefault = true;
break;
}
}
if(!preventDefault) {
this.reverseCache[itemType][zField] = risTag;
return risTag;
}
}
}
}
}
this.reverseCache[itemType][zField] = false;
return false;
};
/********************
* Import Functions *
********************/
//import field mapping
var importFields;
//do not store unknwon fields in notes
//configurable via RIS.import.ignoreUnknown hidden preference
var ignoreUnknown = false;
/**
* @singleton Provides facilities to read one RIS entry at a time
*/
var RISReader = new function() {
//if we read a tag-value pair from the next entry, we need to keep it for later
var _tagValueBuffer = [];
/**
* public
* Returns the next RIS entry
* Note: we do allow entries to be missing a TY tag
*
* @return Array of tag-value pairs in order of appearance.
* Includes an additional property "tags", which is a list of RIS tags.
* The values of the list are arrays, which contain references to the
* tag-value pairs stored in the returned array.
*/
this.nextEntry = function() {
var tagValue,
entry = []; //maintain tag order
entry.tags = {}; //tag list for convenience
while(tagValue = (_tagValueBuffer.length && _tagValueBuffer.pop()) || _getTagValue()) {
if(tagValue.tag == 'TY' && entry.length) {
//we hit a new entry. ER was omitted, but we'll forgive
_tagValueBuffer.push(tagValue);
return entry;
}
if(tagValue.tag == 'ER') {
if(!entry.length) continue; //weird, but keep going and ignore ER outside of entry
return entry;
}
entry.push(tagValue);
//also add to the "tags" list for convenient access
if(!entry.tags[tagValue.tag]) entry.tags[tagValue.tag] = [];
entry.tags[tagValue.tag].push(tagValue);
}
if(entry.length) return entry;
};
var RIS_format = /^([A-Z][A-Z0-9]) {1,2}-(?: (.*))?$/, //allow empty entries
//list of tags for which we preserve newlines
preserveNewLines = ['KW', 'L1', 'L2', 'L3'], //these could use newline as separator
//keep track of maximum line length so we can make a better call on whether
//something should be on a new line or not
_maxLineLength = 0;
/**
* private
* Get the next RIS tag-value pair
*
* @return {
* raw: the line (or multiple lines) that were read in for this tag value pair,
* tag: RIS tag,
* value: value, which may have newlines stripped
* }
*/
function _getTagValue() {
var line, tagValue, temp, lastLineLength = 0;
while((line = _nextLine()) !== false) { //could be reading empty lines
temp = line.match(RIS_format);
if(!temp && !tagValue) {
//doesn't match RIS format and we're not processing a tag-value pair,
//so this is not a multi-line tag-value pair
if(line.trim()) {
Z.debug("RIS: Dropping line outside of RIS record: " + line);
}
continue;
}
if(line.length > _maxLineLength) _maxLineLength = line.length;
if(temp && tagValue) {
//if we are already processing a tag-value pair, then this is the next pair
//store this line for later and return
_lineBuffer.push(line);
return tagValue;
}
if(temp) {
//new tag-value pair
tagValue = {
tag: temp[1],
value: temp[2],
raw: line
};
if(tagValue.value === undefined) tagValue.value = '';
} else {
//tagValue && !temp
//multi-line RIS tag-value pair
var newLineAdded = false;
var cleanLine = line.trim();
//new lines would probably only be meaningful in notes and abstracts
if((['AB', 'N1', 'N2']).indexOf(tagValue.tag) !== -1
//if all lines are not trimmed to ~80 characters or previous line was
// short, this would probably be on a new line. Might want to consider
// looking for periods and capital letters to make a better call.
// Empty lines imply a new line
&& (_maxLineLength > 85
|| (lastLineLength !== undefined && lastLineLength < 65)
|| cleanLine.length == 0)
) {
cleanLine = "\n" + cleanLine;
newLineAdded = true;
}
//don't remove new lines from keywords or attachments
if(!newLineAdded && preserveNewLines.indexOf(tagValue.tag) != -1) {
cleanLine = "\n" + cleanLine;
newLineAdded = true;
}
//check if we need to add a space before concatenating
if(!newLineAdded && tagValue.value.charAt(tagValue.value.length-1) != ' ') {
cleanLine = ' ' + cleanLine;
}
tagValue.raw += "\n" + line;
tagValue.value += cleanLine;
}
lastLineLength = line.length;
}
if(tagValue) return tagValue;
}
var _lineBuffer = [];
/**
* private
* Gets the next line in the buffer or file
*
* @return (String)
*/
function _nextLine() {
// Don't use shortcuts like _lineBuffer.pop() || Zotero.read(),
// because we may have an empty line, which could be meaningful
if(_lineBuffer.length) return _lineBuffer.pop();
var line = Zotero.read();
if (line && (line.indexOf('\u2028') != -1 || line.indexOf('\u2029') != -1)) {
// Apparently some services think that it's cool to break up single
// lines in RIS into shorter lines using Unicode "LINE SEPARATOR"
// character. Well, that sucks for us, because . (dot) in regexp does
// not match this character. We also probably don't want it in the
// metadata, so clean it up here.
// e.g. http://informahealthcare.com/doi/full/10.3109/07434618.2014.906498
// (an Atypon system)
// Also include paragraph separator, though no live example available.
line = line.replace(/\s?[\u2028\u2029]|[\u2028\u2029]\s?/g, ' ');
}
return line;
}
};
/**
* Generic methods for cleaning RIS tags
*/
var TagCleaner = {
/**
* public
* Changes the RIS tag for an indicated tag-value pair. If more than one tag
* is specified, additional pairs are added.
*
* @param (RISReader entry) entry
* @param (Integer) at Index in entry of the tag-value pair to alter
* @param (String[]) toTags Array of tags to change to
*/
changeTag: function(entry, at, toTags) {
var source = entry[at], byTag = entry.tags[source.tag];
//clean up "tags" list
byTag.splice(byTag.indexOf(source),1);
if(!byTag.length) delete entry.tags[source.tag];
if(!toTags || !toTags.length) {
//then we just remove
entry.splice(at,1);
} else {
source.tag = toTags[0]; //re-use the same pair for first tag
if(!entry.tags[toTags[0]]) entry.tags[toTags[0]] = [];
entry.tags[toTags[0]].push(source);
//if we're changing to more than one tag, we need to add extras
for(var i=1, n=toTags.length; i<n; i++) {
var newSource = ZU.deepCopy(source);
newSource.tag = toTags[i];
entry.splice(at+i, 0, newSource);
if(!entry.tags[toTags[i]]) entry.tags[toTags[i]] = [];
entry.tags[toTags[i]].push(newSource);
}
}
}
};
/**
* @singleton Provides facilities to remap ProCite note-based data tagging to
* proper RIS format
* Note that after processing, the order of tag-value pairs in the "tags" list
* may be out of order
*/
var ProCiteCleaner = new function() {
this.proCiteMode = false; //are we sure we're processing a ProCite file?
//ProCite -> Zotero field map
this.proCiteMap = {
'Author Role': { //special case
'actor': 'cast-member',
'author': 'author',
'cartographer': 'cartographer',
'composer': 'composer',
'composed': 'composer',
'director': 'director',
'directed': 'director',
'performer': 'performer',
'performed': 'performer',
'producer': 'producer',
'produced': 'producer',
'editor': 'editor',
'ed': 'editor',
'edited': 'editor',
'editor-in-chief': 'editor',
'compiler': 'editor',
'compiled': 'editor',
'collected': 'editor',
'assembled': 'editor',
'presenter': 'presenter',
'presented': 'presenter',
'translator': 'translator',
'translated':'translator',
'introduction': 'contributor'
//conductor
//illustrator
//librettist
},
'Call Number': 'callNumber',
'Edition': 'edition',
'ISBN': 'ISBN',
'Language': 'language',
'Publisher Name': 'publisher',
'Series Title': 'series',
'Proceedings Title': 'proceedingsTitle',
'Page(s)': 'pages',
'Volume ID': 'volume',
'Issue ID': 'issue',
'Issue Identification': 'issue',
'Series Volume ID': 'seriesNumber',
'Scale': 'scale',
'Place of Publication': 'place',
'Histroy': 'history', // yes, it's misspelled in their export filter
'Size': 'artworkSize'
};
var tagValueSplit = /([A-Za-z,\s]+)\s*:\s*([\s\S]*)/; //ProCite version
/**
* public
* Converts ProCite "tags" to RIS tags
*
* @param (RISReader entry) entry Entry to be cleaned up in-place
* @param (Zotero.Item) item Indicates item type for proper mapping
*/
this.cleanTags = function(entry, item) {
// We _must_ change some tags before mapping from notes, otherwise
// there will be ambiguity
var ty;
if(this.proCiteMode) {
ty = entry.tags.TY && entry.tags.TY[0].value;
if((ty == 'CHAP' || ty == 'BOOK') && entry.tags.VL) {
// Edition in ET, not VL
_changeAllTags(entry, 'VL', 'ET');
}
}
var notes = entry.tags.N1, extentOfWork, packagingMethod;
//go through all the notes
for(var i=0; notes && notes.length && i<entry.length; i++) {
var m;
if(entry[i].tag !== 'N1'
|| !(m = entry[i].value.trim().match(tagValueSplit)) ) {
continue;
}
switch(m[1]) {
case 'Author, Subsidiary':
case 'Author, Monographic':
//seems to always come before "Author Role"
//we guess what RIS tag to assign,
//but this gets fixed on next iteration anyway
var risTag = entry.tags.A1 ? (entry.tags.A2 ? 'A3' : 'A2') : 'A1';
var authors = m[2].split(/;\s*/); //multiple authors on the same line
this._changeTag(entry, i, [risTag]);
//use current tag-value pair for first author
//authors are in firstName lastName format, we need to fix it
entry[i].value = _fixAuthor(authors[0]);
//subsequent authors need to have their own tag-value pairs
for(var j=1; j<authors.length; j++) {
var newEntry = ZU.deepCopy(entry[i]);
newEntry.value = authors[j];
entry.splice(i+1,0,newEntry); //insert into tag-value array
entry.tags[risTag].push(newEntry); //and add to tags
}
i += authors.length - 1; //skip past the new entries we just added
break;
case 'Artist Role':
case 'Series Editor Role':
case 'Editor/Compiler Role':
case 'Cartographer Role':
case 'Composer Role':
case 'Producer Role':
case 'Director Role':
case 'Performer Role':
case 'Author Role':
var authorRoles = _normalizeAuthorRole(m[2]);
var risTags = [], fail = false;
//find a RIS tag for each author role
for(var j=0, k=authorRoles.length; j<k; j++) {
var role = this.proCiteMap['Author Role'][authorRoles[j]];
if(!role) {
Z.debug('RIS: Unknown ProCite author role: ' + authorRoles[j]);
continue;
}
role = 'creators/' + role;
var risTag = importFields.reverseLookup(item.itemType, role);
if(!risTag) {
Z.debug('RIS: Cannot map ProCite author role to RIS tag: ' + role + ' for ' + item.itemType);
Z.debug('RIS: Will not attempt a partial match: ' + m[0]);
fail = true;
break;
}
if(risTags.indexOf(risTag) === -1) risTags.push(risTag); //don't add same role
}
if(fail || !risTags.length) continue;
Z.debug('RIS: ' + m[0]);
Z.debug('RIS: Mapping preceeding authors to ' + risTags.join(', '));
var added;
if(added = this._remapPreceedingTags(entry, i, ['A1','A2','A3'], risTags)) {
this._changeTag(entry, i); //remove ProCite note
i--;
if(added !== true) {
i += added;
}
}
break;
case 'Record ID':
case 'Record Number':
this._changeTag(entry, i, ['ID']);
entry[i].value = m[2];
break;
case 'Notes':
entry[i].value = m[2];
break;
case 'Connective Phrase':
if(m[2].trim().toLowerCase() == 'in') {
//this is somewhat meaningless, remove it
this._changeTag(entry, i);
i--;
}
break;
case 'Extent of Work':
extentOfWork = entry[i]; //processed later
break;
case 'Packaging Method':
packagingMethod = entry[i]; //processed later
break;
default:
if(this.proCiteMap[m[1]]) {
var risTag = importFields.reverseLookup(item.itemType, this.proCiteMap[m[1]]);
if(!risTag) {
Z.debug('RIS: Cannot map ProCite note to RIS tag: ' + this.proCiteMap[m[1]] + ' for ' + item.itemType);
continue;
}
this._changeTag(entry, i, [risTag]);
entry[i].value = m[2];
}
}
}
if(extentOfWork) {
var extent = extentOfWork.value.match(tagValueSplit)[2],
m = extent.match(/^(\d+)\s*(pages?|p(?:p|gs?)?|vols?|volumes?)\.?$/i), //e.g. 2 vols.
units, deletePackagingMethod = false;
if(m) {
//we have both extent and units in the same field
//packagingMethod will be useless
units = m[2].charAt(0).toLowerCase() == 'p' ? 'numPages' : 'numberOfVolumes';
extent = m[1];
} else if(packagingMethod && /^\s*\d+\s*$/.test(extent) //numeric extent
&& (m = packagingMethod.value.match(/:\s*(pages?|p(?:p|gs?)?|vols?|volumes?)\.?\s*$/i))
) {
units = m[1].charAt(0).toLowerCase() == 'p' ? 'numPages' : 'numberOfVolumes';
extent = extent.trim();
deletePackagingMethod = true; //we can delete it since we used it
}
if(units) {
risTag = importFields.reverseLookup(item.itemType, units);
if(risTag) {
extentOfWork.value = extent;
this._changeTag(entry, entry.indexOf(extentOfWork), [risTag]);
if(deletePackagingMethod) {
this._changeTag(entry, entry.indexOf(packagingMethod));