Index: sitescripts/formmail/web/formmail.py |
=================================================================== |
--- a/sitescripts/formmail/web/formmail.py |
+++ b/sitescripts/formmail/web/formmail.py |
@@ -15,42 +15,27 @@ |
# You should have received a copy of the GNU General Public License |
# along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. |
-import re |
import datetime |
-from urlparse import parse_qsl |
-from sitescripts.utils import get_config, sendMail, setupStderr |
-from sitescripts.web import url_handler |
+ |
+from sitescripts.utils import get_config, sendMail, encode_email_address |
+from sitescripts.web import url_handler, form_handler, send_simple_response |
@url_handler('/formmail') |
-def handleRequest(environ, start_response): |
- setupStderr(environ['wsgi.errors']) |
+@form_handler |
+def handleRequest(environ, start_response, data): |
+ params = {name: data.get(name, '').strip() for name in ('name', 'email', 'subject', 'message')} |
+ missing = [k for k, v in params.iteritems() if not v] |
- start_response('200 OK', [('Content-Type', 'text/plain; charset=utf-8')]) |
- if environ['REQUEST_METHOD'].upper() != 'POST' or not environ.get('CONTENT_TYPE', '').startswith('application/x-www-form-urlencoded'): |
- return 'Unsupported request method' |
+ if missing: |
+ text = 'Missing fields: ' + ', '.join(missing) |
+ return send_simple_response(start_response, 400, text) |
try: |
- request_body_length = int(environ['CONTENT_LENGTH']) |
- except: |
- return 'Invalid or missing Content-Length header' |
- |
- request_body = environ['wsgi.input'].read(request_body_length) |
- params = {} |
- for key, value in parse_qsl(request_body): |
- params[key] = value.decode('utf-8').strip() |
- |
- if not 'name' in params or params['name'] == '': |
- return 'No name entered' |
- if not 'email' in params or params['email'] == '': |
- return 'No email address entered' |
- if not 'subject' in params or params['subject'] == '': |
- return 'No subject entered' |
- if not 'message' in params or params['message'] == '': |
- return 'No message entered' |
- |
- if not re.match(r'^\w[\w.+!-]+@\w[\w.-]+\.[a-zA-Z]{2,6}$', params['email']): |
- return 'Invalid email address' |
+ params['email'] = encode_email_address(params['email']) |
+ except ValueError: |
+ return send_simple_response(start_response, 400, 'Invalid email address') |
params['time'] = datetime.datetime.now() |
sendMail(get_config().get('formmail', 'template'), params) |
- return 'Message sent' |
+ |
+ return send_simple_response(start_response, 200, 'Message sent') |