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

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

Sort ContextualDictSource? by dictionary values not by keys.

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