source: main/waeup.kofa/branches/uli-async-update/src/waeup/kofa/interfaces.py @ 10009

Last change on this file since 10009 was 9169, checked in by uli, 12 years ago

Merge changes from trunk, r8786-HEAD

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