Changed DictValidator so that long and int datatypes are not treated as different...
[philipp/winterrodeln/wrpylib.git] / wrpylib / wrvalidators.py
1 #!/usr/bin/python2.6
2 # -*- coding: iso-8859-15 -*-
3 # $Id$
4 # $HeadURL$
5 """This file contains "validators" that convert between string and python (database) representation
6 of properties used in the "Rodelbahnbox" and "Gasthausbox".
7 The "to_python" method has to get a unicode argument.
8 """
9 import formencode
10 import formencode.national
11 import datetime
12 import re
13 import xml.dom.minidom as minidom
14 from xml.parsers.expat import ExpatError
15
16
17 class NoneValidator(formencode.FancyValidator):
18     """Takes a validator and makes it possible that empty strings are mapped to None."""
19     def __init__(self, validator, python_none=None):
20         self.validator = validator
21         self.python_none = python_none
22     
23     def to_python(self, value):
24         self.assert_string(value, None)
25         if value == u'': return self.python_none
26         return self.validator.to_python(value)
27     
28     def from_python(self, value):
29         if value == self.python_none: return u''
30         return self.validator.from_python(value)
31
32
33 class NeinValidator(formencode.FancyValidator):
34     """Take an arbitrary validator and adds the possibility that the
35     string can be u'Nein'.
36     Example together with an UnsignedNone validator:
37     >>> v = NeinValidator(UnsignedNone())
38     >>> v.to_python(u'')
39     None
40     >>> v.to_python(u'34')
41     34
42     >>> v.to_python(u'Nein')
43     u'Nein'
44     """
45     def __init__(self, validator, python_no=u'Nein'):
46         self.validator = validator
47         self.python_no = python_no
48     
49     def to_python(self, value):
50         self.assert_string(value, None)
51         if value == u'Nein': return self.python_no
52         return self.validator.to_python(value)
53     
54     def from_python(self, value):
55         if value == self.python_no: return u'Nein'
56         return self.validator.from_python(value)
57
58
59 class Unicode(formencode.FancyValidator):
60     """Converts an unicode string to an unicode string:
61     u'any string' <=> u'any string'"""
62     def to_python(self, value):
63         self.assert_string(value, None)
64         return unicode(value)
65
66     def from_python(self, value):
67         return unicode(value)
68
69
70 class UnicodeNone(NoneValidator):
71     """Converts an unicode string to an unicode string:
72     u'' <=> None
73     u'any string' <=> u'any string'"""
74     def __init__(self):
75         NoneValidator.__init__(self, Unicode())
76
77
78 class Unsigned(formencode.FancyValidator):
79     """Converts an unsigned number to a string and vice versa:
80     u'0'  <=>  0
81     u'1'  <=>  1
82     u'45' <=> 45
83     """
84     def __init__(self, max=None):
85         self.iv = formencode.validators.Int(min=0, max=max)
86
87     def to_python(self, value):
88         self.assert_string(value, None)
89         return self.iv.to_python(value)
90     
91     def from_python(self, value):
92         return unicode(value)
93
94
95 class UnsignedNone(NoneValidator):
96     """Converts an unsigned number to a string and vice versa:
97     u''   <=> None
98     u'0'  <=>  0
99     u'1'  <=>  1
100     u'45' <=> 45
101     """
102     def __init__(self, max=None):
103         NoneValidator.__init__(self, Unsigned(max))
104
105
106 class UnsignedNeinNone(NoneValidator):
107     """ Translates a number of Nein to a number.
108     u''     <=> None
109     u'Nein' <=> 0
110     u'1'    <=> 1
111     u'2'    <=> 2
112     ...
113     """
114     def __init__(self):
115         NoneValidator.__init__(self, UnsignedNone())
116
117
118 class Loop(formencode.FancyValidator):
119     """Takes a validator and calls from_python(to_python(value))."""
120     def __init__(self, validator):
121         self.validator = validator
122
123     def to_python(self, value):
124         self.assert_string(value, None)
125         return self.validator.from_python(self.validator.to_python(value))
126     
127     def from_python(self, value):
128         # we don't call self.validator.to_python(self.validator.from_python(value))
129         # here because our to_python implementation basically leaves the input untouched
130         # and so should from_python do.
131         return self.validator.from_python(self.validator.to_python(value))
132
133
134 class DictValidator(formencode.FancyValidator):
135     """Translates strings to other values via a python directory.
136     >>> boolValidator = DictValidator({u'': None, u'Ja': True, u'Nein': False})
137     >>> boolValidator.to_python(u'')
138     None
139     >>> boolValidator.to_python(u'Ja')
140     True
141     """
142     def __init__(self, dict):
143         self.dict = dict
144     
145     def to_python(self, value):
146         self.assert_string(value, None)
147         if not self.dict.has_key(value): raise formencode.Invalid("Key not found in dict.", value, None)
148         return self.dict[value]
149     
150     def from_python(self, value):
151         for k, v in self.dict.iteritems():
152             if v == value:
153                 return k
154         raise formencode.Invalid('Invalid value', value, None)
155
156
157 class GermanBoolNone(DictValidator):
158     """Converts German bool values to the python bool type:
159     u''     <=> None
160     u'Ja'   <=> True
161     u'Nein' <=> False
162     """
163     def __init__(self):
164         DictValidator.__init__(self, {u'': None, u'Ja': True, u'Nein': False})
165
166
167 class GermanTristateTuple(DictValidator):
168     """Does the following conversion:
169     u''          <=> (None, None)
170     u'Ja'        <=> (True, False)
171     u'Teilweise' <=> (True,  True)
172     u'Nein'      <=> (False, True)"""
173     def __init__(self, yes_python = (True, False), no_python = (False, True), partly_python = (True, True), none_python = (None, None)):
174         DictValidator.__init__(self, {u'': none_python, u'Ja': yes_python, u'Nein': no_python, u'Teilweise': partly_python})
175
176
177 class GermanTristateFloat(GermanTristateTuple):
178     """Converts the a property with the possible values 0.0, 0.5, 1.0 or None
179     to a German text:
180     u''          <=> None
181     u'Ja'        <=> 1.0
182     u'Teilweise' <=> 0.5
183     u'Nein'      <=> 0.0"""
184     def __init__(self):
185         GermanTristateTuple.__init__(self, yes_python=1.0, no_python=0.0, partly_python=0.5, none_python=None)
186
187
188 class ValueComment(formencode.FancyValidator):
189     """Converts value with a potentially optional comment to a python tuple. If a comment is present, the
190     closing bracket has to be the rightmost character.
191     u''                                 <=> (None, None)
192     u'value'                            <=> (u'value', None)
193     u'value (comment)'                  <=> (u'value', u'comment')
194     u'[[link (linkcomment)]]'           <=> (u'[[link (linkcomment)]]', None)
195     u'[[link (linkcomment)]] (comment)' <=> (u'[[link (linkcomment)]]', comment)
196     """
197     def __init__(self, value_validator=UnicodeNone(), comment_validator=UnicodeNone(), comment_is_optional=True):
198         self.value_validator = value_validator
199         self.comment_validator = comment_validator
200         self.comment_is_optional = comment_is_optional
201     
202     def to_python(self, value):
203         self.assert_string(value, None)
204         if value == u'':
205             v = value
206             c = value
207         else:
208             right = value.rfind(')')
209             if right+1 != len(value):
210                 if not self.comment_is_optional: raise formencode.Invalid(u'Mandatory comment not present', value, None)
211                 v = value
212                 c = u''
213             else:
214                 left = value.rfind('(')
215                 if left < 0: raise formencode.Invalid(u'Invalid format', value, None)
216                 v = value[:left].strip()
217                 c = value[left+1:right].strip()
218         return self.value_validator.to_python(v), self.comment_validator.to_python(c)
219
220     def from_python(self, value):
221         assert len(value) == 2
222         v = self.value_validator.from_python(value[0])
223         c = self.comment_validator.from_python(value[1])
224         if len(c) > 0:
225             if len(v) > 0: return u'%s (%s)' % (v, c)
226             else: return u'(%s)' % c
227         return v
228
229
230 class SemicolonList(formencode.FancyValidator):
231     """Applies a given validator to a semicolon separated list of values and returns a python list.
232     For an empty string an empty list is returned."""
233     def __init__(self, validator=Unicode()):
234         self.validator = validator
235     
236     def to_python(self, value):
237         self.assert_string(value, None)
238         return [self.validator.to_python(s.strip()) for s in value.split(';')]
239     
240     def from_python(self, value):
241         return "; ".join([self.validator.from_python(s) for s in value])
242         
243     
244 class ValueCommentList(SemicolonList):
245     """A value-comment list looks like one of the following lines:
246         value
247         value (optional comment)
248         value1; value2
249         value1; value2 (optional comment)
250         value1 (optional comment1); value2 (optional comment2); value3 (otional comment3)
251         value1 (optional comment1); value2 (optional comment2); value3 (otional comment3)
252     This function returns the value-comment list as list of tuples:
253         [(u'value1', u'comment1'), (u'value2', None)]
254     If no comment is present, None is specified.
255     For an empty string, [] is returned."""    
256     def __init__(self, value_validator=Unicode(), comments_are_optional=True):
257         SemicolonList.__init__(self, ValueComment(value_validator, comment_is_optional=comments_are_optional))
258
259
260 class GenericDateTime(formencode.FancyValidator):
261     """Converts a generic date/time information to a datetime class with a user defined format.
262     '2009-03-22 20:36:15' would be specified as '%Y-%m-%d %H:%M:%S'."""
263     
264     def __init__(self, date_time_format = '%Y-%m-%d %H:%M:%S', **keywords):
265         formencode.FancyValidator.__init__(self, **keywords)
266         self.date_time_format = date_time_format
267     
268     def to_python(self, value, state=None):
269         self.assert_string(value, None)
270         try: return datetime.datetime.strptime(value, self.date_time_format)
271         except ValueError, e: raise formencode.Invalid(str(e), value, None)
272     
273     def from_python(self, value, state=None):
274         return value.strftime(self.date_time_format)
275
276
277 class DateTimeNoSec(GenericDateTime):
278     def __init__(self, **keywords):
279         GenericDateTime.__init__(self, '%Y-%m-%d %H:%M', **keywords)
280
281
282 class DateNone(NoneValidator):
283     """Converts date information to date classes with the format '%Y-%m-%d' or None."""
284     def __init__(self):
285         NoneValidator.__init__(self, GenericDateTime('%Y-%m-%d'))
286
287
288 class Geo(formencode.FancyValidator):
289     """Formats to coordinates '47.076207 N 11.453553 E' to the (latitude, longitude) tuplet."""
290     def to_python(self, value):
291         self.assert_string(value, None)
292         r = re.match(u'(\d+\.\d+) N (\d+\.\d+) E', value)
293         if r is None: raise formencode.Invalid(u"Coordinates '%s' have not a format like '47.076207 N 11.453553 E'" % value, value, None)
294         return (float(r.groups()[0]), float(r.groups()[1]))
295     
296     def from_python(self, value):
297         latitude, longitude = value
298         return u'%.6f N %.6f E' % (latitude, longitude)
299
300
301 class GeoNone(NoneValidator):
302     """Formats to coordinates '47.076207 N 11.453553 E' to the (latitude, longitude) tuplet."""
303     def __init__(self):
304         NoneValidator.__init__(self, Geo(), (None, None))
305
306
307 class MultiGeo(formencode.FancyValidator):
308     "Formats multiple coordinates, even in multiple lines to [(latitude, longitude, elevation), ...] or [(latitude, longitude, None), ...] tuplets."
309     
310     # Valid for input_format
311     FORMAT_GUESS = 0         # guesses the input format; default for input_format
312     FORMAT_NONE = -1          # indicates missing formats
313     
314     # Valid for input_format and output_format
315     FORMAT_GEOCACHING = 1    # e.g. "N 47° 13.692 E 011° 25.535"
316     FORMAT_WINTERRODELN = 2  # e.g. "47.222134 N 11.467211 E"
317     FORMAT_GMAPPLUGIN = 3    # e.g. "47.232922, 11.452239"
318     FORMAT_GPX = 4           # e.g. "<trkpt lat="47.181289" lon="11.408827"><ele>1090.57</ele></trkpt>"
319     
320     input_format = FORMAT_GUESS
321     output_format = FORMAT_WINTERRODELN
322     last_input_format = FORMAT_NONE
323
324     def __init__(self, input_format = FORMAT_GUESS, output_format = FORMAT_WINTERRODELN, **keywords):
325         self.input_format = input_format
326         self.output_format = output_format
327         formencode.FancyValidator.__init__(self, if_empty = (None, None, None), **keywords)
328     
329     def to_python(self, value):
330         self.assert_string(value, None)
331         input_format = self.input_format
332         if not input_format in [self.FORMAT_GUESS, self.FORMAT_GEOCACHING, self.FORMAT_WINTERRODELN, self.FORMAT_GMAPPLUGIN, self.FORMAT_GPX]:
333             raise formencode.Invalid(u"input_format %d is not recognized" % input_format, value, None) # Shouldn't it be an other type of runtime error?
334         lines = [line.strip() for line in value.split("\n") if len(line.strip()) > 0]
335         
336         result = []
337         for line in lines:
338             if input_format == self.FORMAT_GUESS or input_format == self.FORMAT_GEOCACHING:
339                 r = re.match(u'N ?(\d+)° ?(\d+\.\d+) +E ?(\d+)° ?(\d+\.\d+)', line)
340                 if not r is None:
341                     g = r.groups()
342                     result.append((float(g[0]) + float(g[1])/60, float(g[2]) + float(g[3])/60, None))
343                     last_input_format = self.FORMAT_WINTERRODELN
344                     continue
345                     
346             if input_format == self.FORMAT_GUESS or input_format == self.FORMAT_WINTERRODELN:
347                 r = re.match(u'(\d+\.\d+) N (\d+\.\d+) E', line)
348                 if not r is None:
349                     result.append((float(r.groups()[0]), float(r.groups()[1]), None))
350                     last_input_format = self.FORMAT_WINTERRODELN
351                     continue
352                 
353             if input_format == self.FORMAT_GUESS or input_format == self.FORMAT_GMAPPLUGIN:
354                 r = re.match(u'(\d+\.\d+), ?(\d+\.\d+)', line)
355                 if not r is None:
356                     result.append((float(r.groups()[0]), float(r.groups()[1]), None))
357                     last_input_format = self.FORMAT_GMAPPLUGIN
358                     continue
359                 
360             if input_format == self.FORMAT_GUESS or input_format == self.FORMAT_GPX:
361                 try:
362                     xml = minidom.parseString(line)
363                     coord = xml.documentElement
364                     lat = float(coord.getAttribute('lat'))
365                     lon = float(coord.getAttribute('lon'))
366                     try: ele = float(coord.childNodes[0].childNodes[0].nodeValue)
367                     except (IndexError, ValueError): ele = None
368                     result.append((lat, lon, ele))
369                     last_input_format = self.FORMAT_GPX
370                     continue
371                 except (ExpatError, IndexError, ValueError): pass
372
373             raise formencode.Invalid(u"Coordinates '%s' have no known format" % line, value, None)
374             
375         return result
376     
377     def from_python(self, value):
378         output_format = self.output_format
379         result = []
380         for latitude, longitude, height in value:
381             if output_format == self.FORMAT_GEOCACHING:
382                 degree = latitude
383                 result.append(u'N %02d° %02.3f E %03d° %02.3f' % (latitude, latitude % 1 * 60, longitude, longitude % 1 * 60))
384                 
385             elif output_format == self.FORMAT_WINTERRODELN:
386                 result.append(u'%.6f N %.6f E' % (latitude, longitude))
387
388             elif output_format == self.FORMAT_GMAPPLUGIN:
389                 result.append(u'%.6f, %.6f' % (latitude, longitude))
390                 
391             elif output_format == self.FORMAT_GPX:
392                 if not height is None: result.append(u'<trkpt lat="%.6f" lon="%.6f"><ele>%.2f</ele></trkpt>' % (latitude, longitude, height))
393                 else: result.append(u'<trkpt lat="%.6f" lon="%.6f"/>' % (latitude, longitude))
394             
395             else:
396                 raise formencode.Invalid(u"output_format %d is not recognized" % output_format, value, None) # Shouldn't it be an other type of runtime error?
397             
398         return "\n".join(result)
399
400
401 # deprecated
402 class AustrianPhoneNumber(formencode.FancyValidator):
403     """
404     Validates and converts phone numbers to +##/###/####### or +##/###/#######-### (having an extension)
405     @param  default_cc      country code for prepending if none is provided, defaults to 43 (Austria)
406     ::
407         >>> v = AustrianPhoneNumber()
408         >>> v.to_python(u'0512/12345678')
409         u'+43/512/12345678'
410         >>> v.to_python(u'+43/512/12345678')
411         u'+43/512/12345678'
412         >>> v.to_python(u'0512/1234567-89') # 89 is the extension
413         u'+43/512/1234567-89'
414         >>> v.to_python(u'+43/512/1234567-89')
415         u'+43/512/1234567-89'
416         >>> v.to_python(u'0512 / 12345678') # Exception
417         >>> v.to_python(u'0512-12345678') # Exception
418     """
419     # Inspired by formencode.national.InternationalPhoneNumber
420
421     default_cc = 43 # Default country code
422     messages = {'phoneFormat': "'%%(value)s' is an invalid format. Please enter a number in the form +43/###/####### or 0###/########."}
423
424     def to_python(self, value):
425         self.assert_string(value, None)
426         m = re.match(u'^(?:\+(\d+)/)?([\d/]+)(?:-(\d+))?$', value)
427         # This will separate 
428         #     u'+43/512/1234567-89'  => (u'43', u'512/1234567', u'89')
429         #     u'+43/512/1234/567-89' => (u'43', u'512/1234/567', u'89')
430         #     u'+43/512/1234/567'    => (u'43', u'512/1234/567', None)
431         #     u'0512/1234567'        => (None, u'0512/1234567', None)
432         if m is None: raise formencode.Invalid(self.message('phoneFormat', None) % {'value': value}, value, None)
433         (country, phone, extension) = m.groups()
434         
435         # Phone
436         if phone.find(u'//') > -1 or phone.count('/') == 0: raise formencode.Invalid(self.message('phoneFormat', None) % {'value': value}, value, None)
437         
438         # Country
439         if country is None:
440             if phone[0] != '0': raise formencode.Invalid(self.message('phoneFormat', None) % {'value': value}, value, None)
441             phone = phone[1:]
442             country = unicode(self.default_cc)
443         
444         if extension is None: return '+%s/%s' % (country, phone)
445         return '+%s/%s-%s' % (country, phone, extension)
446
447
448 # Deprecated
449 class AustrianPhoneNumberNone(NoneValidator):
450     def __init__(self):
451         NoneValidator.__init__(self, AustrianPhoneNumber())
452
453
454 # Deprecated
455 class AustrianPhoneNumberCommentLoop(NoneValidator):
456     def __init__(self):
457         NoneValidator.__init__(self, Loop(ValueComment(AustrianPhoneNumber())))
458
459
460 class GermanDifficulty(DictValidator):
461     """Converts the difficulty represented in a number from 1 to 3 (or None)
462     to a German representation:
463     u''       <=> None
464     u'leicht' <=> 1
465     u'mittel' <=> 2
466     u'schwer' <=> 3"""
467     def __init__(self):
468         DictValidator.__init__(self, {u'': None, u'leicht': 1, u'mittel': 2, u'schwer': 3})
469
470
471 class GermanAvalanches(DictValidator):
472     """Converts the avalanches property represented as number from 1 to 4 (or None)
473     to a German representation:
474     u''             <=> None
475     u'kaum'         <=> 1
476     u'selten'       <=> 2
477     u'gelegentlich' <=> 3
478     u'häufig'       <=> 4"""
479     def __init__(self):
480         DictValidator.__init__(self, {u'': None, u'kaum': 1, u'selten': 2, u'gelegentlich': 3, u'häufig': 4})
481
482
483 class GermanPublicTransport(DictValidator):
484     """Converts the public_transport property represented as number from 1 to 6 (or None)
485     to a German representation:
486     u''            <=> None
487     u'Sehr gut'    <=> 1
488     u'Gut'         <=> 2
489     u'Mittelmäßig' <=> 3
490     u'Schlecht'    <=> 4
491     u'Nein'        <=> 5
492     u'Ja'          <=> 6"""
493     def __init__(self):
494         DictValidator.__init__(self, {u'': None, u'Sehr gut': 1, u'Gut': 2, u'Mittelmäßig': 3, u'Schlecht': 4, u'Nein': 5, u'Ja': 6})
495
496
497 class GermanTristateFloatComment(ValueComment):
498     """Converts the a property with the possible values 0.0, 0.5, 1.0 or None and an optional comment
499     in parenthesis to a German text:
500     u''                  <=> (None, None)
501     u'Ja'                <=> (1.0,  None)
502     u'Teilweise'         <=> (0.5,  None)
503     u'Nein'              <=> (0.0,  None)
504     u'Ja (aber schmal)'  <=> (1.0,  u'aber schmal')
505     u'Teilweise (oben)'  <=> (0.5,  u'oben')
506     u'Nein (aber breit)' <=> (0.0,  u'aber breit')
507     """
508     def __init__(self):
509         ValueComment.__init__(self, GermanTristateFloat())
510
511
512 class UnsignedCommentNone(NoneValidator):
513     """Converts the a property with unsigned values an optional comment
514     in parenthesis to a text:
515     u''           <=> (None, None)
516     u'2 (Mo, Di)' <=> (2,  u'Mo, Di')
517     u'7'          <=> (7,  None)
518     u'0'          <=> (0,  None)
519     """
520     def __init__(self, max=None):
521         NoneValidator.__init__(self, ValueComment(Unsigned(max=max)), (None, None))
522
523
524 class GermanCachet(formencode.FancyValidator):
525     """Converts a "Gütesiegel":
526     u'' <=> None
527     u'Nein' <=> 'Nein'
528     u'Tiroler Naturrodelbahn-Gütesiegel 2009 mittel' <=> u'Tiroler Naturrodelbahn-Gütesiegel 2009 mittel'"""
529     def to_python(self, value):
530         self.assert_string(value, None)
531         if value == u'': return None
532         elif value == u'Nein': return value
533         elif value.startswith(u'Tiroler Naturrodelbahn-Gütesiegel '):
534             p = value.split(" ")
535             Unsigned().to_python(p[2]) # check if year can be parsed
536             if not p[3] in ['leicht', 'mittel', 'schwer']: raise formencode.Invalid("Unbekannter Schwierigkeitsgrad", value, None)
537             return value
538         else: raise formencode.Invalid(u"Unbekanntes Gütesiegel", value, None)
539     
540     def from_python(self, value):
541         if value == None: return u''
542         assert value != u''
543         return self.to_python(value)
544
545
546 class Url(formencode.FancyValidator):
547     """Validates an URL. In contrast to fromencode.validators.URL, umlauts are allowed."""
548     urlv = formencode.validators.URL()    
549     def to_python(self, value):
550         self.assert_string(value, None)
551         v = value
552         v = v.replace(u'ä', u'a')
553         v = v.replace(u'ö', u'o')
554         v = v.replace(u'ü', u'u')
555         v = v.replace(u'ß', u'ss')
556         v = self.urlv.to_python(v)
557         return value
558     
559     def from_python(self, value):
560         return value
561
562
563 class UrlNeinNone(NoneValidator):
564     """Validates an URL. In contrast to fromencode.validators.URL, umlauts are allowed.
565     The special value u"Nein" is allowed."""
566     def __init__(self):
567         NoneValidator.__init__(self, NeinValidator(Url()))
568
569
570 class ValueCommentListNeinLoopNone(NoneValidator):
571     """Translates a semicolon separated list of values with optional comments in paranthesis or u'Nein' to itself.
572     An empty string is translated to None:
573     u''                   <=> None
574     u'Nein'               <=> u'Nein'
575     u'T-Mobile (gut); A1' <=> u'T-Mobile (gut); A1'"""
576     def __init__(self):
577         NoneValidator.__init__(self, NeinValidator(Loop(ValueCommentList())))
578
579
580 class PhoneNumber(formencode.FancyValidator):
581     """Telefonnumber in international format, e.g. u'+43-699-1234567'"""
582     def __init__(self, default_cc=43):
583         self.validator = formencode.national.InternationalPhoneNumber(default_cc=lambda: default_cc)
584
585     def to_python(self, value):
586         return unicode(self.validator.to_python(value))
587
588     def from_python(self, value):
589         return self.validator.from_python(value)
590
591
592 class PhoneCommentListNeinLoopNone(NoneValidator):
593     """List with semicolon-separated phone numbers in international format with optional comment or 'Nein' as string:
594     u''                                                       <=> None
595     u'Nein'                                                   <=> u'Nein'
596     u'+43-699-1234567 (nicht nach 20:00 Uhr); +43-512-123456' <=> u'+43-699-1234567 (nicht nach 20:00 Uhr); +43-512-123456'
597     """
598     def __init__(self, comments_are_optional):
599         NoneValidator.__init__(self, NeinValidator(Loop(ValueCommentList(PhoneNumber(default_cc=43), comments_are_optional=comments_are_optional))))
600
601
602 class MaskedEmail(formencode.FancyValidator):
603     """A masked email address as defined here is an email address that has the `@` character replacted by the text `(at)`.
604     So instead of `abd.def@example.com` it would be `abc.def(at)example.com`.
605     This validator takes either a normal or a masked email address in it's to_python method and returns the normal email address as well
606     as a bool indicating whether the email address was masked.
607     u''                       <=> (None, None)
608     u'abc.def@example.com'    <=> (u'abc.def@example.com', False)
609     u'abc.def(at)example.com' <=> (u'abc.def@example.com', True)
610     
611     """
612     def __init__(self, *args, **kw):
613         if not kw.has_key('strip'): kw['strip'] = True
614         if not kw.has_key('not_empty'): kw['not_empty'] = False
615         if not kw.has_key('if_empty'): kw['if_empty'] = (None, None)
616         self.at = '(at)'
617         formencode.FancyValidator.__init__(self, *args, **kw)
618
619     def _to_python(self, value, state):
620         email = value.replace(self.at, '@')
621         masked = value != email
622         val_email = formencode.validators.Email()
623         return val_email.to_python(email), masked
624
625     def _from_python(self, value, state):
626         email, masked = value
627         if email is None: return u''
628         val_email = formencode.validators.Email()
629         email = val_email.from_python(email)
630         if masked: email = email.replace('@', self.at)
631         return email
632
633
634 class EmailCommentListNeinLoopNone(NoneValidator):
635     """Converts a semicolon-separated list of email addresses with optional comments to itself.
636     The special value of u'Nein' indicates that there are no email addresses.
637     The empty string translates to None:
638     u''                                                   <=> None
639     u'Nein'                                               <=> u'Nein'
640     u'first@example.com'                                  <=> u'first@example.com'
641     u'first@example.com (Nur Winter); second@example.com' <=> u'first@example.com (Nur Winter); second@example.com'
642
643     If the parameter allow_masked_email is true, the following gives no error:
644     u'abc.def(at)example.com (comment)'                   <=> u'abc.def(at)example.com (comment)'
645     """
646     def __init__(self, allow_masked_email=False):
647         NoneValidator.__init__(self, NeinValidator(Loop(ValueCommentList(MaskedEmail() if allow_masked_email else formencode.validators.Email()))))
648
649
650 class WikiPage(formencode.FancyValidator):
651     """Validates wiki page name like u'[[Birgitzer Alm]]'.
652     The page is not checked for existance.
653     An empty string is an error.
654     u'[[Birgitzer Alm]]' <=> u'[[Birgitzer Alm]]'
655     """
656     def to_python(self, value):
657         self.assert_string(value, None)
658         if not value.startswith('[[') or not value.endswith(']]'): 
659             raise formencode.Invalid('No valid wiki page name', value, None)
660         return value
661     
662     def from_python(self, value):
663         return value
664
665
666 class WikiPageList(SemicolonList):
667     """Validates a list of wiki pages like u'[[Birgitzer Alm]]; [[Kemater Alm]]'.
668     u'[[Birgitzer Alm]]; [[Kemater Alm]]' <=> [u'[[Birgitzer Alm]]', u'[[Kemater Alm]]']
669     u'[[Birgitzer Alm]]'                  <=> [u'[[Birgitzer Alm]]']
670     u''                                   <=> []
671     """
672     def __init__(self):
673         SemicolonList.__init__(self, WikiPage())
674
675
676 class WikiPageListLoopNone(NoneValidator):
677     """Validates a list of wiki pages like u'[[Birgitzer Alm]]; [[Kemater Alm]]' as string.
678     u'[[Birgitzer Alm]]; [[Kemater Alm]]' <=> u'[[Birgitzer Alm]]; [[Kemater Alm]]'
679     u'[[Birgitzer Alm]]'                  <=> u'[[Birgitzer Alm]]'
680     u''                                   <=> None
681     """
682     def __init__(self):
683         NoneValidator.__init__(self, Loop(WikiPageList()))
684
685
686 class TupleSecondValidator(formencode.FancyValidator):
687     """Does not really validate anything but puts the string through
688     a validator in the second part of a tuple.
689     Examples with an Unsigned() validator and the True argument:
690     u'6' <=> (True, 6)
691     u'2' <=> (True, 2)"""
692     def __init__(self, first=True, validator=UnicodeNone()):
693         self.first = first
694         self.validator = validator
695     
696     def to_python(self, value):
697         self.assert_string(value, None)
698         return self.first, self.validator.to_python(value)
699     
700     def from_python(self, value):
701         assert value[0] == self.first
702         return self.validator.from_python(value[1])
703
704
705 class BoolUnicodeTupleValidator(NoneValidator):
706     """Translates an unparsed string or u'Nein' to a tuple:
707     u''         <=> (None, None)
708     u'Nein'     <=> (False, None)
709     u'any text' <=> (True, u'any text')
710     """
711     def __init__(self, validator=UnicodeNone()):
712         NoneValidator.__init__(self, NeinValidator(TupleSecondValidator(True, validator), (False, None)), (None, None))
713
714
715 class GermanLift(BoolUnicodeTupleValidator):
716     """Checks a lift_details property. It is a value comment property with the following
717     values allowed:
718     u'Sessellift'
719     u'Gondel'
720     u'Linienbus'
721     u'Taxi'
722     u'Sonstige'
723     Alternatively, the value u'Nein' is allowed.
724     An empty string maps to (None, None).
725     
726     Examples:
727     u''                                       <=> (None, None)
728     u'Nein'                                   <=> (False, None)
729     u'Sessellift                              <=> (True, u'Sessellift')
730     u'Gondel (nur bis zur Hälfte)'            <=> (True, u'Gondel (nur bis zur Hälfte)')
731     u'Sessellift; Taxi'                       <=> (True, u'Sessellift; Taxi')
732     u'Sessellift (Wochenende); Taxi (6 Euro)' <=> (True, u'Sessellift (Wochenende); Taxi (6 Euro)')
733     """
734     def __init__(self):
735         BoolUnicodeTupleValidator.__init__(self, Loop(ValueCommentList(DictValidator({u'Sessellift': u'Sessellift', u'Gondel': u'Gondel', u'Linienbus': u'Linienbus', u'Taxi': u'Taxi', u'Sonstige': u'Sonstige'}))))
736         
737
738 class SledRental(BoolUnicodeTupleValidator):
739     """The value can be an empty string, u'Nein' or a comma-separated list of unicode strings with optional comments.
740     u''                                       <=> (None, None)
741     u'Nein'                                   <=> (False, None)
742     u'Talstation (nur mit Ticket); Schneealm' <=> (True, u'Talstation (nur mit Ticket); Schneealm')"""
743     def __init__(self):
744         BoolUnicodeTupleValidator.__init__(self, Loop(ValueCommentList()))