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

Last change on this file since 13280 was 13198, checked in by Henrik Bettermann, 9 years ago

Add switch to disable all exports.

  • Property svn:keywords set to Id
File size: 11.0 KB
RevLine 
[7358]1## $Id: utils.py 13198 2015-08-15 07:44:00Z 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)
[13132]84
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) pdf slips.
[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',
[13031]177        'late_registration': 'Late Course Registration Fee'
[9405]178        }
179
[9866]180    SELECTABLE_PAYMENT_CATEGORIES = deepcopy(PAYMENT_CATEGORIES)
[9730]181
[9866]182    PREVIOUS_PAYMENT_CATEGORIES = deepcopy(SELECTABLE_PAYMENT_CATEGORIES)
[9862]183
[12564]184    REPORTABLE_PAYMENT_CATEGORIES = {
185        'schoolfee': 'School Fee',
186        'clearance': 'Acceptance Fee',
187        'hostel_maintenance': 'Hostel Maintenance Fee',
188        'gown': 'Gown Hire Fee',
189        }
190
[9868]191    BALANCE_PAYMENT_CATEGORIES = {
[9867]192        'schoolfee': 'School Fee',
193        }
[9864]194
[9649]195    MODE_GROUPS = {
[11814]196        'All': ('all',),
197        'Undergraduate Full-Time': ('ug_ft',),
198        'Undergraduate Part-Time': ('ug_pt',),
199        'Postgraduate Full-Time': ('pg_ft',),
200        'Postgraduate Part-Time': ('pg_pt',),
[9649]201        }
202
[13125]203    VERDICTS_DICT = {
204        '0': _('(not yet)'),
205        'A': 'Successful student',
206        'B': 'Student with carryover courses',
207        'C': 'Student on probation',
208        }
209
[11800]210    #: Set positive number for allowed max, negative for required min
211    #: avail.
212    #: Use integer for bytes value, float for percent
213    #: value. `cpu-load`, of course, accepts float values only.
214    #: `swap-mem` = Swap Memory, `virt-mem` = Virtual Memory,
[11969]215    #: `cpu-load` = CPU load in percent.
[11800]216    SYSTEM_MAX_LOAD = {
217        'swap-mem': None,
218        'virt-mem': None,
219        'cpu-load': 100.0,
220        }
221
[11814]222    def sendContactForm(self, from_name, from_addr, rcpt_name, rcpt_addr,
223                        from_username, usertype, portal, body, subject):
[7358]224        """Send an email with data provided by forms.
225        """
226        config = grok.getSite()['configuration']
[7734]227        text = _(u"""Fullname: ${a}
228User Id: ${b}
229User Type: ${c}
230Portal: ${d}
[7358]231
[7734]232${e}
233""")
[11814]234        text = _(text, mapping={
235            'a': from_name,
236            'b': from_username,
237            'c': usertype,
238            'd': portal,
239            'e': body})
[7811]240        body = translate(text, 'waeup.kofa',
[7734]241            target_language=self.PORTAL_LANGUAGE)
[8436]242        if not (from_addr and rcpt_addr):
243            return False
[7400]244        return send_mail(
[11814]245            from_name, from_addr, rcpt_name, rcpt_addr,
246            subject, body, config)
[7359]247
[8181]248    @property
249    def tzinfo(self):
[13124]250        """Time zone of the university.
251        """
[8181]252        # For Nigeria: pytz.timezone('Africa/Lagos')
[9543]253        # For Germany: pytz.timezone('Europe/Berlin')
[8181]254        return pytz.utc
255
[11814]256    def fullname(self, firstname, lastname, middlename=None):
[13124]257        """Construct fullname.
[7477]258        """
[7359]259        # We do not necessarily have the middlename attribute
260        if middlename:
[8603]261            name = '%s %s %s' % (firstname, middlename, lastname)
[7359]262        else:
[8603]263            name = '%s %s' % (firstname, lastname)
[11814]264        return string.capwords(
265            name.replace('-', ' - ')).replace(' - ', '-')
[7365]266
267    def genPassword(self, length=8, chars=string.letters + string.digits):
[7477]268        """Generate a random password.
269        """
[7365]270        return ''.join([r().choice(chars) for i in range(length)])
271
[8853]272    def sendCredentials(self, user, password=None, url_info=None, msg=None):
[13124]273        """Send credentials as email. Input is the user for which credentials
274        are sent and the password. Method returns True or False to indicate
275        successful operation.
[7365]276        """
[7819]277        subject = 'Your Kofa credentials'
[7734]278        text = _(u"""Dear ${a},
[7365]279
[7734]280${b}
[7365]281Student Registration and Information Portal of
[7734]282${c}.
[7365]283
[7734]284Your user name: ${d}
285Your password: ${e}
[8853]286${f}
[7365]287
288Please remember your user name and keep
289your password secret!
290
[7382]291Please also note that passwords are case-sensitive.
292
[7365]293Regards
[7734]294""")
[7399]295        config = grok.getSite()['configuration']
296        from_name = config.name_admin
[7402]297        from_addr = config.email_admin
[7407]298        rcpt_name = user.title
299        rcpt_addr = user.email
[11814]300        text = _(text, mapping={
301            'a': rcpt_name,
302            'b': msg,
303            'c': config.name,
304            'd': user.name,
305            'e': password,
306            'f': url_info})
[7734]307
[7811]308        body = translate(text, 'waeup.kofa',
[7734]309            target_language=self.PORTAL_LANGUAGE)
[7399]310        return send_mail(
[11814]311            from_name, from_addr, rcpt_name, rcpt_addr,
312            subject, body, config)
[9987]313
314    def getPaymentItem(self, payment):
[13124]315        """Return payment item. This method can be used to customize the
316        `display_item` property attribute, e.g. in order to hide bed coordinates
317        if maintenance fee is not paid.
[9987]318        """
319        return payment.p_item
[11815]320
321    def expensive_actions_allowed(self, type=None, request=None):
322        """Tell, whether expensive actions are currently allowed.
323        Check system load/health (or other external circumstances) and
324        locally set values to see, whether expensive actions should be
325        allowed (`True`) or better avoided (`False`).
326        Use this to allow or forbid exports, report generations, or
327        similar actions.
328        """
329        max_values = self.SYSTEM_MAX_LOAD
[11816]330        for (key, func) in (
331            ('swap-mem', psutil.swap_memory),
[11818]332            ('virt-mem', psutil.virtual_memory),
[11816]333            ):
334            max_val = max_values.get(key, None)
335            if max_val is None:
336                continue
337            mem_val = func()
[11815]338            if isinstance(max_val, float):
[11816]339                # percents
[11821]340                if max_val < 0.0:
341                    max_val = 100.0 + max_val
[11816]342                if mem_val.percent > max_val:
[11815]343                    return False
344            else:
[11816]345                # number of bytes
[11821]346                if max_val < 0:
347                    max_val = mem_val.total + max_val
[11816]348                if mem_val.used > max_val:
[11815]349                    return False
350        return True
[13198]351
352    def export_disabled_message(self):
353        export_disabled_message = grok.getSite()[
354            'configuration'].export_disabled_message
355        if export_disabled_message:
356            return export_disabled_message
357        return None
Note: See TracBrowser for help on using the repository browser.