source: main/waeup.kofa/trunk/src/waeup/kofa/utils/utils.py @ 13124

Last change on this file since 13124 was 13124, checked in by Henrik Bettermann, 10 years ago

More docs.

  • Property svn:keywords set to Id
File size: 10.6 KB
RevLine 
[7358]1## $Id: utils.py 13124 2015-07-01 16:24:58Z 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##
[7819]18"""General helper utilities for Kofa.
[7358]19"""
20import grok
[11815]21import psutil
[7365]22import string
[8181]23import pytz
[9866]24from copy import deepcopy
[8181]25from random import SystemRandom as r
[7734]26from zope.i18n import translate
[7819]27from waeup.kofa.interfaces import IKofaUtils
[7811]28from waeup.kofa.interfaces import MessageFactory as _
29from waeup.kofa.smtp import send_mail as send_mail_internally
[7969]30from waeup.kofa.utils.helpers import get_sorted_preferred
[7358]31
[11814]32
33def send_mail(from_name, from_addr,
34              rcpt_name, rcpt_addr,
35              subject, body, config):
[7811]36    """Wrapper for the real SMTP functionality in :mod:`waeup.kofa.smtp`.
[7382]37
[7471]38    Merely here to stay compatible with lots of calls to this place.
[7400]39    """
[7471]40    mail_id = send_mail_internally(
41        from_name, from_addr, rcpt_name, rcpt_addr,
42        subject, body, config)
[7399]43    return True
44
[11814]45
[7874]46#: A list of phone prefixes (order num, country, prefix).
47#: Items with same order num will be sorted alphabetically.
48#: The lower the order num, the higher the precedence.
49INT_PHONE_PREFIXES = [
50    (99, _('Germany'), '49'),
[11814]51    (1, _('Nigeria'), '234'),
[7874]52    (99, _('U.S.'), '1'),
53    ]
54
[11814]55
56def sorted_phone_prefixes(data=INT_PHONE_PREFIXES, request=None):
[7874]57    """Sorted tuples of phone prefixes.
58
59    Ordered as shown above and formatted for use in select boxes.
60
61    If request is given, we'll try to translate all country names in
62    order to sort alphabetically correctly.
63
64    XXX: This is a function (and not a constant) as different
65    languages might give different orders. This is not tested yet.
66
67    XXX: If we really want to use alphabetic ordering here, we might
68    think about caching results of translations.
69    """
70    if request is not None:
71        data = [
72            (x, translate(y, context=request), z)
73            for x, y, z in data]
74    return tuple([
[11814]75        ('%s (+%s)' % (x[1], x[2]), '+%s' % x[2])
[7874]76        for x in sorted(data)
77        ])
78
[11814]79
[7831]80class KofaUtils(grok.GlobalUtility):
[7678]81    """A collection of parameters and methods subject to customization.
[7358]82    """
[7831]83    grok.implements(IKofaUtils)
[7678]84    # This the only place where we define the portal language
85    # which is used for the translation of system messages
86    # (e.g. object histories).
[7744]87    PORTAL_LANGUAGE = 'en'
[7358]88
[7701]89    PREFERRED_LANGUAGES_DICT = {
[11814]90        'en': (1, u'English'),
91        'fr': (2, u'Français'),
92        'de': (3, u'Deutsch'),
93        'ha': (4, u'Hausa'),
94        'yo': (5, u'Yoruba'),
95        'ig': (6, u'Igbo'),
[7701]96        }
97
[7874]98    #: A function to return
99    @classmethod
100    def sorted_phone_prefixes(cls, data=INT_PHONE_PREFIXES, request=None):
101        return sorted_phone_prefixes(data, request)
[7871]102
[7841]103    EXAM_SUBJECTS_DICT = {
[7843]104        'math': 'Mathematics',
105        'computer_science': 'Computer Science',
[7841]106        }
[7836]107
[7917]108    #: Exam grades. The tuple is sorted as it should be displayed in
109    #: select boxes.
110    EXAM_GRADES = (
111        ('A', 'Best'),
112        ('B', 'Better'),
113        ('C', 'Good'),
114        )
[7836]115
[7841]116    INST_TYPES_DICT = {
[8084]117        'none': '',
[7681]118        'faculty': 'Faculty of',
119        'department': 'Department of',
120        'school': 'School of',
121        'office': 'Office for',
122        'centre': 'Centre for',
123        'institute': 'Institute of',
124        'school_for': 'School for',
[8084]125        'college': 'College of',
[10302]126        'directorate': 'Directorate of',
[7681]127        }
128
[7841]129    STUDY_MODES_DICT = {
[9131]130        'transfer': 'Transfer',
[7843]131        'ug_ft': 'Undergraduate Full-Time',
132        'ug_pt': 'Undergraduate Part-Time',
[7993]133        'pg_ft': 'Postgraduate Full-Time',
134        'pg_pt': 'Postgraduate Part-Time',
[7681]135        }
136
[11451]137    DISABLE_PAYMENT_GROUP_DICT = {
138        'sf_all': 'School Fee - All Students',
139        }
140
[7841]141    APP_CATS_DICT = {
[7843]142        'basic': 'Basic Application',
[7681]143        'no': 'no application',
144        'pg': 'Postgraduate',
145        'sandwich': 'Sandwich',
146        'cest': 'Part-Time, Diploma, Certificate'
147        }
148
[7841]149    SEMESTER_DICT = {
[10437]150        1: '1st Semester',
151        2: '2nd Semester',
[7681]152        3: 'Combined',
153        9: 'N/A'
154        }
155
[9400]156    SPECIAL_HANDLING_DICT = {
157        'regular': 'Regular Hostel',
158        'blocked': 'Blocked Hostel',
[10831]159        'pg': 'Postgraduate Hostel'
[9400]160        }
161
[10831]162    SPECIAL_APP_DICT = {
163        'transcript': 'Transcript Fee Payment',
[11575]164        'clearance': 'Acceptance Fee',
[10831]165        }
166
[9405]167    PAYMENT_CATEGORIES = {
168        'schoolfee': 'School Fee',
169        'clearance': 'Acceptance Fee',
170        'bed_allocation': 'Bed Allocation Fee',
171        'hostel_maintenance': 'Hostel Maintenance Fee',
172        'transfer': 'Transfer Fee',
173        'gown': 'Gown Hire Fee',
[9866]174        'application': 'Application Fee',
[10449]175        'transcript': 'Transcript Fee',
[13031]176        'late_registration': 'Late Course Registration Fee'
[9405]177        }
178
[9866]179    SELECTABLE_PAYMENT_CATEGORIES = deepcopy(PAYMENT_CATEGORIES)
[9730]180
[9866]181    PREVIOUS_PAYMENT_CATEGORIES = deepcopy(SELECTABLE_PAYMENT_CATEGORIES)
[9862]182
[12564]183    REPORTABLE_PAYMENT_CATEGORIES = {
184        'schoolfee': 'School Fee',
185        'clearance': 'Acceptance Fee',
186        'hostel_maintenance': 'Hostel Maintenance Fee',
187        'gown': 'Gown Hire Fee',
188        }
189
[9868]190    BALANCE_PAYMENT_CATEGORIES = {
[9867]191        'schoolfee': 'School Fee',
192        }
[9864]193
[9649]194    MODE_GROUPS = {
[11814]195        'All': ('all',),
196        'Undergraduate Full-Time': ('ug_ft',),
197        'Undergraduate Part-Time': ('ug_pt',),
198        'Postgraduate Full-Time': ('pg_ft',),
199        'Postgraduate Part-Time': ('pg_pt',),
[9649]200        }
201
[11800]202    #: Set positive number for allowed max, negative for required min
203    #: avail.
204    #:
205    #: Use integer for bytes value, float for percent
206    #: value. `cpu-load`, of course, accepts float values only.
207    #: `swap-mem` = Swap Memory, `virt-mem` = Virtual Memory,
[11969]208    #: `cpu-load` = CPU load in percent.
[11800]209    SYSTEM_MAX_LOAD = {
210        'swap-mem': None,
211        'virt-mem': None,
212        'cpu-load': 100.0,
213        }
214
[11814]215    def sendContactForm(self, from_name, from_addr, rcpt_name, rcpt_addr,
216                        from_username, usertype, portal, body, subject):
[7358]217        """Send an email with data provided by forms.
218        """
219        config = grok.getSite()['configuration']
[7734]220        text = _(u"""Fullname: ${a}
221User Id: ${b}
222User Type: ${c}
223Portal: ${d}
[7358]224
[7734]225${e}
226""")
[11814]227        text = _(text, mapping={
228            'a': from_name,
229            'b': from_username,
230            'c': usertype,
231            'd': portal,
232            'e': body})
[7811]233        body = translate(text, 'waeup.kofa',
[7734]234            target_language=self.PORTAL_LANGUAGE)
[8436]235        if not (from_addr and rcpt_addr):
236            return False
[7400]237        return send_mail(
[11814]238            from_name, from_addr, rcpt_name, rcpt_addr,
239            subject, body, config)
[7359]240
[8181]241    @property
242    def tzinfo(self):
[13124]243        """Time zone of the university.
244        """
[8181]245        # For Nigeria: pytz.timezone('Africa/Lagos')
[9543]246        # For Germany: pytz.timezone('Europe/Berlin')
[8181]247        return pytz.utc
248
[11814]249    def fullname(self, firstname, lastname, middlename=None):
[13124]250        """Construct fullname.
[7477]251        """
[7359]252        # We do not necessarily have the middlename attribute
253        if middlename:
[8603]254            name = '%s %s %s' % (firstname, middlename, lastname)
[7359]255        else:
[8603]256            name = '%s %s' % (firstname, lastname)
[11814]257        return string.capwords(
258            name.replace('-', ' - ')).replace(' - ', '-')
[7365]259
260    def genPassword(self, length=8, chars=string.letters + string.digits):
[7477]261        """Generate a random password.
262        """
[7365]263        return ''.join([r().choice(chars) for i in range(length)])
264
[8853]265    def sendCredentials(self, user, password=None, url_info=None, msg=None):
[13124]266        """Send credentials as email. Input is the user for which credentials
267        are sent and the password. Method returns True or False to indicate
268        successful operation.
[7365]269        """
[7819]270        subject = 'Your Kofa credentials'
[7734]271        text = _(u"""Dear ${a},
[7365]272
[7734]273${b}
[7365]274Student Registration and Information Portal of
[7734]275${c}.
[7365]276
[7734]277Your user name: ${d}
278Your password: ${e}
[8853]279${f}
[7365]280
281Please remember your user name and keep
282your password secret!
283
[7382]284Please also note that passwords are case-sensitive.
285
[7365]286Regards
[7734]287""")
[7399]288        config = grok.getSite()['configuration']
289        from_name = config.name_admin
[7402]290        from_addr = config.email_admin
[7407]291        rcpt_name = user.title
292        rcpt_addr = user.email
[11814]293        text = _(text, mapping={
294            'a': rcpt_name,
295            'b': msg,
296            'c': config.name,
297            'd': user.name,
298            'e': password,
299            'f': url_info})
[7734]300
[7811]301        body = translate(text, 'waeup.kofa',
[7734]302            target_language=self.PORTAL_LANGUAGE)
[7399]303        return send_mail(
[11814]304            from_name, from_addr, rcpt_name, rcpt_addr,
305            subject, body, config)
[9987]306
307    def getPaymentItem(self, payment):
[13124]308        """Return payment item. This method can be used to customize the
309        `display_item` property attribute, e.g. in order to hide bed coordinates
310        if maintenance fee is not paid.
[9987]311        """
312        return payment.p_item
[11815]313
314    def expensive_actions_allowed(self, type=None, request=None):
315        """Tell, whether expensive actions are currently allowed.
316        Check system load/health (or other external circumstances) and
317        locally set values to see, whether expensive actions should be
318        allowed (`True`) or better avoided (`False`).
319        Use this to allow or forbid exports, report generations, or
320        similar actions.
321        """
322        max_values = self.SYSTEM_MAX_LOAD
[11816]323        for (key, func) in (
324            ('swap-mem', psutil.swap_memory),
[11818]325            ('virt-mem', psutil.virtual_memory),
[11816]326            ):
327            max_val = max_values.get(key, None)
328            if max_val is None:
329                continue
330            mem_val = func()
[11815]331            if isinstance(max_val, float):
[11816]332                # percents
[11821]333                if max_val < 0.0:
334                    max_val = 100.0 + max_val
[11816]335                if mem_val.percent > max_val:
[11815]336                    return False
337            else:
[11816]338                # number of bytes
[11821]339                if max_val < 0:
340                    max_val = mem_val.total + max_val
[11816]341                if mem_val.used > max_val:
[11815]342                    return False
343        return True
Note: See TracBrowser for help on using the repository browser.