]> git.plutz.net Git - cgilite/blob - cgi.sh
replace echo by the more unambiguous builtin printf
[cgilite] / cgi.sh
1 #!/bin/zsh
2
3 # Copyright 2014,2015 Paul Hänsch
4 #
5 # This file is part of shcgi.
6
7 # shcgi is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11
12 # shcgi is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU Affero General Public License for more details.
16
17 # You should have received a copy of the GNU Affero General Public License
18 # along with shcgi.  If not, see <http://www.gnu.org/licenses/>. 
19
20 declare -A _GET
21 declare -A _POST
22 declare -A _REF
23
24 [ -z "$HTTP_REFERER" ] && HTTP_REFERER="./"
25
26 cgi_get() {  # parse HTTP GET string
27   debug "== CGI DATA: GET =="
28   printf '%s\n' "$QUERY_STRING" |tr '&' '\n' |while read query; do
29     key="$(printf %s "$query" |sed -r 's:^([a-zA-Z0-9_-]*)=(.*)$:\1:')"
30     val="$(printf %s "$query" |sed -r 's:^([a-zA-Z0-9_-]*)=(.*)$:\2:')"
31     _GET["$key"]="$(printf "$(printf %s "$val" |sed 's:+: :g;s:\\:\\\\:g;s:%:\\x:g')")"
32     debug "_GET[$key] => $val"
33   done
34 }
35
36 cgi_post() {  # parse HTTP POST string
37   debug "== CGI DATA: POST =="
38   sed -u 1q |tr '&' '\n' |while read query; do
39     key="$(printf %s "$query" |sed -r 's:^([a-zA-Z0-9_-]*)=(.*)$:\1:')"
40     val="$(printf %s "$query" |sed -r 's:^([a-zA-Z0-9_-]*)=(.*)$:\2:')"
41     value="$(printf "$(printf %s "$val" |sed 's:+: :g;s:\\:\\\\:g;s:%:\\x:g;')")"
42     if [ -n "$_POST[\"$key\"]" ]; then
43       n=0
44       while [ -n "$_POST[\"$key$n\"]" ]; do n=$(($n + 1)); done
45       _POST["$key$n"]="$value"
46     else
47       _POST["$key"]="$value"
48     fi
49     debug "_POST[$key] => $value"
50   done
51 }
52
53 cgi_refdata() { # Parse GET data from referer
54   debug "== CGI DATA: REFERER =="
55   printf '%s\n' "$HTTP_REFERER" |cut -d'?' -f2- |tr '&' '\n' |while read query; do
56     key="$(printf %s "$query" |sed -r 's:^([a-zA-Z0-9_-]*)=(.*)$:\1:')"
57     val="$(printf %s "$query" |sed -r 's:^([a-zA-Z0-9_-]*)=(.*)$:\2:')"
58     _REF["$key"]="$(printf "$(printf %s "$val" |sed 's:+: :g;s:\\:\\\\:g;s:%:\\x:g')")"
59     debug "_REF[$key] => $val"
60   done
61 }
62
63 urlsave(){
64   printf %s "$*" |sed 's:%:\%25:g;s:\?:\%3F:g;s:&:\%26:g;s:'\'':\%27:g;s: :\%20:g;s:!:\%21:g;s:(:\%28:g;s:):\%29:g;s:":\%22:g;'
65 }