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

Last change on this file since 11450 was 11450, checked in by Henrik Bettermann, 11 years ago

Move ContextualDictSourceFactoryBase? to waeup.kofa.interfaces to avoid circular imports.

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