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

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

Modify getWidgetsData so that we always get the same error format.

Fix tests.

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