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

Last change on this file since 11790 was 11664, checked in by Henrik Bettermann, 10 years ago

Sort ContextualDictSource? by dictionary values not by keys.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 41.2 KB
RevLine 
[7193]1## $Id: interfaces.py 11664 2014-05-26 10:21:17Z 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
[9217]21import zc.async.interfaces
[7670]22import zope.i18nmessageid
[6915]23from datetime import datetime
[7063]24from hurry.file.interfaces import IFileRetrieval
[8394]25from hurry.workflow.interfaces import IWorkflowInfo
[4789]26from zc.sourcefactory.basic import BasicSourceFactory
[6147]27from zope import schema
[7233]28from zope.pluggableauth.interfaces import IPrincipalInfo
29from zope.security.interfaces import IGroupClosureAwarePrincipal as IPrincipal
[4789]30from zope.component import getUtility
[4882]31from zope.component.interfaces import IObjectEvent
[9217]32from zope.configuration.fields import Path
33from zope.container.interfaces import INameChooser, IContainer
[8394]34from zope.interface import Interface, Attribute
[7795]35from zope.schema.interfaces import IObject
[4789]36from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
[8176]37from waeup.kofa.schema import PhoneNumber
[11450]38from waeup.kofa.sourcefactory import SmartBasicContextualSourceFactory
[3521]39
[7811]40_ = MessageFactory = zope.i18nmessageid.MessageFactory('waeup.kofa')
[6990]41
[8214]42DELETION_MARKER = 'XXX'
43IGNORE_MARKER = '<IGNORE>'
[9217]44WAEUP_KEY = 'waeup.kofa'
45VIRT_JOBS_CONTAINER_NAME = 'jobs'
[8202]46
[7673]47CREATED = 'created'
48ADMITTED = 'admitted'
49CLEARANCE = 'clearance started'
50REQUESTED = 'clearance requested'
51CLEARED = 'cleared'
52PAID = 'school fee paid'
53RETURNING = 'returning'
54REGISTERED = 'courses registered'
55VALIDATED = 'courses validated'
[10446]56GRADUATED = 'graduated'
57TRANSCRIPT = 'transcript requested'
[7670]58
[10446]59
[9217]60#: A dict giving job status as tuple (<STRING>, <TRANSLATED_STRING>),
61#: the latter for UI purposes.
62JOB_STATUS_MAP = {
63    zc.async.interfaces.NEW: ('new', _('new')),
64    zc.async.interfaces.COMPLETED: ('completed', _('completed')),
65    zc.async.interfaces.PENDING: ('pending', _('pending')),
66    zc.async.interfaces.ACTIVE: ('active', _('active')),
67    zc.async.interfaces.ASSIGNED: ('assigned', _('assigned')),
68    zc.async.interfaces.CALLBACKS: ('callbacks', _('callbacks')),
69    }
70
[8361]71#default_rest_frontpage = u'' + codecs.open(os.path.join(
72#        os.path.dirname(__file__), 'frontpage.rst'),
73#        encoding='utf-8', mode='rb').read()
74
75default_html_frontpage = u'' + codecs.open(os.path.join(
76        os.path.dirname(__file__), 'frontpage.html'),
[7702]77        encoding='utf-8', mode='rb').read()
[6361]78
[7819]79def SimpleKofaVocabulary(*terms):
[6915]80    """A well-buildt vocabulary provides terms with a value, token and
81       title for each term
82    """
83    return SimpleVocabulary([
84            SimpleTerm(value, value, title) for title, value in terms])
85
86def academic_sessions():
87    curr_year = datetime.now().year
[9115]88    year_range = range(1995, curr_year + 2)
[6915]89    return [('%s/%s' % (year,year+1), year) for year in year_range]
90
[7819]91academic_sessions_vocab = SimpleKofaVocabulary(*academic_sessions())
[6915]92
[7819]93registration_states_vocab = SimpleKofaVocabulary(
[7677]94    (_('created'), CREATED),
95    (_('admitted'), ADMITTED),
96    (_('clearance started'), CLEARANCE),
97    (_('clearance requested'), REQUESTED),
98    (_('cleared'), CLEARED),
99    (_('school fee paid'), PAID),
100    (_('courses registered'), REGISTERED),
101    (_('courses validated'), VALIDATED),
[9671]102    (_('returning'), RETURNING),
[10451]103    (_('graduated'), GRADUATED),
104    (_('transcript requested'), TRANSCRIPT),
[6990]105    )
106
[11450]107class ContextualDictSourceFactoryBase(SmartBasicContextualSourceFactory):
108    """A base for contextual sources based on KofaUtils dicts.
109
110    To create a real source, you have to set the `DICT_NAME` attribute
111    which should be the name of a dictionary in KofaUtils.
112    """
113    def getValues(self, context):
114        utils = getUtility(IKofaUtils)
[11664]115        sorted_items = sorted(getattr(utils, self.DICT_NAME).items(),
116                              key=lambda item: item[1])
117        return [item[0] for item in sorted_items]
[11450]118
119    def getToken(self, context, value):
120        return str(value)
121
122    def getTitle(self, context, value):
123        utils = getUtility(IKofaUtils)
124        return getattr(utils, self.DICT_NAME)[value]
125
[7795]126class SubjectSource(BasicSourceFactory):
[7918]127    """A source for school subjects used in exam documentation.
128    """
[7795]129    def getValues(self):
[7841]130        subjects_dict = getUtility(IKofaUtils).EXAM_SUBJECTS_DICT
[7837]131        return sorted(subjects_dict.keys())
132
[7795]133    def getTitle(self, value):
[7841]134        subjects_dict = getUtility(IKofaUtils).EXAM_SUBJECTS_DICT
[7837]135        return "%s:" % subjects_dict[value]
[7795]136
137class GradeSource(BasicSourceFactory):
[7918]138    """A source for exam grades.
139    """
[7795]140    def getValues(self):
[7918]141        for entry in getUtility(IKofaUtils).EXAM_GRADES:
142            yield entry[0]
[7837]143
[7795]144    def getTitle(self, value):
[7918]145        return dict(getUtility(IKofaUtils).EXAM_GRADES)[value]
[7795]146
[11451]147class DisablePaymentGroupSource(ContextualDictSourceFactoryBase):
148    """A source for filtering groups of students
149    """
150    #: name of dict to deliver from kofa utils.
151    DICT_NAME = 'DISABLE_PAYMENT_GROUP_DICT'
152
[7850]153# Define a validation method for email addresses
[7221]154class NotAnEmailAddress(schema.ValidationError):
155    __doc__ = u"Invalid email address"
156
[8638]157#: Regular expression to check email-address formats. As these can
158#: become rather complex (nearly everything is allowed by RFCs), we only
159#: forbid whitespaces, commas and dots following onto each other.
[7221]160check_email = re.compile(
[8638]161    r"^[^@\s,]+@[^@\.\s,]+(\.[^@\.\s,]+)*$").match
[7221]162
163def validate_email(value):
164    if not check_email(value):
165        raise NotAnEmailAddress(value)
166    return True
167
[7850]168# Define a validation method for international phone numbers
169class InvalidPhoneNumber(schema.ValidationError):
170    __doc__ = u"Invalid phone number"
171
172# represent format +NNN-NNNN-NNNN
173RE_INT_PHONE = re.compile(r"^\+?\d+\-\d+\-[\d\-]+$")
174
175def validate_phone(value):
[7851]176    if not RE_INT_PHONE.match(value):
[7850]177        raise InvalidPhoneNumber(value)
178    return True
179
[4858]180class FatalCSVError(Exception):
181    """Some row could not be processed.
182    """
183    pass
184
[6226]185class DuplicationError(Exception):
186    """An exception that can be raised when duplicates are found.
187
188    When raising :exc:`DuplicationError` you can, beside the usual
189    message, specify a list of objects which are duplicates. These
190    values can be used by catching code to print something helpful or
191    similar.
192    """
193    def __init__(self, msg, entries=[]):
194        self.msg = msg
195        self.entries = entries
196
197    def __str__(self):
198        return '%r' % self.msg
199
[6143]200class RoleSource(BasicSourceFactory):
[7178]201    """A source for site roles.
[6508]202    """
[6143]203    def getValues(self):
[6157]204        # late import: in interfaces we should not import local modules
[7811]205        from waeup.kofa.permissions import get_waeup_role_names
[7186]206        return get_waeup_role_names()
[6157]207
208    def getTitle(self, value):
209        # late import: in interfaces we should not import local modules
[7811]210        from waeup.kofa.permissions import get_all_roles
[7186]211        roles = dict(get_all_roles())
[6157]212        if value in roles.keys():
213            title = roles[value].title
[6569]214            if '.' in title:
215                title = title.split('.', 2)[1]
[6157]216        return title
[6143]217
[7313]218class CaptchaSource(BasicSourceFactory):
219    """A source for captchas.
220    """
221    def getValues(self):
[7323]222        captchas = ['No captcha', 'Testing captcha', 'ReCaptcha']
[7313]223        try:
224            # we have to 'try' because IConfiguration can only handle
[7817]225            # interfaces from w.k.interface.
[7811]226            from waeup.kofa.browser.interfaces import ICaptchaManager
[7313]227        except:
228            return captchas
229        return sorted(getUtility(ICaptchaManager).getAvailCaptchas().keys())
230
231    def getTitle(self, value):
232        return value
233
[7795]234class IResultEntry(Interface):
235    """A school grade entry.
236    """
237    subject = schema.Choice(
238        title = _(u'Subject'),
239        source = SubjectSource(),
240        )
241    grade = schema.Choice(
242        title = _(u'Grade'),
243        source = GradeSource(),
244        )
245
246class IResultEntryField(IObject):
247    """A zope.schema-like field for usage in interfaces.
248
249    Marker interface to distuingish result entries from ordinary
250    object fields. Needed for registration of widgets.
251    """
252
[7819]253class IKofaUtils(Interface):
[7358]254    """A collection of methods which are subject to customization.
255    """
[7568]256
[7841]257    PORTAL_LANGUAGE = Attribute("Dict of global language setting")
258    PREFERRED_LANGUAGES_DICT = Attribute("Dict of preferred languages")
259    EXAM_SUBJECTS_DICT = Attribute("Dict of examination subjects")
260    EXAM_GRADES_DICT = Attribute("Dict of examination grades")
261    INST_TYPES_DICT = Attribute("Dict if institution types")
262    STUDY_MODES_DICT = Attribute("Dict of study modes")
263    APP_CATS_DICT = Attribute("Dict of application categories")
264    SEMESTER_DICT = Attribute("Dict of semesters or trimesters")
[8394]265    INT_PHONE_PREFIXES = Attribute(
266        "Dict of international phone number prefixes")
[7568]267
[7404]268    def sendContactForm(
269          from_name,from_addr,rcpt_name,rcpt_addr,
270          from_username,usertype,portal,body,subject):
[7358]271        """Send an email with data provided by forms.
272        """
273
[7475]274    def fullname(firstname,lastname,middlename):
275        """Full name constructor.
276        """
277
[8853]278    def sendCredentials(user, password, url_info, msg):
[7475]279        """Send credentials as email.
280
281        Input is the applicant for which credentials are sent and the
282        password.
283
284        Returns True or False to indicate successful operation.
285        """
286
287    def genPassword(length, chars):
288        """Generate a random password.
289        """
290
[7819]291class IKofaObject(Interface):
292    """A Kofa object.
[5663]293
294    This is merely a marker interface.
[4789]295    """
296
[7819]297class IUniversity(IKofaObject):
[3521]298    """Representation of a university.
299    """
[5955]300
[6065]301
[7819]302class IKofaContainer(IKofaObject):
303    """A container for Kofa objects.
[4789]304    """
305
[7819]306class IKofaContained(IKofaObject):
307    """An item contained in an IKofaContainer.
[4789]308    """
[6136]309
[7726]310class ICSVExporter(Interface):
311    """A CSV file exporter for objects.
312    """
313    fields = Attribute("""List of fieldnames in resulting CSV""")
[7907]314
315    title = schema.TextLine(
316        title = u'Title',
317        description = u'Description to be displayed in selections.',
318        )
[7726]319    def mangle_value(value, name, obj):
320        """Mangle `value` extracted from `obj` or suobjects thereof.
321
[8394]322        This is called by export before actually writing to the result
323        file.
[7726]324        """
325
[9797]326    def get_filtered(site, **kw):
327        """Get datasets in `site` to be exported.
328
329        The set of data is specified by keywords, which might be
330        different for any implementaion of exporter.
331
332        Returns an iterable.
333        """
334
[7730]335    def export(iterable, filepath=None):
336        """Export iterables as rows in a CSV file.
[7726]337
[8394]338        If `filepath` is not given, a string with the data should be
339        returned.
[7730]340
341        What kind of iterables are acceptable depends on the specific
342        exporter implementation.
[7726]343        """
344
[9766]345    def export_all(site, filepath=None):
[7726]346        """Export all items in `site` as CSV file.
347
[8394]348        if `filepath` is not given, a string with the data should be
349        returned.
[7726]350        """
351
[9797]352    def export_filtered(site, filepath=None, **kw):
353        """Export those items in `site` specified by `args` and `kw`.
354
355        If `filepath` is not given, a string with the data should be
356        returned.
357
358        Which special keywords are supported is up to the respective
359        exporter.
360        """
361
[7819]362class IKofaExporter(Interface):
[4789]363    """An exporter for objects.
364    """
365    def export(obj, filepath=None):
366        """Export by pickling.
367
368        Returns a file-like object containing a representation of `obj`.
369
370        This is done using `pickle`. If `filepath` is ``None``, a
371        `cStringIO` object is returned, that contains the saved data.
372        """
373
[7819]374class IKofaXMLExporter(Interface):
[4789]375    """An XML exporter for objects.
376    """
377    def export(obj, filepath=None):
378        """Export as XML.
379
380        Returns an XML representation of `obj`.
381
382        If `filepath` is ``None``, a StringIO` object is returned,
383        that contains the transformed data.
384        """
385
[7819]386class IKofaXMLImporter(Interface):
[4789]387    """An XML import for objects.
388    """
389    def doImport(filepath):
390        """Create Python object from XML.
391
392        Returns a Python object.
393        """
394
[4858]395class IBatchProcessor(Interface):
396    """A batch processor that handles mass-operations.
397    """
398    name = schema.TextLine(
[7933]399        title = _(u'Processor name')
[4858]400        )
401
[5476]402    def doImport(path, headerfields, mode='create', user='Unknown',
[8218]403                 logger=None, ignore_empty=True):
[4858]404        """Read data from ``path`` and update connected object.
[5476]405
406        `headerfields` is a list of headerfields as read from the file
407        to import.
408
409        `mode` gives the import mode to use (``'create'``,
410        ``'update'``, or ``'remove'``.
411
412        `user` is a string describing the user performing the
413        import. Normally fetched from current principal.
414
415        `logger` is the logger to use during import.
[8218]416
417        `ignore_emtpy` in update mode ignores empty fields if true.
[4858]418        """
419
[7819]420class IContactForm(IKofaObject):
[7225]421    """A contact form.
422    """
423
424    email_from = schema.ASCIILine(
[7828]425        title = _(u'Email Address:'),
[7225]426        default = None,
427        required = True,
428        constraint=validate_email,
429        )
430
431    email_to = schema.ASCIILine(
[7828]432        title = _(u'Email to:'),
[7225]433        default = None,
434        required = True,
435        constraint=validate_email,
436        )
437
438    subject = schema.TextLine(
[7828]439        title = _(u'Subject:'),
[7225]440        required = True,)
441
442    fullname = schema.TextLine(
[7828]443        title = _(u'Full Name:'),
[7225]444        required = True,)
445
446    body = schema.Text(
[7828]447        title = _(u'Text:'),
[7225]448        required = True,)
449
[7819]450class IKofaPrincipalInfo(IPrincipalInfo):
451    """Infos about principals that are users of Kofa Kofa.
[7233]452    """
453    email = Attribute("The email address of a user")
454    phone = Attribute("The phone number of a user")
[8757]455    public_name = Attribute("The public name of a user")
[7225]456
[7233]457
[7819]458class IKofaPrincipal(IPrincipal):
459    """A principle for Kofa Kofa.
[7233]460
461    This interface extends zope.security.interfaces.IPrincipal and
462    requires also an `id` and other attributes defined there.
463    """
464
465    email = schema.TextLine(
[7828]466        title = _(u'Email Address'),
[7233]467        description = u'',
468        required=False,)
469
[8176]470    phone = PhoneNumber(
[7828]471        title = _(u'Phone'),
[7233]472        description = u'',
473        required=False,)
474
[8757]475    public_name = schema.TextLine(
476        title = _(u'Public Name'),
477        required = False,)
478
[10055]479class IFailedLoginInfo(IKofaObject):
480    """Info about failed logins.
481
482    Timestamps are supposed to be stored as floats using time.time()
483    or similar.
484    """
485    num = schema.Int(
486        title = _(u'Number of failed logins'),
487        description = _(u'Number of failed logins'),
488        required = True,
489        default = 0,
490        )
491
492    last = schema.Float(
493        title = _(u'Timestamp'),
494        description = _(u'Timestamp of last failed login or `None`'),
495        required = False,
496        default = None,
497        )
498
499    def as_tuple():
500        """Get login info as tuple ``<NUM>, <TIMESTAMP>``.
501        """
502
503    def set_values(num=0, last=None):
504        """Set number of failed logins and timestamp of last one.
505        """
506
507    def increase():
508        """Increase the current number of failed logins and set timestamp.
509        """
510
511    def reset():
512        """Set failed login counters back to zero.
513        """
514
515
[7819]516class IUserAccount(IKofaObject):
[4789]517    """A user account.
518    """
[10055]519
520    failed_logins = Attribute("""FailedLoginInfo for this account""")
521
[4789]522    name = schema.TextLine(
[7828]523        title = _(u'User Id'),
[6512]524        description = u'Login name of user',
[4789]525        required = True,)
[7221]526
[4789]527    title = schema.TextLine(
[7828]528        title = _(u'Full Name'),
[8759]529        required = True,)
[7221]530
[8756]531    public_name = schema.TextLine(
532        title = _(u'Public Name'),
[8759]533        description = u"Substitute for officer's real name "
534                       "in student object histories.",
[8756]535        required = False,)
536
[7197]537    description = schema.Text(
[7828]538        title = _(u'Description/Notice'),
[4789]539        required = False,)
[7221]540
541    email = schema.ASCIILine(
[7828]542        title = _(u'Email Address'),
[7221]543        default = None,
[7222]544        required = True,
[7221]545        constraint=validate_email,
546        )
547
[8176]548    phone = PhoneNumber(
[7828]549        title = _(u'Phone'),
[7233]550        default = None,
[8062]551        required = False,
[7233]552        )
553
[4789]554    roles = schema.List(
[8486]555        title = _(u'Portal Roles'),
[8079]556        value_type = schema.Choice(source=RoleSource()),
557        required = False,
558        )
[6136]559
[10055]560
561
[7147]562class IPasswordValidator(Interface):
563    """A password validator utility.
564    """
[6136]565
[7147]566    def validate_password(password, password_repeat):
567        """Validates a password by comparing it with
568        control password and checking some other requirements.
569        """
570
571
[7819]572class IUsersContainer(IKofaObject):
[4789]573    """A container for users (principals).
574
575    These users are used for authentication purposes.
576    """
577
578    def addUser(name, password, title=None, description=None):
579        """Add a user.
580        """
581
582    def delUser(name):
583        """Delete a user if it exists.
584        """
585
[6141]586class ILocalRolesAssignable(Interface):
587    """The local roles assignable to an object.
588    """
589    def __call__():
590        """Returns a list of dicts.
591
592        Each dict contains a ``name`` referring to the role assignable
593        for the specified object and a `title` to describe the range
594        of users to which this role can be assigned.
595        """
596
[7819]597class IConfigurationContainer(IKofaObject):
[6907]598    """A container for session configuration objects.
599    """
600
601    name = schema.TextLine(
[7828]602        title = _(u'Name of University'),
603        default = _(u'Sample University'),
[6907]604        required = True,
605        )
606
[7459]607    acronym = schema.TextLine(
[7828]608        title = _(u'Abbreviated Title of University'),
[7819]609        default = u'WAeUP.Kofa',
[7459]610        required = True,
611        )
612
[6907]613    frontpage = schema.Text(
[8361]614        title = _(u'Content in HTML format'),
[6907]615        required = False,
[8361]616        default = default_html_frontpage,
[6907]617        )
618
[7702]619    frontpage_dict = schema.Dict(
620        title = u'Content as language dictionary with values in html format',
[7485]621        required = False,
[7702]622        default = {},
[7485]623        )
624
[7223]625    name_admin = schema.TextLine(
[7828]626        title = _(u'Name of Administrator'),
[7223]627        default = u'Administrator',
[8230]628        required = True,
[7223]629        )
630
[7221]631    email_admin = schema.ASCIILine(
[7828]632        title = _(u'Email Address of Administrator'),
[7221]633        default = 'contact@waeup.org',
[8230]634        required = True,
[7221]635        constraint=validate_email,
636        )
637
638    email_subject = schema.TextLine(
[7828]639        title = _(u'Subject of Email to Administrator'),
640        default = _(u'Kofa Contact'),
[8230]641        required = True,
[7221]642        )
643
[7470]644    smtp_mailer = schema.Choice(
[7828]645        title = _(u'SMTP mailer to use when sending mail'),
[7470]646        vocabulary = 'Mail Delivery Names',
647        default = 'No email service',
648        required = True,
649        )
650
[7313]651    captcha = schema.Choice(
[7828]652        title = _(u'Captcha used for public registration pages'),
[7313]653        source = CaptchaSource(),
654        default = u'No captcha',
655        required = True,
656        )
[7221]657
[7664]658    carry_over = schema.Bool(
[7828]659        title = _(u'Carry-over Course Registration'),
[7664]660        default = False,
661        )
662
[10627]663    current_academic_session = schema.Choice(
664        title = _(u'Current Academic Session'),
[10631]665        description = _(u'Session for which score editing is allowed'),
[10627]666        source = academic_sessions_vocab,
667        default = None,
668        required = False,
669        readonly = False,
670        )
671
[11589]672    next_matric_integer = schema.Int(
673        title = _(u'Next Matriculation Number Integer'),
674        description = _(u'Integer used for constructing the next '
675                         'matriculation number'),
676        default = 0,
677        readonly = False,
678        required = False,
679        )
680
[7819]681class ISessionConfiguration(IKofaObject):
[6915]682    """A session configuration object.
[6907]683    """
684
[6915]685    academic_session = schema.Choice(
[7828]686        title = _(u'Academic Session'),
[6915]687        source = academic_sessions_vocab,
688        default = None,
689        required = True,
690        readonly = True,
691        )
692
[8260]693    application_fee = schema.Float(
694        title = _(u'Application Fee'),
[7927]695        default = 0.0,
[7881]696        required = False,
[6916]697        )
698
[8260]699    clearance_fee = schema.Float(
[9243]700        title = _(u'Acceptance Fee'),
[7927]701        default = 0.0,
[7881]702        required = False,
[6993]703        )
704
[8260]705    booking_fee = schema.Float(
706        title = _(u'Bed Booking Fee'),
[7927]707        default = 0.0,
[7881]708        required = False,
[7250]709        )
710
[9423]711    maint_fee = schema.Float(
[10680]712        title = _(u'Rent (fallback)'),
[9423]713        default = 0.0,
714        required = False,
715        )
716
[10449]717    transcript_fee = schema.Float(
718        title = _(u'Transcript Fee'),
719        default = 0.0,
720        required = False,
721        )
722
[9814]723    clearance_enabled = schema.Bool(
724        title = _(u'Clearance enabled'),
725        default = False,
726        )
727
[11451]728    payment_disabled = schema.List(
729        title = _(u'Payment disabled'),
730        value_type = schema.Choice(
731            source = DisablePaymentGroupSource(),
732            ),
733        required = False,
734        default = [],
735        )
736
[6918]737    def getSessionString():
738        """Returns the session string from the vocabulary.
739        """
740
741
[6916]742class ISessionConfigurationAdd(ISessionConfiguration):
743    """A session configuration object in add mode.
744    """
745
746    academic_session = schema.Choice(
[7828]747        title = _(u'Academic Session'),
[6916]748        source = academic_sessions_vocab,
749        default = None,
750        required = True,
751        readonly = False,
752        )
753
754ISessionConfigurationAdd['academic_session'].order =  ISessionConfiguration[
755    'academic_session'].order
756
[7819]757class IDataCenter(IKofaObject):
[4789]758    """A data center.
759
[8394]760    A data center manages files (uploads, downloads, etc.).
761
762    Beside providing the bare paths needed to keep files, it also
763    provides some helpers to put results of batch processing into
764    well-defined final locations (with well-defined filenames).
765
766    The main use-case is managing of site-related files, i.e. files
767    for import, export etc.
768
769    DataCenters are _not_ meant as storages for object-specific files
770    like passport photographs and similar.
771
772    It is up to the datacenter implementation how to organize data
773    (paths) inside its storage path.
[4789]774    """
[8394]775    storage = schema.Bytes(
776        title = u'Path to directory where everything is kept.'
777        )
[4789]778
[8394]779    deleted_path = schema.Bytes(
780        title = u'Path were data about deleted objects should be stored.'
781        )
782
[9023]783    def getPendingFiles(sort='name'):
[8394]784        """Get a list of files stored in `storage` sorted by basename.
785        """
[9023]786
[9074]787    def getFinishedFiles():
788        """Get a list of files stored in `finished` subfolder of `storage`.
[9023]789        """
790
[8394]791    def setStoragePath(path, move=False, overwrite=False):
792        """Set the path where to store files.
793
794        If `move` is True, move over files from the current location
795        to the new one.
796
797        If `overwrite` is also True, overwrite any already existing
798        files of same name in target location.
799
800        Triggers a DataCenterStorageMovedEvent.
801        """
802
803    def distProcessedFiles(successful, source_path, finished_file,
804                           pending_file, mode='create', move_orig=True):
805        """Distribute processed files over final locations.
806        """
807
808
[4789]809class IDataCenterFile(Interface):
810    """A data center file.
811    """
[4858]812
813    name = schema.TextLine(
814        title = u'Filename')
815
816    size = schema.TextLine(
817        title = u'Human readable file size')
818
819    uploaddate = schema.TextLine(
820        title = u'Human readable upload datetime')
821
822    lines = schema.Int(
823        title = u'Number of lines in file')
[6136]824
[4789]825    def getDate():
826        """Get creation timestamp from file in human readable form.
827        """
828
829    def getSize():
830        """Get human readable size of file.
831        """
[4858]832
833    def getLinesNumber():
834        """Get number of lines of file.
835        """
[4882]836
837class IDataCenterStorageMovedEvent(IObjectEvent):
838    """Emitted, when the storage of a datacenter changes.
839    """
[5007]840
[6136]841class IObjectUpgradeEvent(IObjectEvent):
842    """Can be fired, when an object shall be upgraded.
843    """
844
[6180]845class ILocalRoleSetEvent(IObjectEvent):
846    """A local role was granted/revoked for a principal on an object.
847    """
848    role_id = Attribute(
849        "The role id that was set.")
850    principal_id = Attribute(
851        "The principal id for which the role was granted/revoked.")
852    granted = Attribute(
853        "Boolean. If false, then the role was revoked.")
854
[5007]855class IQueryResultItem(Interface):
856    """An item in a search result.
857    """
858    url = schema.TextLine(
859        title = u'URL that links to the found item')
860    title = schema.TextLine(
861        title = u'Title displayed in search results.')
862    description = schema.Text(
863        title = u'Longer description of the item found.')
[6136]864
[7819]865class IKofaPluggable(Interface):
866    """A component that might be plugged into a Kofa Kofa app.
[5658]867
868    Components implementing this interface are referred to as
869    'plugins'. They are normally called when a new
[7811]870    :class:`waeup.kofa.app.University` instance is created.
[5658]871
872    Plugins can setup and update parts of the central site without the
[7811]873    site object (normally a :class:`waeup.kofa.app.University` object)
[5658]874    needing to know about that parts. The site simply collects all
875    available plugins, calls them and the plugins care for their
[5676]876    respective subarea like the applicants area or the datacenter
[5658]877    area.
878
879    Currently we have no mechanism to define an order of plugins. A
880    plugin should therefore make no assumptions about the state of the
881    site or other plugins being run before and instead do appropriate
882    checks if necessary.
883
884    Updates can be triggered for instance by the respective form in
885    the site configuration. You normally do updates when the
886    underlying software changed.
[5013]887    """
[5069]888    def setup(site, name, logger):
889        """Create an instance of the plugin.
[5013]890
[5658]891        The method is meant to be called by the central app (site)
892        when it is created.
893
894        `site`:
895           The site that requests a setup.
896
897        `name`:
898           The name under which the plugin was registered (utility name).
899
900        `logger`:
901           A standard Python logger for the plugins use.
[5069]902        """
903
904    def update(site, name, logger):
905        """Method to update an already existing plugin.
906
907        This might be called by a site when something serious
[5658]908        changes. It is a poor-man replacement for Zope generations
909        (but probably more comprehensive and better understandable).
910
911        `site`:
912           The site that requests an update.
913
914        `name`:
915           The name under which the plugin was registered (utility name).
916
917        `logger`:
918           A standard Python logger for the plugins use.
[5069]919        """
[5898]920
[5899]921class IAuthPluginUtility(Interface):
[5898]922    """A component that cares for authentication setup at site creation.
923
924    Utilities providing this interface are looked up when a Pluggable
925    Authentication Utility (PAU) for any
[7811]926    :class:`waeup.kofa.app.University` instance is created and put
[5898]927    into ZODB.
928
929    The setup-code then calls the `register` method of the utility and
930    expects a modified (or unmodified) version of the PAU back.
931
932    This allows to define any authentication setup modifications by
933    submodules or third-party modules/packages.
934    """
935
936    def register(pau):
937        """Register any plugins wanted to be in the PAU.
938        """
939
940    def unregister(pau):
941        """Unregister any plugins not wanted to be in the PAU.
942        """
[6273]943
944class IObjectConverter(Interface):
945    """Object converters are available as simple adapters, adapting
946       interfaces (not regular instances).
947
948    """
949
[6277]950    def fromStringDict(self, data_dict, context, form_fields=None):
951        """Convert values in `data_dict`.
[6273]952
[6277]953        Converts data in `data_dict` into real values based on
954        `context` and `form_fields`.
[6273]955
[6277]956        `data_dict` is a mapping (dict) from field names to values
957        represented as strings.
[6273]958
[6277]959        The fields (keys) to convert can be given in optional
960        `form_fields`. If given, form_fields should be an instance of
961        :class:`zope.formlib.form.Fields`. Suitable instances are for
962        example created by :class:`grok.AutoFields`.
[6273]963
[6277]964        If no `form_fields` are given, a default is computed from the
965        associated interface.
[6273]966
[6277]967        The `context` can be an existing object (implementing the
968        associated interface) or a factory name. If it is a string, we
969        try to create an object using
970        :func:`zope.component.createObject`.
971
972        Returns a tuple ``(<FIELD_ERRORS>, <INVARIANT_ERRORS>,
973        <DATA_DICT>)`` where
974
975        ``<FIELD_ERRORS>``
976           is a list of tuples ``(<FIELD_NAME>, <ERROR>)`` for each
977           error that happened when validating the input data in
978           `data_dict`
979
980        ``<INVARIANT_ERRORS>``
981           is a list of invariant errors concerning several fields
982
983        ``<DATA_DICT>``
984           is a dict with the values from input dict converted.
985
986        If errors happen, i.e. the error lists are not empty, always
987        an empty ``<DATA_DICT>`` is returned.
988
989        If ``<DATA_DICT>` is non-empty, there were no errors.
[6273]990        """
[6293]991
[7932]992class IFieldConverter(Interface):
[8214]993    def request_data(name, value, schema_field, prefix='', mode='create'):
[7932]994        """Create a dict with key-value mapping as created by a request.
995
996        `name` and `value` are expected to be parsed from CSV or a
997        similar input and represent an attribute to be set to a
998        representation of value.
999
[8214]1000        `mode` gives the mode of import.
1001
[7932]1002        :meth:`update_request_data` is then requested to turn this
1003        name and value into vars as they would be sent by a regular
1004        form submit. This means we do not create the real values to be
1005        set but we only define the values that would be sent in a
1006        browser request to request the creation of those values.
1007
1008        The returned dict should contain names and values of a faked
1009        browser request for the given `schema_field`.
1010
1011        Field converters are normally registered as adapters to some
1012        specific zope.schema field.
1013        """
1014
[6338]1015class IObjectHistory(Interface):
1016
1017    messages = schema.List(
1018        title = u'List of messages stored',
1019        required = True,
1020        )
1021
1022    def addMessage(message):
1023        """Add a message.
1024        """
[6353]1025
[7819]1026class IKofaWorkflowInfo(IWorkflowInfo):
[6353]1027    """A :class:`hurry.workflow.workflow.WorkflowInfo` with additional
1028       methods for convenience.
1029    """
1030    def getManualTransitions():
1031        """Get allowed manual transitions.
1032
1033        Get a sorted list of tuples containing the `transition_id` and
1034        `title` of each allowed transition.
1035        """
[6481]1036
1037class ISiteLoggers(Interface):
1038
[7819]1039    loggers = Attribute("A list or generator of registered KofaLoggers")
[6481]1040
1041    def register(name, filename=None, site=None, **options):
1042        """Register a logger `name` which logs to `filename`.
1043
1044        If `filename` is not given, logfile will be `name` with
1045        ``.log`` as filename extension.
1046        """
1047
1048    def unregister(name):
1049        """Unregister a once registered logger.
1050        """
1051
1052class ILogger(Interface):
1053    """A logger cares for setup, update and restarting of a Python logger.
1054    """
1055
1056    logger = Attribute("""A :class:`logging.Logger` instance""")
1057
1058
1059    def __init__(name, filename=None, site=None, **options):
[7819]1060        """Create a Kofa logger instance.
[6481]1061        """
1062
1063    def setup():
1064        """Create a Python :class:`logging.Logger` instance.
1065
1066        The created logger is based on the params given by constructor.
1067        """
1068
1069    def update(**options):
1070        """Update the logger.
1071
1072        Updates the logger respecting modified `options` and changed
1073        paths.
1074        """
[6754]1075
1076class ILoggerCollector(Interface):
1077
1078    def getLoggers(site):
1079        """Return all loggers registered for `site`.
1080        """
1081
1082    def registerLogger(site, logging_component):
1083        """Register a logging component residing in `site`.
1084        """
1085
1086    def unregisterLogger(site, logging_component):
1087        """Unregister a logger.
1088        """
[7063]1089
1090#
1091# External File Storage and relatives
1092#
1093class IFileStoreNameChooser(INameChooser):
1094    """See zope.container.interfaces.INameChooser for base methods.
1095    """
[7066]1096    def checkName(name, attr=None):
[7063]1097        """Check whether an object name is valid.
1098
1099        Raises a user error if the name is not valid.
1100        """
1101
[7066]1102    def chooseName(name, attr=None):
1103        """Choose a unique valid file id for the object.
[7063]1104
[7066]1105        The given name may be taken into account when choosing the
1106        name (file id).
[7063]1107
[7066]1108        chooseName is expected to always choose a valid file id (that
1109        would pass the checkName test) and never raise an error.
1110
1111        If `attr` is not ``None`` it might been taken into account as
1112        well when generating the file id. Usual behaviour is to
1113        interpret `attr` as a hint for what type of file for a given
1114        context should be stored if there are several types
1115        possible. For instance for a certain student some file could
1116        be the connected passport photograph or some certificate scan
1117        or whatever. Each of them has to be stored in a different
1118        location so setting `attr` to a sensible value should give
1119        different file ids returned.
[7063]1120        """
1121
1122class IExtFileStore(IFileRetrieval):
1123    """A file storage that stores files in filesystem (not as blobs).
1124    """
1125    root = schema.TextLine(
1126        title = u'Root path of file store.',
1127        )
1128
1129    def getFile(file_id):
1130        """Get raw file data stored under file with `file_id`.
1131
1132        Returns a file descriptor open for reading or ``None`` if the
1133        file cannot be found.
1134        """
1135
[7071]1136    def getFileByContext(context, attr=None):
[7063]1137        """Get raw file data stored for the given context.
1138
1139        Returns a file descriptor open for reading or ``None`` if no
1140        such file can be found.
1141
[7071]1142        Both, `context` and `attr` might be used to find (`context`)
1143        and feed (`attr`) an appropriate file name chooser.
1144
[7063]1145        This is a convenience method.
1146        """
1147
[7090]1148    def deleteFile(file_id):
1149        """Delete file stored under `file_id`.
1150
1151        Remove file from filestore so, that it is not available
1152        anymore on next call to getFile for the same file_id.
1153
1154        Should not complain if no such file exists.
1155        """
1156
1157    def deleteFileByContext(context, attr=None):
1158        """Delete file for given `context` and `attr`.
1159
1160        Both, `context` and `attr` might be used to find (`context`)
1161        and feed (`attr`) an appropriate file name chooser.
1162
1163        This is a convenience method.
1164        """
1165
[7063]1166    def createFile(filename, f):
1167        """Create file given by f with filename `filename`
1168
1169        Returns a hurry.file.File-based object.
1170        """
1171
1172class IFileStoreHandler(Interface):
1173    """Filestore handlers handle specific files for file stores.
1174
1175    If a file to store/get provides a specific filename, a file store
1176    looks up special handlers for that type of file.
1177
1178    """
1179    def pathFromFileID(store, root, filename):
1180        """Turn file id into path to store.
1181
1182        Returned path should be absolute.
1183        """
1184
1185    def createFile(store, root, filename, file_id, file):
1186        """Return some hurry.file based on `store` and `file_id`.
1187
1188        Some kind of callback method called by file stores to create
1189        file objects from file_id.
1190
1191        Returns a tuple ``(raw_file, path, file_like_obj)`` where the
[7819]1192        ``file_like_obj`` should be a HurryFile, a KofaImageFile or
[7063]1193        similar. ``raw_file`` is the (maybe changed) input file and
1194        ``path`` the relative internal path to store the file at.
1195
1196        Please make sure the ``raw_file`` is opened for reading and
1197        the file descriptor set at position 0 when returned.
1198
1199        This method also gets the raw input file object that is about
1200        to be stored and is expected to raise any exceptions if some
1201        kind of validation or similar fails.
1202        """
[7389]1203
1204class IPDF(Interface):
1205    """A PDF representation of some context.
1206    """
1207
[8257]1208    def __call__(view=None, note=None):
[7389]1209        """Create a bytestream representing a PDF from context.
1210
1211        If `view` is passed in additional infos might be rendered into
1212        the document.
[8257]1213
1214        `note` is optional HTML rendered at bottom of the created
1215        PDF. Please consider the limited reportlab support for HTML,
1216        but using font-tags and friends you certainly can get the
1217        desired look.
[7389]1218        """
[7473]1219
1220class IMailService(Interface):
1221    """A mail service.
1222    """
1223
1224    def __call__():
1225        """Get the default mail delivery.
1226        """
[7576]1227
[9217]1228
[7576]1229class IDataCenterConfig(Interface):
1230    path = Path(
1231        title = u'Path',
[7828]1232        description = u"Directory where the datacenter should store "
1233                      u"files by default (adjustable in web UI).",
[7576]1234        required = True,
1235        )
[8346]1236
[9217]1237#
1238# Asynchronous job handling and related
1239#
1240class IJobManager(IKofaObject):
1241    """A manager for asynchronous running jobs (tasks).
1242    """
1243    def put(job, site=None):
1244        """Put a job into task queue.
[8346]1245
[9217]1246        If no `site` is given, queue job in context of current local
1247        site.
1248
1249        Returns a job_id to identify the put job. This job_id is
1250        needed for further references to the job.
1251        """
1252
1253    def jobs(site=None):
1254        """Get an iterable of jobs stored.
1255        """
1256
1257    def get(job_id, site=None):
1258        """Get the job with id `job_id`.
1259
1260        For the `site` parameter see :meth:`put`.
1261        """
1262
1263    def remove(job_id, site=None):
1264        """Remove job with `job_id` from stored jobs.
1265        """
1266
1267    def start_test_job(site=None):
1268        """Start a test job.
1269        """
1270
1271class IProgressable(Interface):
1272    """A component that can indicate its progress status.
[8346]1273    """
[9217]1274    percent = schema.Float(
1275        title = u'Percent of job done already.',
[8346]1276        )
1277
[9217]1278class IJobContainer(IContainer):
1279    """A job container contains IJob objects.
1280    """
1281
1282class IExportJob(zc.async.interfaces.IJob):
1283    def __init__(site, exporter_name):
1284        pass
1285
[9816]1286    finished = schema.Bool(
1287        title = u'`True` if the job finished.`',
1288        default = False,
1289        )
1290
1291    failed = schema.Bool(
1292        title = u"`True` iff the job finished and didn't provide a file.",
1293        default = None,
1294        )
1295
[9764]1296class IExportJobContainer(IKofaObject):
[9217]1297    """A component that contains (maybe virtually) export jobs.
1298    """
[9718]1299    def start_export_job(exporter_name, user_id, *args, **kwargs):
[9217]1300        """Start asynchronous export job.
1301
1302        `exporter_name` is the name of an exporter utility to be used.
1303
1304        `user_id` is the ID of the user that triggers the export.
1305
[9718]1306        `args` positional arguments passed to the export job created.
1307
1308        `kwargs` keyword arguments passed to the export job.
1309
[9217]1310        The job_id is stored along with exporter name and user id in a
1311        persistent list.
1312
1313        Returns the job ID of the job started.
1314        """
1315
1316    def get_running_export_jobs(user_id=None):
1317        """Get export jobs for user with `user_id` as list of tuples.
1318
1319        Each tuples holds ``<job_id>, <exporter_name>, <user_id>`` in
1320        that order. The ``<exporter_name>`` is the utility name of the
1321        used exporter.
1322
1323        If `user_id` is ``None``, all running jobs are returned.
1324        """
1325
1326    def get_export_jobs_status(user_id=None):
1327        """Get running/completed export jobs for `user_id` as list of tuples.
1328
1329        Each tuple holds ``<raw status>, <status translated>,
1330        <exporter title>`` in that order, where ``<status
1331        translated>`` and ``<exporter title>`` are translated strings
1332        representing the status of the job and the human readable
1333        title of the exporter used.
1334        """
1335
1336    def delete_export_entry(entry):
1337        """Delete the export denoted by `entry`.
1338
1339        Removes `entry` from the local `running_exports` list and also
1340        removes the regarding job via the local job manager.
1341
1342        `entry` is a tuple ``(<job id>, <exporter name>, <user id>)``
1343        as created by :meth:`start_export_job` or returned by
1344        :meth:`get_running_export_jobs`.
1345        """
1346
1347    def entry_from_job_id(job_id):
1348        """Get entry tuple for `job_id`.
1349
1350        Returns ``None`` if no such entry can be found.
1351        """
[9726]1352
1353class IExportContainerFinder(Interface):
1354    """A finder for the central export container.
1355    """
1356    def __call__():
1357        """Return the currently used global or site-wide IExportContainer.
1358        """
[9766]1359
1360class IFilteredQuery(IKofaObject):
1361    """A query for objects.
1362    """
1363
1364    defaults = schema.Dict(
1365        title = u'Default Parameters',
1366        required = True,
1367        )
1368
1369    def __init__(**parameters):
1370        """Instantiate a filtered query by passing in parameters.
1371        """
1372
1373    def query():
1374        """Get an iterable of objects denoted by the set parameters.
1375
1376        The search should be applied to objects inside current
1377        site. It's the caller's duty to set the correct site before.
1378
1379        Result can be any iterable like a catalog result set, a list,
1380        or similar.
1381        """
1382
1383class IFilteredCatalogQuery(IFilteredQuery):
1384    """A catalog-based query for objects.
1385    """
1386
1387    cat_name = schema.TextLine(
1388        title = u'Registered name of the catalog to search.',
1389        required = True,
1390        )
1391
1392    def query_catalog(catalog):
1393        """Query catalog with the parameters passed to constructor.
1394        """
Note: See TracBrowser for help on using the repository browser.