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

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

Add public_name to IKofaPrincipalInfo and IKofaPrincipal.

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