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

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

Give access to processed (finished) import files.

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