1 CREATE OR REPLACE FUNCTION evergreen.maintain_901 () RETURNS TRIGGER AS $func$
4 use MARC::File::XML (BinaryEncoding => 'UTF-8');
7 use Unicode::Normalize;
9 MARC::Charset->assume_unicode(1);
11 my $schema = $_TD->{table_schema};
12 my $marc = MARC::Record->new_from_xml($_TD->{new}{marc});
14 my @old901s = $marc->field('901');
15 $marc->delete_fields(@old901s);
17 if ($schema eq 'biblio') {
18 my $tcn_value = $_TD->{new}{tcn_value};
20 # Set TCN value to record ID?
21 my $id_as_tcn = spi_exec_query("
23 FROM config.global_flag
24 WHERE name = 'cat.bib.use_id_for_tcn'
26 if (($id_as_tcn->{processed}) && $id_as_tcn->{rows}[0]->{enabled} eq 't') {
27 $tcn_value = $_TD->{new}{id};
28 $_TD->{new}{tcn_value} = $tcn_value;
31 my $new_901 = MARC::Field->new("901", " ", " ",
33 "b" => $_TD->{new}{tcn_source},
34 "c" => $_TD->{new}{id},
38 if ($_TD->{new}{owner}) {
39 $new_901->add_subfields("o" => $_TD->{new}{owner});
42 if ($_TD->{new}{share_depth}) {
43 $new_901->add_subfields("d" => $_TD->{new}{share_depth});
46 $marc->append_fields($new_901);
47 } elsif ($schema eq 'authority') {
48 my $new_901 = MARC::Field->new("901", " ", " ",
49 "c" => $_TD->{new}{id},
52 $marc->append_fields($new_901);
53 } elsif ($schema eq 'serial') {
54 my $new_901 = MARC::Field->new("901", " ", " ",
55 "c" => $_TD->{new}{id},
57 "o" => $_TD->{new}{owning_lib},
60 if ($_TD->{new}{record}) {
61 $new_901->add_subfields("r" => $_TD->{new}{record});
64 $marc->append_fields($new_901);
66 my $new_901 = MARC::Field->new("901", " ", " ",
67 "c" => $_TD->{new}{id},
70 $marc->append_fields($new_901);
73 my $xml = $marc->as_xml_record();
75 $xml =~ s/^<\?xml.+\?\s*>//go;
76 $xml =~ s/>\s+</></go;
79 # Embed a version of OpenILS::Application::AppUtils->entityize()
80 # to avoid having to set PERL5LIB for PostgreSQL as well
82 # If we are going to convert non-ASCII characters to XML entities,
83 # we had better be dealing with a UTF8 string to begin with
84 $xml = decode_utf8($xml);
88 # Convert raw ampersands to entities
89 $xml =~ s/&(?!\S+;)/&/gso;
91 # Convert Unicode characters to entities
92 $xml =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
94 $xml =~ s/[\x00-\x1f]//go;
95 $_TD->{new}{marc} = $xml;
98 $func$ LANGUAGE PLPERLU;