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

Last change on this file since 10009 was 9816, checked in by Henrik Bettermann, 12 years ago

Extend IExportJob so that AsyncExportJobs? unveil their status like AsyncReportJobs? do. Use this property attribute to hide buttons.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 38.4 KB
Line 
1## $Id: interfaces.py 9816 2012-12-21 13:09:05Z henrik $
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    clearance_enabled = schema.Bool(
634        title = _(u'Clearance enabled'),
635        default = False,
636        )
637
638    def getSessionString():
639        """Returns the session string from the vocabulary.
640        """
641
642
643class ISessionConfigurationAdd(ISessionConfiguration):
644    """A session configuration object in add mode.
645    """
646
647    academic_session = schema.Choice(
648        title = _(u'Academic Session'),
649        source = academic_sessions_vocab,
650        default = None,
651        required = True,
652        readonly = False,
653        )
654
655ISessionConfigurationAdd['academic_session'].order =  ISessionConfiguration[
656    'academic_session'].order
657
658class IDataCenter(IKofaObject):
659    """A data center.
660
661    A data center manages files (uploads, downloads, etc.).
662
663    Beside providing the bare paths needed to keep files, it also
664    provides some helpers to put results of batch processing into
665    well-defined final locations (with well-defined filenames).
666
667    The main use-case is managing of site-related files, i.e. files
668    for import, export etc.
669
670    DataCenters are _not_ meant as storages for object-specific files
671    like passport photographs and similar.
672
673    It is up to the datacenter implementation how to organize data
674    (paths) inside its storage path.
675    """
676    storage = schema.Bytes(
677        title = u'Path to directory where everything is kept.'
678        )
679
680    deleted_path = schema.Bytes(
681        title = u'Path were data about deleted objects should be stored.'
682        )
683
684    def getPendingFiles(sort='name'):
685        """Get a list of files stored in `storage` sorted by basename.
686        """
687
688    def getFinishedFiles():
689        """Get a list of files stored in `finished` subfolder of `storage`.
690        """
691
692    def setStoragePath(path, move=False, overwrite=False):
693        """Set the path where to store files.
694
695        If `move` is True, move over files from the current location
696        to the new one.
697
698        If `overwrite` is also True, overwrite any already existing
699        files of same name in target location.
700
701        Triggers a DataCenterStorageMovedEvent.
702        """
703
704    def distProcessedFiles(successful, source_path, finished_file,
705                           pending_file, mode='create', move_orig=True):
706        """Distribute processed files over final locations.
707        """
708
709
710class IDataCenterFile(Interface):
711    """A data center file.
712    """
713
714    name = schema.TextLine(
715        title = u'Filename')
716
717    size = schema.TextLine(
718        title = u'Human readable file size')
719
720    uploaddate = schema.TextLine(
721        title = u'Human readable upload datetime')
722
723    lines = schema.Int(
724        title = u'Number of lines in file')
725
726    def getDate():
727        """Get creation timestamp from file in human readable form.
728        """
729
730    def getSize():
731        """Get human readable size of file.
732        """
733
734    def getLinesNumber():
735        """Get number of lines of file.
736        """
737
738class IDataCenterStorageMovedEvent(IObjectEvent):
739    """Emitted, when the storage of a datacenter changes.
740    """
741
742class IObjectUpgradeEvent(IObjectEvent):
743    """Can be fired, when an object shall be upgraded.
744    """
745
746class ILocalRoleSetEvent(IObjectEvent):
747    """A local role was granted/revoked for a principal on an object.
748    """
749    role_id = Attribute(
750        "The role id that was set.")
751    principal_id = Attribute(
752        "The principal id for which the role was granted/revoked.")
753    granted = Attribute(
754        "Boolean. If false, then the role was revoked.")
755
756class IQueryResultItem(Interface):
757    """An item in a search result.
758    """
759    url = schema.TextLine(
760        title = u'URL that links to the found item')
761    title = schema.TextLine(
762        title = u'Title displayed in search results.')
763    description = schema.Text(
764        title = u'Longer description of the item found.')
765
766class IKofaPluggable(Interface):
767    """A component that might be plugged into a Kofa Kofa app.
768
769    Components implementing this interface are referred to as
770    'plugins'. They are normally called when a new
771    :class:`waeup.kofa.app.University` instance is created.
772
773    Plugins can setup and update parts of the central site without the
774    site object (normally a :class:`waeup.kofa.app.University` object)
775    needing to know about that parts. The site simply collects all
776    available plugins, calls them and the plugins care for their
777    respective subarea like the applicants area or the datacenter
778    area.
779
780    Currently we have no mechanism to define an order of plugins. A
781    plugin should therefore make no assumptions about the state of the
782    site or other plugins being run before and instead do appropriate
783    checks if necessary.
784
785    Updates can be triggered for instance by the respective form in
786    the site configuration. You normally do updates when the
787    underlying software changed.
788    """
789    def setup(site, name, logger):
790        """Create an instance of the plugin.
791
792        The method is meant to be called by the central app (site)
793        when it is created.
794
795        `site`:
796           The site that requests a setup.
797
798        `name`:
799           The name under which the plugin was registered (utility name).
800
801        `logger`:
802           A standard Python logger for the plugins use.
803        """
804
805    def update(site, name, logger):
806        """Method to update an already existing plugin.
807
808        This might be called by a site when something serious
809        changes. It is a poor-man replacement for Zope generations
810        (but probably more comprehensive and better understandable).
811
812        `site`:
813           The site that requests an update.
814
815        `name`:
816           The name under which the plugin was registered (utility name).
817
818        `logger`:
819           A standard Python logger for the plugins use.
820        """
821
822class IAuthPluginUtility(Interface):
823    """A component that cares for authentication setup at site creation.
824
825    Utilities providing this interface are looked up when a Pluggable
826    Authentication Utility (PAU) for any
827    :class:`waeup.kofa.app.University` instance is created and put
828    into ZODB.
829
830    The setup-code then calls the `register` method of the utility and
831    expects a modified (or unmodified) version of the PAU back.
832
833    This allows to define any authentication setup modifications by
834    submodules or third-party modules/packages.
835    """
836
837    def register(pau):
838        """Register any plugins wanted to be in the PAU.
839        """
840
841    def unregister(pau):
842        """Unregister any plugins not wanted to be in the PAU.
843        """
844
845class IObjectConverter(Interface):
846    """Object converters are available as simple adapters, adapting
847       interfaces (not regular instances).
848
849    """
850
851    def fromStringDict(self, data_dict, context, form_fields=None):
852        """Convert values in `data_dict`.
853
854        Converts data in `data_dict` into real values based on
855        `context` and `form_fields`.
856
857        `data_dict` is a mapping (dict) from field names to values
858        represented as strings.
859
860        The fields (keys) to convert can be given in optional
861        `form_fields`. If given, form_fields should be an instance of
862        :class:`zope.formlib.form.Fields`. Suitable instances are for
863        example created by :class:`grok.AutoFields`.
864
865        If no `form_fields` are given, a default is computed from the
866        associated interface.
867
868        The `context` can be an existing object (implementing the
869        associated interface) or a factory name. If it is a string, we
870        try to create an object using
871        :func:`zope.component.createObject`.
872
873        Returns a tuple ``(<FIELD_ERRORS>, <INVARIANT_ERRORS>,
874        <DATA_DICT>)`` where
875
876        ``<FIELD_ERRORS>``
877           is a list of tuples ``(<FIELD_NAME>, <ERROR>)`` for each
878           error that happened when validating the input data in
879           `data_dict`
880
881        ``<INVARIANT_ERRORS>``
882           is a list of invariant errors concerning several fields
883
884        ``<DATA_DICT>``
885           is a dict with the values from input dict converted.
886
887        If errors happen, i.e. the error lists are not empty, always
888        an empty ``<DATA_DICT>`` is returned.
889
890        If ``<DATA_DICT>` is non-empty, there were no errors.
891        """
892
893class IFieldConverter(Interface):
894    def request_data(name, value, schema_field, prefix='', mode='create'):
895        """Create a dict with key-value mapping as created by a request.
896
897        `name` and `value` are expected to be parsed from CSV or a
898        similar input and represent an attribute to be set to a
899        representation of value.
900
901        `mode` gives the mode of import.
902
903        :meth:`update_request_data` is then requested to turn this
904        name and value into vars as they would be sent by a regular
905        form submit. This means we do not create the real values to be
906        set but we only define the values that would be sent in a
907        browser request to request the creation of those values.
908
909        The returned dict should contain names and values of a faked
910        browser request for the given `schema_field`.
911
912        Field converters are normally registered as adapters to some
913        specific zope.schema field.
914        """
915
916class IObjectHistory(Interface):
917
918    messages = schema.List(
919        title = u'List of messages stored',
920        required = True,
921        )
922
923    def addMessage(message):
924        """Add a message.
925        """
926
927class IKofaWorkflowInfo(IWorkflowInfo):
928    """A :class:`hurry.workflow.workflow.WorkflowInfo` with additional
929       methods for convenience.
930    """
931    def getManualTransitions():
932        """Get allowed manual transitions.
933
934        Get a sorted list of tuples containing the `transition_id` and
935        `title` of each allowed transition.
936        """
937
938class ISiteLoggers(Interface):
939
940    loggers = Attribute("A list or generator of registered KofaLoggers")
941
942    def register(name, filename=None, site=None, **options):
943        """Register a logger `name` which logs to `filename`.
944
945        If `filename` is not given, logfile will be `name` with
946        ``.log`` as filename extension.
947        """
948
949    def unregister(name):
950        """Unregister a once registered logger.
951        """
952
953class ILogger(Interface):
954    """A logger cares for setup, update and restarting of a Python logger.
955    """
956
957    logger = Attribute("""A :class:`logging.Logger` instance""")
958
959
960    def __init__(name, filename=None, site=None, **options):
961        """Create a Kofa logger instance.
962        """
963
964    def setup():
965        """Create a Python :class:`logging.Logger` instance.
966
967        The created logger is based on the params given by constructor.
968        """
969
970    def update(**options):
971        """Update the logger.
972
973        Updates the logger respecting modified `options` and changed
974        paths.
975        """
976
977class ILoggerCollector(Interface):
978
979    def getLoggers(site):
980        """Return all loggers registered for `site`.
981        """
982
983    def registerLogger(site, logging_component):
984        """Register a logging component residing in `site`.
985        """
986
987    def unregisterLogger(site, logging_component):
988        """Unregister a logger.
989        """
990
991#
992# External File Storage and relatives
993#
994class IFileStoreNameChooser(INameChooser):
995    """See zope.container.interfaces.INameChooser for base methods.
996    """
997    def checkName(name, attr=None):
998        """Check whether an object name is valid.
999
1000        Raises a user error if the name is not valid.
1001        """
1002
1003    def chooseName(name, attr=None):
1004        """Choose a unique valid file id for the object.
1005
1006        The given name may be taken into account when choosing the
1007        name (file id).
1008
1009        chooseName is expected to always choose a valid file id (that
1010        would pass the checkName test) and never raise an error.
1011
1012        If `attr` is not ``None`` it might been taken into account as
1013        well when generating the file id. Usual behaviour is to
1014        interpret `attr` as a hint for what type of file for a given
1015        context should be stored if there are several types
1016        possible. For instance for a certain student some file could
1017        be the connected passport photograph or some certificate scan
1018        or whatever. Each of them has to be stored in a different
1019        location so setting `attr` to a sensible value should give
1020        different file ids returned.
1021        """
1022
1023class IExtFileStore(IFileRetrieval):
1024    """A file storage that stores files in filesystem (not as blobs).
1025    """
1026    root = schema.TextLine(
1027        title = u'Root path of file store.',
1028        )
1029
1030    def getFile(file_id):
1031        """Get raw file data stored under file with `file_id`.
1032
1033        Returns a file descriptor open for reading or ``None`` if the
1034        file cannot be found.
1035        """
1036
1037    def getFileByContext(context, attr=None):
1038        """Get raw file data stored for the given context.
1039
1040        Returns a file descriptor open for reading or ``None`` if no
1041        such file can be found.
1042
1043        Both, `context` and `attr` might be used to find (`context`)
1044        and feed (`attr`) an appropriate file name chooser.
1045
1046        This is a convenience method.
1047        """
1048
1049    def deleteFile(file_id):
1050        """Delete file stored under `file_id`.
1051
1052        Remove file from filestore so, that it is not available
1053        anymore on next call to getFile for the same file_id.
1054
1055        Should not complain if no such file exists.
1056        """
1057
1058    def deleteFileByContext(context, attr=None):
1059        """Delete file for given `context` and `attr`.
1060
1061        Both, `context` and `attr` might be used to find (`context`)
1062        and feed (`attr`) an appropriate file name chooser.
1063
1064        This is a convenience method.
1065        """
1066
1067    def createFile(filename, f):
1068        """Create file given by f with filename `filename`
1069
1070        Returns a hurry.file.File-based object.
1071        """
1072
1073class IFileStoreHandler(Interface):
1074    """Filestore handlers handle specific files for file stores.
1075
1076    If a file to store/get provides a specific filename, a file store
1077    looks up special handlers for that type of file.
1078
1079    """
1080    def pathFromFileID(store, root, filename):
1081        """Turn file id into path to store.
1082
1083        Returned path should be absolute.
1084        """
1085
1086    def createFile(store, root, filename, file_id, file):
1087        """Return some hurry.file based on `store` and `file_id`.
1088
1089        Some kind of callback method called by file stores to create
1090        file objects from file_id.
1091
1092        Returns a tuple ``(raw_file, path, file_like_obj)`` where the
1093        ``file_like_obj`` should be a HurryFile, a KofaImageFile or
1094        similar. ``raw_file`` is the (maybe changed) input file and
1095        ``path`` the relative internal path to store the file at.
1096
1097        Please make sure the ``raw_file`` is opened for reading and
1098        the file descriptor set at position 0 when returned.
1099
1100        This method also gets the raw input file object that is about
1101        to be stored and is expected to raise any exceptions if some
1102        kind of validation or similar fails.
1103        """
1104
1105class IPDF(Interface):
1106    """A PDF representation of some context.
1107    """
1108
1109    def __call__(view=None, note=None):
1110        """Create a bytestream representing a PDF from context.
1111
1112        If `view` is passed in additional infos might be rendered into
1113        the document.
1114
1115        `note` is optional HTML rendered at bottom of the created
1116        PDF. Please consider the limited reportlab support for HTML,
1117        but using font-tags and friends you certainly can get the
1118        desired look.
1119        """
1120
1121class IMailService(Interface):
1122    """A mail service.
1123    """
1124
1125    def __call__():
1126        """Get the default mail delivery.
1127        """
1128
1129
1130class IDataCenterConfig(Interface):
1131    path = Path(
1132        title = u'Path',
1133        description = u"Directory where the datacenter should store "
1134                      u"files by default (adjustable in web UI).",
1135        required = True,
1136        )
1137
1138#
1139# Asynchronous job handling and related
1140#
1141class IJobManager(IKofaObject):
1142    """A manager for asynchronous running jobs (tasks).
1143    """
1144    def put(job, site=None):
1145        """Put a job into task queue.
1146
1147        If no `site` is given, queue job in context of current local
1148        site.
1149
1150        Returns a job_id to identify the put job. This job_id is
1151        needed for further references to the job.
1152        """
1153
1154    def jobs(site=None):
1155        """Get an iterable of jobs stored.
1156        """
1157
1158    def get(job_id, site=None):
1159        """Get the job with id `job_id`.
1160
1161        For the `site` parameter see :meth:`put`.
1162        """
1163
1164    def remove(job_id, site=None):
1165        """Remove job with `job_id` from stored jobs.
1166        """
1167
1168    def start_test_job(site=None):
1169        """Start a test job.
1170        """
1171
1172class IProgressable(Interface):
1173    """A component that can indicate its progress status.
1174    """
1175    percent = schema.Float(
1176        title = u'Percent of job done already.',
1177        )
1178
1179class IJobContainer(IContainer):
1180    """A job container contains IJob objects.
1181    """
1182
1183class IExportJob(zc.async.interfaces.IJob):
1184    def __init__(site, exporter_name):
1185        pass
1186
1187    finished = schema.Bool(
1188        title = u'`True` if the job finished.`',
1189        default = False,
1190        )
1191
1192    failed = schema.Bool(
1193        title = u"`True` iff the job finished and didn't provide a file.",
1194        default = None,
1195        )
1196
1197class IExportJobContainer(IKofaObject):
1198    """A component that contains (maybe virtually) export jobs.
1199    """
1200    def start_export_job(exporter_name, user_id, *args, **kwargs):
1201        """Start asynchronous export job.
1202
1203        `exporter_name` is the name of an exporter utility to be used.
1204
1205        `user_id` is the ID of the user that triggers the export.
1206
1207        `args` positional arguments passed to the export job created.
1208
1209        `kwargs` keyword arguments passed to the export job.
1210
1211        The job_id is stored along with exporter name and user id in a
1212        persistent list.
1213
1214        Returns the job ID of the job started.
1215        """
1216
1217    def get_running_export_jobs(user_id=None):
1218        """Get export jobs for user with `user_id` as list of tuples.
1219
1220        Each tuples holds ``<job_id>, <exporter_name>, <user_id>`` in
1221        that order. The ``<exporter_name>`` is the utility name of the
1222        used exporter.
1223
1224        If `user_id` is ``None``, all running jobs are returned.
1225        """
1226
1227    def get_export_jobs_status(user_id=None):
1228        """Get running/completed export jobs for `user_id` as list of tuples.
1229
1230        Each tuple holds ``<raw status>, <status translated>,
1231        <exporter title>`` in that order, where ``<status
1232        translated>`` and ``<exporter title>`` are translated strings
1233        representing the status of the job and the human readable
1234        title of the exporter used.
1235        """
1236
1237    def delete_export_entry(entry):
1238        """Delete the export denoted by `entry`.
1239
1240        Removes `entry` from the local `running_exports` list and also
1241        removes the regarding job via the local job manager.
1242
1243        `entry` is a tuple ``(<job id>, <exporter name>, <user id>)``
1244        as created by :meth:`start_export_job` or returned by
1245        :meth:`get_running_export_jobs`.
1246        """
1247
1248    def entry_from_job_id(job_id):
1249        """Get entry tuple for `job_id`.
1250
1251        Returns ``None`` if no such entry can be found.
1252        """
1253
1254class IExportContainerFinder(Interface):
1255    """A finder for the central export container.
1256    """
1257    def __call__():
1258        """Return the currently used global or site-wide IExportContainer.
1259        """
1260
1261class IFilteredQuery(IKofaObject):
1262    """A query for objects.
1263    """
1264
1265    defaults = schema.Dict(
1266        title = u'Default Parameters',
1267        required = True,
1268        )
1269
1270    def __init__(**parameters):
1271        """Instantiate a filtered query by passing in parameters.
1272        """
1273
1274    def query():
1275        """Get an iterable of objects denoted by the set parameters.
1276
1277        The search should be applied to objects inside current
1278        site. It's the caller's duty to set the correct site before.
1279
1280        Result can be any iterable like a catalog result set, a list,
1281        or similar.
1282        """
1283
1284class IFilteredCatalogQuery(IFilteredQuery):
1285    """A catalog-based query for objects.
1286    """
1287
1288    cat_name = schema.TextLine(
1289        title = u'Registered name of the catalog to search.',
1290        required = True,
1291        )
1292
1293    def query_catalog(catalog):
1294        """Query catalog with the parameters passed to constructor.
1295        """
Note: See TracBrowser for help on using the repository browser.