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
Line 
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##
18"""General helper utilities for Kofa.
19"""
20import os
21import grok
22import string
23from zope.i18n import translate
24from zope.interface import implements
25from random import SystemRandom as r
26from waeup.kofa.interfaces import IKofaUtils
27from waeup.kofa.interfaces import MessageFactory as _
28from waeup.kofa.smtp import send_mail as send_mail_internally
29
30def send_mail(from_name,from_addr,rcpt_name,rcpt_addr,subject,body,config):
31    """Wrapper for the real SMTP functionality in :mod:`waeup.kofa.smtp`.
32
33    Merely here to stay compatible with lots of calls to this place.
34    """
35    mail_id = send_mail_internally(
36        from_name, from_addr, rcpt_name, rcpt_addr,
37        subject, body, config)
38    return True
39
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
72class KofaUtils(grok.GlobalUtility):
73    """A collection of parameters and methods subject to customization.
74
75    """
76    grok.implements(IKofaUtils)
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).
80    PORTAL_LANGUAGE = 'en'
81
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'),
88        'ig':(6, u'Igbo'),
89        }
90
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)
95
96    EXAM_SUBJECTS_DICT = {
97        'math': 'Mathematics',
98        'computer_science': 'Computer Science',
99        }
100
101    EXAM_GRADES_DICT = {
102        'A': (1, 'Best'),
103        'B': (2, 'Better'),
104        'C': (3, 'Good'),
105        }
106
107    INST_TYPES_DICT = {
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
117    STUDY_MODES_DICT = {
118        'ug_ft': 'Undergraduate Full-Time',
119        'ug_pt': 'Undergraduate Part-Time',
120        }
121
122    APP_CATS_DICT = {
123        'basic': 'Basic Application',
124        'no': 'no application',
125        'pg': 'Postgraduate',
126        'sandwich': 'Sandwich',
127        'cest': 'Part-Time, Diploma, Certificate'
128        }
129
130    SEMESTER_DICT = {
131        1: 'First Semester',
132        2: 'Second Semester',
133        3: 'Combined',
134        9: 'N/A'
135        }
136
137    def sendContactForm(self,from_name,from_addr,rcpt_name,rcpt_addr,
138                from_username,usertype,portal,body,subject):
139        """Send an email with data provided by forms.
140        """
141        config = grok.getSite()['configuration']
142        text = _(u"""Fullname: ${a}
143User Id: ${b}
144User Type: ${c}
145Portal: ${d}
146
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})
156        body = translate(text, 'waeup.kofa',
157            target_language=self.PORTAL_LANGUAGE)
158        return send_mail(
159            from_name,from_addr,rcpt_name,rcpt_addr,subject,body,config)
160
161    def fullname(self,firstname,lastname,middlename=None):
162        """Full name constructor.
163        """
164        # We do not necessarily have the middlename attribute
165        if middlename:
166            return string.capwords(
167                '%s %s %s' % (firstname, middlename, lastname))
168        else:
169            return string.capwords(
170                '%s %s' % (firstname, lastname))
171
172    def genPassword(self, length=8, chars=string.letters + string.digits):
173        """Generate a random password.
174        """
175        return ''.join([r().choice(chars) for i in range(length)])
176
177
178    def sendCredentials(self, user, password=None, login_url=None, msg=None):
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.
185        """
186        subject = 'Your Kofa credentials'
187        text = _(u"""Dear ${a},
188
189${b}
190Student Registration and Information Portal of
191${c}.
192
193Your user name: ${d}
194Your password: ${e}
195Login page: ${f}
196
197Please remember your user name and keep
198your password secret!
199
200Please also note that passwords are case-sensitive.
201
202Regards
203""")
204        config = grok.getSite()['configuration']
205        from_name = config.name_admin
206        from_addr = config.email_admin
207        rcpt_name = user.title
208        rcpt_addr = user.email
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
218        body = translate(text, 'waeup.kofa',
219            target_language=self.PORTAL_LANGUAGE)
220        return send_mail(
221            from_name,from_addr,rcpt_name,rcpt_addr,subject,body,config)
Note: See TracBrowser for help on using the repository browser.