This file is indexed.

/usr/share/pyshared/pyxmpp/jabber/vcard.py is in python-pyxmpp 1.1.2-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
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
#
# (C) Copyright 2003-2010 Jacek Konieczny <jajcus@jajcus.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License Version
# 2.1 as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# pylint: disable-msg=W0302
"""Jabber vCard and MIME (RFC 2426) vCard implementation.

Normative reference:
  - `JEP 54 <http://www.jabber.org/jeps/jep-0054.html>`__
  - `RFC 2425 <http://www.ietf.org/rfc/rfc2425.txt>`__
  - `RFC 2426 <http://www.ietf.org/rfc/rfc2426.txt>`__
"""


__docformat__="restructuredtext en"

import base64
import binascii
import libxml2
import re

import pyxmpp.jid
from pyxmpp.utils import to_utf8,from_utf8
from pyxmpp.xmlextra import get_node_ns
from pyxmpp.objects import StanzaPayloadObject
from pyxmpp.exceptions import BadRequestProtocolError, JIDMalformedProtocolError, JIDError

VCARD_NS="vcard-temp"

class Empty(Exception):
    """Exception raised when parsing empty vcard element. Such element will
    be ignored."""
    pass

valid_string_re=re.compile(r"^[\w\d \t]*$")
non_quoted_semicolon_re=re.compile(r'(?<!\\);')

def quote_semicolon(value):
    return value.replace(r';', r'\;')

def unquote_semicolon(value):
    return value.replace(r'\;', r';')

def rfc2425encode(name,value,parameters=None,charset="utf-8"):
    """Encodes a vCard field into an RFC2425 line.

    :Parameters:
        - `name`: field type name
        - `value`: field value
        - `parameters`: optional parameters
        - `charset`: encoding of the output and of the `value` (if not
          `unicode`)
    :Types:
        - `name`: `str`
        - `value`: `unicode` or `str`
        - `parameters`: `dict` of `str` -> `str`
        - `charset`: `str`

    :return: the encoded RFC2425 line (possibly folded)
    :returntype: `str`"""
    if not parameters:
        parameters={}
    if type(value) is unicode:
        value=value.replace(u"\r\n",u"\\n")
        value=value.replace(u"\n",u"\\n")
        value=value.replace(u"\r",u"\\n")
        value=value.encode(charset,"replace")
    elif type(value) is not str:
        raise TypeError,"Bad type for rfc2425 value"
    elif not valid_string_re.match(value):
        parameters["encoding"]="b"
        value=binascii.b2a_base64(value)

    ret=str(name).lower()
    for k,v in parameters.items():
        ret+=";%s=%s" % (str(k),str(v))
    ret+=":"
    while(len(value)>70):
        ret+=value[:70]+"\r\n "
        value=value[70:]
    ret+=value+"\r\n"
    return ret

class VCardField:
    """Base class for vCard fields.

    :Ivariables:
        - `name`: name of the field.
    """
    def __init__(self,name):
        """Initialize a `VCardField` object.

        Set its name.

        :Parameters:
            - `name`: field name
        :Types:
            - `name`: `str`"""
        self.name=name
    def __repr__(self):
        return "<%s %r>" % (self.__class__,self.rfc2426())
    def rfc2426(self):
        """RFC2426-encode the field content.

        :return: the field in the RFC 2426 format.
        :returntype: `str`"""
        return ""

class VCardString(VCardField):
    """Generic class for all standard text fields in the vCard.

    :Ivariables:
        - `value`: field value.
    :Types:
        - `value`: `unicode`"""
    def __init__(self,name, value, rfc2425parameters = None, empty_ok = False):
        """Initialize a `VCardString` object.

        :Parameters:
            - `name`: field name
            - `value`: field value as string or an XML node
            - `rfc2425parameters`: optional RFC 2425 parameters
        :Types:
            - `name`: `str`
            - `value`: `str` or `libxml2.xmlNode`
            - `rfc2425parameters`: `dict`"""
        _unused = rfc2425parameters
        VCardField.__init__(self,name)
        if isinstance(value,libxml2.xmlNode):
            value=value.getContent()
            if value:
                self.value=unicode(value,"utf-8","replace").strip()
            else:
                self.value=u""
        else:
            self.value=value
        if not self.value and not empty_ok:
            raise Empty,"Empty string value"
    def rfc2426(self):
        """RFC2426-encode the field content.

        :return: the field in the RFC 2426 format.
        :returntype: `str`"""
        return rfc2425encode(self.name,self.value)
    def as_xml(self,parent):
        """Create vcard-tmp XML representation of the field.

        :Parameters:
            - `parent`: parent node for the element
        :Types:
            - `parent`: `libxml2.xmlNode`

        :return: xml node with the field data.
        :returntype: `libxml2.xmlNode`"""
        return parent.newTextChild(None, to_utf8(self.name.upper()), to_utf8(self.value))
    def __unicode__(self):
        return self.value
    def __str__(self):
        return self.value.encode("utf-8")

class VCardXString(VCardString):
    """Generic class for all text vCard fields not defined in RFC 2426.

    In the RFC 2425 representation field name will be prefixed with 'x-'.

    :Ivariables:
        - `value`: field value.
    :Types:
        - `value`: `unicode`"""
    def rfc2426(self):
        """RFC2426-encode the field content.

        :return: the field in the RFC 2426 format.
        :returntype: `str`"""
        return rfc2425encode("x-"+self.name,self.value)

class VCardJID(VCardField):
    """JID vCard field.

    This field is not defined in RFC 2426, so it will be named 'x-jabberid'
    in RFC 2425 output.

    :Ivariables:
        - `value`: field value.
    :Types:
        - `value`: `JID`"""
    def __init__(self,name,value,rfc2425parameters=None):
        """Initialize a `VCardJID` object.

        :Parameters:
            - `name`: field name
            - `value`: field value as string or an XML node
            - `rfc2425parameters`: optional RFC 2425 parameters
        :Types:
            - `name`: `str`
            - `value`: `str` or `libxml2.xmlNode`
            - `rfc2425parameters`: `dict`"""
        _unused = rfc2425parameters
        VCardField.__init__(self,name)
        if isinstance(value,libxml2.xmlNode):
            try:
                self.value=pyxmpp.jid.JID(value.getContent())
            except JIDError:
                raise JIDMalformedProtocolError, "JID malformed"
        else:
            self.value=pyxmpp.jid.JID(value)
        if not self.value:
            raise Empty,"Empty JID value"
    def rfc2426(self):
        """RFC2426-encode the field content.

        :return: the field in the RFC 2426 format.
        :returntype: `str`"""
        return rfc2425encode("x-jabberid",self.value.as_unicode())
    def as_xml(self,parent):
        """Create vcard-tmp XML representation of the field.

        :Parameters:
            - `parent`: parent node for the element
        :Types:
            - `parent`: `libxml2.xmlNode`

        :return: xml node with the field data.
        :returntype: `libxml2.xmlNode`"""
        name=to_utf8(self.name.upper())
        content=self.value.as_utf8()
        return parent.newTextChild(None, name, content)
    def __unicode__(self):
        return self.value.as_unicode()
    def __str__(self):
        return self.value.as_string()

class VCardName(VCardField):
    """Name vCard field.

    :Ivariables:
        - `family`: family name.
        - `given`: given name.
        - `middle`: middle name.
        - `prefix`: name prefix.
        - `suffix`: name suffix.
    :Types:
        - `family`: `unicode`
        - `given`: `unicode`
        - `middle`: `unicode`
        - `prefix`: `unicode`
        - `suffix`: `unicode`"""
    def __init__(self,name,value,rfc2425parameters=None):
        """Initialize a `VCardName` object.

        :Parameters:
            - `name`: field name
            - `value`: field value as string or an XML node
            - `rfc2425parameters`: optional RFC 2425 parameters
        :Types:
            - `name`: `str`
            - `value`: `str` or `libxml2.xmlNode`
            - `rfc2425parameters`: `dict`"""
        _unused = rfc2425parameters
        VCardField.__init__(self,name)
        if self.name.upper()!="N":
            raise RuntimeError,"VCardName handles only 'N' type"
        if isinstance(value,libxml2.xmlNode):
            self.family,self.given,self.middle,self.prefix,self.suffix=[u""]*5
            empty=1
            n=value.children
            vns=get_node_ns(value)
            while n:
                if n.type!='element':
                    n=n.next
                    continue
                ns=get_node_ns(n)
                if (ns and vns and ns.getContent()!=vns.getContent()):
                    n=n.next
                    continue
                if n.name=='FAMILY':
                    self.family=unicode(n.getContent(),"utf-8")
                    empty=0
                if n.name=='GIVEN':
                    self.given=unicode(n.getContent(),"utf-8")
                    empty=0
                if n.name=='MIDDLE':
                    self.middle=unicode(n.getContent(),"utf-8")
                    empty=0
                if n.name=='PREFIX':
                    self.prefix=unicode(n.getContent(),"utf-8")
                    empty=0
                if n.name=='SUFFIX':
                    self.suffix=unicode(n.getContent(),"utf-8")
                    empty=0
                n=n.next
            if empty:
                raise Empty, "Empty N value"
        else:
            v=non_quoted_semicolon_re.split(value)
            value=[u""]*5
            value[:len(v)]=v
            self.family,self.given,self.middle,self.prefix,self.suffix=(
                unquote_semicolon(val) for val in value)
    def rfc2426(self):
        """RFC2426-encode the field content.

        :return: the field in the RFC 2426 format.
        :returntype: `str`"""
        return rfc2425encode("n",u';'.join(quote_semicolon(val) for val in
                (self.family,self.given,self.middle,self.prefix,self.suffix)))
    def as_xml(self,parent):
        """Create vcard-tmp XML representation of the field.

        :Parameters:
            - `parent`: parent node for the element
        :Types:
            - `parent`: `libxml2.xmlNode`

        :return: xml node with the field data.
        :returntype: `libxml2.xmlNode`"""
        n=parent.newChild(None,"N",None)
        n.newTextChild(None,"FAMILY",to_utf8(self.family))
        n.newTextChild(None,"GIVEN",to_utf8(self.given))
        n.newTextChild(None,"MIDDLE",to_utf8(self.middle))
        n.newTextChild(None,"PREFIX",to_utf8(self.prefix))
        n.newTextChild(None,"SUFFIX",to_utf8(self.suffix))
        return n
    def __unicode__(self):
        r=[]
        if self.prefix:
            r.append(self.prefix.replace(u",",u" "))
        if self.given:
            r.append(self.given.replace(u",",u" "))
        if self.middle:
            r.append(self.middle.replace(u",",u" "))
        if self.family:
            r.append(self.family.replace(u",",u" "))
        if self.suffix:
            r.append(self.suffix.replace(u",",u" "))
        return u" ".join(r)
    def __str__(self):
        return self.__unicode__().encode("utf-8")

class VCardImage(VCardField):
    """Image vCard field.

    :Ivariables:
        - `image`: image binary data (when `uri` is None)
        - `uri`: image URI (when `image` is None)
        - `type`: optional image type
    :Types:
        - `image`: `str`
        - `uri`: `unicode`
        - `type`: `unicode`"""
    def __init__(self,name,value,rfc2425parameters=None):
        """Initialize a `VCardImage` object.

        :Parameters:
            - `name`: field name
            - `value`: field value as string or an XML node
            - `rfc2425parameters`: optional RFC 2425 parameters
        :Types:
            - `name`: `str`
            - `value`: `str` or `libxml2.xmlNode`
            - `rfc2425parameters`: `dict`"""
        VCardField.__init__(self,name)
        if not rfc2425parameters:
            rfc2425parameters={}
        self.uri,self.type,self.image=[None]*3
        if isinstance(value,libxml2.xmlNode):
            n=value.children
            vns=get_node_ns(value)
            while n:
                if n.type!='element':
                    n=n.next
                    continue
                ns=get_node_ns(n)
                if (ns and vns and ns.getContent()!=vns.getContent()):
                    n=n.next
                    continue
                if n.name=='TYPE':
                    self.type=unicode(n.getContent(),"utf-8","replace")
                if n.name=='BINVAL':
                    self.image=base64.decodestring(n.getContent())
                if n.name=='EXTVAL':
                    self.uri=unicode(n.getContent(),"utf-8","replace")
                n=n.next
            if (self.uri and self.image) or (not self.uri and not self.image):
                raise ValueError,"Bad %s value in vcard" % (name,)
            if (not self.uri and not self.image):
                raise Empty,"Bad %s value in vcard" % (name,)
        else:
            if rfc2425parameters.get("value", "").lower()=="uri":
                self.uri=value
                self.type=None
            else:
                self.type=rfc2425parameters.get("type")
                self.image=value
    def rfc2426(self):
        """RFC2426-encode the field content.

        :return: the field in the RFC 2426 format.
        :returntype: `str`"""
        if self.uri:
            return rfc2425encode(self.name,self.uri,{"value":"uri"})
        elif self.image:
            if self.type:
                p={"type":self.type}
            else:
                p={}
            return rfc2425encode(self.name,self.image,p)
    def as_xml(self,parent):
        """Create vcard-tmp XML representation of the field.

        :Parameters:
            - `parent`: parent node for the element
        :Types:
            - `parent`: `libxml2.xmlNode`

        :return: xml node with the field data.
        :returntype: `libxml2.xmlNode`"""
        n=parent.newChild(None,self.name.upper(),None)
        if self.uri:
            n.newTextChild(None,"EXTVAL",to_utf8(self.uri))
        else:
            if self.type:
                n.newTextChild(None,"TYPE",self.type)
            n.newTextChild(None,"BINVAL",binascii.b2a_base64(self.image))
        return n
    def __unicode__(self):
        if self.uri:
            return self.uri
        if self.type:
            return u"(%s data)" % (self.type,)
        return u"(binary data)"
    def __str__(self):
        return self.__unicode__().encode("utf-8")


class VCardAdr(VCardField):
    """Address vCard field.

    :Ivariables:
        - `type`: type of the address.
        - `pobox`: the post office box.
        - `extadr`: the extended address.
        - `street`: the street address.
        - `locality`: the locality (e.g. city).
        - `region`: the region.
        - `pcode`: the postal code.
        - `ctry`: the country.
    :Types:
        - `type`: `list` of "home","work","postal","parcel","dom","intl" or "pref"
        - `pobox`: `unicode`
        - `extadr`: `unicode`
        - `street`: `unicode`
        - `locality`: `unicode`
        - `region`: `unicode`
        - `pcode`: `unicode`
        - `ctry`: `unicode`"""
    def __init__(self,name,value,rfc2425parameters=None):
        """Initialize a `VCardAdr` object.

        :Parameters:
            - `name`: field name
            - `value`: field value as string or an XML node
            - `rfc2425parameters`: optional RFC 2425 parameters
        :Types:
            - `name`: `str`
            - `value`: `str` or `libxml2.xmlNode`
            - `rfc2425parameters`: `dict`"""
        VCardField.__init__(self,name)
        if not rfc2425parameters:
            rfc2425parameters={}
        if self.name.upper()!="ADR":
            raise RuntimeError,"VCardAdr handles only 'ADR' type"
        (self.pobox,self.extadr,self.street,self.locality,
                self.region,self.pcode,self.ctry)=[""]*7
        self.type=[]
        if isinstance(value,libxml2.xmlNode):
            self.__from_xml(value)
        else:
            t=rfc2425parameters.get("type")
            if t:
                self.type=t.split(",")
            else:
                self.type=["intl","postal","parcel","work"]
            v=non_quoted_semicolon_re.split(value)
            value=[""]*7
            value[:len(v)]=v
            (self.pobox,self.extadr,self.street,self.locality,
                    self.region,self.pcode,self.ctry)=(
                unquote_semicolon(val) for val in value)

    def __from_xml(self,value):
        """Initialize a `VCardAdr` object from and XML element.

        :Parameters:
            - `value`: field value as an XML node
        :Types:
            - `value`: `libxml2.xmlNode`"""
        n=value.children
        vns=get_node_ns(value)
        while n:
            if n.type!='element':
                n=n.next
                continue
            ns=get_node_ns(n)
            if (ns and vns and ns.getContent()!=vns.getContent()):
                n=n.next
                continue
            if n.name=='POBOX':
                self.pobox=unicode(n.getContent(),"utf-8","replace")
            elif n.name in ('EXTADR', 'EXTADD'):
                self.extadr=unicode(n.getContent(),"utf-8","replace")
            elif n.name=='STREET':
                self.street=unicode(n.getContent(),"utf-8","replace")
            elif n.name=='LOCALITY':
                self.locality=unicode(n.getContent(),"utf-8","replace")
            elif n.name=='REGION':
                self.region=unicode(n.getContent(),"utf-8","replace")
            elif n.name=='PCODE':
                self.pcode=unicode(n.getContent(),"utf-8","replace")
            elif n.name=='CTRY':
                self.ctry=unicode(n.getContent(),"utf-8","replace")
            elif n.name in ("HOME","WORK","POSTAL","PARCEL","DOM","INTL",
                    "PREF"):
                self.type.append(n.name.lower())
            n=n.next
        if self.type==[]:
            self.type=["intl","postal","parcel","work"]
        elif "dom" in self.type and "intl" in self.type:
            raise ValueError,"Both 'dom' and 'intl' specified in vcard ADR"

    def rfc2426(self):
        """RFC2426-encode the field content.

        :return: the field in the RFC 2426 format.
        :returntype: `str`"""
        return rfc2425encode("adr",u';'.join(quote_semicolon(val) for val in
                (self.pobox,self.extadr,self.street,self.locality,
                        self.region,self.pcode,self.ctry)),
                {"type":",".join(self.type)})

    def as_xml(self,parent):
        """Create vcard-tmp XML representation of the field.

        :Parameters:
            - `parent`: parent node for the element
        :Types:
            - `parent`: `libxml2.xmlNode`

        :return: xml node with the field data.
        :returntype: `libxml2.xmlNode`"""
        n=parent.newChild(None,"ADR",None)
        for t in ("home","work","postal","parcel","dom","intl","pref"):
            if t in self.type:
                n.newChild(None,t.upper(),None)
        n.newTextChild(None,"POBOX",to_utf8(self.pobox))
        n.newTextChild(None,"EXTADD",to_utf8(self.extadr))
        n.newTextChild(None,"STREET",to_utf8(self.street))
        n.newTextChild(None,"LOCALITY",to_utf8(self.locality))
        n.newTextChild(None,"REGION",to_utf8(self.region))
        n.newTextChild(None,"PCODE",to_utf8(self.pcode))
        n.newTextChild(None,"CTRY",to_utf8(self.ctry))
        return n

class VCardLabel(VCardField):
    """Address label vCard field.

    :Ivariables:
        - `lines`: list of label text lines.
        - `type`: type of the label.
    :Types:
        - `lines`: `list` of `unicode`
        - `type`: `list` of "home","work","postal","parcel","dom","intl" or "pref"
    """
    def __init__(self,name,value,rfc2425parameters=None):
        """Initialize a `VCardLabel` object.

        :Parameters:
            - `name`: field name
            - `value`: field value as string or an XML node
            - `rfc2425parameters`: optional RFC 2425 parameters
        :Types:
            - `name`: `str`
            - `value`: `str` or `libxml2.xmlNode`
            - `rfc2425parameters`: `dict`"""
        VCardField.__init__(self,name)
        if not rfc2425parameters:
            rfc2425parameters={}
        if self.name.upper()!="LABEL":
            raise RuntimeError,"VCardAdr handles only 'LABEL' type"
        if isinstance(value,libxml2.xmlNode):
            self.lines=[]
            self.type=[]
            n=value.children
            vns=get_node_ns(value)
            while n:
                if n.type!='element':
                    n=n.next
                    continue
                ns=get_node_ns(n)
                if (ns and vns and ns.getContent()!=vns.getContent()):
                    n=n.next
                    continue
                if n.name=='LINE':
                    l=unicode(n.getContent(),"utf-8","replace").strip()
                    l=l.replace("\n"," ").replace("\r"," ")
                    self.lines.append(l)
                elif n.name in ("HOME","WORK","POSTAL","PARCEL","DOM","INTL",
                        "PREF"):
                    self.type.append(n.name.lower())
                n=n.next
            if self.type==[]:
                self.type=["intl","postal","parcel","work"]
            elif "dom" in self.type and "intl" in self.type:
                raise ValueError,"Both 'dom' and 'intl' specified in vcard LABEL"
            if not self.lines:
                self.lines=[""]
        else:
            t=rfc2425parameters.get("type")
            if t:
                self.type=t.split(",")
            else:
                self.type=["intl","postal","parcel","work"]
            self.lines=value.split("\\n")

    def rfc2426(self):
        """RFC2426-encode the field content.

        :return: the field in the RFC 2426 format.
        :returntype: `str`"""
        return rfc2425encode("label",u"\n".join(self.lines),
                {"type":",".join(self.type)})
    def as_xml(self,parent):
        """Create vcard-tmp XML representation of the field.

        :Parameters:
            - `parent`: parent node for the element
        :Types:
            - `parent`: `libxml2.xmlNode`

        :return: xml node with the field data.
        :returntype: `libxml2.xmlNode`"""
        n=parent.newChild(None,"ADR",None)
        for t in ("home","work","postal","parcel","dom","intl","pref"):
            if t in self.type:
                n.newChild(None,t.upper(),None)
        for l in self.lines:
            n.newTextChild(None,"LINE",l)
        return n

class VCardTel(VCardField):
    """Telephone vCard field.

    :Ivariables:
        - `number`: phone number.
        - `type`: type of the phone number.
    :Types:
        - `number`: `unicode`
        - `type`: `list` of "home","work","voice","fax","pager","msg","cell","video","bbs","modem","isdn","pcs" or "pref".
    """
    def __init__(self,name,value,rfc2425parameters=None):
        """Initialize a `VCardTel` object.

        :Parameters:
            - `name`: field name
            - `value`: field value as string or an XML node
            - `rfc2425parameters`: optional RFC 2425 parameters
        :Types:
            - `name`: `str`
            - `value`: `str` or `libxml2.xmlNode`
            - `rfc2425parameters`: `dict`"""
        VCardField.__init__(self,name)
        if not rfc2425parameters:
            rfc2425parameters={}
        if self.name.upper()!="TEL":
            raise RuntimeError,"VCardTel handles only 'TEL' type"
        if isinstance(value,libxml2.xmlNode):
            self.number=None
            self.type=[]
            n=value.children
            vns=get_node_ns(value)
            while n:
                if n.type!='element':
                    n=n.next
                    continue
                ns=get_node_ns(n)
                if (ns and vns and ns.getContent()!=vns.getContent()):
                    n=n.next
                    continue
                if n.name=='NUMBER':
                    self.number=unicode(n.getContent(),"utf-8","replace")
                elif n.name in ("HOME","WORK","VOICE","FAX","PAGER","MSG",
                        "CELL","VIDEO","BBS","MODEM","ISDN","PCS",
                        "PREF"):
                    self.type.append(n.name.lower())
                n=n.next
            if self.type==[]:
                self.type=["voice"]
            if not self.number:
                raise Empty,"No tel number"
        else:
            t=rfc2425parameters.get("type")
            if t:
                self.type=t.split(",")
            else:
                self.type=["voice"]
            self.number=value
    def rfc2426(self):
        """RFC2426-encode the field content.

        :return: the field in the RFC 2426 format.
        :returntype: `str`"""
        return rfc2425encode("tel",self.number,{"type":",".join(self.type)})
    def as_xml(self,parent):
        """Create vcard-tmp XML representation of the field.

        :Parameters:
            - `parent`: parent node for the element
        :Types:
            - `parent`: `libxml2.xmlNode`

        :return: xml node with the field data.
        :returntype: `libxml2.xmlNode`"""
        n=parent.newChild(None,"TEL",None)
        for t in ("home","work","voice","fax","pager","msg","cell","video",
                "bbs","modem","isdn","pcs","pref"):
            if t in self.type:
                n.newChild(None,t.upper(),None)
        n.newTextChild(None,"NUMBER",to_utf8(self.number))
        return n

class VCardEmail(VCardField):
    """E-mail vCard field.

    :Ivariables:
        - `address`: e-mail address.
        - `type`: type of the address.
    :Types:
        - `address`: `unicode`
        - `type`: `list` of "home","work","internet" or "x400".
    """
    def __init__(self,name,value,rfc2425parameters=None):
        """Initialize a `VCardEmail` object.

        :Parameters:
            - `name`: field name
            - `value`: field value as string or an XML node
            - `rfc2425parameters`: optional RFC 2425 parameters
        :Types:
            - `name`: `str`
            - `value`: `str` or `libxml2.xmlNode`
            - `rfc2425parameters`: `dict`"""
        VCardField.__init__(self,name)
        if not rfc2425parameters:
            rfc2425parameters={}
        if self.name.upper()!="EMAIL":
            raise RuntimeError,"VCardEmail handles only 'EMAIL' type"
        if isinstance(value,libxml2.xmlNode):
            self.address=None
            self.type=[]
            n=value.children
            vns=get_node_ns(value)
            while n:
                if n.type!='element':
                    n=n.next
                    continue
                ns=get_node_ns(n)
                if (ns and vns and ns.getContent()!=vns.getContent()):
                    n=n.next
                    continue
                if n.name=='USERID':
                    self.address=unicode(n.getContent(),"utf-8","replace")
                elif n.name in ("HOME","WORK","INTERNET","X400"):
                    self.type.append(n.name.lower())
                n=n.next
            if self.type==[]:
                self.type=["internet"]
            if not self.address:
                raise Empty,"No USERID"
        else:
            t=rfc2425parameters.get("type")
            if t:
                self.type=t.split(",")
            else:
                self.type=["internet"]
            self.address=value
    def rfc2426(self):
        """RFC2426-encode the field content.

        :return: the field in the RFC 2426 format.
        :returntype: `str`"""
        return rfc2425encode("email",self.address,{"type":",".join(self.type)})
    def as_xml(self,parent):
        """Create vcard-tmp XML representation of the field.

        :Parameters:
            - `parent`: parent node for the element
        :Types:
            - `parent`: `libxml2.xmlNode`

        :return: xml node with the field data.
        :returntype: `libxml2.xmlNode`"""
        n=parent.newChild(None,"EMAIL",None)
        for t in ("home","work","internet","x400"):
            if t in self.type:
                n.newChild(None,t.upper(),None)
        n.newTextChild(None,"USERID",to_utf8(self.address))
        return n

class VCardGeo(VCardField):
    """Geographical location vCard field.

    :Ivariables:
        - `lat`: the latitude.
        - `lon`: the longitude.
    :Types:
        - `lat`: `unicode`
        - `lon`: `unicode`
    """
    def __init__(self,name,value,rfc2425parameters=None):
        """Initialize a `VCardGeo` object.

        :Parameters:
            - `name`: field name
            - `value`: field value as string or an XML node
            - `rfc2425parameters`: optional RFC 2425 parameters
        :Types:
            - `name`: `str`
            - `value`: `str` or `libxml2.xmlNode`
            - `rfc2425parameters`: `dict`"""
        _unused = rfc2425parameters
        VCardField.__init__(self,name)
        if self.name.upper()!="GEO":
            raise RuntimeError,"VCardName handles only 'GEO' type"
        if isinstance(value,libxml2.xmlNode):
            self.lat,self.lon=[None]*2
            n=value.children
            vns=get_node_ns(value)
            while n:
                if n.type!='element':
                    n=n.next
                    continue
                ns=get_node_ns(n)
                if (ns and vns and ns.getContent()!=vns.getContent()):
                    n=n.next
                    continue
                if n.name=='LAT':
                    self.lat=unicode(n.getContent(),"utf-8")
                if n.name=='LON':
                    self.lon=unicode(n.getContent(),"utf-8")
                n=n.next
            if not self.lat or not self.lon:
                raise ValueError,"Bad vcard GEO value"
        else:
            self.lat,self.lon=(unquote_semicolon(val) for val in non_quoted_semicolon_re.split(value))
    def rfc2426(self):
        """RFC2426-encode the field content.

        :return: the field in the RFC 2426 format.
        :returntype: `str`"""
        return rfc2425encode("geo",u';'.join(quote_semicolon(val) for val in
                (self.lat,self.lon)))
    def as_xml(self,parent):
        """Create vcard-tmp XML representation of the field.

        :Parameters:
            - `parent`: parent node for the element
        :Types:
            - `parent`: `libxml2.xmlNode`

        :return: xml node with the field data.
        :returntype: `libxml2.xmlNode`"""
        n=parent.newChild(None,"GEO",None)
        n.newTextChild(None,"LAT",to_utf8(self.lat))
        n.newTextChild(None,"LON",to_utf8(self.lon))
        return n

class VCardOrg(VCardField):
    """Organization vCard field.

    :Ivariables:
        - `name`: organization name.
        - `unit`: organizational unit.
    :Types:
        - `name`: `unicode`
        - `unit`: `unicode`
    """
    def __init__(self,name,value,rfc2425parameters=None):
        """Initialize a `VCardOrg` object.

        :Parameters:
            - `name`: field name
            - `value`: field value as string or an XML node
            - `rfc2425parameters`: optional RFC 2425 parameters
        :Types:
            - `name`: `str`
            - `value`: `str` or `libxml2.xmlNode`
            - `rfc2425parameters`: `dict`"""
        _unused = rfc2425parameters
        VCardField.__init__(self,name)
        if self.name.upper()!="ORG":
            raise RuntimeError,"VCardName handles only 'ORG' type"
        if isinstance(value,libxml2.xmlNode):
            self.name,self.unit=None,""
            n=value.children
            vns=get_node_ns(value)
            while n:
                if n.type!='element':
                    n=n.next
                    continue
                ns=get_node_ns(n)
                if (ns and vns and ns.getContent()!=vns.getContent()):
                    n=n.next
                    continue
                if n.name=='ORGNAME':
                    self.name=unicode(n.getContent(),"utf-8")
                if n.name=='ORGUNIT':
                    self.unit=unicode(n.getContent(),"utf-8")
                n=n.next
            if not self.name:
                raise Empty,"Bad vcard ORG value"
        else:
            sp=non_quoted_semicolon_re.split(value,1)
            if len(sp)>1:
                self.name,self.unit=(unquote_semicolon(val) for val in sp)
            else:
                self.name=unquote_semicolon(sp[0])
                self.unit=None
    def rfc2426(self):
        """RFC2426-encode the field content.

        :return: the field in the RFC 2426 format.
        :returntype: `str`"""
        if self.unit:
            return rfc2425encode("org",u';'.join(quote_semicolon(val) for val in
                                      (self.name,self.unit)))
        else:
            return rfc2425encode("org",unicode(quote_semicolon(self.name)))
    def as_xml(self,parent):
        """Create vcard-tmp XML representation of the field.

        :Parameters:
            - `parent`: parent node for the element
        :Types:
            - `parent`: `libxml2.xmlNode`

        :return: xml node with the field data.
        :returntype: `libxml2.xmlNode`"""
        n=parent.newChild(None,"ORG",None)
        n.newTextChild(None,"ORGNAME",to_utf8(self.name))
        n.newTextChild(None,"ORGUNIT",to_utf8(self.unit))
        return n

class VCardCategories(VCardField):
    """Categories vCard field.

    :Ivariables:
        - `keywords`: category keywords.
    :Types:
        - `keywords`: `list` of `unicode`
    """
    def __init__(self,name,value,rfc2425parameters=None):
        """Initialize a `VCardCategories` object.

        :Parameters:
            - `name`: field name
            - `value`: field value as string or an XML node
            - `rfc2425parameters`: optional RFC 2425 parameters
        :Types:
            - `name`: `str`
            - `value`: `str` or `libxml2.xmlNode`
            - `rfc2425parameters`: `dict`"""
        _unused = rfc2425parameters
        VCardField.__init__(self,name)
        self.name=name
        if self.name.upper()!="CATEGORIES":
            raise RuntimeError,"VCardName handles only 'CATEGORIES' type"
        if isinstance(value,libxml2.xmlNode):
            self.keywords=[]
            n=value.children
            vns=get_node_ns(value)
            while n:
                if n.type!='element':
                    n=n.next
                    continue
                ns=get_node_ns(n)
                if (ns and vns and ns.getContent()!=vns.getContent()):
                    n=n.next
                    continue
                if n.name=='KEYWORD':
                    self.keywords.append(unicode(n.getContent(),"utf-8"))
                n=n.next
            if not self.keywords:
                raise Empty,"Bad vcard CATEGORIES value"
        else:
            self.keywords=value.split(",")
    def rfc2426(self):
        """RFC2426-encode the field content.

        :return: the field in the RFC 2426 format.
        :returntype: `str`"""
        return rfc2425encode("keywords",u",".join(self.keywords))
    def as_xml(self,parent):
        """Create vcard-tmp XML representation of the field.

        :Parameters:
            - `parent`: parent node for the element
        :Types:
            - `parent`: `libxml2.xmlNode`

        :return: xml node with the field data.
        :returntype: `libxml2.xmlNode`"""
        n=parent.newChild(None,"CATEGORIES",None)
        for k in self.keywords:
            n.newTextChild(None,"KEYWORD",to_utf8(k))
        return n

class VCardSound(VCardField):
    """Sound vCard field.

    :Ivariables:
        - `sound`: binary sound data (when `uri` is None)
        - `uri`: sound URI (when `sound` is None)
        - `phonetic`: phonetic transcription
    :Types:
        - `sound`: `str`
        - `uri`: `unicode`
        - `phonetic`: `unicode`"""
    def __init__(self,name,value,rfc2425parameters=None):
        """Initialize a `VCardSound` object.

        :Parameters:
            - `name`: field name
            - `value`: field value as string or an XML node
            - `rfc2425parameters`: optional RFC 2425 parameters
        :Types:
            - `name`: `str`
            - `value`: `str` or `libxml2.xmlNode`
            - `rfc2425parameters`: `dict`"""
        VCardField.__init__(self,name)
        if not rfc2425parameters:
            rfc2425parameters={}
        self.uri,self.sound,self.phonetic=[None]*3
        if isinstance(value,libxml2.xmlNode):
            n=value.children
            vns=get_node_ns(value)
            while n:
                if n.type!='element':
                    n=n.next
                    continue
                ns=get_node_ns(n)
                if (ns and vns and ns.getContent()!=vns.getContent()):
                    n=n.next
                    continue
                if n.name=='BINVAL':
                    if (self.phonetic or self.uri):
                        raise ValueError,"Bad SOUND value in vcard"
                    self.sound=base64.decodestring(n.getContent())
                if n.name=='PHONETIC':
                    if (self.sound or self.uri):
                        raise ValueError,"Bad SOUND value in vcard"
                    self.phonetic=unicode(n.getContent(),"utf-8","replace")
                if n.name=='EXTVAL':
                    if (self.phonetic or self.sound):
                        raise ValueError,"Bad SOUND value in vcard"
                    self.uri=unicode(n.getContent(),"utf-8","replace")
                n=n.next
            if (not self.phonetic and not self.uri and not self.sound):
                raise Empty,"Bad SOUND value in vcard"
        else:
            if rfc2425parameters.get("value", "").lower()=="uri":
                self.uri=value
                self.sound=None
                self.phonetic=None
            else:
                self.sound=value
                self.uri=None
                self.phonetic=None
    def rfc2426(self):
        """RFC2426-encode the field content.

        :return: the field in the RFC 2426 format.
        :returntype: `str`"""
        if self.uri:
            return rfc2425encode(self.name,self.uri,{"value":"uri"})
        elif self.sound:
            return rfc2425encode(self.name,self.sound)
    def as_xml(self,parent):
        """Create vcard-tmp XML representation of the field.

        :Parameters:
            - `parent`: parent node for the element
        :Types:
            - `parent`: `libxml2.xmlNode`

        :return: xml node with the field data.
        :returntype: `libxml2.xmlNode`"""
        n=parent.newChild(None,self.name.upper(),None)
        if self.uri:
            n.newTextChild(None,"EXTVAL",to_utf8(self.uri))
        elif self.phonetic:
            n.newTextChild(None,"PHONETIC",to_utf8(self.phonetic))
        else:
            n.newTextChild(None,"BINVAL",binascii.b2a_base64(self.sound))
        return n

class VCardPrivacy(VCardField):
    """Privacy vCard field.

    :Ivariables:
        - `value`: privacy information about the vcard data ("public", "private"
          or "confidental")
    :Types:
        - `value`: `str` """
    def __init__(self,name,value,rfc2425parameters=None):
        """Initialize a `VCardPrivacy` object.

        :Parameters:
            - `name`: field name
            - `value`: field value as string or an XML node
            - `rfc2425parameters`: optional RFC 2425 parameters
        :Types:
            - `name`: `str`
            - `value`: `str` or `libxml2.xmlNode`
            - `rfc2425parameters`: `dict`"""
        _unused = rfc2425parameters
        VCardField.__init__(self,name)
        if isinstance(value,libxml2.xmlNode):
            self.value=None
            n=value.children
            vns=get_node_ns(value)
            while n:
                if n.type!='element':
                    n=n.next
                    continue
                ns=get_node_ns(n)
                if (ns and vns and ns.getContent()!=vns.getContent()):
                    n=n.next
                    continue
                if n.name=='PUBLIC':
                    self.value="public"
                elif n.name=='PRIVATE':
                    self.value="private"
                elif n.name=='CONFIDENTAL':
                    self.value="confidental"
                n=n.next
            if not self.value:
                raise Empty
        else:
            self.value=value
    def rfc2426(self):
        """RFC2426-encode the field content.

        :return: the field in the RFC 2426 format.
        :returntype: `str`"""
        return rfc2425encode(self.name,self.value)
    def as_xml(self,parent):
        """Create vcard-tmp XML representation of the field.

        :Parameters:
            - `parent`: parent node for the element
        :Types:
            - `parent`: `libxml2.xmlNode`

        :return: xml node with the field data.
        :returntype: `libxml2.xmlNode`"""
        if self.value in ("public","private","confidental"):
            n=parent.newChild(None,self.name.upper(),None)
            n.newChild(None,self.value.upper(),None)
            return n
        return None

class VCardKey(VCardField):
    """Key vCard field.

    :Ivariables:
        - `type`: key type.
        - `cred`: key data.
    :Types:
        - `type`: `unicode`
        - `cred`: `str` """
    def __init__(self,name,value,rfc2425parameters=None):
        """Initialize a `VCardKey` object.

        :Parameters:
            - `name`: field name
            - `value`: field value as string or an XML node
            - `rfc2425parameters`: optional RFC 2425 parameters
        :Types:
            - `name`: `str`
            - `value`: `str` or `libxml2.xmlNode`
            - `rfc2425parameters`: `dict`"""
        VCardField.__init__(self,name)
        if not rfc2425parameters:
            rfc2425parameters={}
        if isinstance(value,libxml2.xmlNode):
            self.type,self.cred=None,None
            n=value.children
            vns=get_node_ns(value)
            while n:
                if n.type!='element':
                    n=n.next
                    continue
                ns=get_node_ns(n)
                if (ns and vns and ns.getContent()!=vns.getContent()):
                    n=n.next
                    continue
                if n.name=='TYPE':
                    self.type=unicode(n.getContent(),"utf-8","replace")
                if n.name=='CRED':
                    self.cred=base64.decodestring(n.getContent())
                n=n.next
            if not self.cred:
                raise Empty,"Bad %s value in vcard" % (name,)
        else:
            self.type=rfc2425parameters.get("type")
            self.cred=value
    def rfc2426(self):
        """RFC2426-encode the field content.

        :return: the field in the RFC 2426 format.
        :returntype: `str`"""
        if self.type:
            p={"type":self.type}
        else:
            p={}
        return rfc2425encode(self.name,self.cred,p)
    def as_xml(self,parent):
        """Create vcard-tmp XML representation of the field.

        :Parameters:
            - `parent`: parent node for the element
        :Types:
            - `parent`: `libxml2.xmlNode`

        :return: xml node with the field data.
        :returntype: `libxml2.xmlNode`"""
        n=parent.newChild(None,self.name.upper(),None)
        if self.type:
            n.newTextChild(None,"TYPE",self.type)
        n.newTextChild(None,"CRED",binascii.b2a_base64(self.cred))
        return n

class VCard(StanzaPayloadObject):
    """Jabber (vcard-temp) or RFC2426 vCard.

    :Ivariables:
        - `fn`: full name.
        - `n`: structural name.
        - `nickname`: nickname(s).
        - `photo`: photo(s).
        - `bday`: birthday date(s).
        - `adr`: address(es).
        - `label`: address label(s).
        - `tel`: phone number(s).
        - `email`: e-mail address(es).
        - `jabberid`: JID(s).
        - `mailer`: mailer(s).
        - `tz`: timezone(s).
        - `geo`: geolocation(s).
        - `title`: title(s).
        - `role`: role(s).
        - `logo`: logo(s).
        - `org`: organization(s).
        - `categories`: categories.
        - `note`: note(s).
        - `prodid`: product id(s).
        - `rev`: revision(s).
        - `sort-string`: sort string(s).
        - `sound`: sound(s).
        - `uid`: user identifier(s).
        - `url`: URL(s).
        - `class`: class(es).
        - `key`: key(s).
        - `desc`: description.
    :Types:
        - `fn`: `VCardString`,
        - `n`: `VCardName`,
        - `nickname`: `list` of `VCardString`
        - `photo`: `list` of `VCardImage`
        - `bday`: `list` of `VCardString`
        - `adr`: `list` of `VCardAdr`
        - `label`: `list` of `VCardLabel`
        - `tel`: `list` of `VCardTel`
        - `email`: `list` of `VCardEmail`
        - `jabberid`: `list` of `VCardJID`
        - `mailer`: `list` of `VCardString`
        - `tz`: `list` of `VCardString`
        - `geo`: `list` of `VCardGeo`
        - `title`: `list` of `VCardString`
        - `role`: `list` of `VCardString`
        - `logo`: `list` of `VCardImage`
        - `org`: `list` of `VCardOrg`
        - `categories`: `list` of `VCardCategories`
        - `note`: `list` of `VCardString`
        - `prodid`: `list` of `VCardString`
        - `rev`: `list` of `VCardString`
        - `sort-string`: `list` of `VCardString`
        - `sound`: `list` of `VCardSound`
        - `uid`: `list` of `VCardString`
        - `url`: `list` of `VCardString`
        - `class`: `list` of `VCardString`
        - `key`: `list` of `VCardKey`
        - `desc`: `list` of `VCardXString`
    """

    xml_element_name = "vCard"
    xml_element_namespace = VCARD_NS

    components={
            #"VERSION": (VCardString,"optional"),
            "FN": (VCardString,"required"),
            "N": (VCardName,"required"),
            "NICKNAME": (VCardString,"multi"),
            "PHOTO": (VCardImage,"multi"),
            "BDAY": (VCardString,"multi"),
            "ADR": (VCardAdr,"multi"),
            "LABEL": (VCardLabel,"multi"),
            "TEL": (VCardTel,"multi"),
            "EMAIL": (VCardEmail,"multi"),
            "JABBERID": (VCardJID,"multi"),
            "MAILER": (VCardString,"multi"),
            "TZ": (VCardString,"multi"),
            "GEO": (VCardGeo,"multi"),
            "TITLE": (VCardString,"multi"),
            "ROLE": (VCardString,"multi"),
            "LOGO": (VCardImage,"multi"),
            "AGENT": ("VCardAgent","ignore"), #FIXME: agent field
            "ORG": (VCardOrg,"multi"),
            "CATEGORIES": (VCardCategories,"multi"),
            "NOTE": (VCardString,"multi"),
            "PRODID": (VCardString,"multi"),
            "REV": (VCardString,"multi"),
            "SORT-STRING": (VCardString,"multi"),
            "SOUND": (VCardSound,"multi"),
            "UID": (VCardString,"multi"),
            "URL": (VCardString,"multi"),
            "CLASS": (VCardString,"multi"),
            "KEY": (VCardKey,"multi"),
            "DESC": (VCardXString,"multi"),
        };
    def __init__(self,data):
        """Initialize a VCard object from data which may be XML node
        or an RFC2426 string.

        :Parameters:
            - `data`: vcard to parse.
        :Types:
            - `data`: `libxml2.xmlNode`, `unicode` or `str`"""

        # to make pylint happy
        self.n = None
        del self.n

        self.content={}
        if isinstance(data,libxml2.xmlNode):
            self.__from_xml(data)
        else:
            self.__from_rfc2426(data)
        if not self.content.get("N") and self.content.get("FN"):
            s=self.content['FN'].value.replace(";",",")
            s=s.split(None,2)
            if len(s)==2:
                s=u"%s;%s;;;" % (s[1],s[0])
            elif len(s)==3:
                s=u"%s;%s;%s" % (s[2],s[0],s[1])
            else:
                s=u"%s;;;;" % (s[0],)
            self.content["N"]=VCardName("N",s)
        elif not self.content.get("FN") and self.content.get("N"):
            self.__make_fn()
        for c, (_unused, tp) in self.components.items():
            if self.content.has_key(c):
                continue
            if tp=="required":
                raise ValueError,"%s is missing" % (c,)
            elif tp=="multi":
                self.content[c]=[]
            elif tp=="optional":
                self.content[c]=None
            else:
                continue

    def __make_fn(self):
        """Initialize the mandatory `self.fn` from `self.n`.

        This is a workaround for buggy clients which set only one of them."""
        s=[]
        if self.n.prefix:
            s.append(self.n.prefix)
        if self.n.given:
            s.append(self.n.given)
        if self.n.middle:
            s.append(self.n.middle)
        if self.n.family:
            s.append(self.n.family)
        if self.n.suffix:
            s.append(self.n.suffix)
        s=u" ".join(s)
        self.content["FN"]=VCardString("FN", s, empty_ok = True)

    def __from_xml(self,data):
        """Initialize a VCard object from XML node.

        :Parameters:
            - `data`: vcard to parse.
        :Types:
            - `data`: `libxml2.xmlNode`"""
        ns=get_node_ns(data)
        if ns and ns.getContent()!=VCARD_NS:
            raise ValueError, "Not in the %r namespace" % (VCARD_NS,)
        if data.name!="vCard":
            raise ValueError, "Bad root element name: %r" % (data.name,)
        n=data.children
        dns=get_node_ns(data)
        while n:
            if n.type!='element':
                n=n.next
                continue
            ns=get_node_ns(n)
            if (ns and dns and ns.getContent()!=dns.getContent()):
                n=n.next
                continue
            if not self.components.has_key(n.name):
                n=n.next
                continue
            cl,tp=self.components[n.name]
            if tp in ("required","optional"):
                if self.content.has_key(n.name):
                    raise ValueError,"Duplicate %s" % (n.name,)
                try:
                    self.content[n.name]=cl(n.name,n)
                except Empty:
                    pass
            elif tp=="multi":
                if not self.content.has_key(n.name):
                    self.content[n.name]=[]
                try:
                    self.content[n.name].append(cl(n.name,n))
                except Empty:
                    pass
            n=n.next

    def __from_rfc2426(self,data):
        """Initialize a VCard object from an RFC2426 string.

        :Parameters:
            - `data`: vcard to parse.
        :Types:
            - `data`: `libxml2.xmlNode`, `unicode` or `str`"""
        data=from_utf8(data)
        lines=data.split("\n")
        started=0
        current=None
        for l in lines:
            if not l:
                continue
            if l[-1]=="\r":
                l=l[:-1]
            if not l:
                continue
            if l[0] in " \t":
                if current is None:
                    continue
                current+=l[1:]
                continue
            if not started and current and current.upper().strip()=="BEGIN:VCARD":
                started=1
            elif started and current.upper().strip()=="END:VCARD":
                current=None
                break
            elif current and started:
                self._process_rfc2425_record(current)
            current=l
        if started and current:
            self._process_rfc2425_record(current)

    def _process_rfc2425_record(self,data):
        """Parse single RFC2425 record and update attributes of `self`.

        :Parameters:
            - `data`: the record (probably multiline)
        :Types:
            - `data`: `unicode`"""
        label,value=data.split(":",1)
        value=value.replace("\\n","\n").replace("\\N","\n")
        psplit=label.lower().split(";")
        name=psplit[0]
        params=psplit[1:]
        if u"." in name:
            name=name.split(".",1)[1]
        name=name.upper()
        if name in (u"X-DESC",u"X-JABBERID"):
            name=name[2:]
        if not self.components.has_key(name):
            return
        if params:
            params=dict([p.split("=",1) for p in params])
        cl,tp=self.components[name]
        if tp in ("required","optional"):
            if self.content.has_key(name):
                raise ValueError,"Duplicate %s" % (name,)
            try:
                self.content[name]=cl(name,value,params)
            except Empty:
                pass
        elif tp=="multi":
            if not self.content.has_key(name):
                self.content[name]=[]
            try:
                self.content[name].append(cl(name,value,params))
            except Empty:
                pass
        else:
            return
    def __repr__(self):
        return "<vCard of %r>" % (self.content["FN"].value,)
    def rfc2426(self):
        """Get the RFC2426 representation of `self`.

        :return: the UTF-8 encoded RFC2426 representation.
        :returntype: `str`"""
        ret="begin:VCARD\r\n"
        ret+="version:3.0\r\n"
        for _unused, value in self.content.items():
            if value is None:
                continue
            if type(value) is list:
                for v in value:
                    ret+=v.rfc2426()
            else:
                v=value.rfc2426()
                ret+=v
        return ret+"end:VCARD\r\n"

    def complete_xml_element(self, xmlnode, _unused):
        """Complete the XML node with `self` content.

        Should be overriden in classes derived from `StanzaPayloadObject`.

        :Parameters:
            - `xmlnode`: XML node with the element being built. It has already
              right name and namespace, but no attributes or content.
            - `_unused`: document to which the element belongs.
        :Types:
            - `xmlnode`: `libxml2.xmlNode`
            - `_unused`: `libxml2.xmlDoc`"""
        for _unused1, value in self.content.items():
            if value is None:
                continue
            if type(value) is list:
                for v in value:
                    v.as_xml(xmlnode)
            else:
                value.as_xml(xmlnode)

    def __getattr__(self,name):
        try:
            return self.content[name.upper().replace("_","-")]
        except KeyError:
            raise AttributeError,"Attribute %r not found" % (name,)
    def __getitem__(self,name):
        return self.content[name.upper()]

# vi: sts=4 et sw=4