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

Last change on this file since 17305 was 14842, checked in by Henrik Bettermann, 7 years ago

Upgrade to Bootstrap v3.3.7

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 38.9 KB
RevLine 
[7193]1## $Id: interfaces.py 14842 2017-09-08 11:43:29Z henrik $
[3521]2##
[7193]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##
[6361]18import os
[7221]19import re
[7702]20import codecs
[9217]21import zc.async.interfaces
[7670]22import zope.i18nmessageid
[6915]23from datetime import datetime
[7063]24from hurry.file.interfaces import IFileRetrieval
[8394]25from hurry.workflow.interfaces import IWorkflowInfo
[4789]26from zc.sourcefactory.basic import BasicSourceFactory
[6147]27from zope import schema
[7233]28from zope.pluggableauth.interfaces import IPrincipalInfo
29from zope.security.interfaces import IGroupClosureAwarePrincipal as IPrincipal
[4789]30from zope.component import getUtility
[4882]31from zope.component.interfaces import IObjectEvent
[9217]32from zope.configuration.fields import Path
33from zope.container.interfaces import INameChooser, IContainer
[8394]34from zope.interface import Interface, Attribute
[7795]35from zope.schema.interfaces import IObject
[4789]36from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
[11949]37from waeup.ikoba.schema import PhoneNumber
38from waeup.ikoba.sourcefactory import SmartBasicContextualSourceFactory
[3521]39
[11949]40_ = MessageFactory = zope.i18nmessageid.MessageFactory('waeup.ikoba')
[6990]41
[8214]42DELETION_MARKER = 'XXX'
43IGNORE_MARKER = '<IGNORE>'
[11949]44WAEUP_KEY = 'waeup.ikoba'
[9217]45VIRT_JOBS_CONTAINER_NAME = 'jobs'
[8202]46
[12089]47# States for various workflows
48
[7673]49CREATED = 'created'
[12089]50
[11967]51STARTED = 'started'
[11964]52REQUESTED = 'requested'
[12526]53PROVISIONALLY = 'provisionally'
[11964]54APPROVED = 'approved'
[7670]55
[12089]56SUBMITTED = 'submitted'
[12663]57AWAITING = 'awaiting'
[12089]58REJECTED = 'rejected'
59EXPIRED = 'expired'
[12663]60
61VERIFIED = 'verified'
[12200]62PUBLISHED = 'published'
[12089]63
64
[9217]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
[8361]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'),
[7702]82        encoding='utf-8', mode='rb').read()
[6361]83
[11949]84def SimpleIkobaVocabulary(*terms):
[6915]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
[11450]91class ContextualDictSourceFactoryBase(SmartBasicContextualSourceFactory):
[11949]92    """A base for contextual sources based on IkobaUtils dicts.
[11450]93
94    To create a real source, you have to set the `DICT_NAME` attribute
[11949]95    which should be the name of a dictionary in IkobaUtils.
[11450]96    """
97    def getValues(self, context):
[11949]98        utils = getUtility(IIkobaUtils)
[11664]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]
[11450]102
103    def getToken(self, context, value):
104        return str(value)
105
106    def getTitle(self, context, value):
[11949]107        utils = getUtility(IIkobaUtils)
[11450]108        return getattr(utils, self.DICT_NAME)[value]
109
[7850]110# Define a validation method for email addresses
[7221]111class NotAnEmailAddress(schema.ValidationError):
112    __doc__ = u"Invalid email address"
113
[8638]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.
[7221]117check_email = re.compile(
[8638]118    r"^[^@\s,]+@[^@\.\s,]+(\.[^@\.\s,]+)*$").match
[7221]119
120def validate_email(value):
121    if not check_email(value):
122        raise NotAnEmailAddress(value)
123    return True
124
[12419]125# Define a validation method for ids
[12260]126class NotIdValue(schema.ValidationError):
127    __doc__ = u"Invalid id"
128
129#: Regular expressions to check id formats.
[12607]130check_id = re.compile(r"^[a-zA-Z0-9_-]{2,10}$").match
[12260]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
[13805]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
[7850]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):
[7851]162    if not RE_INT_PHONE.match(value):
[7850]163        raise InvalidPhoneNumber(value)
164    return True
165
[4858]166class FatalCSVError(Exception):
167    """Some row could not be processed.
168    """
169    pass
170
[6226]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
[6143]186class RoleSource(BasicSourceFactory):
[7178]187    """A source for site roles.
[6508]188    """
[6143]189    def getValues(self):
[6157]190        # late import: in interfaces we should not import local modules
[11949]191        from waeup.ikoba.permissions import get_waeup_role_names
[7186]192        return get_waeup_role_names()
[6157]193
194    def getTitle(self, value):
195        # late import: in interfaces we should not import local modules
[11949]196        from waeup.ikoba.permissions import get_all_roles
[7186]197        roles = dict(get_all_roles())
[6157]198        if value in roles.keys():
199            title = roles[value].title
[6569]200            if '.' in title:
201                title = title.split('.', 2)[1]
[6157]202        return title
[6143]203
[7313]204class CaptchaSource(BasicSourceFactory):
205    """A source for captchas.
206    """
207    def getValues(self):
[7323]208        captchas = ['No captcha', 'Testing captcha', 'ReCaptcha']
[7313]209        try:
210            # we have to 'try' because IConfiguration can only handle
[7817]211            # interfaces from w.k.interface.
[11949]212            from waeup.ikoba.browser.interfaces import ICaptchaManager
[7313]213        except:
214            return captchas
215        return sorted(getUtility(ICaptchaManager).getAvailCaptchas().keys())
216
217    def getTitle(self, value):
218        return value
219
[12378]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
[11949]234class IIkobaUtils(Interface):
[7358]235    """A collection of methods which are subject to customization.
236    """
[7568]237
[7841]238    PORTAL_LANGUAGE = Attribute("Dict of global language setting")
239    PREFERRED_LANGUAGES_DICT = Attribute("Dict of preferred languages")
[11799]240    SYSTEM_MAX_LOAD = Attribute("Dict of maximum system loads.")
[7568]241
[7404]242    def sendContactForm(
243          from_name,from_addr,rcpt_name,rcpt_addr,
244          from_username,usertype,portal,body,subject):
[7358]245        """Send an email with data provided by forms.
246        """
247
[7475]248    def fullname(firstname,lastname,middlename):
249        """Full name constructor.
250        """
251
[8853]252    def sendCredentials(user, password, url_info, msg):
[7475]253        """Send credentials as email.
254
[11947]255        Input is the customer for which credentials are sent and the
[7475]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
[11949]265class IIkobaObject(Interface):
266    """A Ikoba object.
[5663]267
268    This is merely a marker interface.
[4789]269    """
270
[11954]271class ICompany(IIkobaObject):
272    """Representation of an company.
[3521]273    """
[5955]274
[6065]275
[11949]276class IIkobaContainer(IIkobaObject):
277    """A container for Ikoba objects.
[4789]278    """
279
[11949]280class IIkobaContained(IIkobaObject):
281    """An item contained in an IIkobaContainer.
[4789]282    """
[6136]283
[7726]284class ICSVExporter(Interface):
285    """A CSV file exporter for objects.
286    """
287    fields = Attribute("""List of fieldnames in resulting CSV""")
[7907]288
289    title = schema.TextLine(
290        title = u'Title',
291        description = u'Description to be displayed in selections.',
292        )
[7726]293    def mangle_value(value, name, obj):
294        """Mangle `value` extracted from `obj` or suobjects thereof.
295
[8394]296        This is called by export before actually writing to the result
297        file.
[7726]298        """
299
[9797]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
[7730]309    def export(iterable, filepath=None):
310        """Export iterables as rows in a CSV file.
[7726]311
[8394]312        If `filepath` is not given, a string with the data should be
313        returned.
[7730]314
315        What kind of iterables are acceptable depends on the specific
316        exporter implementation.
[7726]317        """
318
[9766]319    def export_all(site, filepath=None):
[7726]320        """Export all items in `site` as CSV file.
321
[8394]322        if `filepath` is not given, a string with the data should be
323        returned.
[7726]324        """
325
[9797]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
[11949]336class IIkobaExporter(Interface):
[4789]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
[11949]348class IIkobaXMLExporter(Interface):
[4789]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
[11949]360class IIkobaXMLImporter(Interface):
[4789]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
[4858]369class IBatchProcessor(Interface):
370    """A batch processor that handles mass-operations.
371    """
372    name = schema.TextLine(
[7933]373        title = _(u'Processor name')
[4858]374        )
375
[5476]376    def doImport(path, headerfields, mode='create', user='Unknown',
[8218]377                 logger=None, ignore_empty=True):
[4858]378        """Read data from ``path`` and update connected object.
[5476]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.
[8218]390
391        `ignore_emtpy` in update mode ignores empty fields if true.
[4858]392        """
393
[11949]394class IContactForm(IIkobaObject):
[7225]395    """A contact form.
396    """
397
[12522]398    email_from = schema.TextLine(
[7828]399        title = _(u'Email Address:'),
[7225]400        default = None,
401        required = True,
402        constraint=validate_email,
403        )
404
[12522]405    email_to = schema.TextLine(
[7828]406        title = _(u'Email to:'),
[7225]407        default = None,
408        required = True,
409        constraint=validate_email,
410        )
411
412    subject = schema.TextLine(
[7828]413        title = _(u'Subject:'),
[7225]414        required = True,)
415
416    fullname = schema.TextLine(
[7828]417        title = _(u'Full Name:'),
[7225]418        required = True,)
419
420    body = schema.Text(
[7828]421        title = _(u'Text:'),
[7225]422        required = True,)
423
[11949]424class IIkobaPrincipalInfo(IPrincipalInfo):
425    """Infos about principals that are users of Ikoba Ikoba.
[7233]426    """
427    email = Attribute("The email address of a user")
428    phone = Attribute("The phone number of a user")
[8757]429    public_name = Attribute("The public name of a user")
[7225]430
[7233]431
[11949]432class IIkobaPrincipal(IPrincipal):
433    """A principle for Ikoba Ikoba.
[7233]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(
[7828]440        title = _(u'Email Address'),
[7233]441        description = u'',
442        required=False,)
443
[8176]444    phone = PhoneNumber(
[7828]445        title = _(u'Phone'),
[7233]446        description = u'',
447        required=False,)
448
[8757]449    public_name = schema.TextLine(
450        title = _(u'Public Name'),
451        required = False,)
452
[11949]453class IFailedLoginInfo(IIkobaObject):
[10055]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
[11949]490class IUserAccount(IIkobaObject):
[4789]491    """A user account.
492    """
[10055]493
[13803]494    failed_logins = Attribute('FailedLoginInfo for this account')
[10055]495
[4789]496    name = schema.TextLine(
[7828]497        title = _(u'User Id'),
[13803]498        description = _(u'Login name of user'),
[4789]499        required = True,)
[7221]500
[4789]501    title = schema.TextLine(
[7828]502        title = _(u'Full Name'),
[8759]503        required = True,)
[7221]504
[8756]505    public_name = schema.TextLine(
506        title = _(u'Public Name'),
[13803]507        description = _(u"Substitute for officer's real name "
[14842]508                       "in object histories."),
[8756]509        required = False,)
510
[7197]511    description = schema.Text(
[7828]512        title = _(u'Description/Notice'),
[4789]513        required = False,)
[7221]514
[12522]515    email = schema.TextLine(
[7828]516        title = _(u'Email Address'),
[7221]517        default = None,
[7222]518        required = True,
[7221]519        constraint=validate_email,
520        )
521
[8176]522    phone = PhoneNumber(
[7828]523        title = _(u'Phone'),
[7233]524        default = None,
[8062]525        required = False,
[7233]526        )
527
[4789]528    roles = schema.List(
[8486]529        title = _(u'Portal Roles'),
[8079]530        value_type = schema.Choice(source=RoleSource()),
531        required = False,
532        )
[6136]533
[13803]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        )
[10055]540
541
[7147]542class IPasswordValidator(Interface):
543    """A password validator utility.
544    """
[6136]545
[7147]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
[11949]552class IUsersContainer(IIkobaObject):
[4789]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
[6141]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
[11949]577class IConfigurationContainer(IIkobaObject):
[6907]578    """A container for session configuration objects.
579    """
580
581    name = schema.TextLine(
[11954]582        title = _(u'Name of Company'),
583        default = _(u'Sample Company'),
[6907]584        required = True,
585        )
586
[7459]587    acronym = schema.TextLine(
[11954]588        title = _(u'Abbreviated Title of Company'),
[11949]589        default = u'WAeUP.Ikoba',
[7459]590        required = True,
591        )
592
[6907]593    frontpage = schema.Text(
[8361]594        title = _(u'Content in HTML format'),
[6907]595        required = False,
[8361]596        default = default_html_frontpage,
[13805]597        constraint=validate_html,
[6907]598        )
599
[7702]600    frontpage_dict = schema.Dict(
601        title = u'Content as language dictionary with values in html format',
[7485]602        required = False,
[7702]603        default = {},
[7485]604        )
605
[7223]606    name_admin = schema.TextLine(
[7828]607        title = _(u'Name of Administrator'),
[7223]608        default = u'Administrator',
[8230]609        required = True,
[7223]610        )
611
[12522]612    email_admin = schema.TextLine(
[7828]613        title = _(u'Email Address of Administrator'),
[12522]614        default = u'contact@waeup.org',
[8230]615        required = True,
[7221]616        constraint=validate_email,
617        )
618
619    email_subject = schema.TextLine(
[7828]620        title = _(u'Subject of Email to Administrator'),
[11949]621        default = _(u'Ikoba Contact'),
[8230]622        required = True,
[7221]623        )
624
[7470]625    smtp_mailer = schema.Choice(
[7828]626        title = _(u'SMTP mailer to use when sending mail'),
[7470]627        vocabulary = 'Mail Delivery Names',
628        default = 'No email service',
629        required = True,
630        )
631
[12553]632    email_notification = schema.Bool(
633        title = _(u'Notify customers by email'),
634        default = False,
635        )
636
[7313]637    captcha = schema.Choice(
[7828]638        title = _(u'Captcha used for public registration pages'),
[7313]639        source = CaptchaSource(),
640        default = u'No captcha',
641        required = True,
642        )
[7221]643
[13802]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        )
[7664]651
[13806]652    maintmode_enabled_by = schema.TextLine(
653        title = _(u'Maintenance Mode enabled by'),
654        default = None,
655        required = False,
656        )
[13802]657
[13806]658
[11949]659class IDataCenter(IIkobaObject):
[4789]660    """A data center.
661
[8394]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.
[4789]676    """
[8394]677    storage = schema.Bytes(
678        title = u'Path to directory where everything is kept.'
679        )
[4789]680
[8394]681    deleted_path = schema.Bytes(
682        title = u'Path were data about deleted objects should be stored.'
683        )
684
[9023]685    def getPendingFiles(sort='name'):
[8394]686        """Get a list of files stored in `storage` sorted by basename.
687        """
[9023]688
[9074]689    def getFinishedFiles():
690        """Get a list of files stored in `finished` subfolder of `storage`.
[9023]691        """
692
[8394]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
[4789]711class IDataCenterFile(Interface):
712    """A data center file.
713    """
[4858]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')
[6136]726
[4789]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        """
[4858]734
735    def getLinesNumber():
736        """Get number of lines of file.
737        """
[4882]738
739class IDataCenterStorageMovedEvent(IObjectEvent):
740    """Emitted, when the storage of a datacenter changes.
741    """
[5007]742
[6136]743class IObjectUpgradeEvent(IObjectEvent):
744    """Can be fired, when an object shall be upgraded.
745    """
746
[6180]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
[5007]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.')
[6136]766
[11949]767class IIkobaPluggable(Interface):
768    """A component that might be plugged into a Ikoba Ikoba app.
[5658]769
770    Components implementing this interface are referred to as
771    'plugins'. They are normally called when a new
[11954]772    :class:`waeup.ikoba.app.Company` instance is created.
[5658]773
774    Plugins can setup and update parts of the central site without the
[11954]775    site object (normally a :class:`waeup.ikoba.app.Company` object)
[5658]776    needing to know about that parts. The site simply collects all
777    available plugins, calls them and the plugins care for their
[11947]778    respective subarea like the cutomers area or the datacenter
[5658]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.
[5013]789    """
[5069]790    def setup(site, name, logger):
791        """Create an instance of the plugin.
[5013]792
[5658]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.
[5069]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
[5658]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.
[5069]821        """
[5898]822
[5899]823class IAuthPluginUtility(Interface):
[5898]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
[11954]828    :class:`waeup.ikoba.app.Company` instance is created and put
[5898]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        """
[6273]845
846class IObjectConverter(Interface):
847    """Object converters are available as simple adapters, adapting
848       interfaces (not regular instances).
849
850    """
851
[6277]852    def fromStringDict(self, data_dict, context, form_fields=None):
853        """Convert values in `data_dict`.
[6273]854
[6277]855        Converts data in `data_dict` into real values based on
856        `context` and `form_fields`.
[6273]857
[6277]858        `data_dict` is a mapping (dict) from field names to values
859        represented as strings.
[6273]860
[6277]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`.
[6273]865
[6277]866        If no `form_fields` are given, a default is computed from the
867        associated interface.
[6273]868
[6277]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
[12839]891        If ``<DATA_DICT>`` is non-empty, there were no errors.
[6273]892        """
[6293]893
[7932]894class IFieldConverter(Interface):
[8214]895    def request_data(name, value, schema_field, prefix='', mode='create'):
[7932]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
[8214]902        `mode` gives the mode of import.
903
[7932]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
[6338]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        """
[6353]927
[11949]928class IIkobaWorkflowInfo(IWorkflowInfo):
[6353]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        """
[6481]938
939class ISiteLoggers(Interface):
940
[11949]941    loggers = Attribute("A list or generator of registered IkobaLoggers")
[6481]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):
[11949]962        """Create a Ikoba logger instance.
[6481]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        """
[6754]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        """
[7063]991
992#
993# External File Storage and relatives
994#
995class IFileStoreNameChooser(INameChooser):
996    """See zope.container.interfaces.INameChooser for base methods.
997    """
[7066]998    def checkName(name, attr=None):
[7063]999        """Check whether an object name is valid.
1000
1001        Raises a user error if the name is not valid.
1002        """
1003
[7066]1004    def chooseName(name, attr=None):
1005        """Choose a unique valid file id for the object.
[7063]1006
[7066]1007        The given name may be taken into account when choosing the
1008        name (file id).
[7063]1009
[7066]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
[11947]1017        possible. For instance for a certain customer some file could
[7066]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.
[7063]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
[7071]1038    def getFileByContext(context, attr=None):
[7063]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
[7071]1044        Both, `context` and `attr` might be used to find (`context`)
1045        and feed (`attr`) an appropriate file name chooser.
1046
[7063]1047        This is a convenience method.
1048        """
1049
[7090]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
[7063]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
[11949]1094        ``file_like_obj`` should be a HurryFile, a IkobaImageFile or
[7063]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        """
[7389]1105
1106class IPDF(Interface):
1107    """A PDF representation of some context.
1108    """
1109
[8257]1110    def __call__(view=None, note=None):
[7389]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.
[8257]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.
[7389]1120        """
[7473]1121
1122class IMailService(Interface):
1123    """A mail service.
1124    """
1125
1126    def __call__():
1127        """Get the default mail delivery.
1128        """
[7576]1129
[9217]1130
[7576]1131class IDataCenterConfig(Interface):
1132    path = Path(
1133        title = u'Path',
[7828]1134        description = u"Directory where the datacenter should store "
1135                      u"files by default (adjustable in web UI).",
[7576]1136        required = True,
1137        )
[8346]1138
[12060]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
[9217]1148#
1149# Asynchronous job handling and related
1150#
[11949]1151class IJobManager(IIkobaObject):
[9217]1152    """A manager for asynchronous running jobs (tasks).
1153    """
1154    def put(job, site=None):
1155        """Put a job into task queue.
[8346]1156
[9217]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.
[8346]1184    """
[9217]1185    percent = schema.Float(
1186        title = u'Percent of job done already.',
[8346]1187        )
1188
[9217]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
[9816]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
[11949]1207class IExportJobContainer(IIkobaObject):
[9217]1208    """A component that contains (maybe virtually) export jobs.
1209    """
[9718]1210    def start_export_job(exporter_name, user_id, *args, **kwargs):
[9217]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
[9718]1217        `args` positional arguments passed to the export job created.
1218
1219        `kwargs` keyword arguments passed to the export job.
1220
[9217]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        """
[9726]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        """
[9766]1270
[11949]1271class IFilteredQuery(IIkobaObject):
[9766]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        """
[12251]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.