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

Last change on this file since 10332 was 10055, checked in by uli, 12 years ago

Provide infrastructure to remember failed logins.

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