module CGIUtils where
import Buffer
import HtmlView
import Utils
import Control.Exception
import Control.Monad
import Data.List
import qualified Data.Map as Map
import Data.Maybe
import Network.NewCGI hiding (Html)
import Network.URI
import Text.XHtml
outputHtml :: Html -> CGI CGIResult
outputHtml = output . renderHtml
handleError :: Exception -> CGI CGIResult
handleError ex = do
setHeader "Status" "500 Program Error"
outputHtml $ mkErrorPage (show ex)
getInputOrFail :: String -> CGI String
getInputOrFail f = getInput f >>= maybeM ("Input " ++ f ++ " not given")
getInputBufferOrFail :: String -> CGI Buffer
getInputBufferOrFail f = getInputFPS f >>= maybeM ("Input " ++ f ++ " not given")
readInputWithDefault :: Read a => a -> String -> CGI a
readInputWithDefault d = fmap (fromMaybe d) . readInput
-- | Prefers the second table on collisions.
-- FIXME: doesn't work when there are multiple values with
-- the same name.
tableUnion :: [(String,String)] -> [(String,String)] -> [(String,String)]
tableUnion xs ys = Map.toList (Map.fromList ys `Map.union` Map.fromList xs)
-- | Format name-value pairs as application\/x-www-form-urlencoded.
formEncode :: [(String,String)] -> String
formEncode xs =
concat $ intersperse "&" [urlEncode n ++ "=" ++ urlEncode v | (n,v) <- xs]
-- | Convert a single value to the application\/x-www-form-urlencoded encoding.
urlEncode :: String -> String
urlEncode = replace ' ' '+' . escapeURIString okChar
where okChar c = c == ' ' ||
(isUnescapedInURI c && c `notElem` "&=+")
-- | Replace all instances of a value in a list by another value.
replace :: Eq a =>
a -- ^ Value to look for
-> a -- ^ Value to replace it with
-> [a] -- ^ Input list
-> [a] -- ^ Output list
replace x y = map (\z -> if z == x then y else z)