source: main/waeup.kofa/branches/uli-py3/src/waeup/kofa/interfaces.py @ 17808

Last change on this file since 17808 was 15664, checked in by Henrik Bettermann, 5 years ago

Implement combi payments (tests will follow).

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