Skip to content
This repository
Fetching contributors…

Cannot retrieve contributors at this time

file 186 lines (166 sloc) 6.508 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
(ns foreclojure.utils
  (:use (hiccup [core :only [html]]
                [page-helpers :only [doctype include-css
                                     javascript-tag link-to include-js]]
                [form-helpers :only [label]])
        [amalloy.utils.transform :only [transform-if]]
        somnium.congomongo
        [foreclojure.config])
  (:require [sandbar.stateful-session :as session]
            (ring.util [response :as response])
            [clojure.walk :as walk])
  (:import java.net.URLEncoder
           org.apache.commons.mail.SimpleEmail))

(def ^{:dynamic true} *url* nil)

(defn wrap-uri-binding [handler]
  (fn [req]
    (binding [*url* (:uri req)]
      (handler req))))

(defmacro dbg [x]
  `(let [x# ~x] (println '~x "=" x#) x#))

(defmacro assuming
  "Guard body with a series of tests. Each clause is a test-expression
followed by a failure value. Tests will be performed in order; if
each test succeeds, then body is evaluated. Otherwise, fail-expr is
evaluated with the symbol 'why bound to the failure value associated
with the failing test."
  [[& clauses] body & [fail-expr]]
  `(if-let [[~'why]
            (cond
             ~@(mapcat (fn [[test fail-value]]
                         [`(not ~test) [fail-value]])
                       (partition 2 clauses)))]
     ~fail-expr
     ~body))

(defn login-url
  ([] (login-url *url*))
  ([location]
     (str "/login?location=" (URLEncoder/encode location))))

(defn login-link
  ([] (login-link "Log in" *url*))
  ([text] (login-link text *url*))
  ([text location]
     (html
      (link-to (login-url location)
               text))))

;; Assuming that it will always need SSL. Will make it more flexible later.
(defn send-email [{:keys [from to subject body]}]
  (let [{:keys [host port user pass]} config
        base (doto (SimpleEmail.)
               (.setHostName host)
               (.setSSL true)
               (.setFrom from)
               (.setSubject subject)
               (.setMsg body)
               (.setAuthentication user pass))]
    (doseq [person to] (.addTo base person))
    (.send base)))

(defn flash-fn [type]
  (fn [msg url]
    (session/flash-put! type msg)
    (response/redirect url)))

(def flash-error (flash-fn :error))
(def flash-msg (flash-fn :message))

(defmacro def-page [page-name [& args] & code]
  `(defn ~page-name [~@args]
     (html-doc
      ~@code)))

(defn from-mongo [data]
  (walk/postwalk (transform-if float? int)
                 data))

(defn get-user [username]
  (from-mongo
   (fetch-one :users :where {:user username})))

(defmacro with-user [[user-binding] & body]
  `(if-let [username# (session/session-get :user)]
     (let [~user-binding (get-user username#)]
       ~@body)
     [:span.error "You must " (login-link) " to do this."]))

(defn form-row [[type name info]]
  [:tr
   [:td (label name info)]
   [:td (type name)]])

(defn row-class [x]
  {:class (if (even? x)
            "evenrow"
            "oddrow")})

(defn user-attribute [attr]
  (fn [username]
    (attr (from-mongo
           (fetch-one :users
                      :where {:user username}
                      :only [attr])))))

(def get-solved (comp set (user-attribute :solved)))
(def approver? (user-attribute :approver))

(defn can-submit? [username]
  (and (:problem-submission config)
       (>= (count (get-solved username))
           (:advanced-user-count config))))

(defn html-doc [& body]
  (let [user (session/session-get :user)]
    (html
     (doctype :html5)
     [:html
      [:head
       [:title "4Clojure"]
       [:link {:rel "alternate" :type "application/atom+xml" :title "Atom" :href "http://4clojure.com/problems/rss"}]
       [:link {:rel "shortcut icon" :href "/favicon.ico"}]
       (include-js "/vendor/script/jquery-1.5.2.min.js" "/vendor/script/jquery.dataTables.min.js")
       (include-js "/vendor/script/foreclojure.js")
       (include-js "/vendor/script/xregexp.js" "/vendor/script/shCore.js" "/vendor/script/shBrushClojure.js")
       (include-js "/vendor/script/ace/ace.js" "/vendor/script/ace/mode-clojure.js")
       (include-css "/css/style.css" "/css/demo_table.css" "/css/shCore.css" "/css/shThemeDefault.css")
       [:style {:type "text/css"}
        ".syntaxhighlighter { overflow-y: hidden !important; }"]]
      [:script {:type "text/javascript"} "SyntaxHighlighter.all()"]
      [:body
       [:div#top
        (link-to "/" [:img#logo {:src "/images/logo.png"}])]
       [:div#content
        [:br]
        [:div#menu
         (for [[link text & [tabbed]]
               [["/" "Main Page"]
                ["/problems" "Problem List"]
                ["/users" "Top Users"]
                ["/directions" "Getting Started"]
                ["http://try-clojure.org" "REPL" true]
                ["http://clojuredocs.org" "Docs" true]]]
           [:a.menu (assoc (when tabbed {:target "_blank"})
                      :href link)
            text])
         [:span#user-info
          (if user
            [:div
             [:span#username (str "Logged in as " user)]
             [:a#logout {:href "/logout"} "Logout"]]
            [:div
             [:a#login {:href (login-url)} "Login"]
             [:a#register {:href "/register"} "Register"]])]]
        (when user
          [:div#lower-menu
           [:span
            (link-to "/login/update" "Account Settings")]
           (when (:golfing-active config)
             [:span ; deserves its own page, but just make it discoverable for now
              (link-to "/login/update" "Leagues")])
           (when (approver? user)
             [:span
              (link-to "/problems/unapproved" "View Unapproved Problems")])
           (when (can-submit? user)
             [:span (link-to "/problems/submit" "Submit a Problem")])])
        [:div#content_body body]
        [:div#footer
         "The content on 4clojure.com is available under the EPL v 1.0 license."
         [:a#contact {:href "mailto:team@4clojure.com"} "Contact us!"]]
        (javascript-tag
         " var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-22844856-1']);
_gaq.push(['_trackPageview']);

(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
"
         )]]])))
Something went wrong with that request. Please try again.