1 | ## $Id: utils.py 16976 2022-06-29 10:24:59Z 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 | """General helper utilities for Kofa. |
---|
19 | """ |
---|
20 | import grok |
---|
21 | import psutil |
---|
22 | import string |
---|
23 | import pytz |
---|
24 | import decimal |
---|
25 | from copy import deepcopy |
---|
26 | from random import SystemRandom as r |
---|
27 | from zope.i18n import translate |
---|
28 | from waeup.kofa.interfaces import IKofaUtils |
---|
29 | from waeup.kofa.interfaces import MessageFactory as _ |
---|
30 | from waeup.kofa.smtp import send_mail as send_mail_internally |
---|
31 | from waeup.kofa.utils.helpers import get_sorted_preferred |
---|
32 | from waeup.kofa.utils.degrees import DEGREES_DICT |
---|
33 | |
---|
34 | |
---|
35 | def send_mail(from_name, from_addr, |
---|
36 | rcpt_name, rcpt_addr, |
---|
37 | subject, body, config, |
---|
38 | cc=None, bcc=None): |
---|
39 | """Wrapper for the real SMTP functionality in :mod:`waeup.kofa.smtp`. |
---|
40 | |
---|
41 | Merely here to stay compatible with lots of calls to this place. |
---|
42 | """ |
---|
43 | mail_id = send_mail_internally( |
---|
44 | from_name, from_addr, rcpt_name, rcpt_addr, |
---|
45 | subject, body, config, cc, bcc) |
---|
46 | return True |
---|
47 | |
---|
48 | |
---|
49 | #: A list of phone prefixes (order num, country, prefix). |
---|
50 | #: Items with same order num will be sorted alphabetically. |
---|
51 | #: The lower the order num, the higher the precedence. |
---|
52 | INT_PHONE_PREFIXES = [ |
---|
53 | (99, _('Germany'), '49'), |
---|
54 | (1, _('Nigeria'), '234'), |
---|
55 | (99, _('U.S.'), '1'), |
---|
56 | ] |
---|
57 | |
---|
58 | |
---|
59 | def sorted_phone_prefixes(data=INT_PHONE_PREFIXES, request=None): |
---|
60 | """Sorted tuples of phone prefixes. |
---|
61 | |
---|
62 | Ordered as shown above and formatted for use in select boxes. |
---|
63 | |
---|
64 | If request is given, we'll try to translate all country names in |
---|
65 | order to sort alphabetically correctly. |
---|
66 | |
---|
67 | XXX: This is a function (and not a constant) as different |
---|
68 | languages might give different orders. This is not tested yet. |
---|
69 | |
---|
70 | XXX: If we really want to use alphabetic ordering here, we might |
---|
71 | think about caching results of translations. |
---|
72 | """ |
---|
73 | if request is not None: |
---|
74 | data = [ |
---|
75 | (x, translate(y, context=request), z) |
---|
76 | for x, y, z in data] |
---|
77 | return tuple([ |
---|
78 | ('%s (+%s)' % (x[1], x[2]), '+%s' % x[2]) |
---|
79 | for x in sorted(data) |
---|
80 | ]) |
---|
81 | |
---|
82 | |
---|
83 | class KofaUtils(grok.GlobalUtility): |
---|
84 | """A collection of parameters and methods subject to customization. |
---|
85 | """ |
---|
86 | grok.implements(IKofaUtils) |
---|
87 | |
---|
88 | #: This the only place where we define the portal language |
---|
89 | #: which is used for the translation of system messages |
---|
90 | #: (e.g. object histories) pdf slips. |
---|
91 | PORTAL_LANGUAGE = 'en' |
---|
92 | |
---|
93 | DEGREES_DICT = DEGREES_DICT |
---|
94 | |
---|
95 | PREFERRED_LANGUAGES_DICT = { |
---|
96 | 'en': (1, u'English'), |
---|
97 | 'fr': (2, u'Français'), |
---|
98 | 'de': (3, u'Deutsch'), |
---|
99 | 'ha': (4, u'Hausa'), |
---|
100 | 'yo': (5, u'Yoruba'), |
---|
101 | 'ig': (6, u'Igbo'), |
---|
102 | } |
---|
103 | |
---|
104 | #: A function to return |
---|
105 | @classmethod |
---|
106 | def sorted_phone_prefixes(cls, data=INT_PHONE_PREFIXES, request=None): |
---|
107 | return sorted_phone_prefixes(data, request) |
---|
108 | |
---|
109 | EXAM_SUBJECTS_DICT = { |
---|
110 | 'math': 'Mathematics', |
---|
111 | 'computer_science': 'Computer Science', |
---|
112 | } |
---|
113 | |
---|
114 | #: Exam grades. The tuple is sorted as it should be displayed in |
---|
115 | #: select boxes. |
---|
116 | EXAM_GRADES = ( |
---|
117 | ('A', 'Best'), |
---|
118 | ('B', 'Better'), |
---|
119 | ('C', 'Good'), |
---|
120 | ) |
---|
121 | |
---|
122 | INST_TYPES_DICT = { |
---|
123 | 'none': '', |
---|
124 | 'faculty': 'Faculty of', |
---|
125 | 'department': 'Department of', |
---|
126 | 'school': 'School of', |
---|
127 | 'office': 'Office for', |
---|
128 | 'centre': 'Centre for', |
---|
129 | 'centre_of': 'Centre of', |
---|
130 | 'institute': 'Institute of', |
---|
131 | 'school_for': 'School for', |
---|
132 | 'college': 'College of', |
---|
133 | 'directorate': 'Directorate of', |
---|
134 | } |
---|
135 | |
---|
136 | STUDY_MODES_DICT = { |
---|
137 | 'transfer': 'Transfer', |
---|
138 | 'transferred': 'Transferred', |
---|
139 | 'ug_ft': 'Undergraduate Full-Time', |
---|
140 | 'ug_pt': 'Undergraduate Part-Time', |
---|
141 | 'pg_ft': 'Postgraduate Full-Time', |
---|
142 | 'pg_pt': 'Postgraduate Part-Time', |
---|
143 | } |
---|
144 | |
---|
145 | DISABLE_PAYMENT_GROUP_DICT = { |
---|
146 | 'sf_all': 'School Fee - All Students', |
---|
147 | } |
---|
148 | |
---|
149 | APP_CATS_DICT = { |
---|
150 | 'basic': 'Basic Application', |
---|
151 | 'no': 'no application', |
---|
152 | 'pg': 'Postgraduate', |
---|
153 | 'sandwich': 'Sandwich', |
---|
154 | 'cest': 'Part-Time, Diploma, Certificate' |
---|
155 | } |
---|
156 | |
---|
157 | SEMESTER_DICT = { |
---|
158 | 1: '1st Semester', |
---|
159 | 2: '2nd Semester', |
---|
160 | 3: 'Combined', |
---|
161 | 4: '1st Term', |
---|
162 | 5: '2nd Term', |
---|
163 | 6: '3rd Term', |
---|
164 | 9: 'N/A', |
---|
165 | 11: 'Module I', |
---|
166 | 12: 'Module II', |
---|
167 | 13: 'Module III', |
---|
168 | } |
---|
169 | |
---|
170 | COURSE_CATEGORY_DICT = { |
---|
171 | } |
---|
172 | |
---|
173 | SPECIAL_HANDLING_DICT = { |
---|
174 | 'regular': 'Regular Hostel', |
---|
175 | 'blocked': 'Blocked Hostel', |
---|
176 | 'pg': 'Postgraduate Hostel' |
---|
177 | } |
---|
178 | |
---|
179 | SPECIAL_APP_DICT = { |
---|
180 | 'transcript': 'Transcript Fee Payment', |
---|
181 | 'clearance': 'Acceptance Fee', |
---|
182 | } |
---|
183 | |
---|
184 | PAYMENT_CATEGORIES = { |
---|
185 | 'schoolfee': 'School Fee', |
---|
186 | 'clearance': 'Acceptance Fee', |
---|
187 | 'bed_allocation': 'Bed Allocation Fee', |
---|
188 | 'hostel_maintenance': 'Hostel Maintenance Fee', |
---|
189 | 'transfer': 'Transfer Fee', |
---|
190 | 'gown': 'Gown Hire Fee', |
---|
191 | 'application': 'Application Fee', |
---|
192 | 'app_balance': 'Application Fee Balance', |
---|
193 | 'transcript': 'Transcript Fee', |
---|
194 | 'late_registration': 'Late Course Registration Fee', |
---|
195 | 'combi': 'Combi Payment', |
---|
196 | } |
---|
197 | |
---|
198 | #: If PAYMENT_OPTIONS is empty, payment option fields won't show up. |
---|
199 | PAYMENT_OPTIONS = { |
---|
200 | #'credit_card': 'Credit Card', |
---|
201 | #'debit_card': 'Debit Card', |
---|
202 | } |
---|
203 | |
---|
204 | def selectable_payment_categories(self, student): |
---|
205 | return self.PAYMENT_CATEGORIES |
---|
206 | |
---|
207 | def selectable_payment_options(self, student): |
---|
208 | return self.PAYMENT_OPTIONS |
---|
209 | |
---|
210 | PREVIOUS_PAYMENT_CATEGORIES = deepcopy(PAYMENT_CATEGORIES) |
---|
211 | |
---|
212 | REPORTABLE_PAYMENT_CATEGORIES = { |
---|
213 | 'schoolfee': 'School Fee', |
---|
214 | 'clearance': 'Acceptance Fee', |
---|
215 | 'hostel_maintenance': 'Hostel Maintenance Fee', |
---|
216 | 'gown': 'Gown Hire Fee', |
---|
217 | } |
---|
218 | |
---|
219 | BALANCE_PAYMENT_CATEGORIES = { |
---|
220 | 'schoolfee': 'School Fee', |
---|
221 | } |
---|
222 | |
---|
223 | COMBI_PAYMENT_CATEGORIES = { |
---|
224 | 'gown': 'Gown Hire Fee', |
---|
225 | 'transcript': 'Transcript Fee', |
---|
226 | 'late_registration': 'Late Course Registration Fee', |
---|
227 | } |
---|
228 | |
---|
229 | MODE_GROUPS = { |
---|
230 | 'All': ('all',), |
---|
231 | 'Undergraduate Full-Time': ('ug_ft',), |
---|
232 | 'Undergraduate Part-Time': ('ug_pt',), |
---|
233 | 'Postgraduate Full-Time': ('pg_ft',), |
---|
234 | 'Postgraduate Part-Time': ('pg_pt',), |
---|
235 | } |
---|
236 | |
---|
237 | VERDICTS_DICT = { |
---|
238 | '0': _('(not yet)'), |
---|
239 | 'A': 'Successful student', |
---|
240 | 'B': 'Student with carryover courses', |
---|
241 | 'C': 'Student on probation', |
---|
242 | } |
---|
243 | |
---|
244 | #: Set positive number for allowed max, negative for required min |
---|
245 | #: avail. |
---|
246 | #: Use integer for bytes value, float for percent |
---|
247 | #: value. `cpu-load`, of course, accepts float values only. |
---|
248 | #: `swap-mem` = Swap Memory, `virt-mem` = Virtual Memory, |
---|
249 | #: `cpu-load` = CPU load in percent. |
---|
250 | SYSTEM_MAX_LOAD = { |
---|
251 | 'swap-mem': None, |
---|
252 | 'virt-mem': None, |
---|
253 | 'cpu-load': 100.0, |
---|
254 | } |
---|
255 | |
---|
256 | #: Maximum number of files listed in `finished` subfolder |
---|
257 | MAX_FILES = 100 |
---|
258 | |
---|
259 | #: Maximum size in Bytes of passport images in the applicants and |
---|
260 | #: students section |
---|
261 | MAX_PASSPORT_SIZE = 50 * 1024 |
---|
262 | |
---|
263 | #: Temporary passwords and parents password validity period |
---|
264 | TEMP_PASSWORD_MINUTES = 10 |
---|
265 | |
---|
266 | def sendContactForm(self, from_name, from_addr, rcpt_name, rcpt_addr, |
---|
267 | from_username, usertype, portal, body, subject, |
---|
268 | bcc_to=None): |
---|
269 | """Send an email with data provided by forms. |
---|
270 | """ |
---|
271 | config = grok.getSite()['configuration'] |
---|
272 | text = _(u"""${e} |
---|
273 | |
---|
274 | --- |
---|
275 | ${a} (id: ${b}) |
---|
276 | ${d} |
---|
277 | """) |
---|
278 | text = _(text, mapping={ |
---|
279 | 'a': from_name, |
---|
280 | 'b': from_username, |
---|
281 | 'c': usertype, |
---|
282 | 'd': portal, |
---|
283 | 'e': body}) |
---|
284 | body = translate(text, 'waeup.kofa', |
---|
285 | target_language=self.PORTAL_LANGUAGE) |
---|
286 | if not (from_addr and rcpt_addr): |
---|
287 | return False |
---|
288 | return send_mail( |
---|
289 | from_name, from_addr, rcpt_name, rcpt_addr, |
---|
290 | subject, body, config, None, bcc_to) |
---|
291 | |
---|
292 | def getUsers(self): |
---|
293 | users = sorted( |
---|
294 | grok.getSite()['users'].items(), key=lambda x: x[1].title) |
---|
295 | for key, val in users: |
---|
296 | yield(dict(name=key, val="%s (%s)" % (val.title, val.name))) |
---|
297 | |
---|
298 | @property |
---|
299 | def tzinfo(self): |
---|
300 | """Time zone of the university. |
---|
301 | """ |
---|
302 | # For Nigeria: pytz.timezone('Africa/Lagos') |
---|
303 | # For Germany: pytz.timezone('Europe/Berlin') |
---|
304 | return pytz.utc |
---|
305 | |
---|
306 | def fullname(self, firstname, lastname, middlename=None): |
---|
307 | """Construct fullname. |
---|
308 | """ |
---|
309 | # We do not necessarily have the middlename attribute |
---|
310 | if middlename: |
---|
311 | name = '%s %s %s' % (firstname, middlename, lastname) |
---|
312 | else: |
---|
313 | name = '%s %s' % (firstname, lastname) |
---|
314 | if '<' in name: |
---|
315 | return 'XXX' |
---|
316 | return string.capwords( |
---|
317 | name.replace('-', ' - ')).replace(' - ', '-') |
---|
318 | |
---|
319 | def genPassword(self, length=4, chars=string.letters + string.digits): |
---|
320 | """Generate a random password. |
---|
321 | """ |
---|
322 | return ''.join([ |
---|
323 | r().choice(string.uppercase) + |
---|
324 | r().choice(string.lowercase) + |
---|
325 | r().choice(string.digits) for i in range(length)]) |
---|
326 | |
---|
327 | def sendCredentials(self, user, password=None, url_info=None, msg=None): |
---|
328 | """Send credentials as email. Input is the user for which credentials |
---|
329 | are sent and the password. Method returns True or False to indicate |
---|
330 | successful operation. |
---|
331 | """ |
---|
332 | subject = 'Your Kofa credentials' |
---|
333 | text = _(u"""Dear ${a}, |
---|
334 | |
---|
335 | ${b} |
---|
336 | Student Registration and Information Portal of |
---|
337 | ${c}. |
---|
338 | |
---|
339 | Your user name: ${d} |
---|
340 | Your password: ${e} |
---|
341 | ${f} |
---|
342 | |
---|
343 | Please remember your user name and keep |
---|
344 | your password secret! |
---|
345 | |
---|
346 | Please also note that passwords are case-sensitive. |
---|
347 | |
---|
348 | Regards |
---|
349 | """) |
---|
350 | config = grok.getSite()['configuration'] |
---|
351 | from_name = config.name_admin |
---|
352 | from_addr = config.email_admin |
---|
353 | rcpt_name = user.title |
---|
354 | rcpt_addr = user.email |
---|
355 | text = _(text, mapping={ |
---|
356 | 'a': rcpt_name, |
---|
357 | 'b': msg, |
---|
358 | 'c': config.name, |
---|
359 | 'd': user.name, |
---|
360 | 'e': password, |
---|
361 | 'f': url_info}) |
---|
362 | |
---|
363 | body = translate(text, 'waeup.kofa', |
---|
364 | target_language=self.PORTAL_LANGUAGE) |
---|
365 | return send_mail( |
---|
366 | from_name, from_addr, rcpt_name, rcpt_addr, |
---|
367 | subject, body, config) |
---|
368 | |
---|
369 | def informNewStudent(self, user, pw, login_url, rpw_url): |
---|
370 | """Inform student that a new student account has been created. |
---|
371 | """ |
---|
372 | subject = 'Your new Kofa student account' |
---|
373 | text = _(u"""Dear ${a}, |
---|
374 | |
---|
375 | Your student record of the Student Registration and Information Portal of |
---|
376 | ${b} has been created for you. |
---|
377 | |
---|
378 | Your user name: ${c} |
---|
379 | Your password: ${d} |
---|
380 | Login: ${e} |
---|
381 | |
---|
382 | Or request a new secure password here: ${f} |
---|
383 | |
---|
384 | Regards |
---|
385 | """) |
---|
386 | config = grok.getSite()['configuration'] |
---|
387 | from_name = config.name_admin |
---|
388 | from_addr = config.email_admin |
---|
389 | rcpt_name = user.title |
---|
390 | rcpt_addr = user.email |
---|
391 | |
---|
392 | text = _(text, mapping={ |
---|
393 | 'a': rcpt_name, |
---|
394 | 'b': config.name, |
---|
395 | 'c': user.name, |
---|
396 | 'd': pw, |
---|
397 | 'e': login_url, |
---|
398 | 'f': rpw_url |
---|
399 | }) |
---|
400 | body = translate(text, 'waeup.kofa', |
---|
401 | target_language=self.PORTAL_LANGUAGE) |
---|
402 | return send_mail( |
---|
403 | from_name, from_addr, rcpt_name, rcpt_addr, |
---|
404 | subject, body, config) |
---|
405 | |
---|
406 | |
---|
407 | def informApplicant(self, applicant): |
---|
408 | """Inform applicant that the application form was successfully |
---|
409 | submitted. |
---|
410 | """ |
---|
411 | if not getattr(applicant.__parent__, 'send_email', False): |
---|
412 | return |
---|
413 | subject = 'Your application form was successfully submitted' |
---|
414 | text = _(u"""Dear ${a}, |
---|
415 | |
---|
416 | Your application ${b} has been successfully submitted to ${c}. |
---|
417 | |
---|
418 | Regards |
---|
419 | """) |
---|
420 | config = grok.getSite()['configuration'] |
---|
421 | from_name = config.name_admin |
---|
422 | from_addr = config.email_admin |
---|
423 | rcpt_name = applicant.display_fullname |
---|
424 | rcpt_addr = applicant.email |
---|
425 | session = '%s/%s' % ( |
---|
426 | applicant.__parent__.year, applicant.__parent__.year+1) |
---|
427 | text = _(text, mapping={ |
---|
428 | 'a': rcpt_name, |
---|
429 | 'b': applicant.applicant_id, |
---|
430 | 'c': config.name, |
---|
431 | }) |
---|
432 | body = translate(text, 'waeup.kofa', |
---|
433 | target_language=self.PORTAL_LANGUAGE) |
---|
434 | return send_mail( |
---|
435 | from_name, from_addr, rcpt_name, rcpt_addr, |
---|
436 | subject, body, config) |
---|
437 | |
---|
438 | def inviteReferee(self, referee, applicant, url_info=None): |
---|
439 | """Send invitation email to referee. |
---|
440 | """ |
---|
441 | config = grok.getSite()['configuration'] |
---|
442 | subject = 'Request for referee report from %s' % config.name |
---|
443 | text = _(u"""Dear ${a}, |
---|
444 | |
---|
445 | The candidate with Id ${b} and name ${c} applied to |
---|
446 | the ${d} to study ${e} for the ${f} session. |
---|
447 | The candidate has listed you as referee. You are, therefore, required to, |
---|
448 | kindly, provide your referral remarks on or before ${g}. Please use the |
---|
449 | following form: |
---|
450 | |
---|
451 | ${h} |
---|
452 | |
---|
453 | Thank You |
---|
454 | |
---|
455 | The Secretary |
---|
456 | School of Postgraduate Studies |
---|
457 | ${d} |
---|
458 | """) |
---|
459 | from_name = config.name_admin |
---|
460 | from_addr = config.email_admin |
---|
461 | rcpt_name = referee.name |
---|
462 | rcpt_addr = referee.email |
---|
463 | session = '%s/%s' % ( |
---|
464 | applicant.__parent__.year, applicant.__parent__.year+1) |
---|
465 | text = _(text, mapping={ |
---|
466 | 'a': rcpt_name, |
---|
467 | 'b': applicant.applicant_id, |
---|
468 | 'c': applicant.display_fullname, |
---|
469 | 'd': config.name, |
---|
470 | 'e': applicant.course1.title, |
---|
471 | 'f': session, |
---|
472 | 'g': applicant.__parent__.enddate, |
---|
473 | 'h': url_info, |
---|
474 | }) |
---|
475 | |
---|
476 | body = translate(text, 'waeup.kofa', |
---|
477 | target_language=self.PORTAL_LANGUAGE) |
---|
478 | return send_mail( |
---|
479 | from_name, from_addr, rcpt_name, rcpt_addr, |
---|
480 | subject, body, config) |
---|
481 | |
---|
482 | def getPaymentItem(self, payment): |
---|
483 | """Return payment item. This method can be used to customize the |
---|
484 | `display_item` property attribute, e.g. in order to hide bed coordinates |
---|
485 | if maintenance fee is not paid. |
---|
486 | """ |
---|
487 | return payment.p_item |
---|
488 | |
---|
489 | def expensive_actions_allowed(self, type=None, request=None): |
---|
490 | """Tell, whether expensive actions are currently allowed. |
---|
491 | Check system load/health (or other external circumstances) and |
---|
492 | locally set values to see, whether expensive actions should be |
---|
493 | allowed (`True`) or better avoided (`False`). |
---|
494 | Use this to allow or forbid exports, report generations, or |
---|
495 | similar actions. |
---|
496 | """ |
---|
497 | max_values = self.SYSTEM_MAX_LOAD |
---|
498 | for (key, func) in ( |
---|
499 | ('swap-mem', psutil.swap_memory), |
---|
500 | ('virt-mem', psutil.virtual_memory), |
---|
501 | ): |
---|
502 | max_val = max_values.get(key, None) |
---|
503 | if max_val is None: |
---|
504 | continue |
---|
505 | mem_val = func() |
---|
506 | if isinstance(max_val, float): |
---|
507 | # percents |
---|
508 | if max_val < 0.0: |
---|
509 | max_val = 100.0 + max_val |
---|
510 | if mem_val.percent > max_val: |
---|
511 | return False |
---|
512 | else: |
---|
513 | # number of bytes |
---|
514 | if max_val < 0: |
---|
515 | max_val = mem_val.total + max_val |
---|
516 | if mem_val.used > max_val: |
---|
517 | return False |
---|
518 | return True |
---|
519 | |
---|
520 | def export_disabled_message(self): |
---|
521 | export_disabled_message = grok.getSite()[ |
---|
522 | 'configuration'].export_disabled_message |
---|
523 | if export_disabled_message: |
---|
524 | return export_disabled_message |
---|
525 | return None |
---|
526 | |
---|
527 | def format_float(self, value, prec): |
---|
528 | # >>> 4.6 * 100 |
---|
529 | # 459.99999999999994 |
---|
530 | value = decimal.Decimal(str(value)) |
---|
531 | # cut floating point value |
---|
532 | value = int(pow(10, prec)*value) / (1.0*pow(10, prec)) |
---|
533 | return '{:{width}.{prec}f}'.format(value, width=0, prec=prec) |
---|