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

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

Undo changes of previous revision.

  • Property svn:keywords set to Id
File size: 10.4 KB
RevLine 
[7358]1## $Id: utils.py 12588 2015-02-11 07:48: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##
[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.
[7829]82
[7358]83    """
[7831]84    grok.implements(IKofaUtils)
[7678]85    # This the only place where we define the portal language
86    # which is used for the translation of system messages
87    # (e.g. object histories).
[7744]88    PORTAL_LANGUAGE = 'en'
[7358]89
[7701]90    PREFERRED_LANGUAGES_DICT = {
[11814]91        'en': (1, u'English'),
92        'fr': (2, u'Français'),
93        'de': (3, u'Deutsch'),
94        'ha': (4, u'Hausa'),
95        'yo': (5, u'Yoruba'),
96        'ig': (6, u'Igbo'),
[7701]97        }
98
[7874]99    #: A function to return
100    @classmethod
101    def sorted_phone_prefixes(cls, data=INT_PHONE_PREFIXES, request=None):
102        return sorted_phone_prefixes(data, request)
[7871]103
[7841]104    EXAM_SUBJECTS_DICT = {
[7843]105        'math': 'Mathematics',
106        'computer_science': 'Computer Science',
[7841]107        }
[7836]108
[7917]109    #: Exam grades. The tuple is sorted as it should be displayed in
110    #: select boxes.
111    EXAM_GRADES = (
112        ('A', 'Best'),
113        ('B', 'Better'),
114        ('C', 'Good'),
115        )
[7836]116
[7841]117    INST_TYPES_DICT = {
[8084]118        'none': '',
[7681]119        'faculty': 'Faculty of',
120        'department': 'Department of',
121        'school': 'School of',
122        'office': 'Office for',
123        'centre': 'Centre for',
124        'institute': 'Institute of',
125        'school_for': 'School for',
[8084]126        'college': 'College of',
[10302]127        'directorate': 'Directorate of',
[7681]128        }
129
[7841]130    STUDY_MODES_DICT = {
[9131]131        'transfer': 'Transfer',
[7843]132        'ug_ft': 'Undergraduate Full-Time',
133        'ug_pt': 'Undergraduate Part-Time',
[7993]134        'pg_ft': 'Postgraduate Full-Time',
135        'pg_pt': 'Postgraduate Part-Time',
[7681]136        }
137
[11451]138    DISABLE_PAYMENT_GROUP_DICT = {
139        'sf_all': 'School Fee - All Students',
140        }
141
[7841]142    APP_CATS_DICT = {
[7843]143        'basic': 'Basic Application',
[7681]144        'no': 'no application',
145        'pg': 'Postgraduate',
146        'sandwich': 'Sandwich',
147        'cest': 'Part-Time, Diploma, Certificate'
148        }
149
[7841]150    SEMESTER_DICT = {
[10437]151        1: '1st Semester',
152        2: '2nd Semester',
[7681]153        3: 'Combined',
154        9: 'N/A'
155        }
156
[9400]157    SPECIAL_HANDLING_DICT = {
158        'regular': 'Regular Hostel',
159        'blocked': 'Blocked Hostel',
[10831]160        'pg': 'Postgraduate Hostel'
[9400]161        }
162
[10831]163    SPECIAL_APP_DICT = {
164        'transcript': 'Transcript Fee Payment',
[11575]165        'clearance': 'Acceptance Fee',
[10831]166        }
167
[9405]168    PAYMENT_CATEGORIES = {
169        'schoolfee': 'School Fee',
170        'clearance': 'Acceptance Fee',
171        'bed_allocation': 'Bed Allocation Fee',
172        'hostel_maintenance': 'Hostel Maintenance Fee',
173        'transfer': 'Transfer Fee',
174        'gown': 'Gown Hire Fee',
[9866]175        'application': 'Application Fee',
[10449]176        'transcript': 'Transcript 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):
243        # For Nigeria: pytz.timezone('Africa/Lagos')
[9543]244        # For Germany: pytz.timezone('Europe/Berlin')
[8181]245        return pytz.utc
246
[11814]247    def fullname(self, firstname, lastname, middlename=None):
[7477]248        """Full name constructor.
249        """
[7359]250        # We do not necessarily have the middlename attribute
251        if middlename:
[8603]252            name = '%s %s %s' % (firstname, middlename, lastname)
[7359]253        else:
[8603]254            name = '%s %s' % (firstname, lastname)
[11814]255        return string.capwords(
256            name.replace('-', ' - ')).replace(' - ', '-')
[7365]257
258    def genPassword(self, length=8, chars=string.letters + string.digits):
[7477]259        """Generate a random password.
260        """
[7365]261        return ''.join([r().choice(chars) for i in range(length)])
262
[8853]263    def sendCredentials(self, user, password=None, url_info=None, msg=None):
[7399]264        """Send credentials as email.
265
266        Input is the applicant for which credentials are sent and the
267        password.
268
269        Returns True or False to indicate successful operation.
[7365]270        """
[7819]271        subject = 'Your Kofa credentials'
[7734]272        text = _(u"""Dear ${a},
[7365]273
[7734]274${b}
[7365]275Student Registration and Information Portal of
[7734]276${c}.
[7365]277
[7734]278Your user name: ${d}
279Your password: ${e}
[8853]280${f}
[7365]281
282Please remember your user name and keep
283your password secret!
284
[7382]285Please also note that passwords are case-sensitive.
286
[7365]287Regards
[7734]288""")
[7399]289        config = grok.getSite()['configuration']
290        from_name = config.name_admin
[7402]291        from_addr = config.email_admin
[7407]292        rcpt_name = user.title
293        rcpt_addr = user.email
[11814]294        text = _(text, mapping={
295            'a': rcpt_name,
296            'b': msg,
297            'c': config.name,
298            'd': user.name,
299            'e': password,
300            'f': url_info})
[7734]301
[7811]302        body = translate(text, 'waeup.kofa',
[7734]303            target_language=self.PORTAL_LANGUAGE)
[7399]304        return send_mail(
[11814]305            from_name, from_addr, rcpt_name, rcpt_addr,
306            subject, body, config)
[9987]307
308    def getPaymentItem(self, payment):
309        """Return payment item.
310
311        This method can be used to customize the display_item property method.
312        """
313        return payment.p_item
[11815]314
315    def expensive_actions_allowed(self, type=None, request=None):
316        """Tell, whether expensive actions are currently allowed.
317
318        Check system load/health (or other external circumstances) and
319        locally set values to see, whether expensive actions should be
320        allowed (`True`) or better avoided (`False`).
321
322        Use this to allow or forbid exports, report generations, or
323        similar actions.
324        """
325        max_values = self.SYSTEM_MAX_LOAD
[11816]326        for (key, func) in (
327            ('swap-mem', psutil.swap_memory),
[11818]328            ('virt-mem', psutil.virtual_memory),
[11816]329            ):
330            max_val = max_values.get(key, None)
331            if max_val is None:
332                continue
333            mem_val = func()
[11815]334            if isinstance(max_val, float):
[11816]335                # percents
[11821]336                if max_val < 0.0:
337                    max_val = 100.0 + max_val
[11816]338                if mem_val.percent > max_val:
[11815]339                    return False
340            else:
[11816]341                # number of bytes
[11821]342                if max_val < 0:
343                    max_val = mem_val.total + max_val
[11816]344                if mem_val.used > max_val:
[11815]345                    return False
346        return True
Note: See TracBrowser for help on using the repository browser.