Code

Refactored CGI file serving so that FileClass contents are a) read more
[roundup.git] / roundup / cgi / client.py
index 72edc6fa02c092c2d04e218b4cf1a3be2c3ac714..fe8831371b8590243b153b644e93d7bd4bef0411 100644 (file)
@@ -1,4 +1,4 @@
-# $Id: client.py,v 1.143 2003-10-24 09:32:19 jlgijsbers Exp $
+# $Id: client.py,v 1.149 2003-12-05 03:28:38 richard Exp $
 
 __doc__ = """
 WWW request handler (also used in the stand-alone server).
@@ -18,27 +18,27 @@ from roundup.mailgw import uidFromAddress
 from roundup.mailer import Mailer, MessageSendError
 
 class HTTPException(Exception):
-      pass
-class  Unauthorised(HTTPException):
-       pass
-class  NotFound(HTTPException):
-       pass
-class  Redirect(HTTPException):
-       pass
-class  NotModified(HTTPException):
-       pass
+    pass
+class Unauthorised(HTTPException):
+    pass
+class NotFound(HTTPException):
+    pass
+class Redirect(HTTPException):
+    pass
+class NotModified(HTTPException):
+    pass
 
 # used by a couple of routines
 chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
 
 class FormError(ValueError):
-    ''' An "expected" exception occurred during form parsing.
+    """ An "expected" exception occurred during form parsing.
         - ie. something we know can go wrong, and don't want to alarm the
           user with
 
         We trap this at the user interface level and feed back a nice error
         to the user.
-    '''
+    """
     pass
 
 class SendFile(Exception):
@@ -287,13 +287,12 @@ class Client:
             self.write(cgitb.html())
 
     def clean_sessions(self):
-        ''' Age sessions, remove when they haven't been used for a week.
+        """Age sessions, remove when they haven't been used for a week.
         
-            Do it only once an hour.
+        Do it only once an hour.
 
-            Note: also cleans One Time Keys, and other "session" based
-            stuff.
-        '''
+        Note: also cleans One Time Keys, and other "session" based stuff.
+        """
         sessions = self.db.sessions
         last_clean = sessions.get('last_clean', 'last_use') or 0
 
@@ -315,7 +314,7 @@ class Client:
             sessions.set('last_clean', last_use=time.time())
 
     def determine_user(self):
-        ''' Determine who the user is
+        '''Determine who the user is.
         '''
         # open the database as admin
         self.opendb('admin')
@@ -362,7 +361,7 @@ class Client:
         self.opendb(self.user)
 
     def determine_context(self, dre=re.compile(r'([^\d]+)(\d+)')):
-        ''' Determine the context of this page from the URL:
+        """ Determine the context of this page from the URL:
 
             The URL path after the instance identifier is examined. The path
             is generally only one entry long.
@@ -397,7 +396,7 @@ class Client:
              self.classname  - the class to display, can be None
              self.template   - the template to render the current context with
              self.nodeid     - the nodeid of the class we're displaying
-        '''
+        """
         # default the optional variables
         self.classname = None
         self.nodeid = None
@@ -422,7 +421,7 @@ class Client:
             else:
                 self.template = ''
             return
-        elif path[0] == '_file':
+        elif path[0] in ('_file', '@@file'):
             raise SendStaticFile, os.path.join(*path[1:])
         else:
             self.classname = path[0]
@@ -472,13 +471,44 @@ class Client:
         if classname != 'file':
             raise NotFound, designator
 
-        # we just want to serve up the file named
         self.opendb('admin')
         file = self.db.file
-        self.additional_headers['Content-Type'] = file.get(nodeid, 'type')
-        self.write(file.get(nodeid, 'content'))
+
+        mime_type = file.get(nodeid, 'type')
+        content = file.get(nodeid, 'content')
+        lmt = file.get(nodeid, 'activity').timestamp()
+
+        self._serve_file(lmt, mime_type, content)
 
     def serve_static_file(self, file):
+        ''' Serve up the file named from the templates dir
+        '''
+        filename = os.path.join(self.instance.config.TEMPLATES, file)
+
+        # last-modified time
+        lmt = os.stat(filename)[stat.ST_MTIME]
+
+        # detemine meta-type
+        file = str(file)
+        mime_type = mimetypes.guess_type(file)[0]
+        if not mime_type:
+            if file.endswith('.css'):
+                mime_type = 'text/css'
+            else:
+                mime_type = 'text/plain'
+
+        # snarf the content
+        f = open(filename, 'rb')
+        try:
+            content = f.read()
+        finally:
+            f.close()
+
+        self._serve_file(lmt, mime_type, content)
+
+    def _serve_file(self, last_modified, mime_type, content):
+        ''' guts of serve_file() and serve_static_file()
+        '''
         ims = None
         # see if there's an if-modified-since...
         if hasattr(self.request, 'headers'):
@@ -486,25 +516,18 @@ class Client:
         elif self.env.has_key('HTTP_IF_MODIFIED_SINCE'):
             # cgi will put the header in the env var
             ims = self.env['HTTP_IF_MODIFIED_SINCE']
-        filename = os.path.join(self.instance.config.TEMPLATES, file)
-        lmt = os.stat(filename)[stat.ST_MTIME]
         if ims:
             ims = rfc822.parsedate(ims)[:6]
             lmtt = time.gmtime(lmt)[:6]
             if lmtt <= ims:
                 raise NotModified
 
-        # we just want to serve up the file named
-        file = str(file)
-        mt = mimetypes.guess_type(file)[0]
-        if not mt:
-            if file.endswith('.css'):
-                mt = 'text/css'
-            else:
-                mt = 'text/plain'
-        self.additional_headers['Content-Type'] = mt
-        self.additional_headers['Last-Modifed'] = rfc822.formatdate(lmt)
-        self.write(open(filename, 'rb').read())
+        # spit out headers
+        self.additional_headers['Content-Type'] = mime_type
+        self.additional_headers['Content-Length'] = len(content)
+        lmt = rfc822.formatdate(last_modified)
+        self.additional_headers['Last-Modifed'] = lmt
+        self.write(content)
 
     def renderContext(self):
         ''' Return a PageTemplate for the named page
@@ -595,9 +618,10 @@ class Client:
             self.headers_sent = headers
 
     def set_cookie(self, user):
-        ''' Set up a session cookie for the user and store away the user's
-            login info against the session.
-        '''
+        """Set up a session cookie for the user.
+
+        Also store away the user's login info against the session.
+        """
         # TODO generate a much, much stronger session key ;)
         self.session = binascii.b2a_base64(repr(random.random())).strip()
 
@@ -883,7 +907,8 @@ Your password is now: %(password)s
             if not self.standard_message([address], subject, body):
                 return
 
-            self.ok_message.append('Password reset and email sent to %s'%address)
+            self.ok_message.append('Password reset and email sent to %s' %
+                                   address)
             return
 
         # no OTK, so now figure the user
@@ -953,13 +978,13 @@ You should then receive another email with the new password.
     newItemAction = editItemAction
 
     def editItemPermission(self, props):
-        ''' Determine whether the user has permission to edit this item.
+        """Determine whether the user has permission to edit this item.
 
-            Base behaviour is to check the user can edit this class. If we're
-            editing the "user" class, users are allowed to edit their own
-            details. Unless it's the "roles" property, which requires the
-            special Permission "Web Roles".
-        '''
+        Base behaviour is to check the user can edit this class. If we're
+        editing the"user" class, users are allowed to edit their own details.
+        Unless it's the "roles" property, which requires the special Permission
+        "Web Roles".
+        """
         # if this is a user node and the user is editing their own node, then
         # we're OK
         has = self.db.security.hasPermission
@@ -1116,16 +1141,17 @@ You should then receive another email with the new password.
     # More actions
     #
     def editCSVAction(self):
-        ''' Performs an edit of all of a class' items in one go.
+        """ Performs an edit of all of a class' items in one go.
 
             The "rows" CGI var defines the CSV-formatted entries for the
             class. New nodes are identified by the ID 'X' (or any other
             non-existent ID) and removed lines are retired.
-        '''
+        """
         # this is per-class only
         if not self.editCSVPermission():
             self.error_message.append(
-                _('You do not have permission to edit %s' %self.classname))
+                 _('You do not have permission to edit %s' %self.classname))
+            return
 
         # get the CSV module
         if rcsv.error:
@@ -1237,6 +1263,7 @@ You should then receive another email with the new password.
         if not self.searchPermission():
             self.error_message.append(
                 _('You do not have permission to search %s' %self.classname))
+            return
 
         # add a faked :filter form variable for each filtering prop
         props = self.db.classes[self.classname].getprops()
@@ -1364,7 +1391,7 @@ You should then receive another email with the new password.
         raise Redirect, url
 
     def parsePropsFromForm(self, num_re=re.compile('^\d+$')):
-        ''' Item properties and their values are edited with html FORM
+        """ Item properties and their values are edited with html FORM
             variables and their values. You can:
 
             - Change the value of some property of the current item.
@@ -1471,7 +1498,7 @@ You should then receive another email with the new password.
                 This is equivalent to::
 
                     @link@messages=msg-1
-                    @msg-1@content=value
+                    msg-1@content=value
 
                 except that in addition, the "author" and "date"
                 properties of "msg-1" are set to the userid of the
@@ -1481,7 +1508,7 @@ You should then receive another email with the new password.
                 This is equivalent to::
 
                     @link@files=file-1
-                    @file-1@content=value
+                    file-1@content=value
 
                 The String content value is handled as described above for
                 file uploads.
@@ -1504,7 +1531,7 @@ You should then receive another email with the new password.
             doesn't result in any changes would return {('issue','123'): {}})
             The id may be None, which indicates that an item should be
             created.
-        '''
+        """
         # some very useful variables
         db = self.db
         form = self.form
@@ -1675,51 +1702,18 @@ You should then receive another email with the new password.
                 if value != confirm.value:
                     raise FormError, 'Password and confirmation text do '\
                         'not match'
-                value = password.Password(value)
-
-            elif isinstance(proptype, hyperdb.Link):
-                # see if it's the "no selection" choice
-                if value == '-1' or not value:
-                    # if we're creating, just don't include this property
-                    if not nodeid or nodeid.startswith('-'):
-                        continue
-                    value = None
-                else:
-                    # handle key values
-                    link = proptype.classname
-                    if not num_re.match(value):
-                        try:
-                            value = db.classes[link].lookup(value)
-                        except KeyError:
-                            raise FormError, _('property "%(propname)s": '
-                                '%(value)s not a %(classname)s')%{
-                                'propname': propname, 'value': value,
-                                'classname': link}
-                        except TypeError, message:
-                            raise FormError, _('you may only enter ID values '
-                                'for property "%(propname)s": %(message)s')%{
-                                'propname': propname, 'message': message}
+                try:
+                    value = password.Password(value)
+                except hyperdb.HyperdbValueError, msg:
+                    raise FormError, msg
+
             elif isinstance(proptype, hyperdb.Multilink):
-                # perform link class key value lookup if necessary
-                link = proptype.classname
-                link_cl = db.classes[link]
-                l = []
-                for entry in value:
-                    if not entry: continue
-                    if not num_re.match(entry):
-                        try:
-                            entry = link_cl.lookup(entry)
-                        except KeyError:
-                            raise FormError, _('property "%(propname)s": '
-                                '"%(value)s" not an entry of %(classname)s')%{
-                                'propname': propname, 'value': entry,
-                                'classname': link}
-                        except TypeError, message:
-                            raise FormError, _('you may only enter ID values '
-                                'for property "%(propname)s": %(message)s')%{
-                                'propname': propname, 'message': message}
-                    l.append(entry)
-                l.sort()
+                # convert input to list of ids
+                try:
+                    l = hyperdb.rawToHyperdb(self.db, cl, nodeid,
+                        propname, value)
+                except hyperdb.HyperdbValueError, msg:
+                    raise FormError, msg
 
                 # now use that list of ids to modify the multilink
                 if mlaction == 'set':
@@ -1753,13 +1747,10 @@ You should then receive another email with the new password.
                     value.sort()
 
             elif value == '':
-                # if we're creating, just don't include this property
-                if not nodeid or nodeid.startswith('-'):
-                    continue
                 # other types should be None'd if there's no value
                 value = None
             else:
-                # handle ValueErrors for all these in a similar fashion
+                # handle all other types
                 try:
                     if isinstance(proptype, hyperdb.String):
                         if (hasattr(value, 'filename') and
@@ -1777,23 +1768,17 @@ You should then receive another email with the new password.
                                 props['type'] = mimetypes.guess_type(fn)[0]
                                 if not props['type']:
                                     props['type'] = "application/octet-stream"
-                            # finally, read the content
+                            # finally, read the content RAW
                             value = value.value
                         else:
-                            # normal String fix the CRLF/CR -> LF stuff
-                            value = fixNewlines(value)
+                            value = hyperdb.rawToHyperdb(self.db, cl,
+                                nodeid, propname, value)
 
-                    elif isinstance(proptype, hyperdb.Date):
-                        value = date.Date(value, offset=timezone)
-                    elif isinstance(proptype, hyperdb.Interval):
-                        value = date.Interval(value)
-                    elif isinstance(proptype, hyperdb.Boolean):
-                        value = value.lower() in ('yes', 'true', 'on', '1')
-                    elif isinstance(proptype, hyperdb.Number):
-                        value = float(value)
-                except ValueError, msg:
-                    raise FormError, _('Error with %s property: %s')%(
-                        propname, msg)
+                    else:
+                        value = hyperdb.rawToHyperdb(self.db, cl, nodeid,
+                            propname, value)
+                except hyperdb.HyperdbValueError, msg:
+                    raise FormError, msg
 
             # register that we got this property
             if value:
@@ -1875,22 +1860,12 @@ You should then receive another email with the new password.
         for (cn, id), props in all_props.items():
             if isinstance(self.db.classes[cn], hyperdb.FileClass):
                 if id == '-1':
-                      if not props.get('content', ''):
-                            del all_props[(cn, id)]
+                    if not props.get('content', ''):
+                        del all_props[(cn, id)]
                 elif props.has_key('content') and not props['content']:
-                      raise FormError, _('File is empty')
+                    raise FormError, _('File is empty')
         return all_props, all_links
 
-def fixNewlines(text):
-    ''' Homogenise line endings.
-
-        Different web clients send different line ending values, but
-        other systems (eg. email) don't necessarily handle those line
-        endings. Our solution is to convert all line endings to LF.
-    '''
-    text = text.replace('\r\n', '\n')
-    return text.replace('\r', '\n')
-
 def extractFormList(value):
     ''' Extract a list of values from the form value.