source: main/waeup.kofa/trunk/src/waeup/kofa/interfaces.py @ 8755

Last change on this file since 8755 was 8685, checked in by Henrik Bettermann, 13 years ago

Add hostel allocation start end end date attributes to hostels.

Move hostel allocation parameters from configuration to hostels. AccommodationOfficer? must be able to edit these parameters.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 32.7 KB
RevLine 
[7193]1## $Id: interfaces.py 8685 2012-06-12 07:17:01Z henrik $
[3521]2##
[7193]3## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
4## This program is free software; you can redistribute it and/or modify
5## it under the terms of the GNU General Public License as published by
6## the Free Software Foundation; either version 2 of the License, or
7## (at your option) any later version.
8##
9## This program is distributed in the hope that it will be useful,
10## but WITHOUT ANY WARRANTY; without even the implied warranty of
11## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12## GNU General Public License for more details.
13##
14## You should have received a copy of the GNU General Public License
15## along with this program; if not, write to the Free Software
16## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17##
[6361]18import os
[7221]19import re
[7702]20import codecs
[7670]21import zope.i18nmessageid
[6915]22from datetime import datetime
[7063]23from hurry.file.interfaces import IFileRetrieval
[8394]24from hurry.workflow.interfaces import IWorkflowInfo
[4789]25from zc.sourcefactory.basic import BasicSourceFactory
[6147]26from zope import schema
[7233]27from zope.pluggableauth.interfaces import IPrincipalInfo
28from zope.security.interfaces import IGroupClosureAwarePrincipal as IPrincipal
[4789]29from zope.component import getUtility
[4882]30from zope.component.interfaces import IObjectEvent
[7063]31from zope.container.interfaces import INameChooser
[8394]32from zope.interface import Interface, Attribute
[7795]33from zope.schema.interfaces import IObject
[4789]34from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
[8176]35from waeup.kofa.schema import PhoneNumber
[3521]36
[7811]37_ = MessageFactory = zope.i18nmessageid.MessageFactory('waeup.kofa')
[6990]38
[8214]39DELETION_MARKER = 'XXX'
40IGNORE_MARKER = '<IGNORE>'
[8202]41
[7673]42CREATED = 'created'
43ADMITTED = 'admitted'
44CLEARANCE = 'clearance started'
45REQUESTED = 'clearance requested'
46CLEARED = 'cleared'
47PAID = 'school fee paid'
48RETURNING = 'returning'
49REGISTERED = 'courses registered'
50VALIDATED = 'courses validated'
[7670]51
[8361]52#default_rest_frontpage = u'' + codecs.open(os.path.join(
53#        os.path.dirname(__file__), 'frontpage.rst'),
54#        encoding='utf-8', mode='rb').read()
55
56default_html_frontpage = u'' + codecs.open(os.path.join(
57        os.path.dirname(__file__), 'frontpage.html'),
[7702]58        encoding='utf-8', mode='rb').read()
[6361]59
[7819]60def SimpleKofaVocabulary(*terms):
[6915]61    """A well-buildt vocabulary provides terms with a value, token and
62       title for each term
63    """
64    return SimpleVocabulary([
65            SimpleTerm(value, value, title) for title, value in terms])
66
67def year_range():
68    curr_year = datetime.now().year
[7459]69    return range(curr_year - 4, curr_year + 5)
[6915]70
71def academic_sessions():
72    curr_year = datetime.now().year
73    year_range = range(curr_year - 10, curr_year + 2)
74    return [('%s/%s' % (year,year+1), year) for year in year_range]
75
[7819]76academic_sessions_vocab = SimpleKofaVocabulary(*academic_sessions())
[6915]77
[7819]78registration_states_vocab = SimpleKofaVocabulary(
[7677]79    (_('created'), CREATED),
80    (_('admitted'), ADMITTED),
81    (_('clearance started'), CLEARANCE),
82    (_('clearance requested'), REQUESTED),
83    (_('cleared'), CLEARED),
84    (_('school fee paid'), PAID),
85    (_('returning'), RETURNING),
86    (_('courses registered'), REGISTERED),
87    (_('courses validated'), VALIDATED),
[6990]88    )
89
[7795]90class SubjectSource(BasicSourceFactory):
[7918]91    """A source for school subjects used in exam documentation.
92    """
[7795]93    def getValues(self):
[7841]94        subjects_dict = getUtility(IKofaUtils).EXAM_SUBJECTS_DICT
[7837]95        return sorted(subjects_dict.keys())
96
[7795]97    def getTitle(self, value):
[7841]98        subjects_dict = getUtility(IKofaUtils).EXAM_SUBJECTS_DICT
[7837]99        return "%s:" % subjects_dict[value]
[7795]100
101class GradeSource(BasicSourceFactory):
[7918]102    """A source for exam grades.
103    """
[7795]104    def getValues(self):
[7918]105        for entry in getUtility(IKofaUtils).EXAM_GRADES:
106            yield entry[0]
[7837]107
[7795]108    def getTitle(self, value):
[7918]109        return dict(getUtility(IKofaUtils).EXAM_GRADES)[value]
[7795]110
[7850]111# Define a validation method for email addresses
[7221]112class NotAnEmailAddress(schema.ValidationError):
113    __doc__ = u"Invalid email address"
114
[8638]115#: Regular expression to check email-address formats. As these can
116#: become rather complex (nearly everything is allowed by RFCs), we only
117#: forbid whitespaces, commas and dots following onto each other.
[7221]118check_email = re.compile(
[8638]119    r"^[^@\s,]+@[^@\.\s,]+(\.[^@\.\s,]+)*$").match
[7221]120
121def validate_email(value):
122    if not check_email(value):
123        raise NotAnEmailAddress(value)
124    return True
125
[7850]126# Define a validation method for international phone numbers
127class InvalidPhoneNumber(schema.ValidationError):
128    __doc__ = u"Invalid phone number"
129
130# represent format +NNN-NNNN-NNNN
131RE_INT_PHONE = re.compile(r"^\+?\d+\-\d+\-[\d\-]+$")
132
133def validate_phone(value):
[7851]134    if not RE_INT_PHONE.match(value):
[7850]135        raise InvalidPhoneNumber(value)
136    return True
137
[4858]138class FatalCSVError(Exception):
139    """Some row could not be processed.
140    """
141    pass
142
[6226]143class DuplicationError(Exception):
144    """An exception that can be raised when duplicates are found.
145
146    When raising :exc:`DuplicationError` you can, beside the usual
147    message, specify a list of objects which are duplicates. These
148    values can be used by catching code to print something helpful or
149    similar.
150    """
151    def __init__(self, msg, entries=[]):
152        self.msg = msg
153        self.entries = entries
154
155    def __str__(self):
156        return '%r' % self.msg
157
[6143]158class RoleSource(BasicSourceFactory):
[7178]159    """A source for site roles.
[6508]160    """
[6143]161    def getValues(self):
[6157]162        # late import: in interfaces we should not import local modules
[7811]163        from waeup.kofa.permissions import get_waeup_role_names
[7186]164        return get_waeup_role_names()
[6157]165
166    def getTitle(self, value):
167        # late import: in interfaces we should not import local modules
[7811]168        from waeup.kofa.permissions import get_all_roles
[7186]169        roles = dict(get_all_roles())
[6157]170        if value in roles.keys():
171            title = roles[value].title
[6569]172            if '.' in title:
173                title = title.split('.', 2)[1]
[6157]174        return title
[6143]175
[7313]176class CaptchaSource(BasicSourceFactory):
177    """A source for captchas.
178    """
179    def getValues(self):
[7323]180        captchas = ['No captcha', 'Testing captcha', 'ReCaptcha']
[7313]181        try:
182            # we have to 'try' because IConfiguration can only handle
[7817]183            # interfaces from w.k.interface.
[7811]184            from waeup.kofa.browser.interfaces import ICaptchaManager
[7313]185        except:
186            return captchas
187        return sorted(getUtility(ICaptchaManager).getAvailCaptchas().keys())
188
189    def getTitle(self, value):
190        return value
191
[7795]192class IResultEntry(Interface):
193    """A school grade entry.
194    """
195    subject = schema.Choice(
196        title = _(u'Subject'),
197        source = SubjectSource(),
198        )
199    grade = schema.Choice(
200        title = _(u'Grade'),
201        source = GradeSource(),
202        )
203
204class IResultEntryField(IObject):
205    """A zope.schema-like field for usage in interfaces.
206
207    Marker interface to distuingish result entries from ordinary
208    object fields. Needed for registration of widgets.
209    """
210
[7819]211class IKofaUtils(Interface):
[7358]212    """A collection of methods which are subject to customization.
213    """
[7568]214
[7841]215    PORTAL_LANGUAGE = Attribute("Dict of global language setting")
216    PREFERRED_LANGUAGES_DICT = Attribute("Dict of preferred languages")
217    EXAM_SUBJECTS_DICT = Attribute("Dict of examination subjects")
218    EXAM_GRADES_DICT = Attribute("Dict of examination grades")
219    INST_TYPES_DICT = Attribute("Dict if institution types")
220    STUDY_MODES_DICT = Attribute("Dict of study modes")
221    APP_CATS_DICT = Attribute("Dict of application categories")
222    SEMESTER_DICT = Attribute("Dict of semesters or trimesters")
[8394]223    INT_PHONE_PREFIXES = Attribute(
224        "Dict of international phone number prefixes")
[7568]225
[7404]226    def sendContactForm(
227          from_name,from_addr,rcpt_name,rcpt_addr,
228          from_username,usertype,portal,body,subject):
[7358]229        """Send an email with data provided by forms.
230        """
231
[7475]232    def fullname(firstname,lastname,middlename):
233        """Full name constructor.
234        """
235
236    def sendCredentials(user, password, login_url, msg):
237        """Send credentials as email.
238
239        Input is the applicant for which credentials are sent and the
240        password.
241
242        Returns True or False to indicate successful operation.
243        """
244
245    def genPassword(length, chars):
246        """Generate a random password.
247        """
248
[7819]249class IKofaObject(Interface):
250    """A Kofa object.
[5663]251
252    This is merely a marker interface.
[4789]253    """
254
[7819]255class IUniversity(IKofaObject):
[3521]256    """Representation of a university.
257    """
[5955]258
[6065]259
[7819]260class IKofaContainer(IKofaObject):
261    """A container for Kofa objects.
[4789]262    """
263
[7819]264class IKofaContained(IKofaObject):
265    """An item contained in an IKofaContainer.
[4789]266    """
[6136]267
[7726]268class ICSVExporter(Interface):
269    """A CSV file exporter for objects.
270    """
271    fields = Attribute("""List of fieldnames in resulting CSV""")
[7907]272
273    title = schema.TextLine(
274        title = u'Title',
275        description = u'Description to be displayed in selections.',
276        )
[7726]277    def mangle_value(value, name, obj):
278        """Mangle `value` extracted from `obj` or suobjects thereof.
279
[8394]280        This is called by export before actually writing to the result
281        file.
[7726]282        """
283
[7730]284    def export(iterable, filepath=None):
285        """Export iterables as rows in a CSV file.
[7726]286
[8394]287        If `filepath` is not given, a string with the data should be
288        returned.
[7730]289
290        What kind of iterables are acceptable depends on the specific
291        exporter implementation.
[7726]292        """
293
294    def export_all(site, filapath=None):
295        """Export all items in `site` as CSV file.
296
[8394]297        if `filepath` is not given, a string with the data should be
298        returned.
[7726]299        """
300
[7819]301class IKofaExporter(Interface):
[4789]302    """An exporter for objects.
303    """
304    def export(obj, filepath=None):
305        """Export by pickling.
306
307        Returns a file-like object containing a representation of `obj`.
308
309        This is done using `pickle`. If `filepath` is ``None``, a
310        `cStringIO` object is returned, that contains the saved data.
311        """
312
[7819]313class IKofaXMLExporter(Interface):
[4789]314    """An XML exporter for objects.
315    """
316    def export(obj, filepath=None):
317        """Export as XML.
318
319        Returns an XML representation of `obj`.
320
321        If `filepath` is ``None``, a StringIO` object is returned,
322        that contains the transformed data.
323        """
324
[7819]325class IKofaXMLImporter(Interface):
[4789]326    """An XML import for objects.
327    """
328    def doImport(filepath):
329        """Create Python object from XML.
330
331        Returns a Python object.
332        """
333
[4858]334class IBatchProcessor(Interface):
335    """A batch processor that handles mass-operations.
336    """
337    name = schema.TextLine(
[7933]338        title = _(u'Processor name')
[4858]339        )
340
[5476]341    def doImport(path, headerfields, mode='create', user='Unknown',
[8218]342                 logger=None, ignore_empty=True):
[4858]343        """Read data from ``path`` and update connected object.
[5476]344
345        `headerfields` is a list of headerfields as read from the file
346        to import.
347
348        `mode` gives the import mode to use (``'create'``,
349        ``'update'``, or ``'remove'``.
350
351        `user` is a string describing the user performing the
352        import. Normally fetched from current principal.
353
354        `logger` is the logger to use during import.
[8218]355
356        `ignore_emtpy` in update mode ignores empty fields if true.
[4858]357        """
358
[7819]359class IContactForm(IKofaObject):
[7225]360    """A contact form.
361    """
362
363    email_from = schema.ASCIILine(
[7828]364        title = _(u'Email Address:'),
[7225]365        default = None,
366        required = True,
367        constraint=validate_email,
368        )
369
370    email_to = schema.ASCIILine(
[7828]371        title = _(u'Email to:'),
[7225]372        default = None,
373        required = True,
374        constraint=validate_email,
375        )
376
377    subject = schema.TextLine(
[7828]378        title = _(u'Subject:'),
[7225]379        required = True,)
380
381    fullname = schema.TextLine(
[7828]382        title = _(u'Full Name:'),
[7225]383        required = True,)
384
385    body = schema.Text(
[7828]386        title = _(u'Text:'),
[7225]387        required = True,)
388
[7819]389class IKofaPrincipalInfo(IPrincipalInfo):
390    """Infos about principals that are users of Kofa Kofa.
[7233]391    """
392    email = Attribute("The email address of a user")
393    phone = Attribute("The phone number of a user")
[7225]394
[7233]395
[7819]396class IKofaPrincipal(IPrincipal):
397    """A principle for Kofa Kofa.
[7233]398
399    This interface extends zope.security.interfaces.IPrincipal and
400    requires also an `id` and other attributes defined there.
401    """
402
403    email = schema.TextLine(
[7828]404        title = _(u'Email Address'),
[7233]405        description = u'',
406        required=False,)
407
[8176]408    phone = PhoneNumber(
[7828]409        title = _(u'Phone'),
[7233]410        description = u'',
411        required=False,)
412
[7819]413class IUserAccount(IKofaObject):
[4789]414    """A user account.
415    """
416    name = schema.TextLine(
[7828]417        title = _(u'User Id'),
[6512]418        description = u'Login name of user',
[4789]419        required = True,)
[7221]420
[4789]421    title = schema.TextLine(
[7828]422        title = _(u'Full Name'),
[4789]423        required = False,)
[7221]424
[7197]425    description = schema.Text(
[7828]426        title = _(u'Description/Notice'),
[4789]427        required = False,)
[7221]428
429    email = schema.ASCIILine(
[7828]430        title = _(u'Email Address'),
[7221]431        default = None,
[7222]432        required = True,
[7221]433        constraint=validate_email,
434        )
435
[8176]436    phone = PhoneNumber(
[7828]437        title = _(u'Phone'),
[7233]438        default = None,
[8062]439        required = False,
[7233]440        )
441
[4789]442    roles = schema.List(
[8486]443        title = _(u'Portal Roles'),
[8079]444        value_type = schema.Choice(source=RoleSource()),
445        required = False,
446        )
[6136]447
[7147]448class IPasswordValidator(Interface):
449    """A password validator utility.
450    """
[6136]451
[7147]452    def validate_password(password, password_repeat):
453        """Validates a password by comparing it with
454        control password and checking some other requirements.
455        """
456
457
[7819]458class IUsersContainer(IKofaObject):
[4789]459    """A container for users (principals).
460
461    These users are used for authentication purposes.
462    """
463
464    def addUser(name, password, title=None, description=None):
465        """Add a user.
466        """
467
468    def delUser(name):
469        """Delete a user if it exists.
470        """
471
[6141]472class ILocalRolesAssignable(Interface):
473    """The local roles assignable to an object.
474    """
475    def __call__():
476        """Returns a list of dicts.
477
478        Each dict contains a ``name`` referring to the role assignable
479        for the specified object and a `title` to describe the range
480        of users to which this role can be assigned.
481        """
482
[7819]483class IConfigurationContainer(IKofaObject):
[6907]484    """A container for session configuration objects.
485    """
486
487    name = schema.TextLine(
[7828]488        title = _(u'Name of University'),
489        default = _(u'Sample University'),
[6907]490        required = True,
491        )
492
[7459]493    acronym = schema.TextLine(
[7828]494        title = _(u'Abbreviated Title of University'),
[7819]495        default = u'WAeUP.Kofa',
[7459]496        required = True,
497        )
498
[6907]499    skin = schema.Choice(
[7828]500        title = _(u'Skin'),
[6907]501        default = u'gray waeup theme',
[7811]502        vocabulary = 'waeup.kofa.browser.theming.ThemesVocabulary',
[6907]503        required = True,
504        )
505
506    frontpage = schema.Text(
[8361]507        title = _(u'Content in HTML format'),
[6907]508        required = False,
[8361]509        default = default_html_frontpage,
[6907]510        )
511
[7702]512    frontpage_dict = schema.Dict(
513        title = u'Content as language dictionary with values in html format',
[7485]514        required = False,
[7702]515        default = {},
[7485]516        )
517
[7223]518    name_admin = schema.TextLine(
[7828]519        title = _(u'Name of Administrator'),
[7223]520        default = u'Administrator',
[8230]521        required = True,
[7223]522        )
523
[7221]524    email_admin = schema.ASCIILine(
[7828]525        title = _(u'Email Address of Administrator'),
[7221]526        default = 'contact@waeup.org',
[8230]527        required = True,
[7221]528        constraint=validate_email,
529        )
530
531    email_subject = schema.TextLine(
[7828]532        title = _(u'Subject of Email to Administrator'),
533        default = _(u'Kofa Contact'),
[8230]534        required = True,
[7221]535        )
536
[7470]537    smtp_mailer = schema.Choice(
[7828]538        title = _(u'SMTP mailer to use when sending mail'),
[7470]539        vocabulary = 'Mail Delivery Names',
540        default = 'No email service',
541        required = True,
542        )
543
[7313]544    captcha = schema.Choice(
[7828]545        title = _(u'Captcha used for public registration pages'),
[7313]546        source = CaptchaSource(),
547        default = u'No captcha',
548        required = True,
549        )
[7221]550
[7664]551    carry_over = schema.Bool(
[7828]552        title = _(u'Carry-over Course Registration'),
[7664]553        default = False,
554        )
555
[7819]556class ISessionConfiguration(IKofaObject):
[6915]557    """A session configuration object.
[6907]558    """
559
[6915]560    academic_session = schema.Choice(
[7828]561        title = _(u'Academic Session'),
[6915]562        source = academic_sessions_vocab,
563        default = None,
564        required = True,
565        readonly = True,
566        )
567
[8260]568    application_fee = schema.Float(
569        title = _(u'Application Fee'),
[7927]570        default = 0.0,
[7881]571        required = False,
[6916]572        )
573
[8260]574    clearance_fee = schema.Float(
575        title = _(u'Clearance Fee'),
[7927]576        default = 0.0,
[7881]577        required = False,
[6993]578        )
579
[8260]580    booking_fee = schema.Float(
581        title = _(u'Bed Booking Fee'),
[7927]582        default = 0.0,
[7881]583        required = False,
[7250]584        )
585
[6918]586    def getSessionString():
587        """Returns the session string from the vocabulary.
588        """
589
590
[6916]591class ISessionConfigurationAdd(ISessionConfiguration):
592    """A session configuration object in add mode.
593    """
594
595    academic_session = schema.Choice(
[7828]596        title = _(u'Academic Session'),
[6916]597        source = academic_sessions_vocab,
598        default = None,
599        required = True,
600        readonly = False,
601        )
602
603ISessionConfigurationAdd['academic_session'].order =  ISessionConfiguration[
604    'academic_session'].order
605
[7819]606class IDataCenter(IKofaObject):
[4789]607    """A data center.
608
[8394]609    A data center manages files (uploads, downloads, etc.).
610
611    Beside providing the bare paths needed to keep files, it also
612    provides some helpers to put results of batch processing into
613    well-defined final locations (with well-defined filenames).
614
615    The main use-case is managing of site-related files, i.e. files
616    for import, export etc.
617
618    DataCenters are _not_ meant as storages for object-specific files
619    like passport photographs and similar.
620
621    It is up to the datacenter implementation how to organize data
622    (paths) inside its storage path.
[4789]623    """
[8394]624    storage = schema.Bytes(
625        title = u'Path to directory where everything is kept.'
626        )
[4789]627
[8394]628    deleted_path = schema.Bytes(
629        title = u'Path were data about deleted objects should be stored.'
630        )
631
632    def getFiles(sort='name'):
633        """Get a list of files stored in `storage` sorted by basename.
634        """
635    def setStoragePath(path, move=False, overwrite=False):
636        """Set the path where to store files.
637
638        If `move` is True, move over files from the current location
639        to the new one.
640
641        If `overwrite` is also True, overwrite any already existing
642        files of same name in target location.
643
644        Triggers a DataCenterStorageMovedEvent.
645        """
646
647    def distProcessedFiles(successful, source_path, finished_file,
648                           pending_file, mode='create', move_orig=True):
649        """Distribute processed files over final locations.
650        """
651
652
[4789]653class IDataCenterFile(Interface):
654    """A data center file.
655    """
[4858]656
657    name = schema.TextLine(
658        title = u'Filename')
659
660    size = schema.TextLine(
661        title = u'Human readable file size')
662
663    uploaddate = schema.TextLine(
664        title = u'Human readable upload datetime')
665
666    lines = schema.Int(
667        title = u'Number of lines in file')
[6136]668
[4789]669    def getDate():
670        """Get creation timestamp from file in human readable form.
671        """
672
673    def getSize():
674        """Get human readable size of file.
675        """
[4858]676
677    def getLinesNumber():
678        """Get number of lines of file.
679        """
[4882]680
681class IDataCenterStorageMovedEvent(IObjectEvent):
682    """Emitted, when the storage of a datacenter changes.
683    """
[5007]684
[6136]685class IObjectUpgradeEvent(IObjectEvent):
686    """Can be fired, when an object shall be upgraded.
687    """
688
[6180]689class ILocalRoleSetEvent(IObjectEvent):
690    """A local role was granted/revoked for a principal on an object.
691    """
692    role_id = Attribute(
693        "The role id that was set.")
694    principal_id = Attribute(
695        "The principal id for which the role was granted/revoked.")
696    granted = Attribute(
697        "Boolean. If false, then the role was revoked.")
698
[5007]699class IQueryResultItem(Interface):
700    """An item in a search result.
701    """
702    url = schema.TextLine(
703        title = u'URL that links to the found item')
704    title = schema.TextLine(
705        title = u'Title displayed in search results.')
706    description = schema.Text(
707        title = u'Longer description of the item found.')
[6136]708
[7819]709class IKofaPluggable(Interface):
710    """A component that might be plugged into a Kofa Kofa app.
[5658]711
712    Components implementing this interface are referred to as
713    'plugins'. They are normally called when a new
[7811]714    :class:`waeup.kofa.app.University` instance is created.
[5658]715
716    Plugins can setup and update parts of the central site without the
[7811]717    site object (normally a :class:`waeup.kofa.app.University` object)
[5658]718    needing to know about that parts. The site simply collects all
719    available plugins, calls them and the plugins care for their
[5676]720    respective subarea like the applicants area or the datacenter
[5658]721    area.
722
723    Currently we have no mechanism to define an order of plugins. A
724    plugin should therefore make no assumptions about the state of the
725    site or other plugins being run before and instead do appropriate
726    checks if necessary.
727
728    Updates can be triggered for instance by the respective form in
729    the site configuration. You normally do updates when the
730    underlying software changed.
[5013]731    """
[5069]732    def setup(site, name, logger):
733        """Create an instance of the plugin.
[5013]734
[5658]735        The method is meant to be called by the central app (site)
736        when it is created.
737
738        `site`:
739           The site that requests a setup.
740
741        `name`:
742           The name under which the plugin was registered (utility name).
743
744        `logger`:
745           A standard Python logger for the plugins use.
[5069]746        """
747
748    def update(site, name, logger):
749        """Method to update an already existing plugin.
750
751        This might be called by a site when something serious
[5658]752        changes. It is a poor-man replacement for Zope generations
753        (but probably more comprehensive and better understandable).
754
755        `site`:
756           The site that requests an update.
757
758        `name`:
759           The name under which the plugin was registered (utility name).
760
761        `logger`:
762           A standard Python logger for the plugins use.
[5069]763        """
[5898]764
[5899]765class IAuthPluginUtility(Interface):
[5898]766    """A component that cares for authentication setup at site creation.
767
768    Utilities providing this interface are looked up when a Pluggable
769    Authentication Utility (PAU) for any
[7811]770    :class:`waeup.kofa.app.University` instance is created and put
[5898]771    into ZODB.
772
773    The setup-code then calls the `register` method of the utility and
774    expects a modified (or unmodified) version of the PAU back.
775
776    This allows to define any authentication setup modifications by
777    submodules or third-party modules/packages.
778    """
779
780    def register(pau):
781        """Register any plugins wanted to be in the PAU.
782        """
783
784    def unregister(pau):
785        """Unregister any plugins not wanted to be in the PAU.
786        """
[6273]787
788class IObjectConverter(Interface):
789    """Object converters are available as simple adapters, adapting
790       interfaces (not regular instances).
791
792    """
793
[6277]794    def fromStringDict(self, data_dict, context, form_fields=None):
795        """Convert values in `data_dict`.
[6273]796
[6277]797        Converts data in `data_dict` into real values based on
798        `context` and `form_fields`.
[6273]799
[6277]800        `data_dict` is a mapping (dict) from field names to values
801        represented as strings.
[6273]802
[6277]803        The fields (keys) to convert can be given in optional
804        `form_fields`. If given, form_fields should be an instance of
805        :class:`zope.formlib.form.Fields`. Suitable instances are for
806        example created by :class:`grok.AutoFields`.
[6273]807
[6277]808        If no `form_fields` are given, a default is computed from the
809        associated interface.
[6273]810
[6277]811        The `context` can be an existing object (implementing the
812        associated interface) or a factory name. If it is a string, we
813        try to create an object using
814        :func:`zope.component.createObject`.
815
816        Returns a tuple ``(<FIELD_ERRORS>, <INVARIANT_ERRORS>,
817        <DATA_DICT>)`` where
818
819        ``<FIELD_ERRORS>``
820           is a list of tuples ``(<FIELD_NAME>, <ERROR>)`` for each
821           error that happened when validating the input data in
822           `data_dict`
823
824        ``<INVARIANT_ERRORS>``
825           is a list of invariant errors concerning several fields
826
827        ``<DATA_DICT>``
828           is a dict with the values from input dict converted.
829
830        If errors happen, i.e. the error lists are not empty, always
831        an empty ``<DATA_DICT>`` is returned.
832
833        If ``<DATA_DICT>` is non-empty, there were no errors.
[6273]834        """
[6293]835
[7932]836class IFieldConverter(Interface):
[8214]837    def request_data(name, value, schema_field, prefix='', mode='create'):
[7932]838        """Create a dict with key-value mapping as created by a request.
839
840        `name` and `value` are expected to be parsed from CSV or a
841        similar input and represent an attribute to be set to a
842        representation of value.
843
[8214]844        `mode` gives the mode of import.
845
[7932]846        :meth:`update_request_data` is then requested to turn this
847        name and value into vars as they would be sent by a regular
848        form submit. This means we do not create the real values to be
849        set but we only define the values that would be sent in a
850        browser request to request the creation of those values.
851
852        The returned dict should contain names and values of a faked
853        browser request for the given `schema_field`.
854
855        Field converters are normally registered as adapters to some
856        specific zope.schema field.
857        """
858
[6338]859class IObjectHistory(Interface):
860
861    messages = schema.List(
862        title = u'List of messages stored',
863        required = True,
864        )
865
866    def addMessage(message):
867        """Add a message.
868        """
[6353]869
[7819]870class IKofaWorkflowInfo(IWorkflowInfo):
[6353]871    """A :class:`hurry.workflow.workflow.WorkflowInfo` with additional
872       methods for convenience.
873    """
874    def getManualTransitions():
875        """Get allowed manual transitions.
876
877        Get a sorted list of tuples containing the `transition_id` and
878        `title` of each allowed transition.
879        """
[6481]880
881class ISiteLoggers(Interface):
882
[7819]883    loggers = Attribute("A list or generator of registered KofaLoggers")
[6481]884
885    def register(name, filename=None, site=None, **options):
886        """Register a logger `name` which logs to `filename`.
887
888        If `filename` is not given, logfile will be `name` with
889        ``.log`` as filename extension.
890        """
891
892    def unregister(name):
893        """Unregister a once registered logger.
894        """
895
896class ILogger(Interface):
897    """A logger cares for setup, update and restarting of a Python logger.
898    """
899
900    logger = Attribute("""A :class:`logging.Logger` instance""")
901
902
903    def __init__(name, filename=None, site=None, **options):
[7819]904        """Create a Kofa logger instance.
[6481]905        """
906
907    def setup():
908        """Create a Python :class:`logging.Logger` instance.
909
910        The created logger is based on the params given by constructor.
911        """
912
913    def update(**options):
914        """Update the logger.
915
916        Updates the logger respecting modified `options` and changed
917        paths.
918        """
[6754]919
920class ILoggerCollector(Interface):
921
922    def getLoggers(site):
923        """Return all loggers registered for `site`.
924        """
925
926    def registerLogger(site, logging_component):
927        """Register a logging component residing in `site`.
928        """
929
930    def unregisterLogger(site, logging_component):
931        """Unregister a logger.
932        """
[7063]933
934#
935# External File Storage and relatives
936#
937class IFileStoreNameChooser(INameChooser):
938    """See zope.container.interfaces.INameChooser for base methods.
939    """
[7066]940    def checkName(name, attr=None):
[7063]941        """Check whether an object name is valid.
942
943        Raises a user error if the name is not valid.
944        """
945
[7066]946    def chooseName(name, attr=None):
947        """Choose a unique valid file id for the object.
[7063]948
[7066]949        The given name may be taken into account when choosing the
950        name (file id).
[7063]951
[7066]952        chooseName is expected to always choose a valid file id (that
953        would pass the checkName test) and never raise an error.
954
955        If `attr` is not ``None`` it might been taken into account as
956        well when generating the file id. Usual behaviour is to
957        interpret `attr` as a hint for what type of file for a given
958        context should be stored if there are several types
959        possible. For instance for a certain student some file could
960        be the connected passport photograph or some certificate scan
961        or whatever. Each of them has to be stored in a different
962        location so setting `attr` to a sensible value should give
963        different file ids returned.
[7063]964        """
965
966class IExtFileStore(IFileRetrieval):
967    """A file storage that stores files in filesystem (not as blobs).
968    """
969    root = schema.TextLine(
970        title = u'Root path of file store.',
971        )
972
973    def getFile(file_id):
974        """Get raw file data stored under file with `file_id`.
975
976        Returns a file descriptor open for reading or ``None`` if the
977        file cannot be found.
978        """
979
[7071]980    def getFileByContext(context, attr=None):
[7063]981        """Get raw file data stored for the given context.
982
983        Returns a file descriptor open for reading or ``None`` if no
984        such file can be found.
985
[7071]986        Both, `context` and `attr` might be used to find (`context`)
987        and feed (`attr`) an appropriate file name chooser.
988
[7063]989        This is a convenience method.
990        """
991
[7090]992    def deleteFile(file_id):
993        """Delete file stored under `file_id`.
994
995        Remove file from filestore so, that it is not available
996        anymore on next call to getFile for the same file_id.
997
998        Should not complain if no such file exists.
999        """
1000
1001    def deleteFileByContext(context, attr=None):
1002        """Delete file for given `context` and `attr`.
1003
1004        Both, `context` and `attr` might be used to find (`context`)
1005        and feed (`attr`) an appropriate file name chooser.
1006
1007        This is a convenience method.
1008        """
1009
[7063]1010    def createFile(filename, f):
1011        """Create file given by f with filename `filename`
1012
1013        Returns a hurry.file.File-based object.
1014        """
1015
1016class IFileStoreHandler(Interface):
1017    """Filestore handlers handle specific files for file stores.
1018
1019    If a file to store/get provides a specific filename, a file store
1020    looks up special handlers for that type of file.
1021
1022    """
1023    def pathFromFileID(store, root, filename):
1024        """Turn file id into path to store.
1025
1026        Returned path should be absolute.
1027        """
1028
1029    def createFile(store, root, filename, file_id, file):
1030        """Return some hurry.file based on `store` and `file_id`.
1031
1032        Some kind of callback method called by file stores to create
1033        file objects from file_id.
1034
1035        Returns a tuple ``(raw_file, path, file_like_obj)`` where the
[7819]1036        ``file_like_obj`` should be a HurryFile, a KofaImageFile or
[7063]1037        similar. ``raw_file`` is the (maybe changed) input file and
1038        ``path`` the relative internal path to store the file at.
1039
1040        Please make sure the ``raw_file`` is opened for reading and
1041        the file descriptor set at position 0 when returned.
1042
1043        This method also gets the raw input file object that is about
1044        to be stored and is expected to raise any exceptions if some
1045        kind of validation or similar fails.
1046        """
[7389]1047
1048class IPDF(Interface):
1049    """A PDF representation of some context.
1050    """
1051
[8257]1052    def __call__(view=None, note=None):
[7389]1053        """Create a bytestream representing a PDF from context.
1054
1055        If `view` is passed in additional infos might be rendered into
1056        the document.
[8257]1057
1058        `note` is optional HTML rendered at bottom of the created
1059        PDF. Please consider the limited reportlab support for HTML,
1060        but using font-tags and friends you certainly can get the
1061        desired look.
[7389]1062        """
[7473]1063
1064class IMailService(Interface):
1065    """A mail service.
1066    """
1067
1068    def __call__():
1069        """Get the default mail delivery.
1070        """
[7576]1071
1072from zope.configuration.fields import Path
1073class IDataCenterConfig(Interface):
1074    path = Path(
1075        title = u'Path',
[7828]1076        description = u"Directory where the datacenter should store "
1077                      u"files by default (adjustable in web UI).",
[7576]1078        required = True,
1079        )
[8346]1080
1081class IChangePassword(IKofaObject):
1082    """Interface needed for change pasword page.
1083
1084    """
1085    identifier = schema.TextLine(
1086        title = _(u'Unique Identifier'),
[8394]1087        description = _(
1088            u'User Name, Student or Applicant Id, Matriculation or '
1089            u'Registration Number'),
[8346]1090        required = True,
1091        readonly = False,
1092        )
1093
1094    email = schema.ASCIILine(
1095        title = _(u'Email Address'),
1096        required = True,
1097        constraint=validate_email,
[8394]1098        )
Note: See TracBrowser for help on using the repository browser.