rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
config.read([os.path.join(home_dir, self.INI_FILE)])
config.read([config_path])
def load_ini(self, config_path, defaults=None): """Set options from config.ini file in given home_dir
init.initialise(self.dirname, 'sekrit') self.instance = instance.open(self.dirname)
self.instance = tracker = instance.open(self.dirname) if tracker.exists(): tracker.nuke() tracker.init(password.Password('sekrit'))
def setUp(self): MailgwTestCase.count = MailgwTestCase.count + 1 self.dirname = '_test_mailgw_%s'%self.count try: shutil.rmtree(self.dirname) except OSError, error: if error.errno not in (errno.ENOENT, errno.ESRCH): raise # create the instance init.install(self.dirname, 'templates/classic') init.write_select_db(self.dirname, 'anydbm') init.initialise(self.dirname, 'sekrit')
Content-Type: multipart/mixed; boundary="bCsyhTFzCvuiizWE" Content-Disposition: inline Content-Type: text/plain; charset=us-ascii Content-Disposition: inline test attachment binary Content-Type: application/octet-stream Content-Disposition: attachment; filename="main.dvi" xxxxxx
Content-Type: multipart/mixed; boundary="bCsyhTFzCvuiizWE" Content-Disposition: inline --bCsyhTFzCvuiizWE Content-Type: text/plain; charset=us-ascii Content-Disposition: inline test attachment binary --bCsyhTFzCvuiizWE Content-Type: application/octet-stream Content-Disposition: attachment; filename="main.dvi" xxxxxx
def testContentDisposition(self): self.doNewIssue() self._handle_mail('''Content-Type: text/plain;
if self.value is None: value = ''
if self._value is None: value = ''
def email(self, escape=1): ''' fudge email ''' if self.value is None: value = '' else: value = str(self._value) value = value.replace('@', ' at ') value = value.replace('.', ' ') if escape: value = cgi.escape(value) return value
data = part.fp.read()
def handle_message(self, message): ''' message - a Message instance
data = binascii.a2b_base64(data)
data = binascii.a2b_base64(part.fp.read())
def handle_message(self, message): ''' message - a Message instance
data = quopri.decode(data)
decoded = cStringIO.StringIO() quopri.decode(part.fp, decoded) data = decoded.getvalue()
def handle_message(self, message): ''' message - a Message instance
data = binascii.a2b_uu(data)
data = binascii.a2b_uu(part.fp.read())
def handle_message(self, message): ''' message - a Message instance
sys.stdout.write('Importing %s - %d\r'%(classname, n)) sys.stdout.flush()
if self.verbose : sys.stdout.write('Importing %s - %d\r'%(classname, n)) sys.stdout.flush()
def do_import(self, args): ""'''Usage: import import_dir Import a database from the directory containing CSV files, two per class to import.
opts, args = getopt.getopt(sys.argv[1:], 'i:u:hcdsS:v')
opts, args = getopt.getopt(sys.argv[1:], 'i:u:hcdsS:vV')
def main(self): try: opts, args = getopt.getopt(sys.argv[1:], 'i:u:hcdsS:v') except getopt.GetoptError, e: self.usage(str(e)) return 1
return str(psycopg.QuotedString(str(value)))[1:-1]
return str(QuotedString(str(value)))[1:-1]
def sql_stringquote(self, value): ''' psycopg.QuotedString returns a "buffer" object with the single-quotes around it... ''' return str(psycopg.QuotedString(str(value)))[1:-1]
if os.path.isfile(schemafile): if os.path.getmtime(schemafile) < dbtm: self.fastopen = 1 else:
if os.path.isfile(schemafile) \ and (os.path.getmtime(schemafile) < dbtm):
def __open(self): ''' Open the metakit database ''' # make the database dir if it doesn't exist if not os.path.exists(self.config.DATABASE): os.makedirs(self.config.DATABASE)
nodeid = int(nodeid) journaldate = date.Date(journaldate) params = eval(params)
journaldate = str(date.Date(journaldate))
def add_new_columns_v2(self): '''While we're adding the actor column, we need to update the tables to have the correct datatypes.''' for klass in self.classes.values(): cn = klass.classname properties = klass.getprops() old_spec = self.database_schema['tables'][cn]
cl = self.db.classes[cn] if not isinstance(cl, hyperdb.FileClass): continue if not props.get('content', ''): del all_props[(cn, id)]
if isinstance(self.db.classes[cn], hyperdb.FileClass): if id == '-1': if not props.get('content', ''): del all_props[(cn, id)] elif props.has_key('content') and not props['content']: raise ValueError, _('File is empty')
propdef = all_propdef[cn]
def indexargs_href(self, url, args):
def indexargs_url(self, url, args):
def indexargs_href(self, url, args): ''' embed the current index args in a URL ''' l = ['%s=%s'%(k,v) for k,v in args.items()] if self.columns and not args.has_key(':columns'): l.append(':columns=%s'%(','.join(self.columns))) if self.sort[1] is not None and not args.has_key(':sort'): if self.sort[0] == '-': val = '-'+self.sort[1] else: val = self.sort[1] l.append(':sort=%s'%val) if self.group[1] is not None and not args.has_key(':group'): if self.group[0] == '-': val = '-'+self.group[1] else: val = self.group[1] l.append(':group=%s'%val) if self.filter and not args.has_key(':columns'): l.append(':filter=%s'%(','.join(self.filter))) for k,v in self.filterspec.items(): if not args.has_key(k): l.append('%s=%s'%(k, ','.join(v))) if self.search_text and not args.has_key(':search_text'): l.append(':search_text=%s'%self.search_text) if not args.has_key(':pagesize'): l.append(':pagesize=%s'%self.pagesize) if not args.has_key(':startwith'): l.append(':startwith=%s'%self.startwith) return '%s?%s'%(url, '&'.join(l))
def length(self): self.sequence_length = l = len(self._sequence) return l
def length(self): self.sequence_length = l = len(self._sequence) return l
return DateHTMLProperty(self._client, self._nodeid, self._prop, self._formname, self._value.local(offset))
return DateHTMLProperty(self._client, self._classname, self._nodeid, self._prop, self._formname, self._value.local(offset))
def local(self, offset): ''' Return the date/time as a local (timezone offset) date/time. ''' self.view_check()
raise KeyErorr, item
raise KeyError, item
def __getitem__(self, item): ''' return an HTMLProperty instance ''' #print 'HTMLItem.getitem', (self, item) if item == 'id': return self._nodeid
cell.append('%s: <a href="%s%s">%s</a>\n'%(k, classname, args[k], label))
old = '<a href="%s%s">%s</a>'%(classname, args[k], label)
def history(self, direction='descending', dre=re.compile('\d+')): l = ['<table class="history">' '<tr><th colspan="4" class="header">', _('History'), '</th></tr><tr>', _('<th>Date</th>'), _('<th>User</th>'), _('<th>Action</th>'), _('<th>Args</th>'), '</tr>'] comments = {} history = self._klass.history(self._nodeid) history.sort() if direction == 'descending': history.reverse() for id, evt_date, user, action, args in history: date_s = str(evt_date).replace("."," ") arg_s = '' if action == 'link' and type(args) == type(()): if len(args) == 3: linkcl, linkid, key = args arg_s += '<a href="%s%s">%s%s %s</a>'%(linkcl, linkid, linkcl, linkid, key) else: arg_s = str(args)
cell.append('%s: %s' % (k,label))
old = label; cell.append('%s: %s' % (k,old)) if k in current: cell[-1] += ' -> %s'%current[k] current[k] = old
def history(self, direction='descending', dre=re.compile('\d+')): l = ['<table class="history">' '<tr><th colspan="4" class="header">', _('History'), '</th></tr><tr>', _('<th>Date</th>'), _('<th>User</th>'), _('<th>Action</th>'), _('<th>Args</th>'), '</tr>'] comments = {} history = self._klass.history(self._nodeid) history.sort() if direction == 'descending': history.reverse() for id, evt_date, user, action, args in history: date_s = str(evt_date).replace("."," ") arg_s = '' if action == 'link' and type(args) == type(()): if len(args) == 3: linkcl, linkid, key = args arg_s += '<a href="%s%s">%s%s %s</a>'%(linkcl, linkid, linkcl, linkid, key) else: arg_s = str(args)
cell.append('%s: (no value)\n'%k)
if k not in current: cell.append('%s: (no value)'%k) else: cell.append('%s: %s'%(k, current[k])) current[k] = '(no value)'
def history(self, direction='descending', dre=re.compile('\d+')): l = ['<table class="history">' '<tr><th colspan="4" class="header">', _('History'), '</th></tr><tr>', _('<th>Date</th>'), _('<th>User</th>'), _('<th>Action</th>'), _('<th>Args</th>'), '</tr>'] comments = {} history = self._klass.history(self._nodeid) history.sort() if direction == 'descending': history.reverse() for id, evt_date, user, action, args in history: date_s = str(evt_date).replace("."," ") arg_s = '' if action == 'link' and type(args) == type(()): if len(args) == 3: linkcl, linkid, key = args arg_s += '<a href="%s%s">%s%s %s</a>'%(linkcl, linkid, linkcl, linkid, key) else: arg_s = str(args)
cell.append('%s: %s\n'%(k, str(args[k])))
cell.append('%s: %s'%(k, str(args[k]))) if k in current: cell[-1] += ' -> %s'%current[k] current[k] = str(args[k])
def history(self, direction='descending', dre=re.compile('\d+')): l = ['<table class="history">' '<tr><th colspan="4" class="header">', _('History'), '</th></tr><tr>', _('<th>Date</th>'), _('<th>User</th>'), _('<th>Action</th>'), _('<th>Args</th>'), '</tr>'] comments = {} history = self._klass.history(self._nodeid) history.sort() if direction == 'descending': history.reverse() for id, evt_date, user, action, args in history: date_s = str(evt_date).replace("."," ") arg_s = '' if action == 'link' and type(args) == type(()): if len(args) == 3: linkcl, linkid, key = args arg_s += '<a href="%s%s">%s%s %s</a>'%(linkcl, linkid, linkcl, linkid, key) else: arg_s = str(args)
if file is None:
if index is None or file is None:
def html(context=5): etype, evalue = sys.exc_type, sys.exc_value if type(etype) is types.ClassType: etype = etype.__name__ pyver = 'Python ' + string.split(sys.version)[0] + '<br>' + sys.executable head = pydoc.html.heading( '<font size=+1><strong>%s</strong>: %s</font>'%(str(etype), str(evalue)), '#ffffff', '#aa55cc', pyver) head = head + (_('<p>A problem occurred while running a Python script. ' 'Here is the sequence of function calls leading up to ' 'the error, with the most recent (innermost) call first. ' 'The exception attributes are:')) indent = '<tt><small>%s</small>&nbsp;</tt>' % ('&nbsp;' * 5) traceback = [] for frame, file, lnum, func, lines, index in inspect.trace(context): if file is None: link = '&lt;file is None - probably inside <tt>eval</tt> or <tt>exec</tt>&gt;' else: file = os.path.abspath(file) link = '<a href="file:%s">%s</a>' % (file, pydoc.html.escape(file)) args, varargs, varkw, locals = inspect.getargvalues(frame) if func == '?': call = '' else: call = 'in <strong>%s</strong>' % func + inspect.formatargvalues( args, varargs, varkw, locals, formatvalue=lambda value: '=' + pydoc.html.repr(value)) level = '''
interval = now - self.get(sessid, '__timestamp', default=time.time())
sess = self.get(sessid, '__timestamp', None) if sess is None: sess=time.time() self.updateTimestamp(sessid) interval = now - sess
def clean(self, now): """Age sessions, remove when they haven't been used for a week. """ week = 60*60*24*7 for sessid in self.list(): interval = now - self.get(sessid, '__timestamp', default=time.time()) if interval > week: self.destroy(sessid)
filename = os.path.join(self.instance.config.TEMPLATES, file)
prefix = getattr(self.instance.config, 'STATIC_FILES', self.instance.config.TEMPLATES) filename = os.path.normpath(os.path.join(prefix, file)) if not filename.startswith(prefix): raise NotFound, file
def serve_static_file(self, file): ''' Serve up the file named from the templates dir ''' filename = os.path.join(self.instance.config.TEMPLATES, file)
if filterspec:
if self.classname and filterspec:
def indexargs_form(self, columns=1, sort=1, group=1, filter=1, filterspec=1): ''' return the current index args as form elements ''' l = [] sc = self.special_char s = self.input(type="hidden",name="%s",value="%s") if columns and self.columns: l.append(s%(sc+'columns', ','.join(self.columns))) if sort and self.sort[1] is not None: if self.sort[0] == '-': val = '-'+self.sort[1] else: val = self.sort[1] l.append(s%(sc+'sort', val)) if group and self.group[1] is not None: if self.group[0] == '-': val = '-'+self.group[1] else: val = self.group[1] l.append(s%(sc+'group', val)) if filter and self.filter: l.append(s%(sc+'filter', ','.join(self.filter))) if filterspec: props = self.client.db.getclass(self.classname).getprops() for k,v in self.filterspec.items(): if type(v) == type([]): if isinstance(props[k], hyperdb.String): l.append(s%(k, ' '.join(v))) else: l.append(s%(k, ','.join(v))) else: l.append(s%(k, v)) if self.search_text: l.append(s%(sc+'search_text', self.search_text)) l.append(s%(sc+'pagesize', self.pagesize)) l.append(s%(sc+'startwith', self.startwith)) return '\n'.join(l)
props = self.client.db.getclass(self.classname).getprops() q = urllib.quote for k,v in self.filterspec.items(): if not args.has_key(k): if type(v) == type([]): if isinstance(props[k], hyperdb.String): l.append('%s=%s'%(k, '%20'.join([q(i) for i in v])))
if self.classname and self.filterspec: props = self.client.db.getclass(self.classname).getprops() q = urllib.quote for k,v in self.filterspec.items(): if not args.has_key(k): if type(v) == type([]): if isinstance(props[k], hyperdb.String): l.append('%s=%s'%(k, '%20'.join([q(i) for i in v]))) else: l.append('%s=%s'%(k, ','.join([q(i) for i in v])))
def indexargs_url(self, url, args): ''' Embed the current index args in a URL ''' sc = self.special_char l = ['%s=%s'%(k,v) for k,v in args.items()]
l.append('%s=%s'%(k, ','.join([q(i) for i in v]))) else: l.append('%s=%s'%(k, q(v)))
l.append('%s=%s'%(k, q(v)))
def indexargs_url(self, url, args): ''' Embed the current index args in a URL ''' sc = self.special_char l = ['%s=%s'%(k,v) for k,v in args.items()]
props, changed = parsePropsFromForm(self.db, cl, self.form, self.nodeid)
props = parsePropsFromForm(self.db, cl, self.form, self.nodeid)
def shownode(self, message=None): ''' display an item ''' cn = self.classname cl = self.db.classes[cn]
if changed:
if props:
def shownode(self, message=None): ''' display an item ''' cn = self.classname cl = self.db.classes[cn]
', '.join(changed.keys())}
', '.join(props.keys())}
def shownode(self, message=None): ''' display an item ''' cn = self.classname cl = self.db.classes[cn]
props, dummy = parsePropsFromForm(self.db, cl, self.form)
props = parsePropsFromForm(self.db, cl, self.form) print props
def newuser(self, message=None): ''' Add a new user to the database.
props, changed = parsePropsFromForm(self.db, user, self.form,
props = parsePropsFromForm(self.db, user, self.form,
def showuser(self, message=None): '''Display a user page for editing. Make sure the user is allowed to edit this node, and also check for password changes. ''' if self.user == 'anonymous': raise Unauthorised
if self.nodeid == self.getuid() and changed.has_key('password'):
if props.has_key('password'):
def showuser(self, message=None): '''Display a user page for editing. Make sure the user is allowed to edit this node, and also check for password changes. ''' if self.user == 'anonymous': raise Unauthorised
if password: set_cookie = password else:
if not password:
def showuser(self, message=None): '''Display a user page for editing. Make sure the user is allowed to edit this node, and also check for password changes. ''' if self.user == 'anonymous': raise Unauthorised
del changed['password']
elif self.nodeid == self.getuid(): set_cookie = password
def showuser(self, message=None): '''Display a user page for editing. Make sure the user is allowed to edit this node, and also check for password changes. ''' if self.user == 'anonymous': raise Unauthorised
', '.join(changed.keys())}
', '.join(props.keys())}
def showuser(self, message=None): '''Display a user page for editing. Make sure the user is allowed to edit this node, and also check for password changes. ''' if self.user == 'anonymous': raise Unauthorised
props, dummy = parsePropsFromForm(self.db, cl, self.form)
props = parsePropsFromForm(self.db, cl, self.form)
def newuser_action(self, message=None): '''Attempt to create a new user based on the contents of the form and then set the cookie.
changed = {}
def parsePropsFromForm(db, cl, form, nodeid=0): '''Pull properties for the given class out of the form. ''' props = {} changed = {} keys = form.keys() num_re = re.compile('^\d+$') for key in keys: if not cl.properties.has_key(key): continue proptype = cl.properties[key] if isinstance(proptype, hyperdb.String): value = form[key].value.strip() elif isinstance(proptype, hyperdb.Password): value = password.Password(form[key].value.strip()) elif isinstance(proptype, hyperdb.Date): value = date.Date(form[key].value.strip()) elif isinstance(proptype, hyperdb.Interval): value = date.Interval(form[key].value.strip()) elif isinstance(proptype, hyperdb.Link): value = form[key].value.strip() # see if it's the "no selection" choice if value == '-1': # don't set this property continue else: # handle key values link = cl.properties[key].classname if not num_re.match(value): try: value = db.classes[link].lookup(value) except KeyError: raise ValueError, _('property "%(propname)s": ' '%(value)s not a %(classname)s')%{'propname':key, 'value': value, 'classname': link} elif isinstance(proptype, hyperdb.Multilink): value = form[key] if type(value) != type([]): value = [i.strip() for i in value.value.split(',')] else: value = [i.value.strip() for i in value] link = cl.properties[key].classname l = [] for entry in map(str, value): if entry == '': continue if not num_re.match(entry): try: entry = db.classes[link].lookup(entry) except KeyError: raise ValueError, _('property "%(propname)s": ' '"%(value)s" not an entry of %(classname)s')%{ 'propname':key, 'value': entry, 'classname': link} l.append(entry) l.sort() value = l props[key] = value # get the old value if nodeid: try: existing = cl.get(nodeid, key) except KeyError: # this might be a new property for which there is no existing # value if not cl.properties.has_key(key): raise # if changed, set it if nodeid and value != existing: changed[key] = value props[key] = value return props, changed
props[key] = value
def parsePropsFromForm(db, cl, form, nodeid=0): '''Pull properties for the given class out of the form. ''' props = {} changed = {} keys = form.keys() num_re = re.compile('^\d+$') for key in keys: if not cl.properties.has_key(key): continue proptype = cl.properties[key] if isinstance(proptype, hyperdb.String): value = form[key].value.strip() elif isinstance(proptype, hyperdb.Password): value = password.Password(form[key].value.strip()) elif isinstance(proptype, hyperdb.Date): value = date.Date(form[key].value.strip()) elif isinstance(proptype, hyperdb.Interval): value = date.Interval(form[key].value.strip()) elif isinstance(proptype, hyperdb.Link): value = form[key].value.strip() # see if it's the "no selection" choice if value == '-1': # don't set this property continue else: # handle key values link = cl.properties[key].classname if not num_re.match(value): try: value = db.classes[link].lookup(value) except KeyError: raise ValueError, _('property "%(propname)s": ' '%(value)s not a %(classname)s')%{'propname':key, 'value': value, 'classname': link} elif isinstance(proptype, hyperdb.Multilink): value = form[key] if type(value) != type([]): value = [i.strip() for i in value.value.split(',')] else: value = [i.value.strip() for i in value] link = cl.properties[key].classname l = [] for entry in map(str, value): if entry == '': continue if not num_re.match(entry): try: entry = db.classes[link].lookup(entry) except KeyError: raise ValueError, _('property "%(propname)s": ' '"%(value)s" not an entry of %(classname)s')%{ 'propname':key, 'value': entry, 'classname': link} l.append(entry) l.sort() value = l props[key] = value # get the old value if nodeid: try: existing = cl.get(nodeid, key) except KeyError: # this might be a new property for which there is no existing # value if not cl.properties.has_key(key): raise # if changed, set it if nodeid and value != existing: changed[key] = value props[key] = value return props, changed
if nodeid and value != existing: changed[key] = value
if value != existing: props[key] = value else:
def parsePropsFromForm(db, cl, form, nodeid=0): '''Pull properties for the given class out of the form. ''' props = {} changed = {} keys = form.keys() num_re = re.compile('^\d+$') for key in keys: if not cl.properties.has_key(key): continue proptype = cl.properties[key] if isinstance(proptype, hyperdb.String): value = form[key].value.strip() elif isinstance(proptype, hyperdb.Password): value = password.Password(form[key].value.strip()) elif isinstance(proptype, hyperdb.Date): value = date.Date(form[key].value.strip()) elif isinstance(proptype, hyperdb.Interval): value = date.Interval(form[key].value.strip()) elif isinstance(proptype, hyperdb.Link): value = form[key].value.strip() # see if it's the "no selection" choice if value == '-1': # don't set this property continue else: # handle key values link = cl.properties[key].classname if not num_re.match(value): try: value = db.classes[link].lookup(value) except KeyError: raise ValueError, _('property "%(propname)s": ' '%(value)s not a %(classname)s')%{'propname':key, 'value': value, 'classname': link} elif isinstance(proptype, hyperdb.Multilink): value = form[key] if type(value) != type([]): value = [i.strip() for i in value.value.split(',')] else: value = [i.value.strip() for i in value] link = cl.properties[key].classname l = [] for entry in map(str, value): if entry == '': continue if not num_re.match(entry): try: entry = db.classes[link].lookup(entry) except KeyError: raise ValueError, _('property "%(propname)s": ' '"%(value)s" not an entry of %(classname)s')%{ 'propname':key, 'value': entry, 'classname': link} l.append(entry) l.sort() value = l props[key] = value # get the old value if nodeid: try: existing = cl.get(nodeid, key) except KeyError: # this might be a new property for which there is no existing # value if not cl.properties.has_key(key): raise # if changed, set it if nodeid and value != existing: changed[key] = value props[key] = value return props, changed
return props, changed
return props
def parsePropsFromForm(db, cl, form, nodeid=0): '''Pull properties for the given class out of the form. ''' props = {} changed = {} keys = form.keys() num_re = re.compile('^\d+$') for key in keys: if not cl.properties.has_key(key): continue proptype = cl.properties[key] if isinstance(proptype, hyperdb.String): value = form[key].value.strip() elif isinstance(proptype, hyperdb.Password): value = password.Password(form[key].value.strip()) elif isinstance(proptype, hyperdb.Date): value = date.Date(form[key].value.strip()) elif isinstance(proptype, hyperdb.Interval): value = date.Interval(form[key].value.strip()) elif isinstance(proptype, hyperdb.Link): value = form[key].value.strip() # see if it's the "no selection" choice if value == '-1': # don't set this property continue else: # handle key values link = cl.properties[key].classname if not num_re.match(value): try: value = db.classes[link].lookup(value) except KeyError: raise ValueError, _('property "%(propname)s": ' '%(value)s not a %(classname)s')%{'propname':key, 'value': value, 'classname': link} elif isinstance(proptype, hyperdb.Multilink): value = form[key] if type(value) != type([]): value = [i.strip() for i in value.value.split(',')] else: value = [i.value.strip() for i in value] link = cl.properties[key].classname l = [] for entry in map(str, value): if entry == '': continue if not num_re.match(entry): try: entry = db.classes[link].lookup(entry) except KeyError: raise ValueError, _('property "%(propname)s": ' '"%(value)s" not an entry of %(classname)s')%{ 'propname':key, 'value': entry, 'classname': link} l.append(entry) l.sort() value = l props[key] = value # get the old value if nodeid: try: existing = cl.get(nodeid, key) except KeyError: # this might be a new property for which there is no existing # value if not cl.properties.has_key(key): raise # if changed, set it if nodeid and value != existing: changed[key] = value props[key] = value return props, changed
class Class:
class Class(hyperdb.Class):
def setid(self, classname, maxid): ''' No-op in metakit ''' pass
x = open(fnm, 'rb').read()
f = open(fnm, 'rb')
def get(self, nodeid, propname, default=_marker, cache=1): x = Class.get(self, nodeid, propname, default) poss_msg = 'Possibly an access right configuration problem.' if propname == 'content': if x.startswith('file:'): fnm = x[5:] try: x = open(fnm, 'rb').read() except IOError, (strerror): # XXX by catching this we donot see an error in the log. return 'ERROR reading file: %s%s\n%s\n%s'%( self.classname, nodeid, poss_msg, strerror) return x
if not self.db.security.hasPermission('Edit', author, classname): raise Unauthorized, 'You are not permitted to edit %s.'%classname
if nodeid: if not self.db.security.hasPermission('Edit', author, classname): raise Unauthorized, 'You are not permitted to edit %s.'%classname else: if not self.db.security.hasPermission('Create', author, classname): raise Unauthorized, 'You are not permitted to create %s.'%classname
def handle_message(self, message): ''' message - a Message instance
prop = props[k] except:
prop = self.props[k] except KeyError:
def history(self, direction='descending'): l = ['<table width=100% border=0 cellspacing=0 cellpadding=2>', '<tr class="list-header">', _('<th align=left><span class="list-item">Date</span></th>'), _('<th align=left><span class="list-item">User</span></th>'), _('<th align=left><span class="list-item">Action</span></th>'), _('<th align=left><span class="list-item">Args</span></th>'), '</tr>'] comments = {} history = self.klass.history(self.nodeid) history.sort() if direction == 'descending': history.reverse() for id, evt_date, user, action, args in history: date_s = str(evt_date).replace("."," ") arg_s = '' if action == 'link' and type(args) == type(()): if len(args) == 3: linkcl, linkid, key = args arg_s += '<a href="%s%s">%s%s %s</a>'%(linkcl, linkid, linkcl, linkid, key) else: arg_s = str(args)
hrefable = os.path.exists( os.path.join(self.db.config.TEMPLATES, classname+'.item'))
def history(self, direction='descending'): l = ['<table width=100% border=0 cellspacing=0 cellpadding=2>', '<tr class="list-header">', _('<th align=left><span class="list-item">Date</span></th>'), _('<th align=left><span class="list-item">User</span></th>'), _('<th align=left><span class="list-item">Action</span></th>'), _('<th align=left><span class="list-item">Args</span></th>'), '</tr>'] comments = {} history = self.klass.history(self.nodeid) history.sort() if direction == 'descending': history.reverse() for id, evt_date, user, action, args in history: date_s = str(evt_date).replace("."," ") arg_s = '' if action == 'link' and type(args) == type(()): if len(args) == 3: linkcl, linkid, key = args arg_s += '<a href="%s%s">%s%s %s</a>'%(linkcl, linkid, linkcl, linkid, key) else: arg_s = str(args)
subml.append('<a href="%s%s">%s</a>'%( classname, linkid, label))
if hrefable: subml.append('<a href="%s%s">%s</a>'%( classname, linkid, label))
def history(self, direction='descending'): l = ['<table width=100% border=0 cellspacing=0 cellpadding=2>', '<tr class="list-header">', _('<th align=left><span class="list-item">Date</span></th>'), _('<th align=left><span class="list-item">User</span></th>'), _('<th align=left><span class="list-item">Action</span></th>'), _('<th align=left><span class="list-item">Args</span></th>'), '</tr>'] comments = {} history = self.klass.history(self.nodeid) history.sort() if direction == 'descending': history.reverse() for id, evt_date, user, action, args in history: date_s = str(evt_date).replace("."," ") arg_s = '' if action == 'link' and type(args) == type(()): if len(args) == 3: linkcl, linkid, key = args arg_s += '<a href="%s%s">%s%s %s</a>'%(linkcl, linkid, linkcl, linkid, key) else: arg_s = str(args)
if value: value = str(linkcl.get(value, k)) else: value = _('[unselected]')
if value: value = '<a href="%s%s">%s</a>'%(propclass.classname, value, linkcl.get(value, k)) else: value = _('[unselected]')
def do_plain(self, property, escape=0): ''' display a String property directly;
value = ', '.join([linkcl.get(i, k) for i in value])
value = ', '.join(['<a href="%s%s">%s</a>'%(propclass.classname, i, linkcl.get(i, k)) for i in value])
def do_plain(self, property, escape=0): ''' display a String property directly;
setup( name = "roundup", version = __version__, description = "A simple-to-use and -install issue-tracking system"
setup_args = { 'name': "roundup", 'version': __version__, 'description': "A simple-to-use and -install issue-tracking system"
def main(): # build list of scripts from their implementation modules roundup_scripts = map(scriptname, glob('roundup/scripts/[!_]*.py')) # template munching packagelist = [ 'roundup', 'roundup.cgi', 'roundup.cgi.PageTemplates', 'roundup.cgi.TAL', 'roundup.cgi.ZTUtils', 'roundup.backends', 'roundup.scripts', ] installdatafiles = [ ('share/roundup/cgi-bin', ['cgi-bin/roundup.cgi']), ] py_modules = ['roundup.demo',] # install man pages on POSIX platforms if os.name == 'posix': installdatafiles.append(('man/man1', ['doc/roundup-admin.1', 'doc/roundup-mailgw.1', 'doc/roundup-server.1', 'doc/roundup-demo.1'])) # add the templates to the data files lists from roundup.init import listTemplates templates = [t['path'] for t in listTemplates('templates').values()] for tdir in templates: # scan for data files for idir in '. detectors extensions html'.split(): idir = os.path.join(tdir, idir) if not os.path.isdir(idir): continue tfiles = [] for f in os.listdir(idir): if f.startswith('.'): continue ifile = os.path.join(idir, f) if os.path.isfile(ifile): tfiles.append(ifile) installdatafiles.append( (os.path.join('share', 'roundup', idir), tfiles) ) # add message files for (_dist_file, _mo_file) in list_message_files(): installdatafiles.append((os.path.dirname(_mo_file), [os.path.join("build", _mo_file)])) # perform the setup action from roundup import __version__ setup( name = "roundup", version = __version__, description = "A simple-to-use and -install issue-tracking system" " with command-line, web and e-mail interfaces. Highly" " customisable.", long_description =
long_description =
'long_description':
def main(): # build list of scripts from their implementation modules roundup_scripts = map(scriptname, glob('roundup/scripts/[!_]*.py')) # template munching packagelist = [ 'roundup', 'roundup.cgi', 'roundup.cgi.PageTemplates', 'roundup.cgi.TAL', 'roundup.cgi.ZTUtils', 'roundup.backends', 'roundup.scripts', ] installdatafiles = [ ('share/roundup/cgi-bin', ['cgi-bin/roundup.cgi']), ] py_modules = ['roundup.demo',] # install man pages on POSIX platforms if os.name == 'posix': installdatafiles.append(('man/man1', ['doc/roundup-admin.1', 'doc/roundup-mailgw.1', 'doc/roundup-server.1', 'doc/roundup-demo.1'])) # add the templates to the data files lists from roundup.init import listTemplates templates = [t['path'] for t in listTemplates('templates').values()] for tdir in templates: # scan for data files for idir in '. detectors extensions html'.split(): idir = os.path.join(tdir, idir) if not os.path.isdir(idir): continue tfiles = [] for f in os.listdir(idir): if f.startswith('.'): continue ifile = os.path.join(idir, f) if os.path.isfile(ifile): tfiles.append(ifile) installdatafiles.append( (os.path.join('share', 'roundup', idir), tfiles) ) # add message files for (_dist_file, _mo_file) in list_message_files(): installdatafiles.append((os.path.dirname(_mo_file), [os.path.join("build", _mo_file)])) # perform the setup action from roundup import __version__ setup( name = "roundup", version = __version__, description = "A simple-to-use and -install issue-tracking system" " with command-line, web and e-mail interfaces. Highly" " customisable.", long_description =
author = "Richard Jones", author_email = "[email protected]", url = 'http://roundup.sourceforge.net/', download_url = 'http://sourceforge.net/project/showfiles.php?group_id=31577', packages = packagelist, py_modules = py_modules, classifiers = [
'author': "Richard Jones", 'author_email': "[email protected]", 'url': 'http://roundup.sourceforge.net/', 'download_url': 'http://sourceforge.net/project/showfiles.php?group_id=31577', 'packages': packagelist, 'classifiers': [
def main(): # build list of scripts from their implementation modules roundup_scripts = map(scriptname, glob('roundup/scripts/[!_]*.py')) # template munching packagelist = [ 'roundup', 'roundup.cgi', 'roundup.cgi.PageTemplates', 'roundup.cgi.TAL', 'roundup.cgi.ZTUtils', 'roundup.backends', 'roundup.scripts', ] installdatafiles = [ ('share/roundup/cgi-bin', ['cgi-bin/roundup.cgi']), ] py_modules = ['roundup.demo',] # install man pages on POSIX platforms if os.name == 'posix': installdatafiles.append(('man/man1', ['doc/roundup-admin.1', 'doc/roundup-mailgw.1', 'doc/roundup-server.1', 'doc/roundup-demo.1'])) # add the templates to the data files lists from roundup.init import listTemplates templates = [t['path'] for t in listTemplates('templates').values()] for tdir in templates: # scan for data files for idir in '. detectors extensions html'.split(): idir = os.path.join(tdir, idir) if not os.path.isdir(idir): continue tfiles = [] for f in os.listdir(idir): if f.startswith('.'): continue ifile = os.path.join(idir, f) if os.path.isfile(ifile): tfiles.append(ifile) installdatafiles.append( (os.path.join('share', 'roundup', idir), tfiles) ) # add message files for (_dist_file, _mo_file) in list_message_files(): installdatafiles.append((os.path.dirname(_mo_file), [os.path.join("build", _mo_file)])) # perform the setup action from roundup import __version__ setup( name = "roundup", version = __version__, description = "A simple-to-use and -install issue-tracking system" " with command-line, web and e-mail interfaces. Highly" " customisable.", long_description =
cmdclass = {
'cmdclass': {
def main(): # build list of scripts from their implementation modules roundup_scripts = map(scriptname, glob('roundup/scripts/[!_]*.py')) # template munching packagelist = [ 'roundup', 'roundup.cgi', 'roundup.cgi.PageTemplates', 'roundup.cgi.TAL', 'roundup.cgi.ZTUtils', 'roundup.backends', 'roundup.scripts', ] installdatafiles = [ ('share/roundup/cgi-bin', ['cgi-bin/roundup.cgi']), ] py_modules = ['roundup.demo',] # install man pages on POSIX platforms if os.name == 'posix': installdatafiles.append(('man/man1', ['doc/roundup-admin.1', 'doc/roundup-mailgw.1', 'doc/roundup-server.1', 'doc/roundup-demo.1'])) # add the templates to the data files lists from roundup.init import listTemplates templates = [t['path'] for t in listTemplates('templates').values()] for tdir in templates: # scan for data files for idir in '. detectors extensions html'.split(): idir = os.path.join(tdir, idir) if not os.path.isdir(idir): continue tfiles = [] for f in os.listdir(idir): if f.startswith('.'): continue ifile = os.path.join(idir, f) if os.path.isfile(ifile): tfiles.append(ifile) installdatafiles.append( (os.path.join('share', 'roundup', idir), tfiles) ) # add message files for (_dist_file, _mo_file) in list_message_files(): installdatafiles.append((os.path.dirname(_mo_file), [os.path.join("build", _mo_file)])) # perform the setup action from roundup import __version__ setup( name = "roundup", version = __version__, description = "A simple-to-use and -install issue-tracking system" " with command-line, web and e-mail interfaces. Highly" " customisable.", long_description =
scripts = roundup_scripts, data_files = installdatafiles )
'scripts': roundup_scripts, 'data_files': installdatafiles } if sys.version_info[:2] > (2, 2): setup_args['py_modules'] = py_modules setup(**setup_args)
def main(): # build list of scripts from their implementation modules roundup_scripts = map(scriptname, glob('roundup/scripts/[!_]*.py')) # template munching packagelist = [ 'roundup', 'roundup.cgi', 'roundup.cgi.PageTemplates', 'roundup.cgi.TAL', 'roundup.cgi.ZTUtils', 'roundup.backends', 'roundup.scripts', ] installdatafiles = [ ('share/roundup/cgi-bin', ['cgi-bin/roundup.cgi']), ] py_modules = ['roundup.demo',] # install man pages on POSIX platforms if os.name == 'posix': installdatafiles.append(('man/man1', ['doc/roundup-admin.1', 'doc/roundup-mailgw.1', 'doc/roundup-server.1', 'doc/roundup-demo.1'])) # add the templates to the data files lists from roundup.init import listTemplates templates = [t['path'] for t in listTemplates('templates').values()] for tdir in templates: # scan for data files for idir in '. detectors extensions html'.split(): idir = os.path.join(tdir, idir) if not os.path.isdir(idir): continue tfiles = [] for f in os.listdir(idir): if f.startswith('.'): continue ifile = os.path.join(idir, f) if os.path.isfile(ifile): tfiles.append(ifile) installdatafiles.append( (os.path.join('share', 'roundup', idir), tfiles) ) # add message files for (_dist_file, _mo_file) in list_message_files(): installdatafiles.append((os.path.dirname(_mo_file), [os.path.join("build", _mo_file)])) # perform the setup action from roundup import __version__ setup( name = "roundup", version = __version__, description = "A simple-to-use and -install issue-tracking system" " with command-line, web and e-mail interfaces. Highly" " customisable.", long_description =
self.hour, self.minute, self.second, 0, 0, 0))
self.hour, self.minute, int(self.second), 0, 0, 0))
def pretty(self, format='%d %B %Y'): ''' print up the date date using a pretty format...
self._nodeid, classname)
self._nodeid, classname, property, itemid)
def hasPermission(self, permission, classname=_marker, property=None, itemid=None): '''Determine if the user has the Permission.
return reduce(operator.add, [len(x) for x in stores], 0)
return len(self.items()) def has_key(self, key): for store in self.stores: if store.has_key(key): return 1 return 0
def __len__(self): return reduce(operator.add, [len(x) for x in stores], 0)
self.stores.append(store)
self.stores = [store] + self.stores
def push(self, store): self.stores.append(store)
try: self.handle_message(message) except MailUsageError, value: fulldoc = '\n'.join(string.split(__doc__, '\n')[2:]) sendto = [message.getaddrlist('from')[0][1]] m = ['Subject: Failed issue tracker submission', ''] m.append(str(value)) m.append('\n\nMail Gateway Help\n=================') m.append(fulldoc) except: sendto = [message.getaddrlist('from')[0][1]] m = ['Subject: failed issue tracker submission']
sendto = message.getaddrlist('from') if sendto: try: self.handle_message(message) return except MailUsageError, value: fulldoc = '\n'.join(string.split(__doc__, '\n')[2:]) sendto = [sendto[0][1]] m = ['Subject: Failed issue tracker submission', ''] m.append(str(value)) m.append('\n\nMail Gateway Help\n=================') m.append(fulldoc) except: sendto = [sendto[0][1]] m = ['Subject: failed issue tracker submission'] m.append('') m.append('---- traceback of failure ----') s = cStringIO.StringIO() import traceback traceback.print_exc(None, s) m.append(s.getvalue()) m.append('---- failed message follows ----') try: message.fp.seek(0) except: pass m.append(message.fp.read()) else: sendto = [self.ADMIN_EMAIL] m = ['Subject: badly formed message from mail gateway']
def handle_Message(self, message): '''Handle an RFC822 Message
m.append('---- traceback of failure ----') s = cStringIO.StringIO() import traceback traceback.print_exc(None, s) m.append(s.getvalue())
m.append('The mail gateway retrieved a message which has no From:') m.append('line, indicating that it is corrupt. Please check your') m.append('mail gateway source.') m.append('')
def handle_Message(self, message): '''Handle an RFC822 Message
if m: try: smtp = smtplib.SMTP(self.MAILHOST) smtp.sendmail(self.ADMIN_EMAIL, sendto, '\n'.join(m)) except socket.error, value: return "Couldn't send confirmation email: mailhost %s"%value except smtplib.SMTPException, value: return "Couldn't send confirmation email: %s"%value
try: smtp = smtplib.SMTP(self.MAILHOST) smtp.sendmail(self.ADMIN_EMAIL, sendto, '\n'.join(m)) except socket.error, value: raise MailGWError, "Couldn't send confirmation email: "\ "mailhost %s"%value except smtplib.SMTPException, value: raise MailGWError, "Couldn't send confirmation email: %s"%value
def handle_Message(self, message): '''Handle an RFC822 Message
props[key] = date.Date(value)
try: props[key] = date.Date(value) except ValueError, message: raise UsageError, ''' Subject argument list contains an invalid date for %s. Error was: %s Subject was: "%s" '''%(key, message, subject)
def handle_message(self, message): ''' message - a Message instance
props[key] = date.Interval(value)
try: props[key] = date.Interval(value) except ValueError, message: raise UsageError, ''' Subject argument list contains an invalid date interval for %s. Error was: %s Subject was: "%s" '''%(key, message, subject)
def handle_message(self, message): ''' message - a Message instance
cl.set(nodeid, **props)
try: cl.set(nodeid, **props) except (TypeError, IndexError, ValueError), message: raise MailUsageError, ''' There was a problem with the message you sent: %s '''%message
def handle_message(self, message): ''' message - a Message instance
props['status'] = '1'
try: unread_id = self.db.status.lookup('unread') except KeyError: pass else: props['status'] = '1'
def handle_message(self, message): ''' message - a Message instance
nodeid = cl.create(**props)
try: nodeid = cl.create(**props) except (TypeError, IndexError, ValueError), message: raise MailUsageError, ''' There was a problem with the message you sent: %s '''%message
def handle_message(self, message): ''' message - a Message instance
for cl in 'issue', 'file', 'msg', 'keyword':
for cl in 'issue', 'file', 'msg', 'keyword', 'priority', 'status':
def open(name=None): ''' as from the roundupdb method openDB ''' from roundup.hyperdb import String, Password, Date, Link, Multilink from roundup.hyperdb import Interval, Boolean, Number # open the database db = Database(config, name) # # Now initialise the schema. Must do this each time the database is # opened. # # Class automatically gets these properties: # creation = Date() # activity = Date() # creator = Link('user') pri = Class(db, "priority", name=String(), order=String()) pri.setkey("name") stat = Class(db, "status", name=String(), order=String()) stat.setkey("name") keyword = Class(db, "keyword", name=String()) keyword.setkey("name") query = Class(db, "query", klass=String(), name=String(), url=String()) query.setkey("name") # add any additional database schema configuration here # Note: roles is a comma-separated string of Role names user = Class(db, "user", username=String(), password=Password(), address=String(), realname=String(), phone=String(), organisation=String(), alternate_addresses=String(), queries=Multilink('query'), roles=String(), timezone=String()) user.setkey("username") # FileClass automatically gets these properties: # content = String() [saved to disk in <tracker home>/db/files/] # (it also gets the Class properties creation, activity and creator) msg = FileClass(db, "msg", author=Link("user", do_journal='no'), recipients=Multilink("user", do_journal='no'), date=Date(), summary=String(), files=Multilink("file"), messageid=String(), inreplyto=String()) file = FileClass(db, "file", name=String(), type=String()) # IssueClass automatically gets these properties: # title = String() # messages = Multilink("msg") # files = Multilink("file") # nosy = Multilink("user") # superseder = Multilink("issue") # (it also gets the Class properties creation, activity and creator) issue = IssueClass(db, "issue", assignedto=Link("user"), topic=Multilink("keyword"), priority=Link("priority"), status=Link("status")) # # SECURITY SETTINGS # # See the configuration and customisation document for information # about security setup. # Assign the access and edit Permissions for issue, file and message # to regular users now for cl in 'issue', 'file', 'msg', 'query', 'keyword': p = db.security.getPermission('View', cl) db.security.addPermissionToRole('User', p) p = db.security.getPermission('Edit', cl) db.security.addPermissionToRole('User', p) for cl in 'priority', 'status': p = db.security.getPermission('View', cl) db.security.addPermissionToRole('User', p) # and give the regular users access to the web and email interface p = db.security.getPermission('Web Access') db.security.addPermissionToRole('User', p) p = db.security.getPermission('Email Access') db.security.addPermissionToRole('User', p) # May users view other user information? Comment these lines out # if you don't want them to p = db.security.getPermission('View', 'user') db.security.addPermissionToRole('User', p) # Assign the appropriate permissions to the anonymous user's Anonymous # Role. Choices here are: # - Allow anonymous users to register through the web p = db.security.getPermission('Web Registration') db.security.addPermissionToRole('Anonymous', p) # - Allow anonymous (new) users to register through the email gateway p = db.security.getPermission('Email Registration') db.security.addPermissionToRole('Anonymous', p) # - Allow anonymous users access to view issues (which implies being # able to view all linked information too for cl in 'issue', 'file', 'msg', 'keyword': p = db.security.getPermission('View', cl) db.security.addPermissionToRole('Anonymous', p) # - Allow anonymous users access to edit the "issue" class of data # Note: this also grants access to create related information like # files and messages etc that are linked to issues #p = db.security.getPermission('Edit', 'issue') #db.security.addPermissionToRole('Anonymous', p) # oh, g'wan, let anonymous access the web interface too p = db.security.getPermission('Web Access') db.security.addPermissionToRole('Anonymous', p) import detectors detectors.init(db) # schema is set up - run any post-initialisation db.post_init() return db
return self.user.lookup(self.journaltag)
if (self.journal_uid is None or self.journal_uid[0] != self.journaltag): uid = self.user.lookup(self.journaltag) self.journal_uid = (self.journaltag, uid) return self.journal_uid[1]
def getuid(self): """Return the id of the "user" node associated with the user that owns this connection to the hyperdatabase.""" if self.journaltag is None: return None elif self.journaltag == 'admin': # admin user may not exist, but always has ID 1 return '1' else: return self.user.lookup(self.journaltag)
ZRoundup.manage_addZRoundupForm, ZRoundup.manage_addZRoundup
manage_addZRoundupForm, manage_addZRoundup
def initialize(context): context.registerClass( ZRoundup, meta_type = 'Z Roundup', constructors = ( ZRoundup.manage_addZRoundupForm, ZRoundup.manage_addZRoundup ) )
self.additional_headers['Expires'] = 'Thu, 1 Jan 1970 00:00:00 GMT'
date = rfc822.formatdate(time.time() + 5) self.additional_headers['Expires'] = date
def inner_main(self): ''' Process a request.
mt = mimetypes.guess_type(str(file))[0]
file = str(file) mt = mimetypes.guess_type(file)[0]
def serve_static_file(self, file): ims = None # see if there's an if-modified-since... if hasattr(self.request, 'headers'): ims = self.request.headers.getheader('if-modified-since') 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
mt = 'text/plain'
if file.endswith('.css'): mt = 'text/css' else: mt = 'text/plain'
def serve_static_file(self, file): ims = None # see if there's an if-modified-since... if hasattr(self.request, 'headers'): ims = self.request.headers.getheader('if-modified-since') 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
self.form = {} for name, value in cgi.parse_qsl(url): if self.form.has_key(name): if isinstance(self.form[name], type([])): self.form[name].append(cgi.MiniFieldStorage(name, value)) else: self.form[name] = [self.form[name], cgi.MiniFieldStorage(name, value)] else: self.form[name] = cgi.MiniFieldStorage(name, value)
env = {'QUERY_STRING': url} self.form = cgi.FieldStorage(environ=env)
def updateFromURL(self, url): ''' Parse the URL for query args, and update my attributes using the values. ''' self.form = {} for name, value in cgi.parse_qsl(url): if self.form.has_key(name): if isinstance(self.form[name], type([])): self.form[name].append(cgi.MiniFieldStorage(name, value)) else: self.form[name] = [self.form[name], cgi.MiniFieldStorage(name, value)] else: self.form[name] = cgi.MiniFieldStorage(name, value) self._post_init()
roundup_server.RoundupRequestHandler.TRACKER_HOMES = {'demo': home}
def run_demo(home): """Run the demo tracker installed in ``home``""" roundup_server.RoundupRequestHandler.TRACKER_HOMES = {'demo': home} cfg = configuration.CoreConfig(home) url = cfg["TRACKER_WEB"] hostname, port = urlparse.urlparse(url)[1].split(':') port = int(port) success_message = '''Server running - connect to: %s
sys.argv = sys.argv[:1] roundup_server.run(port=port, success_message=success_message)
sys.argv = sys.argv[:1] + ['-p', str(port), 'demo=' + home] roundup_server.run(success_message=success_message)
def run_demo(home): """Run the demo tracker installed in ``home``""" roundup_server.RoundupRequestHandler.TRACKER_HOMES = {'demo': home} cfg = configuration.CoreConfig(home) url = cfg["TRACKER_WEB"] hostname, port = urlparse.urlparse(url)[1].split(':') port = int(port) success_message = '''Server running - connect to: %s
path_components = url[2].split( '/' )
path = url[2] path_components = path.split( '/' )
def _opendb(self): '''Open the roundup instance database for a transaction. ''' instance = roundup.instance.open(self.instance_home) request = RequestWrapper(self.REQUEST['RESPONSE']) env = self.REQUEST.environ
where.append(' or '.join(l))
if l: where.append(' or '.join(l))
def filter(self, search_matches, filterspec, sort=(None,None), group=(None,None)): '''Return a list of the ids of the active nodes in this class that match the 'filter' spec, sorted by the group spec and then the sort spec
def ngettext(self, singular, plural, count):
def ungettext(self, singular, plural, count):
def ngettext(self, singular, plural, count): if count == 1: _msg = singular else: _msg = plural return self.gettext(_msg)
return self.gettext(_msg)
return self.ugettext(_msg)
def ngettext(self, singular, plural, count): if count == 1: _msg = singular else: _msg = plural return self.gettext(_msg)
try: _fallback = translation(domain=domain, languages=["en"], class_=RoundupTranslations) except IOError:
if language == "en":
def get_translation(language=None, domain=DOMAIN): """Return Translation object for given language and domain""" if language: _languages = [language] else: # use OS environment _languages = None # except for english ("en") language, add english fallback if available try: _fallback = translation(domain=domain, languages=["en"], class_=RoundupTranslations) except IOError: # no .mo files found _fallback = None # get the translation try: _translation = translation(domain=domain, languages=_languages, class_=RoundupTranslations) except IOError: _translation = None # see what's found if _translation and _fallback: _translation.add_fallback(_fallback) elif _fallback: _translation = _fallback elif not _translation: _translation = RoundupNullTranslations() return _translation
elif have_datetime and isinstance(spec, datetime.datetime):
elif isinstance(spec, datetime.datetime):
def __init__(self, spec='.', offset=0, add_granularity=0, translator=i18n): """Construct a date given a specification and a time zone offset.
ts = calendar.timegm((y,m,d,H+offset,M,S,0,0,0))
def __init__(self, spec='.', offset=0, add_granularity=0, translator=i18n): """Construct a date given a specification and a time zone offset.
self.second, x, x, x = time.gmtime(ts)
self.second = _local_to_utc(y, m, d, H, M, S, offset)
def __init__(self, spec='.', offset=0, add_granularity=0, translator=i18n): """Construct a date given a specification and a time zone offset.
H = -offset
H = 0
def set(self, spec, offset=0, date_re=date_re, serialised_re=serialised_date_re, add_granularity=0): ''' set the date to the value in spec '''
H = int(info['H']) - offset
H = int(info['H'])
def set(self, spec, offset=0, date_re=date_re, serialised_re=serialised_date_re, add_granularity=0): ''' set the date to the value in spec '''
self.second, x, x, x = time.gmtime(ts)
self.second = y, m, d, H, M, S
def set(self, spec, offset=0, date_re=date_re, serialised_re=serialised_date_re, add_granularity=0): ''' set the date to the value in spec '''
return Date((self.year, self.month, self.day, self.hour + offset, self.minute, self.second, 0, 0, 0), translator=self.translator)
y, m, d, H, M, S = _utc_to_local(self.year, self.month, self.day, self.hour, self.minute, self.second, offset) return Date((y, m, d, H, M, S, 0, 0, 0), translator=self.translator)
def local(self, offset): """ Return this date as yyyy-mm-dd.hh:mm:ss in a local time zone. """ return Date((self.year, self.month, self.day, self.hour + offset, self.minute, self.second, 0, 0, 0), translator=self.translator)
def _serve_file(self, last_modified, mime_type, content):
def _serve_file(self, 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'): ims = self.request.headers.getheader('if-modified-since') 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'] if ims: ims = rfc822.parsedate(ims)[:6] lmtt = time.gmtime(lmt)[:6] if lmtt <= ims: raise NotModified
lmt = rfc822.formatdate(last_modified)
lmt = rfc822.formatdate(lmt)
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'): ims = self.request.headers.getheader('if-modified-since') 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'] if ims: ims = rfc822.parsedate(ims)[:6] lmtt = time.gmtime(lmt)[:6] if lmtt <= ims: raise NotModified
smtp = smtplib.SMTP(self.MAILHOST) smtp.sendmail(self.ADMIN_EMAIL, sendto, message.getvalue())
if ROUNDUPDBSENDMAILDEBUG: print 'From: %s\nTo: %s\n%s\n=-=-=-=-=-=-=-='%( self.ADMIN_EMAIL, sendto, message.getvalue()) else: smtp = smtplib.SMTP(self.MAILHOST) smtp.sendmail(self.ADMIN_EMAIL, sendto, message.getvalue())
def sendmessage(self, nodeid, msgid, change_note): """Send a message to the members of an issue's nosy list.
elif hqre.match(c):
elif hqre.match(c) and c != '_':
def encode_header(header, charset='utf-8'): """ Will encode in quoted-printable encoding only if header contains non latin characters """ # Return empty headers unchanged if not header: return header # return plain header if it is not contains non-ascii characters if hqre.match(header): return header quoted = '' #max_encoded = 76 - len(charset) - 7 for c in header: # Space may be represented as _ instead of =20 for readability if c == ' ': quoted += '_' # These characters can be included verbatim elif hqre.match(c): quoted += c # Otherwise, replace with hex value like =E2 else: quoted += "=%02X" % ord(c) plain = 0 return '=?%s?q?%s?=' % (charset, quoted)
if extension: filename = '%s.%s'%(name, extension) else: filename = name src = os.path.join(self.dir, filename) if not os.path.exists(src): filename = filename + '.html' src = os.path.join(self.dir, filename) if not os.path.exists(src): if not extension: raise NoTemplate, 'Template file "%s" doesn\'t exist'%name generic = '_generic.%s'%extension src = os.path.join(self.dir, generic) if not os.path.exists(src): generic = '_generic.%s.html'%extension src = os.path.join(self.dir, generic) if not os.path.exists(src): raise NoTemplate, 'No template file exists for '\ 'templating "%s" with template "%s" (neither '\ '"%s" nor "%s")'%(name, extension, filename, generic) filename = generic
src, filename = find_template(self.dir, name, extension)
def get(self, name, extension=None): ''' Interface to get a template, possibly loading a compiled template.
if os.path.exists(os.path.join(self._db.config.TEMPLATES, classname + '.item')): current[prop_n] = '<a href="%s%s">%s</a>'%(classname, self._klass.get(self._nodeid, prop_n, None), current[prop_n])
try: find_template(self._db.config.TEMPLATES, classname, 'item') except NoTemplate: pass else: id = self._klass.get(self._nodeid, prop_n, None) current[prop_n] = '<a href="%s%s">%s</a>'%( classname, id, current[prop_n])
def history(self, direction='descending', dre=re.compile('\d+')): l = ['<table class="history">' '<tr><th colspan="4" class="header">', _('History'), '</th></tr><tr>', _('<th>Date</th>'), _('<th>User</th>'), _('<th>Action</th>'), _('<th>Args</th>'), '</tr>'] current = {} comments = {} history = self._klass.history(self._nodeid) history.sort() timezone = self._db.getUserTimezone() if direction == 'descending': history.reverse() for prop_n in self._props.keys(): prop = self[prop_n] if isinstance(prop, HTMLProperty): current[prop_n] = prop.plain() # make link if hrefable if (self._props.has_key(prop_n) and isinstance(self._props[prop_n], hyperdb.Link)): classname = self._props[prop_n].classname if os.path.exists(os.path.join(self._db.config.TEMPLATES, classname + '.item')): current[prop_n] = '<a href="%s%s">%s</a>'%(classname, self._klass.get(self._nodeid, prop_n, None), current[prop_n])
DEBUG = open(DEBUG, 'a')
if DEBUG == 'stdout': DEBUG = sys.stdout else: DEBUG = open(DEBUG, 'a')
def write(self, content): pass
TRACE = open(TRACE, 'w')
if TRACE == 'stdout': TRACE = sys.stdout else: TRACE = open(TRACE, 'w')
def write(self, content): pass
def getnodeids(self, classname, db=None): '''Retrieve all the ids of the nodes for a particular Class. ''' raise NotImplementedError
def getnodeids(self, classname, db=None): '''Retrieve all the ids of the nodes for a particular Class. ''' raise NotImplementedError
fid, name = event['old_value'].split(':')
fid, name = event['old_value'].split(':', 1)
def to_date(ts): return date.Date(time.gmtime(float(ts)))
if (properties.has_key('creation') or properties.has_key('activity') or properties.has_key('creator')): raise ValueError, '"creation", "activity" and "creator" are '\ 'reserved' if hasattr(db, classname): raise ValueError, "Class %s already exists"%classname
def __init__(self, db, classname, **properties): #self.db = weakref.proxy(db) self.db = db self.classname = classname self.keyname = None self.ruprops = properties self.privateprops = { 'id' : hyperdb.String(), 'activity' : hyperdb.Date(), 'creation' : hyperdb.Date(), 'creator' : hyperdb.Link('user') }
self.keyname = None
self.key = None
def __init__(self, db, classname, **properties): #self.db = weakref.proxy(db) self.db = db self.classname = classname self.keyname = None self.ruprops = properties self.privateprops = { 'id' : hyperdb.String(), 'activity' : hyperdb.Date(), 'creation' : hyperdb.Date(), 'creator' : hyperdb.Link('user') }