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

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

Rollback r9209. Looks like multiple merges from trunk confuse svn when merging back into trunk.

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