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

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

All fees must be float not int.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 30.1 KB
Line 
1## $Id: interfaces.py 7927 2012-03-20 14:20:04Z 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'Importer 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 = True,
428        )
429
430    roles = schema.List(
431        title = _(u'Portal roles'),
432        value_type = schema.Choice(source=RoleSource()))
433
434class IPasswordValidator(Interface):
435    """A password validator utility.
436    """
437
438    def validate_password(password, password_repeat):
439        """Validates a password by comparing it with
440        control password and checking some other requirements.
441        """
442
443
444class IUsersContainer(IKofaObject):
445    """A container for users (principals).
446
447    These users are used for authentication purposes.
448    """
449
450    def addUser(name, password, title=None, description=None):
451        """Add a user.
452        """
453
454    def delUser(name):
455        """Delete a user if it exists.
456        """
457
458class ILocalRolesAssignable(Interface):
459    """The local roles assignable to an object.
460    """
461    def __call__():
462        """Returns a list of dicts.
463
464        Each dict contains a ``name`` referring to the role assignable
465        for the specified object and a `title` to describe the range
466        of users to which this role can be assigned.
467        """
468
469class IConfigurationContainer(IKofaObject):
470    """A container for session configuration objects.
471    """
472
473    name = schema.TextLine(
474        title = _(u'Name of University'),
475        default = _(u'Sample University'),
476        required = True,
477        )
478
479    acronym = schema.TextLine(
480        title = _(u'Abbreviated Title of University'),
481        default = u'WAeUP.Kofa',
482        required = True,
483        )
484
485    skin = schema.Choice(
486        title = _(u'Skin'),
487        default = u'gray waeup theme',
488        vocabulary = 'waeup.kofa.browser.theming.ThemesVocabulary',
489        required = True,
490        )
491
492    frontpage = schema.Text(
493        title = _(u'Content in reST format'),
494        required = False,
495        default = default_frontpage,
496        )
497
498    frontpage_dict = schema.Dict(
499        title = u'Content as language dictionary with values in html format',
500        required = False,
501        default = {},
502        )
503
504    accommodation_session = schema.Choice(
505        title = _(u'Accommodation Booking Session'),
506        source = academic_sessions_vocab,
507        default = datetime.now().year,
508        required = False,
509        readonly = False,
510        )
511
512    accommodation_states = schema.List(
513        title = _(u'Allowed States for Accommodation Booking'),
514        value_type = schema.Choice(
515            vocabulary = registration_states_vocab,
516            ),
517        default = [],
518        )
519
520    name_admin = schema.TextLine(
521        title = _(u'Name of Administrator'),
522        default = u'Administrator',
523        required = False,
524        )
525
526    email_admin = schema.ASCIILine(
527        title = _(u'Email Address of Administrator'),
528        default = 'contact@waeup.org',
529        required = False,
530        constraint=validate_email,
531        )
532
533    email_subject = schema.TextLine(
534        title = _(u'Subject of Email to Administrator'),
535        default = _(u'Kofa Contact'),
536        required = False,
537        )
538
539    smtp_mailer = schema.Choice(
540        title = _(u'SMTP mailer to use when sending mail'),
541        vocabulary = 'Mail Delivery Names',
542        default = 'No email service',
543        required = True,
544        )
545
546    captcha = schema.Choice(
547        title = _(u'Captcha used for public registration pages'),
548        source = CaptchaSource(),
549        default = u'No captcha',
550        required = True,
551        )
552
553    carry_over = schema.Bool(
554        title = _(u'Carry-over Course Registration'),
555        default = False,
556        )
557
558class ISessionConfiguration(IKofaObject):
559    """A session configuration object.
560    """
561
562    academic_session = schema.Choice(
563        title = _(u'Academic Session'),
564        source = academic_sessions_vocab,
565        default = None,
566        required = True,
567        readonly = True,
568        )
569
570    school_fee_base = schema.Float(
571        title = _(u'School Fee'),
572        default = 0.0,
573        )
574
575    surcharge_1 = schema.Float(
576        title = _(u'Surcharge Portal Provider'),
577        default = 0.0,
578        required = False,
579        )
580
581    surcharge_2 = schema.Float(
582        title = _(u'Surcharge Payment Gateway Provider'),
583        default = 0.0,
584        required = False,
585        )
586
587    surcharge_3 = schema.Float(
588        title = _(u'Surcharge 3'),
589        default = 0.0,
590        required = False,
591        )
592
593    clearance_fee = schema.Float(
594        title = _(u'Clearance Fee'),
595        default = 0.0,
596        required = False,
597        )
598
599    booking_fee = schema.Float(
600        title = _(u'Booking Fee'),
601        default = 0.0,
602        required = False,
603        )
604
605    acceptance_fee = schema.Float(
606        title = _(u'Acceptance Fee'),
607        default = 0.0,
608        required = False,
609        )
610
611    def getSessionString():
612        """Returns the session string from the vocabulary.
613        """
614
615
616class ISessionConfigurationAdd(ISessionConfiguration):
617    """A session configuration object in add mode.
618    """
619
620    academic_session = schema.Choice(
621        title = _(u'Academic Session'),
622        source = academic_sessions_vocab,
623        default = None,
624        required = True,
625        readonly = False,
626        )
627
628ISessionConfigurationAdd['academic_session'].order =  ISessionConfiguration[
629    'academic_session'].order
630
631class IDataCenter(IKofaObject):
632    """A data center.
633
634    TODO : declare methods, at least those needed by pages.
635    """
636    pass
637
638class IDataCenterFile(Interface):
639    """A data center file.
640    """
641
642    name = schema.TextLine(
643        title = u'Filename')
644
645    size = schema.TextLine(
646        title = u'Human readable file size')
647
648    uploaddate = schema.TextLine(
649        title = u'Human readable upload datetime')
650
651    lines = schema.Int(
652        title = u'Number of lines in file')
653
654    def getDate():
655        """Get creation timestamp from file in human readable form.
656        """
657
658    def getSize():
659        """Get human readable size of file.
660        """
661
662    def getLinesNumber():
663        """Get number of lines of file.
664        """
665
666class IDataCenterStorageMovedEvent(IObjectEvent):
667    """Emitted, when the storage of a datacenter changes.
668    """
669
670class IObjectUpgradeEvent(IObjectEvent):
671    """Can be fired, when an object shall be upgraded.
672    """
673
674class ILocalRoleSetEvent(IObjectEvent):
675    """A local role was granted/revoked for a principal on an object.
676    """
677    role_id = Attribute(
678        "The role id that was set.")
679    principal_id = Attribute(
680        "The principal id for which the role was granted/revoked.")
681    granted = Attribute(
682        "Boolean. If false, then the role was revoked.")
683
684class IQueryResultItem(Interface):
685    """An item in a search result.
686    """
687    url = schema.TextLine(
688        title = u'URL that links to the found item')
689    title = schema.TextLine(
690        title = u'Title displayed in search results.')
691    description = schema.Text(
692        title = u'Longer description of the item found.')
693
694class IKofaPluggable(Interface):
695    """A component that might be plugged into a Kofa Kofa app.
696
697    Components implementing this interface are referred to as
698    'plugins'. They are normally called when a new
699    :class:`waeup.kofa.app.University` instance is created.
700
701    Plugins can setup and update parts of the central site without the
702    site object (normally a :class:`waeup.kofa.app.University` object)
703    needing to know about that parts. The site simply collects all
704    available plugins, calls them and the plugins care for their
705    respective subarea like the applicants area or the datacenter
706    area.
707
708    Currently we have no mechanism to define an order of plugins. A
709    plugin should therefore make no assumptions about the state of the
710    site or other plugins being run before and instead do appropriate
711    checks if necessary.
712
713    Updates can be triggered for instance by the respective form in
714    the site configuration. You normally do updates when the
715    underlying software changed.
716    """
717    def setup(site, name, logger):
718        """Create an instance of the plugin.
719
720        The method is meant to be called by the central app (site)
721        when it is created.
722
723        `site`:
724           The site that requests a setup.
725
726        `name`:
727           The name under which the plugin was registered (utility name).
728
729        `logger`:
730           A standard Python logger for the plugins use.
731        """
732
733    def update(site, name, logger):
734        """Method to update an already existing plugin.
735
736        This might be called by a site when something serious
737        changes. It is a poor-man replacement for Zope generations
738        (but probably more comprehensive and better understandable).
739
740        `site`:
741           The site that requests an update.
742
743        `name`:
744           The name under which the plugin was registered (utility name).
745
746        `logger`:
747           A standard Python logger for the plugins use.
748        """
749
750class IAuthPluginUtility(Interface):
751    """A component that cares for authentication setup at site creation.
752
753    Utilities providing this interface are looked up when a Pluggable
754    Authentication Utility (PAU) for any
755    :class:`waeup.kofa.app.University` instance is created and put
756    into ZODB.
757
758    The setup-code then calls the `register` method of the utility and
759    expects a modified (or unmodified) version of the PAU back.
760
761    This allows to define any authentication setup modifications by
762    submodules or third-party modules/packages.
763    """
764
765    def register(pau):
766        """Register any plugins wanted to be in the PAU.
767        """
768
769    def unregister(pau):
770        """Unregister any plugins not wanted to be in the PAU.
771        """
772
773class IObjectConverter(Interface):
774    """Object converters are available as simple adapters, adapting
775       interfaces (not regular instances).
776
777    """
778
779    def fromStringDict(self, data_dict, context, form_fields=None):
780        """Convert values in `data_dict`.
781
782        Converts data in `data_dict` into real values based on
783        `context` and `form_fields`.
784
785        `data_dict` is a mapping (dict) from field names to values
786        represented as strings.
787
788        The fields (keys) to convert can be given in optional
789        `form_fields`. If given, form_fields should be an instance of
790        :class:`zope.formlib.form.Fields`. Suitable instances are for
791        example created by :class:`grok.AutoFields`.
792
793        If no `form_fields` are given, a default is computed from the
794        associated interface.
795
796        The `context` can be an existing object (implementing the
797        associated interface) or a factory name. If it is a string, we
798        try to create an object using
799        :func:`zope.component.createObject`.
800
801        Returns a tuple ``(<FIELD_ERRORS>, <INVARIANT_ERRORS>,
802        <DATA_DICT>)`` where
803
804        ``<FIELD_ERRORS>``
805           is a list of tuples ``(<FIELD_NAME>, <ERROR>)`` for each
806           error that happened when validating the input data in
807           `data_dict`
808
809        ``<INVARIANT_ERRORS>``
810           is a list of invariant errors concerning several fields
811
812        ``<DATA_DICT>``
813           is a dict with the values from input dict converted.
814
815        If errors happen, i.e. the error lists are not empty, always
816        an empty ``<DATA_DICT>`` is returned.
817
818        If ``<DATA_DICT>` is non-empty, there were no errors.
819        """
820
821class IObjectHistory(Interface):
822
823    messages = schema.List(
824        title = u'List of messages stored',
825        required = True,
826        )
827
828    def addMessage(message):
829        """Add a message.
830        """
831
832class IKofaWorkflowInfo(IWorkflowInfo):
833    """A :class:`hurry.workflow.workflow.WorkflowInfo` with additional
834       methods for convenience.
835    """
836    def getManualTransitions():
837        """Get allowed manual transitions.
838
839        Get a sorted list of tuples containing the `transition_id` and
840        `title` of each allowed transition.
841        """
842
843class ISiteLoggers(Interface):
844
845    loggers = Attribute("A list or generator of registered KofaLoggers")
846
847    def register(name, filename=None, site=None, **options):
848        """Register a logger `name` which logs to `filename`.
849
850        If `filename` is not given, logfile will be `name` with
851        ``.log`` as filename extension.
852        """
853
854    def unregister(name):
855        """Unregister a once registered logger.
856        """
857
858class ILogger(Interface):
859    """A logger cares for setup, update and restarting of a Python logger.
860    """
861
862    logger = Attribute("""A :class:`logging.Logger` instance""")
863
864
865    def __init__(name, filename=None, site=None, **options):
866        """Create a Kofa logger instance.
867        """
868
869    def setup():
870        """Create a Python :class:`logging.Logger` instance.
871
872        The created logger is based on the params given by constructor.
873        """
874
875    def update(**options):
876        """Update the logger.
877
878        Updates the logger respecting modified `options` and changed
879        paths.
880        """
881
882class ILoggerCollector(Interface):
883
884    def getLoggers(site):
885        """Return all loggers registered for `site`.
886        """
887
888    def registerLogger(site, logging_component):
889        """Register a logging component residing in `site`.
890        """
891
892    def unregisterLogger(site, logging_component):
893        """Unregister a logger.
894        """
895
896#
897# External File Storage and relatives
898#
899class IFileStoreNameChooser(INameChooser):
900    """See zope.container.interfaces.INameChooser for base methods.
901    """
902    def checkName(name, attr=None):
903        """Check whether an object name is valid.
904
905        Raises a user error if the name is not valid.
906        """
907
908    def chooseName(name, attr=None):
909        """Choose a unique valid file id for the object.
910
911        The given name may be taken into account when choosing the
912        name (file id).
913
914        chooseName is expected to always choose a valid file id (that
915        would pass the checkName test) and never raise an error.
916
917        If `attr` is not ``None`` it might been taken into account as
918        well when generating the file id. Usual behaviour is to
919        interpret `attr` as a hint for what type of file for a given
920        context should be stored if there are several types
921        possible. For instance for a certain student some file could
922        be the connected passport photograph or some certificate scan
923        or whatever. Each of them has to be stored in a different
924        location so setting `attr` to a sensible value should give
925        different file ids returned.
926        """
927
928class IExtFileStore(IFileRetrieval):
929    """A file storage that stores files in filesystem (not as blobs).
930    """
931    root = schema.TextLine(
932        title = u'Root path of file store.',
933        )
934
935    def getFile(file_id):
936        """Get raw file data stored under file with `file_id`.
937
938        Returns a file descriptor open for reading or ``None`` if the
939        file cannot be found.
940        """
941
942    def getFileByContext(context, attr=None):
943        """Get raw file data stored for the given context.
944
945        Returns a file descriptor open for reading or ``None`` if no
946        such file can be found.
947
948        Both, `context` and `attr` might be used to find (`context`)
949        and feed (`attr`) an appropriate file name chooser.
950
951        This is a convenience method.
952        """
953
954    def deleteFile(file_id):
955        """Delete file stored under `file_id`.
956
957        Remove file from filestore so, that it is not available
958        anymore on next call to getFile for the same file_id.
959
960        Should not complain if no such file exists.
961        """
962
963    def deleteFileByContext(context, attr=None):
964        """Delete file for given `context` and `attr`.
965
966        Both, `context` and `attr` might be used to find (`context`)
967        and feed (`attr`) an appropriate file name chooser.
968
969        This is a convenience method.
970        """
971
972    def createFile(filename, f):
973        """Create file given by f with filename `filename`
974
975        Returns a hurry.file.File-based object.
976        """
977
978class IFileStoreHandler(Interface):
979    """Filestore handlers handle specific files for file stores.
980
981    If a file to store/get provides a specific filename, a file store
982    looks up special handlers for that type of file.
983
984    """
985    def pathFromFileID(store, root, filename):
986        """Turn file id into path to store.
987
988        Returned path should be absolute.
989        """
990
991    def createFile(store, root, filename, file_id, file):
992        """Return some hurry.file based on `store` and `file_id`.
993
994        Some kind of callback method called by file stores to create
995        file objects from file_id.
996
997        Returns a tuple ``(raw_file, path, file_like_obj)`` where the
998        ``file_like_obj`` should be a HurryFile, a KofaImageFile or
999        similar. ``raw_file`` is the (maybe changed) input file and
1000        ``path`` the relative internal path to store the file at.
1001
1002        Please make sure the ``raw_file`` is opened for reading and
1003        the file descriptor set at position 0 when returned.
1004
1005        This method also gets the raw input file object that is about
1006        to be stored and is expected to raise any exceptions if some
1007        kind of validation or similar fails.
1008        """
1009
1010class IPDF(Interface):
1011    """A PDF representation of some context.
1012    """
1013
1014    def __call__(view=None):
1015        """Create a bytestream representing a PDF from context.
1016
1017        If `view` is passed in additional infos might be rendered into
1018        the document.
1019        """
1020
1021class IMailService(Interface):
1022    """A mail service.
1023    """
1024
1025    def __call__():
1026        """Get the default mail delivery.
1027        """
1028
1029from zope.configuration.fields import Path
1030class IDataCenterConfig(Interface):
1031    path = Path(
1032        title = u'Path',
1033        description = u"Directory where the datacenter should store "
1034                      u"files by default (adjustable in web UI).",
1035        required = True,
1036        )
Note: See TracBrowser for help on using the repository browser.