fix crash when importing/saving bib with '&' in TCN value
[evergreen-equinox.git] / Open-ILS / src / sql / Pg / 002.functions.config.sql
index afd2b2b..99f98d8 100644 (file)
@@ -422,6 +422,8 @@ $f$ LANGUAGE PLPERLU;
 CREATE OR REPLACE FUNCTION maintain_901 () RETURNS TRIGGER AS $func$
 DECLARE
     use_id_for_tcn BOOLEAN;
+    norm_tcn_value TEXT;
+    norm_tcn_source TEXT;
 BEGIN
     -- Remove any existing 901 fields before we insert the authoritative one
     NEW.marc := REGEXP_REPLACE(NEW.marc, E'<datafield[^>]*?tag="901".+?</datafield>', '', 'g');
@@ -433,14 +435,21 @@ BEGIN
 
         IF use_id_for_tcn = 't' THEN
             NEW.tcn_value := NEW.id;
+            norm_tcn_value := NEW.tcn_value;
+        ELSE
+            -- yes, ampersands can show up in tcn_values ...
+            norm_tcn_value := REGEXP_REPLACE(NEW.tcn_value, E'&(?!\\S+;)', '&amp;', 'g');
         END IF;
+        -- ... and TCN sources
+        -- FIXME we have here yet another (stub) version of entityize
+        norm_tcn_source := REGEXP_REPLACE(NEW.tcn_source, E'&(?!\\S+;)', '&amp;', 'g');
 
         NEW.marc := REGEXP_REPLACE(
             NEW.marc,
             E'(</(?:[^:]*?:)?record>)',
             E'<datafield tag="901" ind1=" " ind2=" ">' ||
-                '<subfield code="a">' || NEW.tcn_value || E'</subfield>' ||
-                '<subfield code="b">' || NEW.tcn_source || E'</subfield>' ||
+                '<subfield code="a">' || norm_tcn_value || E'</subfield>' ||
+                '<subfield code="b">' || norm_tcn_source || E'</subfield>' ||
                 '<subfield code="c">' || NEW.id || E'</subfield>' ||
                 '<subfield code="t">' || TG_TABLE_SCHEMA || E'</subfield>' ||
                 CASE WHEN NEW.owner IS NOT NULL THEN '<subfield code="o">' || NEW.owner || E'</subfield>' ELSE '' END ||