rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
env['TRACKER_NAME'] = instance_name
|
env['TRACKER_NAME'] = tracker_name
|
def inner_run_cgi(self): ''' This is the inner part of the CGI handling '''
|
c = instance.Client(instance, self, env)
|
c = tracker.Client(tracker, self, env)
|
def inner_run_cgi(self): ''' This is the inner part of the CGI handling '''
|
roundup-server [-n hostname] [-p port] [-l file] [-d file] [name=instance home]*
|
roundup-server [-n hostname] [-p port] [-l file] [-d file] [name=tracker home]*
|
def usage(message=''): if message: message = _('Error: %(error)s\n\n')%{'error': message} print _('''%(message)sUsage:
|
name=instance home Sets the instance home(s) to use. The name is how the instance is
|
name=tracker home Sets the tracker home(s) to use. The name is how the tracker is
|
def usage(message=''): if message: message = _('Error: %(error)s\n\n')%{'error': message} print _('''%(message)sUsage:
|
instance home is the directory that was identified when you did
|
tracker home is the directory that was identified when you did
|
def usage(message=''): if message: message = _('Error: %(error)s\n\n')%{'error': message} print _('''%(message)sUsage:
|
where.append(' or '.join(["_%s._%s LIKE '%s'"%(cn, k, s) for s in v]))
|
where.append('(' +' or '.join(["_%s._%s LIKE '%s'"%(cn, k, s) for s in v]) +')')
|
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
|
where.append('(_%s._%s in (%s))'%(cn, k, s))
|
l.append('(_%s._%s in (%s))'%(cn, k, s))
|
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
|
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
|
sql = 'select id,__retired__ from _%s where _%s=%s'%(self.classname, self.key, self.db.arg)
|
sql = '''select id from _%s where _%s=%s and __retired__ != '1' '''%(self.classname, self.key, self.db.arg)
|
def lookup(self, keyvalue): '''Locate a particular node by its key property and return its id.
|
l = self.db.cursor.fetchall() if not l or int(l[0][1]):
|
row = self.db.sql_fetchone() if not row:
|
def lookup(self, keyvalue): '''Locate a particular node by its key property and return its id.
|
return l[0][0]
|
return row[0]
|
def lookup(self, keyvalue): '''Locate a particular node by its key property and return its id.
|
return templating.translationService.translate(domain="roundup", msgid=msgid, context=self.context)
|
return self.client.translator.gettext(msgid)
|
def gettext(self, msgid): """Return the localized translation of msgid""" return templating.translationService.translate(domain="roundup", msgid=msgid, context=self.context)
|
converter = _converters.get(rutyp.__class__, None)
|
converter = _converters.get(raw.__class__, None)
|
def get(self, nodeid, propname, default=_marker, cache=1): '''Get the value of a property on an existing node of this class.
|
str = time.strftime(format, (self.year, self.month, self.day, self.hour, self.minute, int(self.second), 0, 0, 0))
|
t = (self.year, self.month, self.day, self.hour, self.minute, int(self.second), 0, 0, 0) t = calendar.timegm(t) t = time.gmtime(t) str = time.strftime(format, t)
|
def pretty(self, format='%d %B %Y'): ''' print up the date date using a pretty format...
|
""'''Usage: install [template [backend [admin password]]]
|
""'''Usage: install [template [backend [admin password [key=val[,key=val]]]]]
|
def do_install(self, tracker_home, args): ""'''Usage: install [template [backend [admin password]]] Install a new Roundup tracker.
|
init.install(tracker_home, templates[template]['path'])
|
init.install(tracker_home, templates[template]['path'], settings=defns)
|
def do_install(self, tracker_home, args): ""'''Usage: install [template [backend [admin password]]] Install a new Roundup tracker.
|
except (getopt.GetoptError), e:
|
except (getopt.GetoptError, configuration.ConfigurationError), e:
|
def run(port=undefined, success_message=None): ''' Script entry point - handle args and figure out what to to. ''' # time out after a minute if we can import socket if hasattr(socket, 'setdefaulttimeout'): socket.setdefaulttimeout(60) config = ServerConfig() options = "hvS" if RoundupService: options += 'c' try: (optlist, args) = config.getopt(sys.argv[1:], options, ("help", "version", "save-config",), host="n:", port="p:", group="g:", user="u:", logfile="l:", pidfile="d:", log_hostnames="N") except (getopt.GetoptError), e: #, configuration.ConfigurationError), e: usage(str(e)) return # if running in windows service mode, don't do any other stuff if ("-c", "") in optlist: RoundupService.address = (config.HOST, config.PORT) # XXX why the 1st argument to the service is "-c" # instead of the script name??? return win32serviceutil.HandleCommandLine(RoundupService, argv=["-c"] + args) # add tracker names from command line. # this is done early to let '--save-config' handle the trackers. if args: for arg in args: try: name, home = arg.split('=') except ValueError: raise ValueError, _("Instances must be name=home") config.add_option(TrackerHomeOption(config, "trackers", name)) config["TRACKERS_" + name.upper()] = home # handle remaining options if optlist: for (opt, arg) in optlist: if opt in ("-h", "--help"): usage() elif opt in ("-v", "--version"): print '%s (python %s)' % (roundup_version, sys.version.split()[0]) elif opt in ("-S", "--save-config"): config.save() print _("Configuration saved to %s") % config.filepath # any of the above options prevent server from running return RoundupRequestHandler.LOG_IPADDRESS = not config.LOG_HOSTNAMES # obtain server before changing user id - allows to use port < # 1024 if started as root try: httpd = server_class((config.HOST, config.PORT), RoundupRequestHandler) except socket.error, e: if e[0] == errno.EADDRINUSE: raise socket.error, \ _("Unable to bind to port %s, port already in use.") \ % config.PORT raise # change user and/or group setgid(config.GROUP) setuid(config.USER) # apply tracker specs for (name, home) in config.trackers(): home = os.path.abspath(home) RoundupRequestHandler.TRACKER_HOMES[name] = home # we don't want the cgi module interpreting the command-line args ;) sys.argv = sys.argv[:1] # fork the server from our parent if a pidfile is specified if config.PIDFILE: if not hasattr(os, 'fork'): print _("Sorry, you can't run the server as a daemon" " on this Operating System") sys.exit(0) else: daemonize(config.PIDFILE) # redirect stdout/stderr to our logfile if config.LOGFILE: # appending, unbuffered sys.stdout = sys.stderr = open(config.LOGFILE, 'a', 0) if success_message: print success_message else: print _('Roundup server started on %(HOST)s:%(PORT)s') \ % config try: httpd.serve_forever() except KeyboardInterrupt: print 'Keyboard Interrupt: exiting'
|
dirname = os.path.join(self.tracker_home, dirname) if os.path.isdir(dirname): for name in os.listdir(dirname):
|
dirpath = os.path.join(self.tracker_home, dirname) if os.path.isdir(dirpath): for name in os.listdir(dirpath):
|
def load_extensions(self, parent, dirname): dirname = os.path.join(self.tracker_home, dirname) if os.path.isdir(dirname): for name in os.listdir(dirname): if not name.endswith('.py'): continue vars = {} self._load_python(os.path.join(dirname, name), vars) vars['init'](parent)
|
if self.user in ('admin', self.db.user.get(self.nodeid, 'username')): self.shownode(message) else:
|
if self.user == 'anonymous':
|
def showuser(self, message=None): ''' display an item ''' if self.user in ('admin', self.db.user.get(self.nodeid, 'username')): self.shownode(message) else: raise Unauthorised
|
print self.user, password
|
def login_action(self, message=None): if not self.form.has_key('__login_name'): return self.login(message='Username required') self.user = self.form['__login_name'].value if self.form.has_key('__login_password'): password = self.form['__login_password'].value else: password = '' print self.user, password # make sure the user exists try: uid = self.db.user.lookup(self.user) except KeyError: name = self.user self.make_user_anonymous() return self.login(message='No such user "%s"'%name)
|
|
uid = self.db.user.lookup(self.user) user = binascii.b2a_base64('%s:%s'%(self.user, password)).strip() path = '/'.join((self.env['SCRIPT_NAME'], self.env['INSTANCE_NAME'], '')) self.header({'Set-Cookie': 'roundup_user=%s; Path=%s;'%(user, path)}) return self.index()
|
user = binascii.b2a_base64('%s:%s'%(user, password)).strip() path = '/'.join((self.env['SCRIPT_NAME'], self.env['INSTANCE_NAME'])) self.header({'Set-Cookie': 'roundup_user="%s"; Path="%s";'%(user, path)})
|
def login_action(self, message=None): if not self.form.has_key('__login_name'): return self.login(message='Username required') self.user = self.form['__login_name'].value if self.form.has_key('__login_password'): password = self.form['__login_password'].value else: password = '' print self.user, password # make sure the user exists try: uid = self.db.user.lookup(self.user) except KeyError: name = self.user self.make_user_anonymous() return self.login(message='No such user "%s"'%name)
|
path = '/'.join((self.env['SCRIPT_NAME'], self.env['INSTANCE_NAME'], ''))
|
def logout(self, message=None): self.make_user_anonymous() # construct the logout cookie path = '/'.join((self.env['SCRIPT_NAME'], self.env['INSTANCE_NAME'], '')) now = Cookie._getdate() self.header({'Set-Cookie': 'roundup_user=deleted; Max-Age=0; expires=%s; Path=%s;'%(now, path)}) return self.login()
|
|
'roundup_user=deleted; Max-Age=0; expires=%s; Path=%s;'%(now, path)})
|
'roundup_user=deleted; Max-Age=0; expires="%s"; Path="%s";'%(now, path)})
|
def logout(self, message=None): self.make_user_anonymous() # construct the logout cookie path = '/'.join((self.env['SCRIPT_NAME'], self.env['INSTANCE_NAME'], '')) now = Cookie._getdate() self.header({'Set-Cookie': 'roundup_user=deleted; Max-Age=0; expires=%s; Path=%s;'%(now, path)}) return self.login()
|
uid = self.db.user.lookup(self.user) user = binascii.b2a_base64('%s:%s'%(self.user, password)).strip() path = '/'.join((self.env['SCRIPT_NAME'], self.env['INSTANCE_NAME'], '')) self.header({'Set-Cookie': 'roundup_user=%s; Path=%s;'%(user, path)})
|
self.set_cookie(self.user, password)
|
def newuser_action(self, message=None): ''' create a new user based on the contents of the form and then set the cookie ''' # re-open the database as "admin" self.db.close() self.db = self.instance.open('admin')
|
authid = messages.get(msgid, 'inreplyto') recipients = messages.get(msgid, 'messageid')
|
inreplyto = messages.get(msgid, 'inreplyto') messageid = messages.get(msgid, 'messageid')
|
def send_message(self, nodeid, msgid, note, sendto, from_address=None, bcc_sendto=[]): '''Actually send the nominated message from this node to the sendto recipients, with the note appended. ''' users = self.db.user messages = self.db.msg files = self.db.file
|
)
|
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())
|
|
self.pagesize = 50
|
self.pagesize = 5
|
def _post_init(self): ''' Set attributes based on self.form ''' # extract the index display information from the form self.columns = [] for name in ':columns @columns'.split(): if self.form.has_key(name): self.special_char = name[0] self.columns = handleListCGIValue(self.form[name]) break self.show = support.TruthDict(self.columns)
|
if not d.has_key(propname):
|
if (not d.has_key(propname)) or (d[propname] is None):
|
def get(self, nodeid, propname, default=_marker, cache=1): '''Get the value of a property on an existing node of this class.
|
new_value = cl.get(nodeid, key)
|
try: new_value = cl.get(nodeid, key) except KeyError: continue
|
def generateChangeNote(self, nodeid, oldvalues): """Generate a change note that lists property changes """ if __debug__ : if not isinstance(oldvalues, type({})) : raise TypeError("'oldvalues' must be dict-like, not %s."% type(oldvalues))
|
filename = filename + extension src = os.path.join(dir, filename)
|
f = filename + extension src = os.path.join(dir, f)
|
def find_template(dir, name, view): ''' Find a template in the nominated dir ''' # find the source if view: filename = '%s.%s'%(name, view) else: filename = name # try old-style src = os.path.join(dir, filename) if os.path.exists(src): return (src, filename) # try with a .html or .xml extension (new-style) for extension in '.html', '.xml': filename = filename + extension src = os.path.join(dir, filename) if os.path.exists(src): return (src, filename) # no view == no generic template is possible if not view: raise NoTemplate, 'Template file "%s" doesn\'t exist'%name # try for a _generic template generic = '_generic.%s'%view src = os.path.join(dir, generic) if os.path.exists(src): return (src, generic) # finally, try _generic.html generic = generic + '.html' src = os.path.join(dir, generic) if os.path.exists(src): return (src, generic) raise NoTemplate, 'No template file exists for templating "%s" '\ 'with template "%s" (neither "%s" nor "%s")'%(name, view, filename, generic)
|
return (src, filename)
|
return (src, f)
|
def find_template(dir, name, view): ''' Find a template in the nominated dir ''' # find the source if view: filename = '%s.%s'%(name, view) else: filename = name # try old-style src = os.path.join(dir, filename) if os.path.exists(src): return (src, filename) # try with a .html or .xml extension (new-style) for extension in '.html', '.xml': filename = filename + extension src = os.path.join(dir, filename) if os.path.exists(src): return (src, filename) # no view == no generic template is possible if not view: raise NoTemplate, 'Template file "%s" doesn\'t exist'%name # try for a _generic template generic = '_generic.%s'%view src = os.path.join(dir, generic) if os.path.exists(src): return (src, generic) # finally, try _generic.html generic = generic + '.html' src = os.path.join(dir, generic) if os.path.exists(src): return (src, generic) raise NoTemplate, 'No template file exists for templating "%s" '\ 'with template "%s" (neither "%s" nor "%s")'%(name, view, filename, generic)
|
l = [nodeid, date, user, action, export_data]
|
params = export_data l = [nodeid, date, user, action, params]
|
def export_journals(self): '''Export a class's journal - generate a list of lists of CSV-able data:
|
def history(self, direction='descending'):
|
def history(self, direction='descending', dre=re.compile('\d+')):
|
def history(self, direction='descending'): 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 self.value is None:
|
if self._value is None:
|
def plain(self): ''' Render a "plain" representation of the property ''' if self.value is None: return '' return self._value and "Yes" or "No"
|
nodeid integer, date timestamp, tag varchar(255), action varchar(255), params text)'''%spec.classname
|
nodeid integer, date %s, tag varchar(255), action varchar(255), params text)''' % (spec.classname, self.hyperdb_to_sql_datatypes[hyperdb.Date])
|
def create_journal_table(self, spec): ''' create the journal table for a class given the spec and already-determined cols ''' # journal table cols = ','.join(['%s varchar'%x for x in 'nodeid date tag action params'.split()]) sql = '''create table %s__journal ( nodeid integer, date timestamp, tag varchar(255), action varchar(255), params text)'''%spec.classname self.sql(sql) self.create_journal_table_indexes(spec)
|
raise ValueError, _('default value for ' + \ 'DateHTMLProperty must be either DateHTMLProperty ' + \
|
raise ValueError, _('default value for ' 'DateHTMLProperty must be either DateHTMLProperty '
|
def field(self, size = 30, default = None): ''' Render a form edit field for the property
|
def props_from_args(self, args, klass=None):
|
def props_from_args(self, args):
|
def props_from_args(self, args, klass=None): props = {} for arg in args: if arg.find('=') == -1: raise UsageError, _('argument "%(arg)s" not propname=value')%locals() try: key, value = arg.split('=') except ValueError: raise UsageError, _('argument "%(arg)s" not propname=value')%locals() props[key] = value return props
|
return self.form.keys():
|
return self.form.keys()
|
def keys(self): return self.form.keys():
|
sys.stdout.write ('Exporting %s - %d\r'%(classname, nodeid))
|
sys.stdout.write ('Exporting %s - %s\r'%(classname, nodeid))
|
def do_export(self, args): ""'''Usage: export [class[,class]] export_dir Export the database to colon-separated-value files.
|
sys.stdout.write('Importing %s - %d\r'%(classname, n))
|
sys.stdout.write('Importing %s - %s\r'%(classname, n))
|
def do_import(self, args): ""'''Usage: import import_dir Import a database from the directory containing CSV files, two per class to import.
|
try: tblid = self.tables.find(name=tablenm) except ValueError: open('/u/roundup-sf/roundup/error.out','w').write('\nself.tables=%s, tablenm=%s\n' % (self.tables.structure(), tablenm)) raise
|
tblid = self.tables.find(name=tablenm)
|
def addjournal(self, tablenm, nodeid, action, params, creator=None, creation=None): try: tblid = self.tables.find(name=tablenm) except ValueError: open('/u/roundup-sf/roundup/error.out','w').write('\nself.tables=%s, tablenm=%s\n' % (self.tables.structure(), tablenm)) raise if tblid == -1: tblid = self.tables.append(name=tablenm) if creator is None: creator = self.curuserid else: try: creator = int(creator) except TypeError: creator = int(self.getclass('user').lookup(creator)) if creation is None: creation = int(time.time()) elif isinstance(creation, date.Date): creation = int(calendar.timegm(creation.get_tuple())) # tableid:I,nodeid:I,date:I,user:I,action:I,params:B self.hist.append(tableid=tblid, nodeid=int(nodeid), date=creation, action=action, user = creator, params = marshal.dumps(params))
|
""'''Usage: install [template [backend [admin password [key=val[,key=val]]]]]
|
""'''Usage: install [template [backend [key=val[,key=val]]]]
|
def do_install(self, tracker_home, args): ""'''Usage: install [template [backend [admin password [key=val[,key=val]]]]] Install a new Roundup tracker.
|
The template, backend and admin password may be specified on the command-line as arguments, in that order. The last command line argument allows to pass initial values for config options. For example, passing
|
The template and backend may be specified on the command-line as arguments, in that order. Command line arguments following the backend allows you to pass initial values for config options. For example, passing
|
def do_install(self, tracker_home, args): ""'''Usage: install [template [backend [admin password [key=val[,key=val]]]]] Install a new Roundup tracker.
|
if not self.hasPermission('Edit', self.classname, itemid=qid):
|
if not self.hasPermission('Edit', 'query', itemid=qid):
|
def handle(self): """Mangle some of the form variables.
|
if not self.hasPermission('Create', self.classname):
|
if not self.hasPermission('Create', 'query'):
|
def handle(self): """Mangle some of the form variables.
|
return self.hasPermission('Create', self.classname)
|
return self.hasPermission('Create')
|
def newItemPermission(self, props): """Determine whether the user has permission to create this item.
|
raise Redirect, '%s/%s%s?:ok_message=%s'%(
|
raise Redirect, '%s%s%s?:ok_message=%s'%(
|
def registerAction(self): '''Attempt to create a new user based on the contents of the form and then set the cookie.
|
raise Redirect, '%s/%s%s?:ok_message=%s'%(self.base, self.classname,
|
raise Redirect, '%s%s%s?:ok_message=%s'%(self.base, self.classname,
|
def editItemAction(self): ''' Perform an edit of an item in the database.
|
raise Redirect, '%s/%s%s?:ok_message=%s'%(self.base, self.classname,
|
raise Redirect, '%s%s%s?:ok_message=%s'%(self.base, self.classname,
|
def newItemAction(self): ''' Add a new item to the database.
|
def lookupIds(db, prop, ids, num_re=re.compile('-?\d+')):
|
def lookupIds(db, prop, ids, fail_ok=False, num_re=re.compile('-?\d+')): ''' "fail_ok" should be specified if we wish to pass through bad values (most likely form values that we wish to represent back to the user) '''
|
def lookupIds(db, prop, ids, num_re=re.compile('-?\d+')): cl = db.getclass(prop.classname) l = [] for entry in ids: if num_re.match(entry): l.append(entry) else: try: l.append(cl.lookup(entry)) except KeyError: # ignore invalid keys pass return l
|
except KeyError: pass
|
except (TypeError, KeyError): if fail_ok: l.append(entry)
|
def lookupIds(db, prop, ids, num_re=re.compile('-?\d+')): cl = db.getclass(prop.classname) l = [] for entry in ids: if num_re.match(entry): l.append(entry) else: try: l.append(cl.lookup(entry)) except KeyError: # ignore invalid keys pass return l
|
handleListCGIValue(form[item]))
|
handleListCGIValue(form[item]), fail_ok=True)
|
def __getitem__(self, item): ''' return an HTMLProperty instance ''' #print 'HTMLClass.getitem', (self, item)
|
value = lookupIds(self._db, prop, [value])[0]
|
value = lookupIds(self._db, prop, [value], fail_ok=True)[0]
|
def __getitem__(self, item): ''' return an HTMLProperty instance ''' #print 'HTMLClass.getitem', (self, item)
|
Subject: [issue1] Testing... [assignedto=mary; nosy=john]
|
Subject: [issue1] Testing... [assignedto=mary; nosy=+john]
|
def testFollowup(self): self.doNewIssue()
|
Subject: Re: Testing... [assignedto=mary; nosy=john]
|
Subject: Re: Testing... [assignedto=mary; nosy=+john]
|
def testFollowupTitleMatch(self): self.doNewIssue() message = cStringIO.StringIO('''Content-Type: text/plain;
|
fp.seek(0)
|
message.fp.seek(0)
|
def handle_Message(self, message): '''Handle an RFC822 Message
|
m.append(fp.read())
|
m.append(message.fp.read())
|
def handle_Message(self, message): '''Handle an RFC822 Message
|
trackers = dict([(name, roundup.instance.open(home))
|
trackers = dict([(name, roundup.instance.open(home, optimize=1))
|
def get_server(self): """Return HTTP server object to run""" # redirect stdout/stderr to our logfile # this is done early to have following messages go to this logfile if self["LOGFILE"]: # appending, unbuffered sys.stdout = sys.stderr = open(self["LOGFILE"], 'a', 0) # we don't want the cgi module interpreting the command-line args ;) sys.argv = sys.argv[:1] # preload all trackers unless we are in "debug" mode tracker_homes = self.trackers() if self["MULTIPROCESS"] == "debug": trackers = None else: trackers = dict([(name, roundup.instance.open(home)) for (name, home) in tracker_homes]) # build customized request handler class class RequestHandler(RoundupRequestHandler): LOG_IPADDRESS = not self["LOG_HOSTNAMES"] TRACKER_HOMES = dict(tracker_homes) TRACKERS = trackers # obtain request server class if self["MULTIPROCESS"] not in MULTIPROCESS_TYPES: print _("Multiprocess mode \"%s\" is not available, " "switching to single-process") % self["MULTIPROCESS"] self["MULTIPROCESS"] = "none" server_class = BaseHTTPServer.HTTPServer elif self["MULTIPROCESS"] == "fork": class ForkingServer(SocketServer.ForkingMixIn, BaseHTTPServer.HTTPServer): pass server_class = ForkingServer elif self["MULTIPROCESS"] == "thread": class ThreadingServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): pass server_class = ThreadingServer else: server_class = BaseHTTPServer.HTTPServer # obtain server before changing user id - allows to # use port < 1024 if started as root try: httpd = server_class((self["HOST"], self["PORT"]), RequestHandler) except socket.error, e: if e[0] == errno.EADDRINUSE: raise socket.error, \ _("Unable to bind to port %s, port already in use.") \ % self["PORT"] raise # change user and/or group setgid(self["GROUP"]) setuid(self["USER"]) # return the server return httpd
|
queries.append(qid) self.db.user.set(self.userid, queries=queries)
|
if qid not in queries: queries.append(qid) self.db.user.set(self.userid, queries=queries)
|
def handle(self, wcre=re.compile(r'[\s,]+')): """Mangle some of the form variables.
|
raise ValueError, "%s already indexed on %s"%(self.classname, self.key)
|
else: tablename = "_%s.%s"%(self.classname, self.key) self.db._db.getas(tablename)
|
def setkey(self, propname): '''Select a String property of this class to be the key property.
|
iv = self.db._db.view('_%s' % self.classname)
|
tablename = "_%s.%s"%(self.classname, self.key) iv = self.db._db.view(tablename)
|
def setkey(self, propname): '''Select a String property of this class to be the key property.
|
iv = self.db._db.getas('_%s[k:S,i:I]' % self.classname)
|
iv = self.db._db.getas('_%s[k:S,i:I]' % tablename)
|
def setkey(self, propname): '''Select a String property of this class to be the key property.
|
return self.db._db.view("_%s" % self.classname).ordered(1)
|
tablename = "_%s.%s"%(self.classname, self.key) return self.db._db.view("_%s" % tablename).ordered(1)
|
def getindexview(self, RW=0): # XXX FIX ME -> The RW flag doesn't do anything. return self.db._db.view("_%s" % self.classname).ordered(1)
|
m.insert(0, '----------')
|
def generateChangeNote(self, nodeid, newvalues): """Generate a change note that lists property changes """ cn = self.classname cl = self.db.classes[cn] changed = {} props = cl.getprops(protected=0)
|
|
index.render(filterspec, search_text, filter, columns, sort, group, show_customization=show_customization,
|
index.render(filterspec=filterspec, search_text=search_text, filter=filter, columns=columns, sort=sort, group=group, show_customization=show_customization,
|
def list(self, sort=None, group=None, filter=None, columns=None, filterspec=None, show_customization=None, show_nodes=1, pagesize=None): ''' call the template index with the args
|
return cgi.escape(url)
|
return cgi.escape(html)
|
def html_quote(self, html): '''HTML-quote the supplied text.''' return cgi.escape(url)
|
if (cookie.has_key('roundup_user_2') and cookie['roundup_user_2'].value != 'deleted'):
|
if (cookie.has_key(self.cookie_name) and cookie[self.cookie_name].value != 'deleted'):
|
def determine_user(self): ''' Determine who the user is ''' # determine the uid to use self.opendb('admin') # clean age sessions self.clean_sessions() # make sure we have the session Class sessions = self.db.sessions
|
self.session = cookie['roundup_user_2'].value
|
self.session = cookie[self.cookie_name].value
|
def determine_user(self): ''' Determine who the user is ''' # determine the uid to use self.opendb('admin') # clean age sessions self.clean_sessions() # make sure we have the session Class sessions = self.db.sessions
|
'roundup_user_2=%s; expires=%s; Path=%s;'%(self.session, expire, self.cookie_path)
|
'%s=%s; expires=%s; Path=%s;'%(self.cookie_name, self.session, expire, self.cookie_path)
|
def set_cookie(self, user): ''' Set up a session cookie for the user and 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()
|
'roundup_user_2=deleted; Max-Age=0; expires=%s; Path=%s;'%(now, self.cookie_path)
|
'%s=deleted; Max-Age=0; expires=%s; Path=%s;'%(self.cookie_name, now, self.cookie_path)
|
def logout_action(self): ''' Make us really anonymous - nuke the cookie too ''' # log us out self.make_user_anonymous()
|
else: cell.append(' <a href="%s%s">%s</a>,\n'%( classname, linkid, label))
|
label = None if label is not None: cell.append('%s: <a href="%s%s">%s</a>\n'%( classname, classname, args[k], label))
|
def do_history(self, direction='descending'): ''' list the history of the item
|
print (sql, args)
|
def filter(self, search_matches, filterspec, sort, group): ''' 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
|
|
print l
|
def filter(self, search_matches, filterspec, sort, group): ''' 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
|
|
(FloatNumberOption, "timezone", "0", "Numeric timezone offset used when users do not choose their own\n" "in their settings.",
|
(TimezoneOption, "timezone", "UTC", "Default timezone offset," " applied when user's timezone is not set.",
|
def _value2str(self, value): if value is None: return self.null_strings[0] else: return value
|
<table width="100%%" bgcolor="
|
<table width="100%%" bgcolor="white" cellspacing=0 cellpadding=0 border=0>
|
def linereader(file=file, lnum=[lnum]): line = linecache.getline(file, lnum[0]) lnum[0] = lnum[0] + 1 return line
|
where.append(s)
|
where.append('(' + s +')')
|
def find(self, **propspec): '''Get the ids of nodes in this class which link to the given nodes.
|
where.append(' or '.join(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
|
writer.addheader('Date', time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()))
|
writer.addheader('Date', formatdate(time.gmtime()))
|
def get_standard_message(self, to, subject, author=None): '''Form a standard email message from Roundup.
|
def determine_context(self, dre=re.compile(r'([^\d]+)(\d+)')):
|
def determine_context(self, dre=re.compile(r'([^\d]+)(\d+)'), mc=re.compile(r'(</?(.*?)>)')):
|
def determine_context(self, dre=re.compile(r'([^\d]+)(\d+)')): ''' Determine the context of this page from the URL:
|
reg = self.addPermission(name="Register Web", description="User may register through the web") reg = self.addPermission(name="Register Email", description="User may register through the email")
|
def __init__(self, db): ''' Initialise the permission and role classes, and add in the base roles (for admin user). ''' self.db = weakref.proxy(db) # use a weak ref to avoid circularity
|
|
m.append("New submission from %s%s:"%(authname, authaddr))
|
m.append(_("New submission from %(authname)s%(authaddr)s:") % locals())
|
def send_message(self, nodeid, msgid, note, sendto, from_address=None, bcc_sendto=[]): '''Actually send the nominated message from this node to the sendto recipients, with the note appended. ''' users = self.db.user messages = self.db.msg files = self.db.file
|
m.append("%s%s added the comment:"%(authname, authaddr)) else: m.append("System message:")
|
m.append(_("%(authname)%(authaddr)s added the comment:") % locals()) else: m.append(_("System message:"))
|
def send_message(self, nodeid, msgid, note, sendto, from_address=None, bcc_sendto=[]): '''Actually send the nominated message from this node to the sendto recipients, with the note appended. ''' users = self.db.user messages = self.db.msg files = self.db.file
|
raise Redirect, '%suser%s?@ok_message=%s&@template=%s'%(self.base, self.userid, urllib.quote(message), urllib.quote(self.template))
|
raise Redirect, '%suser%s?@ok_message=%s'%(self.base, self.userid, urllib.quote(message))
|
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)
|
''' If the issue is currently 'unread', 'resolved' or 'done-cbb', then set it to 'chatting'
|
''' If the issue is currently 'unread', 'resolved', 'done-cbb' or None, then set it to 'chatting'
|
def chatty(db, cl, nodeid, newvalues): ''' If the issue is currently 'unread', 'resolved' or 'done-cbb', then set it to 'chatting' ''' # don't fire if there's no new message (ie. chat) if not newvalues.has_key('messages'): return if newvalues['messages'] == cl.get(nodeid, 'messages'): return # get the chatting state ID try: chatting_id = db.status.lookup('chatting') except KeyError: # no chatting state, ignore all this stuff return # get the current value current_status = cl.get(nodeid, 'status') # see if there's an explicit change in this transaction if newvalues.has_key('status'): # yep, skip return # determine the id of 'unread', 'resolved' and 'chatting' fromstates = [] for state in 'unread resolved done-cbb'.split(): try: fromstates.append(db.status.lookup(state)) except KeyError: pass # ok, there's no explicit change, so check if we are in a state that # should be changed if current_status in fromstates: # yep, we're now chatting newvalues['status'] = chatting_id
|
if current_status in fromstates:
|
if current_status in fromstates + [None]:
|
def chatty(db, cl, nodeid, newvalues): ''' If the issue is currently 'unread', 'resolved' or 'done-cbb', then set it to 'chatting' ''' # don't fire if there's no new message (ie. chat) if not newvalues.has_key('messages'): return if newvalues['messages'] == cl.get(nodeid, 'messages'): return # get the chatting state ID try: chatting_id = db.status.lookup('chatting') except KeyError: # no chatting state, ignore all this stuff return # get the current value current_status = cl.get(nodeid, 'status') # see if there's an explicit change in this transaction if newvalues.has_key('status'): # yep, skip return # determine the id of 'unread', 'resolved' and 'chatting' fromstates = [] for state in 'unread resolved done-cbb'.split(): try: fromstates.append(db.status.lookup(state)) except KeyError: pass # ok, there's no explicit change, so check if we are in a state that # should be changed if current_status in fromstates: # yep, we're now chatting newvalues['status'] = chatting_id
|
config["MAIL_TLS_CERFILE"])
|
config["MAIL_TLS_CERTFILE"])
|
def __init__(self, config):
|
(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d(\.\d+)?)
|
(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d?(\.\d+)?)
|
def set(self, spec, offset=0, date_re=re.compile(r''' ((?P<y>\d\d\d\d)([/-](?P<m>\d\d?)([/-](?P<d>\d\d?))?)? # yyyy[-mm[-dd]] |(?P<a>\d\d?)[/-](?P<b>\d\d?))? # or mm-dd (?P<n>\.)? # . (((?P<H>\d?\d):(?P<M>\d\d))?(:(?P<S>\d\d(\.\d+)?))?)? # hh:mm:ss (?P<o>.+)? # offset ''', re.VERBOSE), serialised_re=re.compile(r''' (\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d(\.\d+)?) ''', re.VERBOSE), add_granularity=0): ''' set the date to the value in spec '''
|
return '%4d%02d%02d%02d%02d%02d'%(self.year, self.month,
|
return '%4d%02d%02d%02d%02d%f'%(self.year, self.month,
|
def serialise(self): return '%4d%02d%02d%02d%02d%02d'%(self.year, self.month, self.day, self.hour, self.minute, self.second)
|
def labelprop(self):
|
def labelprop(self, default_to_id=0):
|
def labelprop(self): return 'key'
|
self.header({'Set-Cookie': 'roundup_user="%s"; expires="%s"; Path="%s";' % (
|
self.header({'Set-Cookie': 'roundup_user=%s; expires=%s; Path=%s;' % (
|
def set_cookie(self, user, password): # construct the cookie user = binascii.b2a_base64('%s:%s'%(user, password)).strip() expire = Cookie._getdate(86400*365) path = '/'.join((self.env['SCRIPT_NAME'], self.env['INSTANCE_NAME'])) self.header({'Set-Cookie': 'roundup_user="%s"; expires="%s"; Path="%s";' % ( user, expire, path)})
|
'roundup_user=deleted; Max-Age=0; expires="%s"; Path="%s";'%(now,
|
'roundup_user=deleted; Max-Age=0; expires=%s; Path=%s;'%(now,
|
def logout(self, message=None): self.make_user_anonymous() # construct the logout cookie now = Cookie._getdate() path = '/'.join((self.env['SCRIPT_NAME'], self.env['INSTANCE_NAME'])) self.header({'Set-Cookie': 'roundup_user=deleted; Max-Age=0; expires="%s"; Path="%s";'%(now, path)}) return self.login()
|
value = value.get_tuple()
|
if not isinstance(value, type('')): value = value.get_tuple()
|
def export_journals(self): '''Export a class's journal - generate a list of lists of CSV-able data:
|
' 1 January 2000')
|
' 1 %s 2000' % time.strftime('%B', time.localtime(0)))
|
def testReldate_date(self): self.assertEqual(self.tf.do_reldate('date'), '- 2y 1m') self.assertEqual(self.tf.do_reldate('date', pretty=1), ' 1 January 2000')
|
'nosy': ['1'], 'deadline': date.Date('2004-03-08')}):
|
'nosy': ['1'], 'deadline': date.Date('2004-03-08'), 'files': [f]}):
|
def filteringSetup(self): for user in ( {'username': 'bleep', 'age': 1}, {'username': 'blop', 'age': 1.5}, {'username': 'blorp', 'age': 2}): self.db.user.create(**user) iss = self.db.issue for issue in ( {'title': 'issue one', 'status': '2', 'assignedto': '1', 'foo': date.Interval('1:10'), 'priority': '3', 'deadline': date.Date('2003-02-16.22:50')}, {'title': 'issue two', 'status': '1', 'assignedto': '2', 'foo': date.Interval('1d'), 'priority': '3', 'deadline': date.Date('2003-01-01.00:00')}, {'title': 'issue three', 'status': '1', 'priority': '2', 'nosy': ['1','2'], 'deadline': date.Date('2003-02-18')}, {'title': 'non four', 'status': '3', 'foo': date.Interval('0:10'), 'priority': '2', 'nosy': ['1'], 'deadline': date.Date('2004-03-08')}): self.db.issue.create(**issue) file_content = ''.join([chr(i) for i in range(255)]) self.db.file.create(content=file_content) self.db.commit() return self.assertEqual, self.db.issue.filter
|
file_content = ''.join([chr(i) for i in range(255)]) self.db.file.create(content=file_content)
|
def filteringSetup(self): for user in ( {'username': 'bleep', 'age': 1}, {'username': 'blop', 'age': 1.5}, {'username': 'blorp', 'age': 2}): self.db.user.create(**user) iss = self.db.issue for issue in ( {'title': 'issue one', 'status': '2', 'assignedto': '1', 'foo': date.Interval('1:10'), 'priority': '3', 'deadline': date.Date('2003-02-16.22:50')}, {'title': 'issue two', 'status': '1', 'assignedto': '2', 'foo': date.Interval('1d'), 'priority': '3', 'deadline': date.Date('2003-01-01.00:00')}, {'title': 'issue three', 'status': '1', 'priority': '2', 'nosy': ['1','2'], 'deadline': date.Date('2003-02-18')}, {'title': 'non four', 'status': '3', 'foo': date.Interval('0:10'), 'priority': '2', 'nosy': ['1'], 'deadline': date.Date('2004-03-08')}): self.db.issue.create(**issue) file_content = ''.join([chr(i) for i in range(255)]) self.db.file.create(content=file_content) self.db.commit() return self.assertEqual, self.db.issue.filter
|
|
''' % cfg["TRACKER_WEB"]
|
''' % url
|
def run_demo(home): """Run the demo tracker installed in ``home``""" roundup_server.RoundupRequestHandler.TRACKER_HOMES = {'demo': home} cfg = configuration.CoreConfig(home) success_message = '''Server running - connect to: %s
|
roundup_server.run(success_message=success_message)
|
roundup_server.run(port=port, 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) success_message = '''Server running - connect to: %s
|
if self._value:
|
if self._value and not isinstance(self._value, (str, unicode)):
|
def __init__(self, client, classname, nodeid, prop, name, value, anonymous=0): HTMLProperty.__init__(self, client, classname, nodeid, prop, name, value, anonymous) if self._value: self._value.setTranslator(self._client.translator)
|
self.classname = None
|
self.classname = self.nodeid = None
|
def inner_main(self): ''' Process a request.
|
if ok_message: self.ok_message.append(ok_message) if error_message: self.error_message.append(error_message)
|
def determine_context(self, dre=re.compile(r'([^\d]+)(\d+)')): """ Determine the context of this page from the URL:
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.