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

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

Remove INT_PHONE_PREFIXES from KofaUtils?. It's not used.

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