]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/templates/opac/parts/misc_util.tt2
LP2061136 - Stamping 1405 DB upgrade script
[Evergreen.git] / Open-ILS / src / templates / opac / parts / misc_util.tt2
1 [%- 
2     # Support multiscript records via alternate graphic 880 fields
3     # get_graphic_880s(target_field='100')
4     # See "Model A" in http://www.loc.gov/marc/bibliographic/ecbdmulti.html
5     # and $6 description in http://www.loc.gov/marc/bibliographic/ecbdcntf.html
6     MACRO get_graphic_880s BLOCK;
7         FOR node IN xml.findnodes('//*[@tag="' _ target_field _ '"]');
8             raw_vals = [];
9             core_val = '';
10             FOR subnode IN node.findnodes('./*[not(contains("e w 0 4 5 6 7 8 9", @code))]');
11                 raw_vals.push(subnode.textContent());
12             END;
13             core_val = raw_vals.join(" ");
14             raw_vals = [];
15
16             linked_fields = [];
17             FOR sub IN node.findnodes('./*[@code="6"]');
18                 linked_fields.push(sub.textContent);
19             END;
20             graphics = [];
21             get_linked_880s;
22             graphic_880s.push({
23                 primary => {"occur" => occurrence, "value" => core_val},
24                 graphic => graphics
25             });
26         END;
27     END;
28
29     MACRO get_linked_880s BLOCK;
30         FOR link_field IN linked_fields;
31             target = target_field _ link_field.substr(3);
32             # Get the linked 880 value
33             raw_val = '';
34             dir = '';
35             occurrence = '';
36             script = '';
37             FOR node IN xml.findnodes('//*[@tag="880"]');
38                 # Operate only on the target linked fields
39                 FOR linknode IN node.findnodes('./*[@code="6"]');
40                     lf = linknode.textContent();
41                     IF lf.substr(0, target.length) == target;
42                         occurrence = lf.substr(4, 2);
43                         rawscript = lf.substr(7, 2);
44                         SWITCH rawscript;
45                         CASE '(3';
46                             script = 'Arabic';
47                         CASE '(B';
48                             script = 'Latin';
49                         CASE '$1';
50                             script = 'CJK';
51                         CASE '(N';
52                             script = 'Cyrillic';
53                         CASE '(S';
54                             script = 'Greek';
55                         CASE '(2';
56                             script = 'Hebrew';
57                         END;
58
59                         rawdir = lf.substr(9, 1);
60                         SWITCH rawdir;
61                         CASE 'r';
62                             dir = 'rtl';
63                         END;
64
65                         raw_vals = [];
66                         FOR subnode IN node.findnodes('./*[not(contains("w 0 5 6 8 9", @code))]');
67                             raw_vals.push(subnode.textContent());
68                         END;
69                         raw_val = raw_vals.join(" ");
70                     END;
71                 END;
72             END;
73             graphics.push({
74                 occur => occurrence,
75                 value => raw_val,
76                 script => script,
77                 dir => dir
78             });
79         END;
80     END;
81
82     BLOCK get_ccvm_icon;
83         ctx.media_prefix _ '/images/format_icons/' _ ccvm.ctype _ '/' _ ccvm.code _ '.png' _ ctx.cache_key;
84     END;
85
86     # Extract MARC fields from XML
87     #   get_marc_attrs( args = { marc_xml => doc } )
88     BLOCK get_marc_attrs;
89         USE Dumper;
90         xml = args.marc_xml;
91
92         args.bibid = [];
93         FOR bibid IN xml.findnodes('//*[@tag="901"]/*[@code="c"]');
94             args.bibid.push(bibid.textContent);
95         END;
96
97         args.df_bib_list = args.bibid;
98         args.bibid = args.bibid.0; 
99
100         IF args.mr_constituent_ids.size && !args.df_bib_list.size;
101             args.df_bib_list = args.mr_constituent_ids;
102         END;
103
104
105         # Gather display field data for this record and map it
106         # to a display field map.  Hopefully, one day, this can
107         # replace the XPath below entirely.
108
109         args.display_fields = {};
110         args.hl = {};
111
112         args.hl_field = 'highlight';
113         IF CGI.param('no_highlight') || search.no_highlight;
114             args.hl_field = 'value';
115         END;
116         hl_field = args.hl_field;
117
118         junk = ctx.timelog('Fetching display fields and Using data from "' _ hl_field _ '" for rendering'); 
119         args.display_field_list = ctx.fetch_display_fields(args.df_bib_list.list);
120
121         junk = ctx.timelog('Mapping display fields for bib(s) ' _ args.df_bib_list.list.join(', ')); 
122         FOR df IN args.display_field_list;
123             df_map = ctx.search_cdfm('field', df.field).0;
124             df_name = df_map.name();
125             IF df_map.multi() == 't';
126                 IF NOT args.hl_display_fields.$df_name;
127                     args.hl_display_fields.$df_name = [];
128                     args.hl.$df_name = [];
129                 END;
130                 args.hl_display_fields.$df_name.push(df);
131                 args.hl.$df_name.push(df.$hl_field || df.value);
132             ELSIF !args.hl_display_fields.$df_name.defined;
133                 args.hl_display_fields.$df_name = df;
134                 args.hl.$df_name = df.$hl_field || df.value;
135             END;
136         END;
137         junk = ctx.timelog('Finished mapping display fields for bib(s) ' _ args.df_bib_list.list.join(', ')); 
138
139         # Map item types to schema.org types; impedance mismatch :(
140         args.schema.itemtype = {};
141         schema_typemap = {};
142
143         schema_typemap.bluray = 'Movie'; # Movie could also be TVSeries
144         schema_typemap.book = 'Book';
145         schema_typemap.braille = 'Book';
146         schema_typemap.casaudiobook = 'Book AudioObject';
147         schema_typemap.casmusic = 'MusicAlbum';
148         schema_typemap.cdaudiobook = 'Book AudioObject';
149         schema_typemap.cdmusic = 'MusicAlbum';
150         schema_typemap.dvd = 'Movie';
151         schema_typemap.eaudio = 'AudioObject';
152         schema_typemap.ebook = 'Book';
153         # schema_typemap.equip = '';
154         schema_typemap.evideo = 'Movie';
155         # schema_typemap.kit = '';
156         schema_typemap.lpbook = 'Book';
157         schema_typemap.map = 'Map';
158         # schema_typemap.microform = '';
159         schema_typemap.music = 'MusicAlbum';
160         schema_typemap.phonomusic = 'MusicAlbum';
161         # schema_typemap.phonospoken = '';
162         # schema_typemap.picture = ''; Painting or Photograph?
163         schema_typemap.score = 'Book'; # schema.org has no generic Music type
164         schema_typemap.serial = 'Periodical';
165         schema_typemap.software = 'SoftwareApplication';
166         schema_typemap.vhs = 'Movie';
167
168         schema_typemap.a = 'Book';
169         schema_typemap.e = 'Map';
170         schema_typemap.j = 'MusicAlbum';
171
172         # Hard-coded to match defaults in config.copy_status for all OPAC-visible statuses
173         schema_copy_status = {};
174         schema_copy_status.0 = '<link property="availability" href="http://schema.org/InStock" />'; # Available
175         schema_copy_status.1 = '<link property="availability" href="http://schema.org/OutOfStock" />'; # Checked out
176         schema_copy_status.5 = '<link property="availability" href="http://schema.org/PreOrder" />'; # In process
177         schema_copy_status.6 = '<link property="availability" href="http://schema.org/PreOrder" />'; # In transit
178         schema_copy_status.7 = '<link property="availability" href="http://schema.org/InStock" />'; # Reshelving
179         schema_copy_status.8 = '<link property="availability" href="http://schema.org/OutOfStock" />'; # On holds shelf
180         schema_copy_status.9 = '<link property="availability" href="http://schema.org/PreOrder" />'; # On order
181         schema_copy_status.12 = '<link property="availability" href="http://schema.org/InStoreOnly" />'; # Reserves
182
183         args.isbns = [];
184         FOR isbn IN xml.findnodes('//*[@tag="020"]/*[@code="a"]');
185             args.isbns.push(isbn.textContent);
186         END;
187
188         # UPCs can be identified either by ind1="1" or subfield 2 of "upc"
189         args.upcs = [];
190         FOR upc IN xml.findnodes('//*[@tag="024" and @ind="1"]/*[@code="a"]');
191             args.upcs.push(upc.textContent);
192         END;
193         FOR upcfield IN xml.findnodes('//*[@tag="024"]/*[@code="2" and text()="upc"]');
194             my_parent = upcfield.parentNode();
195             FOR upc IN my_parent.findnodes('./*[@code="a"]');
196                 args.upcs.push(upc.textContent);
197             END;
198         END;
199         args.upc = args.upcs.0; # use first UPC as the default
200
201         # These are URIs that link out to related works for linked data purposes,
202         # such as OCLC Work Entities like http://worldcat.org/entity/work/id/415491
203
204         # We differentiate between http://schema.org/sameAs relations, which
205         # are roughly the same as the work we're describing here, and
206         # http://schema.org/exampleOfWork which point to a broader work, of which
207         # this is a more specific edition or manifestation.
208         args.links.sameAs = [];
209         args.links.exampleOfWork = [];
210         FOR link_node IN xml.findnodes('//*[@tag="024"]/*[@code="2" and text()="uri"]');
211             my_parent = link_node.parentNode();
212             FOR link IN my_parent.findnodes('./*[@code="a"]');
213                 link_uri = link.textContent | trim;
214                 IF link_uri.search('worldcat.org/entity/work');
215                     args.links.exampleOfWork.push(link_uri);
216                 ELSE;
217                     args.links.sameAs.push(link_uri);
218                 END;
219             END;
220         END;
221         FOR lccn IN xml.findnodes('//*[@tag="010"]/*[@code="a"]');
222             lccn_num = lccn.textContent | trim;
223             args.links.sameAs.push('http://lccn.loc.gov/' _ lccn_num);
224         END;
225         FOR oclcnum IN xml.findnodes('//*[@tag="035"]/*[@code="a"]');
226             oclcnum = oclcnum.textContent | trim;
227             NEXT UNLESS oclcnum.search('^\(OCoLC\)');
228             oclcnum = oclcnum | remove('\(OCoLC\)');
229             # These prefixes are often included in the 035, even though they should not be
230             oclcnum = oclcnum | remove('ocm');
231             oclcnum = oclcnum | remove('ocn');
232             oclcnum = oclcnum | remove('on') | trim;
233             args.links.sameAs.push('http://www.worldcat.org/oclc/' _ oclcnum);
234         END;
235         args.links.sameAs = args.links.sameAs.unique;
236
237         args.issns = [];
238         FOR sub IN xml.findnodes('//*[@tag="022"]/*[@code="a"]');
239             args.issns.push(sub.textContent);
240         END;
241         args.issn = (args.issns.size) ? args.issn.0 : '';
242
243         graphic_880s = [];
244         get_graphic_880s(target_field='100');
245         get_graphic_880s(target_field='110');
246         get_graphic_880s(target_field='111');
247         args.graphic_authors = graphic_880s;
248         args.authors = [];
249         FOR author IN args.graphic_authors;
250             args.authors.push(author.primary.value);
251         END;
252         args.author = (args.authors.size) ? args.authors.0 : '';
253
254         # Include subfields 'abnp' to generate a more comprehensive title display in search results
255         titresults = xml.findnodes('//*[@tag="245"]/*[@code="a" or @code="b" or @code="n" or @code="p"]');
256         titresults_content = [];
257             FOR sub IN titresults; titresults_content.push(sub.textContent); END;
258
259         args.title = titresults_content.join(" ");
260         # Avoid ugly trailing syntax on brief titles
261         args.title = args.title | replace('[:;/]$', '');
262
263         graphic_880s = [];
264         get_graphic_880s(target_field='245');
265         args.graphic_titles = graphic_880s;
266         args.titles = [];
267         FOR title IN args.graphic_titles;
268             args.titles.push(title.primary.value);
269         END;
270         args.title_extended = (args.titles.size) ? args.titles.0 : '';
271
272         # Create a version of the title designed for sorted displays.
273         args.sort_title = args.title | upper;
274
275         # If the title has a "non-filing chaaracters" 
276         # (to logically remove leading "The " for example)
277         # chop the title. Otherwise, chop until the first alphanumeric.
278         # BTW: Template Toolkit folds 1-element arrays to scalars!
279         title_node = xml.findnodes('//*[@tag="245"]');
280
281         args.nonfiling_characters = title_node.findvalue('@ind2');
282       
283         IF (args.nonfiling_characters > 0);
284              args.sort_title = args.sort_title.substr(args.nonfiling_characters); 
285         ELSE;
286              args.sort_title = args.sort_title.replace('^[^A-Z0-9]*','');
287         END;
288       
289         args.pubplaces = [];
290         pubplace_hunt = xml.findnodes('//*[@tag="260"]/*[@code="a"]') ||
291             xml.findnodes('//*[@tag="264" and @ind2="1"]/*[@code="a"]');
292         FOR sub IN pubplace_hunt;
293             args.pubplaces.push(sub.textContent);
294         END;
295         args.pubplace = (args.pubplaces.size) ? args.pubplaces.0 : '';
296
297         args.publishers = [];
298         publishers_hunt = xml.findnodes('//*[@tag="260"]/*[@code="b"]') ||
299             xml.findnodes('//*[@tag="264" and @ind2="1"]/*[@code="b"]');
300         FOR sub IN publishers_hunt;
301             args.publishers.push(sub.textContent);
302         END;
303         args.publisher = (args.publishers.size) ? args.publishers.0 : '';
304
305         args.pubdates = [];
306         pubdates_hunt = xml.findnodes('//*[@tag="260"]/*[@code="c"]') || 
307             xml.findnodes('//*[@tag="264" and @ind2="1"]/*[@code="c"]');
308         FOR sub IN pubdates_hunt;
309             args.pubdates.push(sub.textContent);
310         END;
311         args.pubdate = (args.pubdates.size) ? args.pubdates.0 : '';
312
313         # Get RDA Copyright Info.
314         args.copyrights = [];
315         FOR sub IN xml.findnodes('//*[@tag="264" and @ind2="4"]/*[@code="c"]');
316             args.copyrights.push(sub.textContent);
317         END;
318         args.copyright = (args.copyrights.size) ? args.copyrights.0 : '';
319
320         IF args.copyright.length >= 4;
321             args.copyrightYear = args.copyright.match('(\d{4})');
322             IF args.copyrightYear;
323                 args.copyrightYear = args.copyrightYear.0;
324             END;
325         END;
326
327         # Get the RDA Production info.
328         args.producers = [];
329         FOR sub IN xml.findnodes('//*[@tag="264" and @ind2="0"]/*[@code="b"]');
330             args.producers.push(sub.textContent);
331         END;
332         args.producer = (args.producers.size) ? args.producers.0 : '';
333
334         args.prodplaces = [];
335         FOR sub IN xml.findnodes('//*[@tag="264" and @ind2="0"]/*[@code="a"]');
336             args.prodplaces.push(sub.textContent);
337         END;
338         args.prodplace = (args.prodplaces.size) ? args.prodplaces.0 : '';
339
340         args.proddates = [];
341         FOR sub IN xml.findnodes('//*[@tag="264" and @ind2="0"]/*[@code="c"]');
342             args.proddates.push(sub.textContent);
343         END;
344         args.proddate = (args.proddates.size) ? args.proddates.0 : '';
345
346         # Get the RDA Distribution args.
347         args.distributors = [];
348         FOR sub IN xml.findnodes('//*[@tag="264" and @ind2="2"]/*[@code="b"]');
349             args.distributors.push(sub.textContent);
350         END;
351         args.distributor = (args.distributors.size) ? args.distributors.0 : '';
352
353         args.distplaces = [];
354         FOR sub IN xml.findnodes('//*[@tag="264" and @ind2="2"]/*[@code="a"]');
355             args.distplaces.push(sub.textContent);
356         END;
357         args.distplace = (args.distplaces.size) ? args.distplaces.0 : '';
358
359         args.distdates = [];
360         FOR sub IN xml.findnodes('//*[@tag="264" and @ind2="2"]/*[@code="c"]');
361             args.distdates.push(sub.textContent);
362         END;
363         args.distdate = (args.distdates.size) ? args.distdates.0 : '';
364
365         # Get the RDA Manufacture args.
366         args.manufacturers = [];
367         FOR sub IN xml.findnodes('//*[@tag="264" and @ind2="3"]/*[@code="b"]');
368             args.manufacturers.push(sub.textContent);
369         END;
370         args.manufacturer = (args.manufacturers.size) ? args.manufacturers.0 : '';
371
372         args.manplaces = [];
373         FOR sub IN xml.findnodes('//*[@tag="264" and @ind2="3"]/*[@code="a"]');
374             args.manplaces.push(sub.textContent);
375         END;
376         args.manplace = (args.manplaces.size) ? args.manplaces.0 : '';
377
378         args.mandates = [];
379         FOR sub IN xml.findnodes('//*[@tag="264" and @ind2="3"]/*[@code="c"]');
380             args.mandates.push(sub.textContent);
381         END;
382         args.mandate = (args.mandates.size) ? args.mandates.0 : '';
383
384         # RDA adds 264 to the pubinfo 880 consideration mix
385         graphic_880s = [];
386         get_graphic_880s(target_field='260');
387         get_graphic_880s(target_field='264');
388         args.graphic_pubinfos = graphic_880s;
389         args.pubinfos = [];
390         FOR pubinfo IN args.graphic_pubinfos;
391             args.pubinfos.push(pubinfo.primary.value);
392         END;
393         args.pubinfo = (args.pubinfos.size) ? args.pubinfos.0 : '';
394
395         args.summaries = [];
396         FOR sub IN xml.findnodes('//*[@tag="520"]/*[@code="a"]');
397             args.summaries.push(sub.textContent);
398         END;
399         args.summary = (args.summaries.size) ? args.summaries.0 : '';
400
401         # 250 gets pride of place for edition statement, and is the
402         # only logical choice for 880 graphic fields
403         graphic_880s = [];
404         get_graphic_880s(target_field='250');
405         args.graphic_editions = graphic_880s;
406         args.editions = [];
407         FOR edition IN args.graphic_editions;
408             args.editions.push(edition.primary.value);
409         END;
410
411         ed_hunt = xml.findnodes('//*[@tag="250"]/*[@code="a"]');
412         FOR sub IN ed_hunt;
413             args.editions.push(sub.textContent);
414         END;
415         args.edition = (args.editions.size) ? args.editions.0 : '';
416
417         phys_content = [];
418         FOR sub IN xml.findnodes(
419             '//*[@tag="300"]/*[@code="a" or @code="b" or @code="c" or @code="e"]'
420         );
421             phys_content.push(sub.textContent);
422         END;
423         args.phys_desc = phys_content.join(" ");
424
425         graphic_880s = [];
426         get_graphic_880s(target_field='505');
427         args.graphic_contents = graphic_880s;
428         FOR content IN args.graphic_contents;
429             args.contents.push(content.primary.value);
430         END;
431         args.content = (args.contents.size) ? args.contents.0 : '';
432
433         # Maintain contents_list in case any custom use was made of it
434         args.contents_list = [];
435         FOR sub IN xml.findnodes('//*[@tag="505"]');
436             args.contents_list.push(sub.textContent);
437         END;
438
439         # MARC Callnumber
440         args.marc_cns = [];
441         FOR sub IN xml.findnodes('//*[@tag="092" or @tag="099"]/*');
442             args.marc_cns.push(sub.textContent);
443         END;
444         args.marc_cn = (args.marc_cns.size ) ? args.marc_cns.0 : '';
445             
446
447         # clean up the ISBN
448         args.isbn_clean = args.isbns.0.replace('\ .*', '');
449         FOR isbn IN args.isbns;
450             clean_isbn = isbn.replace('\ .*', '');
451             clean_isbn = clean_isbn.replace('-', '');
452             IF clean_isbn.length == 13;
453                 args.gtin13 = clean_isbn;
454                 LAST;
455             END;
456         END;
457
458         IF ebook_api.overdrive.enabled == 'true';
459             FOR marc037 IN xml.findnodes('//*[@tag="037"]');
460                 marc037_id = marc037.findnodes('./*[@code="a"]').textContent;
461                 marc037_source = marc037.findnodes('./*[@code="b"]').textContent;
462                 IF marc037_source.match('OverDrive') AND marc037_id;
463                     args.overdrive_id = marc037_id;
464                     LAST;
465                 END;
466             END;
467         END;
468
469         # Extract the 856 URLs that are not otherwise represented by asset.uri's
470         args.online_res = [];
471         FOR node IN xml.findnodes('//*[@tag="856" and @ind1="4" and (@ind2="0" or @ind2="1" or @ind2="2")]');
472             IF node.findnodes('./*[@code="9" or @code="w" or @code="n"]'); NEXT; END; # asset.uri's
473             lind2 = node.getAttribute('ind2') || '';
474             ltype = '';
475             IF lind2 == '0'; ltype = l('Electronic Resource:'); END;
476             IF lind2 == '1'; ltype = l('Version of Resource:'); END;
477             IF lind2 == '2'; ltype = l('Related Resource:'); END;
478             label = node.findnodes('./*[@code="y"]');
479             notes = node.findnodes('./*[@code="z" or @code="3"]');
480             FOR href IN node.findnodes('./*[@code="u"]');
481                 NEXT UNLESS href;
482                 # it's possible for multiple $u's to exist within 1 856 tag.
483                 # in that case, honor the label/notes data for the first $u, but
484                 # leave any subsequent $u's as unadorned href's. 
485                 # use href/link/note keys to be consistent with args.uri's
486                 args.online_res.push({
487                     href => href.textContent, 
488                     link => (loop.first AND label) ? label.textContent : href.textContent,
489                     note => (loop.first) ? notes.textContent : '',
490                     type => ltype
491                 });
492             END;
493         END;
494  
495         args.holdings = [];
496         args.uris = [];
497         args.issns = [];
498         args.resolver_isbns = [];
499         args.resolver_issns = [];
500
501         # we use $9 of ISBN and ISSN as a flag for e-version
502         FOR resolver_isbn IN xml.findnodes('//*[@tag="020"]/*[@code="9"]');
503             IF resolver_isbn.textContent == "SFX" || resolver_isbn.textContent == "CUFTS";
504                 my_parent = resolver_isbn.parentNode();
505                 FOR resolver_isbn_val IN my_parent.findnodes('./*[@code="a"]');
506                     args.resolver_isbns.push(
507                         resolver_isbn_val.textContent.replace('-', '').replace('\ .*', '')
508                     );
509                 END;
510             END;
511         END;
512
513         FOR resolver_issn IN xml.findnodes('//*[@tag="022"]/*[@code="9"]');
514             IF resolver_issn.textContent == "SFX" || resolver_issn.textContent == "CUFTS";
515                 my_parent = resolver_issn.parentNode();
516                 FOR resolver_issn_val IN my_parent.findnodes('./*[@code="a"]');
517                     args.resolver_issns.push(
518                         resolver_issn_val.textContent.replace('[^\d\-X]', '')
519                     );
520                 END;
521             END;
522         END;
523
524         # now snag all issns 
525         FOR rawissn IN xml.findnodes('//*[@tag="022"]/*[@code="a"]');
526             args.issns.push(
527                 rawissn.textContent.replace('[^\d\-X]', '')
528             );
529         END;
530
531         ou_hiding_disabled = ctx.org_hiding_disabled();
532
533         # explicitly grabbing the first bib_source node, though there should be only one anyway
534         bib_source = xml.findnodes('//*[local-name()="bib_source"][1]');
535         args.bib_source.id = bib_source.getAttribute('ident');
536         args.bib_source.source = bib_source.textContent;
537
538         FOR volume IN xml.findnodes('//*[local-name()="volumes"]/*[local-name()="volume"]');
539
540             # Check volume visibility - could push this into XPath
541             vol.label = volume.getAttribute('label');
542
543             # Prepend prefix, if any
544             prefix = volume.findnodes('./*[local-name()="call_number_prefix"][@ident!="-1"]');
545             IF prefix.getAttribute('label') != '';
546                 vol.label = prefix.getAttribute('label') _ " " _ vol.label;
547             END;
548
549             # Append prefix, if any
550             suffix = volume.findnodes('./*[local-name()="call_number_suffix"][@ident!="-1"]');
551             IF suffix.getAttribute('label') != '';
552                 vol.label = vol.label _ " " _ suffix.getAttribute('label');
553             END;
554
555             vol.id = volume.getAttribute('id');
556             NEXT IF volume.getAttribute('opac_visible') == 'false';
557             NEXT IF volume.getAttribute('deleted') == 'true';
558
559             IF vol.label == '##URI##';
560                 FOR uri IN volume.findnodes('./*[local-name()="uris"]/*[local-name()="uri"]');
561                     res = {};
562                     res.href = uri.getAttribute('href');
563                     res.link = uri.getAttribute('label');
564                     res.note = uri.getAttribute('use_restriction');
565                     # Avoid displaying the href as the link text if we can display the note instead
566                     IF res.link == res.href AND res.note;
567                         res.link = res.note;
568                         res.note = '';
569                     END;
570
571                     # Unique-ify the URI list because multiple $9's on the same link can cause dupes.
572                     found_u = 0;
573                     FOR test_u IN args.uris;
574                         IF test_u.href == res.href AND test_u.link == res.link AND test_u.note == res.note;
575                             found_u = 1;
576                             LAST;
577                         END;
578                     END;
579                     IF NOT found_u;
580                         args.uris.push(res);
581                     END;
582
583                     IF ebook_api.ebook_test.enabled == 'true';
584                         IF !args.ebook_test_id;
585                             FOR base_uri IN ebook_api.ebook_test.base_uris;
586                                 IF res.href.match(base_uri);
587                                     args.ebook_test_id = res.href.remove(base_uri);
588                                     LAST;
589                                 END;
590                             END;
591                         END;
592                     END;
593
594                     IF ebook_api.oneclickdigital.enabled == 'true';
595                         # A record might conceivably have multiple OneClickdigital URIs,
596                         # but we use (the same) ISBN as the ebook ID in each case.
597                         IF !args.oneclickdigital_id;
598                             FOR base_uri IN ebook_api.oneclickdigital.base_uris;
599                                 IF res.href.match(base_uri);
600                                     # found a OneClickdigital URI, let's grab our ID and move on
601                                     args.oneclickdigital_id = clean_isbn;
602                                     LAST;
603                                 END;
604                             END;
605                         END;
606                     END;
607
608                     IF ebook_api.overdrive.enabled == 'true';
609                         # Ideally we already have an OverDrive record ID from MARC 037 (see above).
610                         # But for older records, it will be embedded in the URI in MARC 856.
611                         IF !args.overdrive_id;
612                             FOR base_uri IN ebook_api.overdrive.base_uris;
613                                 IF res.href.match(base_uri);
614                                     args.overdrive_id = res.href.remove('^.*/ContentDetails.htm\?ID=');
615                                     LAST;
616                                 END;
617                             END;
618                         END;
619                     END;
620                 END;
621
622                 NEXT;
623             ELSE;
624                 copies = volume.findnodes('./*[local-name()="copies"]/*[local-name()="copy"]');
625                 FOR copy IN copies;
626                     parts = copy.findnodes('./*[local-name()="monograph_parts"]/*[local-name()="monograph_part"]');
627                     part_label = '';
628                     FOREACH part IN parts;
629                         part_label = part.getAttribute('label');
630                         LAST IF part_label != '';
631                     END;
632                     # Check copy visibility
633                     cp.deleted = copy.getAttribute('deleted');    
634                     cp.visible = copy.getAttribute('opac_visible');
635                     NEXT IF (cp.deleted == 'true' OR cp.visible == 'false');
636
637                     # Iterate through all of the children to determine visibility
638                     FOR node IN cp.childNodes;
639                         NEXT IF cp.visible == 'false';
640                         vis = node.getAttribute('opac_visible');
641                         del = node.getAttribute('deleted');
642                         IF vis == 'false' or del == 'true';
643                             cp.visible = 'false';
644                         END;
645                     END;
646
647                     NEXT IF cp.visible == 'false';
648                     
649                     loc = copy.findnodes('./*[local-name()="location"]');
650                     NEXT IF loc.getAttribute('opac_visible') == 'false';
651
652                     circlib = copy.findnodes('./*[local-name()="circlib"]');
653                     NEXT IF circlib.getAttribute('opac_visible') == 'false';
654
655                     status = copy.findnodes('./*[local-name()="status"]');
656                     NEXT IF status.getAttribute('opac_visible') == 'false';
657
658                     # extract the circ_lib id from the circ_lib node
659                     circ_lib = copy.findnodes('./*[local-name()="circ_lib"]');
660                     circ_lib_id = circ_lib.getAttribute('id').replace('.*/', '');
661
662                     UNLESS ou_hiding_disabled;
663                         NEXT UNLESS ctx.org_within_hiding_scope(circ_lib_id);
664                     END;
665
666                     holding = {
667                         circ_lib => circ_lib_id,
668                         label => vol.label,
669                         part_label => part_label,
670                         location => loc.textContent,
671                         library => circlib.textContent,
672                         status => status.textContent,
673                         status_code => status.getAttribute('ident'),
674                         barcode => copy.getAttribute('barcode'),
675                         owner => volume.getAttribute('lib')
676                     };
677                     args.holdings.push(holding);
678                     part_label = '';
679                 END;
680             END;
681         END;
682
683         # Extract the copy count summary
684         count_type = (ctx.is_staff) ? 'staff' : 'public';
685
686         # Consortial copy count summary first
687         xpath = '//*[local-name()="counts"]/*[local-name()="count"][@type="' _ count_type _ '"]';
688         args.copy_counts = {};
689         FOR node IN xml.findnodes(xpath);
690             FOR attr IN ['count', 'available', 'unshadow', 'transcendant', 'org_unit']; 
691                 depth = node.getAttribute('depth');
692                 count_org_unit = node.getAttribute('org_unit');
693                 args.copy_counts.$depth.$attr = node.getAttribute(attr);
694                 args.org_copy_counts.$count_org_unit.$attr = node.getAttribute(attr);
695             END;
696         END;
697
698         # Get preferred library copy count
699         args.plib_copy_counts = {};
700         count_type = 'pref_lib';
701         xpath = '//*[local-name()="counts"]/*[local-name()="count"][@type="' _ count_type _ '"]';
702         FOR node IN xml.findnodes(xpath);
703             FOR attr IN ['count', 'available', 'unshadow', 'transcendant', 'org_unit']; 
704                 depth = node.getAttribute('depth');
705                 args.plib_copy_counts.$depth.$attr = node.getAttribute(attr);
706             END;
707         END;
708
709         mmr_unique_bib = [];
710         # "mattype" == "custom marc format specifier"
711         icon_style = ctx.get_cgf('opac.icon_attr').value || 'item_type';
712         formats_xpath = '//*[local-name()="attributes"]/*[local-name()="field"][@name="' _ icon_style _ '"]';
713
714         args.all_formats = [];
715         FOR node IN xml.findnodes(formats_xpath);
716             IF node AND node.textContent;
717                 ccvm = ctx.get_ccvm(node.getAttribute('cvmid'));
718                 NEXT IF ccvm.opac_visible == 'f';
719
720                 format = {};
721                 this_icon_source = node.getAttribute('source_list');
722                 including = 'F';
723                 # Just display everything if we don't have the data
724                 IF NOT args.mr_constituent_ids OR NOT this_icon_source;
725                     including = 'T';
726                 # We have an array of search-included bib IDs and we have the bib ID that this icon belongs to
727                 ELSE;
728                     FOR mr_constituent_id IN args.mr_constituent_ids;
729                         IF this_icon_source.split(',').grep('^' _ mr_constituent_id _ '$' ).size;
730                             # This bib appears to be in the array of filtered bibs
731                             including = 'T';
732                         END;
733                     END;
734                 END;
735                 IF including == 'T';
736                     type = ccvm.code.remove('-'); # blu-ray to bluray
737                     format.label = ccvm.search_label || ccvm.value;
738                     format.icon = PROCESS get_ccvm_icon ccvm=ccvm;
739                     format.itemtype = schema_typemap.$type || 'CreativeWork';
740                     format.search_format = ccvm.code;
741                     format.source_bibs = this_icon_source.split(',');
742                     FOR bib_source IN format.source_bibs;
743                         IF NOT mmr_unique_bib.grep(bib_source).size; mmr_unique_bib.push(bib_source); END;
744                     END;
745                     args.all_formats.push(format); # metarecords want all formats
746
747                     IF !args.format_label;
748                         # use the first format as the default
749                         args.format_label = format.label;
750                         args.schema.itemtype = format.itemtype;
751                         args.format_icon = format.icon;
752                     END;
753                 END;
754             END;
755         END;
756
757         formats_xpath = '//*[local-name()="attributes"]/*[local-name()="field"][@name="item_lang"]';
758         args.all_lang = [];
759         FOR node IN xml.findnodes(formats_xpath);
760             IF node AND node.textContent;
761                 ccvm = ctx.get_ccvm(node.getAttribute('cvmid'));
762                 NEXT IF ccvm.opac_visible == 'f';
763
764                 lang = {};
765                 this_source = node.getAttribute('source_list');
766                 including = 'F';
767                 # Just display everything if we don't have the data
768                 IF NOT args.mr_constituent_ids OR NOT this_source;
769                     including = 'T';
770                 # We have an array of search-included bib IDs and we have the bib ID that this lang belongs to
771                 ELSE;
772                     FOR mr_constituent_id IN args.mr_constituent_ids;
773                         IF this_source.split(',').grep('^' _ mr_constituent_id _ '$' ).size;
774                             # This bib appears to be in the array of filtered bibs
775                             including = 'T';
776                         END;
777                     END;
778                 END;
779                 IF including == 'T';
780                     lang.label = ccvm.search_label || ccvm.value;
781                     lang.itemtype = schema_typemap.$type || 'CreativeWork';
782                     lang.search_format = node.textContent;
783                     lang.source_bibs = this_source.split(',');
784                     FOR bib_source IN lang.source_bibs;
785                         IF NOT mmr_unique_bib.grep(bib_source).size; mmr_unique_bib.push(bib_source); END;
786                     END;
787
788                     args.all_lang.push(lang); # metarecords want all
789                 END;
790             END;
791         END;
792         args.mmr_unique_bib = mmr_unique_bib;
793
794         IF args.ebook_test_id;
795             args.ebook.ebook_id = args.ebook_test_id;
796             args.ebook.vendor = 'ebook_test';
797         ELSIF args.oneclickdigital_id;
798             args.ebook.ebook_id = args.oneclickdigital_id;
799             args.ebook.vendor = 'oneclickdigital';
800         ELSIF args.overdrive_id;
801             args.ebook.ebook_id = args.overdrive_id;
802             args.ebook.vendor = 'overdrive';
803         END;
804
805     END;
806
807     # Get the library or location group
808     # get_library()
809     # magically upgrades any use of 'loc' to 'locg', 
810     # which is a superset of 'loc'.
811     BLOCK get_library;
812         loc_name = 'locg';
813
814         # Location groups don't have shortnames, so they'll take priority
815         # (_org doesn't contain the group and breaks the selector).
816         loc_value = ctx.copy_location_group ? CGI.param(loc_name)
817                   : ctx.copy_location_group_org # resolved locg
818                     || CGI.param(loc_name) || CGI.param('loc') || ctx.search_ou;
819     END;
820
821 -%]
822
823
824 [%- BLOCK carousels;
825     config = {
826         animated => 0,
827         animation_interval => 5,
828         width => 5,
829         sm_width => 3,
830         xs_width => 2,
831     };
832     config.import(args);
833     carousels = [];
834     IF config.carousel_id;
835         carousels.push(ctx.get_carousel(config.carousel_id));
836     ELSE;
837         visible_carousels = ctx.get_visible_carousels();
838         FOREACH car IN visible_carousels;
839             carousel = ctx.get_carousel(car.carousel);
840             IF car.override_name.defined;
841                 carousel.name = car.override_name;
842             END;
843             carousels.push(carousel);
844         END; 
845     END;
846     IF carousels.size > 0;
847 %]
848 <script type="text/javascript" src="[% ctx.media_prefix %]/js/ui/default/common/build/js/glide/glide.min.js[% ctx.cache_key %]"></script>
849 <div class="carousels">
850 [% FOREACH carousel IN carousels;
851    IF carousel.bibs.size > 0;
852 %]
853 <div class="carousel">
854 <div class="carousel-title">[% carousel.name %]</div>
855 <div class="carousel-body glide" id="carousel-[% carousel.id %]">
856   <div class="glide__track" data-glide-el="track">
857     <ul class="glide__slides">
858 [% FOREACH bib IN carousel.bibs; %]
859       <li class="glide__slide"><div class="carousel-entry">
860         <a href="[% mkurl(ctx.opac_root  _ '/record/' _ bib.id) %]">
861           <img alt="[% l('Book cover') %]" class="carousel-entry-image" src="[% ctx.media_prefix %]/opac/extras/ac/jacket/medium/r/[% bib.id | uri %]"></img>
862         </a><br>
863         <span class="carousel-entry-title"><a href="[% mkurl(ctx.opac_root  _ '/record/' _ bib.id) %]">[% bib.title | html %]</a></span>
864       </div></li>
865 [% END; %]
866     </ul>
867   </div>
868   <div class="glide__arrows" data-glide-el="controls">
869     <button class="glide__arrow glide__arrow--left" data-glide-dir="<">[% l('prev') %]</button>
870     <button class="glide__arrow glide__arrow--right" data-glide-dir=">">[% l('next') %]</button>
871   </div>
872 </div>
873 </div>
874 <script>
875     var glide = new Glide('#carousel-[% carousel.id %]', {
876         type: 'carousel',
877         rewind: false,
878         perView: [% config.width %],
879         breakpoints: {
880             992: {
881                 perView: [% config.sm_width %]
882             },
883             768: {
884                 perView: [% config.xs_width %]
885             }
886         },
887         startAt: 0,
888         [% IF config.animated %] autoplay: [% config.animation_interval * 1000 %],[% END %]
889     });
890     glide.mount();
891 </script>
892 [% END; %]
893 [% END; %]
894 </div>
895 [% END -%]
896 [% END -%]
897 [% MACRO accordion(str, trunc_length, element) BLOCK;
898     IF truncate_contents != 1;
899         ctx.defang_string(str);
900     ELSE;
901         UNLESS trunc_length;
902             trunc_length = contents_truncate_length || 100;
903         END;
904         IF str.length > trunc_length;
905             accordion_res = ctx.split_for_accordion(str, trunc_length);
906             str = accordion_res.0;
907             IF accordion_res.1;
908                 str = str _ " <a onclick='toggleAccordion(this, " _ element _ ")'>" _ l('Read More') _ "</a>";
909             END;
910             str;
911         ELSE;
912             ctx.defang_string(str);
913         END;
914     END;
915 END; %]