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

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

Remove session configuration. We do not have sessions in Ikoba.

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