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