This file is indexed.

/usr/share/pyshared/pyweblib/forms.py is in python-weblib 1.3.9-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
"""
pyweblib.forms - class library for handling <FORM> input
(c) by Michael Stroeder <michael@stroeder.com>

This module is distributed under the terms of the
GPL (GNU GENERAL PUBLIC LICENSE) Version 2
(see http://www.gnu.org/copyleft/gpl.html)

Python compability note:
This module only works with Python 2.0 since all string parameters
are assumed to be Unicode objects and string methods are used instead
string module.

$Id: forms.py,v 1.47 2012/03/16 13:09:48 michael Exp $
"""

__version__ = '0.16.0'

import sys,types,re,urllib
import helper

def escapeHTML(s):
  """
  Escape all characters with a special meaning in HTML
  to appropriate character tags
  """
  s = s.replace('&','&#38;')
  s = s.replace('<','&#60;')
  s = s.replace('>','&#62;')
  s = s.replace("'",'&#39;')
  s = s.replace('"','&#34;')
  s = s.replace(':','&#58;')
  s = s.replace('=','&#61;')
  s = s.replace('{','&#123;')
  s = s.replace('}','&#125;')
  s = s.replace('(','&#40;')
  s = s.replace(')','&#41;')
  s = s.replace('`','&#96;')
  return s


class Field:
  """
  Base class for all kind of single input fields.

  In most cases this class is not used directly
  since derivate classes for most types of input fields exist.
  """

  def __init__(
    self,name,text,maxLen,maxValues,pattern,required=0,default=None,accessKey='',
  ):
    """
    name
        Field name used in <INPUT NAME="..">
    text
        User-friendly text describing this field
    maxLen
        maximum length of a single input value [Bytes]
    maxValues
        maximum amount of input values
    default
        default value to be used in method inputfield()
    required
        flag which marks field as mandantory input field
    accessKey
        key for accessing this field to be displayed by method inputHTML()
    pattern
        regex pattern of valid values either as string
        or tuple (pattern,options)
    """
    self.value = []
    self.name = name
    self.text = text
    self.maxLen = maxLen
    self.maxValues = maxValues
    self.required = required
    self.accessKey = accessKey
    self.inputHTMLTemplate = r'%s'
    self.valueHTMLTemplate = r'%s'
    # Charset is the preferred character set of the browser.
    # This is set by Form.add() the something meaningful.
    self.charset = 'iso-8859-1'
    self.setDefault(default)
    self.setRegex(pattern)

  def _accessKeyAttr(self):
    if self.accessKey:
      return 'accesskey="%s"' % (self.accessKey)
    else:
      return ''

  def idAttrStr(self,id_value):
    if id_value is None:
      return ''
    else:
      return 'id="%s" ' % (id_value)

  def labelHTML(self,labelText=None,for_value=None):
    labelText = (labelText or self.text).encode(self.charset)
    return '<label for="%s">%s</label>' % (for_value or self.name,labelText)

  def getValue(self):
    """
    Returns self.value in case of multi-valued input or
    self.value[0] if only one value is allowed.
    """
    if self.maxValues>1:
      return self.value
    else:
      return self.value[0]

  def setDefault(self,default):
    """
    Set the default of a field.

    Mainly this is used by the application if self.default shall
    be changed after initializing the field object.
    """
    if type(default)==types.ListType:
      self.default = [i for i in default if i!=None]
    else:
      self.default = default or ''

  def _patternAndOptions(self,pattern):
    """
    The result is a tuple (pattern string,pattern options).

    pattern
        Either a string containing a regex pattern,
        a tuple (pattern string, pattern options) or None.
    """
    if type(pattern) is types.TupleType:
      return pattern
    else:
      return pattern, 0

  def setRegex(self,pattern):
    """
    Set the regex pattern for validating this field.

    Mainly this is used if self._re shall be changed after
    the field object was initialized.

    pattern
        Either a string containing a regex pattern,
        a tuple (pattern string, pattern options) or None.
        If None regex checking in _validateFormat is switched off
        (not recommended).
    """
    patternstring,patternoptions = self._patternAndOptions(pattern)
    if patternstring is None:
      # Regex checking is completely switched off
      self._re = None
    else:
      # This is a Unicode input field
      patternoptions = patternoptions | re.U
      self._re = re.compile('%s$' % patternstring,patternoptions)

  def _validateLen(self,value):
    """Check length of the user's value for this field."""
    if len(value)>self.maxLen:
      raise InvalidValueLen(self.name,self.text,len(value),self.maxLen)

  def _validateFormat(self,value):
    """
    Check format of the user's value for this field.

    Empty input (zero-length string) are valid in any case.
    You might override this method to change this behaviour.
    """
    if (not self._re is None) and value:
      rm = self._re.match(value)
      if rm is None:
        raise InvalidValueFormat(
          self.name,
          self.text.encode(self.charset),
          value.encode(self.charset)
        )

  def _validateMaxValue(self):
    if len(self.value)>=self.maxValues:
      raise TooManyValues(self.name,self.text,len(self.value),self.maxValues)

  def _encodeValue(self,value):
    """
    Return Unicode object or string to be stored in self.value
    """
    try:
      value = unicode(value,self.charset)
    except UnicodeError:
      # Work around buggy browsers...
      value = unicode(value,'iso-8859-1')
    return value

  def setValue(self,value):
    """
    Store the user's value into the field object.

    This method can be used to modify the user's value
    before storing it into self.value.
    """
    value = self._encodeValue(value)
    # Check if input is valid
    # Length valid?
    self._validateLen(value)
    # Format valid?
    self._validateFormat(value)
    self._validateMaxValue()
    self.value.append(value)

  def setCharset(self,charset):
    """Define the character set of the user's input."""
    self.charset = charset

  def _defaultValue(self,default):
    """returns default value"""
    return default or self.__dict__.get('default','')

  def titleHTML(self,title):
    """HTML output of default."""
    return escapeHTML(title or self.text).encode(self.charset)

  def _defaultHTML(self,default):
    """HTML output of default."""
    return escapeHTML(self._defaultValue(default)).encode(self.charset)

  def valueHTML(self):
    """
    HTML output of self.value using the HTML template string
    in self.valueHTMLTemplate.
    """
    return [
      self.valueHTMLTemplate % v
      for v in self.value
    ]


class Textarea(Field):
  """
  Multi-line input field:
  <textarea>
  """

  def __init__(
    self,name,text,maxLen,maxValues,pattern,required=0,default=None,accessKey='',
    rows=10,cols=60
  ):
    self.rows  = rows
    self.cols  = cols
    Field.__init__(
      self,name,text,maxLen,maxValues,None,required,default,accessKey
    )

  def setRegex(self,pattern):
    """
    Like Field.setRegex() but pattern options re.S and re.M are
    automatically added.
    """
    patternstring,patternoptions = self._patternAndOptions(pattern)
    # This is a Unicode input field
    patternoptions = patternoptions | re.M|re.S
    Field.setRegex(self,(patternstring,patternoptions))

  def inputHTML(self,default=None,id_value=None,title=None):
    """Returns string with HTML input field."""
    return self.inputHTMLTemplate % (
      '<textarea %stitle="%s" name="%s" %s rows="%d" cols="%d">%s</textarea>' % (
        self.idAttrStr(id_value),
        self.titleHTML(title),
        self.name,
        self._accessKeyAttr(),
        self.rows,self.cols,
        self._defaultHTML(default)
      )
    )

  def valueHTML(self):
    """
    HTML output of self.value using the HTML template string
    in self.valueHTMLTemplate.
    """
    return [
      self.valueHTMLTemplate % '<pre>%s</pre>' % v
      for v in self.value
    ]


class Input(Field):
  """
  Normal one-line input field:
  <input>
  """

  def __init__(
    self,name,text,maxLen,maxValues,pattern,required=0,default=None,accessKey='',
    size=None
  ):
    self.size = size or maxLen
    Field.__init__(
      self,name,text,maxLen,maxValues,pattern,required,default,accessKey,
    )

  def inputHTML(self,default=None,id_value=None,title=None):
    return self.inputHTMLTemplate % (
      '<input %stitle="%s" name="%s" %s maxlength="%d" size="%d" value="%s">' % (
        self.idAttrStr(id_value),
        self.titleHTML(title),
        self.name,
        self._accessKeyAttr(),
        self.maxLen,
        self.size,
        self._defaultHTML(default)
      )
    )


class HiddenInput(Input):
  """
  Hidden input field:
  <input type="hidden">
  """

  def __init__(
    self,name,text,maxLen,maxValues,pattern,required=0,default=None,accessKey=''
  ):
    Input.__init__(
      self,name,text,maxLen,maxValues,pattern,required,default,accessKey,
    )

  def inputHTML(self,default=None,id_value=None,title=None,show=0):
    default_html = self._defaultHTML(default)
    if show:
      default_str = default_html
    else:
      default_str = ''
    return self.inputHTMLTemplate % (
      '<input type="hidden" %stitle="%s" name="%s" %s  value="%s">%s' % (
        self.idAttrStr(id_value),
        self.titleHTML(title),
        self.name,
        self._accessKeyAttr(),
        default_html,
        default_str
      )
    )


class File(Input):
  """
  File upload field
  <input type="file">
  """
  mimeType='application/octet-stream'

  def _validateFormat(self,value):
    """Binary data is assumed to be valid all the time"""
    return

  def _encodeValue(self,value):
    """
    Return Unicode object or string to be stored in self.value
    """
    return value

  def inputHTML(self,default=None,id_value=None,title=None,mimeType=None):
    return self.inputHTMLTemplate % (
      '<input type="file" %stitle="%s" name="%s" %s accept="%s">' % (
        self.idAttrStr(id_value),
        self.titleHTML(title),
        self.name,
        self._accessKeyAttr(),
        mimeType or self.mimeType
      )
    )


class Password(Input):
  """
  Password input field:
  <input type=password>
  """

  def inputHTML(self,default=None,id_value=None,title=None):
    return self.inputHTMLTemplate % (
      '<input %stitle="%s" name="%s" %s maxlength="%d" size="%d" type="password" value="%s">' % (
        self.idAttrStr(id_value),
        self.titleHTML(title),
        self.name,
        self._accessKeyAttr(),
        self.maxLen,
        self.size,
        default or ''
      )
    )

  def valueHTML(self):
    """For security reasons only stars are printed"""
    return [
      self.valueHTMLTemplate % (len(v)*'*')
      for v in self.value
    ]


class Radio(Field):
  """
  Radio buttons:
  <INPUT TYPE=RADIO>
  """

  def __init__(
    self,name,text,maxValues=1,required=0,default=None,accessKey='',
    options=None
  ):
    """
    pattern and maxLen are determined from __init__ params
    Additional parameters:
    options=[]
      List of options. Either just a list of strings
      ['value1','value2',..] for simple options
      or a list of tuples of string pairs
      [('value1','description1),('value2','description2),..]
      for options with different option value and description.
    """
    self.setOptions(options)
    self.setDefault(default)
    Field.__init__(
      self,name,text,self.maxLen,maxValues,'',required,default,accessKey
    )

  def _validateFormat(self,value):
    """
    Check format of the user's value for this field.

    Empty input (zero-length string) are valid in any case.
    You might override this method to change this behaviour.
    """
    if value and (not value in self.optionValues):
      raise InvalidValueFormat(
        self.name,
        self.text.encode(self.charset),
        value.encode(self.charset)
      )

  def setOptions(self,options):
    self.optionValues = {}
    self.maxLen = 0
    if options:
      optionValues = []
      for i in options:
        if type(i) is types.TupleType:
          optionValue = i[0]
        else:
          optionValue = i
        self.optionValues[optionValue] = None
      self.maxLen = max(map(len,self.optionValues.keys()))
    self.options  = options

  def inputHTML(self,default=None,id_value=None,title=None):
    s = []
    default_value = self._defaultValue(default)
    for i in self.options:
      if type(i) is types.TupleType:
        optionValue,optionText = i
      else:
        optionValue = optionText = i
      s.append("""
        <input
          type="radio"
          %s
          title="%s"
          name="%s"
          %s
          value="%s"
          %s
        >%s<br>
        """ % (
          self.idAttrStr(id_value),
          self.titleHTML(title),
          self.name.encode(self.charset),
          self._accessKeyAttr(),
          optionValue,
          ' checked'*(optionValue==default_value),
          optionText
        )
      )
    return self.inputHTMLTemplate % '\n'.join(s)

  def setDefault(self,default):
    """
    Set the default of a default field.

    Mainly this is used if self.default shall be changed after
    initializing the field object.
    """
    optionValues = []
    for i in self.options:
      if type(i) is types.TupleType:
        optionValues.append(i[0])
      else:
        optionValues.append(i)
    if type(default)==types.StringType and not default in optionValues:
      # Append option to list of options if singleton
      self.options.append(default)
    elif type(default)==types.ListType:
      # Extend list of options with items in default which are not in options
      self.options.extend(filter(lambda x,o=optionValues:not x in o,default))
    self.default = default


class Select(Radio):
  """
  Select field:
  <select multiple>
    <option value="value">description</option>
  </select>
  """

  def __init__(
    self,name,text,maxValues,required=0,default=None,accessKey='',
    options=None,size=1,ignoreCase=0,multiSelect=0,
  ):
    """
    Additional parameters:
    size
      Integer for the size of displayed select field.
    ignorecase
      Integer flag. If non-zero the case of input strings is ignored
      when checking input values.
    multiSelect
      Integer flag. If non-zero the select field has HTML attribute
      "multiple" set.
    """
    self.size        = size
    self.multiSelect = multiSelect
    self.ignoreCase  = ignoreCase
    Radio.__init__(
      self,name,text,maxValues,required,default,accessKey,options,
    )

  def inputHTML(self,default=None,id_value=None,title=None):
    s = ['<select %stitle="%s" name="%s" %s  size="%d" %s>' % (
      self.idAttrStr(id_value),
      self.titleHTML(title),
      self.name,
      self._accessKeyAttr(),
      self.size,
      " multiple"*(self.multiSelect>0)
    )]
    default_value = self._defaultValue(default)
    for i in self.options:
      if type(i) is types.TupleType:
        try:
          optionValue,optionText,optionTitle = i
        except ValueError:
          optionTitle = None
          optionValue,optionText = i
      else:
        optionTitle = None
        optionValue = optionText = i
      if self.multiSelect:
        option_selected = optionValue in default_value
      else:
        option_selected = (optionValue==default_value) or (self.ignoreCase and optionValue.lower()==default_value.lower())
      if optionTitle:
        optionTitle_attr = u' title="%s"' % escapeHTML(optionTitle.encode(self.charset))
      else:
        optionTitle_attr = ''
      s.append(
        '<option value="%s"%s%s>%s</option>' % (
          escapeHTML(optionValue.encode(self.charset)),
          optionTitle_attr,
          ' selected'*(option_selected),
          escapeHTML(optionText.encode(self.charset)),
        )
      )
    s.append('</select>')
    return self.inputHTMLTemplate % '\n'.join(s)


class Checkbox(Field):
  """
  Check boxes:
  <INPUT TYPE=CHECKBOX>
  """

  def __init__(
    self,name,text,maxValues=1,required=0,accessKey='',
    default=None,checked=0
  ):
    """
    pattern and maxLen are determined by default
    """
    pattern = default
    maxLen = len(default or '')
    self.checked = checked
    Field.__init__(
      self,name,text,maxLen,maxValues,pattern,required,default,accessKey
    )

  def inputHTML(self,default=None,id_value=None,title=None,checked=None):
    if checked is None:
      checked = self.checked
    return self.inputHTMLTemplate % (
      '<input type="checkbox" %stitle="%s" name="%s" %s value="%s"%s>' % (
        self.idAttrStr(id_value),
        self.titleHTML(title),
        self.name,
        self._accessKeyAttr(),
        self._defaultValue(default),' checked'*(checked)
      )
    )


class Keygen(Field):
  """
  Select field for client-side key generation with
  Netscape/Mozilla/Opera browser:
  <KEYGEN>
  """

  def __init__(
    self,name,text,maxLen,maxValues,required=0,
    minKeyLength=512
  ):
    Field.__init__(
      self,name,text,maxLen,maxValues,(r'[ -z\r\n]*',re.M+re.S),required
    )
    self.minKeyLength = minKeyLength

  def _encodeValue(self,value):
    return value.replace('\n','').replace('\r','')

  def inputHTML(self,challenge,id_value=None,title=None,):
    return self.inputHTMLTemplate % (
      '<keygen %stitle="%s" name="%s" %s challenge="%s">' % (
        self.idAttrStr(id_value),
        self.titleHTML(title),
        self.name,
        self._accessKeyAttr(),
        challenge
      )
    )

  def valueHTML(self):
    return self.valueHTMLTemplate % ('%d Bytes' % (len(self.value)))


class FormException(Exception):
  """
  Base exception class to indicate form processing errors.

  Attributes:
  args          unstructured List of parameters
  """
  def __init__(self,*args,**kwargs):
    self.args = args
    for key,value in kwargs.items():
      setattr(self,key,value)
  def html(self):
    return escapeHTML(str(self))

class InvalidRequestMethod(FormException):
  """
  Exception raised when HTTP request method was invalid.

  Attributes:
  method        string containing method used
  """
  def __init__(self,method):
    self.method = method
  def __str__(self):
    return 'Invalid request method %s.' % (self.method)

class InvalidFormEncoding(FormException):
  """
  The form data is malformed.

  Attributes:
  param         name/value causing the exception
  """
  def __init__(self,param):
    self.param = param
  def __str__(self):
    return 'The form data is malformed.'

class ContentLengthExceeded(FormException):
  """
  Overall length of input data too large.

  Attributes:
  contentLength         received content length
  maxContentLength      maximum valid content length
  """
  def __init__(self,contentLength,maxContentLength):
    self.contentLength = contentLength
    self.maxContentLength = maxContentLength
  def __str__(self):
    return 'Input length of %d bytes exceeded the maximum of %d bytes.' % (
      self.contentLength,self.maxContentLength
    )

class UndeclaredFieldName(FormException):
  """
  Parameter with undeclared name attribute received.

  Attributes:
  name          name of undeclared field
  """
  def __init__(self,name):
    self.name = name
  def __str__(self):
    return 'Unknown parameter %s.' % (self.name)

class ParamsMissing(FormException):
  """
  Required parameters are missing.

  Attributes:
  missingParamNames     list of strings containing all names of missing
                        input fields.
  """
  def __init__(self,missingParamNames):
    self.missingParamNames = missingParamNames
  def __str__(self):
    return 'Required fields missing: %s' % (
      ', '.join(
        map(
          lambda i:'%s (%s)' % (i[1],i[0]),
          self.missingParamNames
        )
      )
    )

class InvalidValueFormat(FormException):
  """
  The user's input does not match the required format.

  Attributes:
  name          name of input field (Field.name)
  text          textual description of input field (Field.text)
  value         input value received
  """
  def __init__(self,name,text,value):
    self.name = name
    self.text = text
    self.value = value
  def __str__(self):
    return 'Input value "%s" for field %s (%s) has invalid format.' % (
      self.value,self.text,self.name
    )

class InvalidValueLen(FormException):
  """
  Length of user input value invalid.

  Attributes:
  name          name of input field (Field.name)
  text          textual description of input field (Field.text)
  valueLen      integer number of received value length
  maxValueLen   integer number of maximum value length
  """
  def __init__(self,name,text,valueLen,maxValueLen):
    self.name      = name
    self.text      = text
    self.valueLen    = valueLen
    self.maxValueLen = maxValueLen
  def __str__(self):
    return 'Content too long. Field %s (%s) has %d characters but is limited to %d.' % (
      self.text,self.name,self.valueLen,self.maxValueLen
    )

class TooManyValues(FormException):
  """
  User's input contained too many values for same parameter.

  Attributes:
  name                  name of input field (Field.name)
  text                  textual description of input field (Field.text)
  valueCount            integer number of values counted with name
  maxValueCount         integer number of maximum values with name allowed
  """
  def __init__(self,name,text,valueCount,maxValueCount):
    self.name      = name
    self.text      = text
    self.valueCount    = valueCount
    self.maxValueCount = maxValueCount
  def __str__(self):
    return '%d values for field %s (%s). Limited to %d input values.' % (
      self.valueCount,self.text,self.name,self.maxValueCount
    )


class Form:
  """
  Class for declaring and processing a whole <form>
  """

  def __init__(self,inf,env):
    """
    Initialize a Form
    inf                 Read from this file object if method is POST.
    env                 Dictionary holding the environment vars.
    """
    # Dictionary of Field objects
    self.field = {}
    # Ordered list of input field names
    self.declaredFieldNames = []
    # List of parameters names received
    self.inputFieldNames = []
    # Save the environment vars
    self.env = env
    # input file object
    self.inf = inf or sys.stdin
    # Save request method
    self.request_method = env['REQUEST_METHOD']
    self.script_name = env['SCRIPT_NAME']
    # Initialize the AcceptHeaderDict objects
    self.http_accept_charset = helper.AcceptCharsetDict('HTTP_ACCEPT_CHARSET',env)
    self.http_accept_language = helper.AcceptHeaderDict('HTTP_ACCEPT_LANGUAGE',env)
    self.accept_language = self.http_accept_language.keys()
    self.http_accept_encoding = helper.AcceptHeaderDict('HTTP_ACCEPT_ENCODING',env)
    # Set the preferred character set
    self.accept_charset = self.http_accept_charset.preferred()
    # Determine query string and content length dependent on request method
    self.checkRequestMethod()
    return # Form.__init__()

  def checkRequestMethod(self):
    """
    Checks whether the HTTP request method is accepted
    """
    if not self.request_method in ['POST','GET']:
      raise InvalidRequestMethod(self.request_method)

  def getContentType(self):
    """
    Determine the HTTP content type of HTTP request
    """
    if self.request_method=='POST':
      return self.env.get('CONTENT_TYPE','application/x-www-form-urlencoded').lower() or None
    elif self.request_method=='GET':
      return 'application/x-www-form-urlencoded'

  def addField(self,f):
    """
    Add a input field object f to the form.
    """
    f.setCharset(self.accept_charset)
    self.field[f.name] = f
    if not f.name in self.declaredFieldNames:
      self.declaredFieldNames.append(f.name)
    return # Form.addField()

  def getInputValue(self,name,default=[]):
    """
    Return input value of a field defined by name if presented
    in form input. Return default else.
    """
    if name in self.inputFieldNames:
      return self.field[name].value
    else:
      return default

  def hiddenInputFields(self,outf=sys.stdout,ignoreFieldNames=None):
    """
    Output all parameters as hidden fields.

    outf
        File object for output.
    ignoreFieldNames
        Names of parameters to be excluded.
    """
    ignoreFieldNames=ignoreFieldNames or []
    for f in [
      self.field[p]
      for p in self.declaredFieldNames
      if (p in self.inputFieldNames) and not (p in ignoreFieldNames)
    ]:
      for v in f.value:
        outf.write(
          '<input type="hidden" name="%s" value="%s">\n\r' % (
            f.name.encode(f.charset),escapeHTML(v.encode(f.charset))
          )
        )
    return # Form.hiddenInputFields()

  def _parseFormUrlEncoded(self,maxContentLength,ignoreEmptyFields,ignoreUndeclaredFields,stripValues,unquote):

    if self.request_method=='POST':
      query_string = self.inf.read(int(self.env['CONTENT_LENGTH']))
    elif self.request_method=='GET':
      query_string = self.env.get('QUERY_STRING','')

    self.inf.close()

    inputlist = query_string.split('&')

    contentLength = 0

    # Loop over all name attributes declared
    for param in inputlist:

      if param:

        # Einzelne Parametername/-daten-Paare auseinandernehmen
        try:
          name,value = param.split('=',1)
        except ValueError:
          raise InvalidFormEncoding(param)
        name = unquote(name).strip()

        if not name in self.declaredFieldNames:
          if ignoreUndeclaredFields:
            continue
          else:
            raise UndeclaredFieldName(name)

        value = unquote(value)
        if stripValues:
          value = value.strip()

        contentLength += len(value)
        # Gesamtlaenge der Daten noch zulaessig?
        if contentLength > maxContentLength:
          raise ContentLengthExceeded(contentLength,maxContentLength)

        f = self.field[name]

        # input is empty string?
        if value or (not ignoreEmptyFields):
          # Input is stored in field instance
          f.setValue(value)
          # Add name of field to list of input keys
          if not name in self.inputFieldNames:
            self.inputFieldNames.append(name)

    return #_parseFormUrlEncoded()


  def _parseMultipartFormData(self,maxContentLength,ignoreEmptyFields,ignoreUndeclaredFields,stripValues,unquote):

    import cgi
    ctype, pdict = cgi.parse_header(self.env['CONTENT_TYPE'])
    parts = cgi.parse_multipart(self.inf,pdict)

    contentLength = 0

    for name in parts.keys():

      if not name in self.declaredFieldNames:
        if ignoreUndeclaredFields:
          continue
        else:
          raise UndeclaredFieldName(name)

      for value in parts[name]:

#        if stripValues:
#     value = value.strip()

        contentLength += len(value)
        # Gesamtlaenge der Daten noch zulaessig?
        if contentLength > maxContentLength:
          raise ContentLengthExceeded(contentLength,maxContentLength)

        f = self.field[name]

        # input is empty string?
        if value or (not ignoreEmptyFields):
          # Input is stored in field instance
          f.setValue(value)
          # Add name of field to list of input keys
          if not name in self.inputFieldNames:
            self.inputFieldNames.append(name)

    return # _parseMultipartFormData()


  def getInputFields(
    self,
    ignoreEmptyFields=0,
    ignoreUndeclaredFields=0,
    stripValues=1,
    unquotePlus=0,
  ):
    """
    Process user's <form> input and store the values in each
    field instance's content attribute.

    When a processing error occurs FormException (or derivatives)
    are raised.

    ignoreEmptyFields=0         Ignore fields with empty input.
    ignoreUndeclaredFields=0    Ignore fields with names not declared.
                                Normally UndeclaredFieldName is raised.
    stripValues=1               If true leading and trailing whitespaces
                                are stripped from all input values.
    unquotePlus=0
       If non-zero urllib.unquote_plus() is used instead of urllib.unquote().
    """

    unquote = {0:urllib.unquote_plus,1:urllib.unquote_plus}[unquotePlus]

    # Calculate maxContentLength
    maxContentLength = 0
    for name,f in self.field.items():
      maxContentLength += f.maxValues*f.maxLen

    content_type = self.getContentType()
    if content_type.startswith('application/x-www-form-urlencoded'):
      # Parse user's input
      self._parseFormUrlEncoded(maxContentLength,ignoreEmptyFields,ignoreUndeclaredFields,stripValues,unquote)
    elif content_type.startswith('multipart/form-data'):
      self._parseMultipartFormData(maxContentLength,ignoreEmptyFields,ignoreUndeclaredFields,stripValues,unquote)
    else:
      raise FormException('Invalid content type %s received' % (repr(content_type)))


    # Are all required parameters present?
    missing_params = []
    for n,f in self.field.items():
      if f.required and not (f.name in self.inputFieldNames):
        missing_params.append((f.name,f.text))
    if missing_params:
      raise ParamsMissing(missing_params)

    return # Form.getInputFields()