source: main/waeup.kofa/branches/uli-diazo-themed/src/waeup/kofa/interfaces.py @ 10976

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

Extend IHostel so that we can configure maintenance fee for each hostel.

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