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

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

Local exports for departments.

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