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

Last change on this file since 9798 was 9797, checked in by uli, 12 years ago

Local exports for departments.

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