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