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 pathMODS.js
1914 lines (1751 loc) · 108 KB
/
MODS.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": "0e2235e7-babf-413c-9acf-f27cce5f059c",
"label": "MODS",
"creator": "Simon Kornblith and Richard Karnesky",
"target": "xml",
"minVersion": "2.1.9",
"maxVersion": "",
"priority": 50,
"configOptions": {
"dataMode": "xml/dom"
},
"displayOptions": {
"exportNotes": true
},
"inRepository": true,
"translatorType": 3,
"browserSupport": "gcsv",
"lastUpdated": "2015-02-11 01:24:19"
}
var fromMarcGenre = {
// "abstract or summary":XXX,
// "abstract":XXX,
// "summary":XXX,
"art reproduction":"artwork",
"article":"journalArticle",
"autobiography":"book",
"bibliography":"bookSection",
"biography":"book",
"book":"book",
// "calendar":XXX,
// "catalog":XXX,
"chart":"artwork",
"comic or graphic novel":"book",
"comic":"book",
"graphic novel":"book",
"comic strip":"artwork",
"conference publication":"conferencePaper",
// "database":XXX,
"dictionary":"dictionaryEntry",
"diorama":"artwork",
// "directory":XXX,
"drama":"book",
"encyclopedia":"encyclopediaArticle",
// "essay":XXX,
"festschrift":"book",
"fiction":"book",
// "filmography":XXX,
"filmstrip":"videoRecording",
// "findingaid":XXX,
// "flash card":XXX,
"folktale":"book",
// "font":XXX,
// "game":XXX,
"government publication":"book",
"graphic":"artwork",
"globe":"map",
"handbook":"book",
"history":"book",
"hymnal":"book",
"humor,satire":"book",
"humor":"book",
"satire":"book",
// "index":XXX,
// "instruction":XXX,
// "interview":XXX,
// "issue":XXX,
"journal":"journalArticle",
"kit":"artwork",
// "language instruction":XXX,
"law report or digest":"journalArticle",
"law report":"journalArticle",
"digest":"journalArticle",
"law digest":"journalArticle",
"legal article":"journalArticle",
"legal case and case notes":"case",
"legal case":"case",
"case notes":"case",
"legislation":"statute",
"loose-leaf":"manuscript",
"map":"map",
"memoir":"book",
"microscope slide":"artwork",
"model":"artwork",
// "multivolume monograph":XXX,
"novel":"book",
// "numeric data":XXX,
// "offprint":XXX,
"online system or service":"webpage",
"online system":"webpage",
"service":"webpage",
"online service":"webpage",
"patent":"patent",
"periodical":"journalArticle",
"picture":"artwork",
// "poetry":XXX,
// "programmed text":XXX,
"realia":"artwork",
// "rehearsal":XXX,
// "remote sensing image":XXX,
// "reporting":XXX,
// "review":XXX,
"script":"book",
// "series":XXX,
// "short story":XXX,
"slide":"artwork",
"sound":"audioRecording",
"speech":"audioRecording",
"standard or specification":"report",
"standard":"report",
// "specification":XXX,
// "statistics":XXX,
// "survey of literature":XXX,
"technical report":"report",
"newspaper":"newspaperArticle",
"theses":"thesis",
"thesis":"thesis",
// "toy":XXX,
"transparency":"artwork",
// "treaty":XXX,
"videorecording":"videoRecording",
"letter":"letter",
"motion picture":"film",
"art original":"artwork",
"web site":"webpage",
"yearbook":"book"
};
var toMarcGenre = {
"artwork":"art original",
"audioRecording":"sound",
"bill":"legislation",
"blogPost":"web site",
"book":"book",
"bookSection":"book",
"case":"legal case and case notes",
//"computerProgram":XXX,
"conferencePaper":"conference publication",
"dictionaryEntry":"dictionary",
//"document":XXX,
"email":"letter",
"encyclopediaArticle":"encyclopedia",
"film":"motion picture",
"forumPost":"web site",
//"hearing":XXX,
"instantMessage":"letter",
"interview":"interview",
"journalArticle":"journal",
"letter":"letter",
"magazineArticle":"periodical",
//"manuscript":XXX,
"map":"map",
"newspaperArticle":"newspaper",
"patent":"patent",
"podcast":"speech",
//"presentation":XXX,
"radioBroadcast":"sound",
"report":"technical report",
"statute":"legislation",
"thesis":"thesis",
//"tvBroadcast":XXX,
"videoRecording":"videorecording",
"webpage":"web site"
};
var dctGenres = {
//"collection":XXX,
//"dataset":XXX,
//"event":XXX,
"image":"artwork",
"interactiveresource":"webpage",
//"model":XXX,
"movingimage":"videoRecording",
//"physical object":XXX,
//"place":XXX,
//"resource":XXX,
//"service":XXX,
"software":"computerProgram",
"sound":"audioRecording",
"stillimage":"artwork"
//"text":XXX
};
var fromTypeOfResource = {
//"text":XXX,
"cartographic":"map",
//"notated music":XXX,
"sound recording-musical":"audioRecording",
"sound recording-nonmusical":"audioRecording",
"sound recording":"audioRecording",
"still image":"artwork",
"moving image":"videoRecording",
//"three dimensional object":XXX,
"software, multimedia":"computerProgram"
};
var toTypeOfResource = {
"artwork":"still image",
"audioRecording":"sound recording",
"bill":"text",
"blogPost":"software, multimedia",
"book":"text",
"bookSection":"text",
"case":"text",
"computerProgram":"software, multimedia",
"conferencePaper":"text",
"dictionaryEntry":"text",
"document":"text",
"email":"text",
"encyclopediaArticle":"text",
"film":"moving image",
"forumPost":"text",
"hearing":"text",
"instantMessage":"text",
"interview":"text",
"journalArticle":"text",
"letter":"text",
"magazineArticle":"text",
"manuscript":"text",
"map":"cartographic",
"newspaperArticle":"text",
"patent":"text",
"podcast":"sound recording-nonmusical",
"presentation":"mixed material",
"radioBroadcast":"sound recording-nonmusical",
"report":"text",
"statute":"text",
"thesis":"text",
"tvBroadcast":"moving image",
"videoRecording":"moving image",
"webpage":"software, multimedia"
};
var modsTypeRegex = {
// 'artwork':
// 'audioRecording': /\bmusic/i,
// 'bill':
'blogPost': /\bblog/i,
// 'book':
// 'bookSection':
// 'case':
// 'computerProgram':
// 'conferencePaper':
// 'dictionaryEntry':
// 'email':
// 'encyclopediaArticle':
// 'film':
// 'forumPost':
// 'hearing':
// 'instantMessage':
// 'interview':
'journalArticle': /journal\s*article/i,
// 'letter':
'magazineArticle': /magazine\s*article/i,
// 'manuscript':
// 'map':
'newspaperArticle': /newspaper\*article/i
// 'patent':
// 'podcast':
// 'presentation':
// 'radioBroadcast':
// 'report':
// 'statute':
// 'thesis':
// 'tvBroadcast':
// 'videoRecording':
// 'webpage':
};
var modsInternetMediaTypes = {
//a ton of types listed at http://www.iana.org/assignments/media-types/index.html
'text/html': 'webpage'
};
var marcRelators = {
"aut":"author",
"edt":"editor",
"ctb":"contributor",
"pbd":"seriesEditor",
"trl":"translator"
};
// Item types that are part of a larger work
var partialItemTypes = ["blogPost", "bookSection", "conferencePaper", "dictionaryEntry",
"encyclopediaArticle", "forumPost", "journalArticle", "magazineArticle",
"newspaperArticle", "webpage"];
// Namespace array for using ZU.xpath
var ns = "http://www.loc.gov/mods/v3",
xns = {"m":ns};
function detectImport() {
var doc = Zotero.getXML().documentElement;
if (!doc) {
return false;
}
return doc.namespaceURI === "http://www.loc.gov/mods/v3" && (doc.tagName === "modsCollection" || doc.tagName === "mods");
}
/**
* If property is defined, this function adds an appropriate XML element as a child of
* parentElement.
* @param {Element} parentElement The parent of the new element to be created.
* @param {String} elementName The name of the new element to be created.
* @param {Any} property The property to inspect. If this property is defined and not
* null, false, or empty, a new element is created whose textContent is its value.
* @param {Object} [attributes] If defined, this object defines attributes to be added
* to the new element.
*/
function mapProperty(parentElement, elementName, property, attributes) {
if(!property && property !== 0) return null;
var doc = parentElement.ownerDocument,
newElement = doc.createElementNS(ns, elementName);
if(attributes) {
for(var i in attributes) {
newElement.setAttribute(i, attributes[i]);
}
}
newElement.appendChild(doc.createTextNode(property));
parentElement.appendChild(newElement);
return newElement;
}
function doExport() {
Zotero.setCharacterSet("utf-8");
var parser = new DOMParser();
var doc = parser.parseFromString('<modsCollection xmlns="http://www.loc.gov/mods/v3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-2.xsd" />', 'application/xml');
var item;
while(item = Zotero.nextItem()) {
// Don't export notes or standalone attachments
if(item.itemType === "note" || item.itemType === "attachment") continue;
var mods = doc.createElementNS(ns, "mods"),
isPartialItem = partialItemTypes.indexOf(item.itemType) !== -1,
recordInfo = doc.createElementNS(ns, "recordInfo"),
host = doc.createElementNS(ns, "relatedItem"),
series = doc.createElementNS(ns, "relatedItem"),
topOrHost = (isPartialItem ? host : mods);
/** CORE FIELDS **/
// XML tag titleInfo; object field title
if(item.title) {
var titleInfo = doc.createElementNS(ns, "titleInfo");
mapProperty(titleInfo, "title", item.title);
mods.appendChild(titleInfo);
}
if(item.shortTitle) {
var titleInfo = doc.createElementNS(ns, "titleInfo");
titleInfo.setAttribute("type", "abbreviated");
mapProperty(titleInfo, "title", item.shortTitle);
mods.appendChild(titleInfo);
}
// XML tag typeOfResource/genre; object field type
mapProperty(mods, "typeOfResource", toTypeOfResource[item.itemType]);
mapProperty(mods, "genre", item.itemType, {"authority":"local"});
mapProperty(topOrHost, "genre", toMarcGenre[item.itemType], {"authority":"marcgt"});
// XML tag genre; object field thesisType, type
if(item.thesisType) {
mapProperty(mods, "genre", item.thesisType);
} else if(item.type) {
mapProperty(mods, "genre", item.type);
}
// XML tag name; object field creators
for(var j=0; j<item.creators.length; j++) {
var creator = item.creators[j],
roleTerm = "";
if(creator.creatorType == "author") {
roleTerm = "aut";
} else if(creator.creatorType == "editor") {
roleTerm = "edt";
} else if(creator.creatorType == "translator") {
roleTerm = "trl";
} else if(creator.creatorType == "seriesEditor") {
roleTerm = "pbd";
} else {
roleTerm = "ctb";
}
var name = doc.createElementNS(ns, "name"), namePart;
if(creator.fieldMode == 1) {
name.setAttribute("type", "corporate");
mapProperty(name, "namePart", creator.lastName);
} else {
name.setAttribute("type", "personal");
mapProperty(name, "namePart", creator.lastName, {"type":"family"});
mapProperty(name, "namePart", creator.firstName, {"type":"given"});
}
var role = doc.createElementNS(ns, "role");
mapProperty(role, "roleTerm", roleTerm,
{"type":"code", "authority":"marcrelator"});
name.appendChild(role);
var creatorParent = creator.creatorType === "seriesEditor" ? series
: creator.creatorType === "editor" ? topOrHost
: mods;
creatorParent.appendChild(name);
}
// XML tag recordInfo.recordOrigin; used to store our generator note
//mods.recordInfo.recordOrigin = "Zotero for Firefox "+Zotero.Utilities.getVersion();
/** FIELDS ON NEARLY EVERYTHING BUT NOT A PART OF THE CORE **/
// XML tag recordInfo.recordContentSource; object field source
mapProperty(recordInfo, "recordContentSource", item.libraryCatalog);
// XML tag accessCondition; object field rights
mapProperty(mods, "accessCondition", item.rights);
/** SUPPLEMENTAL FIELDS **/
var part = doc.createElementNS(ns, "part");
// XML tag detail; object field volume
const details = ["volume", "issue", "section"];
for(var i=0; i<details.length; i++) {
if(item[details[i]] || item[details[i]] === 0) {
var detail = doc.createElementNS(ns, "detail"),
number = doc.createElementNS(ns, "number");
detail.setAttribute("type", details[i]);
number.appendChild(doc.createTextNode(item[details[i]]));
detail.appendChild(number);
part.appendChild(detail);
}
}
// XML tag detail; object field pages
if(item.pages) {
var range = Zotero.Utilities.getPageRange(item.pages),
extent = doc.createElementNS(ns, "extent");
extent.setAttribute("unit", "pages");
mapProperty(extent, "start", range[0]);
mapProperty(extent, "end", range[1]);
part.appendChild(extent);
}
// Assign part if something was assigned
if(part.hasChildNodes()) {
// For a journal article, bookSection, etc., the part is the host
topOrHost.appendChild(part);
}
var originInfo = doc.createElementNS(ns, "originInfo")
// XML tag originInfo; object fields edition, place, publisher, year, date
mapProperty(originInfo, "edition", item.edition);
if(item.place) {
var place = doc.createElementNS(ns, "place"),
placeTerm = doc.createElementNS(ns, "placeTerm");
placeTerm.setAttribute("type", "text");
placeTerm.appendChild(doc.createTextNode(item.place));
place.appendChild(placeTerm);
originInfo.appendChild(place);
}
if(item.publisher) {
mapProperty(originInfo, "publisher", item.publisher);
} else if(item.distributor) {
mapProperty(originInfo, "distributor", item.publisher);
}
if(item.date) {
if(["book", "bookSection"].indexOf(item.itemType) !== -1) {
// Assume year is copyright date
var dateType = "copyrightDate";
} else if(["journalArticle", "magazineArticle", "newspaperArticle"].indexOf(item.itemType) !== -1) {
// Assume date is date issued
var dateType = "dateIssued";
} else {
// Assume date is date created
var dateType = "dateCreated";
}
mapProperty(originInfo, dateType, item.date);
}
if(item.numPages) {
var physicalDescription = doc.createElementNS(ns, "physicalDescription");
mapProperty(physicalDescription, "extent", item.numPages+" p.");
mods.appendChild(physicalDescription);
}
if(isPartialItem) {
// eXist Solutions points out that these types are more often
// continuing than not & will use this internally.
// Perhaps comment this out in the main distribution, though.
if(["journalArticle", "magazineArticle", "newspaperArticle"].indexOf(item.itemType) !== -1) {
mapProperty(originInfo, "issuance", "continuing");
}
else if (["bookSection", "conferencePaper", "dictionaryEntry",
"encyclopediaArticle"].indexOf(item.itemType) !== -1) {
mapProperty(originInfo, "issuance", "monographic");
}
} else {
// eXist Solutions points out that most types are more often
// monographic than not & will use this internally.
// Perhaps comment this out in the main distribution, though.
mapProperty(originInfo, "issuance", "monographic");
}
if(originInfo.hasChildNodes()) {
// For a journal article, bookSection, etc., the part is the host
topOrHost.appendChild(originInfo);
}
// XML tag identifier; object fields ISBN, ISSN
mapProperty(topOrHost, "identifier", item.ISBN, {"type":"isbn"});
mapProperty(topOrHost, "identifier", item.ISSN, {"type":"issn"});
mapProperty(mods, "identifier", item.DOI, {"type":"doi"});
// XML tag relatedItem.name; object field conferenceName
if(item.conferenceName) {
var name = doc.createElementNS(ns, "name");
name.setAttribute("type", "conference");
mapProperty(name, "namePart", item.conferenceName);
}
// XML tag relatedItem.titleInfo; object field publication
if(item.publicationTitle) {
var titleInfo = doc.createElementNS(ns, "titleInfo");
mapProperty(titleInfo, "title", item.publicationTitle);
host.appendChild(titleInfo);
}
// XML tag relatedItem.titleInfo; object field journalAbbreviation
if(item.journalAbbreviation) {
var titleInfo = doc.createElementNS(ns, "titleInfo");
titleInfo.setAttribute("type", "abbreviated");
mapProperty(titleInfo, "title", item.journalAbbreviation);
host.appendChild(titleInfo);
}
// XML tag classification; object field callNumber
mapProperty(topOrHost, "classification", item.callNumber);
// XML tag location.url; object field url
if(item.url) {
var location = doc.createElementNS(ns, "location");
var url = mapProperty(location, "url", item.url, {"usage":"primary display"});
if(url && item.accessDate) url.setAttribute("dateLastAccessed", item.accessDate);
mods.appendChild(location);
}
// XML tag location.physicalLocation; object field archiveLocation
if(item.archiveLocation) {
var location = doc.createElementNS(ns, "location");
mapProperty(location, "physicalLocation", item.archiveLocation);
topOrHost.appendChild(location);
}
// XML tag abstract; object field abstractNote
mapProperty(mods, "abstract", item.abstractNote);
// XML tag series/titleInfo; object field series, seriesTitle, seriesText, seriesNumber
var titleInfo = doc.createElementNS(ns, "titleInfo");
mapProperty(titleInfo, "title", item.series);
mapProperty(titleInfo, "title", item.seriesTitle);
mapProperty(titleInfo, "subTitle", item.seriesText);
if(titleInfo.hasChildNodes()) series.appendChild(titleInfo);
if(item.seriesNumber) {
var seriesPart = doc.createElementNS(ns, "part"),
detail = doc.createElementNS(ns, "detail"),
number = doc.createElementNS(ns, "number");
detail.setAttribute("type", "volume");
number.appendChild(doc.createTextNode(item.seriesNumber));
detail.appendChild(number);
seriesPart.appendChild(detail);
series.appendChild(seriesPart);
}
/** NOTES **/
if(Zotero.getOption("exportNotes")) {
for(var j=0; j<item.notes.length; j++) {
mapProperty(mods, "note", item.notes[j].note);
}
}
/** TAGS **/
for(var j=0; j<item.tags.length; j++) {
var subject = doc.createElementNS(ns, "subject"),
topic = doc.createElementNS(ns, "topic");
topic.appendChild(doc.createTextNode(item.tags[j].tag));
subject.appendChild(topic);
mods.appendChild(subject);
}
/** LANGUAGE **/
if(item.language) {
var language = doc.createElementNS(ns, "language");
mapProperty(language, "languageTerm", item.language, {"type":"text"});
mods.appendChild(language);
}
/** EXTRA->NOTE **/
mapProperty(mods, "note", item.extra);
if(recordInfo.hasChildNodes()) mods.appendChild(recordInfo);
if(host.hasChildNodes()) {
host.setAttribute("type", "host");
mods.appendChild(host);
}
if(series.hasChildNodes()) {
series.setAttribute("type", "series");
topOrHost.appendChild(series);
}
doc.documentElement.appendChild(mods);
}
Zotero.write('<?xml version="1.0"?>'+"\n");
var serializer = new XMLSerializer();
Zotero.write(serializer.serializeToString(doc));
}
function processTitleInfo(titleInfo) {
var title = ZU.xpathText(titleInfo, "m:title[1]", xns).trim();
var subtitle = ZU.xpathText(titleInfo, "m:subTitle[1]", xns);
if(subtitle) title = title.replace(/:$/,'') + ": "+ subtitle.trim();
var nonSort = ZU.xpathText(titleInfo, "m:nonSort[1]", xns);
if(nonSort) title = nonSort.trim() + " " + title;
return title;
}
function processTitle(contextElement) {
// Try to find a titleInfo element with no type specified and a title element as a
// child
var titleElements = ZU.xpath(contextElement, "m:titleInfo[not(@type)][m:title][1]", xns);
if(titleElements.length) return processTitleInfo(titleElements[0]);
// That failed, so look for any titleInfo element without no type secified
var title = ZU.xpathText(contextElement, "m:titleInfo[not(@type)][1]", xns);
if(title) return title;
// That failed, so just go for the first title
return ZU.xpathText(contextElement, "m:titleInfo[1]", xns);
}
function processGenre(contextElement) {
// Try to get itemType by treating local genre as Zotero item type
var genre = ZU.xpath(contextElement, 'm:genre[@authority="local"]', xns);
for(var i=0; i<genre.length; i++) {
var genreStr = genre[i].textContent;
if(Zotero.Utilities.itemTypeExists(genreStr)) return genreStr;
}
// Try to get MARC genre and convert to an item type
genre = ZU.xpath(contextElement, 'm:genre[@authority="marcgt"] | m:genre[@authority="marc"]', xns);
for(var i=0; i<genre.length; i++) {
var genreStr = genre[i].textContent;
if(fromMarcGenre[genreStr]) return fromMarcGenre[genreStr];
}
// Try to get DCT genre and convert to an item type
genre = ZU.xpath(contextElement, 'm:genre[@authority="dct"]', xns);
for(var i=0; i<genre.length; i++) {
var genreStr = genre[i].textContent.replace(/\s+/g, "");
if(dctGenres[genreStr]) return dctGenres[genreStr];
}
// Try unlabeled genres
genre = ZU.xpath(contextElement, 'm:genre', xns);
for(var i=0; i<genre.length; i++) {
var genreStr = genre[i].textContent;
// Zotero
if(Zotero.Utilities.itemTypeExists(genreStr)) return genreStr;
// MARC
if(fromMarcGenre[genreStr]) return fromMarcGenre[genreStr];
// DCT
var dctGenreStr = genreStr.replace(/\s+/g, "");
if(dctGenres[dctGenreStr]) return dctGenres[dctGenreStr];
// Try regexps
for(var type in modsTypeRegex) {
if(modsTypeRegex[type].exec(genreStr)) return type;
}
}
return undefined;
}
function processItemType(contextElement) {
var type = processGenre(contextElement);
if(type) return type;
// Try to get type information from typeOfResource
var typeOfResource = ZU.xpath(contextElement, 'm:typeOfResource', xns);
for(var i=0; i<typeOfResource.length; i++) {
var typeOfResourceStr = typeOfResource[i].textContent.trim();
// Try list
if(fromTypeOfResource[typeOfResourceStr]) {
return fromTypeOfResource[typeOfResourceStr];
}
// Try regexps
for(var type in modsTypeRegex) {
if(modsTypeRegex[type].exec(typeOfResourceStr)) return type;
}
}
var hasHost = false;
var periodical = false;
// Try to get genre data from host
var hosts = ZU.xpath(contextElement, 'm:relatedItem[@type="host"]', xns);
for(var i=0; i<hosts.length; i++) {
type = processGenre(hosts[i]);
if(type) return type;
}
// Figure out if it's a periodical
var periodical = ZU.xpath(contextElement,
'm:relatedItem[@type="host"]/m:originInfo/m:issuance[text()="continuing" or text()="serial"]',
xns).length;
// Try physicalDescription/internetMediaType
var internetMediaTypes = ZU.xpath(contextElement, 'm:physicalDescription/m:internetMediaType', xns);
for(var i=0; i<internetMediaTypes.length; i++) {
var internetMediaTypeStr = internetMediaTypes[i].textContent.trim();
if(modsInternetMediaTypes[internetMediaTypeStr]) {
return modsInternetMediaTypes[internetMediaTypeStr];
};
}
// As a last resort, if it has a host, let's set it to book chapter, so we can import
// more info. Otherwise default to document
if(hosts.length) {
if(periodical) return 'journalArticle';
return 'bookSection';
}
return "document";
}
function processCreator(name, itemType, defaultCreatorType) {
var creator = {};
var backupName = new Array();
creator.firstName = ZU.xpathText(name, 'm:namePart[@type="given"]', xns, " ") || undefined;
creator.lastName = ZU.xpathText(name, 'm:namePart[@type="family"]', xns, " ");
if(!creator.lastName) {
var isPersonalName = name.getAttribute("type") === "personal",
backupName = ZU.xpathText(name, 'm:namePart[not(@type="date")][not(@type="termsOfAddress")]', xns, (isPersonalName ? " " : ": "));
if(!backupName) return null;
if(isPersonalName) {
creator = ZU.cleanAuthor(backupName.replace(/[\[\(][^A-Za-z]*[\]\)]/g, ''),
"author", true);
delete creator.creatorType;
} else {
creator.lastName = ZU.trimInternal(backupName);
creator.fieldMode = 1;
}
}
if(!creator.lastName) return null;
// Look for roles
var roles = ZU.xpath(name, 'm:role/m:roleTerm[@type="text" or not(@type)]', xns);
var validCreatorsForItemType = ZU.getCreatorsForType(itemType);
for(var i=0; i<roles.length; i++) {
var roleStr = roles[i].textContent.toLowerCase();
if(validCreatorsForItemType.indexOf(roleStr) !== -1) {
creator.creatorType = roleStr;
}
}
if(!creator.creatorType) {
// Look for MARC roles
var roles = ZU.xpath(name, 'm:role/m:roleTerm[@type="code"][@authority="marcrelator"]', xns);
for(var i=0; i<roles.length; i++) {
var roleStr = roles[i].textContent.toLowerCase();
if(marcRelators[roleStr]) creator.creatorType = marcRelators[roleStr];
}
// Default to author
if(!creator.creatorType) creator.creatorType = defaultCreatorType;
}
return creator;
}
function processCreators(contextElement, newItem, defaultCreatorType) {
var names = ZU.xpath(contextElement, 'm:name', xns);
for(var i=0; i<names.length; i++) {
var creator = processCreator(names[i], newItem.itemType, defaultCreatorType);
if(creator) newItem.creators.push(creator);
}
}
function processExtent(extent, newItem) {
//try to parse extent according to
//http://www.loc.gov/standards/mods/v3/mods-userguide-elements.html#extent
//i.e. http://www.loc.gov/marc/bibliographic/bd300.html
//and http://www.loc.gov/marc/bibliographic/bd306.html
var extentRe = new RegExp(
'^(.*?)(?=(?:[:;]|$))' + //extent [1]
'(?::.*?(?=(?:;|$)))?' + //other physical details
'(?:;(.*))?' + //dimensions [2]
'$' //make sure to capture the rest of the line
);
var ma = extentRe.exec(extent);
if(ma && ma[1]) {
//drop supplemental info (i.e. everything after +)
if(ma[1].indexOf('+') >= 0) {
ma[1] = ma[1].slice(0, ma[1].indexOf('+'));
}
// pages
if(!newItem.pages && ZU.fieldIsValidForType('pages', newItem.itemType)) {
var pages = ma[1].match(/\bp(?:ages?)?\.?\s+([a-z]?\d+(?:\s*-\s*[a-z]?\d+))/i);
if(pages) {
newItem.pages = pages[1].replace(/\s+/,'');
}
}
// volume
if(!newItem.volume && ZU.fieldIsValidForType('volume', newItem.itemType)) {
var volume = ma[1].match(/\bv(?:ol(?:ume)?)?\.?\s+(\d+)/i);
if(volume) {
newItem.volume = volume[1];
}
}
//issue
if(!newItem.issue && ZU.fieldIsValidForType('issue', newItem.itemType)) {
var issue = ma[1].match(/\b(?:no?|iss(?:ue)?)\.?\s+(\d+)/i);
if(issue) {
newItem.issue = issue[1];
}
}
// numPages
if(!newItem.numPages && ZU.fieldIsValidForType('numPages', newItem.itemType)) {
var pages = ma[1].match(/(\d+)\s*p(?:ages?)?\b/i);
if(pages) {
newItem.numPages = pages[1];
}
}
// numberOfVolumes
if(!newItem.numberOfVolumes && ZU.fieldIsValidForType('numberOfVolumes', newItem.itemType)) {
//includes volumes, scores, sound (discs, but I think there could be others)
//video (cassette, but could have others)
var nVol = ma[1].match(/(\d+)\s+(?:v(?:olumes?)?|scores?|sound|video)\b/i);
if(nVol) {
newItem.numberOfVolumes = nVol[1];
}
}
// runningTime
if(!newItem.runningTime && ZU.fieldIsValidForType('runningTime', newItem.itemType)) {
//several possible formats:
var rt;
// 002016 = 20 min., 16 sec.
if(rt = ma[1].match(/\b(\d{2,3})(\d{2})(\d{2})\b/)) {
newItem.runningTime = rt[1] + ':' + rt[2] + ':' + rt[3];
// (ca. 124 min.)
} else if(rt = ma[1].match(/((\d+)\s*((?:hours?|hrs?)|(?:minutes?|mins?)|(?:seconds?|secs?))\.?\s+)?((\d+)\s*((?:hours?|hrs?)|(?:minutes?|mins?)|(?:seconds?|secs?))\.?\s+)?((\d+)\s*((?:hours?|hrs?)|(?:minutes?|mins?)|(?:seconds?|secs?))\.?)/i)) {
var hrs=0, mins=0, secs=0;
for(var i=2; i<7; i+=2) {
if(!rt[i]) continue;
switch(rt[i].charAt(0).toLowerCase()) {
case 'h':
hrs = rt[i-1];
break;
case 'm':
mins = rt[i-1];
break;
case 's':
secs = rt[i-1];
break;
}
}
if(secs > 59) {
mins += secs/60;
secs %= 60;
}
if(secs < 10) {
secs = '0' + secs;
}
if(mins > 59) {
hrs += hrs/60;
mins %= 60;
}
if(mins < 10) {
mins = '0' + mins;
}
newItem.runningTime = ( (hrs*1) ? hrs + ':' : '' ) + mins + ':' + secs;
// (46:00)
} else if(rt = ma[1].match(/\b(\d{0,3}:\d{1,2}:\d{2})\b/)) {
newItem.runningTime = rt[1];
}
}
}
// dimensions: artworkSize
// only part of artwork right now, but maybe will be in other types in the future
if(!newItem.artworkSize && ma && ma[2] && ZU.fieldIsValidForType('artworkSize', newItem.itemType)) {
//drop supplemental info (i.e. everything after +)
if(ma[2].indexOf('+') >= 0) {
ma[2] = ma[2].slice(0, ma[2].indexOf('+'));
}
//26 cm. or 33 x 15 cm. or 1/2 in. or 1 1/2 x 15/16 in.
var dim = ma[2].match(/(?:(?:(?:\d+\s+)?\d+\/)?\d+\s*x\s*)?(?:(?:\d+\s+)?\d+\/)?\d+\s*(?:cm|mm|m|in|ft)\./i);
if(dim) newItem.artworkSize = dim[0];
}
}
function processIdentifiers(contextElement, newItem) {
var isbnNodes = ZU.xpath(contextElement, './/m:identifier[@type="isbn"]', xns),
isbns = [];
for(var i=0; i<isbnNodes.length; i++) {
var m = isbnNodes[i].textContent.replace(/\s*-\s*/g,'').match(/(?:[\dX]{10}|\d{13})/i);
if(m) isbns.push(m[0]);
}
if(isbns.length) newItem.ISBN = isbns.join(", ");
var issnNodes = ZU.xpath(contextElement, './/m:identifier[@type="issn"]', xns),
issns = [];
for(var i=0; i<issnNodes.length; i++) {
var m = issnNodes[i].textContent.match(/\b\d{4}\s*-?\s*\d{4}\b/i);
if(m) issns.push(m[0]);
}
if(issns.length) newItem.ISSN = issns.join(", ");
newItem.DOI = ZU.xpathText(contextElement, 'm:identifier[@type="doi"]', xns);
}
function getFirstResult(contextNode, xpaths) {
for(var i=0; i<xpaths.length; i++) {
var results = ZU.xpath(contextNode, xpaths[i], xns);
if(results.length) return results[0].textContent;
}
}
function doImport() {
var xml = Zotero.getXML();
var modsElements = ZU.xpath(xml, "/m:mods | /m:modsCollection/m:mods", xns);
for(var iModsElements=0, nModsElements=modsElements.length;
iModsElements<nModsElements; iModsElements++) {
var modsElement = modsElements[iModsElements],
newItem = new Zotero.Item();
// title
newItem.title = processTitle(modsElement);
// shortTitle
var abbreviatedTitle = ZU.xpath(modsElement, 'm:titleInfo[@type="abbreviated"]', xns);
if(abbreviatedTitle.length) {
newItem.shortTitle = processTitleInfo(abbreviatedTitle[0]);
}
// itemType
newItem.itemType = processItemType(modsElement);
var isPartialItem = partialItemTypes.indexOf(newItem.itemType) !== -1;
// TODO: thesisType, type
// creators
processCreators(modsElement, newItem, "author");
// source
newItem.source = ZU.xpathText(modsElement, 'm:recordInfo/m:recordContentSource', xns);
// accessionNumber
newItem.accessionNumber = ZU.xpathText(modsElement, 'm:recordInfo/m:recordIdentifier', xns);
// rights
newItem.rights = ZU.xpathText(modsElement, 'm:accessCondition', xns);
/** SUPPLEMENTAL FIELDS **/
var part = [], originInfo = [];
// host
var hostNodes = ZU.xpath(modsElement, 'm:relatedItem[@type="host"]', xns)
for(var i=0; i<hostNodes.length; i++) {
var host = hostNodes[i];
// publicationTitle