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

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

We need documents which can be accessed or downloaded from product pages. These documents can provide general information of registration processes or pdf forms to be filled offline and later uploaded by customers.

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