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

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

Fix docstrings as slanged by Sphinx.

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