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

Last change on this file since 7942 was 7917, checked in by uli, 13 years ago

Simplify the design of EXAM_GRADES (former EXAM_GRADES_DICT). Grades
are now sorted automatically by their position in the tuple. CAREFUL!
This means that most probably changes in custom packages are
neccessary!

  • Property svn:keywords set to Id
File size: 6.7 KB
Line 
1## $Id: utils.py 7917 2012-03-19 06:51:42Z 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. The tuple is sorted as it should be displayed in
102    #: select boxes.
103    EXAM_GRADES = (
104        ('A', 'Best'),
105        ('B', 'Better'),
106        ('C', 'Good'),
107        )
108
109    INST_TYPES_DICT = {
110        'faculty': 'Faculty of',
111        'department': 'Department of',
112        'school': 'School of',
113        'office': 'Office for',
114        'centre': 'Centre for',
115        'institute': 'Institute of',
116        'school_for': 'School for',
117        }
118
119    STUDY_MODES_DICT = {
120        'ug_ft': 'Undergraduate Full-Time',
121        'ug_pt': 'Undergraduate Part-Time',
122        }
123
124    APP_CATS_DICT = {
125        'basic': 'Basic Application',
126        'no': 'no application',
127        'pg': 'Postgraduate',
128        'sandwich': 'Sandwich',
129        'cest': 'Part-Time, Diploma, Certificate'
130        }
131
132    SEMESTER_DICT = {
133        1: 'First Semester',
134        2: 'Second Semester',
135        3: 'Combined',
136        9: 'N/A'
137        }
138
139    def sendContactForm(self,from_name,from_addr,rcpt_name,rcpt_addr,
140                from_username,usertype,portal,body,subject):
141        """Send an email with data provided by forms.
142        """
143        config = grok.getSite()['configuration']
144        text = _(u"""Fullname: ${a}
145User Id: ${b}
146User Type: ${c}
147Portal: ${d}
148
149${e}
150""")
151        text = _(text,
152            mapping = {
153            'a':from_name,
154            'b':from_username,
155            'c':usertype,
156            'd':portal,
157            'e':body})
158        body = translate(text, 'waeup.kofa',
159            target_language=self.PORTAL_LANGUAGE)
160        return send_mail(
161            from_name,from_addr,rcpt_name,rcpt_addr,subject,body,config)
162
163    def fullname(self,firstname,lastname,middlename=None):
164        """Full name constructor.
165        """
166        # We do not necessarily have the middlename attribute
167        if middlename:
168            return string.capwords(
169                '%s %s %s' % (firstname, middlename, lastname))
170        else:
171            return string.capwords(
172                '%s %s' % (firstname, lastname))
173
174    def genPassword(self, length=8, chars=string.letters + string.digits):
175        """Generate a random password.
176        """
177        return ''.join([r().choice(chars) for i in range(length)])
178
179
180    def sendCredentials(self, user, password=None, login_url=None, msg=None):
181        """Send credentials as email.
182
183        Input is the applicant for which credentials are sent and the
184        password.
185
186        Returns True or False to indicate successful operation.
187        """
188        subject = 'Your Kofa credentials'
189        text = _(u"""Dear ${a},
190
191${b}
192Student Registration and Information Portal of
193${c}.
194
195Your user name: ${d}
196Your password: ${e}
197Login page: ${f}
198
199Please remember your user name and keep
200your password secret!
201
202Please also note that passwords are case-sensitive.
203
204Regards
205""")
206        config = grok.getSite()['configuration']
207        from_name = config.name_admin
208        from_addr = config.email_admin
209        rcpt_name = user.title
210        rcpt_addr = user.email
211        text = _(text,
212            mapping = {
213            'a':rcpt_name,
214            'b':msg,
215            'c':config.name,
216            'd':user.name,
217            'e':password,
218            'f':login_url})
219
220        body = translate(text, 'waeup.kofa',
221            target_language=self.PORTAL_LANGUAGE)
222        return send_mail(
223            from_name,from_addr,rcpt_name,rcpt_addr,subject,body,config)
Note: See TracBrowser for help on using the repository browser.