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

Last change on this file since 8142 was 8079, checked in by Henrik Bettermann, 13 years ago

Local roles are not required.

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