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

Last change on this file since 8157 was 8084, checked in by Henrik Bettermann, 13 years ago

Extend vocaularies for Uniben.

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