1 | ## $Id: utils.py 16299 2020-11-04 17:52:22Z 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 | def selectable_payment_categories(self, student): |
---|
191 | return self.PAYMENT_CATEGORIES |
---|
192 | |
---|
193 | PREVIOUS_PAYMENT_CATEGORIES = deepcopy(PAYMENT_CATEGORIES) |
---|
194 | |
---|
195 | REPORTABLE_PAYMENT_CATEGORIES = { |
---|
196 | 'schoolfee': 'School Fee', |
---|
197 | 'clearance': 'Acceptance Fee', |
---|
198 | 'hostel_maintenance': 'Hostel Maintenance Fee', |
---|
199 | 'gown': 'Gown Hire Fee', |
---|
200 | } |
---|
201 | |
---|
202 | BALANCE_PAYMENT_CATEGORIES = { |
---|
203 | 'schoolfee': 'School Fee', |
---|
204 | } |
---|
205 | |
---|
206 | COMBI_PAYMENT_CATEGORIES = { |
---|
207 | 'gown': 'Gown Hire Fee', |
---|
208 | 'transcript': 'Transcript Fee', |
---|
209 | 'late_registration': 'Late Course Registration Fee', |
---|
210 | } |
---|
211 | |
---|
212 | MODE_GROUPS = { |
---|
213 | 'All': ('all',), |
---|
214 | 'Undergraduate Full-Time': ('ug_ft',), |
---|
215 | 'Undergraduate Part-Time': ('ug_pt',), |
---|
216 | 'Postgraduate Full-Time': ('pg_ft',), |
---|
217 | 'Postgraduate Part-Time': ('pg_pt',), |
---|
218 | } |
---|
219 | |
---|
220 | VERDICTS_DICT = { |
---|
221 | '0': _('(not yet)'), |
---|
222 | 'A': 'Successful student', |
---|
223 | 'B': 'Student with carryover courses', |
---|
224 | 'C': 'Student on probation', |
---|
225 | } |
---|
226 | |
---|
227 | #: Set positive number for allowed max, negative for required min |
---|
228 | #: avail. |
---|
229 | #: Use integer for bytes value, float for percent |
---|
230 | #: value. `cpu-load`, of course, accepts float values only. |
---|
231 | #: `swap-mem` = Swap Memory, `virt-mem` = Virtual Memory, |
---|
232 | #: `cpu-load` = CPU load in percent. |
---|
233 | SYSTEM_MAX_LOAD = { |
---|
234 | 'swap-mem': None, |
---|
235 | 'virt-mem': None, |
---|
236 | 'cpu-load': 100.0, |
---|
237 | } |
---|
238 | |
---|
239 | #: Maximum number of files listed in `finished` subfolder |
---|
240 | MAX_FILES = 100 |
---|
241 | |
---|
242 | #: Maximum size in Bytes of passport images in the applicants and |
---|
243 | #: students section |
---|
244 | MAX_PASSPORT_SIZE = 50 * 1024 |
---|
245 | |
---|
246 | #: Temporary passwords and parents password validity period |
---|
247 | TEMP_PASSWORD_MINUTES = 10 |
---|
248 | |
---|
249 | def sendContactForm(self, from_name, from_addr, rcpt_name, rcpt_addr, |
---|
250 | from_username, usertype, portal, body, subject, |
---|
251 | bcc_to=None): |
---|
252 | """Send an email with data provided by forms. |
---|
253 | """ |
---|
254 | config = grok.getSite()['configuration'] |
---|
255 | text = _(u"""${e} |
---|
256 | |
---|
257 | --- |
---|
258 | ${a} (id: ${b}) |
---|
259 | ${d} |
---|
260 | """) |
---|
261 | text = _(text, mapping={ |
---|
262 | 'a': from_name, |
---|
263 | 'b': from_username, |
---|
264 | 'c': usertype, |
---|
265 | 'd': portal, |
---|
266 | 'e': body}) |
---|
267 | body = translate(text, 'waeup.kofa', |
---|
268 | target_language=self.PORTAL_LANGUAGE) |
---|
269 | if not (from_addr and rcpt_addr): |
---|
270 | return False |
---|
271 | return send_mail( |
---|
272 | from_name, from_addr, rcpt_name, rcpt_addr, |
---|
273 | subject, body, config, None, bcc_to) |
---|
274 | |
---|
275 | def getUsers(self): |
---|
276 | users = sorted( |
---|
277 | grok.getSite()['users'].items(), key=lambda x: x[1].title) |
---|
278 | for key, val in users: |
---|
279 | yield(dict(name=key, val="%s (%s)" % (val.title, val.name))) |
---|
280 | |
---|
281 | @property |
---|
282 | def tzinfo(self): |
---|
283 | """Time zone of the university. |
---|
284 | """ |
---|
285 | # For Nigeria: pytz.timezone('Africa/Lagos') |
---|
286 | # For Germany: pytz.timezone('Europe/Berlin') |
---|
287 | return pytz.utc |
---|
288 | |
---|
289 | def fullname(self, firstname, lastname, middlename=None): |
---|
290 | """Construct fullname. |
---|
291 | """ |
---|
292 | # We do not necessarily have the middlename attribute |
---|
293 | if middlename: |
---|
294 | name = '%s %s %s' % (firstname, middlename, lastname) |
---|
295 | else: |
---|
296 | name = '%s %s' % (firstname, lastname) |
---|
297 | if '<' in name: |
---|
298 | return 'XXX' |
---|
299 | return string.capwords( |
---|
300 | name.replace('-', ' - ')).replace(' - ', '-') |
---|
301 | |
---|
302 | def genPassword(self, length=4, chars=string.letters + string.digits): |
---|
303 | """Generate a random password. |
---|
304 | """ |
---|
305 | return ''.join([ |
---|
306 | r().choice(string.uppercase) + |
---|
307 | r().choice(string.lowercase) + |
---|
308 | r().choice(string.digits) for i in range(length)]) |
---|
309 | |
---|
310 | def sendCredentials(self, user, password=None, url_info=None, msg=None): |
---|
311 | """Send credentials as email. Input is the user for which credentials |
---|
312 | are sent and the password. Method returns True or False to indicate |
---|
313 | successful operation. |
---|
314 | """ |
---|
315 | subject = 'Your Kofa credentials' |
---|
316 | text = _(u"""Dear ${a}, |
---|
317 | |
---|
318 | ${b} |
---|
319 | Student Registration and Information Portal of |
---|
320 | ${c}. |
---|
321 | |
---|
322 | Your user name: ${d} |
---|
323 | Your password: ${e} |
---|
324 | ${f} |
---|
325 | |
---|
326 | Please remember your user name and keep |
---|
327 | your password secret! |
---|
328 | |
---|
329 | Please also note that passwords are case-sensitive. |
---|
330 | |
---|
331 | Regards |
---|
332 | """) |
---|
333 | config = grok.getSite()['configuration'] |
---|
334 | from_name = config.name_admin |
---|
335 | from_addr = config.email_admin |
---|
336 | rcpt_name = user.title |
---|
337 | rcpt_addr = user.email |
---|
338 | text = _(text, mapping={ |
---|
339 | 'a': rcpt_name, |
---|
340 | 'b': msg, |
---|
341 | 'c': config.name, |
---|
342 | 'd': user.name, |
---|
343 | 'e': password, |
---|
344 | 'f': url_info}) |
---|
345 | |
---|
346 | body = translate(text, 'waeup.kofa', |
---|
347 | target_language=self.PORTAL_LANGUAGE) |
---|
348 | return send_mail( |
---|
349 | from_name, from_addr, rcpt_name, rcpt_addr, |
---|
350 | subject, body, config) |
---|
351 | |
---|
352 | def inviteReferee(self, referee, applicant, url_info=None): |
---|
353 | """Send invitation email to referee. |
---|
354 | """ |
---|
355 | config = grok.getSite()['configuration'] |
---|
356 | subject = 'Request for referee report from %s' % config.name |
---|
357 | text = _(u"""Dear ${a}, |
---|
358 | |
---|
359 | The candidate with Id ${b} and name ${c} applied to |
---|
360 | the ${d} to study ${e} for the ${f} session. |
---|
361 | The candidate has listed you as referee. You are thus required to kindly use |
---|
362 | the link below to provide your referral remarks on or before |
---|
363 | ${g}. |
---|
364 | |
---|
365 | ${h} |
---|
366 | |
---|
367 | Thank You |
---|
368 | |
---|
369 | The Secretary |
---|
370 | Post Graduate School |
---|
371 | ${d} |
---|
372 | """) |
---|
373 | from_name = config.name_admin |
---|
374 | from_addr = config.email_admin |
---|
375 | rcpt_name = referee.name |
---|
376 | rcpt_addr = referee.email |
---|
377 | session = '%s/%s' % ( |
---|
378 | applicant.__parent__.year, applicant.__parent__.year+1) |
---|
379 | text = _(text, mapping={ |
---|
380 | 'a': rcpt_name, |
---|
381 | 'b': applicant.applicant_id, |
---|
382 | 'c': applicant.display_fullname, |
---|
383 | 'd': config.name, |
---|
384 | 'e': applicant.course1.title, |
---|
385 | 'f': session, |
---|
386 | 'g': applicant.__parent__.enddate, |
---|
387 | 'h': url_info, |
---|
388 | }) |
---|
389 | |
---|
390 | body = translate(text, 'waeup.kofa', |
---|
391 | target_language=self.PORTAL_LANGUAGE) |
---|
392 | return send_mail( |
---|
393 | from_name, from_addr, rcpt_name, rcpt_addr, |
---|
394 | subject, body, config) |
---|
395 | |
---|
396 | def getPaymentItem(self, payment): |
---|
397 | """Return payment item. This method can be used to customize the |
---|
398 | `display_item` property attribute, e.g. in order to hide bed coordinates |
---|
399 | if maintenance fee is not paid. |
---|
400 | """ |
---|
401 | return payment.p_item |
---|
402 | |
---|
403 | def expensive_actions_allowed(self, type=None, request=None): |
---|
404 | """Tell, whether expensive actions are currently allowed. |
---|
405 | Check system load/health (or other external circumstances) and |
---|
406 | locally set values to see, whether expensive actions should be |
---|
407 | allowed (`True`) or better avoided (`False`). |
---|
408 | Use this to allow or forbid exports, report generations, or |
---|
409 | similar actions. |
---|
410 | """ |
---|
411 | max_values = self.SYSTEM_MAX_LOAD |
---|
412 | for (key, func) in ( |
---|
413 | ('swap-mem', psutil.swap_memory), |
---|
414 | ('virt-mem', psutil.virtual_memory), |
---|
415 | ): |
---|
416 | max_val = max_values.get(key, None) |
---|
417 | if max_val is None: |
---|
418 | continue |
---|
419 | mem_val = func() |
---|
420 | if isinstance(max_val, float): |
---|
421 | # percents |
---|
422 | if max_val < 0.0: |
---|
423 | max_val = 100.0 + max_val |
---|
424 | if mem_val.percent > max_val: |
---|
425 | return False |
---|
426 | else: |
---|
427 | # number of bytes |
---|
428 | if max_val < 0: |
---|
429 | max_val = mem_val.total + max_val |
---|
430 | if mem_val.used > max_val: |
---|
431 | return False |
---|
432 | return True |
---|
433 | |
---|
434 | def export_disabled_message(self): |
---|
435 | export_disabled_message = grok.getSite()[ |
---|
436 | 'configuration'].export_disabled_message |
---|
437 | if export_disabled_message: |
---|
438 | return export_disabled_message |
---|
439 | return None |
---|
440 | |
---|
441 | def format_float(self, value, prec): |
---|
442 | # >>> 4.6 * 100 |
---|
443 | # 459.99999999999994 |
---|
444 | value = decimal.Decimal(str(value)) |
---|
445 | # cut floating point value |
---|
446 | value = int(pow(10, prec)*value) / (1.0*pow(10, prec)) |
---|
447 | return '{:{width}.{prec}f}'.format(value, width=0, prec=prec) |
---|