## $Id: interfaces.py 7726 2012-02-29 13:41:49Z uli $ ## ## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ## import os import re import codecs import zope.i18nmessageid from datetime import datetime from hurry.file.interfaces import IFileRetrieval from hurry.workflow.interfaces import IWorkflow, IWorkflowInfo from zc.sourcefactory.basic import BasicSourceFactory from zope import schema from zope.pluggableauth.interfaces import IPrincipalInfo from zope.security.interfaces import IGroupClosureAwarePrincipal as IPrincipal from zope.component import getUtility from zope.component.interfaces import IObjectEvent from zope.container.interfaces import INameChooser from zope.interface import Interface, Attribute, implements from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm _ = MessageFactory = zope.i18nmessageid.MessageFactory('waeup.sirp') CREATED = 'created' ADMITTED = 'admitted' CLEARANCE = 'clearance started' REQUESTED = 'clearance requested' CLEARED = 'cleared' PAID = 'school fee paid' RETURNING = 'returning' REGISTERED = 'courses registered' VALIDATED = 'courses validated' default_frontpage = u'' + codecs.open(os.path.join( os.path.dirname(__file__), 'frontpage.rst'), encoding='utf-8', mode='rb').read() def SimpleSIRPVocabulary(*terms): """A well-buildt vocabulary provides terms with a value, token and title for each term """ return SimpleVocabulary([ SimpleTerm(value, value, title) for title, value in terms]) def year_range(): curr_year = datetime.now().year return range(curr_year - 4, curr_year + 5) def academic_sessions(): curr_year = datetime.now().year year_range = range(curr_year - 10, curr_year + 2) return [('%s/%s' % (year,year+1), year) for year in year_range] academic_sessions_vocab = SimpleSIRPVocabulary(*academic_sessions()) registration_states_vocab = SimpleSIRPVocabulary( (_('created'), CREATED), (_('admitted'), ADMITTED), (_('clearance started'), CLEARANCE), (_('clearance requested'), REQUESTED), (_('cleared'), CLEARED), (_('school fee paid'), PAID), (_('returning'), RETURNING), (_('courses registered'), REGISTERED), (_('courses validated'), VALIDATED), ) # Define a valiation method for email addresses class NotAnEmailAddress(schema.ValidationError): __doc__ = u"Invalid email address" check_email = re.compile( r"[a-zA-Z0-9._%-']+@([a-zA-Z0-9-]+.)*[a-zA-Z]{2,4}").match def validate_email(value): if not check_email(value): raise NotAnEmailAddress(value) return True class FatalCSVError(Exception): """Some row could not be processed. """ pass class DuplicationError(Exception): """An exception that can be raised when duplicates are found. When raising :exc:`DuplicationError` you can, beside the usual message, specify a list of objects which are duplicates. These values can be used by catching code to print something helpful or similar. """ def __init__(self, msg, entries=[]): self.msg = msg self.entries = entries def __str__(self): return '%r' % self.msg class RoleSource(BasicSourceFactory): """A source for site roles. """ def getValues(self): # late import: in interfaces we should not import local modules from waeup.sirp.permissions import get_waeup_role_names return get_waeup_role_names() def getTitle(self, value): # late import: in interfaces we should not import local modules from waeup.sirp.permissions import get_all_roles roles = dict(get_all_roles()) if value in roles.keys(): title = roles[value].title if '.' in title: title = title.split('.', 2)[1] return title class CaptchaSource(BasicSourceFactory): """A source for captchas. """ def getValues(self): captchas = ['No captcha', 'Testing captcha', 'ReCaptcha'] try: # we have to 'try' because IConfiguration can only handle # interfaces from w.s.interface. from waeup.sirp.browser.interfaces import ICaptchaManager except: return captchas return sorted(getUtility(ICaptchaManager).getAvailCaptchas().keys()) def getTitle(self, value): return value class ISIRPUtils(Interface): """A collection of methods which are subject to customization. """ def storage(): """Return the initial storage path of the data center. """ def sendContactForm( from_name,from_addr,rcpt_name,rcpt_addr, from_username,usertype,portal,body,subject): """Send an email with data provided by forms. """ def fullname(firstname,lastname,middlename): """Full name constructor. """ def sendCredentials(user, password, login_url, msg): """Send credentials as email. Input is the applicant for which credentials are sent and the password. Returns True or False to indicate successful operation. """ def genPassword(length, chars): """Generate a random password. """ def getVerdictsDict(): """Provide a dict of verdicts. """ class ISIRPObject(Interface): """A SIRP object. This is merely a marker interface. """ class IUniversity(ISIRPObject): """Representation of a university. """ class ISIRPContainer(ISIRPObject): """A container for SIRP objects. """ class ISIRPContained(ISIRPObject): """An item contained in an ISIRPContainer. """ class ICSVExporter(Interface): """A CSV file exporter for objects. """ fields = Attribute("""List of fieldnames in resulting CSV""") def mangle_value(value, name, obj): """Mangle `value` extracted from `obj` or suobjects thereof. This is called by export before actually writing to the result file. """ def export(context, filepath=None): """Export context as CSV file. If `filepath` is not given, a string with the data should be returned. """ def export_all(site, filapath=None): """Export all items in `site` as CSV file. if `filepath` is not given, a string with the data should be returned. """ class ISIRPExporter(Interface): """An exporter for objects. """ def export(obj, filepath=None): """Export by pickling. Returns a file-like object containing a representation of `obj`. This is done using `pickle`. If `filepath` is ``None``, a `cStringIO` object is returned, that contains the saved data. """ class ISIRPXMLExporter(Interface): """An XML exporter for objects. """ def export(obj, filepath=None): """Export as XML. Returns an XML representation of `obj`. If `filepath` is ``None``, a StringIO` object is returned, that contains the transformed data. """ class ISIRPXMLImporter(Interface): """An XML import for objects. """ def doImport(filepath): """Create Python object from XML. Returns a Python object. """ class IBatchProcessor(Interface): """A batch processor that handles mass-operations. """ name = schema.TextLine( title = u'Importer name' ) mode = schema.Choice( title = u'Import mode', values = ['create', 'update', 'remove'] ) def doImport(path, headerfields, mode='create', user='Unknown', logger=None): """Read data from ``path`` and update connected object. `headerfields` is a list of headerfields as read from the file to import. `mode` gives the import mode to use (``'create'``, ``'update'``, or ``'remove'``. `user` is a string describing the user performing the import. Normally fetched from current principal. `logger` is the logger to use during import. """ class IContactForm(ISIRPObject): """A contact form. """ email_from = schema.ASCIILine( title = u'Email Address:', default = None, required = True, constraint=validate_email, ) email_to = schema.ASCIILine( title = u'Email to:', default = None, required = True, constraint=validate_email, ) subject = schema.TextLine( title = u'Subject:', required = True,) fullname = schema.TextLine( title = u'Full Name:', required = True,) body = schema.Text( title = u'Text:', required = True,) class ISIRPPrincipalInfo(IPrincipalInfo): """Infos about principals that are users of SIRP SIRP. """ email = Attribute("The email address of a user") phone = Attribute("The phone number of a user") class ISIRPPrincipal(IPrincipal): """A principle for SIRP SIRP. This interface extends zope.security.interfaces.IPrincipal and requires also an `id` and other attributes defined there. """ email = schema.TextLine( title = u'Email', description = u'', required=False,) phone = schema.TextLine( title = u'Phone', description = u'', required=False,) class IUserAccount(ISIRPObject): """A user account. """ name = schema.TextLine( title = u'User ID', description = u'Login name of user', required = True,) title = schema.TextLine( title = u'Full Name', required = False,) description = schema.Text( title = u'Description/Notice', required = False,) email = schema.ASCIILine( title = u'Email', default = None, required = True, constraint=validate_email, ) phone = schema.TextLine( title = u'Phone', default = None, required = True, ) roles = schema.List( title = u'Portal roles', value_type = schema.Choice(source=RoleSource())) class IPasswordValidator(Interface): """A password validator utility. """ def validate_password(password, password_repeat): """Validates a password by comparing it with control password and checking some other requirements. """ class IUsersContainer(ISIRPObject): """A container for users (principals). These users are used for authentication purposes. """ def addUser(name, password, title=None, description=None): """Add a user. """ def delUser(name): """Delete a user if it exists. """ class ILocalRolesAssignable(Interface): """The local roles assignable to an object. """ def __call__(): """Returns a list of dicts. Each dict contains a ``name`` referring to the role assignable for the specified object and a `title` to describe the range of users to which this role can be assigned. """ class IConfigurationContainer(ISIRPObject): """A container for session configuration objects. """ name = schema.TextLine( title = u'Name of University', default = u'Sample University', required = True, ) acronym = schema.TextLine( title = u'Abbreviated Title of University', default = u'WAeUP.SIRP', required = True, ) skin = schema.Choice( title = u'Skin', default = u'gray waeup theme', vocabulary = 'waeup.sirp.browser.theming.ThemesVocabulary', required = True, ) frontpage = schema.Text( title = u'Content in reST format', required = False, default = default_frontpage, ) frontpage_dict = schema.Dict( title = u'Content as language dictionary with values in html format', required = False, default = {}, ) accommodation_session = schema.Choice( title = u'Accommodation Booking Session', source = academic_sessions_vocab, default = datetime.now().year, required = False, readonly = False, ) accommodation_states = schema.List( title = u'Allowed States for Accommodation Booking', value_type = schema.Choice( vocabulary = registration_states_vocab, ), default = [], ) name_admin = schema.TextLine( title = u'Name of Administrator', default = u'Administrator', required = False, ) email_admin = schema.ASCIILine( title = u'Email Address of Administrator', default = 'contact@waeup.org', required = False, constraint=validate_email, ) email_subject = schema.TextLine( title = u'Subject of Email to Administrator', default = u'SIRP Contact', required = False, ) smtp_mailer = schema.Choice( title = u'SMTP mailer to use when sending mail', vocabulary = 'Mail Delivery Names', default = 'No email service', required = True, ) captcha = schema.Choice( title = u'Captcha used for public registration pages', source = CaptchaSource(), default = u'No captcha', required = True, ) carry_over = schema.Bool( title = u'Carry-over Course Registration', default = False, ) class ISessionConfiguration(ISIRPObject): """A session configuration object. """ academic_session = schema.Choice( title = u'Academic Session', source = academic_sessions_vocab, default = None, required = True, readonly = True, ) school_fee_base = schema.Int( title = u'School Fee', default = 0, ) surcharge_1 = schema.Int( title = u'Surcharge 1', default = 0, ) surcharge_2 = schema.Int( title = u'Surcharge 2', default = 0, ) surcharge_3 = schema.Int( title = u'Surcharge 3', default = 0, ) clearance_fee = schema.Int( title = u'Clearance Fee', default = 0, ) booking_fee = schema.Int( title = u'Booking Fee', default = 0, ) acceptance_fee = schema.Int( title = u'Acceptance Fee', default = 0, ) def getSessionString(): """Returns the session string from the vocabulary. """ class ISessionConfigurationAdd(ISessionConfiguration): """A session configuration object in add mode. """ academic_session = schema.Choice( title = u'Academic Session', source = academic_sessions_vocab, default = None, required = True, readonly = False, ) ISessionConfigurationAdd['academic_session'].order = ISessionConfiguration[ 'academic_session'].order class IDataCenter(ISIRPObject): """A data center. TODO : declare methods, at least those needed by pages. """ pass class IDataCenterFile(Interface): """A data center file. """ name = schema.TextLine( title = u'Filename') size = schema.TextLine( title = u'Human readable file size') uploaddate = schema.TextLine( title = u'Human readable upload datetime') lines = schema.Int( title = u'Number of lines in file') def getDate(): """Get creation timestamp from file in human readable form. """ def getSize(): """Get human readable size of file. """ def getLinesNumber(): """Get number of lines of file. """ class IDataCenterStorageMovedEvent(IObjectEvent): """Emitted, when the storage of a datacenter changes. """ class IObjectUpgradeEvent(IObjectEvent): """Can be fired, when an object shall be upgraded. """ class ILocalRoleSetEvent(IObjectEvent): """A local role was granted/revoked for a principal on an object. """ role_id = Attribute( "The role id that was set.") principal_id = Attribute( "The principal id for which the role was granted/revoked.") granted = Attribute( "Boolean. If false, then the role was revoked.") class IQueryResultItem(Interface): """An item in a search result. """ url = schema.TextLine( title = u'URL that links to the found item') title = schema.TextLine( title = u'Title displayed in search results.') description = schema.Text( title = u'Longer description of the item found.') class ISIRPPluggable(Interface): """A component that might be plugged into a SIRP SIRP app. Components implementing this interface are referred to as 'plugins'. They are normally called when a new :class:`waeup.sirp.app.University` instance is created. Plugins can setup and update parts of the central site without the site object (normally a :class:`waeup.sirp.app.University` object) needing to know about that parts. The site simply collects all available plugins, calls them and the plugins care for their respective subarea like the applicants area or the datacenter area. Currently we have no mechanism to define an order of plugins. A plugin should therefore make no assumptions about the state of the site or other plugins being run before and instead do appropriate checks if necessary. Updates can be triggered for instance by the respective form in the site configuration. You normally do updates when the underlying software changed. """ def setup(site, name, logger): """Create an instance of the plugin. The method is meant to be called by the central app (site) when it is created. `site`: The site that requests a setup. `name`: The name under which the plugin was registered (utility name). `logger`: A standard Python logger for the plugins use. """ def update(site, name, logger): """Method to update an already existing plugin. This might be called by a site when something serious changes. It is a poor-man replacement for Zope generations (but probably more comprehensive and better understandable). `site`: The site that requests an update. `name`: The name under which the plugin was registered (utility name). `logger`: A standard Python logger for the plugins use. """ class IAuthPluginUtility(Interface): """A component that cares for authentication setup at site creation. Utilities providing this interface are looked up when a Pluggable Authentication Utility (PAU) for any :class:`waeup.sirp.app.University` instance is created and put into ZODB. The setup-code then calls the `register` method of the utility and expects a modified (or unmodified) version of the PAU back. This allows to define any authentication setup modifications by submodules or third-party modules/packages. """ def register(pau): """Register any plugins wanted to be in the PAU. """ def unregister(pau): """Unregister any plugins not wanted to be in the PAU. """ class IObjectConverter(Interface): """Object converters are available as simple adapters, adapting interfaces (not regular instances). """ def fromStringDict(self, data_dict, context, form_fields=None): """Convert values in `data_dict`. Converts data in `data_dict` into real values based on `context` and `form_fields`. `data_dict` is a mapping (dict) from field names to values represented as strings. The fields (keys) to convert can be given in optional `form_fields`. If given, form_fields should be an instance of :class:`zope.formlib.form.Fields`. Suitable instances are for example created by :class:`grok.AutoFields`. If no `form_fields` are given, a default is computed from the associated interface. The `context` can be an existing object (implementing the associated interface) or a factory name. If it is a string, we try to create an object using :func:`zope.component.createObject`. Returns a tuple ``(, , )`` where ```` is a list of tuples ``(, )`` for each error that happened when validating the input data in `data_dict` ```` is a list of invariant errors concerning several fields ```` is a dict with the values from input dict converted. If errors happen, i.e. the error lists are not empty, always an empty ```` is returned. If ``` is non-empty, there were no errors. """ class IObjectHistory(Interface): messages = schema.List( title = u'List of messages stored', required = True, ) def addMessage(message): """Add a message. """ class ISIRPWorkflowInfo(IWorkflowInfo): """A :class:`hurry.workflow.workflow.WorkflowInfo` with additional methods for convenience. """ def getManualTransitions(): """Get allowed manual transitions. Get a sorted list of tuples containing the `transition_id` and `title` of each allowed transition. """ class ISiteLoggers(Interface): loggers = Attribute("A list or generator of registered SIRPLoggers") def register(name, filename=None, site=None, **options): """Register a logger `name` which logs to `filename`. If `filename` is not given, logfile will be `name` with ``.log`` as filename extension. """ def unregister(name): """Unregister a once registered logger. """ class ILogger(Interface): """A logger cares for setup, update and restarting of a Python logger. """ logger = Attribute("""A :class:`logging.Logger` instance""") def __init__(name, filename=None, site=None, **options): """Create a SIRP logger instance. """ def setup(): """Create a Python :class:`logging.Logger` instance. The created logger is based on the params given by constructor. """ def update(**options): """Update the logger. Updates the logger respecting modified `options` and changed paths. """ class ILoggerCollector(Interface): def getLoggers(site): """Return all loggers registered for `site`. """ def registerLogger(site, logging_component): """Register a logging component residing in `site`. """ def unregisterLogger(site, logging_component): """Unregister a logger. """ # # External File Storage and relatives # class IFileStoreNameChooser(INameChooser): """See zope.container.interfaces.INameChooser for base methods. """ def checkName(name, attr=None): """Check whether an object name is valid. Raises a user error if the name is not valid. """ def chooseName(name, attr=None): """Choose a unique valid file id for the object. The given name may be taken into account when choosing the name (file id). chooseName is expected to always choose a valid file id (that would pass the checkName test) and never raise an error. If `attr` is not ``None`` it might been taken into account as well when generating the file id. Usual behaviour is to interpret `attr` as a hint for what type of file for a given context should be stored if there are several types possible. For instance for a certain student some file could be the connected passport photograph or some certificate scan or whatever. Each of them has to be stored in a different location so setting `attr` to a sensible value should give different file ids returned. """ class IExtFileStore(IFileRetrieval): """A file storage that stores files in filesystem (not as blobs). """ root = schema.TextLine( title = u'Root path of file store.', ) def getFile(file_id): """Get raw file data stored under file with `file_id`. Returns a file descriptor open for reading or ``None`` if the file cannot be found. """ def getFileByContext(context, attr=None): """Get raw file data stored for the given context. Returns a file descriptor open for reading or ``None`` if no such file can be found. Both, `context` and `attr` might be used to find (`context`) and feed (`attr`) an appropriate file name chooser. This is a convenience method. """ def deleteFile(file_id): """Delete file stored under `file_id`. Remove file from filestore so, that it is not available anymore on next call to getFile for the same file_id. Should not complain if no such file exists. """ def deleteFileByContext(context, attr=None): """Delete file for given `context` and `attr`. Both, `context` and `attr` might be used to find (`context`) and feed (`attr`) an appropriate file name chooser. This is a convenience method. """ def createFile(filename, f): """Create file given by f with filename `filename` Returns a hurry.file.File-based object. """ class IFileStoreHandler(Interface): """Filestore handlers handle specific files for file stores. If a file to store/get provides a specific filename, a file store looks up special handlers for that type of file. """ def pathFromFileID(store, root, filename): """Turn file id into path to store. Returned path should be absolute. """ def createFile(store, root, filename, file_id, file): """Return some hurry.file based on `store` and `file_id`. Some kind of callback method called by file stores to create file objects from file_id. Returns a tuple ``(raw_file, path, file_like_obj)`` where the ``file_like_obj`` should be a HurryFile, a SIRPImageFile or similar. ``raw_file`` is the (maybe changed) input file and ``path`` the relative internal path to store the file at. Please make sure the ``raw_file`` is opened for reading and the file descriptor set at position 0 when returned. This method also gets the raw input file object that is about to be stored and is expected to raise any exceptions if some kind of validation or similar fails. """ class IPDF(Interface): """A PDF representation of some context. """ def __call__(view=None): """Create a bytestream representing a PDF from context. If `view` is passed in additional infos might be rendered into the document. """ class IMailService(Interface): """A mail service. """ def __call__(): """Get the default mail delivery. """ from zope.configuration.fields import Path class IDataCenterConfig(Interface): path = Path( title = u'Path', description = u"Directory where the datacenter should store" u"files by default (adjustable in web UI).", required = True, )