~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
# Copyright 2009-2011 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

__metaclass__ = type
__all__ = [
    'HasRenewalPolicyMixin',
    'ProposedTeamMembersEditView',
    'TeamAddMyTeamsView',
    'TeamAddView',
    'TeamBadges',
    'TeamBrandingView',
    'TeamBreadcrumb',
    'TeamContactAddressView',
    'TeamEditMenu',
    'TeamEditView',
    'TeamIndexMenu',
    'TeamJoinView',
    'TeamLeaveView',
    'TeamMailingListConfigurationView',
    'TeamMailingListModerationView',
    'TeamMailingListSubscribersView',
    'TeamMapData',
    'TeamMapLtdData',
    'TeamMapView',
    'TeamMapLtdView',
    'TeamMemberAddView',
    'TeamMembershipView',
    'TeamMugshotView',
    'TeamNavigation',
    'TeamOverviewMenu',
    'TeamOverviewNavigationMenu',
    'TeamPrivacyAdapter',
    'TeamReassignmentView',
    ]


import cgi
from datetime import (
    datetime,
    timedelta,
    )
import math
from urllib import unquote

from lazr.restful.utils import smartquote
import pytz
from z3c.ptcompat import ViewPageTemplateFile
from zope.app.form.browser import TextAreaWidget
from zope.component import getUtility
from zope.formlib import form
from zope.formlib.form import FormFields
from zope.interface import (
    classImplements,
    implements,
    Interface,
    )
from zope.publisher.interfaces.browser import IBrowserPublisher
from zope.schema import (
    Bool,
    Choice,
    List,
    Text,
    )
from zope.schema.vocabulary import (
    getVocabularyRegistry,
    SimpleTerm,
    SimpleVocabulary,
    )
from zope.security.interfaces import Unauthorized

from lp import _
from lp.app.browser.badge import HasBadgeBase
from lp.app.browser.launchpadform import (
    action,
    custom_widget,
    LaunchpadFormView,
    )
from lp.app.browser.tales import PersonFormatterAPI
from lp.app.errors import UnexpectedFormData
from lp.app.validators import LaunchpadValidationError
from lp.app.validators.validation import validate_new_team_email
from lp.app.widgets.itemswidgets import (
    LabeledMultiCheckBoxWidget,
    LaunchpadRadioWidget,
    LaunchpadRadioWidgetWithDescription,
    )
from lp.app.widgets.owner import HiddenUserWidget
from lp.app.widgets.popup import PersonPickerWidget
from lp.code.browser.sourcepackagerecipelisting import HasRecipesMenuMixin
from lp.registry.browser.branding import BrandingChangeView
from lp.registry.browser.mailinglists import enabled_with_active_mailing_list
from lp.registry.browser.objectreassignment import ObjectReassignmentView
from lp.registry.browser.person import (
    CommonMenuLinks,
    PersonIndexView,
    PersonNavigation,
    PersonRenameFormMixin,
    PPANavigationMenuMixIn,
    )
from lp.registry.browser.teamjoin import (
    TeamJoinMixin,
    userIsActiveTeamMember,
    )
from lp.registry.errors import TeamSubscriptionPolicyError
from lp.registry.interfaces.mailinglist import (
    IMailingList,
    IMailingListSet,
    MailingListStatus,
    PostedMessageStatus,
    PURGE_STATES,
    )
from lp.registry.interfaces.mailinglistsubscription import (
    MailingListAutoSubscribePolicy,
    )
from lp.registry.interfaces.person import (
    CLOSED_TEAM_POLICY,
    ImmutableVisibilityError,
    IPersonSet,
    ITeam,
    ITeamContactAddressForm,
    ITeamCreation,
    ITeamReassignment,
    OPEN_TEAM_POLICY,
    PersonVisibility,
    PRIVATE_TEAM_PREFIX,
    TeamContactMethod,
    TeamMembershipRenewalPolicy,
    TeamSubscriptionPolicy,
    )
from lp.registry.interfaces.poll import IPollSet
from lp.registry.interfaces.teammembership import (
    CyclicalTeamMembershipError,
    DAYS_BEFORE_EXPIRATION_WARNING_IS_SENT,
    ITeamMembership,
    ITeamMembershipSet,
    TeamMembershipStatus,
    )
from lp.services.config import config
from lp.services.fields import PublicPersonChoice
from lp.services.identity.interfaces.emailaddress import IEmailAddressSet
from lp.services.privacy.interfaces import IObjectPrivacy
from lp.services.propertycache import cachedproperty
from lp.services.verification.interfaces.authtoken import LoginTokenType
from lp.services.verification.interfaces.logintoken import ILoginTokenSet
from lp.services.webapp import (
    ApplicationMenu,
    canonical_url,
    enabled_with_permission,
    LaunchpadView,
    Link,
    NavigationMenu,
    stepthrough,
    )
from lp.services.webapp.authorization import (
    check_permission,
    clear_cache,
    )
from lp.services.webapp.batching import (
    ActiveBatchNavigator,
    BatchNavigator,
    InactiveBatchNavigator,
    )
from lp.services.webapp.breadcrumb import Breadcrumb
from lp.services.webapp.interfaces import ILaunchBag
from lp.services.webapp.menu import structured


class TeamPrivacyAdapter:
    """Provides `IObjectPrivacy` for `ITeam`."""

    implements(IObjectPrivacy)

    def __init__(self, context):
        self.context = context

    @property
    def is_private(self):
        """Return True if the team is private, otherwise False."""
        return self.context.visibility != PersonVisibility.PUBLIC


class TeamBadges(HasBadgeBase):
    """Provides `IHasBadges` for `ITeam`."""

    def getPrivateBadgeTitle(self):
        """Return private badge info useful for a tooltip."""
        return "This is a %s team" % self.context.visibility.title.lower()


class HasRenewalPolicyMixin:
    """Mixin to be used on forms which contain ITeam.renewal_policy.

    This mixin will short-circuit Launchpad*FormView when defining whether
    the renewal_policy widget should be displayed in a single or multi-line
    layout. We need that because that field has a very long title, thus
    breaking the page layout.

    Since this mixin short-circuits Launchpad*FormView in some cases, it must
    always precede Launchpad*FormView in the inheritance list.
    """

    def isMultiLineLayout(self, field_name):
        if field_name == 'renewal_policy':
            return True
        return super(HasRenewalPolicyMixin, self).isMultiLineLayout(
            field_name)

    def isSingleLineLayout(self, field_name):
        if field_name == 'renewal_policy':
            return False
        return super(HasRenewalPolicyMixin, self).isSingleLineLayout(
            field_name)


class TeamFormMixin:
    """Form to be used on forms which conditionally display team visibility.

    The visibility field should only be shown to users with
    launchpad.Commercial permission on the team.
    """
    field_names = [
        "name", "visibility", "displayname", "contactemail",
        "teamdescription", "subscriptionpolicy",
        "defaultmembershipperiod", "renewal_policy",
        "defaultrenewalperiod", "teamowner",
        ]
    private_prefix = PRIVATE_TEAM_PREFIX

    def _validateVisibilityConsistency(self, value):
        """Perform a consistency check regarding visibility.

        This property must be overridden if the current context is not an
        IPerson.
        """
        return self.context.visibilityConsistencyWarning(value)

    @property
    def _visibility(self):
        """Return the visibility for the object."""
        return self.context.visibility

    @property
    def _name(self):
        return self.context.name

    def validate(self, data):
        visibility = data.get('visibility', self._visibility)
        if visibility != PersonVisibility.PUBLIC:
            if visibility != self._visibility:
                # If the user is attempting to change the team visibility
                # ensure that there are no constraints being violated.
                warning = self._validateVisibilityConsistency(visibility)
                if warning is not None:
                    self.setFieldError('visibility', warning)
            if (data['subscriptionpolicy']
                != TeamSubscriptionPolicy.RESTRICTED):
                self.setFieldError(
                    'subscriptionpolicy',
                    'Private teams must have a Restricted subscription '
                    'policy.')

    def conditionallyOmitVisibility(self):
        """Remove the visibility field if not authorized."""
        if not check_permission('launchpad.Commercial', self.context):
            self.form_fields = self.form_fields.omit('visibility')


class TeamEditView(TeamFormMixin, PersonRenameFormMixin,
                   HasRenewalPolicyMixin):
    """View for editing team details."""
    schema = ITeam

    @property
    def label(self):
        """The form label."""
        return 'Edit "%s" team' % self.context.displayname

    page_title = label

    custom_widget(
        'renewal_policy', LaunchpadRadioWidget, orientation='vertical')
    custom_widget(
        'subscriptionpolicy', LaunchpadRadioWidgetWithDescription,
        orientation='vertical')
    custom_widget('teamdescription', TextAreaWidget, height=10, width=30)

    def setUpFields(self):
        """See `LaunchpadViewForm`.

        When editing a team the contactemail field is not displayed.
        """
        # Make an instance copy of field_names so as to not modify the single
        # class list.
        self.field_names = list(self.field_names)
        self.field_names.remove('contactemail')
        self.field_names.remove('teamowner')
        super(TeamEditView, self).setUpFields()
        self.conditionallyOmitVisibility()

    def setUpWidgets(self):
        super(TeamEditView, self).setUpWidgets()
        team = self.context
        # Do we need to only show open subscription policy choices?
        try:
            team.checkClosedSubscriptionPolicyAllowed()
        except TeamSubscriptionPolicyError:
            # Ideally SimpleVocabulary.fromItems() would accept 3-tuples but
            # it doesn't so we need to be a bit more verbose.
            self.widgets['subscriptionpolicy'].vocabulary = (
                SimpleVocabulary([SimpleVocabulary.createTerm(
                    policy, policy.name, policy.title)
                    for policy in OPEN_TEAM_POLICY])
                )
        # Do we need to only show closed subscription policy choices?
        try:
            team.checkOpenSubscriptionPolicyAllowed()
        except TeamSubscriptionPolicyError:
            # Ideally SimpleVocabulary.fromItems() would accept 3-tuples but
            # it doesn't so we need to be a bit more verbose.
            self.widgets['subscriptionpolicy'].vocabulary = (
                SimpleVocabulary([SimpleVocabulary.createTerm(
                    policy, policy.name, policy.title)
                    for policy in CLOSED_TEAM_POLICY])
                )

    @action('Save', name='save')
    def action_save(self, action, data):
        try:
            self.updateContextFromData(data)
        except ImmutableVisibilityError, error:
            self.request.response.addErrorNotification(str(error))
            # Abort must be called or changes to fields before the one causing
            # the error will be committed.  If we have a database validation
            # error we want to abort the transaction.
            # XXX: BradCrittenden 2009-04-13 bug=360540: Remove the call to
            # abort if it is moved up to updateContextFromData.
            self._abort()

    @property
    def next_url(self):
        return canonical_url(self.context)

    cancel_url = next_url


def generateTokenAndValidationEmail(email, team):
    """Send a validation message to the given email."""
    login = getUtility(ILaunchBag).login
    token = getUtility(ILoginTokenSet).new(
        team, login, email, LoginTokenType.VALIDATETEAMEMAIL)

    user = getUtility(ILaunchBag).user
    token.sendTeamEmailAddressValidationEmail(user)


class MailingListTeamBaseView(LaunchpadFormView):
    """A base view for manipulating a team's mailing list.

    This class contains common functionality for retrieving and
    checking the state of mailing lists.
    """

    def _getList(self):
        """Try to find a mailing list for this team.

        :return: The mailing list object, or None if this team has no
        mailing list.
        """
        return getUtility(IMailingListSet).get(self.context.name)

    def getListInState(self, *statuses):
        """Return this team's mailing list if it's in one of the given states.

        :param statuses: The states that the mailing list must be in for it to
            be returned.
        :return: This team's IMailingList or None if the team doesn't have
            a mailing list, or if it isn't in one of the given states.
        """
        mailing_list = self._getList()
        if mailing_list is not None and mailing_list.status in statuses:
            return mailing_list
        return None

    @property
    def list_is_usable(self):
        """Checks whether or not the list is usable; ie. accepting messages.

        The list must exist and must be in a state acceptable to
        MailingList.is_usable.
        """
        mailing_list = self._getList()
        return mailing_list is not None and mailing_list.is_usable

    @property
    def mailinglist_address(self):
        """The address for this team's mailing list."""
        mailing_list = self._getList()
        assert mailing_list is not None, (
                'Attempt to find address of nonexistent mailing list.')
        return mailing_list.address


class TeamContactAddressView(MailingListTeamBaseView):
    """A view for manipulating the team's contact address."""

    schema = ITeamContactAddressForm

    custom_widget(
        'contact_method', LaunchpadRadioWidget, orientation='vertical')

    @property
    def label(self):
        return "%s contact address" % self.context.displayname

    page_title = label

    def setUpFields(self):
        """See `LaunchpadFormView`.
        """
        super(TeamContactAddressView, self).setUpFields()

        # Replace the default contact_method field by a custom one.
        self.form_fields = (
            form.FormFields(self.getContactMethodField())
            + self.form_fields.omit('contact_method'))

    def getContactMethodField(self):
        """Create the form.Fields to use for the contact_method field.

        If the team has a mailing list that can be the team contact
        method, the full range of TeamContactMethod terms shows up
        in the contact_method vocabulary. Otherwise, the HOSTED_LIST
        term does not show up in the vocabulary.
        """
        terms = [term for term in TeamContactMethod]
        for i, term in enumerate(TeamContactMethod):
            if term.value == TeamContactMethod.HOSTED_LIST:
                hosted_list_term_index = i
                break
        if self.list_is_usable:
            # The team's mailing list can be used as the contact
            # address. However we need to change the title of the
            # corresponding term to include the list's email address.
            title = structured(
                'The Launchpad mailing list for this team - '
                '<strong>%s</strong>', self.mailinglist_address)
            hosted_list_term = SimpleTerm(
                TeamContactMethod.HOSTED_LIST,
                TeamContactMethod.HOSTED_LIST.name, title)
            terms[hosted_list_term_index] = hosted_list_term
        else:
            # The team's mailing list does not exist or can't be
            # used as the contact address. Remove the term from the
            # field.
            del terms[hosted_list_term_index]

        return form.FormField(
            Choice(__name__='contact_method',
                   title=_("How do people contact this team's members?"),
                   required=True, vocabulary=SimpleVocabulary(terms)))

    def validate(self, data):
        """Validate the team contact email address.

        Validation only occurs if the user wants to use an external address,
        and the given email address is not already in use by this team.
        This also ensures the mailing list is active if the HOSTED_LIST option
        has been chosen.
        """
        if data['contact_method'] == TeamContactMethod.EXTERNAL_ADDRESS:
            email = data['contact_address']
            if not email:
                self.setFieldError(
                   'contact_address',
                   'Enter the contact address you want to use for this team.')
                return
            email = getUtility(IEmailAddressSet).getByEmail(
                data['contact_address'])
            if email is None or email.person != self.context:
                try:
                    validate_new_team_email(data['contact_address'])
                except LaunchpadValidationError, error:
                    # We need to wrap this in structured, so that the
                    # markup is preserved.  Note that this puts the
                    # responsibility for security on the exception thrower.
                    self.setFieldError('contact_address',
                                       structured(str(error)))
        elif data['contact_method'] == TeamContactMethod.HOSTED_LIST:
            mailing_list = getUtility(IMailingListSet).get(self.context.name)
            if mailing_list is None or not mailing_list.is_usable:
                self.addError(
                    "This team's mailing list is not active and may not be "
                    "used as its contact address yet")
        else:
            # Nothing to validate!
            pass

    @property
    def initial_values(self):
        """Infer the contact method from this team's preferredemail.

        Return a dictionary representing the contact_address and
        contact_method so inferred.
        """
        context = self.context
        if context.preferredemail is None:
            return dict(contact_method=TeamContactMethod.NONE)
        mailing_list = getUtility(IMailingListSet).get(context.name)
        if (mailing_list is not None
            and mailing_list.address == context.preferredemail.email):
            return dict(contact_method=TeamContactMethod.HOSTED_LIST)
        return dict(contact_address=context.preferredemail.email,
                    contact_method=TeamContactMethod.EXTERNAL_ADDRESS)

    @action('Change', name='change')
    def change_action(self, action, data):
        """Changes the contact address for this mailing list."""
        context = self.context
        email_set = getUtility(IEmailAddressSet)
        list_set = getUtility(IMailingListSet)
        contact_method = data['contact_method']
        if contact_method == TeamContactMethod.NONE:
            context.setContactAddress(None)
        elif contact_method == TeamContactMethod.HOSTED_LIST:
            mailing_list = list_set.get(context.name)
            assert mailing_list is not None and mailing_list.is_usable, (
                "A team can only use a usable mailing list as its contact "
                "address.")
            email = email_set.getByEmail(mailing_list.address)
            assert email is not None, (
                "Cannot find mailing list's posting address")
            context.setContactAddress(email)
        elif contact_method == TeamContactMethod.EXTERNAL_ADDRESS:
            contact_address = data['contact_address']
            email = email_set.getByEmail(contact_address)
            if email is None:
                generateTokenAndValidationEmail(contact_address, context)
                self.request.response.addInfoNotification(
                    "A confirmation message has been sent to '%s'. Follow "
                    "the instructions in that message to confirm the new "
                    "contact address for this team. (If the message "
                    "doesn't arrive in a few minutes, your mail provider "
                    "might use 'greylisting', which could delay the "
                    "message for up to an hour or two.)" % contact_address)
            else:
                context.setContactAddress(email)
        else:
            raise UnexpectedFormData(
                "Unknown contact_method: %s" % contact_method)

    @property
    def next_url(self):
        return canonical_url(self.context)

    cancel_url = next_url


class TeamMailingListConfigurationView(MailingListTeamBaseView):
    """A view for creating and configuring a team's mailing list.

    Allows creating a request for a list, cancelling the request,
    setting the welcome message, deactivating, and reactivating the
    list.
    """

    schema = IMailingList
    field_names = ['welcome_message']
    label = "Mailing list configuration"
    custom_widget('welcome_message', TextAreaWidget, width=72, height=10)
    page_title = label

    def __init__(self, context, request):
        """Set feedback messages for users who want to edit the mailing list.

        There are a number of reasons why your changes to the mailing
        list might not take effect immediately. First, the mailing
        list may not actually be set as the team contact
        address. Second, the mailing list may be in a transitional
        state: from MODIFIED to UPDATING to ACTIVE can take a while.
        """
        super(TeamMailingListConfigurationView, self).__init__(
            context, request)
        list_set = getUtility(IMailingListSet)
        self.mailing_list = list_set.get(self.context.name)

    @action('Save', name='save')
    def save_action(self, action, data):
        """Sets the welcome message for a mailing list."""
        welcome_message = data.get('welcome_message')
        assert (self.mailing_list is not None
                and self.mailing_list.is_usable), (
            "Only a usable mailing list can be configured.")

        if (welcome_message is not None
            and welcome_message != self.mailing_list.welcome_message):
            self.mailing_list.welcome_message = welcome_message

        self.next_url = canonical_url(self.context)

    def cancel_list_creation_validator(self, action, data):
        """Validator for the `cancel_list_creation` action.

        Adds an error if someone tries to cancel a request that's
        already been approved or declined. This can only happen
        through bypassing the UI.
        """
        getUtility(IMailingListSet).get(self.context.name)
        if self.getListInState(MailingListStatus.REGISTERED) is None:
            self.addError("This application can't be cancelled.")

    @action('Cancel Application', name='cancel_list_creation',
            validator=cancel_list_creation_validator)
    def cancel_list_creation(self, action, data):
        """Cancels a pending mailing list registration."""
        mailing_list_set = getUtility(IMailingListSet)
        mailing_list_set.get(self.context.name).cancelRegistration()
        self.request.response.addInfoNotification(
            "Mailing list application cancelled.")
        self.next_url = canonical_url(self.context)

    def create_list_creation_validator(self, action, data):
        """Validator for the `create_list_creation` action.

        Adds an error if someone tries to create a mailing list for a
        team that already has one. This can only happen through
        bypassing the UI.
        """
        if not self.list_can_be_created:
            self.addError(
                "You cannot create a new mailing list for this team.")

    @action('Create new Mailing List', name='create_list_creation',
            validator=create_list_creation_validator)
    def create_list_creation(self, action, data):
        """Creates a new mailing list."""
        getUtility(IMailingListSet).new(self.context)
        self.request.response.addInfoNotification(
            "The mailing list is being created and will be available for "
            "use in a few minutes.")
        self.next_url = canonical_url(self.context)

    def deactivate_list_validator(self, action, data):
        """Adds an error if someone tries to deactivate a non-active list.

        This can only happen through bypassing the UI.
        """
        if not self.list_can_be_deactivated:
            self.addError("This list can't be deactivated.")

    @action('Deactivate this Mailing List', name='deactivate_list',
            validator=deactivate_list_validator)
    def deactivate_list(self, action, data):
        """Deactivates a mailing list."""
        getUtility(IMailingListSet).get(self.context.name).deactivate()
        self.request.response.addInfoNotification(
            "The mailing list will be deactivated within a few minutes.")
        self.next_url = canonical_url(self.context)

    def reactivate_list_validator(self, action, data):
        """Adds an error if a non-deactivated list is reactivated.

        This can only happen through bypassing the UI.
        """
        if not self.list_can_be_reactivated:
            self.addError("Only a deactivated list can be reactivated.")

    @action('Reactivate this Mailing List', name='reactivate_list',
            validator=reactivate_list_validator)
    def reactivate_list(self, action, data):
        getUtility(IMailingListSet).get(self.context.name).reactivate()
        self.request.response.addInfoNotification(
            "The mailing list will be reactivated within a few minutes.")
        self.next_url = canonical_url(self.context)

    def purge_list_validator(self, action, data):
        """Adds an error if the list is not safe to purge.

        This can only happen through bypassing the UI.
        """
        if not self.list_can_be_purged:
            self.addError('This list cannot be purged.')

    @action('Purge this Mailing List', name='purge_list',
            validator=purge_list_validator)
    def purge_list(self, action, data):
        getUtility(IMailingListSet).get(self.context.name).purge()
        self.request.response.addInfoNotification(
            'The mailing list has been purged.')
        self.next_url = canonical_url(self.context)

    @property
    def list_is_usable_but_not_contact_method(self):
        """The list could be the contact method for its team, but isn't.

        The list exists and is usable, but isn't set as the contact
        method.
        """

        return (self.list_is_usable and
                (self.context.preferredemail is None or
                 self.mailing_list.address !=
                 self.context.preferredemail.email))

    @property
    def mailing_list_status_message(self):
        """A status message describing the state of the mailing list.

        This status message helps a user be aware of behind-the-scenes
        processes that would otherwise manifest only as mysterious
        failures and inconsistencies.
        """
        contact_admin = (
            'Please '
            '<a href="https://answers.launchpad.net/launchpad/+faq/197">'
            'contact a Launchpad administrator</a> for further assistance.')

        if (self.mailing_list is None or
            self.mailing_list.status == MailingListStatus.PURGED):
            # Purged lists act as if they don't exist.
            return None
        elif self.mailing_list.status == MailingListStatus.REGISTERED:
            return None
        elif self.mailing_list.status in [MailingListStatus.APPROVED,
                                          MailingListStatus.CONSTRUCTING]:
            return _("This team's mailing list will be available within "
                     "a few minutes.")
        elif self.mailing_list.status == MailingListStatus.DECLINED:
            return _("The application for this team's mailing list has been "
                     'declined. ' + contact_admin)
        elif self.mailing_list.status == MailingListStatus.ACTIVE:
            return None
        elif self.mailing_list.status == MailingListStatus.DEACTIVATING:
            return _("This team's mailing list is being deactivated.")
        elif self.mailing_list.status == MailingListStatus.INACTIVE:
            return _("This team's mailing list has been deactivated.")
        elif self.mailing_list.status == MailingListStatus.FAILED:
            return _("This team's mailing list could not be created. " +
                     contact_admin)
        elif self.mailing_list.status == MailingListStatus.MODIFIED:
            return _("An update to this team's mailing list is pending "
                     "and has not yet taken effect.")
        elif self.mailing_list.status == MailingListStatus.UPDATING:
            return _("A change to this team's mailing list is currently "
                     "being applied.")
        elif self.mailing_list.status == MailingListStatus.MOD_FAILED:
            return _("This team's mailing list is in an inconsistent state "
                     'because a change to its configuration was not '
                     'applied. ' + contact_admin)
        else:
            raise AssertionError(
                "Unknown mailing list status: %s" % self.mailing_list.status)

    @property
    def initial_values(self):
        """The initial value of welcome_message comes from the database.

        :return: A dictionary containing the current welcome message.
        """
        if self.mailing_list is not None:
            return dict(welcome_message=self.mailing_list.welcome_message)
        else:
            return {}

    @property
    def list_application_can_be_cancelled(self):
        """Can this team's mailing list request be cancelled?

        It can only be cancelled if its state is REGISTERED.
        """
        return self.getListInState(MailingListStatus.REGISTERED) is not None

    @property
    def list_can_be_created(self):
        """Can a mailing list be created for this team?

        It can only be requested if there's no mailing list associated with
        this team, or the mailing list has been purged.
        """
        mailing_list = getUtility(IMailingListSet).get(self.context.name)
        return (mailing_list is None or
                mailing_list.status == MailingListStatus.PURGED)

    @property
    def list_can_be_deactivated(self):
        """Is this team's list in a state where it can be deactivated?

        The list must exist and be in the ACTIVE state.
        """
        return self.getListInState(MailingListStatus.ACTIVE) is not None

    @property
    def list_can_be_reactivated(self):
        """Is this team's list in a state where it can be reactivated?

        The list must exist and be in the INACTIVE state.
        """
        return self.getListInState(MailingListStatus.INACTIVE) is not None

    @property
    def list_can_be_purged(self):
        """Is this team's list in a state where it can be purged?

        The list must exist and be in one of the REGISTERED, DECLINED, FAILED,
        or INACTIVE states.  Further, the user doing the purging, must be
        an owner, Launchpad administrator or mailing list expert.
        """
        is_moderator = check_permission('launchpad.Moderate', self.context)
        is_mailing_list_manager = check_permission(
            'launchpad.Moderate', self.context)
        if is_moderator or is_mailing_list_manager:
            return self.getListInState(*PURGE_STATES) is not None
        else:
            return False


class TeamMailingListSubscribersView(LaunchpadView):
    """The list of people subscribed to a team's mailing list."""

    max_columns = 4

    @property
    def label(self):
        return ('Mailing list subscribers for the %s team' %
                self.context.displayname)

    @cachedproperty
    def subscribers(self):
        return BatchNavigator(
            self.context.mailing_list.getSubscribers(), self.request)

    def renderTable(self):
        html = ['<table style="max-width: 80em">']
        items = list(self.subscribers.currentBatch())
        assert len(items) > 0, (
            "Don't call this method if there are no subscribers to show.")
        # When there are more than 10 items, we use multiple columns, but
        # never more columns than self.max_columns.
        columns = int(math.ceil(len(items) / 10.0))
        columns = min(columns, self.max_columns)
        rows = int(math.ceil(len(items) / float(columns)))
        for i in range(0, rows):
            html.append('<tr>')
            for j in range(0, columns):
                index = i + (j * rows)
                if index >= len(items):
                    break
                subscriber_link = PersonFormatterAPI(items[index]).link(None)
                html.append(
                    '<td style="width: 20em">%s</td>' % subscriber_link)
            html.append('</tr>')
        html.append('</table>')
        return '\n'.join(html)


class TeamMailingListModerationView(MailingListTeamBaseView):
    """A view for moderating the held messages of a mailing list."""

    schema = Interface
    label = 'Mailing list moderation'

    def __init__(self, context, request):
        """Allow for review and moderation of held mailing list posts."""
        super(TeamMailingListModerationView, self).__init__(context, request)
        list_set = getUtility(IMailingListSet)
        self.mailing_list = list_set.get(self.context.name)
        if self.mailing_list is None:
            self.request.response.addInfoNotification(
                '%s does not have a mailing list.' % self.context.displayname)
            return self.request.response.redirect(canonical_url(self.context))

    @cachedproperty
    def hold_count(self):
        """The number of message being held for moderator approval.

        :return: Number of message being held for moderator approval.
        """
        ## return self.mailing_list.getReviewableMessages().count()
        # This looks like it would be more efficient, but it raises
        # LocationError.
        return self.held_messages.currentBatch().listlength

    @cachedproperty
    def held_messages(self):
        """All the messages being held for moderator approval.

        :return: Sequence of held messages.
        """
        results = self.mailing_list.getReviewableMessages()
        navigator = BatchNavigator(results, self.request)
        navigator.setHeadings('message', 'messages')
        return navigator

    @action('Moderate', name='moderate')
    def moderate_action(self, action, data):
        """Commits the moderation actions."""
        # We're somewhat abusing LaunchpadFormView, so the interesting bits
        # won't be in data.  Instead, get it out of the request.
        reviewable = self.hold_count
        disposed_count = 0
        actions = {}
        form = self.request.form_ng
        for field_name in form:
            if (field_name.startswith('field.') and
                field_name.endswith('')):
                # A moderated message.
                quoted_id = field_name[len('field.'):]
                message_id = unquote(quoted_id)
                actions[message_id] = form.getOne(field_name)
        messages = self.mailing_list.getReviewableMessages(
            message_id_filter=actions)
        for message in messages:
            action_name = actions[message.message_id]
            # This essentially acts like a switch statement or if/elifs.  It
            # looks the action up in a map of allowed actions, watching out
            # for bogus input.
            try:
                action, status = dict(
                    approve=(message.approve, PostedMessageStatus.APPROVED),
                    reject=(message.reject, PostedMessageStatus.REJECTED),
                    discard=(message.discard, PostedMessageStatus.DISCARDED),
                    # hold is a no-op.  Using None here avoids the bogus input
                    # trigger.
                    hold=(None, None),
                    )[action_name]
            except KeyError:
                raise UnexpectedFormData(
                    'Invalid moderation action for held message %s: %s' %
                    (message.message_id, action_name))
            if action is not None:
                disposed_count += 1
                action(self.user)
                self.request.response.addInfoNotification(
                    'Held message %s; Message-ID: %s' % (
                        status.title.lower(), message.message_id))
        still_held = reviewable - disposed_count
        if still_held > 0:
            self.request.response.addInfoNotification(
                'Messages still held for review: %d of %d' %
                (still_held, reviewable))
        self.next_url = canonical_url(self.context)


class TeamAddView(TeamFormMixin, HasRenewalPolicyMixin, LaunchpadFormView):
    """View for adding a new team."""

    page_title = 'Register a new team in Launchpad'
    label = page_title
    schema = ITeamCreation

    custom_widget('teamowner', HiddenUserWidget)
    custom_widget(
        'renewal_policy', LaunchpadRadioWidget, orientation='vertical')
    custom_widget(
        'subscriptionpolicy', LaunchpadRadioWidgetWithDescription,
        orientation='vertical')
    custom_widget('teamdescription', TextAreaWidget, height=10, width=30)

    def setUpFields(self):
        """See `LaunchpadViewForm`.

        Only Launchpad Admins get to see the visibility field.
        """
        super(TeamAddView, self).setUpFields()
        self.conditionallyOmitVisibility()

    @action('Create Team', name='create')
    def create_action(self, action, data):
        name = data.get('name')
        displayname = data.get('displayname')
        teamdescription = data.get('teamdescription')
        defaultmembershipperiod = data.get('defaultmembershipperiod')
        defaultrenewalperiod = data.get('defaultrenewalperiod')
        subscriptionpolicy = data.get('subscriptionpolicy')
        teamowner = data.get('teamowner')
        team = getUtility(IPersonSet).newTeam(
            teamowner, name, displayname, teamdescription,
            subscriptionpolicy, defaultmembershipperiod, defaultrenewalperiod)
        visibility = data.get('visibility')
        if visibility:
            team.visibility = visibility
        email = data.get('contactemail')
        if email is not None:
            generateTokenAndValidationEmail(email, team)
            self.request.response.addNotification(
                "A confirmation message has been sent to '%s'. Follow the "
                "instructions in that message to confirm the new "
                "contact address for this team. "
                "(If the message doesn't arrive in a few minutes, your mail "
                "provider might use 'greylisting', which could delay the "
                "message for up to an hour or two.)" % email)

        self.next_url = canonical_url(team)

    def _validateVisibilityConsistency(self, value):
        """See `TeamFormMixin`."""
        return None

    @property
    def _visibility(self):
        """Return the visibility for the object.

        For a new team it is PUBLIC unless otherwise set in the form data.
        """
        return PersonVisibility.PUBLIC

    @property
    def _name(self):
        return None


class ProposedTeamMembersEditView(LaunchpadFormView):
    schema = Interface
    label = 'Proposed team members'

    @action('Save changes', name='save')
    def action_save(self, action, data):
        expires = self.context.defaultexpirationdate
        statuses = dict(
            approve=TeamMembershipStatus.APPROVED,
            decline=TeamMembershipStatus.DECLINED,
            )
        target_team = self.context
        failed_joins = []
        for person in target_team.proposedmembers:
            action = self.request.form.get('action_%d' % person.id)
            status = statuses.get(action)
            if status is None:
                # The action is "hold" or no action was specified for this
                # person, which could happen if the set of proposed members
                # changed while the form was being processed.
                continue
            try:
                target_team.setMembershipData(
                    person, status, reviewer=self.user, expires=expires,
                    comment=self.request.form.get('comment'))
            except CyclicalTeamMembershipError:
                failed_joins.append(person)

        if len(failed_joins) > 0:
            failed_names = [person.displayname for person in failed_joins]
            failed_list = ", ".join(failed_names)

            mapping = dict(this_team=target_team.displayname,
                failed_list=failed_list)

            if len(failed_joins) == 1:
                self.request.response.addInfoNotification(
                    _('${this_team} is a member of the following team, so it '
                      'could not be accepted:  '
                      '${failed_list}.  You need to "Decline" that team.',
                      mapping=mapping))
            else:
                self.request.response.addInfoNotification(
                    _('${this_team} is a member of the following teams, so '
                      'they could not be accepted:  '
                      '${failed_list}.  You need to "Decline" those teams.',
                      mapping=mapping))
            self.next_url = ''
        else:
            self.next_url = self._next_url

    @property
    def page_title(self):
        return 'Proposed members of %s' % self.context.displayname

    @property
    def _next_url(self):
        return '%s/+members' % canonical_url(self.context)

    cancel_url = _next_url


class TeamBrandingView(BrandingChangeView):

    schema = ITeam
    field_names = ['icon', 'logo', 'mugshot']


class ITeamMember(Interface):
    """The interface used in the form to add a new member to a team."""

    newmember = PublicPersonChoice(
        title=_('New member'), required=True,
        vocabulary='ValidTeamMember',
        description=_("The user or team which is going to be "
                        "added as the new member of this team."))


class TeamMemberAddView(LaunchpadFormView):

    schema = ITeamMember
    label = "Select the new member"
    # XXX: jcsackett 5.7.2011 bug=799847 The assignment of 'false' to the vars
    # below should be changed to the more appropriate False bool when we're
    # making use of the JSON cache to setup pickers, rather than assembling
    # javascript in a view macro.
    custom_widget(
        'newmember', PersonPickerWidget,
        show_assign_me_button='false', show_remove_button='false')

    @property
    def page_title(self):
        return 'Add members to %s' % self.context.displayname

    @property
    def cancel_url(self):
        return canonical_url(self.context)

    def validate(self, data):
        """Verify new member.

        This checks that the new member has some active members and is not
        already an active team member.
        """
        newmember = data.get('newmember')
        error = None
        if newmember is not None:
            if newmember.is_team and not newmember.activemembers:
                error = _("You can't add a team that doesn't have any active"
                          " members.")
            elif newmember in self.context.activemembers:
                error = _("%s (%s) is already a member of %s." % (
                    newmember.displayname, newmember.name,
                    self.context.displayname))

        if error:
            self.setFieldError("newmember", error)

    @action(u"Add Member", name="add")
    def add_action(self, action, data):
        """Add the new member to the team."""
        newmember = data['newmember']
        # If we get to this point with the member being the team itself,
        # it means the ValidTeamMemberVocabulary is broken.
        assert newmember != self.context, (
            "Can't add team to itself: %s" % newmember)

        changed, new_status = self.context.addMember(
            newmember, reviewer=self.user,
            status=TeamMembershipStatus.APPROVED)

        if new_status == TeamMembershipStatus.INVITED:
            msg = "%s has been invited to join this team." % (
                  newmember.unique_displayname)
        else:
            msg = "%s has been added as a member of this team." % (
                  newmember.unique_displayname)
        self.request.response.addInfoNotification(msg)
        # Clear the newmember widget so that the user can add another member.
        self.widgets['newmember'].setRenderedValue(None)


class TeamMapView(LaunchpadView):
    """Show all people with known locations on a map.

    Also provides links to edit the locations of people in the team without
    known locations.
    """

    label = "Team member locations"
    limit = None

    @cachedproperty
    def mapped_participants(self):
        """Participants with locations."""
        return self.context.getMappedParticipants(limit=self.limit)

    @cachedproperty
    def mapped_participants_count(self):
        """Count of participants with locations."""
        return self.context.mapped_participants_count

    @cachedproperty
    def has_mapped_participants(self):
        """Does the team have any mapped participants?"""
        return self.mapped_participants_count > 0

    @cachedproperty
    def unmapped_participants(self):
        """Participants (ordered by name) with no recorded locations."""
        return list(self.context.unmapped_participants)

    @cachedproperty
    def unmapped_participants_count(self):
        """Count of participants with no recorded locations."""
        return self.context.unmapped_participants_count

    @cachedproperty
    def times(self):
        """The current times in time zones with members."""
        zones = set(participant.time_zone
                    for participant in self.mapped_participants)
        times = [datetime.now(pytz.timezone(zone))
                 for zone in zones]
        timeformat = '%H:%M'
        return sorted(
            set(time.strftime(timeformat) for time in times))

    @cachedproperty
    def bounds(self):
        """A dictionary with the bounds and center of the map, or None"""
        if self.has_mapped_participants:
            return self.context.getMappedParticipantsBounds(self.limit)
        return None

    @property
    def map_html(self):
        """HTML which shows the map with location of the team's members."""
        return """
            <script type="text/javascript">
                LPS.use('node', 'lp.app.mapping', function(Y) {
                    function renderMap() {
                        Y.lp.app.mapping.renderTeamMap(
                            %(min_lat)s, %(max_lat)s, %(min_lng)s,
                            %(max_lng)s, %(center_lat)s, %(center_lng)s);
                     }
                     Y.on("domready", renderMap);
                });
            </script>""" % self.bounds

    @property
    def map_portlet_html(self):
        """The HTML which shows a small version of the team's map."""
        return """
            <script type="text/javascript">
                LPS.use('node', 'lp.app.mapping', function(Y) {
                    function renderMap() {
                        Y.lp.app.mapping.renderTeamMapSmall(
                            %(center_lat)s, %(center_lng)s);
                     }
                     Y.on("domready", renderMap);
                });
            </script>""" % self.bounds


class TeamMapData(TeamMapView):
    """An XML dump of the locations of all team members."""

    def render(self):
        self.request.response.setHeader(
            'content-type', 'application/xml;charset=utf-8')
        body = LaunchpadView.render(self)
        return body.encode('utf-8')


class TeamMapLtdMixin:
    """A mixin for team views with limited participants."""
    limit = 24


class TeamMapLtdView(TeamMapLtdMixin, TeamMapView):
    """Team map view with limited participants."""


class TeamMapLtdData(TeamMapLtdMixin, TeamMapData):
    """An XML dump of the locations of limited number of team members."""


class TeamNavigation(PersonNavigation):

    usedfor = ITeam

    @stepthrough('+poll')
    def traverse_poll(self, name):
        return getUtility(IPollSet).getByTeamAndName(self.context, name)

    @stepthrough('+invitation')
    def traverse_invitation(self, name):
        # Return the found membership regardless of its status as we know
        # TeamInvitationView can handle memberships in statuses other than
        # INVITED.
        membership = getUtility(ITeamMembershipSet).getByPersonAndTeam(
            self.context, getUtility(IPersonSet).getByName(name))
        if membership is None:
            return None
        return TeamInvitationView(membership, self.request)

    @stepthrough('+member')
    def traverse_member(self, name):
        person = getUtility(IPersonSet).getByName(name)
        if person is None:
            return None
        return getUtility(ITeamMembershipSet).getByPersonAndTeam(
            person, self.context)


class TeamBreadcrumb(Breadcrumb):
    """Builds a breadcrumb for an `ITeam`."""

    @property
    def text(self):
        return smartquote('"%s" team') % self.context.displayname


class TeamMembershipSelfRenewalView(LaunchpadFormView):

    implements(IBrowserPublisher)

    # This is needed for our breadcrumbs, as there's no <browser:page>
    # declaration for this view.
    __name__ = '+self-renewal'
    schema = ITeamMembership
    field_names = []
    template = ViewPageTemplateFile(
        '../templates/teammembership-self-renewal.pt')

    @property
    def label(self):
        return "Renew membership of %s in %s" % (
            self.context.person.displayname, self.context.team.displayname)

    page_title = label

    def __init__(self, context, request):
        # Only the member himself or admins of the member (in case it's a
        # team) can see the page in which they renew memberships that are
        # about to expire.
        if not check_permission('launchpad.Edit', context.person):
            raise Unauthorized(
                "You may not renew the membership for %s." %
                context.person.displayname)
        LaunchpadFormView.__init__(self, context, request)

    def browserDefault(self, request):
        return self, ()

    @property
    def reason_for_denied_renewal(self):
        """Return text describing why the membership can't be renewed."""
        context = self.context
        ondemand = TeamMembershipRenewalPolicy.ONDEMAND
        admin = TeamMembershipStatus.ADMIN
        approved = TeamMembershipStatus.APPROVED
        date_limit = datetime.now(pytz.UTC) - timedelta(
            days=DAYS_BEFORE_EXPIRATION_WARNING_IS_SENT)
        if context.status not in (admin, approved):
            text = "it is not active."
        elif context.team.renewal_policy != ondemand:
            text = ('<a href="%s">%s</a> is not a team that allows its '
                    'members to renew their own memberships.'
                    % (canonical_url(context.team),
                       context.team.unique_displayname))
        elif context.dateexpires is None or context.dateexpires > date_limit:
            if context.person.is_team:
                link_text = "Somebody else has already renewed it."
            else:
                link_text = (
                    "You or one of the team administrators has already "
                    "renewed it.")
            text = ('it is not set to expire in %d days or less. '
                    '<a href="%s/+members">%s</a>'
                    % (DAYS_BEFORE_EXPIRATION_WARNING_IS_SENT,
                       canonical_url(context.team), link_text))
        else:
            raise AssertionError('This membership can be renewed!')
        return text

    @property
    def time_before_expiration(self):
        return self.context.dateexpires - datetime.now(pytz.timezone('UTC'))

    @property
    def next_url(self):
        return canonical_url(self.context.person)

    cancel_url = next_url

    @action(_("Renew"), name="renew")
    def renew_action(self, action, data):
        member = self.context.person
        # This if-statement prevents an exception if the user
        # double clicks on the submit button.
        if self.context.canBeRenewedByMember():
            member.renewTeamMembership(self.context.team)
        self.request.response.addInfoNotification(
            _("Membership renewed until ${date}.", mapping=dict(
                    date=self.context.dateexpires.strftime('%Y-%m-%d'))))


class ITeamMembershipInvitationAcknowledgementForm(Interface):
    """Schema for the form in which team admins acknowledge invitations.

    We could use ITeamMembership for that, but the acknowledger_comment is
    marked readonly there and that means LaunchpadFormView won't include the
    value of that in the data given to our action handler.
    """

    acknowledger_comment = Text(
        title=_("Comment"), required=False, readonly=False)


class TeamInvitationView(LaunchpadFormView):
    """Where team admins can accept/decline membership invitations."""

    implements(IBrowserPublisher)

    # This is needed for our breadcrumbs, as there's no <browser:page>
    # declaration for this view.
    __name__ = '+invitation'
    schema = ITeamMembershipInvitationAcknowledgementForm
    field_names = ['acknowledger_comment']
    custom_widget('acknowledger_comment', TextAreaWidget, height=5, width=60)
    template = ViewPageTemplateFile(
        '../templates/teammembership-invitation.pt')

    def __init__(self, context, request):
        # Only admins of the invited team can see the page in which they
        # approve/decline invitations.
        if not check_permission('launchpad.Edit', context.person):
            raise Unauthorized(
                "Only team administrators can approve/decline invitations "
                "sent to this team.")
        LaunchpadFormView.__init__(self, context, request)

    @property
    def label(self):
        """See `LaunchpadFormView`."""
        return "Make %s a member of %s" % (
            self.context.person.displayname, self.context.team.displayname)

    @property
    def page_title(self):
        return smartquote(
            '"%s" team invitation') % self.context.team.displayname

    def browserDefault(self, request):
        return self, ()

    @property
    def next_url(self):
        return canonical_url(self.context.person)

    @action(_("Accept"), name="accept")
    def accept_action(self, action, data):
        if self.context.status != TeamMembershipStatus.INVITED:
            self.request.response.addInfoNotification(
                _("This invitation has already been processed."))
            return
        member = self.context.person
        try:
            member.acceptInvitationToBeMemberOf(
                self.context.team, data['acknowledger_comment'])
        except CyclicalTeamMembershipError:
            self.request.response.addInfoNotification(
                _("This team may not be added to ${that_team} because it is "
                  "a member of ${this_team}.",
                  mapping=dict(
                      that_team=self.context.team.displayname,
                      this_team=member.displayname)))
        else:
            self.request.response.addInfoNotification(
                _("This team is now a member of ${team}.", mapping=dict(
                    team=self.context.team.displayname)))

    @action(_("Decline"), name="decline")
    def decline_action(self, action, data):
        if self.context.status != TeamMembershipStatus.INVITED:
            self.request.response.addInfoNotification(
                _("This invitation has already been processed."))
            return
        member = self.context.person
        member.declineInvitationToBeMemberOf(
            self.context.team, data['acknowledger_comment'])
        self.request.response.addInfoNotification(
            _("Declined the invitation to join ${team}", mapping=dict(
                  team=self.context.team.displayname)))

    @action(_("Cancel"), name="cancel")
    def cancel_action(self, action, data):
        # Simply redirect back.
        pass


class TeamMenuMixin(PPANavigationMenuMixIn, CommonMenuLinks):
    """Base class of team menus.

    You will need to override the team attribute if your menu subclass
    has the view as its context object.
    """

    def profile(self):
        target = ''
        text = 'Overview'
        return Link(target, text)

    @enabled_with_permission('launchpad.Edit')
    def edit(self):
        target = '+edit'
        text = 'Change details'
        return Link(target, text, icon='edit')

    @enabled_with_permission('launchpad.Edit')
    def branding(self):
        target = '+branding'
        text = 'Change branding'
        return Link(target, text, icon='edit')

    @enabled_with_permission('launchpad.Owner')
    def reassign(self):
        target = '+reassign'
        text = 'Change owner'
        summary = 'Change the owner of the team'
        return Link(target, text, summary, icon='edit')

    @enabled_with_permission('launchpad.Moderate')
    def delete(self):
        target = '+delete'
        text = 'Delete'
        summary = 'Delete this team'
        return Link(target, text, summary, icon='trash-icon')

    @enabled_with_permission('launchpad.View')
    def members(self):
        target = '+members'
        text = 'Show all members'
        return Link(target, text, icon='team')

    @enabled_with_permission('launchpad.Edit')
    def received_invitations(self):
        target = '+invitations'
        text = 'Show received invitations'
        return Link(target, text, icon='info')

    @enabled_with_permission('launchpad.Edit')
    def add_member(self):
        target = '+addmember'
        text = 'Add member'
        return Link(target, text, icon='add')

    @enabled_with_permission('launchpad.Edit')
    def proposed_members(self):
        target = '+editproposedmembers'
        text = 'Approve or decline members'
        return Link(target, text, icon='add')

    def map(self):
        target = '+map'
        text = 'View map and time zones'
        return Link(target, text, icon='meeting')

    def add_my_teams(self):
        target = '+add-my-teams'
        text = 'Add one of my teams'
        enabled = True
        restricted = TeamSubscriptionPolicy.RESTRICTED
        if self.person.subscriptionpolicy == restricted:
            # This is a restricted team; users can't join.
            enabled = False
        return Link(target, text, icon='add', enabled=enabled)

    def memberships(self):
        target = '+participation'
        text = 'Show team participation'
        return Link(target, text, icon='info')

    @enabled_with_permission('launchpad.View')
    def mugshots(self):
        target = '+mugshots'
        text = 'Show member photos'
        return Link(target, text, icon='team')

    def polls(self):
        target = '+polls'
        text = 'Show polls'
        return Link(target, text, icon='info')

    @enabled_with_permission('launchpad.Edit')
    def add_poll(self):
        target = '+newpoll'
        text = 'Create a poll'
        return Link(target, text, icon='add')

    @enabled_with_permission('launchpad.Edit')
    def editemail(self):
        target = '+contactaddress'
        text = 'Set contact address'
        summary = (
            'The address Launchpad uses to contact %s' %
            self.person.displayname)
        return Link(target, text, summary, icon='edit')

    @enabled_with_permission('launchpad.Moderate')
    def configure_mailing_list(self):
        target = '+mailinglist'
        mailing_list = self.person.mailing_list
        if mailing_list is not None:
            text = 'Configure mailing list'
            icon = 'edit'
        else:
            text = 'Create a mailing list'
            icon = 'add'
        summary = (
            'The mailing list associated with %s' % self.context.displayname)
        return Link(target, text, summary, icon=icon)

    @enabled_with_active_mailing_list
    @enabled_with_permission('launchpad.Edit')
    def moderate_mailing_list(self):
        target = '+mailinglist-moderate'
        text = 'Moderate mailing list'
        summary = (
            'The mailing list associated with %s' % self.context.displayname)
        return Link(target, text, summary, icon='edit')

    @enabled_with_permission('launchpad.Edit')
    def editlanguages(self):
        target = '+editlanguages'
        text = 'Set preferred languages'
        return Link(target, text, icon='edit')

    def leave(self):
        enabled = True
        if not userIsActiveTeamMember(self.person):
            enabled = False
        if self.person.teamowner == self.user:
            # The owner cannot leave his team.
            enabled = False
        target = '+leave'
        text = 'Leave the Team'
        icon = 'remove'
        return Link(target, text, icon=icon, enabled=enabled)

    def join(self):
        enabled = True
        person = self.person
        if userIsActiveTeamMember(person):
            enabled = False
        elif (self.person.subscriptionpolicy ==
              TeamSubscriptionPolicy.RESTRICTED):
            # This is a restricted team; users can't join.
            enabled = False
        target = '+join'
        text = 'Join the team'
        icon = 'add'
        return Link(target, text, icon=icon, enabled=enabled)


class TeamOverviewMenu(ApplicationMenu, TeamMenuMixin, HasRecipesMenuMixin):

    usedfor = ITeam
    facet = 'overview'
    links = [
        'edit',
        'branding',
        'common_edithomepage',
        'members',
        'mugshots',
        'add_member',
        'proposed_members',
        'memberships',
        'received_invitations',
        'editemail',
        'configure_mailing_list',
        'moderate_mailing_list',
        'editlanguages',
        'map',
        'polls',
        'add_poll',
        'join',
        'leave',
        'add_my_teams',
        'reassign',
        'projects',
        'activate_ppa',
        'maintained',
        'ppa',
        'related_software_summary',
        'view_recipes',
        'subscriptions',
        'structural_subscriptions',
        ]


class TeamOverviewNavigationMenu(NavigationMenu, TeamMenuMixin):
    """A top-level menu for navigation within a Team."""

    usedfor = ITeam
    facet = 'overview'
    links = ['profile', 'polls', 'members', 'ppas']


class TeamMembershipView(LaunchpadView):
    """The view behind ITeam/+members."""

    @cachedproperty
    def label(self):
        return smartquote('Members of "%s"' % self.context.displayname)

    @cachedproperty
    def active_memberships(self):
        """Current members of the team."""
        return ActiveBatchNavigator(
            self.context.member_memberships, self.request)

    @cachedproperty
    def inactive_memberships(self):
        """Former members of the team."""
        return InactiveBatchNavigator(
            self.context.getInactiveMemberships(), self.request)

    @cachedproperty
    def invited_memberships(self):
        """Other teams invited to become members of this team."""
        return list(self.context.getInvitedMemberships())

    @cachedproperty
    def proposed_memberships(self):
        """Users who have requested to join this team."""
        return list(self.context.getProposedMemberships())

    @property
    def have_pending_members(self):
        return self.proposed_memberships or self.invited_memberships


class TeamIndexView(PersonIndexView, TeamJoinMixin):
    """The view class for the +index page.

    This class is needed, so an action menu that only applies to
    teams can be displayed without showing up on the person index page.
    """

    @property
    def super_teams(self):
        """Return only the super teams that the viewer is able to see."""
        return [
            team for team in self.context.super_teams
            if check_permission('launchpad.View', team)]

    @property
    def can_show_subteam_portlet(self):
        """Only show the subteam portlet if there is info to display.

        Either the team is a member of another team, or there are
        invitations to join a team, and the owner needs to see the
        link so that the invitation can be accepted.
        """
        try:
            return (len(self.super_teams) > 0
                    or (self.context.open_membership_invitations
                        and check_permission('launchpad.Edit', self.context)))
        except AttributeError, e:
            raise AssertionError(e)

    @property
    def visibility_info(self):
        if self.context.visibility == PersonVisibility.PRIVATE:
            return 'Private team'
        else:
            return 'Public team'

    @property
    def visibility_portlet_class(self):
        """The portlet class for team visibility."""
        if self.context.visibility == PersonVisibility.PUBLIC:
            return 'portlet'
        return 'portlet private'

    @property
    def add_member_step_title(self):
        """A string for setup_add_member_handler with escaped quotes."""
        vocabulary_registry = getVocabularyRegistry()
        vocabulary = vocabulary_registry.get(self.context, 'ValidTeamMember')
        return vocabulary.step_title.replace("'", "\\'").replace('"', '\\"')


class TeamJoinForm(Interface):
    """Schema for team join."""
    mailinglist_subscribe = Bool(
        title=_("Subscribe me to this team's mailing list"),
        required=True, default=True)


class TeamJoinView(LaunchpadFormView, TeamJoinMixin):
    """A view class for joining a team."""
    schema = TeamJoinForm

    @property
    def label(self):
        return 'Join ' + cgi.escape(self.context.displayname)

    page_title = label

    def setUpWidgets(self):
        super(TeamJoinView, self).setUpWidgets()
        if 'mailinglist_subscribe' in self.field_names:
            widget = self.widgets['mailinglist_subscribe']
            widget.setRenderedValue(self.user_wants_list_subscriptions)

    @property
    def field_names(self):
        """See `LaunchpadFormView`.

        If the user can subscribe to the mailing list then include the
        mailinglist subscription checkbox otherwise remove it.
        """
        if self.user_can_subscribe_to_list:
            return ['mailinglist_subscribe']
        else:
            return []

    @property
    def join_allowed(self):
        """Is the logged in user allowed to join this team?

        The answer is yes if this team's subscription policy is not RESTRICTED
        and this team's visibility is either None or PUBLIC.
        """
        # Joining a moderated team will put you on the proposed_members
        # list. If it is a private team, you are not allowed to view the
        # proposed_members attribute until you are an active member;
        # therefore, it would look like the join button is broken. Either
        # private teams should always have a restricted subscription policy,
        # or we need a more complicated permission model.
        if not (self.context.visibility is None
                or self.context.visibility == PersonVisibility.PUBLIC):
            return False

        restricted = TeamSubscriptionPolicy.RESTRICTED
        return self.context.subscriptionpolicy != restricted

    @property
    def user_can_request_to_join(self):
        """Can the logged in user request to join this team?

        The user can request if he's allowed to join this team and if he's
        not yet an active member of this team.
        """
        if not self.join_allowed:
            return False
        return not (self.user_is_active_member or
                    self.user_is_proposed_member)

    @property
    def user_wants_list_subscriptions(self):
        """Is the user interested in subscribing to mailing lists?"""
        return (self.user.mailing_list_auto_subscribe_policy !=
                MailingListAutoSubscribePolicy.NEVER)

    @property
    def team_is_moderated(self):
        """Is this team a moderated team?

        Return True if the team's subscription policy is MODERATED.
        """
        policy = self.context.subscriptionpolicy
        return policy == TeamSubscriptionPolicy.MODERATED

    @property
    def next_url(self):
        return canonical_url(self.context)

    @property
    def cancel_url(self):
        return canonical_url(self.context)

    @action(_("Join"), name="join")
    def action_save(self, action, data):
        response = self.request.response

        if self.user_can_request_to_join:
            # Shut off mailing list auto-subscription - we want direct
            # control over it.
            self.user.join(self.context, may_subscribe_to_list=False)

            if self.team_is_moderated:
                response.addInfoNotification(
                    _('Your request to join ${team} is awaiting '
                      'approval.',
                      mapping={'team': self.context.displayname}))
            else:
                response.addInfoNotification(
                    _('You have successfully joined ${team}.',
                      mapping={'team': self.context.displayname}))
            if data.get('mailinglist_subscribe', False):
                self._subscribeToList(response)

        else:
            response.addErrorNotification(
                _('You cannot join ${team}.',
                  mapping={'team': self.context.displayname}))

    def _subscribeToList(self, response):
        """Subscribe the user to the team's mailing list."""

        if self.user_can_subscribe_to_list:
            # 'user_can_subscribe_to_list' should have dealt with
            # all of the error cases.
            self.context.mailing_list.subscribe(self.user)

            if self.team_is_moderated:
                response.addInfoNotification(
                    _('Your mailing list subscription is '
                      'awaiting approval.'))
            else:
                response.addInfoNotification(
                    structured(
                        _("You have been subscribed to this "
                          "team&#x2019;s mailing list.")))
        else:
            # A catch-all case, perhaps from stale or mangled
            # form data.
            response.addErrorNotification(
                _('Mailing list subscription failed.'))


class TeamAddMyTeamsView(LaunchpadFormView):
    """Propose/add to this team any team that you're an administrator of."""

    page_title = 'Propose/add one of your teams to another one'
    custom_widget('teams', LabeledMultiCheckBoxWidget)

    def initialize(self):
        context = self.context
        if context.subscriptionpolicy == TeamSubscriptionPolicy.MODERATED:
            self.label = 'Propose these teams as members'
        else:
            self.label = 'Add these teams to %s' % context.displayname
        self.next_url = canonical_url(context)
        super(TeamAddMyTeamsView, self).initialize()

    def setUpFields(self):
        terms = []
        for team in self.candidate_teams:
            text = structured(
                '<a href="%s">%s</a>', canonical_url(team), team.displayname)
            terms.append(SimpleTerm(team, team.name, text))
        self.form_fields = FormFields(
            List(__name__='teams',
                 title=_(''),
                 value_type=Choice(vocabulary=SimpleVocabulary(terms)),
                 required=False),
            render_context=self.render_context)

    def setUpWidgets(self, context=None):
        super(TeamAddMyTeamsView, self).setUpWidgets(context)
        self.widgets['teams'].display_label = False

    @cachedproperty
    def candidate_teams(self):
        """Return the set of teams that can be added/proposed for the context.

        We return only teams that the user can administer, that aren't already
        a member in the context or that the context isn't a member of. (Of
        course, the context is also omitted.)
        """
        candidates = []
        for team in self.user.getAdministratedTeams():
            if team == self.context:
                continue
            elif team.visibility != PersonVisibility.PUBLIC:
                continue
            elif team in self.context.activemembers:
                # The team is already a member of the context object.
                continue
            elif self.context.hasParticipationEntryFor(team):
                # The context object is a member/submember of the team.
                continue
            candidates.append(team)
        return candidates

    @property
    def cancel_url(self):
        """The return URL."""
        return canonical_url(self.context)

    def validate(self, data):
        if len(data.get('teams', [])) == 0:
            self.setFieldError('teams',
                               'Please select the team(s) you want to be '
                               'member(s) of this team.')

    def hasCandidates(self, action):
        """Return whether the user has teams to propose."""
        return len(self.candidate_teams) > 0

    @action(_("Continue"), name="continue", condition=hasCandidates)
    def continue_action(self, action, data):
        """Make the selected teams join this team."""
        context = self.context
        is_admin = check_permission('launchpad.Admin', context)
        membership_set = getUtility(ITeamMembershipSet)
        proposed_team_names = []
        added_team_names = []
        accepted_invite_team_names = []
        membership_set = getUtility(ITeamMembershipSet)
        for team in data['teams']:
            membership = membership_set.getByPersonAndTeam(team, context)
            if (membership is not None
                and membership.status == TeamMembershipStatus.INVITED):
                team.acceptInvitationToBeMemberOf(
                    context,
                    'Accepted an already pending invitation while trying to '
                    'propose the team for membership.')
                accepted_invite_team_names.append(team.displayname)
            elif is_admin:
                context.addMember(team, reviewer=self.user)
                added_team_names.append(team.displayname)
            else:
                team.join(context, requester=self.user)
                membership = membership_set.getByPersonAndTeam(team, context)
                if membership.status == TeamMembershipStatus.PROPOSED:
                    proposed_team_names.append(team.displayname)
                elif membership.status == TeamMembershipStatus.APPROVED:
                    added_team_names.append(team.displayname)
                else:
                    raise AssertionError(
                        'Unexpected membership status (%s) for %s.'
                        % (membership.status.name, team.name))
        full_message = ''
        for team_names, message in (
            (proposed_team_names, 'proposed to this team.'),
            (added_team_names, 'added to this team.'),
            (accepted_invite_team_names,
             'added to this team because of an existing invite.'),
            ):
            if len(team_names) == 0:
                continue
            elif len(team_names) == 1:
                verb = 'has been'
                team_string = team_names[0]
            elif len(team_names) > 1:
                verb = 'have been'
                team_string = (
                    ', '.join(team_names[:-1]) + ' and ' + team_names[-1])
            full_message += '%s %s %s' % (team_string, verb, message)
        self.request.response.addInfoNotification(full_message)


class TeamLeaveView(LaunchpadFormView, TeamJoinMixin):
    schema = Interface

    @property
    def label(self):
        return 'Leave ' + cgi.escape(self.context.displayname)

    page_title = label

    @property
    def cancel_url(self):
        return canonical_url(self.context)

    next_url = cancel_url

    @action(_("Leave"), name="leave")
    def action_save(self, action, data):
        if self.user_can_request_to_leave:
            self.user.leave(self.context)


class TeamReassignmentView(ObjectReassignmentView):

    ownerOrMaintainerAttr = 'teamowner'
    schema = ITeamReassignment

    def __init__(self, context, request):
        super(TeamReassignmentView, self).__init__(context, request)
        self.callback = self._afterOwnerChange
        self.teamdisplayname = self.contextName
        self._next_url = canonical_url(self.context)

    def validateOwner(self, new_owner):
        """Display error if the owner is not valid.

        Called by ObjectReassignmentView.validate().
        """
        if self.context.inTeam(new_owner):
            path = self.context.findPathToTeam(new_owner)
            if len(path) == 1:
                relationship = 'a direct member'
                path_string = ''
            else:
                relationship = 'an indirect member'
                full_path = [self.context] + path
                path_string = '(%s)' % '&rArr;'.join(
                    team.displayname for team in full_path)
            error = structured(
                'Circular team memberships are not allowed. '
                '%(new)s cannot be the new team owner, since %(context)s '
                'is %(relationship)s of %(new)s. '
                '<span style="white-space: nowrap">%(path)s</span>'
                % dict(new=new_owner.displayname,
                        context=self.context.displayname,
                        relationship=relationship,
                        path=path_string))
            self.setFieldError(self.ownerOrMaintainerName, error)

    @property
    def contextName(self):
        return self.context.displayname

    @property
    def next_url(self):
        return self._next_url

    def _afterOwnerChange(self, team, oldOwner, newOwner):
        """Add the new and the old owners as administrators of the team.

        When a user creates a new team, he is added as an administrator of
        that team. To be consistent with this, we must make the new owner an
        administrator of the team. This rule is ignored only if the new owner
        is an inactive member of the team, as that means he's not interested
        in being a member. The same applies to the old owner.
        """
        # Both new and old owners won't be added as administrators of the team
        # only if they're inactive members. If they're either active or
        # proposed members they'll be made administrators of the team.
        if newOwner not in team.inactivemembers:
            team.addMember(
                newOwner, reviewer=oldOwner,
                status=TeamMembershipStatus.ADMIN, force_team_add=True)
        if oldOwner not in team.inactivemembers:
            team.addMember(
                oldOwner, reviewer=oldOwner,
                status=TeamMembershipStatus.ADMIN, force_team_add=True)

        # If the current logged in user cannot see the team anymore as a
        # result of the ownership change, we don't want them to get a nasty
        # error page. So we redirect to launchpad.net with a notification.
        clear_cache()
        if not check_permission('launchpad.LimitedView', team):
            self.request.response.addNotification(
                "The owner of team %s was successfully changed but you are "
                "now no longer authorised to view the team."
                    % self.teamdisplayname)
            self._next_url = canonical_url(self.user)


class ITeamIndexMenu(Interface):
    """A marker interface for the +index navigation menu."""


class ITeamEditMenu(Interface):
    """A marker interface for the edit navigation menu."""


class TeamNavigationMenuBase(NavigationMenu, TeamMenuMixin):

    @property
    def person(self):
        """Override CommonMenuLinks since the view is the context."""
        return self.context.context


class TeamIndexMenu(TeamNavigationMenuBase):
    """A menu for different aspects of editing a team."""

    usedfor = ITeamIndexMenu
    facet = 'overview'
    title = 'Change team'
    links = ('edit', 'delete', 'join', 'add_my_teams', 'leave')


class TeamEditMenu(TeamNavigationMenuBase):
    """A menu for different aspects of editing a team."""

    usedfor = ITeamEditMenu
    facet = 'overview'
    title = 'Change team'
    links = ('branding', 'common_edithomepage', 'editlanguages', 'reassign',
             'editemail')


class TeamMugshotView(LaunchpadView):
    """A view for the team mugshot (team photo) page"""

    label = "Member photos"
    batch_size = config.launchpad.mugshot_batch_size

    def initialize(self):
        """Cache images to avoid dying from a million cuts."""
        getUtility(IPersonSet).cacheBrandingForPeople(
            self.members.currentBatch())

    @cachedproperty
    def members(self):
        """Get a batch of all members in the team."""
        batch_nav = BatchNavigator(
            self.context.allmembers, self.request, size=self.batch_size)
        return batch_nav


classImplements(TeamIndexView, ITeamIndexMenu)
classImplements(TeamEditView, ITeamEditMenu)