source: main/waeup.ikoba/trunk/src/waeup/ikoba/interfaces.py @ 11962

Last change on this file since 11962 was 11958, checked in by Henrik Bettermann, 10 years ago

Add components for customer management. Some tests are still missing.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 39.3 KB
Line 
1## $Id: interfaces.py 11958 2014-11-14 22:32:42Z henrik $
2##
3## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
4## This program is free software; you can redistribute it and/or modify
5## it under the terms of the GNU General Public License as published by
6## the Free Software Foundation; either version 2 of the License, or
7## (at your option) any later version.
8##
9## This program is distributed in the hope that it will be useful,
10## but WITHOUT ANY WARRANTY; without even the implied warranty of
11## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12## GNU General Public License for more details.
13##
14## You should have received a copy of the GNU General Public License
15## along with this program; if not, write to the Free Software
16## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17##
18import os
19import re
20import codecs
21import zc.async.interfaces
22import zope.i18nmessageid
23from datetime import datetime
24from hurry.file.interfaces import IFileRetrieval
25from hurry.workflow.interfaces import IWorkflowInfo
26from zc.sourcefactory.basic import BasicSourceFactory
27from zope import schema
28from zope.pluggableauth.interfaces import IPrincipalInfo
29from zope.security.interfaces import IGroupClosureAwarePrincipal as IPrincipal
30from zope.component import getUtility
31from zope.component.interfaces import IObjectEvent
32from zope.configuration.fields import Path
33from zope.container.interfaces import INameChooser, IContainer
34from zope.interface import Interface, Attribute
35from zope.schema.interfaces import IObject
36from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
37from waeup.ikoba.schema import PhoneNumber
38from waeup.ikoba.sourcefactory import SmartBasicContextualSourceFactory
39
40_ = MessageFactory = zope.i18nmessageid.MessageFactory('waeup.ikoba')
41
42DELETION_MARKER = 'XXX'
43IGNORE_MARKER = '<IGNORE>'
44WAEUP_KEY = 'waeup.ikoba'
45VIRT_JOBS_CONTAINER_NAME = 'jobs'
46
47CREATED = 'created'
48ADMITTED = 'admitted'
49CLEARANCE = 'clearance started'
50REQUESTED = 'clearance requested'
51CLEARED = 'cleared'
52PAID = 'school fee paid'
53RETURNING = 'returning'
54REGISTERED = 'courses registered'
55VALIDATED = 'courses validated'
56GRADUATED = 'graduated'
57TRANSCRIPT = 'transcript requested'
58
59
60#: A dict giving job status as tuple (<STRING>, <TRANSLATED_STRING>),
61#: the latter for UI purposes.
62JOB_STATUS_MAP = {
63    zc.async.interfaces.NEW: ('new', _('new')),
64    zc.async.interfaces.COMPLETED: ('completed', _('completed')),
65    zc.async.interfaces.PENDING: ('pending', _('pending')),
66    zc.async.interfaces.ACTIVE: ('active', _('active')),
67    zc.async.interfaces.ASSIGNED: ('assigned', _('assigned')),
68    zc.async.interfaces.CALLBACKS: ('callbacks', _('callbacks')),
69    }
70
71#default_rest_frontpage = u'' + codecs.open(os.path.join(
72#        os.path.dirname(__file__), 'frontpage.rst'),
73#        encoding='utf-8', mode='rb').read()
74
75default_html_frontpage = u'' + codecs.open(os.path.join(
76        os.path.dirname(__file__), 'frontpage.html'),
77        encoding='utf-8', mode='rb').read()
78
79def SimpleIkobaVocabulary(*terms):
80    """A well-buildt vocabulary provides terms with a value, token and
81       title for each term
82    """
83    return SimpleVocabulary([
84            SimpleTerm(value, value, title) for title, value in terms])
85
86def application_sessions():
87    curr_year = datetime.now().year
88    year_range = range(1995, curr_year + 2)
89    return [('%s/%s' % (year,year+1), year) for year in year_range]
90
91application_sessions_vocab = SimpleIkobaVocabulary(*application_sessions())
92
93registration_states_vocab = SimpleIkobaVocabulary(
94    (_('created'), CREATED),
95    (_('admitted'), ADMITTED),
96    (_('clearance started'), CLEARANCE),
97    (_('clearance requested'), REQUESTED),
98    (_('cleared'), CLEARED),
99    (_('school fee paid'), PAID),
100    (_('courses registered'), REGISTERED),
101    (_('courses validated'), VALIDATED),
102    (_('returning'), RETURNING),
103    )
104
105class ContextualDictSourceFactoryBase(SmartBasicContextualSourceFactory):
106    """A base for contextual sources based on IkobaUtils dicts.
107
108    To create a real source, you have to set the `DICT_NAME` attribute
109    which should be the name of a dictionary in IkobaUtils.
110    """
111    def getValues(self, context):
112        utils = getUtility(IIkobaUtils)
113        sorted_items = sorted(getattr(utils, self.DICT_NAME).items(),
114                              key=lambda item: item[1])
115        return [item[0] for item in sorted_items]
116
117    def getToken(self, context, value):
118        return str(value)
119
120    def getTitle(self, context, value):
121        utils = getUtility(IIkobaUtils)
122        return getattr(utils, self.DICT_NAME)[value]
123
124class SubjectSource(BasicSourceFactory):
125    """A source for school subjects used in exam documentation.
126    """
127    def getValues(self):
128        subjects_dict = getUtility(IIkobaUtils).EXAM_SUBJECTS_DICT
129        return sorted(subjects_dict.keys())
130
131    def getTitle(self, value):
132        subjects_dict = getUtility(IIkobaUtils).EXAM_SUBJECTS_DICT
133        return "%s:" % subjects_dict[value]
134
135class GradeSource(BasicSourceFactory):
136    """A source for exam grades.
137    """
138    def getValues(self):
139        for entry in getUtility(IIkobaUtils).EXAM_GRADES:
140            yield entry[0]
141
142    def getTitle(self, value):
143        return dict(getUtility(IIkobaUtils).EXAM_GRADES)[value]
144
145# Define a validation method for email addresses
146class NotAnEmailAddress(schema.ValidationError):
147    __doc__ = u"Invalid email address"
148
149#: Regular expression to check email-address formats. As these can
150#: become rather complex (nearly everything is allowed by RFCs), we only
151#: forbid whitespaces, commas and dots following onto each other.
152check_email = re.compile(
153    r"^[^@\s,]+@[^@\.\s,]+(\.[^@\.\s,]+)*$").match
154
155def validate_email(value):
156    if not check_email(value):
157        raise NotAnEmailAddress(value)
158    return True
159
160# Define a validation method for international phone numbers
161class InvalidPhoneNumber(schema.ValidationError):
162    __doc__ = u"Invalid phone number"
163
164# represent format +NNN-NNNN-NNNN
165RE_INT_PHONE = re.compile(r"^\+?\d+\-\d+\-[\d\-]+$")
166
167def validate_phone(value):
168    if not RE_INT_PHONE.match(value):
169        raise InvalidPhoneNumber(value)
170    return True
171
172class FatalCSVError(Exception):
173    """Some row could not be processed.
174    """
175    pass
176
177class DuplicationError(Exception):
178    """An exception that can be raised when duplicates are found.
179
180    When raising :exc:`DuplicationError` you can, beside the usual
181    message, specify a list of objects which are duplicates. These
182    values can be used by catching code to print something helpful or
183    similar.
184    """
185    def __init__(self, msg, entries=[]):
186        self.msg = msg
187        self.entries = entries
188
189    def __str__(self):
190        return '%r' % self.msg
191
192class RoleSource(BasicSourceFactory):
193    """A source for site roles.
194    """
195    def getValues(self):
196        # late import: in interfaces we should not import local modules
197        from waeup.ikoba.permissions import get_waeup_role_names
198        return get_waeup_role_names()
199
200    def getTitle(self, value):
201        # late import: in interfaces we should not import local modules
202        from waeup.ikoba.permissions import get_all_roles
203        roles = dict(get_all_roles())
204        if value in roles.keys():
205            title = roles[value].title
206            if '.' in title:
207                title = title.split('.', 2)[1]
208        return title
209
210class CaptchaSource(BasicSourceFactory):
211    """A source for captchas.
212    """
213    def getValues(self):
214        captchas = ['No captcha', 'Testing captcha', 'ReCaptcha']
215        try:
216            # we have to 'try' because IConfiguration can only handle
217            # interfaces from w.k.interface.
218            from waeup.ikoba.browser.interfaces import ICaptchaManager
219        except:
220            return captchas
221        return sorted(getUtility(ICaptchaManager).getAvailCaptchas().keys())
222
223    def getTitle(self, value):
224        return value
225
226class IResultEntry(Interface):
227    """A school grade entry.
228    """
229    subject = schema.Choice(
230        title = _(u'Subject'),
231        source = SubjectSource(),
232        )
233    grade = schema.Choice(
234        title = _(u'Grade'),
235        source = GradeSource(),
236        )
237
238class IResultEntryField(IObject):
239    """A zope.schema-like field for usage in interfaces.
240
241    Marker interface to distuingish result entries from ordinary
242    object fields. Needed for registration of widgets.
243    """
244
245class IIkobaUtils(Interface):
246    """A collection of methods which are subject to customization.
247    """
248
249    PORTAL_LANGUAGE = Attribute("Dict of global language setting")
250    PREFERRED_LANGUAGES_DICT = Attribute("Dict of preferred languages")
251    EXAM_SUBJECTS_DICT = Attribute("Dict of examination subjects")
252    EXAM_GRADES = Attribute("Dict of examination grades")
253    INST_TYPES_DICT = Attribute("Dict if company types")
254    STUDY_MODES_DICT = Attribute("Dict of study modes")
255    APP_CATS_DICT = Attribute("Dict of application categories")
256    SEMESTER_DICT = Attribute("Dict of semesters or trimesters")
257    SYSTEM_MAX_LOAD = Attribute("Dict of maximum system loads.")
258
259    def sendContactForm(
260          from_name,from_addr,rcpt_name,rcpt_addr,
261          from_username,usertype,portal,body,subject):
262        """Send an email with data provided by forms.
263        """
264
265    def fullname(firstname,lastname,middlename):
266        """Full name constructor.
267        """
268
269    def sendCredentials(user, password, url_info, msg):
270        """Send credentials as email.
271
272        Input is the customer for which credentials are sent and the
273        password.
274
275        Returns True or False to indicate successful operation.
276        """
277
278    def genPassword(length, chars):
279        """Generate a random password.
280        """
281
282class IIkobaObject(Interface):
283    """A Ikoba object.
284
285    This is merely a marker interface.
286    """
287
288class ICompany(IIkobaObject):
289    """Representation of an company.
290    """
291
292
293class IIkobaContainer(IIkobaObject):
294    """A container for Ikoba objects.
295    """
296
297class IIkobaContained(IIkobaObject):
298    """An item contained in an IIkobaContainer.
299    """
300
301class ICSVExporter(Interface):
302    """A CSV file exporter for objects.
303    """
304    fields = Attribute("""List of fieldnames in resulting CSV""")
305
306    title = schema.TextLine(
307        title = u'Title',
308        description = u'Description to be displayed in selections.',
309        )
310    def mangle_value(value, name, obj):
311        """Mangle `value` extracted from `obj` or suobjects thereof.
312
313        This is called by export before actually writing to the result
314        file.
315        """
316
317    def get_filtered(site, **kw):
318        """Get datasets in `site` to be exported.
319
320        The set of data is specified by keywords, which might be
321        different for any implementaion of exporter.
322
323        Returns an iterable.
324        """
325
326    def export(iterable, filepath=None):
327        """Export iterables as rows in a CSV file.
328
329        If `filepath` is not given, a string with the data should be
330        returned.
331
332        What kind of iterables are acceptable depends on the specific
333        exporter implementation.
334        """
335
336    def export_all(site, filepath=None):
337        """Export all items in `site` as CSV file.
338
339        if `filepath` is not given, a string with the data should be
340        returned.
341        """
342
343    def export_filtered(site, filepath=None, **kw):
344        """Export those items in `site` specified by `args` and `kw`.
345
346        If `filepath` is not given, a string with the data should be
347        returned.
348
349        Which special keywords are supported is up to the respective
350        exporter.
351        """
352
353class IIkobaExporter(Interface):
354    """An exporter for objects.
355    """
356    def export(obj, filepath=None):
357        """Export by pickling.
358
359        Returns a file-like object containing a representation of `obj`.
360
361        This is done using `pickle`. If `filepath` is ``None``, a
362        `cStringIO` object is returned, that contains the saved data.
363        """
364
365class IIkobaXMLExporter(Interface):
366    """An XML exporter for objects.
367    """
368    def export(obj, filepath=None):
369        """Export as XML.
370
371        Returns an XML representation of `obj`.
372
373        If `filepath` is ``None``, a StringIO` object is returned,
374        that contains the transformed data.
375        """
376
377class IIkobaXMLImporter(Interface):
378    """An XML import for objects.
379    """
380    def doImport(filepath):
381        """Create Python object from XML.
382
383        Returns a Python object.
384        """
385
386class IBatchProcessor(Interface):
387    """A batch processor that handles mass-operations.
388    """
389    name = schema.TextLine(
390        title = _(u'Processor name')
391        )
392
393    def doImport(path, headerfields, mode='create', user='Unknown',
394                 logger=None, ignore_empty=True):
395        """Read data from ``path`` and update connected object.
396
397        `headerfields` is a list of headerfields as read from the file
398        to import.
399
400        `mode` gives the import mode to use (``'create'``,
401        ``'update'``, or ``'remove'``.
402
403        `user` is a string describing the user performing the
404        import. Normally fetched from current principal.
405
406        `logger` is the logger to use during import.
407
408        `ignore_emtpy` in update mode ignores empty fields if true.
409        """
410
411class IContactForm(IIkobaObject):
412    """A contact form.
413    """
414
415    email_from = schema.ASCIILine(
416        title = _(u'Email Address:'),
417        default = None,
418        required = True,
419        constraint=validate_email,
420        )
421
422    email_to = schema.ASCIILine(
423        title = _(u'Email to:'),
424        default = None,
425        required = True,
426        constraint=validate_email,
427        )
428
429    subject = schema.TextLine(
430        title = _(u'Subject:'),
431        required = True,)
432
433    fullname = schema.TextLine(
434        title = _(u'Full Name:'),
435        required = True,)
436
437    body = schema.Text(
438        title = _(u'Text:'),
439        required = True,)
440
441class IIkobaPrincipalInfo(IPrincipalInfo):
442    """Infos about principals that are users of Ikoba Ikoba.
443    """
444    email = Attribute("The email address of a user")
445    phone = Attribute("The phone number of a user")
446    public_name = Attribute("The public name of a user")
447
448
449class IIkobaPrincipal(IPrincipal):
450    """A principle for Ikoba Ikoba.
451
452    This interface extends zope.security.interfaces.IPrincipal and
453    requires also an `id` and other attributes defined there.
454    """
455
456    email = schema.TextLine(
457        title = _(u'Email Address'),
458        description = u'',
459        required=False,)
460
461    phone = PhoneNumber(
462        title = _(u'Phone'),
463        description = u'',
464        required=False,)
465
466    public_name = schema.TextLine(
467        title = _(u'Public Name'),
468        required = False,)
469
470class IFailedLoginInfo(IIkobaObject):
471    """Info about failed logins.
472
473    Timestamps are supposed to be stored as floats using time.time()
474    or similar.
475    """
476    num = schema.Int(
477        title = _(u'Number of failed logins'),
478        description = _(u'Number of failed logins'),
479        required = True,
480        default = 0,
481        )
482
483    last = schema.Float(
484        title = _(u'Timestamp'),
485        description = _(u'Timestamp of last failed login or `None`'),
486        required = False,
487        default = None,
488        )
489
490    def as_tuple():
491        """Get login info as tuple ``<NUM>, <TIMESTAMP>``.
492        """
493
494    def set_values(num=0, last=None):
495        """Set number of failed logins and timestamp of last one.
496        """
497
498    def increase():
499        """Increase the current number of failed logins and set timestamp.
500        """
501
502    def reset():
503        """Set failed login counters back to zero.
504        """
505
506
507class IUserAccount(IIkobaObject):
508    """A user account.
509    """
510
511    failed_logins = Attribute("""FailedLoginInfo for this account""")
512
513    name = schema.TextLine(
514        title = _(u'User Id'),
515        description = u'Login name of user',
516        required = True,)
517
518    title = schema.TextLine(
519        title = _(u'Full Name'),
520        required = True,)
521
522    public_name = schema.TextLine(
523        title = _(u'Public Name'),
524        description = u"Substitute for officer's real name "
525                       "in object histories.",
526        required = False,)
527
528    description = schema.Text(
529        title = _(u'Description/Notice'),
530        required = False,)
531
532    email = schema.ASCIILine(
533        title = _(u'Email Address'),
534        default = None,
535        required = True,
536        constraint=validate_email,
537        )
538
539    phone = PhoneNumber(
540        title = _(u'Phone'),
541        default = None,
542        required = False,
543        )
544
545    roles = schema.List(
546        title = _(u'Portal Roles'),
547        value_type = schema.Choice(source=RoleSource()),
548        required = False,
549        )
550
551
552
553class IPasswordValidator(Interface):
554    """A password validator utility.
555    """
556
557    def validate_password(password, password_repeat):
558        """Validates a password by comparing it with
559        control password and checking some other requirements.
560        """
561
562
563class IUsersContainer(IIkobaObject):
564    """A container for users (principals).
565
566    These users are used for authentication purposes.
567    """
568
569    def addUser(name, password, title=None, description=None):
570        """Add a user.
571        """
572
573    def delUser(name):
574        """Delete a user if it exists.
575        """
576
577class ILocalRolesAssignable(Interface):
578    """The local roles assignable to an object.
579    """
580    def __call__():
581        """Returns a list of dicts.
582
583        Each dict contains a ``name`` referring to the role assignable
584        for the specified object and a `title` to describe the range
585        of users to which this role can be assigned.
586        """
587
588class IConfigurationContainer(IIkobaObject):
589    """A container for session configuration objects.
590    """
591
592    name = schema.TextLine(
593        title = _(u'Name of Company'),
594        default = _(u'Sample Company'),
595        required = True,
596        )
597
598    acronym = schema.TextLine(
599        title = _(u'Abbreviated Title of Company'),
600        default = u'WAeUP.Ikoba',
601        required = True,
602        )
603
604    frontpage = schema.Text(
605        title = _(u'Content in HTML format'),
606        required = False,
607        default = default_html_frontpage,
608        )
609
610    frontpage_dict = schema.Dict(
611        title = u'Content as language dictionary with values in html format',
612        required = False,
613        default = {},
614        )
615
616    name_admin = schema.TextLine(
617        title = _(u'Name of Administrator'),
618        default = u'Administrator',
619        required = True,
620        )
621
622    email_admin = schema.ASCIILine(
623        title = _(u'Email Address of Administrator'),
624        default = 'contact@waeup.org',
625        required = True,
626        constraint=validate_email,
627        )
628
629    email_subject = schema.TextLine(
630        title = _(u'Subject of Email to Administrator'),
631        default = _(u'Ikoba Contact'),
632        required = True,
633        )
634
635    smtp_mailer = schema.Choice(
636        title = _(u'SMTP mailer to use when sending mail'),
637        vocabulary = 'Mail Delivery Names',
638        default = 'No email service',
639        required = True,
640        )
641
642    captcha = schema.Choice(
643        title = _(u'Captcha used for public registration pages'),
644        source = CaptchaSource(),
645        default = u'No captcha',
646        required = True,
647        )
648
649
650class ISessionConfiguration(IIkobaObject):
651    """A session configuration object.
652    """
653
654    application_session = schema.Choice(
655        title = _(u'Period'),
656        source = application_sessions_vocab,
657        default = None,
658        required = True,
659        readonly = True,
660        )
661
662
663    def getSessionString():
664        """Returns the session string from the vocabulary.
665        """
666
667
668class ISessionConfigurationAdd(ISessionConfiguration):
669    """A session configuration object in add mode.
670    """
671
672    application_session = schema.Choice(
673        title = _(u'Academic Session'),
674        source = application_sessions_vocab,
675        default = None,
676        required = True,
677        readonly = False,
678        )
679
680ISessionConfigurationAdd['application_session'].order =  ISessionConfiguration[
681    'application_session'].order
682
683class IDataCenter(IIkobaObject):
684    """A data center.
685
686    A data center manages files (uploads, downloads, etc.).
687
688    Beside providing the bare paths needed to keep files, it also
689    provides some helpers to put results of batch processing into
690    well-defined final locations (with well-defined filenames).
691
692    The main use-case is managing of site-related files, i.e. files
693    for import, export etc.
694
695    DataCenters are _not_ meant as storages for object-specific files
696    like passport photographs and similar.
697
698    It is up to the datacenter implementation how to organize data
699    (paths) inside its storage path.
700    """
701    storage = schema.Bytes(
702        title = u'Path to directory where everything is kept.'
703        )
704
705    deleted_path = schema.Bytes(
706        title = u'Path were data about deleted objects should be stored.'
707        )
708
709    def getPendingFiles(sort='name'):
710        """Get a list of files stored in `storage` sorted by basename.
711        """
712
713    def getFinishedFiles():
714        """Get a list of files stored in `finished` subfolder of `storage`.
715        """
716
717    def setStoragePath(path, move=False, overwrite=False):
718        """Set the path where to store files.
719
720        If `move` is True, move over files from the current location
721        to the new one.
722
723        If `overwrite` is also True, overwrite any already existing
724        files of same name in target location.
725
726        Triggers a DataCenterStorageMovedEvent.
727        """
728
729    def distProcessedFiles(successful, source_path, finished_file,
730                           pending_file, mode='create', move_orig=True):
731        """Distribute processed files over final locations.
732        """
733
734
735class IDataCenterFile(Interface):
736    """A data center file.
737    """
738
739    name = schema.TextLine(
740        title = u'Filename')
741
742    size = schema.TextLine(
743        title = u'Human readable file size')
744
745    uploaddate = schema.TextLine(
746        title = u'Human readable upload datetime')
747
748    lines = schema.Int(
749        title = u'Number of lines in file')
750
751    def getDate():
752        """Get creation timestamp from file in human readable form.
753        """
754
755    def getSize():
756        """Get human readable size of file.
757        """
758
759    def getLinesNumber():
760        """Get number of lines of file.
761        """
762
763class IDataCenterStorageMovedEvent(IObjectEvent):
764    """Emitted, when the storage of a datacenter changes.
765    """
766
767class IObjectUpgradeEvent(IObjectEvent):
768    """Can be fired, when an object shall be upgraded.
769    """
770
771class ILocalRoleSetEvent(IObjectEvent):
772    """A local role was granted/revoked for a principal on an object.
773    """
774    role_id = Attribute(
775        "The role id that was set.")
776    principal_id = Attribute(
777        "The principal id for which the role was granted/revoked.")
778    granted = Attribute(
779        "Boolean. If false, then the role was revoked.")
780
781class IQueryResultItem(Interface):
782    """An item in a search result.
783    """
784    url = schema.TextLine(
785        title = u'URL that links to the found item')
786    title = schema.TextLine(
787        title = u'Title displayed in search results.')
788    description = schema.Text(
789        title = u'Longer description of the item found.')
790
791class IIkobaPluggable(Interface):
792    """A component that might be plugged into a Ikoba Ikoba app.
793
794    Components implementing this interface are referred to as
795    'plugins'. They are normally called when a new
796    :class:`waeup.ikoba.app.Company` instance is created.
797
798    Plugins can setup and update parts of the central site without the
799    site object (normally a :class:`waeup.ikoba.app.Company` object)
800    needing to know about that parts. The site simply collects all
801    available plugins, calls them and the plugins care for their
802    respective subarea like the cutomers area or the datacenter
803    area.
804
805    Currently we have no mechanism to define an order of plugins. A
806    plugin should therefore make no assumptions about the state of the
807    site or other plugins being run before and instead do appropriate
808    checks if necessary.
809
810    Updates can be triggered for instance by the respective form in
811    the site configuration. You normally do updates when the
812    underlying software changed.
813    """
814    def setup(site, name, logger):
815        """Create an instance of the plugin.
816
817        The method is meant to be called by the central app (site)
818        when it is created.
819
820        `site`:
821           The site that requests a setup.
822
823        `name`:
824           The name under which the plugin was registered (utility name).
825
826        `logger`:
827           A standard Python logger for the plugins use.
828        """
829
830    def update(site, name, logger):
831        """Method to update an already existing plugin.
832
833        This might be called by a site when something serious
834        changes. It is a poor-man replacement for Zope generations
835        (but probably more comprehensive and better understandable).
836
837        `site`:
838           The site that requests an update.
839
840        `name`:
841           The name under which the plugin was registered (utility name).
842
843        `logger`:
844           A standard Python logger for the plugins use.
845        """
846
847class IAuthPluginUtility(Interface):
848    """A component that cares for authentication setup at site creation.
849
850    Utilities providing this interface are looked up when a Pluggable
851    Authentication Utility (PAU) for any
852    :class:`waeup.ikoba.app.Company` instance is created and put
853    into ZODB.
854
855    The setup-code then calls the `register` method of the utility and
856    expects a modified (or unmodified) version of the PAU back.
857
858    This allows to define any authentication setup modifications by
859    submodules or third-party modules/packages.
860    """
861
862    def register(pau):
863        """Register any plugins wanted to be in the PAU.
864        """
865
866    def unregister(pau):
867        """Unregister any plugins not wanted to be in the PAU.
868        """
869
870class IObjectConverter(Interface):
871    """Object converters are available as simple adapters, adapting
872       interfaces (not regular instances).
873
874    """
875
876    def fromStringDict(self, data_dict, context, form_fields=None):
877        """Convert values in `data_dict`.
878
879        Converts data in `data_dict` into real values based on
880        `context` and `form_fields`.
881
882        `data_dict` is a mapping (dict) from field names to values
883        represented as strings.
884
885        The fields (keys) to convert can be given in optional
886        `form_fields`. If given, form_fields should be an instance of
887        :class:`zope.formlib.form.Fields`. Suitable instances are for
888        example created by :class:`grok.AutoFields`.
889
890        If no `form_fields` are given, a default is computed from the
891        associated interface.
892
893        The `context` can be an existing object (implementing the
894        associated interface) or a factory name. If it is a string, we
895        try to create an object using
896        :func:`zope.component.createObject`.
897
898        Returns a tuple ``(<FIELD_ERRORS>, <INVARIANT_ERRORS>,
899        <DATA_DICT>)`` where
900
901        ``<FIELD_ERRORS>``
902           is a list of tuples ``(<FIELD_NAME>, <ERROR>)`` for each
903           error that happened when validating the input data in
904           `data_dict`
905
906        ``<INVARIANT_ERRORS>``
907           is a list of invariant errors concerning several fields
908
909        ``<DATA_DICT>``
910           is a dict with the values from input dict converted.
911
912        If errors happen, i.e. the error lists are not empty, always
913        an empty ``<DATA_DICT>`` is returned.
914
915        If ``<DATA_DICT>` is non-empty, there were no errors.
916        """
917
918class IFieldConverter(Interface):
919    def request_data(name, value, schema_field, prefix='', mode='create'):
920        """Create a dict with key-value mapping as created by a request.
921
922        `name` and `value` are expected to be parsed from CSV or a
923        similar input and represent an attribute to be set to a
924        representation of value.
925
926        `mode` gives the mode of import.
927
928        :meth:`update_request_data` is then requested to turn this
929        name and value into vars as they would be sent by a regular
930        form submit. This means we do not create the real values to be
931        set but we only define the values that would be sent in a
932        browser request to request the creation of those values.
933
934        The returned dict should contain names and values of a faked
935        browser request for the given `schema_field`.
936
937        Field converters are normally registered as adapters to some
938        specific zope.schema field.
939        """
940
941class IObjectHistory(Interface):
942
943    messages = schema.List(
944        title = u'List of messages stored',
945        required = True,
946        )
947
948    def addMessage(message):
949        """Add a message.
950        """
951
952class IIkobaWorkflowInfo(IWorkflowInfo):
953    """A :class:`hurry.workflow.workflow.WorkflowInfo` with additional
954       methods for convenience.
955    """
956    def getManualTransitions():
957        """Get allowed manual transitions.
958
959        Get a sorted list of tuples containing the `transition_id` and
960        `title` of each allowed transition.
961        """
962
963class ISiteLoggers(Interface):
964
965    loggers = Attribute("A list or generator of registered IkobaLoggers")
966
967    def register(name, filename=None, site=None, **options):
968        """Register a logger `name` which logs to `filename`.
969
970        If `filename` is not given, logfile will be `name` with
971        ``.log`` as filename extension.
972        """
973
974    def unregister(name):
975        """Unregister a once registered logger.
976        """
977
978class ILogger(Interface):
979    """A logger cares for setup, update and restarting of a Python logger.
980    """
981
982    logger = Attribute("""A :class:`logging.Logger` instance""")
983
984
985    def __init__(name, filename=None, site=None, **options):
986        """Create a Ikoba logger instance.
987        """
988
989    def setup():
990        """Create a Python :class:`logging.Logger` instance.
991
992        The created logger is based on the params given by constructor.
993        """
994
995    def update(**options):
996        """Update the logger.
997
998        Updates the logger respecting modified `options` and changed
999        paths.
1000        """
1001
1002class ILoggerCollector(Interface):
1003
1004    def getLoggers(site):
1005        """Return all loggers registered for `site`.
1006        """
1007
1008    def registerLogger(site, logging_component):
1009        """Register a logging component residing in `site`.
1010        """
1011
1012    def unregisterLogger(site, logging_component):
1013        """Unregister a logger.
1014        """
1015
1016#
1017# External File Storage and relatives
1018#
1019class IFileStoreNameChooser(INameChooser):
1020    """See zope.container.interfaces.INameChooser for base methods.
1021    """
1022    def checkName(name, attr=None):
1023        """Check whether an object name is valid.
1024
1025        Raises a user error if the name is not valid.
1026        """
1027
1028    def chooseName(name, attr=None):
1029        """Choose a unique valid file id for the object.
1030
1031        The given name may be taken into account when choosing the
1032        name (file id).
1033
1034        chooseName is expected to always choose a valid file id (that
1035        would pass the checkName test) and never raise an error.
1036
1037        If `attr` is not ``None`` it might been taken into account as
1038        well when generating the file id. Usual behaviour is to
1039        interpret `attr` as a hint for what type of file for a given
1040        context should be stored if there are several types
1041        possible. For instance for a certain customer some file could
1042        be the connected passport photograph or some certificate scan
1043        or whatever. Each of them has to be stored in a different
1044        location so setting `attr` to a sensible value should give
1045        different file ids returned.
1046        """
1047
1048class IExtFileStore(IFileRetrieval):
1049    """A file storage that stores files in filesystem (not as blobs).
1050    """
1051    root = schema.TextLine(
1052        title = u'Root path of file store.',
1053        )
1054
1055    def getFile(file_id):
1056        """Get raw file data stored under file with `file_id`.
1057
1058        Returns a file descriptor open for reading or ``None`` if the
1059        file cannot be found.
1060        """
1061
1062    def getFileByContext(context, attr=None):
1063        """Get raw file data stored for the given context.
1064
1065        Returns a file descriptor open for reading or ``None`` if no
1066        such file can be found.
1067
1068        Both, `context` and `attr` might be used to find (`context`)
1069        and feed (`attr`) an appropriate file name chooser.
1070
1071        This is a convenience method.
1072        """
1073
1074    def deleteFile(file_id):
1075        """Delete file stored under `file_id`.
1076
1077        Remove file from filestore so, that it is not available
1078        anymore on next call to getFile for the same file_id.
1079
1080        Should not complain if no such file exists.
1081        """
1082
1083    def deleteFileByContext(context, attr=None):
1084        """Delete file for given `context` and `attr`.
1085
1086        Both, `context` and `attr` might be used to find (`context`)
1087        and feed (`attr`) an appropriate file name chooser.
1088
1089        This is a convenience method.
1090        """
1091
1092    def createFile(filename, f):
1093        """Create file given by f with filename `filename`
1094
1095        Returns a hurry.file.File-based object.
1096        """
1097
1098class IFileStoreHandler(Interface):
1099    """Filestore handlers handle specific files for file stores.
1100
1101    If a file to store/get provides a specific filename, a file store
1102    looks up special handlers for that type of file.
1103
1104    """
1105    def pathFromFileID(store, root, filename):
1106        """Turn file id into path to store.
1107
1108        Returned path should be absolute.
1109        """
1110
1111    def createFile(store, root, filename, file_id, file):
1112        """Return some hurry.file based on `store` and `file_id`.
1113
1114        Some kind of callback method called by file stores to create
1115        file objects from file_id.
1116
1117        Returns a tuple ``(raw_file, path, file_like_obj)`` where the
1118        ``file_like_obj`` should be a HurryFile, a IkobaImageFile or
1119        similar. ``raw_file`` is the (maybe changed) input file and
1120        ``path`` the relative internal path to store the file at.
1121
1122        Please make sure the ``raw_file`` is opened for reading and
1123        the file descriptor set at position 0 when returned.
1124
1125        This method also gets the raw input file object that is about
1126        to be stored and is expected to raise any exceptions if some
1127        kind of validation or similar fails.
1128        """
1129
1130class IPDF(Interface):
1131    """A PDF representation of some context.
1132    """
1133
1134    def __call__(view=None, note=None):
1135        """Create a bytestream representing a PDF from context.
1136
1137        If `view` is passed in additional infos might be rendered into
1138        the document.
1139
1140        `note` is optional HTML rendered at bottom of the created
1141        PDF. Please consider the limited reportlab support for HTML,
1142        but using font-tags and friends you certainly can get the
1143        desired look.
1144        """
1145
1146class IMailService(Interface):
1147    """A mail service.
1148    """
1149
1150    def __call__():
1151        """Get the default mail delivery.
1152        """
1153
1154
1155class IDataCenterConfig(Interface):
1156    path = Path(
1157        title = u'Path',
1158        description = u"Directory where the datacenter should store "
1159                      u"files by default (adjustable in web UI).",
1160        required = True,
1161        )
1162
1163#
1164# Asynchronous job handling and related
1165#
1166class IJobManager(IIkobaObject):
1167    """A manager for asynchronous running jobs (tasks).
1168    """
1169    def put(job, site=None):
1170        """Put a job into task queue.
1171
1172        If no `site` is given, queue job in context of current local
1173        site.
1174
1175        Returns a job_id to identify the put job. This job_id is
1176        needed for further references to the job.
1177        """
1178
1179    def jobs(site=None):
1180        """Get an iterable of jobs stored.
1181        """
1182
1183    def get(job_id, site=None):
1184        """Get the job with id `job_id`.
1185
1186        For the `site` parameter see :meth:`put`.
1187        """
1188
1189    def remove(job_id, site=None):
1190        """Remove job with `job_id` from stored jobs.
1191        """
1192
1193    def start_test_job(site=None):
1194        """Start a test job.
1195        """
1196
1197class IProgressable(Interface):
1198    """A component that can indicate its progress status.
1199    """
1200    percent = schema.Float(
1201        title = u'Percent of job done already.',
1202        )
1203
1204class IJobContainer(IContainer):
1205    """A job container contains IJob objects.
1206    """
1207
1208class IExportJob(zc.async.interfaces.IJob):
1209    def __init__(site, exporter_name):
1210        pass
1211
1212    finished = schema.Bool(
1213        title = u'`True` if the job finished.`',
1214        default = False,
1215        )
1216
1217    failed = schema.Bool(
1218        title = u"`True` iff the job finished and didn't provide a file.",
1219        default = None,
1220        )
1221
1222class IExportJobContainer(IIkobaObject):
1223    """A component that contains (maybe virtually) export jobs.
1224    """
1225    def start_export_job(exporter_name, user_id, *args, **kwargs):
1226        """Start asynchronous export job.
1227
1228        `exporter_name` is the name of an exporter utility to be used.
1229
1230        `user_id` is the ID of the user that triggers the export.
1231
1232        `args` positional arguments passed to the export job created.
1233
1234        `kwargs` keyword arguments passed to the export job.
1235
1236        The job_id is stored along with exporter name and user id in a
1237        persistent list.
1238
1239        Returns the job ID of the job started.
1240        """
1241
1242    def get_running_export_jobs(user_id=None):
1243        """Get export jobs for user with `user_id` as list of tuples.
1244
1245        Each tuples holds ``<job_id>, <exporter_name>, <user_id>`` in
1246        that order. The ``<exporter_name>`` is the utility name of the
1247        used exporter.
1248
1249        If `user_id` is ``None``, all running jobs are returned.
1250        """
1251
1252    def get_export_jobs_status(user_id=None):
1253        """Get running/completed export jobs for `user_id` as list of tuples.
1254
1255        Each tuple holds ``<raw status>, <status translated>,
1256        <exporter title>`` in that order, where ``<status
1257        translated>`` and ``<exporter title>`` are translated strings
1258        representing the status of the job and the human readable
1259        title of the exporter used.
1260        """
1261
1262    def delete_export_entry(entry):
1263        """Delete the export denoted by `entry`.
1264
1265        Removes `entry` from the local `running_exports` list and also
1266        removes the regarding job via the local job manager.
1267
1268        `entry` is a tuple ``(<job id>, <exporter name>, <user id>)``
1269        as created by :meth:`start_export_job` or returned by
1270        :meth:`get_running_export_jobs`.
1271        """
1272
1273    def entry_from_job_id(job_id):
1274        """Get entry tuple for `job_id`.
1275
1276        Returns ``None`` if no such entry can be found.
1277        """
1278
1279class IExportContainerFinder(Interface):
1280    """A finder for the central export container.
1281    """
1282    def __call__():
1283        """Return the currently used global or site-wide IExportContainer.
1284        """
1285
1286class IFilteredQuery(IIkobaObject):
1287    """A query for objects.
1288    """
1289
1290    defaults = schema.Dict(
1291        title = u'Default Parameters',
1292        required = True,
1293        )
1294
1295    def __init__(**parameters):
1296        """Instantiate a filtered query by passing in parameters.
1297        """
1298
1299    def query():
1300        """Get an iterable of objects denoted by the set parameters.
1301
1302        The search should be applied to objects inside current
1303        site. It's the caller's duty to set the correct site before.
1304
1305        Result can be any iterable like a catalog result set, a list,
1306        or similar.
1307        """
1308
1309class IFilteredCatalogQuery(IFilteredQuery):
1310    """A catalog-based query for objects.
1311    """
1312
1313    cat_name = schema.TextLine(
1314        title = u'Registered name of the catalog to search.',
1315        required = True,
1316        )
1317
1318    def query_catalog(catalog):
1319        """Query catalog with the parameters passed to constructor.
1320        """
Note: See TracBrowser for help on using the repository browser.