source: main/waeup.ikoba/branches/uli-payments/src/waeup/ikoba/interfaces.py @ 12045

Last change on this file since 12045 was 11991, checked in by uli, 10 years ago

Add interface for ZCML directive pointing to paypal config.

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