diff --git a/roundup/cgi/client.py b/roundup/cgi/client.py
index c2ccb937fe1a579b8cad312bdbfc9b3c7a0447fd..d4499bb334839aef8aa2abe05e2a15eebff01ca7 100644 (file)
--- a/roundup/cgi/client.py
+++ b/roundup/cgi/client.py
-# $Id: client.py,v 1.131 2003-08-28 01:39:15 richard Exp $
+# $Id: client.py,v 1.141 2003-10-04 11:21:47 jlgijsbers Exp $
__doc__ = """
WWW request handler (also used in the stand-alone server).
import os, os.path, cgi, StringIO, urlparse, re, traceback, mimetypes, urllib
import binascii, Cookie, time, random, MimeWriter, smtplib, socket, quopri
-import stat, rfc822, string
+import stat, rfc822
-from roundup import roundupdb, date, hyperdb, password, token
+from roundup import roundupdb, date, hyperdb, password, token, rcsv
from roundup.i18n import _
from roundup.cgi.templating import Templates, HTMLRequest, NoTemplate
from roundup.cgi import cgitb
from roundup.cgi.PageTemplates import PageTemplate
from roundup.rfc2822 import encode_header
-from roundup.mailgw import uidFromAddress, openSMTPConnection
+from roundup.mailgw import uidFromAddress
+from roundup.mailer import Mailer, MessageSendError
class HTTPException(Exception):
pass
class NotModified(HTTPException):
pass
-# set to indicate to roundup not to actually _send_ email
-# this var must contain a file to write the mail to
-SENDMAILDEBUG = os.environ.get('SENDMAILDEBUG', '')
-
# used by a couple of routines
-chars = string.letters+string.digits
+chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
-# XXX actually _use_ FormError
class FormError(ValueError):
''' An "expected" exception occurred during form parsing.
- ie. something we know can go wrong, and don't want to alarm the
self.instance = instance
self.request = request
self.env = env
+ self.mailer = Mailer(instance.config)
# save off the path
self.path = env['PATH_INFO']
except NotFound:
# pass through
raise
+ except FormError, e:
+ self.error_message.append(_('Form Error: ') + str(e))
+ self.write(self.renderContext())
except:
# everything else
self.write(cgitb.html())
return 1 on successful login
'''
- # parse the props from the form
- try:
- props = self.parsePropsFromForm()[0][('user', None)]
- except (ValueError, KeyError), message:
- self.error_message.append(_('Error: ') + str(message))
- return
+ props = self.parsePropsFromForm()[0][('user', None)]
# make sure we're allowed to register
if not self.registerPermission(props):
# send the email
tracker_name = self.db.config.TRACKER_NAME
- subject = 'Complete your registration to %s'%tracker_name
- body = '''
-To complete your registration of the user "%(name)s" with %(tracker)s,
-please visit the following URL:
+ tracker_email = self.db.config.TRACKER_EMAIL
+ subject = 'Complete your registration to %s -- key %s' % (tracker_name,
+ otk)
+ body = """To complete your registration of the user "%(name)s" with
+%(tracker)s, please do one of the following:
+
+- send a reply to %(tracker_email)s and maintain the subject line as is (the
+reply's additional "Re:" is ok),
+
+- or visit the following URL:
%(url)s?@action=confrego&otk=%(otk)s
-'''%{'name': props['username'], 'tracker': tracker_name, 'url': self.base,
- 'otk': otk}
- if not self.sendEmail(props['address'], subject, body):
+""" % {'name': props['username'], 'tracker': tracker_name, 'url': self.base,
+ 'otk': otk, 'tracker_email': tracker_email}
+ if not self.standard_message([props['address']], subject, body,
+ tracker_email):
return
# commit changes to the database
# redirect to the "you're almost there" page
raise Redirect, '%suser?@template=rego_progress'%self.base
- def sendEmail(self, to, subject, content):
- # send email to the user's email address
- message = StringIO.StringIO()
- writer = MimeWriter.MimeWriter(message)
- tracker_name = self.db.config.TRACKER_NAME
- writer.addheader('Subject', encode_header(subject))
- writer.addheader('To', to)
- writer.addheader('From', roundupdb.straddr((tracker_name,
- self.db.config.ADMIN_EMAIL)))
- writer.addheader('Date', time.strftime("%a, %d %b %Y %H:%M:%S +0000",
- time.gmtime()))
- # add a uniquely Roundup header to help filtering
- writer.addheader('X-Roundup-Name', tracker_name)
- # avoid email loops
- writer.addheader('X-Roundup-Loop', 'hello')
- writer.addheader('Content-Transfer-Encoding', 'quoted-printable')
- body = writer.startbody('text/plain; charset=utf-8')
-
- # message body, encoded quoted-printable
- content = StringIO.StringIO(content)
- quopri.encode(content, body, 0)
-
- if SENDMAILDEBUG:
- # don't send - just write to a file
- open(SENDMAILDEBUG, 'a').write('FROM: %s\nTO: %s\n%s\n'%(
- self.db.config.ADMIN_EMAIL,
- ', '.join(to),message.getvalue()))
- else:
- # now try to send the message
- try:
- # send the message as admin so bounces are sent there
- # instead of to roundup
- smtp = openSMTPConnection(self.db.config)
- smtp.sendmail(self.db.config.ADMIN_EMAIL, [to],
- message.getvalue())
- except socket.error, value:
- self.error_message.append("Error: couldn't send email: "
- "mailhost %s"%value)
- return 0
- except smtplib.SMTPException, msg:
- self.error_message.append("Error: couldn't send email: %s"%msg)
- return 0
- return 1
-
+ def standard_message(self, to, subject, body, author=None):
+ try:
+ self.mailer.standard_message(to, subject, body, author)
+ return 1
+ except MessageSendError, e:
+ self.error_message.append(str(e))
+
def registerPermission(self, props):
''' Determine whether the user has permission to register
def confRegoAction(self):
''' Grab the OTK, use it to load up the new user details
'''
- # pull the rego information out of the otk database
- otk = self.form['otk'].value
- props = self.db.otks.getall(otk)
- for propname, proptype in self.db.user.getprops().items():
- value = props.get(propname, None)
- if value is None:
- pass
- elif isinstance(proptype, hyperdb.Date):
- props[propname] = date.Date(value)
- elif isinstance(proptype, hyperdb.Interval):
- props[propname] = date.Interval(value)
- elif isinstance(proptype, hyperdb.Password):
- props[propname] = password.Password()
- props[propname].unpack(value)
-
- # re-open the database as "admin"
- if self.user != 'admin':
- self.opendb('admin')
-
- # create the new user
- cl = self.db.user
-# XXX we need to make the "default" page be able to display errors!
try:
- props['roles'] = self.instance.config.NEW_WEB_USER_ROLES
- del props['__time']
- self.userid = cl.create(**props)
- # clear the props from the otk database
- self.db.otks.destroy(otk)
- self.db.commit()
+ # pull the rego information out of the otk database
+ self.userid = self.db.confirm_registration(self.form['otk'].value)
except (ValueError, KeyError), message:
+ # XXX: we need to make the "default" page be able to display errors!
self.error_message.append(str(message))
return
-
+
# log the new user in
- self.user = cl.get(self.userid, 'username')
+ self.user = self.db.user.get(self.userid, 'username')
# re-open the database for real, using the user
self.opendb(self.user)
Your password is now: %(password)s
'''%{'name': name, 'password': newpw}
- if not self.sendEmail(address, subject, body):
+ if not self.standard_message([address], subject, body):
return
self.ok_message.append('Password reset and email sent to %s'%address)
You should then receive another email with the new password.
'''%{'name': name, 'tracker': tracker_name, 'url': self.base, 'otk': otk}
- if not self.sendEmail(address, subject, body):
+ if not self.standard_message([address], subject, body):
return
self.ok_message.append('Email sent to %s'%address)
See parsePropsFromForm and _editnodes for special variables
'''
- # parse the props from the form
- try:
- props, links = self.parsePropsFromForm()
- except (ValueError, KeyError), message:
- self.error_message.append(_('Parse Error: ') + str(message))
- return
+ props, links = self.parsePropsFromForm()
# handle the props
try:
self.classname, self.nodeid, urllib.quote(message),
urllib.quote(self.template))
+ newItemAction = editItemAction
+
def editItemPermission(self, props):
''' Determine whether the user has permission to edit this item.
return 1
return 0
- def newItemAction(self):
- ''' Add a new item to the database.
-
- This follows the same form as the editItemAction, with the same
- special form values.
- '''
- # parse the props from the form
- try:
- props, links = self.parsePropsFromForm()
- except (ValueError, KeyError), message:
- self.error_message.append(_('Error: ') + str(message))
- return
-
- # handle the props - edit or create
- try:
- # when it hits the None element, it'll set self.nodeid
- messages = self._editnodes(props, links)
-
- except (ValueError, KeyError, IndexError), message:
- # these errors might just be indicative of user dumbness
- self.error_message.append(_('Error: ') + str(message))
- return
-
- # commit now that all the tricky stuff is done
- self.db.commit()
-
- # redirect to the new item's page
- raise Redirect, '%s%s%s?@ok_message=%s&@template=%s'%(self.base,
- self.classname, self.nodeid, urllib.quote(messages),
- urllib.quote(self.template))
-
def newItemPermission(self, props):
''' Determine whether the user has permission to create (edit) this
item.
_('You do not have permission to edit %s' %self.classname))
# get the CSV module
- try:
- import csv
- except ImportError:
- self.error_message.append(_(
- 'Sorry, you need the csv module to use this function.<br>\n'
- 'Get it from: <a href="http://www.object-craft.com.au/projects/csv/">http://www.object-craft.com.au/projects/csv/'))
+ if rcsv.error:
+ self.error_message.append(_(rcsv.error))
return
cl = self.db.classes[self.classname]
props = ['id'] + idlessprops
# do the edit
- rows = self.form['rows'].value.splitlines()
- p = csv.parser()
+ rows = StringIO.StringIO(self.form['rows'].value)
+ reader = rcsv.reader(rows, rcsv.comma_separated)
found = {}
line = 0
- for row in rows[1:]:
+ for values in reader:
line += 1
- values = p.parse(row)
- # not a complete row, keep going
- if not values: continue
-
+ if line == 1: continue
# skip property names header
if values == props:
continue
for entry in extractFormList(form[key]):
m = self.FV_DESIGNATOR.match(entry)
if not m:
- raise ValueError, \
+ raise FormError, \
'link "%s" value "%s" not a designator'%(key, entry)
value.append((m.group(1), m.group(2)))
# make sure the link property is valid
if (not isinstance(propdef[propname], hyperdb.Multilink) and
not isinstance(propdef[propname], hyperdb.Link)):
- raise ValueError, '%s %s is not a link or '\
+ raise FormError, '%s %s is not a link or '\
'multilink property'%(cn, propname)
all_links.append((cn, nodeid, propname, value))
# does the property exist?
if not propdef.has_key(propname):
if mlaction != 'set':
- raise ValueError, 'You have submitted a %s action for'\
+ raise FormError, 'You have submitted a %s action for'\
' the property "%s" which doesn\'t exist'%(mlaction,
propname)
# the form element is probably just something we don't care
else:
# multiple values are not OK
if isinstance(value, type([])):
- raise ValueError, 'You have submitted more than one value'\
+ raise FormError, 'You have submitted more than one value'\
' for the %s property'%propname
# value might be a file upload...
if not hasattr(value, 'filename') or value.filename is None:
confirm = form[key]
break
else:
- raise ValueError, 'Password and confirmation text do '\
+ raise FormError, 'Password and confirmation text do '\
'not match'
if isinstance(confirm, type([])):
- raise ValueError, 'You have submitted more than one value'\
+ raise FormError, 'You have submitted more than one value'\
' for the %s property'%propname
if value != confirm.value:
- raise ValueError, 'Password and confirmation text do '\
+ raise FormError, 'Password and confirmation text do '\
'not match'
value = password.Password(value)
try:
value = db.classes[link].lookup(value)
except KeyError:
- raise ValueError, _('property "%(propname)s": '
+ raise FormError, _('property "%(propname)s": '
'%(value)s not a %(classname)s')%{
'propname': propname, 'value': value,
'classname': link}
except TypeError, message:
- raise ValueError, _('you may only enter ID values '
+ raise FormError, _('you may only enter ID values '
'for property "%(propname)s": %(message)s')%{
'propname': propname, 'message': message}
elif isinstance(proptype, hyperdb.Multilink):
try:
entry = link_cl.lookup(entry)
except KeyError:
- raise ValueError, _('property "%(propname)s": '
+ raise FormError, _('property "%(propname)s": '
'"%(value)s" not an entry of %(classname)s')%{
'propname': propname, 'value': entry,
'classname': link}
except TypeError, message:
- raise ValueError, _('you may only enter ID values '
+ raise FormError, _('you may only enter ID values '
'for property "%(propname)s": %(message)s')%{
'propname': propname, 'message': message}
l.append(entry)
try:
existing.remove(entry)
except ValueError:
- raise ValueError, _('property "%(propname)s": '
+ raise FormError, _('property "%(propname)s": '
'"%(value)s" not currently in list')%{
'propname': propname, 'value': entry}
else:
elif isinstance(proptype, hyperdb.Number):
value = float(value)
except ValueError, msg:
- raise ValueError, _('Error with %s property: %s')%(
+ raise FormError, _('Error with %s property: %s')%(
propname, msg)
# register that we got this property
# no existing value
if not propdef.has_key(propname):
raise
+ except IndexError, message:
+ raise FormError(str(message))
# make sure the existing multilink is sorted
if isinstance(proptype, hyperdb.Multilink):
s.append('Required %s %s %s not supplied'%(thing[0], p,
', '.join(required)))
if s:
- raise ValueError, '\n'.join(s)
+ raise FormError, '\n'.join(s)
# When creating a FileClass node, it should have a non-empty content
# property to be created. When editing a FileClass node, it should
if not props.get('content', ''):
del all_props[(cn, id)]
elif props.has_key('content') and not props['content']:
- raise ValueError, _('File is empty')
+ raise FormError, _('File is empty')
return all_props, all_links
def fixNewlines(text):