1 | ## $Id: utils.py 14698 2017-06-21 22:12:04Z 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 | from copy import deepcopy |
---|
25 | from random import SystemRandom as r |
---|
26 | from zope.i18n import translate |
---|
27 | from waeup.kofa.interfaces import IKofaUtils |
---|
28 | from waeup.kofa.interfaces import MessageFactory as _ |
---|
29 | from waeup.kofa.smtp import send_mail as send_mail_internally |
---|
30 | from waeup.kofa.utils.helpers import get_sorted_preferred |
---|
31 | from waeup.kofa.utils.degrees import DEGREES_DICT |
---|
32 | |
---|
33 | |
---|
34 | def send_mail(from_name, from_addr, |
---|
35 | rcpt_name, rcpt_addr, |
---|
36 | subject, body, config): |
---|
37 | """Wrapper for the real SMTP functionality in :mod:`waeup.kofa.smtp`. |
---|
38 | |
---|
39 | Merely here to stay compatible with lots of calls to this place. |
---|
40 | """ |
---|
41 | mail_id = send_mail_internally( |
---|
42 | from_name, from_addr, rcpt_name, rcpt_addr, |
---|
43 | subject, body, config) |
---|
44 | return True |
---|
45 | |
---|
46 | |
---|
47 | #: A list of phone prefixes (order num, country, prefix). |
---|
48 | #: Items with same order num will be sorted alphabetically. |
---|
49 | #: The lower the order num, the higher the precedence. |
---|
50 | INT_PHONE_PREFIXES = [ |
---|
51 | (99, _('Germany'), '49'), |
---|
52 | (1, _('Nigeria'), '234'), |
---|
53 | (99, _('U.S.'), '1'), |
---|
54 | ] |
---|
55 | |
---|
56 | |
---|
57 | def sorted_phone_prefixes(data=INT_PHONE_PREFIXES, request=None): |
---|
58 | """Sorted tuples of phone prefixes. |
---|
59 | |
---|
60 | Ordered as shown above and formatted for use in select boxes. |
---|
61 | |
---|
62 | If request is given, we'll try to translate all country names in |
---|
63 | order to sort alphabetically correctly. |
---|
64 | |
---|
65 | XXX: This is a function (and not a constant) as different |
---|
66 | languages might give different orders. This is not tested yet. |
---|
67 | |
---|
68 | XXX: If we really want to use alphabetic ordering here, we might |
---|
69 | think about caching results of translations. |
---|
70 | """ |
---|
71 | if request is not None: |
---|
72 | data = [ |
---|
73 | (x, translate(y, context=request), z) |
---|
74 | for x, y, z in data] |
---|
75 | return tuple([ |
---|
76 | ('%s (+%s)' % (x[1], x[2]), '+%s' % x[2]) |
---|
77 | for x in sorted(data) |
---|
78 | ]) |
---|
79 | |
---|
80 | |
---|
81 | class KofaUtils(grok.GlobalUtility): |
---|
82 | """A collection of parameters and methods subject to customization. |
---|
83 | """ |
---|
84 | grok.implements(IKofaUtils) |
---|
85 | |
---|
86 | #: This the only place where we define the portal language |
---|
87 | #: which is used for the translation of system messages |
---|
88 | #: (e.g. object histories) pdf slips. |
---|
89 | PORTAL_LANGUAGE = 'en' |
---|
90 | |
---|
91 | DEGREES_DICT = DEGREES_DICT |
---|
92 | |
---|
93 | PREFERRED_LANGUAGES_DICT = { |
---|
94 | 'en': (1, u'English'), |
---|
95 | 'fr': (2, u'Français'), |
---|
96 | 'de': (3, u'Deutsch'), |
---|
97 | 'ha': (4, u'Hausa'), |
---|
98 | 'yo': (5, u'Yoruba'), |
---|
99 | 'ig': (6, u'Igbo'), |
---|
100 | } |
---|
101 | |
---|
102 | #: A function to return |
---|
103 | @classmethod |
---|
104 | def sorted_phone_prefixes(cls, data=INT_PHONE_PREFIXES, request=None): |
---|
105 | return sorted_phone_prefixes(data, request) |
---|
106 | |
---|
107 | EXAM_SUBJECTS_DICT = { |
---|
108 | 'math': 'Mathematics', |
---|
109 | 'computer_science': 'Computer Science', |
---|
110 | } |
---|
111 | |
---|
112 | #: Exam grades. The tuple is sorted as it should be displayed in |
---|
113 | #: select boxes. |
---|
114 | EXAM_GRADES = ( |
---|
115 | ('A', 'Best'), |
---|
116 | ('B', 'Better'), |
---|
117 | ('C', 'Good'), |
---|
118 | ) |
---|
119 | |
---|
120 | INST_TYPES_DICT = { |
---|
121 | 'none': '', |
---|
122 | 'faculty': 'Faculty of', |
---|
123 | 'department': 'Department of', |
---|
124 | 'school': 'School of', |
---|
125 | 'office': 'Office for', |
---|
126 | 'centre': 'Centre for', |
---|
127 | 'institute': 'Institute of', |
---|
128 | 'school_for': 'School for', |
---|
129 | 'college': 'College of', |
---|
130 | 'directorate': 'Directorate of', |
---|
131 | } |
---|
132 | |
---|
133 | STUDY_MODES_DICT = { |
---|
134 | 'transfer': 'Transfer', |
---|
135 | 'ug_ft': 'Undergraduate Full-Time', |
---|
136 | 'ug_pt': 'Undergraduate Part-Time', |
---|
137 | 'pg_ft': 'Postgraduate Full-Time', |
---|
138 | 'pg_pt': 'Postgraduate Part-Time', |
---|
139 | } |
---|
140 | |
---|
141 | ENABLE_SCORE_EDITING_GROUP_DICT = {} # not configured in base package |
---|
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 | 'transcript': 'Transcript Fee', |
---|
185 | 'late_registration': 'Late Course Registration Fee' |
---|
186 | } |
---|
187 | |
---|
188 | SELECTABLE_PAYMENT_CATEGORIES = deepcopy(PAYMENT_CATEGORIES) |
---|
189 | |
---|
190 | PREVIOUS_PAYMENT_CATEGORIES = deepcopy(SELECTABLE_PAYMENT_CATEGORIES) |
---|
191 | |
---|
192 | REPORTABLE_PAYMENT_CATEGORIES = { |
---|
193 | 'schoolfee': 'School Fee', |
---|
194 | 'clearance': 'Acceptance Fee', |
---|
195 | 'hostel_maintenance': 'Hostel Maintenance Fee', |
---|
196 | 'gown': 'Gown Hire Fee', |
---|
197 | } |
---|
198 | |
---|
199 | BALANCE_PAYMENT_CATEGORIES = { |
---|
200 | 'schoolfee': 'School Fee', |
---|
201 | } |
---|
202 | |
---|
203 | MODE_GROUPS = { |
---|
204 | 'All': ('all',), |
---|
205 | 'Undergraduate Full-Time': ('ug_ft',), |
---|
206 | 'Undergraduate Part-Time': ('ug_pt',), |
---|
207 | 'Postgraduate Full-Time': ('pg_ft',), |
---|
208 | 'Postgraduate Part-Time': ('pg_pt',), |
---|
209 | } |
---|
210 | |
---|
211 | SCORE_EDITING_GROUP_DICT = { |
---|
212 | 'All': ('all',), |
---|
213 | 'Undergraduate Full-Time': ('ug_ft',), |
---|
214 | 'Undergraduate Part-Time': ('ug_pt',), |
---|
215 | 'Postgraduate Full-Time': ('pg_ft',), |
---|
216 | 'Postgraduate Part-Time': ('pg_pt',), |
---|
217 | } |
---|
218 | |
---|
219 | VERDICTS_DICT = { |
---|
220 | '0': _('(not yet)'), |
---|
221 | 'A': 'Successful student', |
---|
222 | 'B': 'Student with carryover courses', |
---|
223 | 'C': 'Student on probation', |
---|
224 | } |
---|
225 | |
---|
226 | #: Set positive number for allowed max, negative for required min |
---|
227 | #: avail. |
---|
228 | #: Use integer for bytes value, float for percent |
---|
229 | #: value. `cpu-load`, of course, accepts float values only. |
---|
230 | #: `swap-mem` = Swap Memory, `virt-mem` = Virtual Memory, |
---|
231 | #: `cpu-load` = CPU load in percent. |
---|
232 | SYSTEM_MAX_LOAD = { |
---|
233 | 'swap-mem': None, |
---|
234 | 'virt-mem': None, |
---|
235 | 'cpu-load': 100.0, |
---|
236 | } |
---|
237 | |
---|
238 | def sendContactForm(self, from_name, from_addr, rcpt_name, rcpt_addr, |
---|
239 | from_username, usertype, portal, body, subject): |
---|
240 | """Send an email with data provided by forms. |
---|
241 | """ |
---|
242 | config = grok.getSite()['configuration'] |
---|
243 | text = _(u"""Fullname: ${a} |
---|
244 | User Id: ${b} |
---|
245 | User Type: ${c} |
---|
246 | Portal: ${d} |
---|
247 | |
---|
248 | ${e} |
---|
249 | """) |
---|
250 | text = _(text, mapping={ |
---|
251 | 'a': from_name, |
---|
252 | 'b': from_username, |
---|
253 | 'c': usertype, |
---|
254 | 'd': portal, |
---|
255 | 'e': body}) |
---|
256 | body = translate(text, 'waeup.kofa', |
---|
257 | target_language=self.PORTAL_LANGUAGE) |
---|
258 | if not (from_addr and rcpt_addr): |
---|
259 | return False |
---|
260 | return send_mail( |
---|
261 | from_name, from_addr, rcpt_name, rcpt_addr, |
---|
262 | subject, body, config) |
---|
263 | |
---|
264 | @property |
---|
265 | def tzinfo(self): |
---|
266 | """Time zone of the university. |
---|
267 | """ |
---|
268 | # For Nigeria: pytz.timezone('Africa/Lagos') |
---|
269 | # For Germany: pytz.timezone('Europe/Berlin') |
---|
270 | return pytz.utc |
---|
271 | |
---|
272 | def fullname(self, firstname, lastname, middlename=None): |
---|
273 | """Construct fullname. |
---|
274 | """ |
---|
275 | # We do not necessarily have the middlename attribute |
---|
276 | if middlename: |
---|
277 | name = '%s %s %s' % (firstname, middlename, lastname) |
---|
278 | else: |
---|
279 | name = '%s %s' % (firstname, lastname) |
---|
280 | if '<' in name: |
---|
281 | return 'XXX' |
---|
282 | return string.capwords( |
---|
283 | name.replace('-', ' - ')).replace(' - ', '-') |
---|
284 | |
---|
285 | def genPassword(self, length=8, chars=string.letters + string.digits): |
---|
286 | """Generate a random password. |
---|
287 | """ |
---|
288 | return ''.join([r().choice(chars) for i in range(length)]) |
---|
289 | |
---|
290 | def sendCredentials(self, user, password=None, url_info=None, msg=None): |
---|
291 | """Send credentials as email. Input is the user for which credentials |
---|
292 | are sent and the password. Method returns True or False to indicate |
---|
293 | successful operation. |
---|
294 | """ |
---|
295 | subject = 'Your Kofa credentials' |
---|
296 | text = _(u"""Dear ${a}, |
---|
297 | |
---|
298 | ${b} |
---|
299 | Student Registration and Information Portal of |
---|
300 | ${c}. |
---|
301 | |
---|
302 | Your user name: ${d} |
---|
303 | Your password: ${e} |
---|
304 | ${f} |
---|
305 | |
---|
306 | Please remember your user name and keep |
---|
307 | your password secret! |
---|
308 | |
---|
309 | Please also note that passwords are case-sensitive. |
---|
310 | |
---|
311 | Regards |
---|
312 | """) |
---|
313 | config = grok.getSite()['configuration'] |
---|
314 | from_name = config.name_admin |
---|
315 | from_addr = config.email_admin |
---|
316 | rcpt_name = user.title |
---|
317 | rcpt_addr = user.email |
---|
318 | text = _(text, mapping={ |
---|
319 | 'a': rcpt_name, |
---|
320 | 'b': msg, |
---|
321 | 'c': config.name, |
---|
322 | 'd': user.name, |
---|
323 | 'e': password, |
---|
324 | 'f': url_info}) |
---|
325 | |
---|
326 | body = translate(text, 'waeup.kofa', |
---|
327 | target_language=self.PORTAL_LANGUAGE) |
---|
328 | return send_mail( |
---|
329 | from_name, from_addr, rcpt_name, rcpt_addr, |
---|
330 | subject, body, config) |
---|
331 | |
---|
332 | def inviteReferee(self, referee, applicant, url_info=None): |
---|
333 | """Send invitation email to referee. |
---|
334 | """ |
---|
335 | config = grok.getSite()['configuration'] |
---|
336 | subject = 'Request for referee report from %s' % config.name |
---|
337 | text = _(u"""Dear ${a}, |
---|
338 | |
---|
339 | The candidate with Id ${b} and name ${c} applied to |
---|
340 | the ${d} to study ${e} for the ${f} session. |
---|
341 | The candidate has listed you as referee. You are thus required to kindly use |
---|
342 | the link below to provide your referral remarks on or before |
---|
343 | ${g}. |
---|
344 | |
---|
345 | ${h} |
---|
346 | |
---|
347 | Thank You |
---|
348 | |
---|
349 | The Secretary |
---|
350 | Post Graduate School |
---|
351 | ${d} |
---|
352 | """) |
---|
353 | from_name = config.name_admin |
---|
354 | from_addr = config.email_admin |
---|
355 | rcpt_name = referee.name |
---|
356 | rcpt_addr = referee.email |
---|
357 | session = '%s/%s' % ( |
---|
358 | applicant.__parent__.year, applicant.__parent__.year+1) |
---|
359 | text = _(text, mapping={ |
---|
360 | 'a': rcpt_name, |
---|
361 | 'b': applicant.applicant_id, |
---|
362 | 'c': applicant.display_fullname, |
---|
363 | 'd': config.name, |
---|
364 | 'e': applicant.course1.title, |
---|
365 | 'f': session, |
---|
366 | 'g': applicant.__parent__.enddate, |
---|
367 | 'h': url_info, |
---|
368 | }) |
---|
369 | |
---|
370 | body = translate(text, 'waeup.kofa', |
---|
371 | target_language=self.PORTAL_LANGUAGE) |
---|
372 | return send_mail( |
---|
373 | from_name, from_addr, rcpt_name, rcpt_addr, |
---|
374 | subject, body, config) |
---|
375 | |
---|
376 | def getPaymentItem(self, payment): |
---|
377 | """Return payment item. This method can be used to customize the |
---|
378 | `display_item` property attribute, e.g. in order to hide bed coordinates |
---|
379 | if maintenance fee is not paid. |
---|
380 | """ |
---|
381 | return payment.p_item |
---|
382 | |
---|
383 | def expensive_actions_allowed(self, type=None, request=None): |
---|
384 | """Tell, whether expensive actions are currently allowed. |
---|
385 | Check system load/health (or other external circumstances) and |
---|
386 | locally set values to see, whether expensive actions should be |
---|
387 | allowed (`True`) or better avoided (`False`). |
---|
388 | Use this to allow or forbid exports, report generations, or |
---|
389 | similar actions. |
---|
390 | """ |
---|
391 | max_values = self.SYSTEM_MAX_LOAD |
---|
392 | for (key, func) in ( |
---|
393 | ('swap-mem', psutil.swap_memory), |
---|
394 | ('virt-mem', psutil.virtual_memory), |
---|
395 | ): |
---|
396 | max_val = max_values.get(key, None) |
---|
397 | if max_val is None: |
---|
398 | continue |
---|
399 | mem_val = func() |
---|
400 | if isinstance(max_val, float): |
---|
401 | # percents |
---|
402 | if max_val < 0.0: |
---|
403 | max_val = 100.0 + max_val |
---|
404 | if mem_val.percent > max_val: |
---|
405 | return False |
---|
406 | else: |
---|
407 | # number of bytes |
---|
408 | if max_val < 0: |
---|
409 | max_val = mem_val.total + max_val |
---|
410 | if mem_val.used > max_val: |
---|
411 | return False |
---|
412 | return True |
---|
413 | |
---|
414 | def export_disabled_message(self): |
---|
415 | export_disabled_message = grok.getSite()[ |
---|
416 | 'configuration'].export_disabled_message |
---|
417 | if export_disabled_message: |
---|
418 | return export_disabled_message |
---|
419 | return None |
---|
420 | |
---|
421 | def format_float(self, value, prec): |
---|
422 | # cut floating point value |
---|
423 | value = int(pow(10, prec)*value) / (1.0*pow(10, prec)) |
---|
424 | return '{:{width}.{prec}f}'.format(value, width=0, prec=prec) |
---|