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

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

Remove unused IkobaUtils? attributes.

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