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

Last change on this file since 7912 was 7874, checked in by uli, 13 years ago

A (slightly) different setup to register phone prefixes in KofaUtils?.

  • Property svn:keywords set to Id
File size: 6.6 KB
RevLine 
[7358]1## $Id: utils.py 7874 2012-03-14 03:19:19Z uli $
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"""
[7568]20import os
[7358]21import grok
[7365]22import string
[7734]23from zope.i18n import translate
[7829]24from zope.interface import implements
[7365]25from random import SystemRandom as r
[7819]26from waeup.kofa.interfaces import IKofaUtils
[7811]27from waeup.kofa.interfaces import MessageFactory as _
28from waeup.kofa.smtp import send_mail as send_mail_internally
[7358]29
[7471]30def send_mail(from_name,from_addr,rcpt_name,rcpt_addr,subject,body,config):
[7811]31    """Wrapper for the real SMTP functionality in :mod:`waeup.kofa.smtp`.
[7382]32
[7471]33    Merely here to stay compatible with lots of calls to this place.
[7400]34    """
[7471]35    mail_id = send_mail_internally(
36        from_name, from_addr, rcpt_name, rcpt_addr,
37        subject, body, config)
[7399]38    return True
39
[7874]40#: A list of phone prefixes (order num, country, prefix).
41#: Items with same order num will be sorted alphabetically.
42#: The lower the order num, the higher the precedence.
43INT_PHONE_PREFIXES = [
44    (99, _('Germany'), '49'),
45    ( 1, _('Nigeria'), '234'),
46    (99, _('U.S.'), '1'),
47    ]
48
49def sorted_phone_prefixes(data = INT_PHONE_PREFIXES, request=None):
50    """Sorted tuples of phone prefixes.
51
52    Ordered as shown above and formatted for use in select boxes.
53
54    If request is given, we'll try to translate all country names in
55    order to sort alphabetically correctly.
56
57    XXX: This is a function (and not a constant) as different
58    languages might give different orders. This is not tested yet.
59
60    XXX: If we really want to use alphabetic ordering here, we might
61    think about caching results of translations.
62    """
63    if request is not None:
64        data = [
65            (x, translate(y, context=request), z)
66            for x, y, z in data]
67    return tuple([
68        ('%s (+%s)' % (x[1],x[2]), '+%s' % x[2])
69        for x in sorted(data)
70        ])
71
[7831]72class KofaUtils(grok.GlobalUtility):
[7678]73    """A collection of parameters and methods subject to customization.
[7829]74
[7358]75    """
[7831]76    grok.implements(IKofaUtils)
[7678]77    # This the only place where we define the portal language
78    # which is used for the translation of system messages
79    # (e.g. object histories).
[7744]80    PORTAL_LANGUAGE = 'en'
[7358]81
[7701]82    PREFERRED_LANGUAGES_DICT = {
83        'en':(1, u'English'),
84        'fr':(2, u'Français'),
85        'de':(3, u'Deutsch'),
86        'ha':(4, u'Hausa'),
87        'yo':(5, u'Yoruba'),
[7722]88        'ig':(6, u'Igbo'),
[7701]89        }
90
[7874]91    #: A function to return
92    @classmethod
93    def sorted_phone_prefixes(cls, data=INT_PHONE_PREFIXES, request=None):
94        return sorted_phone_prefixes(data, request)
[7871]95
[7841]96    EXAM_SUBJECTS_DICT = {
[7843]97        'math': 'Mathematics',
98        'computer_science': 'Computer Science',
[7841]99        }
[7836]100
[7841]101    EXAM_GRADES_DICT = {
[7843]102        'A': (1, 'Best'),
103        'B': (2, 'Better'),
104        'C': (3, 'Good'),
[7841]105        }
[7836]106
[7841]107    INST_TYPES_DICT = {
[7681]108        'faculty': 'Faculty of',
109        'department': 'Department of',
110        'school': 'School of',
111        'office': 'Office for',
112        'centre': 'Centre for',
113        'institute': 'Institute of',
114        'school_for': 'School for',
115        }
116
[7841]117    STUDY_MODES_DICT = {
[7843]118        'ug_ft': 'Undergraduate Full-Time',
119        'ug_pt': 'Undergraduate Part-Time',
[7681]120        }
121
[7841]122    APP_CATS_DICT = {
[7843]123        'basic': 'Basic Application',
[7681]124        'no': 'no application',
125        'pg': 'Postgraduate',
126        'sandwich': 'Sandwich',
127        'cest': 'Part-Time, Diploma, Certificate'
128        }
129
[7841]130    SEMESTER_DICT = {
[7681]131        1: 'First Semester',
132        2: 'Second Semester',
133        3: 'Combined',
134        9: 'N/A'
135        }
136
[7404]137    def sendContactForm(self,from_name,from_addr,rcpt_name,rcpt_addr,
[7402]138                from_username,usertype,portal,body,subject):
[7358]139        """Send an email with data provided by forms.
140        """
141        config = grok.getSite()['configuration']
[7734]142        text = _(u"""Fullname: ${a}
143User Id: ${b}
144User Type: ${c}
145Portal: ${d}
[7358]146
[7734]147${e}
148""")
149        text = _(text,
150            mapping = {
151            'a':from_name,
152            'b':from_username,
153            'c':usertype,
154            'd':portal,
155            'e':body})
[7811]156        body = translate(text, 'waeup.kofa',
[7734]157            target_language=self.PORTAL_LANGUAGE)
[7400]158        return send_mail(
[7402]159            from_name,from_addr,rcpt_name,rcpt_addr,subject,body,config)
[7359]160
161    def fullname(self,firstname,lastname,middlename=None):
[7477]162        """Full name constructor.
163        """
[7359]164        # We do not necessarily have the middlename attribute
165        if middlename:
[7365]166            return string.capwords(
167                '%s %s %s' % (firstname, middlename, lastname))
[7359]168        else:
[7365]169            return string.capwords(
170                '%s %s' % (firstname, lastname))
171
172    def genPassword(self, length=8, chars=string.letters + string.digits):
[7477]173        """Generate a random password.
174        """
[7365]175        return ''.join([r().choice(chars) for i in range(length)])
176
[7382]177
[7407]178    def sendCredentials(self, user, password=None, login_url=None, msg=None):
[7399]179        """Send credentials as email.
180
181        Input is the applicant for which credentials are sent and the
182        password.
183
184        Returns True or False to indicate successful operation.
[7365]185        """
[7819]186        subject = 'Your Kofa credentials'
[7734]187        text = _(u"""Dear ${a},
[7365]188
[7734]189${b}
[7365]190Student Registration and Information Portal of
[7734]191${c}.
[7365]192
[7734]193Your user name: ${d}
194Your password: ${e}
195Login page: ${f}
[7365]196
197Please remember your user name and keep
198your password secret!
199
[7382]200Please also note that passwords are case-sensitive.
201
[7365]202Regards
[7734]203""")
[7399]204        config = grok.getSite()['configuration']
205        from_name = config.name_admin
[7402]206        from_addr = config.email_admin
[7407]207        rcpt_name = user.title
208        rcpt_addr = user.email
[7734]209        text = _(text,
210            mapping = {
211            'a':rcpt_name,
212            'b':msg,
213            'c':config.name,
214            'd':user.name,
215            'e':password,
216            'f':login_url})
217
[7811]218        body = translate(text, 'waeup.kofa',
[7734]219            target_language=self.PORTAL_LANGUAGE)
[7399]220        return send_mail(
[7402]221            from_name,from_addr,rcpt_name,rcpt_addr,subject,body,config)
Note: See TracBrowser for help on using the repository browser.