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

Last change on this file since 14022 was 13806, checked in by Henrik Bettermann, 8 years ago

Add portal maintenance mode.

See r13394, r13396, r13468.

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