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

Last change on this file since 9200 was 9115, checked in by Henrik Bettermann, 12 years ago

The year_range function was only used in applicants. Extend academic session range properly.

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