-
Notifications
You must be signed in to change notification settings - Fork 717
/
item.js
5544 lines (4726 loc) · 152 KB
/
item.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/>.
***** END LICENSE BLOCK *****
*/
/*
* Constructor for Item object
*/
Zotero.Item = function(itemTypeOrID) {
if (arguments[1] || arguments[2]) {
throw ("Zotero.Item constructor only takes one parameter");
}
Zotero.Item._super.apply(this);
this._disabled = false;
// loadPrimaryData (additional properties in dataObject.js)
this._itemTypeID = null;
this._createdByUserID = null;
this._lastModifiedByUserID = null;
this._firstCreator = null;
this._sortCreator = null;
this._attachmentCharset = null;
this._attachmentLinkMode = null;
this._attachmentContentType = null;
this._attachmentPath = null;
this._attachmentSyncState = 0;
this._attachmentSyncedModificationTime = null;
this._attachmentSyncedHash = null;
this._attachmentLastProcessedModificationTime = null;
// loadCreators
this._creators = [];
this._creatorIDs = [];
// loadItemData
this._itemData = null;
this._noteTitle = null;
this._noteText = null;
this._displayTitle = null;
// loadChildItems
this._attachments = null;
this._notes = null;
// loadAnnotation
this._annotationType = null;
this._annotationAuthorName = null;
this._annotationText = null;
this._annotationImage = null;
this._annotationComment = null;
this._annotationColor = null;
this._annotationPageLabel = null;
this._annotationSortIndex = null;
this._annotationPosition = null;
this._annotationIsExternal = null;
this._tags = [];
this._collections = [];
this._bestAttachmentState = null;
this._fileExists = null;
this._hasNote = null;
this._noteAccessTime = null;
if (itemTypeOrID) {
// setType initializes type-specific properties in this._itemData
this.setType(Zotero.ItemTypes.getID(itemTypeOrID));
}
}
Zotero.extendClass(Zotero.DataObject, Zotero.Item);
Zotero.Item.prototype._objectType = 'item';
Zotero.defineProperty(Zotero.Item.prototype, 'ContainerObjectsClass', {
get: function() { return Zotero.Collections; }
});
Zotero.Item.prototype._dataTypes = Zotero.Item._super.prototype._dataTypes.concat([
'creators',
'itemData',
'note',
'annotation',
'annotationDeferred',
'childItems',
// 'relatedItems', // TODO: remove
'tags',
'collections',
'relations'
]);
Zotero.defineProperty(Zotero.Item.prototype, 'id', {
get: function() { return this._id; },
set: function(val) { return this.setField('id', val); }
});
Zotero.defineProperty(Zotero.Item.prototype, 'itemID', {
get: function() {
Zotero.debug("Item.itemID is deprecated -- use Item.id");
return this._id;
},
enumerable: false
});
for (let name of ['libraryID', 'key', 'dateAdded', 'dateModified', 'version', 'synced',
'createdByUserID', 'lastModifiedByUserID']) {
let prop = '_' + name;
Zotero.defineProperty(Zotero.Item.prototype, name, {
get: function () { return this[prop]; },
set: function (val) { return this.setField(name, val); }
});
}
Zotero.defineProperty(Zotero.Item.prototype, 'itemTypeID', {
get: function() { return this._itemTypeID; }
});
Zotero.defineProperty(Zotero.Item.prototype, 'itemType', {
get: function() { return Zotero.ItemTypes.getName(this._itemTypeID); }
});
// .parentKey and .parentID defined in dataObject.js, but create aliases
Zotero.defineProperty(Zotero.Item.prototype, 'parentItemID', {
get: function() { return this.parentID; },
set: function(val) { return this.parentID = val; }
});
Zotero.defineProperty(Zotero.Item.prototype, 'parentItemKey', {
get: function() { return this.parentKey; },
set: function(val) { return this.parentKey = val; }
});
Zotero.defineProperty(Zotero.Item.prototype, 'parentItem', {
get: function() { return Zotero.Items.get(this.parentID) || undefined; },
});
Zotero.defineProperty(Zotero.Item.prototype, 'firstCreator', {
get: function() { return this._firstCreator; }
});
Zotero.defineProperty(Zotero.Item.prototype, 'sortCreator', {
get: function() { return this._sortCreator; }
});
Zotero.defineProperty(Zotero.Item.prototype, 'relatedItems', {
get: function() { return this._getRelatedItems(); }
});
Zotero.defineProperty(Zotero.Item.prototype, 'treeViewID', {
get: function () {
return this.id
}
});
Zotero.Item.prototype.getID = function() {
Zotero.debug('Item.getID() is deprecated -- use Item.id');
return this._id;
}
Zotero.Item.prototype.getType = function() {
Zotero.debug('Item.getType() is deprecated -- use Item.itemTypeID');
return this._itemTypeID;
}
Zotero.Item.prototype.isPrimaryField = function (fieldName) {
Zotero.debug("Zotero.Item.isPrimaryField() is deprecated -- use Zotero.Items.isPrimaryField()");
return this.ObjectsClass.isPrimaryField(fieldName);
}
Zotero.Item.prototype._get = function () {
throw new Error("_get is not valid for items");
}
Zotero.Item.prototype._set = function () {
throw new Error("_set is not valid for items");
}
Zotero.Item.prototype._setParentKey = function() {
if (!this.isNote() && !this.isAttachment() && !this.isAnnotation()) {
throw new Error("_setParentKey() can only be called on items of type 'note', 'attachment', or 'annotation'");
}
Zotero.Item._super.prototype._setParentKey.apply(this, arguments);
}
//////////////////////////////////////////////////////////////////////////////
//
// Public Zotero.Item methods
//
//////////////////////////////////////////////////////////////////////////////
/*
* Retrieves an itemData field value
*
* @param {String|Integer} field fieldID or fieldName
* @param {Boolean} [unformatted] Skip any special processing of DB value
* (e.g. multipart date field)
* @param {Boolean} includeBaseMapped If true and field is a base field, returns
* value of type-specific field instead
* (e.g. 'label' for 'publisher' in 'audioRecording')
* @return {String} Value as string or empty string if value is not present
*/
Zotero.Item.prototype.getField = function(field, unformatted, includeBaseMapped) {
if (field != 'id') this._disabledCheck();
//Zotero.debug('Requesting field ' + field + ' for item ' + this._id, 4);
this._requireData('primaryData');
// TODO: Add sortCreator
if (field === 'firstCreator' && !this._id) {
// Hack to get a firstCreator for an unsaved item
let creatorsData = this.getCreators(true);
return Zotero.Items.getFirstCreatorFromData(this.itemTypeID, creatorsData);
} else if (field === 'id' || this.ObjectsClass.isPrimaryField(field)) {
var privField = '_' + field;
//Zotero.debug('Returning ' + (this[privField] ? this[privField] : '') + ' (typeof ' + typeof this[privField] + ')');
return this[privField];
} else if (field == 'year') {
return this.getField('date', true, true).substr(0,4);
}
if (this.isNote()) {
switch (Zotero.ItemFields.getName(field)) {
case 'title':
return this.getNoteTitle();
default:
return '';
}
}
if (includeBaseMapped) {
var fieldID = Zotero.ItemFields.getFieldIDFromTypeAndBase(
this._itemTypeID, field
);
}
if (!fieldID) {
var fieldID = Zotero.ItemFields.getID(field);
}
let value = this._itemData[fieldID];
if (value === undefined) {
//Zotero.debug("Field '" + field + "' doesn't exist for item type " + this._itemTypeID + " in Item.getField()");
return '';
}
// If the item is identified (has an id or key), this field has to be populated
if (this._identified && value === null && !this._loaded.itemData) {
throw new Zotero.Exception.UnloadedDataException(
"Item data not loaded and field '" + field + "' not set for item " + this.libraryKey,
"itemData"
);
}
value = (value !== null && value !== false) ? value : '';
if (!unformatted) {
// Multipart date fields
if (Zotero.ItemFields.isDate(fieldID)) {
value = Zotero.Date.multipartToStr(value);
}
}
//Zotero.debug('Returning ' + value);
return value;
}
Zotero.Item.prototype.getExtraField = function (fieldName) {
var { fields } = Zotero.Utilities.Internal.extractExtraFields(this.getField('extra'));
return fields.get(fieldName) || '';
};
/**
* @param {Boolean} asNames
* @return {Integer[]|String[]}
*/
Zotero.Item.prototype.getUsedFields = function(asNames) {
this._requireData('itemData');
return Object.keys(this._itemData)
.filter(id => this._itemData[id] !== false && this._itemData[id] !== null)
.map(id => asNames ? Zotero.ItemFields.getName(id) : parseInt(id));
};
/*
* Populate basic item data from a database row
*/
Zotero.Item.prototype.loadFromRow = function(row, reload) {
// If necessary or reloading, set the type and reinitialize this._itemData
if (reload || (!this._itemTypeID && row.itemTypeID)) {
this.setType(row.itemTypeID, true);
}
this._parseRowData(row);
this._finalizeLoadFromRow(row);
}
Zotero.Item.prototype._parseRowData = function(row) {
var primaryFields = this.ObjectsClass.primaryFields;
for (let i=0; i<primaryFields.length; i++) {
let col = primaryFields[i];
try {
var val = row[col];
}
catch (e) {
Zotero.debug('Skipping missing field ' + col);
continue;
}
//Zotero.debug("Setting field '" + col + "' to '" + val + "' for item " + this.id);
switch (col) {
// Unchanged
case 'libraryID':
case 'itemTypeID':
case 'attachmentSyncState':
case 'attachmentSyncedModificationTime':
case 'attachmentSyncedHash':
case 'attachmentLastProcessedModificationTime':
case 'createdByUserID':
case 'lastModifiedByUserID':
break;
case 'itemID':
col = 'id';
break;
// Integer or 0
case 'version':
val = val ? parseInt(val) : 0;
break;
// Value or false
case 'parentKey':
val = val || false;
break;
// Integer or false if falsy
case 'parentID':
val = val ? parseInt(val) : false;
break;
case 'attachmentLinkMode':
val = val !== null
? parseInt(val)
// Shouldn't happen
: Zotero.Attachments.LINK_MODE_IMPORTED_URL;
break;
case 'attachmentPath':
// Ignore .zotero* files that were relinked before we started blocking them
if (!val || val.startsWith('.zotero')) {
val = '';
}
break;
// Boolean
case 'synced':
case 'deleted':
case 'inPublications':
val = !!val;
break;
default:
val = val ? val : '';
}
this['_' + col] = val;
}
}
Zotero.Item.prototype._finalizeLoadFromRow = function(row) {
this._loaded.primaryData = true;
this._clearChanged('primaryData');
this._clearChanged('attachmentData');
this._identified = true;
}
/*
* Set or change the item's type
*/
Zotero.Item.prototype.setType = function(itemTypeID, loadIn) {
if (itemTypeID == this._itemTypeID) {
return true;
}
// Adjust 'note' data type based on whether the item is an attachment or note
var isAttachment = Zotero.ItemTypes.getID('attachment') == itemTypeID;
var isNote = Zotero.ItemTypes.getID('note') == itemTypeID;
this._skipDataTypeLoad.note = !(isAttachment || isNote);
var oldItemTypeID = this._itemTypeID;
if (oldItemTypeID) {
if (loadIn) {
throw new Error('Cannot change type in loadIn mode');
}
// Changing the item type can affect fields and creators, so they need to be loaded
this._requireData('itemData');
this._requireData('creators');
var copiedFields = [];
var newNotifierFields = [];
// Special cases handled below
var bookTypeID = Zotero.ItemTypes.getID('book');
var bookSectionTypeID = Zotero.ItemTypes.getID('bookSection');
var obsoleteFields = this.getFieldsNotInType(itemTypeID);
if (obsoleteFields) {
// Move bookTitle to title and clear short title when going from
// bookSection to book if there's not also a title
if (oldItemTypeID == bookSectionTypeID && itemTypeID == bookTypeID) {
var titleFieldID = Zotero.ItemFields.getID('title');
var bookTitleFieldID = Zotero.ItemFields.getID('bookTitle');
var shortTitleFieldID = Zotero.ItemFields.getID('shortTitle');
if (this._itemData[bookTitleFieldID] && !this._itemData[titleFieldID]) {
copiedFields.push([titleFieldID, this._itemData[bookTitleFieldID]]);
newNotifierFields.push(titleFieldID);
if (this._itemData[shortTitleFieldID]) {
this.setField(shortTitleFieldID, false);
}
}
}
for (let oldFieldID of obsoleteFields) {
// Try to get a base type for this field
var baseFieldID =
Zotero.ItemFields.getBaseIDFromTypeAndField(oldItemTypeID, oldFieldID);
if (baseFieldID) {
var newFieldID =
Zotero.ItemFields.getFieldIDFromTypeAndBase(itemTypeID, baseFieldID);
// If so, save value to copy to new field
if (newFieldID) {
copiedFields.push([newFieldID, this.getField(oldFieldID)]);
}
}
// Clear old field
/*
delete this._itemData[oldFieldID];
if (!this._changed.itemData) {
this._changed.itemData = {};
}
this._changed.itemData[oldFieldID] = true;
*/
this.setField(oldFieldID, false);
}
}
// Move title to bookTitle and clear shortTitle when going from book to bookSection
if (oldItemTypeID == bookTypeID && itemTypeID == bookSectionTypeID) {
var titleFieldID = Zotero.ItemFields.getID('title');
var bookTitleFieldID = Zotero.ItemFields.getID('bookTitle');
var shortTitleFieldID = Zotero.ItemFields.getID('shortTitle');
if (this._itemData[titleFieldID]) {
copiedFields.push([bookTitleFieldID, this._itemData[titleFieldID]]);
newNotifierFields.push(bookTitleFieldID);
this.setField(titleFieldID, false);
}
if (this._itemData[shortTitleFieldID]) {
this.setField(shortTitleFieldID, false);
}
}
for (var fieldID in this._itemData) {
if (this._itemData[fieldID] &&
(!obsoleteFields || obsoleteFields.indexOf(fieldID) == -1)) {
copiedFields.push([fieldID, this.getField(fieldID)]);
}
}
}
this._itemTypeID = itemTypeID;
// If there's an existing type
if (oldItemTypeID) {
// Reset custom creator types to the default
let creators = this.getCreators();
if (creators.length) {
let removeAll = !Zotero.CreatorTypes.itemTypeHasCreators(itemTypeID);
for (let i = 0; i < this.getCreators().length; i++) {
// Remove all creators if new item type doesn't have any
if (removeAll) {
throw new Error("Disabled");
this.removeCreator(i);
i--;
continue;
}
if (!Zotero.CreatorTypes.isValidForItemType(creators[i].creatorTypeID, itemTypeID)) {
// Convert existing primary creator type to new item type's
// primary creator type, or contributor (creatorTypeID 2)
// if none or not currently primary
let oldPrimary = Zotero.CreatorTypes.getPrimaryIDForType(oldItemTypeID);
let newPrimary = false;
if (oldPrimary == creators[i].creatorTypeID) {
newPrimary = Zotero.CreatorTypes.getPrimaryIDForType(itemTypeID);
}
creators[i].creatorTypeID = newPrimary ? newPrimary : 2;
this.setCreator(i, creators[i]);
}
}
}
}
// Initialize this._itemData with type-specific fields
this._itemData = {};
var fields = Zotero.ItemFields.getItemTypeFields(itemTypeID);
for (let fieldID of fields) {
this._itemData[fieldID] = null;
}
// DEBUG: clear change item data?
if (copiedFields) {
for (let f of copiedFields) {
// For fields that we moved to different fields in the new type
// (e.g., book -> bookTitle), mark the old value as explicitly
// false in previousData (since otherwise it would be null)
if (newNotifierFields.indexOf(f[0]) != -1) {
this._markFieldChange(Zotero.ItemFields.getName(f[0]), false);
this.setField(f[0], f[1]);
}
// For fields that haven't changed, clear from previousData
// after setting
else {
this.setField(f[0], f[1]);
this._clearFieldChange(Zotero.ItemFields.getName(f[0]));
}
}
}
if (loadIn) {
this._loaded['itemData'] = false;
}
else {
if (oldItemTypeID) {
this._markFieldChange('itemType', Zotero.ItemTypes.getName(oldItemTypeID));
}
if (!this._changed.primaryData) {
this._changed.primaryData = {};
}
this._changed.primaryData.itemTypeID = true;
}
return true;
}
/*
* Find existing fields from current type that aren't in another
*
* If _allowBaseConversion_, don't return fields that can be converted
* via base fields (e.g. label => publisher => studio)
*/
Zotero.Item.prototype.getFieldsNotInType = function (itemTypeID, allowBaseConversion) {
var fieldIDs = [];
for (var field in this._itemData) {
if (this._itemData[field]) {
var fieldID = Zotero.ItemFields.getID(field);
if (Zotero.ItemFields.isValidForType(fieldID, itemTypeID)) {
continue;
}
if (allowBaseConversion) {
var baseID = Zotero.ItemFields.getBaseIDFromTypeAndField(this.itemTypeID, field);
if (baseID) {
var newFieldID = Zotero.ItemFields.getFieldIDFromTypeAndBase(itemTypeID, baseID);
if (newFieldID) {
continue;
}
}
}
fieldIDs.push(fieldID);
}
}
if (!fieldIDs.length) {
return false;
}
return fieldIDs;
}
/*
* Set a field value, loading existing itemData first if necessary
*
* Field can be passed as fieldID or fieldName
*/
Zotero.Item.prototype.setField = function(field, value, loadIn) {
this._disabledCheck();
if (value === undefined) {
throw new Error(`'${field}' value cannot be undefined`);
}
//Zotero.debug("Setting field '" + field + "' to '" + value + "' (loadIn: " + (loadIn ? 'true' : 'false') + ") for item " + this.id + " ");
if (!field) {
throw new Error("Field not specified");
}
if (field == 'id' || field == 'libraryID' || field == 'key') {
return this._setIdentifier(field, value);
}
// Primary field
if (this.ObjectsClass.isPrimaryField(field)) {
this._requireData('primaryData');
if (loadIn) {
throw new Error('Cannot set primary field ' + field + ' in loadIn mode in Zotero.Item.setField()');
}
switch (field) {
case 'itemTypeID':
if (typeof value != 'number' || value != parseInt(value)) {
throw new Error(`${field} must be a number`);
}
break;
case 'dateAdded':
case 'dateModified':
// Accept ISO dates
if (Zotero.Date.isISODate(value)) {
let d = Zotero.Date.isoToDate(value);
value = Zotero.Date.dateToSQL(d, true);
}
// Make sure it's valid
let date = Zotero.Date.sqlToDate(value, true);
if (!date) throw new Error("Invalid SQL date: " + value);
value = Zotero.Date.dateToSQL(date, true);
break;
case 'version':
if (typeof value != 'number' || value != parseInt(value)) {
throw new Error(`${field} must be a number`);
}
break;
case 'synced':
if (typeof value != 'boolean') {
throw new Error(`${field} must be a boolean`);
}
value = !!value;
break;
case 'createdByUserID':
case 'lastModifiedByUserID':
if (typeof value != 'number' || value != parseInt(value)) {
throw new Error(`${field} must be a number`);
}
if (!this._libraryID) {
throw new Error(`libraryID must be set before setting ${field}`);
}
if (Zotero.Libraries.get(this._libraryID).libraryType != 'group') {
throw new Error(`${field} is only valid for group library items`);
}
break;
default:
throw new Error('Primary field ' + field + ' cannot be changed in Zotero.Item.setField()');
}
/*
if (!Zotero.ItemFields.validate(field, value)) {
throw("Value '" + value + "' of type " + typeof value + " does not validate for field '" + field + "' in Zotero.Item.setField()");
}
*/
// If field value has changed
if (this['_' + field] === value) {
if (field == 'synced') {
Zotero.debug("Setting synced to " + value);
}
else {
Zotero.debug("Field '" + field + "' has not changed", 4);
return false;
}
}
else {
Zotero.debug("Field '" + field + "' has changed from '" + this['_' + field] + "' to '" + value + "'", 4);
}
// Save a copy of the field before modifying
this._markFieldChange(field, this['_' + field]);
if (field == 'itemTypeID') {
this.setType(value, loadIn);
}
else {
this['_' + field] = value;
if (!this._changed.primaryData) {
this._changed.primaryData = {};
}
this._changed.primaryData[field] = true;
}
return true;
}
// Normalize values
if (typeof value == 'number') {
value = "" + value;
}
else if (typeof value == 'string') {
value = value.trim().normalize();
}
if (value === "" || value === null || value === false) {
value = false;
}
if (!loadIn) {
this._requireData('itemData');
}
let itemTypeID = this.itemTypeID;
if (!itemTypeID) {
throw new Error('Item type must be set before setting field data');
}
var fieldID = Zotero.ItemFields.getID(field);
if (!fieldID) {
throw new Error('"' + field + '" is not a valid itemData field');
}
if (loadIn && this.isNote() && field == Zotero.ItemFields.getID('title')) {
this._noteTitle = value ? value : "";
return true;
}
// Make sure to use type-specific field ID if available
fieldID = Zotero.ItemFields.getFieldIDFromTypeAndBase(itemTypeID, fieldID) || fieldID;
if (value !== false && !Zotero.ItemFields.isValidForType(fieldID, itemTypeID)) {
let msg = "'" + field + "' is not a valid field for type '"
+ Zotero.ItemFields.getName(itemTypeID) + "'";
if (loadIn) {
Zotero.debug(msg + " -- ignoring value '" + value + "'", 2);
return false;
}
else {
throw new Error(msg);
}
}
// If not a multiline field, strip newlines
if (typeof value == 'string' && !Zotero.ItemFields.isMultiline(fieldID)) {
value = value.replace(/[\r\n]+/g, " ");;
}
if (fieldID == Zotero.ItemFields.getID('ISBN')) {
// Hyphenate ISBNs, but only if everything is in expected format and valid
let isbns = ('' + value).trim().split(/\s*[,;]\s*|\s+/),
newISBNs = '',
failed = false;
for (let i=0; i<isbns.length; i++) {
let isbn = Zotero.Utilities.Internal.hyphenateISBN(isbns[i]);
if (!isbn) {
failed = true;
break;
}
newISBNs += ' ' + isbn;
}
if (!failed) value = newISBNs.substr(1);
}
if (!loadIn) {
// Save date field as multipart date
if (value !== false
&& (Zotero.ItemFields.isDate(fieldID))
&& !Zotero.Date.isMultipart(value)) {
value = Zotero.Date.strToMultipart(value);
}
// Validate access date
else if (fieldID == Zotero.ItemFields.getID('accessDate')) {
if (value && value != 'CURRENT_TIMESTAMP') {
// Accept ISO dates
if (Zotero.Date.isISODate(value) && !Zotero.Date.isSQLDate(value)) {
let d = Zotero.Date.isoToDate(value);
value = Zotero.Date.dateToSQL(d, true);
}
if (!Zotero.Date.isSQLDate(value) && !Zotero.Date.isSQLDateTime(value)) {
Zotero.logError(`Discarding invalid ${Zotero.ItemFields.getName(field)} '${value}' `
+ `for item ${this.libraryKey} in setField()`);
return false;
}
}
}
// If existing value, make sure it's actually changing
if ((this._itemData[fieldID] === null && value === false)
|| (this._itemData[fieldID] !== null && this._itemData[fieldID] === value)) {
return false;
}
// Save a copy of the field before modifying
this._markFieldChange(
Zotero.ItemFields.getName(field), this._itemData[fieldID]
);
}
this._itemData[fieldID] = value;
if (!loadIn) {
if (!this._changed.itemData) {
this._changed.itemData = {};
}
this._changed.itemData[fieldID] = true;
}
return true;
}
/*
* Get the title for an item for display in the interface
*
* This is the same as the standard title field (with includeBaseMapped on)
* except for letters and interviews, which get placeholder titles in
* square braces (e.g. "[Letter to Thoreau]"), and cases
*/
Zotero.Item.prototype.getDisplayTitle = function (includeAuthorAndDate) {
if (this._displayTitle !== null) {
return this._displayTitle;
}
return this._displayTitle = this.getField('title', false, true);
}
/**
* Update the generated display title from the loaded data
*/
Zotero.Item.prototype.updateDisplayTitle = function () {
var title = this.getField('title', false, true);
var itemTypeID = this.itemTypeID;
var itemTypeName = Zotero.ItemTypes.getName(itemTypeID);
var itemTypeLetter = Zotero.ItemTypes.getID('letter');
var itemTypeInterview = Zotero.ItemTypes.getID('interview');
var itemTypeCase = Zotero.ItemTypes.getID('case');
var creatorTypeAuthor = Zotero.CreatorTypes.getID('author');
var creatorTypeRecipient = Zotero.CreatorTypes.getID('recipient');
var creatorTypeInterviewer = Zotero.CreatorTypes.getID('interviewer');
var creatorTypeInterviewee = Zotero.CreatorTypes.getID('interviewee');
// 'letter' and 'interview'
if (title === "" && (itemTypeID == itemTypeLetter || itemTypeID == itemTypeInterview)) {
var creatorsData = this.getCreators();
var authors = [];
var participants = [];
for (let i=0; i<creatorsData.length; i++) {
let creatorData = creatorsData[i];
let creatorTypeID = creatorsData[i].creatorTypeID;
if ((itemTypeID == itemTypeLetter && creatorTypeID == creatorTypeRecipient) ||
(itemTypeID == itemTypeInterview && creatorTypeID == creatorTypeInterviewer)) {
participants.push(creatorData);
}
else if ((itemTypeID == itemTypeLetter && creatorTypeID == creatorTypeAuthor) ||
(itemTypeID == itemTypeInterview && creatorTypeID == creatorTypeInterviewee)) {
authors.push(creatorData);
}
}
var strParts = [];
if (participants.length > 0) {
let names = [];
let max = Math.min(4, participants.length);
for (let i=0; i<max; i++) {
names.push(
participants[i].name !== undefined
? participants[i].name
: participants[i].lastName
);
}
switch (names.length) {
case 1:
var str = 'oneParticipant';
break;
case 2:
var str = 'twoParticipants';
break;
case 3:
var str = 'threeParticipants';
break;
default:
var str = 'manyParticipants';
}
strParts.push(Zotero.getString('pane.items.' + itemTypeName + '.' + str, names));
}
else {
strParts.push(Zotero.ItemTypes.getLocalizedString(itemTypeID));
}
title = '[' + strParts.join('; ') + ']';
}
// 'case'
else if (itemTypeID == itemTypeCase) {
if (title) { // common law cases always have case names
var reporter = this.getField('reporter');
if (reporter) {
title = title + ' (' + reporter + ')';
} else {
var court = this.getField('court');
if (court) {
title = title + ' (' + court + ')';
}
}
}
else { // civil law cases have only shortTitle as case name
var strParts = [];
var caseinfo = "";
var part = this.getField('court');
if (part) {
strParts.push(part);
}
part = Zotero.Date.multipartToSQL(this.getField('date', true, true));
if (part) {
strParts.push(part);
}
var creatorData = this.getCreator(0);
if (creatorData && creatorData.creatorTypeID === creatorTypeAuthor) {
strParts.push(creatorData.lastName);
}
title = '[' + strParts.join(', ') + ']';
}
}
this._displayTitle = title;
};
/*
* Returns the number of creators for this item
*/
Zotero.Item.prototype.numCreators = function() {
this._requireData('creators');
return this._creators.length;
}
Zotero.Item.prototype.hasCreatorAt = function(pos) {
this._requireData('creators');
return !!this._creators[pos];
}
/**
* @param {Integer} pos
* @return {Object|Boolean} The internal creator data object at the given position, or FALSE if none
*/
Zotero.Item.prototype.getCreator = function (pos) {
this._requireData('creators');
if (!this._creators[pos]) {
return false;
}