-vcf_escape(){
- for each in "$@"; do
- printf %s\\n "$each" \
- | sed -r ':X;$!{N;bX}; s;\r\n;\n;g; s;([;,\\]);\\\1;g; s;\n;\\n;g;'
- done \
- | sed -r ':X;$!{N;bX}; s;\n;\;;g'
-}
-
-[ "${_POST[hi_select]}" = "list" ] || _POST[hi_company]="${_POST[hi_other]}"
-[ -n "${_POST[hi_company]}${_POST[hi_number]}${_POST[hi_status]}" ] \
-&& _POST[X-HEALTH-INSURANCE]="$(vcf_escape "${_POST[hi_company]}" "${_POST[hi_number]}" "${_POST[hi_status]}")"
-
-sed -r 's;$;\r;' >"$tempfile" <<EOF
-BEGIN:VCARD
-VERSION:4.0
-N:$(vcf_escape "${_POST[0N]}" "${_POST[1N]}" "${_POST[2N]}" "${_POST[3N]}" "${_POST[4N]}")
-UID:${_POST[UID]}
-$(
- for field in $VCF_FIELDS; do for key in $field $field{0..100}; do
- [ -z "${_POST[$key]+x}" ] && break
- [ -z "${_POST[$key]}" ] && continue
- case "$key" in
- (TEL[0-9]*)
- printf '%s;TYPE=%s:%s\r\n' "${field}" "${_POST[phonetype${key#TEL}]}" "$(vcf_escape "${_POST[$key]}")"
- ;;
- (X-HEALTH-INSURANCE)
- printf '%s:%s\r\n' "${field}" "${_POST[$key]}"
+action="$(POST action)"
+newfield="$(POST newfield |grep -m 1 -xE '[A-Z][A-Z0-9-]*')"
+
+if printf '%s\n' "$action" |grep -qxE 'addfield [A-Z][A-Z0-9]*'; then
+ newfield="${action##* }"
+ action=addfield
+fi
+
+if ! tempfile=$(CHECK_SLOCK "$cardfile"); then
+ SET_COOKIE 0 message="NO VALID FILE LOCK"
+ REDIRECT "/cards/?o=${order}&f=${filter}&e=${card}"
+ exit 0
+elif [ "$(POST tid)" != "$(transid "$tempfile")" ]; then
+ SET_COOKIE 0 message="INVALID TRANSACTION ID"
+ REDIRECT "/cards/?o=${order}&f=${filter}&e=${card}"
+ exit 0
+fi
+
+# [ "${_POST[hi_select]}" = "list" ] || _POST[hi_company]="${_POST[hi_other]}"
+# [ -n "${_POST[hi_company]}${_POST[hi_number]}${_POST[hi_status]}" ] \
+# && _POST[X-HEALTH-INSURANCE]="$(pdi_escape "${_POST[hi_company]}" "${_POST[hi_number]}" "${_POST[hi_status]}")"
+
+# vcf="$(pdi_load "$cardfile")"
+vcf="$(pdi_load "$tempfile")"
+
+vcf="$(pdi_update_value "$vcf" N 1 "$(pdi_escape "$(POST 1N)" "$(POST 2N)" "$(POST 3N)" "$(POST 4N)" "$(POST 5N)")")"
+vcf="$(pdi_update_value "$vcf" FN 1 "$(pdi_escape "$(POST 4N) $(POST 2N) $(POST 3N) $(POST 1N) $(POST 5N)" \
+ | sed -E 's;^ +;;; s; +$;;; s; +; ;g;')" )"
+
+for field in $(POST_KEYS |grep -xE '[A-Z][A-Z0-9-]*'); do
+ for cnt in $(seq 1 $(POST_COUNT "$field")); do
+ case "$field" in
+ # (TEL)
+ # printf '%s;TYPE=%s:%s\r\n' "${field}" "${_POST[phonetype${key#TEL}]}" "$(pdi_escape "$(POST "$field" "$cnt")")"
+ # ;;
+ X-HEALTH-INSURANCE)
+ hi_select="$(POST "$field" "$cnt")"
+ if [ "$hi_select" = list ]; then
+ vcf="$(pdi_update_value "$vcf" "$field" "$cnt" "$(pdi_escape "$(POST "hi_company" "$cnt")" \
+ "$(POST "hi_number" "$cnt")" \
+ "$(POST "hi_status" "$cnt")" \
+ )")"
+ elif [ "$hi_select" = other ]; then
+ vcf="$(pdi_update_value "$vcf" "$field" "$cnt" "$(pdi_escape "$(POST "hi_other" "$cnt")" \
+ "$(POST "hi_number" "$cnt")" \
+ "$(POST "hi_status" "$cnt")" \
+ )")"
+ fi