1 | ## $Id: utils.py 16812 2022-02-16 15:50:47Z 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 | 'ug_ft': 'Undergraduate Full-Time', |
---|
139 | 'ug_pt': 'Undergraduate Part-Time', |
---|
140 | 'pg_ft': 'Postgraduate Full-Time', |
---|
141 | 'pg_pt': 'Postgraduate Part-Time', |
---|
142 | } |
---|
143 | |
---|
144 | DISABLE_PAYMENT_GROUP_DICT = { |
---|
145 | 'sf_all': 'School Fee - All Students', |
---|
146 | } |
---|
147 | |
---|
148 | APP_CATS_DICT = { |
---|
149 | 'basic': 'Basic Application', |
---|
150 | 'no': 'no application', |
---|
151 | 'pg': 'Postgraduate', |
---|
152 | 'sandwich': 'Sandwich', |
---|
153 | 'cest': 'Part-Time, Diploma, Certificate' |
---|
154 | } |
---|
155 | |
---|
156 | SEMESTER_DICT = { |
---|
157 | 1: '1st Semester', |
---|
158 | 2: '2nd Semester', |
---|
159 | 3: 'Combined', |
---|
160 | 4: '1st Term', |
---|
161 | 5: '2nd Term', |
---|
162 | 6: '3rd Term', |
---|
163 | 9: 'N/A', |
---|
164 | 11: 'Module I', |
---|
165 | 12: 'Module II', |
---|
166 | 13: 'Module III', |
---|
167 | } |
---|
168 | |
---|
169 | COURSE_CATEGORY_DICT = { |
---|
170 | } |
---|
171 | |
---|
172 | SPECIAL_HANDLING_DICT = { |
---|
173 | 'regular': 'Regular Hostel', |
---|
174 | 'blocked': 'Blocked Hostel', |
---|
175 | 'pg': 'Postgraduate Hostel' |
---|
176 | } |
---|
177 | |
---|
178 | SPECIAL_APP_DICT = { |
---|
179 | 'transcript': 'Transcript Fee Payment', |
---|
180 | 'clearance': 'Acceptance Fee', |
---|
181 | } |
---|
182 | |
---|
183 | PAYMENT_CATEGORIES = { |
---|
184 | 'schoolfee': 'School Fee', |
---|
185 | 'clearance': 'Acceptance Fee', |
---|
186 | 'bed_allocation': 'Bed Allocation Fee', |
---|
187 | 'hostel_maintenance': 'Hostel Maintenance Fee', |
---|
188 | 'transfer': 'Transfer Fee', |
---|
189 | 'gown': 'Gown Hire Fee', |
---|
190 | 'application': 'Application Fee', |
---|
191 | 'app_balance': 'Application Fee Balance', |
---|
192 | 'transcript': 'Transcript Fee', |
---|
193 | 'late_registration': 'Late Course Registration Fee', |
---|
194 | 'combi': 'Combi Payment', |
---|
195 | } |
---|
196 | |
---|
197 | #: If PAYMENT_OPTIONS is empty, payment option fields won't show up. |
---|
198 | PAYMENT_OPTIONS = { |
---|
199 | #'credit_card': 'Credit Card', |
---|
200 | #'debit_card': 'Debit Card', |
---|
201 | } |
---|
202 | |
---|
203 | def selectable_payment_categories(self, student): |
---|
204 | return self.PAYMENT_CATEGORIES |
---|
205 | |
---|
206 | def selectable_payment_options(self, student): |
---|
207 | return self.PAYMENT_OPTIONS |
---|
208 | |
---|
209 | PREVIOUS_PAYMENT_CATEGORIES = deepcopy(PAYMENT_CATEGORIES) |
---|
210 | |
---|
211 | REPORTABLE_PAYMENT_CATEGORIES = { |
---|
212 | 'schoolfee': 'School Fee', |
---|
213 | 'clearance': 'Acceptance Fee', |
---|
214 | 'hostel_maintenance': 'Hostel Maintenance Fee', |
---|
215 | 'gown': 'Gown Hire Fee', |
---|
216 | } |
---|
217 | |
---|
218 | BALANCE_PAYMENT_CATEGORIES = { |
---|
219 | 'schoolfee': 'School Fee', |
---|
220 | } |
---|
221 | |
---|
222 | COMBI_PAYMENT_CATEGORIES = { |
---|
223 | 'gown': 'Gown Hire Fee', |
---|
224 | 'transcript': 'Transcript Fee', |
---|
225 | 'late_registration': 'Late Course Registration Fee', |
---|
226 | } |
---|
227 | |
---|
228 | MODE_GROUPS = { |
---|
229 | 'All': ('all',), |
---|
230 | 'Undergraduate Full-Time': ('ug_ft',), |
---|
231 | 'Undergraduate Part-Time': ('ug_pt',), |
---|
232 | 'Postgraduate Full-Time': ('pg_ft',), |
---|
233 | 'Postgraduate Part-Time': ('pg_pt',), |
---|
234 | } |
---|
235 | |
---|
236 | VERDICTS_DICT = { |
---|
237 | '0': _('(not yet)'), |
---|
238 | 'A': 'Successful student', |
---|
239 | 'B': 'Student with carryover courses', |
---|
240 | 'C': 'Student on probation', |
---|
241 | } |
---|
242 | |
---|
243 | #: Set positive number for allowed max, negative for required min |
---|
244 | #: avail. |
---|
245 | #: Use integer for bytes value, float for percent |
---|
246 | #: value. `cpu-load`, of course, accepts float values only. |
---|
247 | #: `swap-mem` = Swap Memory, `virt-mem` = Virtual Memory, |
---|
248 | #: `cpu-load` = CPU load in percent. |
---|
249 | SYSTEM_MAX_LOAD = { |
---|
250 | 'swap-mem': None, |
---|
251 | 'virt-mem': None, |
---|
252 | 'cpu-load': 100.0, |
---|
253 | } |
---|
254 | |
---|
255 | #: Maximum number of files listed in `finished` subfolder |
---|
256 | MAX_FILES = 100 |
---|
257 | |
---|
258 | #: Maximum size in Bytes of passport images in the applicants and |
---|
259 | #: students section |
---|
260 | MAX_PASSPORT_SIZE = 50 * 1024 |
---|
261 | |
---|
262 | #: Temporary passwords and parents password validity period |
---|
263 | TEMP_PASSWORD_MINUTES = 10 |
---|
264 | |
---|
265 | def sendContactForm(self, from_name, from_addr, rcpt_name, rcpt_addr, |
---|
266 | from_username, usertype, portal, body, subject, |
---|
267 | bcc_to=None): |
---|
268 | """Send an email with data provided by forms. |
---|
269 | """ |
---|
270 | config = grok.getSite()['configuration'] |
---|
271 | text = _(u"""${e} |
---|
272 | |
---|
273 | --- |
---|
274 | ${a} (id: ${b}) |
---|
275 | ${d} |
---|
276 | """) |
---|
277 | text = _(text, mapping={ |
---|
278 | 'a': from_name, |
---|
279 | 'b': from_username, |
---|
280 | 'c': usertype, |
---|
281 | 'd': portal, |
---|
282 | 'e': body}) |
---|
283 | body = translate(text, 'waeup.kofa', |
---|
284 | target_language=self.PORTAL_LANGUAGE) |
---|
285 | if not (from_addr and rcpt_addr): |
---|
286 | return False |
---|
287 | return send_mail( |
---|
288 | from_name, from_addr, rcpt_name, rcpt_addr, |
---|
289 | subject, body, config, None, bcc_to) |
---|
290 | |
---|
291 | def getUsers(self): |
---|
292 | users = sorted( |
---|
293 | grok.getSite()['users'].items(), key=lambda x: x[1].title) |
---|
294 | for key, val in users: |
---|
295 | yield(dict(name=key, val="%s (%s)" % (val.title, val.name))) |
---|
296 | |
---|
297 | @property |
---|
298 | def tzinfo(self): |
---|
299 | """Time zone of the university. |
---|
300 | """ |
---|
301 | # For Nigeria: pytz.timezone('Africa/Lagos') |
---|
302 | # For Germany: pytz.timezone('Europe/Berlin') |
---|
303 | return pytz.utc |
---|
304 | |
---|
305 | def fullname(self, firstname, lastname, middlename=None): |
---|
306 | """Construct fullname. |
---|
307 | """ |
---|
308 | # We do not necessarily have the middlename attribute |
---|
309 | if middlename: |
---|
310 | name = '%s %s %s' % (firstname, middlename, lastname) |
---|
311 | else: |
---|
312 | name = '%s %s' % (firstname, lastname) |
---|
313 | if '<' in name: |
---|
314 | return 'XXX' |
---|
315 | return string.capwords( |
---|
316 | name.replace('-', ' - ')).replace(' - ', '-') |
---|
317 | |
---|
318 | def genPassword(self, length=4, chars=string.letters + string.digits): |
---|
319 | """Generate a random password. |
---|
320 | """ |
---|
321 | return ''.join([ |
---|
322 | r().choice(string.uppercase) + |
---|
323 | r().choice(string.lowercase) + |
---|
324 | r().choice(string.digits) for i in range(length)]) |
---|
325 | |
---|
326 | def sendCredentials(self, user, password=None, url_info=None, msg=None): |
---|
327 | """Send credentials as email. Input is the user for which credentials |
---|
328 | are sent and the password. Method returns True or False to indicate |
---|
329 | successful operation. |
---|
330 | """ |
---|
331 | subject = 'Your Kofa credentials' |
---|
332 | text = _(u"""Dear ${a}, |
---|
333 | |
---|
334 | ${b} |
---|
335 | Student Registration and Information Portal of |
---|
336 | ${c}. |
---|
337 | |
---|
338 | Your user name: ${d} |
---|
339 | Your password: ${e} |
---|
340 | ${f} |
---|
341 | |
---|
342 | Please remember your user name and keep |
---|
343 | your password secret! |
---|
344 | |
---|
345 | Please also note that passwords are case-sensitive. |
---|
346 | |
---|
347 | Regards |
---|
348 | """) |
---|
349 | config = grok.getSite()['configuration'] |
---|
350 | from_name = config.name_admin |
---|
351 | from_addr = config.email_admin |
---|
352 | rcpt_name = user.title |
---|
353 | rcpt_addr = user.email |
---|
354 | text = _(text, mapping={ |
---|
355 | 'a': rcpt_name, |
---|
356 | 'b': msg, |
---|
357 | 'c': config.name, |
---|
358 | 'd': user.name, |
---|
359 | 'e': password, |
---|
360 | 'f': url_info}) |
---|
361 | |
---|
362 | body = translate(text, 'waeup.kofa', |
---|
363 | target_language=self.PORTAL_LANGUAGE) |
---|
364 | return send_mail( |
---|
365 | from_name, from_addr, rcpt_name, rcpt_addr, |
---|
366 | subject, body, config) |
---|
367 | |
---|
368 | def informNewStudent(self, user, pw, login_url, rpw_url): |
---|
369 | """Inform student that a new student account has been created. |
---|
370 | """ |
---|
371 | subject = 'Your new Kofa student account' |
---|
372 | text = _(u"""Dear ${a}, |
---|
373 | |
---|
374 | Your student record of the Student Registration and Information Portal of |
---|
375 | ${b} has been created for you. |
---|
376 | |
---|
377 | Your user name: ${c} |
---|
378 | Your password: ${d} |
---|
379 | Login: ${e} |
---|
380 | |
---|
381 | Or request a new secure password here: ${f} |
---|
382 | |
---|
383 | Regards |
---|
384 | """) |
---|
385 | config = grok.getSite()['configuration'] |
---|
386 | from_name = config.name_admin |
---|
387 | from_addr = config.email_admin |
---|
388 | rcpt_name = user.title |
---|
389 | rcpt_addr = user.email |
---|
390 | |
---|
391 | text = _(text, mapping={ |
---|
392 | 'a': rcpt_name, |
---|
393 | 'b': config.name, |
---|
394 | 'c': user.name, |
---|
395 | 'd': pw, |
---|
396 | 'e': login_url, |
---|
397 | 'f': rpw_url |
---|
398 | }) |
---|
399 | body = translate(text, 'waeup.kofa', |
---|
400 | target_language=self.PORTAL_LANGUAGE) |
---|
401 | return send_mail( |
---|
402 | from_name, from_addr, rcpt_name, rcpt_addr, |
---|
403 | subject, body, config) |
---|
404 | |
---|
405 | |
---|
406 | def inviteReferee(self, referee, applicant, url_info=None): |
---|
407 | """Send invitation email to referee. |
---|
408 | """ |
---|
409 | config = grok.getSite()['configuration'] |
---|
410 | subject = 'Request for referee report from %s' % config.name |
---|
411 | text = _(u"""Dear ${a}, |
---|
412 | |
---|
413 | The candidate with Id ${b} and name ${c} applied to |
---|
414 | the ${d} to study ${e} for the ${f} session. |
---|
415 | The candidate has listed you as referee. You are, therefore, required to, |
---|
416 | kindly, provide your referral remarks on or before ${g}. Please use the |
---|
417 | following form: |
---|
418 | |
---|
419 | ${h} |
---|
420 | |
---|
421 | Thank You |
---|
422 | |
---|
423 | The Secretary |
---|
424 | School of Postgraduate Studies |
---|
425 | ${d} |
---|
426 | """) |
---|
427 | from_name = config.name_admin |
---|
428 | from_addr = config.email_admin |
---|
429 | rcpt_name = referee.name |
---|
430 | rcpt_addr = referee.email |
---|
431 | session = '%s/%s' % ( |
---|
432 | applicant.__parent__.year, applicant.__parent__.year+1) |
---|
433 | text = _(text, mapping={ |
---|
434 | 'a': rcpt_name, |
---|
435 | 'b': applicant.applicant_id, |
---|
436 | 'c': applicant.display_fullname, |
---|
437 | 'd': config.name, |
---|
438 | 'e': applicant.course1.title, |
---|
439 | 'f': session, |
---|
440 | 'g': applicant.__parent__.enddate, |
---|
441 | 'h': url_info, |
---|
442 | }) |
---|
443 | |
---|
444 | body = translate(text, 'waeup.kofa', |
---|
445 | target_language=self.PORTAL_LANGUAGE) |
---|
446 | return send_mail( |
---|
447 | from_name, from_addr, rcpt_name, rcpt_addr, |
---|
448 | subject, body, config) |
---|
449 | |
---|
450 | def getPaymentItem(self, payment): |
---|
451 | """Return payment item. This method can be used to customize the |
---|
452 | `display_item` property attribute, e.g. in order to hide bed coordinates |
---|
453 | if maintenance fee is not paid. |
---|
454 | """ |
---|
455 | return payment.p_item |
---|
456 | |
---|
457 | def expensive_actions_allowed(self, type=None, request=None): |
---|
458 | """Tell, whether expensive actions are currently allowed. |
---|
459 | Check system load/health (or other external circumstances) and |
---|
460 | locally set values to see, whether expensive actions should be |
---|
461 | allowed (`True`) or better avoided (`False`). |
---|
462 | Use this to allow or forbid exports, report generations, or |
---|
463 | similar actions. |
---|
464 | """ |
---|
465 | max_values = self.SYSTEM_MAX_LOAD |
---|
466 | for (key, func) in ( |
---|
467 | ('swap-mem', psutil.swap_memory), |
---|
468 | ('virt-mem', psutil.virtual_memory), |
---|
469 | ): |
---|
470 | max_val = max_values.get(key, None) |
---|
471 | if max_val is None: |
---|
472 | continue |
---|
473 | mem_val = func() |
---|
474 | if isinstance(max_val, float): |
---|
475 | # percents |
---|
476 | if max_val < 0.0: |
---|
477 | max_val = 100.0 + max_val |
---|
478 | if mem_val.percent > max_val: |
---|
479 | return False |
---|
480 | else: |
---|
481 | # number of bytes |
---|
482 | if max_val < 0: |
---|
483 | max_val = mem_val.total + max_val |
---|
484 | if mem_val.used > max_val: |
---|
485 | return False |
---|
486 | return True |
---|
487 | |
---|
488 | def export_disabled_message(self): |
---|
489 | export_disabled_message = grok.getSite()[ |
---|
490 | 'configuration'].export_disabled_message |
---|
491 | if export_disabled_message: |
---|
492 | return export_disabled_message |
---|
493 | return None |
---|
494 | |
---|
495 | def format_float(self, value, prec): |
---|
496 | # >>> 4.6 * 100 |
---|
497 | # 459.99999999999994 |
---|
498 | value = decimal.Decimal(str(value)) |
---|
499 | # cut floating point value |
---|
500 | value = int(pow(10, prec)*value) / (1.0*pow(10, prec)) |
---|
501 | return '{:{width}.{prec}f}'.format(value, width=0, prec=prec) |
---|