source: main/waeup.kofa/trunk/src/waeup/kofa/interfaces.py @ 13211

Last change on this file since 13211 was 13211, checked in by Henrik Bettermann, 9 years ago

Explain that the export_disabled_message field means.

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