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

Last change on this file since 10055 was 10055, checked in by uli, 11 years ago

Provide infrastructure to remember failed logins.

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