~launchpad-pqm/launchpad/devel

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
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
# Copyright 2009-2011 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

# pylint: disable-msg=E0211,E0213

"""Person interfaces."""

__metaclass__ = type

__all__ = [
    'CLOSED_TEAM_POLICY',
    'IAdminPeopleMergeSchema',
    'IAdminTeamMergeSchema',
    'IHasStanding',
    'IObjectReassignment',
    'IPerson',
    'IPersonClaim',
    'IPersonPublic',
    'IPersonSet',
    'IPersonSettings',
    'ISoftwareCenterAgentAPI',
    'ISoftwareCenterAgentApplication',
    'IPersonLimitedView',
    'IPersonViewRestricted',
    'IRequestPeopleMerge',
    'ITeam',
    'ITeamContactAddressForm',
    'ITeamCreation',
    'ITeamReassignment',
    'ImmutableVisibilityError',
    'NoSuchPerson',
    'OPEN_TEAM_POLICY',
    'PersonCreationRationale',
    'PersonVisibility',
    'PersonalStanding',
    'PRIVATE_TEAM_PREFIX',
    'TeamContactMethod',
    'TeamMembershipRenewalPolicy',
    'TeamSubscriptionPolicy',
    'validate_person',
    'validate_person_or_closed_team',
    'validate_public_person',
    'validate_subscription_policy',
    ]

from lazr.enum import (
    DBEnumeratedType,
    DBItem,
    EnumeratedType,
    Item,
    )
from lazr.lifecycle.snapshot import doNotSnapshot
from lazr.restful.declarations import (
    call_with,
    collection_default_content,
    export_as_webservice_collection,
    export_as_webservice_entry,
    export_factory_operation,
    export_read_operation,
    export_write_operation,
    exported,
    LAZR_WEBSERVICE_EXPORTED,
    operation_for_version,
    operation_parameters,
    operation_returns_collection_of,
    operation_returns_entry,
    rename_parameters_as,
    REQUEST_USER,
    )
from lazr.restful.fields import (
    CollectionField,
    Reference,
    )
from lazr.restful.interface import copy_field
from zope.component import getUtility
from zope.formlib.form import NoInputData
from zope.interface import (
    Attribute,
    Interface,
    )
from zope.interface.exceptions import Invalid
from zope.interface.interface import invariant
from zope.schema import (
    Bool,
    Choice,
    Datetime,
    Int,
    List,
    Object,
    Text,
    TextLine,
    )

from canonical.database.sqlbase import block_implicit_flushes
from canonical.launchpad import _
from lp.services.identity.interfaces.account import (
    AccountStatus,
    IAccount,
    )
from lp.services.identity.interfaces.emailaddress import IEmailAddress
from canonical.launchpad.interfaces.launchpad import (
    IHasIcon,
    IHasLogo,
    IHasMugshot,
    IPrivacy,
    )
from canonical.launchpad.interfaces.validation import validate_new_team_email
from canonical.launchpad.webapp.authorization import check_permission
from canonical.launchpad.webapp.interfaces import ILaunchpadApplication
from lp.answers.interfaces.questionsperson import IQuestionsPerson
from lp.app.errors import NameLookupFailed
from lp.app.interfaces.headings import IRootContext
from lp.app.validators import LaunchpadValidationError
from lp.app.validators.email import email_validator
from lp.app.validators.name import name_validator
from lp.blueprints.interfaces.specificationtarget import IHasSpecifications
from lp.bugs.interfaces.bugtarget import IHasBugs
from lp.code.interfaces.hasbranches import (
    IHasBranches,
    IHasMergeProposals,
    IHasRequestedReviews,
    )
from lp.code.interfaces.hasrecipes import IHasRecipes
from lp.registry.errors import (
    OpenTeamLinkageError,
    PrivatePersonLinkageError,
    TeamSubscriptionPolicyError,
    )
from lp.registry.interfaces.gpg import IGPGKey
from lp.registry.interfaces.irc import IIrcID
from lp.registry.interfaces.jabber import IJabberID
from lp.registry.interfaces.location import (
    IHasLocation,
    ILocationRecord,
    IObjectWithLocation,
    ISetLocation,
    )
from lp.registry.interfaces.mailinglistsubscription import (
    MailingListAutoSubscribePolicy,
    )
from lp.registry.interfaces.ssh import ISSHKey
from lp.registry.interfaces.teammembership import (
    ITeamMembership,
    ITeamParticipation,
    TeamMembershipStatus,
    )
from lp.registry.interfaces.wikiname import IWikiName
from lp.services.fields import (
    BlacklistableContentNameField,
    IconImageUpload,
    is_public_person_or_closed_team,
    is_public_person,
    LogoImageUpload,
    MugshotImageUpload,
    PasswordField,
    PersonChoice,
    PublicPersonChoice,
    StrippedTextLine,
    )
from lp.services.worlddata.interfaces.language import ILanguage
from lp.translations.interfaces.hastranslationimports import (
    IHasTranslationImports,
    )


PRIVATE_TEAM_PREFIX = 'private-'


@block_implicit_flushes
def validate_person_common(obj, attr, value, validate_func,
                           error_class=PrivatePersonLinkageError):
    """Validate the person using the supplied function."""
    if value is None:
        return None
    assert isinstance(value, (int, long)), (
        "Expected int for Person foreign key reference, got %r" % type(value))

    # Importing here to avoid a cyclic import.
    from lp.registry.model.person import Person
    person = Person.get(value)
    if not validate_func(person):
        raise error_class(
            "Cannot link person (name=%s, visibility=%s) to %s (name=%s)"
            % (person.name, person.visibility.name,
               obj, getattr(obj, 'name', None)))
    return value


def validate_person(obj, attr, value):
    """Validate the person is a real person with no other restrictions."""

    def validate(person):
        return IPerson.providedBy(person)

    return validate_person_common(obj, attr, value, validate)


def validate_public_person(obj, attr, value):
    """Validate that the person identified by value is public."""

    def validate(person):
        return is_public_person(person)

    return validate_person_common(obj, attr, value, validate)


def validate_person_or_closed_team(obj, attr, value):

    def validate(person):
        return is_public_person_or_closed_team(person)

    return validate_person_common(
        obj, attr, value, validate, error_class=OpenTeamLinkageError)


def validate_subscription_policy(obj, attr, value):
    """Validate the team subscription_policy."""
    if value is None:
        return None

    # If we are just creating a new team, it can have any subscription policy.
    if getattr(obj, '_SO_creating', True):
        return value

    team = obj
    existing_subscription_policy = getattr(team, 'subscriptionpolicy', None)
    if value == existing_subscription_policy:
        return value
    if value in OPEN_TEAM_POLICY:
        team.checkOpenSubscriptionPolicyAllowed(policy=value)
    if value in CLOSED_TEAM_POLICY:
        team.checkClosedSubscriptionPolicyAllowed(policy=value)
    return value


class PersonalStanding(DBEnumeratedType):
    """A person's standing.

    Standing is currently (just) used to determine whether a person's posts to
    a mailing list require first-post moderation or not.  Any person with good
    or excellent standing may post directly to the mailing list without
    moderation.  Any person with unknown or poor standing must have their
    first-posts moderated.
    """

    UNKNOWN = DBItem(0, """
        Unknown standing

        Nothing about this person's standing is known.
        """)

    POOR = DBItem(100, """
        Poor standing

        This person has poor standing.
        """)

    GOOD = DBItem(200, """
        Good standing

        This person has good standing and may post to a mailing list without
        being subject to first-post moderation rules.
        """)

    EXCELLENT = DBItem(300, """
        Excellent standing

        This person has excellent standing and may post to a mailing list
        without being subject to first-post moderation rules.
        """)


class PersonCreationRationale(DBEnumeratedType):
    """The rationale for the creation of a given person.

    Launchpad automatically creates user accounts under certain
    circumstances. The owners of these accounts may discover Launchpad
    at a later date and wonder why Launchpad knows about them, so we
    need to make it clear why a certain account was automatically created.
    """

    UNKNOWN = DBItem(1, """
        Unknown

        The reason for the creation of this person is unknown.
        """)

    BUGIMPORT = DBItem(2, """
        Existing user in another bugtracker from which we imported bugs.

        A bugzilla import or sf.net import, for instance. The bugtracker from
        which we were importing should be described in
        Person.creation_comment.
        """)

    SOURCEPACKAGEIMPORT = DBItem(3, """
        This person was mentioned in a source package we imported.

        When gina imports source packages, it has to create Person entries for
        the email addresses that are listed as maintainer and/or uploader of
        the package, in case they don't exist in Launchpad.
        """)

    POFILEIMPORT = DBItem(4, """
        This person was mentioned in a POFile imported into Rosetta.

        When importing POFiles into Rosetta, we need to give credit for the
        translations on that POFile to its last translator, which may not
        exist in Launchpad, so we'd need to create it.
        """)

    KEYRINGTRUSTANALYZER = DBItem(5, """
        Created by the keyring trust analyzer.

        The keyring trust analyzer is responsible for scanning GPG keys
        belonging to the strongly connected set and assign all email addresses
        registered on those keys to the people representing their owners in
        Launchpad. If any of these people doesn't exist, it creates them.
        """)

    FROMEMAILMESSAGE = DBItem(6, """
        Created when parsing an email message.

        Sometimes we parse email messages and want to associate them with the
        sender, which may not have a Launchpad account. In that case we need
        to create a Person entry to associate with the email.
        """)

    SOURCEPACKAGEUPLOAD = DBItem(7, """
        This person was mentioned in a source package uploaded.

        Some uploaded packages may be uploaded with a maintainer that is not
        registered in Launchpad, and in these cases, soyuz may decide to
        create the new Person instead of complaining.
        """)

    OWNER_CREATED_LAUNCHPAD = DBItem(8, """
        Created by the owner, coming from Launchpad.

        Somebody was navigating through Launchpad and at some point decided to
        create an account.
        """)

    OWNER_CREATED_SHIPIT = DBItem(9, """
        Created by the owner, coming from Shipit.

        Somebody went to one of the shipit sites to request Ubuntu CDs and was
        directed to Launchpad to create an account.
        """)

    OWNER_CREATED_UBUNTU_WIKI = DBItem(10, """
        Created by the owner, coming from the Ubuntu wiki.

        Somebody went to the Ubuntu wiki and was directed to Launchpad to
        create an account.
        """)

    USER_CREATED = DBItem(11, """
        Created by a user to represent a person which does not use Launchpad.

        A user wanted to reference a person which is not a Launchpad user, so
        he created this "placeholder" profile.
        """)

    OWNER_CREATED_UBUNTU_SHOP = DBItem(12, """
        Created by the owner, coming from the Ubuntu Shop.

        Somebody went to the Ubuntu Shop and was directed to Launchpad to
        create an account.
        """)

    OWNER_CREATED_UNKNOWN_TRUSTROOT = DBItem(13, """
        Created by the owner, coming from unknown OpenID consumer.

        Somebody went to an OpenID consumer we don't know about and was
        directed to Launchpad to create an account.
        """)

    OWNER_SUBMITTED_HARDWARE_TEST = DBItem(14, """
        Created by a submission to the hardware database.

        Somebody without a Launchpad account made a submission to the
        hardware database.
        """)

    BUGWATCH = DBItem(15, """
        Created by the updating of a bug watch.

        A watch was made against a remote bug that the user submitted or
        commented on.
        """)

    SOFTWARE_CENTER_PURCHASE = DBItem(16, """
        Created by purchasing commercial software through Software Center.

        A purchase of commercial software (ie. subscriptions to a private
        and commercial archive) was made via Software Center.
        """)


class TeamMembershipRenewalPolicy(DBEnumeratedType):
    """TeamMembership Renewal Policy.

    How Team Memberships can be renewed on a given team.
    """

    NONE = DBItem(10, """
        invite them to apply for renewal

        Memberships can be renewed only by team administrators or by going
        through the normal workflow for joining the team.
        """)

    ONDEMAND = DBItem(20, """
        invite them to renew their own membership

        Memberships can be renewed by the members themselves a few days before
        it expires. After it expires the member has to go through the normal
        workflow for joining the team.
        """)

    AUTOMATIC = DBItem(30, """
        renew their membership automatically, also notifying the admins

        Memberships are automatically renewed when they expire and a note is
        sent to the member and to team admins.
        """)


class TeamSubscriptionPolicy(DBEnumeratedType):
    """Team Subscription Policies

    The policies that describe who can be a member and how new memberships
    are handled. The choice of policy reflects the need to build a community
    versus the need to control Launchpad assets.
    """

    OPEN = DBItem(2, """
        Open Team

        Membership is open, no approval required, and subteams can be open or
        closed. Any user can be a member of the team and no approval is
        required. Subteams can be Open, Delegated, Moderated, or Restricted.
        Open is a good choice for encouraging a community of contributors.
        Open teams cannot have PPAs.
        """)

    DELEGATED = DBItem(4, """
        Delegated Team

        Membership is open, requires approval, and subteams can be open or
        closed. Any user can be a member of the team via a subteam, but team
        administrators approve direct memberships. Subteams can be Open,
        Delegated, Moderated, or Restricted. Delegated is a good choice for
        managing a large community of contributors. Delegated teams cannot
        have PPAs.
        """)

    MODERATED = DBItem(1, """
        Moderated Team

        Membership is closed, requires approval, and subteams must be closed.
        Any user can propose a new member, but team administrators approve
        membership. Subteams must be Moderated or Restricted. Moderated is a
        good choice for teams that manage things that need to be secure, like
        projects, branches, or PPAs, but want to encourage users to help.
        """)

    RESTRICTED = DBItem(3, """
        Restricted Team

        Membership is closed, requires approval, and subteams must be closed.
        Only the team's administrators can invite a user to be a member.
        Subteams must be Moderated or Restricted. Restricted is a good choice
        for teams that manage things that need to be secure, like projects,
        branches, or PPAs.
        """)


OPEN_TEAM_POLICY = (
    TeamSubscriptionPolicy.OPEN, TeamSubscriptionPolicy.DELEGATED)


CLOSED_TEAM_POLICY = (
    TeamSubscriptionPolicy.RESTRICTED, TeamSubscriptionPolicy.MODERATED)


class PersonVisibility(DBEnumeratedType):
    """The visibility level of person or team objects.

    Currently, only teams can have their visibility set to something
    besides PUBLIC.
    """

    PUBLIC = DBItem(1, """
        Public

        Everyone can view all the attributes of this person.
        """)

    PRIVATE = DBItem(30, """
        Private

        Only Launchpad admins and team members can view the membership list
        for this team or its name.  The team roles are restricted to
        subscribing to bugs, being bug supervisor, owning code branches, and
        having a PPA.
        """)


class PersonNameField(BlacklistableContentNameField):
    """A `Person` team name, which is unique and performs psuedo blacklisting.

    If the team name is not unique, and the clash is with a private team,
    return the blacklist message.  Also return the blacklist message if the
    private prefix is used but the user is not privileged to create private
    teams.
    """
    errormessage = _("%s is already in use by another person or team.")

    blacklistmessage = _("The name '%s' has been blocked by the Launchpad "
                         "administrators.")

    @property
    def _content_iface(self):
        """Return the interface this field belongs to."""
        return IPerson

    def _getByName(self, name):
        """Return a Person by looking up his name."""
        return getUtility(IPersonSet).getByName(name, ignore_merged=False)

    def _validate(self, input):
        """See `UniqueField`."""
        # If the name didn't change then we needn't worry about validating it.
        if self.unchanged(input):
            return

        if not check_permission('launchpad.Commercial', self.context):
            # Commercial admins can create private teams, with or without the
            # private prefix.

            if input.startswith(PRIVATE_TEAM_PREFIX):
                raise LaunchpadValidationError(self.blacklistmessage % input)

            # If a non-privileged user attempts to use an existing name AND
            # the existing project is private, then return the blacklist
            # message rather than the message indicating the project exists.
            existing_object = self._getByAttribute(input)
            if (existing_object is not None and
                existing_object.visibility != PersonVisibility.PUBLIC):
                raise LaunchpadValidationError(self.blacklistmessage % input)

        # Perform the normal validation, including the real blacklist checks.
        super(PersonNameField, self)._validate(input)


def team_subscription_policy_can_transition(team, policy):
    """Can the team can change its subscription policy?

    Returns True when the policy can change. or raises an error. OPEN teams
    cannot be members of MODERATED or RESTRICTED teams. OPEN teams
    cannot have PPAs. Changes from between OPEN and the two closed states
    can be blocked by team membership and team artifacts.

    We only perform the check if a subscription policy is transitioning from
    open->closed or visa versa. So if a team already has a closed subscription
    policy, it is always allowed to transition to another closed policy.

    :param team: The team to change.
    :param policy: The TeamSubsciptionPolicy to change to.
    :raises TeamSubsciptionPolicyError: Raised when a membership constrain
        or a team artifact prevents the policy from being set.
    """
    if team is None or policy == team.subscriptionpolicy:
        # The team is being initialized or the policy is not changing.
        return True
    elif (policy in OPEN_TEAM_POLICY
          and team.subscriptionpolicy in CLOSED_TEAM_POLICY):
        team.checkOpenSubscriptionPolicyAllowed(policy)
    elif (policy in CLOSED_TEAM_POLICY
          and team.subscriptionpolicy in OPEN_TEAM_POLICY):
        team.checkClosedSubscriptionPolicyAllowed(policy)
    return True


class TeamSubsciptionPolicyChoice(Choice):
    """A valid team subscription policy."""

    def _getTeam(self):
        """Return the context if it is a team or None."""
        if IPerson.providedBy(self.context):
            return self.context
        else:
            return None

    def constraint(self, value):
        """See `IField`."""
        team = self._getTeam()
        policy = value
        try:
            return team_subscription_policy_can_transition(team, policy)
        except TeamSubscriptionPolicyError:
            return False

    def _validate(self, value):
        """Ensure the TeamSubsciptionPolicy is valid for state of the team.

        Returns True if the team can change its subscription policy to the
        `TeamSubscriptionPolicy`, otherwise raise TeamSubscriptionPolicyError.
        """
        team = self._getTeam()
        policy = value
        team_subscription_policy_can_transition(team, policy)
        super(TeamSubsciptionPolicyChoice, self)._validate(value)


class IPersonClaim(Interface):
    """The schema used by IPerson's +claim form."""

    emailaddress = TextLine(title=_('Email address'), required=True)


# This has to be defined here to avoid circular import problems.
class IHasStanding(Interface):
    """An object that can have personal standing."""

    personal_standing = Choice(
        title=_('Personal standing'),
        required=True,
        vocabulary=PersonalStanding,
        description=_('The standing of a person for non-member mailing list '
                      'posting privileges.'))

    personal_standing_reason = Text(
        title=_('Reason for personal standing'),
        required=False,
        description=_("The reason the person's standing is what it is."))


class IPersonSettings(Interface):
    """Settings for a person (not a team!) that are used relatively rarely.

    We store these attributes on a separate object, PersonSettings, to which
    the Person class delegates.  This makes it possible to shrink the size of
    the person record.

    In the future, perhaps we will adapt IPerson to IPersonSettings when
    we want these attributes instead of delegating, so we can shrink the
    class, too.

    We also may want TeamSettings and PersonTeamSettings in the future.
    """

    selfgenerated_bugnotifications = Bool(
        title=_("Send me bug notifications for changes I make"),
        required=False, default=False)


class IPersonPublic(IPrivacy):
    """Public attributes for a Person.

    Very few attributes on a person can be public because private teams
    are also persons. The public attributes are generally information
    needed by the system to determine if the principal in the current
    interaction can work with the object.
    """

    id = Int(title=_('ID'), required=True, readonly=True)
    # This is redefined from IPrivacy.private because the attribute is
    # read-only. It is a summary of the team's visibility.
    private = exported(Bool(
            title=_("This team is private"),
            readonly=True, required=False,
            description=_("Private teams are visible only to "
                          "their members.")))
    is_valid_person = Bool(
        title=_("This is an active user and not a team."), readonly=True)
    is_valid_person_or_team = exported(
        Bool(title=_("This is an active user or a team."), readonly=True),
        exported_as='is_valid')
    is_merge_pending = exported(Bool(
        title=_("Is this person due to be merged with another?"),
        required=False, default=False))
    is_team = exported(
        Bool(title=_('Is this object a team?'), readonly=True))
    account_status = Choice(
        title=_("The status of this person's account"), required=False,
        readonly=True, vocabulary=AccountStatus)
    account_status_comment = Text(
        title=_("Why are you deactivating your account?"), required=False,
        readonly=True)


class IPersonLimitedView(IHasIcon, IHasLogo):
    """IPerson attributes that require launchpad.LimitedView permission."""

    name = exported(
        PersonNameField(
            title=_('Name'), required=True, readonly=False,
            constraint=name_validator,
            description=_(
                "A short unique name, beginning with a lower-case "
                "letter or number, and containing only letters, "
                "numbers, dots, hyphens, or plus signs.")))
    displayname = exported(
        StrippedTextLine(
            title=_('Display Name'), required=True, readonly=False,
            description=_(
                "Your name as you would like it displayed throughout "
                "Launchpad. Most people use their full name here.")),
        exported_as='display_name')
    unique_displayname = TextLine(
        title=_('Return a string of the form $displayname ($name).'))
    # NB at this stage we do not allow individual people to have their own
    # icon, only teams get that. People can however have a logo and mugshot
    # The icon is only used for teams; that's why we use /@@/team as the
    # default image resource.
    icon = IconImageUpload(
        title=_("Icon"), required=False,
        default_image_resource='/@@/team',
        description=_(
            "A small image of exactly 14x14 pixels and at most 5kb in size, "
            "that can be used to identify this team. The icon will be "
            "displayed whenever the team name is listed - for example "
            "in listings of bugs or on a person's membership table."))
    iconID = Int(title=_('Icon ID'), required=True, readonly=True)
    logo = exported(
        LogoImageUpload(
            title=_("Logo"), required=False,
            default_image_resource='/@@/person-logo',
            description=_(
                "An image of exactly 64x64 pixels that will be displayed in "
                "the heading of all pages related to you. Traditionally this "
                "is a logo, a small picture or a personal mascot. It should "
                "be no bigger than 50kb in size.")))
    logoID = Int(title=_('Logo ID'), required=True, readonly=True)
    # title is required for the Launchpad Page Layout main template
    title = Attribute('Person Page Title')
    is_probationary = exported(
        Bool(title=_("Is this a probationary user?"), readonly=True))

    @operation_parameters(
        name=TextLine(required=True, constraint=name_validator))
    @operation_returns_entry(Interface)  # Really IArchive.
    @export_read_operation()
    @operation_for_version("beta")
    def getPPAByName(name):
        """Return a PPA with the given name if it exists.

        :param name: A string with the exact name of the ppa being looked up.
        :raises: `NoSuchPPA` if a suitable PPA could not be found.

        :return: a PPA `IArchive` record corresponding to the name.
        """


class IPersonViewRestricted(IHasBranches, IHasSpecifications,
                    IHasMergeProposals, IHasMugshot,
                    IHasLocation, IHasRequestedReviews, IObjectWithLocation,
                    IHasBugs, IHasRecipes, IHasTranslationImports,
                    IPersonSettings, IQuestionsPerson):
    """IPerson attributes that require launchpad.View permission."""
    account = Object(schema=IAccount)
    accountID = Int(title=_('Account ID'), required=True, readonly=True)
    password = PasswordField(
        title=_('Password'), required=True, readonly=False)
    karma = exported(
        Int(title=_('Karma'), readonly=True,
            description=_('The cached total karma for this person.')))
    homepage_content = exported(
        Text(title=_("Homepage Content"), required=False,
            description=_(
                "The content of your profile page. Use plain text, "
                "paragraphs are preserved and URLs are linked in pages.")))

    mugshot = exported(MugshotImageUpload(
        title=_("Mugshot"), required=False,
        default_image_resource='/@@/person-mugshot',
        description=_(
            "A large image of exactly 192x192 pixels, that will be displayed "
            "on your home page in Launchpad. Traditionally this is a great "
            "big picture of your grinning face. Make the most of it! It "
            "should be no bigger than 100kb in size. ")))
    mugshotID = Int(title=_('Mugshot ID'), required=True, readonly=True)

    languages = exported(
        CollectionField(
            title=_('List of languages known by this person'),
            readonly=True, required=False,
            value_type=Reference(schema=ILanguage)))

    hide_email_addresses = exported(
        Bool(title=_("Hide my email addresses from other Launchpad users"),
             required=False, default=False))
    # This is not a date of birth, it is the date the person record was
    # created in this db
    datecreated = exported(
        Datetime(title=_('Date Created'), required=True, readonly=True),
        exported_as='date_created')
    creation_rationale = Choice(
        title=_("Rationale for this entry's creation"), required=False,
        readonly=True, values=PersonCreationRationale.items)
    creation_comment = TextLine(
        title=_("Comment for this entry's creation"),
        description=_(
            "This comment may be displayed verbatim in a web page, so it "
            "has to follow some structural constraints, that is, it must "
            "be of the form: 'when %(action_details)s' (e.g 'when the "
            "foo package was imported into Ubuntu Breezy'). The only "
            "exception to this is when we allow users to create Launchpad "
            "profiles through the /people/+newperson page."),
        required=False, readonly=True)
    # XXX Guilherme Salgado 2006-11-10:
    # We can't use a Choice field here because we don't have a vocabulary
    # which contains valid people but not teams, and we don't really need one
    # apart from here.
    registrant = Attribute('The user who created this profile.')

    oauth_access_tokens = Attribute(_("Non-expired access tokens"))

    oauth_request_tokens = Attribute(_("Non-expired request tokens"))

    sshkeys = exported(
             CollectionField(
                title=_('List of SSH keys'),
                readonly=False, required=False,
                value_type=Reference(schema=ISSHKey)))

    # Properties of the Person object.
    karma_category_caches = Attribute(
        'The caches of karma scores, by karma category.')
    is_ubuntu_coc_signer = exported(
    Bool(title=_("Signed Ubuntu Code of Conduct"),
            readonly=True))
    activesignatures = Attribute("Retrieve own Active CoC Signatures.")
    inactivesignatures = Attribute("Retrieve own Inactive CoC Signatures.")
    signedcocs = Attribute("List of Signed Code Of Conduct")
    gpg_keys = exported(
        CollectionField(
            title=_("List of valid OpenPGP keys ordered by ID"),
            readonly=False, required=False,
            value_type=Reference(schema=IGPGKey)))
    pending_gpg_keys = CollectionField(
        title=_("Set of fingerprints pending confirmation"),
        readonly=False, required=False,
        value_type=Reference(schema=IGPGKey))
    inactive_gpg_keys = Attribute(
        "List of inactive OpenPGP keys in LP Context, ordered by ID")
    wiki_names = exported(
        CollectionField(
            title=_("All WikiNames of this Person, sorted alphabetically by "
                    "URL."),
            readonly=True, required=False,
            value_type=Reference(schema=IWikiName)))
    ircnicknames = exported(
        CollectionField(title=_("List of IRC nicknames of this Person."),
                        readonly=True, required=False,
                        value_type=Reference(schema=IIrcID)),
        exported_as='irc_nicknames')
    jabberids = exported(
        CollectionField(title=_("List of Jabber IDs of this Person."),
                        readonly=True, required=False,
                        value_type=Reference(schema=IJabberID)),
        exported_as='jabber_ids')
    team_memberships = exported(
        CollectionField(
            title=_("All TeamMemberships for Teams this Team or Person is an "
                    "active member of."),
            value_type=Reference(schema=ITeamMembership),
            readonly=True, required=False),
        exported_as='memberships_details')
    open_membership_invitations = exported(
        CollectionField(
            title=_('Open membership invitations.'),
            description=_("All TeamMemberships which represent an invitation "
                          "(to join a team) sent to this person."),
            readonly=True, required=False,
            value_type=Reference(schema=ITeamMembership)))
    # XXX: salgado, 2008-08-01: Unexported because this method doesn't take
    # into account whether or not a team's memberships are private.
    # teams_participated_in = exported(
    #     CollectionField(
    #         title=_('All teams in which this person is a participant.'),
    #         readonly=True, required=False,
    #         value_type=Reference(schema=Interface)),
    #     exported_as='participations')
    teams_participated_in = CollectionField(
        title=_('All teams in which this person is a participant.'),
        readonly=True, required=False,
        value_type=Reference(schema=Interface))
    # XXX: salgado, 2008-08-01: Unexported because this method doesn't take
    # into account whether or not a team's memberships are private.
    # teams_indirectly_participated_in = exported(
    #     CollectionField(
    #         title=_(
    #             'All teams in which this person is an indirect member.'),
    #         readonly=True, required=False,
    #         value_type=Reference(schema=Interface)),
    #     exported_as='indirect_participations')
    teams_indirectly_participated_in = CollectionField(
        title=_('All teams in which this person is an indirect member.'),
        readonly=True, required=False,
        value_type=Reference(schema=Interface))
    teams_with_icons = Attribute(
        "Iterable of all Teams that this person is active in that have "
        "icons")
    guessedemails = Attribute(
        "List of emails with status NEW. These email addresses probably "
        "came from a gina or POFileImporter run.")
    validatedemails = exported(
        CollectionField(
            title=_("Confirmed e-mails of this person."),
            description=_(
                "Confirmed e-mails are the ones in the VALIDATED state"),
            readonly=True, required=False,
            value_type=Reference(schema=IEmailAddress)),
        exported_as='confirmed_email_addresses')
    unvalidatedemails = Attribute(
        "Emails this person added in Launchpad but are not yet validated.")
    specifications = Attribute(
        "Any specifications related to this person, either because the are "
        "a subscriber, or an assignee, or a drafter, or the creator. "
        "Sorted newest-first.")
    assigned_specs = Attribute(
        "Specifications assigned to this person, sorted newest first.")
    assigned_specs_in_progress = Attribute(
        "Specifications assigned to this person whose implementation is "
        "started but not yet completed, sorted newest first.")
    teamowner = exported(
        PublicPersonChoice(
            title=_('Team Owner'), required=False, readonly=False,
            vocabulary='ValidTeamOwner'),
        exported_as='team_owner')
    teamownerID = Int(title=_("The Team Owner's ID or None"), required=False,
                      readonly=True)
    preferredemail = exported(
        Reference(title=_("Preferred email address"),
               description=_("The preferred email address for this person. "
                             "The one we'll use to communicate with them."),
               readonly=True, required=False, schema=IEmailAddress),
        exported_as='preferred_email_address')

    safe_email_or_blank = TextLine(
        title=_("Safe email for display"),
        description=_("The person's preferred email if they have"
                      "one and do not choose to hide it. Otherwise"
                      "the empty string."),
        readonly=True)

    verbose_bugnotifications = Bool(
        title=_("Include bug descriptions when sending me bug notifications"),
        required=False, default=True)

    mailing_list_auto_subscribe_policy = exported(
        Choice(title=_('Mailing List Auto-subscription Policy'),
               required=True,
               vocabulary=MailingListAutoSubscribePolicy,
               default=MailingListAutoSubscribePolicy.ON_REGISTRATION,
               description=_(
                   "This attribute determines whether a person is "
                   "automatically subscribed to a team's mailing list when "
                   "the person joins said team.")))

    merged = Int(
        title=_('Merged Into'), required=False, readonly=True,
        description=_(
            "When a Person is merged into another Person, this attribute "
            "is set on the Person referencing the destination Person. If "
            "this is set to None, then this Person has not been merged "
            "into another and is still valid"))

    archive = exported(
        Reference(
            title=_("Default PPA"),
            description=_("The PPA named 'ppa' owned by this person."),
            readonly=True, required=False,
            # Really IArchive, see archive.py
            schema=Interface))

    ppas = exported(
        CollectionField(
            title=_("PPAs for this person."),
            description=_(
                "PPAs owned by the context person ordered by name."),
            readonly=True, required=False,
            # Really IArchive, see archive.py
            value_type=Reference(schema=Interface)))

    entitlements = Attribute("List of Entitlements for this person or team.")

    structural_subscriptions = Attribute(
        "The structural subscriptions for this person.")

    visibilityConsistencyWarning = Attribute(
        "Warning that a private team may leak membership info.")

    sub_teams = exported(
        CollectionField(
            title=_("All subteams of this team."),
            description=_("""
                A subteam is any team that is a member (either directly or
                indirectly) of this team. As an example, let's say we have
                this hierarchy of teams:

                Rosetta Translators
                    Rosetta pt Translators
                        Rosetta pt_BR Translators

                In this case, both 'Rosetta pt Translators' and 'Rosetta pt_BR
                Translators' are subteams of the 'Rosetta Translators' team,
                and all members of both subteams are considered members of
                "Rosetta Translators".
                """),
            readonly=True, required=False,
            value_type=Reference(schema=Interface)))

    super_teams = exported(
        CollectionField(
            title=_("All superteams of this team."),
            description=_("""
                A superteam is any team that this team is a member of. For
                example, let's say we have this hierarchy of teams, and we are
                the "Rosetta pt_BR Translators":

                Rosetta Translators
                    Rosetta pt Translators
                        Rosetta pt_BR Translators

                In this case, we will return both 'Rosetta pt Translators' and
                'Rosetta Translators', because we are member of both of them.
                """),
            readonly=True, required=False,
            value_type=Reference(schema=Interface)))

    hardware_submissions = exported(CollectionField(
            title=_("Hardware submissions"),
            readonly=True, required=False,
            value_type=Reference(schema=Interface)))  # HWSubmission

    administrated_teams = Attribute(
        u"the teams that this person/team is an administrator of.")

    def anyone_can_join():
        """Quick check as to whether a team allows anyone to join."""

    @invariant
    def personCannotHaveIcon(person):
        """Only Persons can have icons."""
        # XXX Guilherme Salgado 2007-05-28:
        # This invariant is busted! The person parameter provided to this
        # method will always be an instance of zope.formlib.form.FormData
        # containing only the values of the fields included in the POSTed
        # form. IOW, person.inTeam() will raise a NoInputData just like
        # person.teamowner would as it's not present in most of the
        # person-related forms.
        if person.icon is not None and not person.is_team:
            raise Invalid('Only teams can have an icon.')

    def convertToTeam(team_owner):
        """Convert this person into a team owned by the given team_owner.

        Also adds the given team owner as an administrator of the team.

        Only Person entries whose account_status is NOACCOUNT and which are
        not teams can be converted into teams.
        """

    @call_with(registrant=REQUEST_USER)
    @operation_parameters(
        description=Text(),
        distroseries=List(value_type=Reference(schema=Interface)),
        name=TextLine(),
        recipe_text=Text(),
        daily_build_archive=Reference(schema=Interface),
        build_daily=Bool(),
        )
    @export_factory_operation(Interface, [])
    @operation_for_version("beta")
    def createRecipe(name, description, recipe_text, distroseries,
                     registrant, daily_build_archive=None, build_daily=False):
        """Create a SourcePackageRecipe owned by this person.

        :param name: the name to use for referring to the recipe.
        :param description: A description of the recipe.
        :param recipe_text: The text of the recipe.
        :param distroseries: The distroseries to use.
        :param registrant: The person who created this recipe.
        :param daily_build_archive: The archive to use for daily builds.
        :param build_daily: If True, build this recipe daily (if changed).
        :return: a SourcePackageRecipe.
        """

    @operation_parameters(name=TextLine(required=True))
    @operation_returns_entry(Interface)  # Really ISourcePackageRecipe.
    @export_read_operation()
    @operation_for_version("beta")
    def getRecipe(name):
        """Return the person's recipe with the given name."""

    def getMergeQueue(name):
        """Return the person's merge queue with the given name."""

    @call_with(requester=REQUEST_USER)
    @export_read_operation()
    @operation_for_version("beta")
    def getArchiveSubscriptionURLs(requester):
        """Return private archive URLs that this person can see.

        For each of the private archives (PPAs) that this person can see,
        return a URL that includes the HTTP basic auth data.  The URL
        returned is suitable for including in a sources.list file.
        """

    @call_with(requester=REQUEST_USER)
    @operation_parameters(
        archive=Reference(schema=Interface))  # Really IArchive
    @export_write_operation()
    @operation_for_version("beta")
    def getArchiveSubscriptionURL(requester, archive):
        """Get a text line that is suitable to be used for a sources.list
        entry.

        It will create a new IArchiveAuthToken if one doesn't already exist.
        """

    def getInvitedMemberships():
        """Return all TeamMemberships of this team with the INVITED status.

        The results are ordered using Person.sortingColumns.
        """

    def getInactiveMemberships():
        """Return all inactive TeamMemberships of this team.

        Inactive memberships are the ones with status EXPIRED or DEACTIVATED.

        The results are ordered using Person.sortingColumns.
        """

    def getProposedMemberships():
        """Return all TeamMemberships of this team with the PROPOSED status.

        The results are ordered using Person.sortingColumns.
        """

    @operation_returns_collection_of(Interface)
    @export_read_operation()
    @operation_for_version("beta")
    def getBugSubscriberPackages():
        """Return the packages for which this person is a bug subscriber.

        Returns a list of IDistributionSourcePackage's, ordered alphabetically
        (A to Z) by name.
        """

    def setContactAddress(email):
        """Set the given email address as this team's contact address.

        This method must be used only for teams, unless the disable argument
        is True.

        If the team has a contact address its status will be changed to
        VALIDATED.

        If the given email is None the team is left without a contact address.
        """

    def setPreferredEmail(email):
        """Set the given email address as this person's preferred one.

        If ``email`` is None, the preferred email address is unset, which
        will make the person invalid.

        This method must be used only for people, not teams.
        """

    # XXX: salgado, 2008-08-01: Unexported because this method doesn't take
    # into account whether or not a team's memberships are private.
    # @operation_parameters(team=copy_field(ITeamMembership['team']))
    # @operation_returns_collection_of(Interface) # Really IPerson
    # @export_read_operation()
    def findPathToTeam(team):
        """Return the teams providing membership to the given team.

        If there is more than one path leading this person to the given team,
        only the one with the oldest teams is returned.

        This method must not be called if this person is not an indirect
        member of the given team.
        """

    # XXX BarryWarsaw 2007-11-29: I'd prefer for this to be an Object() with a
    # schema of IMailingList, but setting that up correctly causes a circular
    # import error with interfaces.mailinglists that is too difficult to
    # unfunge for this one attribute.
    mailing_list = Attribute(
        _("The team's mailing list, if it has one, otherwise None."))

    def getProjectsAndCategoriesContributedTo(limit=10):
        """Return a list of dicts with projects and the contributions made
        by this person on that project.

        The list is limited to the :limit: projects this person is most
        active.

        The dictionaries containing the following keys:
            - project:    The project, which is either an IProduct or an
                          IDistribution.
            - categories: A dictionary mapping KarmaCategory titles to
                          the icons which represent that category.
        """

    def getOwnedOrDrivenPillars():
        """Return the pillars that this person directly owns or drives."""

    def getOwnedProjects(match_name=None):
        """Projects owned by this person or teams to which she belongs.

        :param match_name: string optional project name to screen the results.
        """

    def isAnyPillarOwner():
        """Is this person the owner of any pillar?"""

    def isAnySecurityContact():
        """Is this person the security contact of any pillar?"""

    def getAllCommercialSubscriptionVouchers(voucher_proxy=None):
        """Return all commercial subscription vouchers.

        All of a `Person`s vouchers are returned, regardless of redemption
        status.  Even vouchers marked inactive are returned.
        The result is a dictionary, indexed by the three
        voucher statuses.
        :return: dict
        """

    def getRedeemableCommercialSubscriptionVouchers(voucher_proxy=None):
        """Return the set of redeemable vouchers.

        The `Person`s vouchers are returned if they are unredeemed and active.

        The result is a list of vouchers.
        :return: list
        """

    def assignKarma(action_name, product=None, distribution=None,
                    sourcepackagename=None, datecreated=None):
        """Assign karma for the action named <action_name> to this person.

        This karma will be associated with the given product or distribution.
        If a distribution is given, then product must be None and an optional
        sourcepackagename may also be given. If a product is given, then
        distribution and sourcepackagename must be None.

        If a datecreated is specified, the karma will be created with that
        date.  This is how historic karma events can be created.
        """

    def latestKarma(quantity=25):
        """Return the latest karma actions for this person.

        Return no more than the number given as quantity.
        """

    def iterTopProjectsContributedTo(limit=10):
        """Iterate over the top projects contributed to.

        Iterate no more than the given limit.
        """

    # XXX: salgado, 2008-08-01: Unexported because this method doesn't take
    # into account whether or not a team's memberships are private.
    # @operation_parameters(team=copy_field(ITeamMembership['team']))
    # @export_read_operation()
    def inTeam(team):
        """Is this person is a member of `team`?

        Returns `True` when you ask if an `IPerson` (or an `ITeam`,
        since it inherits from `IPerson`) is a member of himself
        (i.e. `person1.inTeam(person1)`).

        :param team: Either an object providing `IPerson`, the string name of
            a team or `None`. If a string was supplied the team is looked up.
        :return: A bool with the result of the membership lookup. When looking
            up the team from a string finds nothing or team was `None` then
            `False` is returned.
        """

    def clearInTeamCache():
        """Clears the person's inTeam cache.

        To be used when membership changes are enacted. Only meant to be
        used between TeamMembership and Person objects.
        """

    def getLatestMaintainedPackages():
        """Return `SourcePackageRelease`s maintained by this person.

        This method will only include the latest source package release
        for each source package name, distribution series combination.
        """

    def getLatestSynchronisedPublishings():
        """Return `SourcePackagePublishingHistory`s synchronised by this
        person.

        This method will only include the latest publishings for each source
        package name, distribution series combination.
        """

    def getLatestUploadedButNotMaintainedPackages():
        """Return `SourcePackageRelease`s created by this person but
        not maintained by him.

        This method will only include the latest source package release
        for each source package name, distribution series combination.
        """

    def getLatestUploadedPPAPackages():
        """Return `SourcePackageRelease`s uploaded by this person to any PPA.

        This method will only include the latest source package release
        for each source package name, distribution series combination.
        """

    def isUploader(distribution):
        """Return whether this person is an uploader for distribution.

        Returns True if this person is an uploader for distribution, or
        False otherwise.
        """

    def validateAndEnsurePreferredEmail(email):
        """Ensure this person has a preferred email.

        If this person doesn't have a preferred email, <email> will be set as
        this person's preferred one. Otherwise it'll be set as VALIDATED and
        this person will keep their old preferred email.

        This method is meant to be the only one to change the status of an
        email address, but as we all know the real world is far from ideal
        and we have to deal with this in one more place, which is the case
        when people explicitly want to change their preferred email address.
        On that case, though, all we have to do is use
        person.setPreferredEmail().
        """

    def hasParticipationEntryFor(team):
        """Return True when this person is a member of the given team.

        The person's membership may be direct or indirect.
        """

    def getAdministratedTeams():
        """Return the teams that this person/team is an administrator of.

        This includes teams for which the person is the owner, a direct
        member with admin privilege, or member of a team with such
        privileges.  It excludes teams which have been merged.
        """

    def getTeamAdminsEmailAddresses():
        """Return a set containing the email addresses of all administrators
        of this team.
        """

    def getLatestApprovedMembershipsForPerson(limit=5):
        """Return the <limit> latest approved membrships for this person."""

    def getPathsToTeams():
        """Return the paths to all teams related to this person."""

    @operation_parameters(
        language=Reference(schema=ILanguage))
    @export_write_operation()
    @operation_for_version("devel")
    def addLanguage(language):
        """Add a language to this person's preferences.

        :param language: An object providing ILanguage.

        If the given language is one of the user's preferred languages
        already, nothing will happen.
        """

    @operation_parameters(
        language=Reference(schema=ILanguage))
    @export_write_operation()
    @operation_for_version("devel")
    def removeLanguage(language):
        """Remove a language from this person's preferences.

        :param language: An object providing ILanguage.

        If the given language is not present, nothing  will happen.
        """

    def isBugContributor(user):
        """Is the person a contributer to bugs in Launchpad?

        Return True if the user has any bugs assigned to him, either
        directly or by team participation.

        :user: The user doing the search. Private bugs that this
        user doesn't have access to won't be included in the
        count.
        """

    def isBugContributorInTarget(user, target):
        """Is the person a contributor to bugs in `target`?

        Return True if the user has any bugs assigned to him in the
        context of a specific target, either directly or by team
        participation.

        :user: The user doing the search. Private bugs that this
        user doesn't have access to won't be included in the
        count.

        :target: An object providing `IBugTarget` to search within.
        """

    def autoSubscribeToMailingList(mailinglist, requester=None):
        """Subscribe this person to a mailing list.

        This method takes the user's mailing list auto-subscription
        setting into account, and it may or may not result in a list
        subscription.  It will only subscribe the user to the mailing
        list if all of the following conditions are met:

          * The mailing list is not None.
          * The mailing list is in an unusable state.
          * The user is not already subscribed.
          * The user has a preferred address set.
          * The user's auto-subscribe preference is ALWAYS, or
          * The user's auto-subscribe preference is ON_REGISTRATION,
            and the requester is either themself or None.

        This method will not raise exceptions if any of the above are
        not true.  If you want these problems to raise exceptions
        consider using `IMailinglist.subscribe()` directly.

        :param mailinglist: The list to subscribe to.  No action is
                taken if the list is None, or in an unusable state.

        :param requester: The person requesting the list subscription,
                if not the user himself.  The default assumes the user
                themself is making the request.

        :return: True if the user was subscribed, false if they weren't.
        """

    @operation_parameters(
        name=TextLine(required=True, constraint=name_validator),
        displayname=TextLine(required=False),
        description=TextLine(required=False),
        private=Bool(required=False),
        )
    @export_factory_operation(Interface, [])  # Really IArchive.
    @operation_for_version("beta")
    def createPPA(name=None, displayname=None, description=None,
                  private=False):
        """Create a PPA.

        :param name: A string with the name of the new PPA to create. If
            not specified, defaults to 'ppa'.
        :param displayname: The displayname for the new PPA.
        :param description: The description for the new PPA.
        :param private: Whether or not to create a private PPA. Defaults to
            False, which means the PPA will be public.
        :raises: `PPACreationError` if an error is encountered

        :return: a PPA `IArchive` record.
        """

    def checkRename():
        """Check if a person or team can be renamed.

        :return: a text string of the reason, or None if the rename is
        allowed.
        """

    def canCreatePPA():
        """Check if a person or team can create a PPA.

        :return: a boolean.
        """

    active_member_count = Attribute(
        "The number of real people who are members of this team.")
    # activemembers.value_type.schema will be set to IPerson once
    # IPerson is defined.
    activemembers = Attribute(
        'List of direct members with ADMIN or APPROVED status')
    # For the API we need eager loading
    api_activemembers = exported(
        doNotSnapshot(
            CollectionField(
                title=_(
                    "List of direct members with ADMIN or APPROVED status"),
                value_type=Reference(schema=Interface))),
        exported_as='members')
    adminmembers = exported(
        doNotSnapshot(
            CollectionField(
                title=_("List of this team's admins."),
                value_type=Reference(schema=Interface))),
        exported_as='admins')
    all_member_count = Attribute(
        "The total number of real people who are members of this team, "
        "including subteams.")
    all_members_prepopulated = exported(
        doNotSnapshot(
            CollectionField(
                title=_("All participants of this team."),
                description=_(
                    "List of all direct and indirect people and teams who, "
                    "one way or another, are a part of this team. If you "
                    "want a method to check if a given person is a member "
                    "of a team, you should probably look at "
                    "IPerson.inTeam()."),
                value_type=Reference(schema=Interface))),
        exported_as='participants')
    allmembers = doNotSnapshot(
        Attribute("List of all members, without checking karma etc."))
    approvedmembers = doNotSnapshot(
        Attribute("List of members with APPROVED status"))
    deactivated_member_count = Attribute("Number of deactivated members")
    deactivatedmembers = exported(
        doNotSnapshot(
            CollectionField(
                title=_(
                    "All members whose membership is in the "
                    "DEACTIVATED state"),
                value_type=Reference(schema=Interface))),
        exported_as='deactivated_members')
    expired_member_count = Attribute("Number of EXPIRED members.")
    expiredmembers = exported(
        doNotSnapshot(
            CollectionField(
                title=_("All members whose membership is in the "
                        "EXPIRED state"),
                value_type=Reference(schema=Interface))),
        exported_as='expired_members')
    inactivemembers = doNotSnapshot(
        Attribute(
            "List of members with EXPIRED or DEACTIVATED status"))
    inactive_member_count = Attribute("Number of inactive members")
    invited_members = exported(
        doNotSnapshot(
            CollectionField(
                title=_("All members whose membership is "
                        "in the INVITED state"),
                value_type=Reference(schema=Interface))))

    invited_member_count = Attribute("Number of members with INVITED status")
    member_memberships = exported(
        doNotSnapshot(
            CollectionField(
                title=_("Active TeamMemberships for this object's members."),
                description=_(
                    "Active TeamMemberships are the ones with the ADMIN or "
                    "APPROVED status.  The results are ordered using "
                    "Person.sortingColumns."),
                readonly=True, required=False,
                value_type=Reference(schema=ITeamMembership))),
        exported_as='members_details')
    pendingmembers = doNotSnapshot(
        Attribute(
            "List of members with INVITED or PROPOSED status"))
    proposedmembers = exported(
        doNotSnapshot(
            CollectionField(
                title=_("All members whose membership is in the "
                        "PROPOSED state"),
                value_type=Reference(schema=Interface))),
        exported_as='proposed_members')
    proposed_member_count = Attribute("Number of PROPOSED members")

    mapped_participants_count = Attribute(
        "The number of mapped participants")
    unmapped_participants = doNotSnapshot(
        CollectionField(
            title=_("List of participants with no coordinates recorded."),
            value_type=Reference(schema=Interface)))
    unmapped_participants_count = Attribute(
        "The number of unmapped participants")

    def getMappedParticipants(limit=None):
        """List of participants with coordinates.

        :param limit: The optional maximum number of items to return.
        :return: A list of `IPerson` objects
        """

    def getMappedParticipantsBounds():
        """Return a dict of the bounding longitudes latitudes, and centers.

        This method cannot be called if there are no mapped participants.

        :return: a dict containing: min_lat, min_lng, max_lat, max_lng,
            center_lat, and center_lng
        """

    def getMembersWithPreferredEmails():
        """Returns a result set of persons with precached addresses.

        Persons or teams without preferred email addresses are not included.
        """

    def getMembersWithPreferredEmailsCount():
        """Returns the count of persons/teams with preferred emails.

        See also getMembersWithPreferredEmails.
        """

    def getDirectAdministrators():
        """Return this team's administrators.

        This includes all direct members with admin rights and also
        the team owner. Note that some other persons/teams might have admin
        privilege by virtue of being a member of a team with admin rights.
        """

    @operation_parameters(status=copy_field(ITeamMembership['status']))
    @operation_returns_collection_of(Interface)  # Really IPerson
    @export_read_operation()
    @operation_for_version("beta")
    def getMembersByStatus(status, orderby=None):
        """Return the people whose membership on this team match :status:.

        If no orderby is provided, Person.sortingColumns is used.
        """


class IPersonEditRestricted(Interface):
    """IPerson attributes that require launchpad.Edit permission."""

    @call_with(requester=REQUEST_USER)
    @operation_parameters(team=copy_field(ITeamMembership['team']))
    @export_write_operation()
    @operation_for_version("beta")
    def join(team, requester=None, may_subscribe_to_list=True):
        """Join the given team if its subscriptionpolicy is not RESTRICTED.

        Join the given team according to the policies and defaults of that
        team:

        - If the team subscriptionpolicy is OPEN, the user is added as
          an APPROVED member with a NULL TeamMembership.reviewer.
        - If the team subscriptionpolicy is MODERATED, the user is added as
          a PROPOSED member and one of the team's administrators have to
          approve the membership.

        If may_subscribe_to_list is True, then also attempt to
        subscribe to the team's mailing list, depending on the list
        status and the person's auto-subscribe settings.

        :param requester: The person who requested the membership on
            behalf of a team or None when a person requests the
            membership for himself.

        :param may_subscribe_to_list: If True, also try subscribing to
            the team mailing list.
        """

    @operation_parameters(team=copy_field(ITeamMembership['team']))
    @export_write_operation()
    @operation_for_version("beta")
    def leave(team):
        """Leave the given team.

        This is a convenience method for retractTeamMembership() that allows
        a user to leave the given team, or to cancel a PENDING membership
        request.

        :param team: The team to leave.
        """

    @operation_parameters(
        visible=copy_field(ILocationRecord['visible'], required=True))
    @export_write_operation()
    @operation_for_version("beta")
    def setLocationVisibility(visible):
        """Specify the visibility of a person's location and time zone."""

    def setMembershipData(person, status, reviewer, expires=None,
                          comment=None):
        """Set the attributes of the person's membership on this team.

        Set the status, dateexpires, reviewer and comment, where reviewer is
        the user responsible for this status change and comment is the comment
        left by the reviewer for the change.

        This method will ensure that we only allow the status transitions
        specified in the TeamMembership spec. It's also responsible for
        filling/cleaning the TeamParticipation table when the transition
        requires it.
        """

    @call_with(reviewer=REQUEST_USER)
    @operation_parameters(
        person=copy_field(ITeamMembership['person']),
        status=copy_field(ITeamMembership['status']),
        comment=Text(required=False))
    @export_write_operation()
    @operation_for_version("beta")
    def addMember(person, reviewer, status=TeamMembershipStatus.APPROVED,
                  comment=None, force_team_add=False,
                  may_subscribe_to_list=True):
        """Add the given person as a member of this team.

        :param person: If the given person is already a member of this
            team we'll simply change its membership status. Otherwise a new
            TeamMembership is created with the given status.

        :param reviewer: The user who made the given person a member of this
            team.

        :param comment: String that will be assigned to the
            proponent_comment, reviwer_comment, or acknowledger comment.

        :param status: `TeamMembershipStatus` value must be either
            Approved, Proposed or Admin.
            If the new member is a team, the status will be changed to
            Invited unless the user is also an admin of that team.

        :param force_team_add: If the person is actually a team and
            force_team_add is False, the team will actually be invited to
            join this one. Otherwise the team is added as if it were a
            person.

        :param may_subscribe_to_list: If the person is not a team, and
            may_subscribe_to_list is True, then the person may be subscribed
            to the team's mailing list, depending on the list status and the
            person's auto-subscribe settings.

        :return: A tuple containing a boolean indicating when the
            membership status changed and the current `TeamMembershipStatus`.
            This depends on the desired status passed as an argument, the
            subscription policy and the user's privileges.
        """

    @operation_parameters(
        team=copy_field(ITeamMembership['team']),
        comment=Text())
    @export_write_operation()
    @operation_for_version("beta")
    def acceptInvitationToBeMemberOf(team, comment):
        """Accept an invitation to become a member of the given team.

        There must be a TeamMembership for this person and the given team with
        the INVITED status. The status of this TeamMembership will be changed
        to APPROVED.
        """

    @operation_parameters(
        team=copy_field(ITeamMembership['team']),
        comment=Text())
    @export_write_operation()
    @operation_for_version("beta")
    def declineInvitationToBeMemberOf(team, comment):
        """Decline an invitation to become a member of the given team.

        There must be a TeamMembership for this person and the given team with
        the INVITED status. The status of this TeamMembership will be changed
        to INVITATION_DECLINED.
        """

    @call_with(user=REQUEST_USER)
    @operation_parameters(
        team=copy_field(ITeamMembership['team']),
        comment=Text(required=False))
    @export_write_operation()
    @operation_for_version("beta")
    def retractTeamMembership(team, user, comment=None):
        """Retract this team's membership in the given team.

        If there's a membership entry for this team on the given team and
        its status is either APPROVED, ADMIN, PENDING, or INVITED, the status
        is changed and the relevant entries in TeamParticipation.

        APPROVED and ADMIN status are changed to DEACTIVATED.
        PENDING status is changed to DECLINED.
        INVITED status is changes to INVITATION_DECLINED.

        :param team: The team to leave.
        :param user: The user making the retraction.
        :param comment: An optional explanation about why the change was made.
        """

    def renewTeamMembership(team):
        """Renew the TeamMembership for this person on the given team.

        The given team's renewal policy must be ONDEMAND and the membership
        must be active (APPROVED or ADMIN) and set to expire in less than
        DAYS_BEFORE_EXPIRATION_WARNING_IS_SENT days.
        """


class IPersonCommAdminWriteRestricted(Interface):
    """IPerson attributes that require launchpad.Admin permission to set."""

    visibility = exported(
        Choice(title=_("Visibility"),
               description=_(
                   "Public visibility is standard.  "
                   "Private means the team is completely "
                   "hidden."),
               required=True, vocabulary=PersonVisibility,
               default=PersonVisibility.PUBLIC))


class IPersonSpecialRestricted(Interface):
    """IPerson methods that require launchpad.Special permission to use."""

    def deactivateAccount(comment):
        """Deactivate this person's Launchpad account.

        Deactivating an account means:
            - Setting its password to NULL;
            - Removing the user from all teams he's a member of;
            - Changing all his email addresses' status to NEW;
            - Revoking Code of Conduct signatures of that user;
            - Reassigning bugs/specs assigned to him;
            - Changing the ownership of products/projects/teams owned by him.

        :param comment: An explanation of why the account status changed.
        """

    def reactivate(comment, password, preferred_email):
        """Reactivate this person and its account.

        Set the account status to ACTIVE, the account's password to the given
        one and its preferred email address.

        If the person's name contains a -deactivatedaccount suffix (usually
        added by `IPerson`.deactivateAccount(), it is removed.

        :param comment: An explanation of why the account status changed.
        :param password: The user's password.
        :param preferred_email: The `EmailAddress` to set as the account's
            preferred email address. It cannot be None.
        """

    # XXX 2011-04-20, Abel Deuring, Bug=767293: The methods canAccess()
    # and canWrite() are defined in this interface for two reasons:
    # 1. The functions zope.security.checker.canWrite() and
    #    zope.security.checker.canAccess() can at present check only
    #    permissions for the current user, and this interface is
    #    protected by the permission launchpad.Special, which
    #    allows users only access to theirs own object.
    # 2. Allowing users access to check permissions for other persons
    #    than themselves might leak information.
    def canAccess(obj, attribute):
        """True if this person can access the given attribute of the object.

        :param obj: The object to be checked.
        :param attributes: The name of an attribute to check.
        :return: True if the person can access the attribute of the given
            object, else False.
        """

    def canWrite(obj, attribute):
        """True if this person can write the given attribute of the object.

        :param obj: The object to be checked.
        :param attribute: The name an attribute to check.
        :return: True if the person can change the attribute of the given
            object, else False.
        """


class IPerson(IPersonPublic, IPersonLimitedView, IPersonViewRestricted,
              IPersonEditRestricted, IPersonCommAdminWriteRestricted,
              IPersonSpecialRestricted, IHasStanding, ISetLocation,
              IRootContext):
    """A Person."""
    export_as_webservice_entry(plural_name='people')


# Set the schemas to the newly defined interface for classes that deferred
# doing so when defined.
PersonChoice.schema = IPerson


class ITeamPublic(Interface):
    """Public attributes of a Team."""

    @invariant
    def defaultRenewalPeriodIsRequiredForSomeTeams(person):
        """Teams may specify a default renewal period.

        The team renewal period cannot be less than 1 day, and when the
        renewal policy is is 'On Demand' or 'Automatic', it cannot be None.
        """
        # The person arg is a zope.formlib.form.FormData instance.
        # Instead of checking 'not person.is_team' or 'person.teamowner',
        # we check for a field in the schema to identify this as a team.
        try:
            renewal_policy = person.renewal_policy
        except NoInputData:
            # This is not a team.
            return

        renewal_period = person.defaultrenewalperiod
        is_required_value_missing = (
            renewal_period is None
            and renewal_policy in [
                TeamMembershipRenewalPolicy.AUTOMATIC,
                TeamMembershipRenewalPolicy.ONDEMAND])
        out_of_range = (
            renewal_period is not None
            and (renewal_period <= 0 or renewal_period > 3650))
        if is_required_value_missing or out_of_range:
            raise Invalid(
                'You must specify a default renewal period '
                'from 1 to 3650 days.')

    teamdescription = exported(
        Text(title=_('Team Description'), required=False, readonly=False,
             description=_(
                "Details about the team's work, highlights, goals, "
                "and how to contribute. Use plain text, paragraphs are "
                "preserved and URLs are linked in pages.")),
        exported_as='team_description')

    subscriptionpolicy = exported(
        TeamSubsciptionPolicyChoice(title=_('Subscription policy'),
               vocabulary=TeamSubscriptionPolicy,
               default=TeamSubscriptionPolicy.MODERATED, required=True,
               description=_(
                TeamSubscriptionPolicy.__doc__.split('\n\n')[1])),
        exported_as='subscription_policy')

    renewal_policy = exported(
        Choice(title=_("When someone's membership is about to expire, "
                       "notify them and"),
               required=True, vocabulary=TeamMembershipRenewalPolicy,
               default=TeamMembershipRenewalPolicy.NONE))

    defaultmembershipperiod = exported(
        Int(title=_('Subscription period'), required=False, max=3650,
            description=_(
                "Number of days a new subscription lasts before expiring. "
                "You can customize the length of an individual subscription "
                "when approving it. Leave this empty or set to 0 for "
                "subscriptions to never expire.")),
        exported_as='default_membership_period')

    defaultrenewalperiod = exported(
        Int(title=_('Renewal period'), required=False,
            description=_(
                "Number of days a subscription lasts after being renewed. "
                "The number can be from 1 to 3650 (10 years). "
                "You can customize the lengths of individual renewals, but "
                "this is what's used for auto-renewed and user-renewed "
                "memberships.")),
        exported_as='default_renewal_period')

    defaultexpirationdate = Attribute(
        "The date, according to team's default values, in which a newly "
        "approved membership will expire.")

    defaultrenewedexpirationdate = Attribute(
        "The date, according to team's default values, in "
        "which a just-renewed membership will expire.")

    def checkOpenSubscriptionPolicyAllowed(policy='open'):
        """ Check whether this team's subscription policy can be open.

        An open subscription policy is OPEN or DELEGATED.
        A closed subscription policy is MODERATED or RESTRICTED.
        An closed subscription policy is required when:
        - any of the team's super teams are closed.
        - the team has any active PPAs
        - it is subscribed or assigned to any private bugs
        - it owns or is the security contact for any pillars

        :param policy: The policy that is being checked for validity. This is
            an optional parameter used in the message of the exception raised
            when an open policy is not allowed. Sometimes though, the caller
            just wants to know if any open policy is allowed without having a
            particular policy to check. In this case, the method is called
            without a policy parameter being required.
        :raises TeamSubscriptionPolicyError: When the subscription policy is
            not allowed to be open.
        """

    def checkClosedSubscriptionPolicyAllowed(policy='closed'):
        """ Return true if this team's subscription policy must be open.

        An open subscription policy is OPEN or DELEGATED.
        A closed subscription policy is MODERATED or RESTRICTED.
        An open subscription policy is required when:
        - any of the team's sub (member) teams are open.

        :param policy: The policy that is being checked for validity. This is
            an optional parameter used in the message of the exception raised
            when a closed policy is not allowed. Sometimes though, the caller
            just wants to know if any closed policy is allowed without having
            a particular policy to check. In this case, the method is called
            without a policy parameter being required.
        :raises TeamSubscriptionPolicyError: When the subscription policy is
            not allowed to be closed.
        """


class ITeam(IPerson, ITeamPublic):
    """A group of people and other teams.

    Launchpadlib example of getting the date a user joined a team::

        def get_join_date(team, user):
            team = launchpad.people[team]
            members = team.members_details
            for member in members:
                if member.member.name == user:
                    return member.date_joined
            return None

    Implementation notes:

    - ITeam extends IPerson.
    - The teamowner should never be None.
    """
    export_as_webservice_entry('team')

    # Logo, Mugshot and displayname are here so that they can have a
    # description on a Team which is different to the description they have on
    # a Person.
    logo = copy_field(
        IPerson['logo'], default_image_resource='/@@/team-logo',
        description=_(
            "An image of exactly 64x64 pixels that will be displayed in "
            "the heading of all pages related to the team. Traditionally "
            "this is a logo, a small picture or a personal mascot. It "
            "should be no bigger than 50kb in size."))

    mugshot = copy_field(
        IPerson['mugshot'], default_image_resource='/@@/team-mugshot',
        description=_(
            "A large image of exactly 192x192 pixels, that will be displayed "
            "on the team page in Launchpad. It "
            "should be no bigger than 100kb in size. "))

    displayname = copy_field(
        IPerson['displayname'],
        description=_(
            "This team's name as you would like it displayed throughout "
            "Launchpad."))


class IPersonSet(Interface):
    """The set of Persons."""
    export_as_webservice_collection(IPerson)

    title = Attribute('Title')

    @collection_default_content()
    def getTopContributors(limit=50):
        """Return the top contributors in Launchpad, up to the given limit."""

    def isNameBlacklisted(name, user=None):
        """Is the given name blacklisted by Launchpad Administrators?

        :param name: The name to be checked.
        :param user: The `IPerson` that wants to use the name. If the user
            is an admin for the nameblacklist expression, he can use the name.
        """

    def createPersonAndEmail(
            email, rationale, comment=None, name=None, displayname=None,
            password=None, passwordEncrypted=False,
            hide_email_addresses=False, registrant=None):
        """Create and return an `IPerson` and `IEmailAddress`.

        The newly created EmailAddress will have a status of NEW and will be
        linked to the newly created Person.

        An Account is also created, but this will change in the future!

        If the given name is None, we generate a unique nickname from the
        email address given.

        :param email: The email address, as text.
        :param rationale: An item of `PersonCreationRationale` to be used as
            the person's creation_rationale.
        :param comment: A comment explaining why the person record was
            created (usually used by scripts which create them automatically).
            Must be of the following form: "when %(action_details)s"
            (e.g. "when the foo package was imported into Ubuntu Breezy").
        :param name: The person's name.
        :param displayname: The person's displayname.
        :param password: The person's password.
        :param passwordEncrypted: Whether or not the given password is
            encrypted.
        :param registrant: The user who created this person, if any.
        :param hide_email_addresses: Whether or not Launchpad should hide the
            person's email addresses from other users.
        :raises InvalidName: When the given name is not valid.
        :raises InvalidEmailAddress: When the given email is not valid.
        :raises NameAlreadyTaken: When the given name is already in use.
        :raises EmailAddressAlreadyTaken: When the given email is already in
            use.
        :raises NicknameGenerationError: When no name is provided and we can't
            generate a nickname from the given email address.
        """

    def createPersonWithoutEmail(
        name, rationale, comment=None, displayname=None, registrant=None):
        """Create and return an `IPerson` without using an email address.

        :param name: The person's name.
        :param comment: A comment explaining why the person record was
            created (usually used by scripts which create them automatically).
            Must be of the following form: "when %(action_details)s"
            (e.g. "when the foo package was imported into Ubuntu Breezy").
        :param displayname: The person's displayname.
        :param registrant: The user who created this person, if any.
        :raises InvalidName: When the passed name isn't valid.
        :raises NameAlreadyTaken: When the passed name has already been
            used.
        """

    def ensurePerson(email, displayname, rationale, comment=None,
                     registrant=None):
        """Make sure that there is a person in the database with the given
        email address. If necessary, create the person, using the
        displayname given.

        The comment must be of the following form: "when %(action_details)s"
        (e.g. "when the foo package was imported into Ubuntu Breezy").

        If the email address is already registered and bound to an
        `IAccount`, the created `IPerson` will have 'hide_email_addresses'
        flag set to True.

        XXX sabdfl 2005-06-14: this should be extended to be similar or
        identical to the other person creation argument lists, so we can
        call it and create a full person if needed. Email would remain the
        deciding factor, we would not try and guess if someone existed based
        on the displayname or other arguments.
        """

    def getOrCreateByOpenIDIdentifier(openid_identifier, email,
                                      full_name, creation_rationale, comment):
        """Get or create a person for a given OpenID identifier.

        This is used when users login. We get the account with the given
        OpenID identifier (creating one if it doesn't already exist) and
        act according to the account's state:
          - If the account is suspended, we stop and raise an error.
          - If the account is deactivated, we reactivate it and proceed;
          - If the account is active, we just proceed.

        If there is no existing Launchpad person for the account, we
        create it.

        :param openid_identifier: representing the authenticated user.
        :param email_address: the email address of the user.
        :param full_name: the full name of the user.
        :param creation_rationale: When an account or person needs to
            be created, this indicates why it was created.
        :param comment: If the account is reactivated or person created,
            this comment indicates why.
        :return: a tuple of `IPerson` and a boolean indicating whether the
            database was updated.
        :raises AccountSuspendedError: if the account associated with the
            identifier has been suspended.
        """

    @call_with(teamowner=REQUEST_USER)
    @rename_parameters_as(
        displayname='display_name', teamdescription='team_description',
        subscriptionpolicy='subscription_policy',
        defaultmembershipperiod='default_membership_period',
        defaultrenewalperiod='default_renewal_period')
    @operation_parameters(
        subscriptionpolicy=Choice(
            title=_('Subscription policy'), vocabulary=TeamSubscriptionPolicy,
            required=False, default=TeamSubscriptionPolicy.MODERATED))
    @export_factory_operation(
        ITeam, ['name', 'displayname', 'teamdescription',
                'defaultmembershipperiod', 'defaultrenewalperiod'])
    @operation_for_version("beta")
    def newTeam(teamowner, name, displayname, teamdescription=None,
                subscriptionpolicy=TeamSubscriptionPolicy.MODERATED,
                defaultmembershipperiod=None, defaultrenewalperiod=None):
        """Create and return a new Team with given arguments."""

    def get(personid):
        """Return the person with the given id or None if it's not found."""

    @operation_parameters(
        email=TextLine(required=True, constraint=email_validator))
    @operation_returns_entry(IPerson)
    @export_read_operation()
    @operation_for_version("beta")
    def getByEmail(email):
        """Return the person with the given email address.

        Return None if there is no person with the given email address.
        """

    def getByEmails(emails, include_hidden=True):
        """Search for people with the given email addresses.

        :param emails: A list of email addresses.
        :param include_hidden: Include people who have opted to hide their
            email. Defaults to True.

        :return: A `ResultSet` of `IEmailAddress`, `IPerson`.
        """

    def getByName(name, ignore_merged=True):
        """Return the person with the given name, ignoring merged persons if
        ignore_merged is True.

        Return None if there is no person with the given name.
        """

    def getByAccount(account):
        """Return the `IPerson` with the given account, or None."""

    def updateStatistics(ztm):
        """Update statistics caches and commit."""

    def peopleCount():
        """Return the number of non-merged persons in the database as
           of the last statistics update.
        """

    def teamsCount():
        """Return the number of teams in the database as of the last
           statistics update.
        """

    @operation_parameters(
        text=TextLine(title=_("Search text"), default=u""))
    @operation_returns_collection_of(IPerson)
    @export_read_operation()
    @operation_for_version("beta")
    def find(text=""):
        """Return all non-merged Persons and Teams whose name, displayname or
        email address match <text>.

        The results will be ordered using the default ordering specified in
        Person._defaultOrder.

        While we don't have Full Text Indexes in the emailaddress table, we'll
        be trying to match the text only against the beginning of an email
        address.
        """

    @operation_parameters(
        text=TextLine(
            title=_("Search text"), default=u""),
        created_after=Datetime(
            title=_("Created after"), required=False),
        created_before=Datetime(
            title=_("Created before"), required=False),
        )
    @operation_returns_collection_of(IPerson)
    @export_read_operation()
    @operation_for_version("beta")
    def findPerson(text="", exclude_inactive_accounts=True,
                   must_have_email=False,
                   created_after=None, created_before=None):
        """Return all non-merged Persons with at least one email address whose
        name, displayname or email address match <text>.

        If text is an empty string, all persons with at least one email
        address will be returned.

        The results will be ordered using the default ordering specified in
        Person._defaultOrder.

        If exclude_inactive_accounts is True, any accounts whose
        account_status is any of INACTIVE_ACCOUNT_STATUSES will not be in the
        returned set.

        If must_have_email is True, only people with one or more email
        addresses are returned.

        While we don't have Full Text Indexes in the emailaddress table, we'll
        be trying to match the text only against the beginning of an email
        address.

        If created_before or created_after are not None, they are used to
        restrict the search to the dates provided.
        """

    @operation_parameters(
        text=TextLine(title=_("Search text"), default=u""))
    @operation_returns_collection_of(IPerson)
    @export_read_operation()
    @operation_for_version("beta")
    def findTeam(text=""):
        """Return all Teams whose name, displayname or email address
        match <text>.

        The results will be ordered using the default ordering specified in
        Person._defaultOrder.

        While we don't have Full Text Indexes in the emailaddress table, we'll
        be trying to match the text only against the beginning of an email
        address.
        """

    def latest_teams(limit=5):
        """Return the latest teams registered, up to the limit specified."""

    def mergeAsync(from_person, to_person, reviewer=None, delete=False):
        """Merge a person/team into another asynchronously.

        This schedules a call to `merge()` to happen outside of the current
        context/request. The intention is that it is called soon after this
        method is called but there is no guarantee of that, nor is that call
        guaranteed to succeed. If either user is in a pending person merge
        job, None is returned.

        :param from_person: An IPerson or ITeam that is a duplicate.
        :param to_person: An IPerson or ITeam that is a master.
        :param reviewer: An IPerson who approved the ITeam merger.
        :param delete: The merge is really a deletion.
        :return: A `PersonMergeJob` or None.
        """

    def delete(from_person, reviewer):
        """Delete a person/team.

        The old team (from_person) will be left as an atavism.

        Deleting a person is not supported at this time.

        When deleting teams, from_person must have no IMailingLists
        associated with and no active members. Any active team members will be
        deactivated.

        :param from_person: An IPerson or ITeam that is a duplicate.
        :param reviewer: An IPerson who approved the ITeam merger.
        """

    def merge(from_person, to_person, reviewer=None):
        """Merge a person/team into another.

        The old person/team (from_person) will be left as an atavism.

        When merging two person entries, from_person can't have email
        addresses associated with.

        When merging teams, from_person must have no IMailingLists
        associated with it. If it has active members they will be deactivated
        - and reviewer must be supplied.

        :param from_person: An IPerson or ITeam that is a duplicate.
        :param to_person: An IPerson or ITeam that is a master.
        :param reviewer: An IPerson who approved the ITeam merger.
        """

    def getValidPersons(persons):
        """Get all the Persons that are valid.

        This method is more effective than looking at
        Person.is_valid_person_or_team, since it avoids issuing one DB
        query per person. It queries the ValidPersonOrTeamCache table,
        issuing one query for all the person records. This makes the
        method useful for filling the ORM cache, so that checks to
        .is_valid_person won't issue any DB queries.

        XXX: This method exists mainly to fill the ORM cache for
             ValidPersonOrTeamCache. It would be better to add a column
             to the Person table. If we do that, this method can go
             away. Bug 221901. -- Bjorn Tillenius, 2008-04-25
        """

    def getPeopleWithBranches(product=None):
        """Return the people who have branches.

        :param product: If supplied, only people who have branches in the
            specified product are returned.
        """

    def updatePersonalStandings():
        """Update the personal standings of some people.

        Personal standing controls whether a person can post to a mailing list
        they are not a member of without moderation.  A person starts out with
        Unknown standing.  Once they have at least one message approved for
        three different lists, this method will bump their standing to Good.
        If a person's standing is already Good, or Poor or Excellent, no
        change to standing is made.
        """

    def cacheBrandingForPeople(people):
        """Prefetch Librarian aliases and content for personal images."""

    def getPrecachedPersonsFromIDs(
        person_ids, need_karma=False, need_ubuntu_coc=False,
        need_location=False, need_archive=False,
        need_preferred_email=False, need_validity=False):
        """Lookup person objects from ids with optional precaching.

        :param person_ids: List of person ids.
        :param need_karma: The karma attribute will be cached.
        :param need_ubuntu_coc: The is_ubuntu_coc_signer attribute will be
            cached.
        :param need_location: The location attribute will be cached.
        :param need_archive: The archive attribute will be cached.
        :param need_preferred_email: The preferred email attribute will be
            cached.
        :param need_validity: The is_valid attribute will be cached.
        """


class IRequestPeopleMerge(Interface):
    """This schema is used only because we want a very specific vocabulary."""

    dupe_person = Choice(
        title=_('Duplicated Account'), required=True,
        vocabulary='PersonAccountToMerge',
        description=_(
            "The e-mail address or Launchpad ID of the account you want to "
            "merge into yours."))


class IAdminPeopleMergeSchema(Interface):
    """The schema used by the admin merge people page."""

    dupe_person = Choice(
        title=_('Duplicated Person'), required=True,
        vocabulary='AdminMergeablePerson',
        description=_("The duplicated person found in Launchpad."))

    target_person = Choice(
        title=_('Target Person'), required=True,
        vocabulary='AdminMergeablePerson',
        description=_("The person to be merged on."))


class IAdminTeamMergeSchema(Interface):
    """The schema used by the admin merge teams page."""

    dupe_person = Choice(
        title=_('Duplicated Team'), required=True, vocabulary='ValidTeam',
        description=_("The duplicated team found in Launchpad."))

    target_person = Choice(
        title=_('Target Team'), required=True, vocabulary='ValidTeam',
        description=_("The team to be merged on."))


class IObjectReassignment(Interface):
    """The schema used by the object reassignment page."""

    owner = PublicPersonChoice(title=_('New'), vocabulary='ValidOwner',
                               required=True)


class ITeamReassignment(Interface):
    """The schema used by the team reassignment page."""

    owner = PublicPersonChoice(
        title=_('New'), vocabulary='ValidTeamOwner', required=True)


class ITeamCreation(ITeam):
    """An interface to be used by the team creation form.

    We need this special interface so we can allow people to specify a contact
    email address for a team upon its creation.
    """

    contactemail = TextLine(
        title=_("Contact Email Address"), required=False, readonly=False,
        description=_(
            "This is the email address we'll send all notifications to this "
            "team. If no contact address is chosen, notifications directed "
            "to this team will be sent to all team members. After finishing "
            "the team creation, a new message will be sent to this address "
            "with instructions on how to finish its registration."),
        constraint=validate_new_team_email)


class TeamContactMethod(EnumeratedType):
    """The method used by Launchpad to contact a given team."""

    HOSTED_LIST = Item("""
        The Launchpad mailing list for this team

        Notifications directed to this team are sent to its Launchpad-hosted
        mailing list.
        """)

    NONE = Item("""
        Each member individually

        Notifications directed to this team will be sent to each of its
        members.
        """)

    EXTERNAL_ADDRESS = Item("""
        Another e-mail address

        Notifications directed to this team are sent to the contact address
        specified.
        """)


class ITeamContactAddressForm(Interface):

    contact_address = TextLine(
        title=_("Contact Email Address"), required=False, readonly=False)

    contact_method = Choice(
        title=_("How do people contact these team's members?"),
        required=True, vocabulary=TeamContactMethod)


class ISoftwareCenterAgentAPI(Interface):
    """XMLRPC API used by the software center agent."""

    def getOrCreateSoftwareCenterCustomer(openid_identifier, email,
                                          full_name):
        """Get or create an LP person based on a given identifier.

        See the method of the same name on `IPersonSet`. This XMLRPC version
        doesn't require the creation rationale and comment.

        This is added as a private XMLRPC method instead of exposing via the
        API as it should not be needed long-term. Long term we should allow
        the software center to create subscriptions to private PPAs without
        requiring a Launchpad account.
        """


class ISoftwareCenterAgentApplication(ILaunchpadApplication):
    """XMLRPC application root for ISoftwareCenterAgentAPI."""


class ImmutableVisibilityError(Exception):
    """A change in team membership visibility is not allowed."""


class NoSuchPerson(NameLookupFailed):
    """Raised when we try to look up an IPerson that doesn't exist."""

    _message_prefix = "No such person"


# Fix value_type.schema of IPersonViewRestricted attributes.
for name in [
    'all_members_prepopulated',
    'api_activemembers',
    'adminmembers',
    'proposedmembers',
    'invited_members',
    'deactivatedmembers',
    'expiredmembers',
    'unmapped_participants',
    ]:
    IPersonViewRestricted[name].value_type.schema = IPerson

IPersonViewRestricted['sub_teams'].value_type.schema = ITeam
IPersonViewRestricted['super_teams'].value_type.schema = ITeam
# XXX: salgado, 2008-08-01: Uncomment these when teams_*participated_in are
# exported again.
# IPersonViewRestricted['teams_participated_in'].value_type.schema = ITeam
# IPersonViewRestricted[
#   'teams_indirectly_participated_in'].value_type.schema = ITeam

# Fix schema of operation parameters. We need zope.deferredimport!
params_to_fix = [
    # XXX: salgado, 2008-08-01: Uncomment these when they are exported again.
    # (IPersonViewRestricted['findPathToTeam'], 'team'),
    # (IPersonViewRestricted['inTeam'], 'team'),
    (IPersonEditRestricted['join'], 'team'),
    (IPersonEditRestricted['leave'], 'team'),
    (IPersonEditRestricted['addMember'], 'person'),
    (IPersonEditRestricted['acceptInvitationToBeMemberOf'], 'team'),
    (IPersonEditRestricted['declineInvitationToBeMemberOf'], 'team'),
    (IPersonEditRestricted['retractTeamMembership'], 'team'),
    ]
for method, name in params_to_fix:
    method.queryTaggedValue(
        'lazr.restful.exported')['params'][name].schema = IPerson

# Fix schema of operation return values.
# XXX: salgado, 2008-08-01: Uncomment when findPathToTeam is exported again.
# IPersonPublic['findPathToTeam'].queryTaggedValue(
#     'lazr.webservice.exported')['return_type'].value_type.schema = IPerson
IPersonViewRestricted['getMembersByStatus'].queryTaggedValue(
    LAZR_WEBSERVICE_EXPORTED)['return_type'].value_type.schema = IPerson

# Fix schema of ITeamMembership fields.  Has to be done here because of
# circular dependencies.
for name in ['team', 'person', 'last_changed_by']:
    ITeamMembership[name].schema = IPerson

# Fix schema of ITeamParticipation fields.  Has to be done here because of
# circular dependencies.
for name in ['team', 'person']:
    ITeamParticipation[name].schema = IPerson

# Thank circular dependencies once again.
IIrcID['person'].schema = IPerson
IJabberID['person'].schema = IPerson
IWikiName['person'].schema = IPerson
IEmailAddress['person'].schema = IPerson