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
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
|
# Copyright 2009-2010 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
# pylint: disable-msg=C0103,W0613,R0911,F0401
#
"""Implementation of the lp: htmlform: fmt: namespaces in TALES."""
__metaclass__ = type
import bisect
import cgi
from email.Utils import formatdate
import math
import os.path
import rfc822
import sys
from textwrap import dedent
import urllib
##import warnings
from datetime import datetime, timedelta
from lazr.enum import enumerated_type_registry
from lazr.uri import URI
from zope.interface import Interface, Attribute, implements
from zope.component import adapts, getUtility, queryAdapter, getMultiAdapter
from zope.app import zapi
from zope.publisher.browser import BrowserView
from zope.traversing.interfaces import (
ITraversable,
IPathAdapter,
TraversalError,
)
from zope.security.interfaces import Unauthorized
from zope.security.proxy import isinstance as zope_isinstance
from zope.schema import TextLine
import pytz
from z3c.ptcompat import ViewPageTemplateFile
from canonical.launchpad import _
from canonical.launchpad.interfaces.launchpad import (
IHasIcon, IHasLogo, IHasMugshot, IPrivacy)
from canonical.launchpad.layers import LaunchpadLayer
import canonical.launchpad.pagetitles
from canonical.launchpad.webapp import canonical_url, urlappend
from canonical.launchpad.webapp.authorization import check_permission
from canonical.launchpad.webapp.badge import IHasBadges
from canonical.launchpad.webapp.interfaces import (
IApplicationMenu, IContextMenu, IFacetMenu, ILaunchBag, INavigationMenu,
IPrimaryContext, NoCanonicalUrl)
from canonical.launchpad.webapp.menu import get_current_view, get_facet
from canonical.launchpad.webapp.publisher import (
get_current_browser_request, LaunchpadView, nearest)
from canonical.launchpad.webapp.session import get_cookie_domain
from canonical.lazr.canonicalurl import nearest_adapter
from lp.app.browser.stringformatter import escape, FormattersAPI
from lp.blueprints.interfaces.specification import ISpecification
from lp.blueprints.interfaces.sprint import ISprint
from lp.bugs.interfaces.bug import IBug
from lp.buildmaster.enums import BuildStatus
from lp.code.interfaces.branch import IBranch
from lp.soyuz.enums import ArchivePurpose
from lp.soyuz.interfaces.archive import IPPA
from lp.soyuz.interfaces.archivesubscriber import IArchiveSubscriberSet
from lp.soyuz.interfaces.binarypackagename import (
IBinaryAndSourcePackageName,
)
from lp.registry.interfaces.distribution import IDistribution
from lp.registry.interfaces.distributionsourcepackage import (
IDistributionSourcePackage,
)
from lp.registry.interfaces.person import IPerson
from lp.registry.interfaces.product import IProduct
from lp.registry.interfaces.projectgroup import IProjectGroup
SEPARATOR = ' : '
def format_link(obj, view_name=None, empty_value='None'):
"""Return the equivalent of obj/fmt:link as a string."""
if obj is None:
return empty_value
adapter = queryAdapter(obj, IPathAdapter, 'fmt')
link = getattr(adapter, 'link', None)
if link is None:
raise NotImplementedError("Missing link function on adapter.")
return link(view_name)
class MenuLinksDict(dict):
"""A dict class to construct menu links when asked for and not before.
We store all the information we need to construct the requested links,
including the menu object and request url.
"""
def __init__(self, menu, request_url, request):
self._request_url = request_url
self._menu = menu
self._all_link_names = []
self._extra_link_names = []
dict.__init__(self)
# The object has the facet, but does not have a menu, this
# is probably the overview menu with is the default facet.
if menu is None or getattr(menu, 'disabled', False):
return
menu.request = request
# We get all the possible link names for the menu.
# The link names are the defined menu links plus any extras.
self._all_link_names = list(menu.links)
extras = menu.extra_attributes
if extras is not None:
self._extra_link_names = list(extras)
self._all_link_names.extend(extras)
def __getitem__(self, link_name):
if not link_name in self._all_link_names:
raise KeyError(link_name)
link = dict.get(self, link_name, None)
if link is None:
if link_name in self._extra_link_names:
link = getattr(self._menu, link_name, None)
else:
link = self._menu.initLink(link_name, self._request_url)
if not link_name in self._extra_link_names:
self._menu.updateLink(link, self._request_url)
self[link_name] = link
return link
def __delitem__(self, key):
self._all_link_names.remove(key)
dict.__delitem__(self, key)
def items(self):
return zip(self._all_link_names, self.values())
def values(self):
return [self[key] for key in self._all_link_names]
def keys(self):
return self._all_link_names
def iterkeys(self):
return iter(self._all_link_names)
__iter__ = iterkeys
class MenuAPI:
"""Namespace to give access to the facet menus.
The facet menu can be accessed with an expression like:
tal:define="facetmenu view/menu:facet"
which gives the facet menu of the nearest object along the canonical url
chain that has an IFacetMenu adapter.
"""
def __init__(self, context):
self._tales_context = context
if zope_isinstance(context, (LaunchpadView, BrowserView)):
# The view is a LaunchpadView or a SimpleViewClass from a
# template. The facet is added to the call by the ZCML.
self.view = context
self._context = self.view.context
self._request = self.view.request
self._selectedfacetname = getattr(
self.view, '__launchpad_facetname__', None)
else:
self._context = context
self._request = get_current_browser_request()
self.view = None
self._selectedfacetname = None
def __getattribute__(self, facet):
"""Retrieve the links associated with a facet.
It's used with expressions like context/menu:bugs/subscribe.
:return: A dictionary mapping the link name to the associated Link
object.
:raise AttributeError: when there is no application menu for the
facet.
"""
# Use __getattribute__ instead of __getattr__, since __getattr__
# gets called if any of the other properties raise an AttributeError,
# which makes troubleshooting confusing. The has_facet can't easily
# be placed first, since all the properties it uses would need to
# be retrieved with object.__getattribute().
missing = object()
if (getattr(MenuAPI, facet, missing) is not missing
or facet in object.__getattribute__(self, '__dict__')):
return object.__getattribute__(self, facet)
has_facet = object.__getattribute__(self, '_has_facet')
if not has_facet(facet):
raise AttributeError(facet)
menu = queryAdapter(self._context, IApplicationMenu, facet)
if menu is None:
menu = queryAdapter(self._context, INavigationMenu, facet)
links = self._getMenuLinksAndAttributes(menu)
object.__setattr__(self, facet, links)
return links
def _getMenuLinksAndAttributes(self, menu):
"""Return a dict of the links and attributes of the menu."""
return MenuLinksDict(menu, self._request_url(), self._request)
def _has_facet(self, facet):
"""Does the object have the named facet?"""
menu = self._facet_menu()
if menu is None:
return False
return facet in menu.links
def _request_url(self):
request = self._request
if request is None:
return None
request_urlobj = URI(request.getURL())
# If the default view name is being used, we will want the url
# without the default view name.
defaultviewname = zapi.getDefaultViewName(self._context, request)
if request_urlobj.path.rstrip('/').endswith(defaultviewname):
request_urlobj = URI(request.getURL(1))
query = request.get('QUERY_STRING')
if query:
request_urlobj = request_urlobj.replace(query=query)
return request_urlobj
def facet(self):
"""Return the IFacetMenu links related to the context."""
menu = self._facet_menu()
if menu is None:
return []
menu.request = self._request
return list(menu.iterlinks(
request_url=self._request_url(),
selectedfacetname=self._selectedfacetname))
def _facet_menu(self):
"""Return the IFacetMenu related to the context."""
try:
try:
context = IPrimaryContext(self._context).context
except TypeError:
# Could not adapt raises a type error. If there was no
# way to adapt, then just use self._context.
context = self._context
menu = nearest_adapter(context, IFacetMenu)
except NoCanonicalUrl:
menu = None
return menu
def selectedfacetname(self):
if self._selectedfacetname is None:
return 'unknown'
else:
return self._selectedfacetname
@property
def context(self):
menu = IContextMenu(self._context, None)
return self._getMenuLinksAndAttributes(menu)
@property
def navigation(self):
"""Navigation menu links list."""
try:
# NavigationMenus may be associated with a content object or one
# of its views. The context we need is the one from the TAL
# expression.
context = self._tales_context
if self._selectedfacetname is not None:
selectedfacetname = self._selectedfacetname
else:
# XXX sinzui 2008-05-09 bug=226917: We should be retrieving
# the facet name from the layer implemented by the request.
view = get_current_view(self._request)
selectedfacetname = get_facet(view)
try:
menu = nearest_adapter(
context, INavigationMenu, name=selectedfacetname)
except NoCanonicalUrl:
menu = None
return self._getMenuLinksAndAttributes(menu)
except AttributeError, e:
# If this method gets an AttributeError, we rethrow it as a
# AssertionError. Otherwise, zope will hide the root cause
# of the error and just say that "navigation" can't be traversed.
new_exception = AssertionError(
'AttributError in MenuAPI.navigation: %s' % e)
# We cannot use parens around the arguments to `raise`,
# since that will cause it to ignore the third argument,
# which is the original traceback.
new_exception.addinfo(sys.exc_info()[2])
raise
class CountAPI:
"""Namespace to provide counting-related functions, such as length.
This is available for all objects. Individual operations may fail for
objects that do not support them.
"""
def __init__(self, context):
self._context = context
def len(self):
"""somelist/count:len gives you an int that is len(somelist)."""
return len(self._context)
class EnumValueAPI:
"""Namespace to test the value of an EnumeratedType Item.
The value is given in the next path step.
tal:condition="somevalue/enumvalue:BISCUITS"
Registered for canonical.lazr.enum.Item.
"""
implements(ITraversable)
def __init__(self, item):
self.item = item
def traverse(self, name, furtherPath):
if self.item.name == name:
return True
else:
# Check whether this was an allowed value for this
# enumerated type.
enum = self.item.enum
try:
enum.getTermByToken(name)
except LookupError:
raise TraversalError(
'The enumerated type %s does not have a value %s.' %
(enum.name, name))
return False
class HTMLFormAPI:
"""HTML form helper API, available as request/htmlform:.
Use like:
request/htmlform:fieldname/selected/literalvalue
if request.form[fieldname] == literalvalue:
return "selected"
else:
return None
"""
implements(ITraversable)
def __init__(self, request):
self.form = request.form
def traverse(self, name, furtherPath):
if len(furtherPath) == 1:
operation = furtherPath.pop()
return HTMLFormOperation(self.form.get(name), operation)
else:
operation = furtherPath.pop()
value = furtherPath.pop()
if htmlmatch(self.form.get(name), value):
return operation
else:
return None
def htmlmatch(formvalue, value):
value = str(value)
if isinstance(formvalue, list):
return value in formvalue
else:
return formvalue == value
class HTMLFormOperation:
implements(ITraversable)
def __init__(self, formvalue, operation):
self.formvalue = formvalue
self.operation = operation
def traverse(self, name, furtherPath):
if htmlmatch(self.formvalue, name):
return self.operation
else:
return None
class IRequestAPI(Interface):
"""Launchpad lp:... API available for an IApplicationRequest."""
person = Attribute("The IPerson for the request's principal.")
cookie_scope = Attribute("The scope parameters for cookies.")
class RequestAPI:
"""Adapter from IApplicationRequest to IRequestAPI."""
implements(IRequestAPI)
def __init__(self, request):
self.request = request
@property
def person(self):
return IPerson(self.request.principal, None)
@property
def cookie_scope(self):
params = '; Path=/'
uri = URI(self.request.getURL())
if uri.scheme == 'https':
params += '; Secure'
domain = get_cookie_domain(uri.host)
if domain is not None:
params += '; Domain=%s' % domain
return params
class DBSchemaAPI:
"""Adapter from integers to things that can extract information from
DBSchemas.
"""
implements(ITraversable)
def __init__(self, number):
self._number = number
def traverse(self, name, furtherPath):
if name in enumerated_type_registry:
enum = enumerated_type_registry[name]
return enum.items[self._number].title
else:
raise TraversalError(name)
class NoneFormatter:
"""Adapter from None to various string formats.
In general, these will return an empty string. They are provided for ease
of handling NULL values from the database, which become None values for
attributes in content classes.
"""
implements(ITraversable)
allowed_names = set([
'approximatedate',
'approximateduration',
'break-long-words',
'date',
'datetime',
'displaydate',
'isodate',
'email-to-html',
'exactduration',
'lower',
'nice_pre',
'nl_to_br',
'pagetitle',
'rfc822utcdatetime',
'text-to-html',
'time',
'url',
'link',
])
def __init__(self, context):
self.context = context
def traverse(self, name, furtherPath):
if name == 'shorten':
if not len(furtherPath):
raise TraversalError(
"you need to traverse a number after fmt:shorten")
# Remove the maxlength from the path as it is a parameter
# and not another traversal command.
furtherPath.pop()
return ''
# We need to check to see if the name has been augmented with optional
# evaluation parameters, delimited by ":". These parameters are:
# param1 = rootsite (used with link and url)
# param2 = default value (in case of context being None)
# We are interested in the default value (param2).
result = ''
for nm in self.allowed_names:
if name.startswith(nm + ":"):
name_parts = name.split(":")
name = name_parts[0]
if len(name_parts) > 2:
result = name_parts[2]
break
if name in self.allowed_names:
return result
else:
raise TraversalError(name)
class ObjectFormatterAPI:
"""Adapter for any object to a formatted string."""
implements(ITraversable)
# Although we avoid mutables as class attributes, the two ones below are
# constants, so it's not a problem. We might want to use something like
# frozenset (http://code.activestate.com/recipes/414283/) here, though.
# The names which can be traversed further (e.g context/fmt:url/+edit).
traversable_names = {
'api_url': 'api_url',
'link': 'link',
'url': 'url',
}
# Names which are allowed but can't be traversed further.
final_traversable_names = {
'pagetitle': 'pagetitle',
'public-private-css': 'public_private_css',
}
def __init__(self, context):
self._context = context
def url(self, view_name=None, rootsite=None):
"""Return the object's canonical URL.
:param view_name: If not None, return the URL to the page with that
name on this object.
:param rootsite: If not None, return the URL to the page on the
specified rootsite. Note this is available only for subclasses
that allow specifying the rootsite.
"""
try:
url = canonical_url(
self._context, path_only_if_possible=True,
rootsite=rootsite, view_name=view_name)
except Unauthorized:
url = ""
return url
def api_url(self, context):
"""Return the object's (partial) canonical web service URL.
This method returns everything that goes after the web service version
number. Effectively the canonical URL but only the relative part with
no site.
"""
try:
url = canonical_url(self._context, force_local_path=True)
except Unauthorized:
url = ""
return url
def traverse(self, name, furtherPath):
"""Traverse the specified path, processing any optional parameters.
Up to 2 parameters are currently supported, and the path name will be
of the form:
name:param1:param2
where
param1 = rootsite (only used for link and url paths).
param2 = default (used when self.context is None). The context
is not None here so this parameter is ignored.
"""
if name.startswith('link:') or name.startswith('url:'):
name_parts = name.split(':')
name = name_parts[0]
rootsite = name_parts[1]
if rootsite != '':
extra_path = None
if len(furtherPath) > 0:
extra_path = '/'.join(reversed(furtherPath))
# Remove remaining entries in furtherPath so that traversal
# stops here.
del furtherPath[:]
if name == 'link':
if rootsite is None:
return self.link(extra_path)
else:
return self.link(extra_path, rootsite=rootsite)
else:
if rootsite is None:
self.url(extra_path)
else:
return self.url(extra_path, rootsite=rootsite)
if '::' in name:
name = name.split(':')[0]
if name in self.traversable_names:
if len(furtherPath) >= 1:
extra_path = '/'.join(reversed(furtherPath))
del furtherPath[:]
else:
extra_path = None
method_name = self.traversable_names[name]
return getattr(self, method_name)(extra_path)
elif name in self.final_traversable_names:
method_name = self.final_traversable_names[name]
return getattr(self, method_name)()
else:
raise TraversalError(name)
def link(self, view_name, rootsite=None):
"""Return an HTML link to the object's page.
The link consists of an icon followed by the object's name.
:param view_name: If not None, the link will point to the page with
that name on this object.
:param rootsite: If not None, return the URL to the page on the
specified rootsite. Note this is available only for subclasses
that allow specifying the rootsite.
"""
raise NotImplementedError(
"No link implementation for %r, IPathAdapter implementation "
"for %r." % (self, self._context))
def public_private_css(self):
"""Return the CSS class that represents the object's privacy."""
privacy = IPrivacy(self._context, None)
if privacy is not None and privacy.private:
return 'private'
else:
return 'public'
def pagetitle(self):
"""The page title to be used.
By default, reverse breadcrumbs are always used if they are available.
If not available, then the view's .page_title attribute or entry in
pagetitles.py (deprecated) is used. If breadcrumbs are available,
then a view can still choose to override them by setting the attribute
.override_title_breadcrumbs to True.
"""
view = self._context
request = get_current_browser_request()
module = canonical.launchpad.pagetitles
hierarchy_view = getMultiAdapter(
(view.context, request), name='+hierarchy')
override = getattr(view, 'override_title_breadcrumbs', False)
if (override or
hierarchy_view is None or
not hierarchy_view.display_breadcrumbs):
# The breadcrumbs are either not available or are overridden. If
# the view has a .page_title attribute use that.
page_title = getattr(view, 'page_title', None)
if page_title is not None:
return page_title
# If there is no template for the view, just use the default
# Launchpad title.
template = getattr(view, 'template', None)
if template is None:
template = getattr(view, 'index', None)
if template is None:
return module.DEFAULT_LAUNCHPAD_TITLE
# There is no .page_title attribute on the view, so fallback to
# looking for an an entry in pagetitles.py. This is deprecated
# though, so issue a warning.
filename = os.path.basename(template.filename)
name, ext = os.path.splitext(filename)
title_name = name.replace('-', '_')
title_object = getattr(module, title_name, None)
# Page titles are mandatory.
assert title_object is not None, (
'No .page_title or pagetitles.py found for %s'
% template.filename)
## 2009-09-08 BarryWarsaw bug 426527: Enable this when we want to
## force conversions from pagetitles.py; however tests will fail
## because of this output.
## warnings.warn('Old style pagetitles.py entry found for %s. '
## 'Switch to using a .page_title attribute on the '
## 'view instead.' % template.filename,
## DeprecationWarning)
if isinstance(title_object, basestring):
return title_object
else:
title = title_object(view.context, view)
if title is None:
return module.DEFAULT_LAUNCHPAD_TITLE
else:
return title
# Use the reverse breadcrumbs.
return SEPARATOR.join(
breadcrumb.text for breadcrumb
in reversed(hierarchy_view.items))
class ObjectImageDisplayAPI:
"""Base class for producing the HTML that presents objects
as an icon, a logo, a mugshot or a set of badges.
"""
def __init__(self, context):
self._context = context
#def default_icon_resource(self, context):
def sprite_css(self):
"""Return the CSS class for the sprite"""
# XXX: mars 2008-08-22 bug=260468
# This should be refactored. We shouldn't have to do type-checking
# using interfaces.
context = self._context
if IProduct.providedBy(context):
return 'sprite product'
elif IProjectGroup.providedBy(context):
return 'sprite project'
elif IPerson.providedBy(context):
if context.isTeam():
return 'sprite team'
else:
if context.is_valid_person:
return 'sprite person'
else:
return 'sprite person-inactive'
elif IDistribution.providedBy(context):
return 'sprite distribution'
elif IDistributionSourcePackage.providedBy(context):
return 'sprite package-source'
elif ISprint.providedBy(context):
return 'sprite meeting'
elif IBug.providedBy(context):
return 'sprite bug'
elif IPPA.providedBy(context):
if context.enabled:
return 'sprite ppa-icon'
else:
return 'sprite ppa-icon-inactive'
elif IBranch.providedBy(context):
return 'sprite branch'
elif ISpecification.providedBy(context):
return 'sprite blueprint'
elif IBinaryAndSourcePackageName.providedBy(context):
return 'sprite package-source'
return None
def default_logo_resource(self, context):
# XXX: mars 2008-08-22 bug=260468
# This should be refactored. We shouldn't have to do type-checking
# using interfaces.
if IProjectGroup.providedBy(context):
return '/@@/project-logo'
elif IPerson.providedBy(context):
if context.isTeam():
return '/@@/team-logo'
else:
if context.is_valid_person:
return '/@@/person-logo'
else:
return '/@@/person-inactive-logo'
elif IProduct.providedBy(context):
return '/@@/product-logo'
elif IDistribution.providedBy(context):
return '/@@/distribution-logo'
elif ISprint.providedBy(context):
return '/@@/meeting-logo'
return None
def default_mugshot_resource(self, context):
# XXX: mars 2008-08-22 bug=260468
# This should be refactored. We shouldn't have to do type-checking
# using interfaces.
if IProjectGroup.providedBy(context):
return '/@@/project-mugshot'
elif IPerson.providedBy(context):
if context.isTeam():
return '/@@/team-mugshot'
else:
if context.is_valid_person:
return '/@@/person-mugshot'
else:
return '/@@/person-inactive-mugshot'
elif IProduct.providedBy(context):
return '/@@/product-mugshot'
elif IDistribution.providedBy(context):
return '/@@/distribution-mugshot'
elif ISprint.providedBy(context):
return '/@@/meeting-mugshot'
return None
def _get_custom_icon_url(self):
"""Return the URL for this object's icon."""
context = self._context
if IHasIcon.providedBy(context) and context.icon is not None:
icon_url = context.icon.getURL()
return icon_url
elif context is None:
return ''
else:
return None
def icon(self):
#XXX: this should go away as soon as all image:icon where replaced
return None
def logo(self):
"""Return the appropriate <img> tag for this object's logo.
:return: A string, or None if the context object doesn't have
a logo.
"""
context = self._context
if not IHasLogo.providedBy(context):
context = nearest(context, IHasLogo)
if context is None:
# we use the Launchpad logo for anything which is in no way
# related to a Pillar (for example, a buildfarm)
url = '/@@/launchpad-logo'
elif context.logo is not None:
url = context.logo.getURL()
else:
url = self.default_logo_resource(context)
if url is None:
# We want to indicate that there is no logo for this
# object.
return None
logo = '<img alt="" width="64" height="64" src="%s" />'
return logo % url
def mugshot(self):
"""Return the appropriate <img> tag for this object's mugshot.
:return: A string, or None if the context object doesn't have
a mugshot.
"""
context = self._context
assert IHasMugshot.providedBy(context), 'No Mugshot for this item'
if context.mugshot is not None:
url = context.mugshot.getURL()
else:
url = self.default_mugshot_resource(context)
if url is None:
# We want to indicate that there is no mugshot for this
# object.
return None
mugshot = """<img alt="" class="mugshot"
width="192" height="192" src="%s" />"""
return mugshot % url
def badges(self):
raise NotImplementedError(
"Badge display not implemented for this item")
def boolean(self):
"""Return an icon representing the context as a boolean value."""
if bool(self._context):
icon = 'yes'
else:
icon = 'no'
markup = (
'<span class="sprite %(icon)s"> '
'<span class="invisible-link">%(icon)s</span></span>')
return markup % dict(icon=icon)
class BugTaskImageDisplayAPI(ObjectImageDisplayAPI):
"""Adapter for IBugTask objects to a formatted string. This inherits
from the generic ObjectImageDisplayAPI and overrides the icon
presentation method.
Used for image:icon.
"""
implements(ITraversable)
allowed_names = set([
'icon',
'logo',
'mugshot',
'badges',
'sprite_css',
])
icon_template = (
'<span alt="%s" title="%s" class="%s"> </span>')
linked_icon_template = (
'<a href="%s" alt="%s" title="%s" class="%s"></a>')
def traverse(self, name, furtherPath):
"""Special-case traversal for icons with an optional rootsite."""
if name in self.allowed_names:
return getattr(self, name)()
else:
raise TraversalError(name)
def sprite_css(self):
"""Return the CSS class for the sprite"""
if self._context.importance:
importance = self._context.importance.title.lower()
return "sprite bug-%s" % importance
else:
return "sprite bug"
def icon(self):
"""Display the icon dependent on the IBugTask.importance."""
if self._context.importance:
importance = self._context.importance.title.lower()
alt = "(%s)" % importance
title = importance.capitalize()
if importance not in ("undecided", "wishlist"):
# The other status names do not make a lot of sense on
# their own, so tack on a noun here.
title += " importance"
css = "sprite bug-%s" % importance
else:
alt = ""
title = ""
css = self.sprite_css()
return self.icon_template % (alt, title, css)
def _hasBugBranch(self):
"""Return whether the bug has a branch linked to it."""
return self._context.bug.linked_branches.count() > 0
def _hasSpecification(self):
"""Return whether the bug is linked to a specification."""
return self._context.bug.specifications.count() > 0
def _hasPatch(self):
"""Return whether the bug has a patch."""
return self._context.bug.has_patches
def badges(self):
badges = []
if self._context.bug.private:
badges.append(self.icon_template % (
"private", "Private", "sprite private"))
if self._hasBugBranch():
badges.append(self.icon_template % (
"branch", "Branch exists", "sprite branch"))
if self._hasSpecification():
badges.append(self.icon_template % (
"blueprint", "Related to a blueprint", "sprite blueprint"))
if self._context.milestone:
milestone_text = "milestone %s" % self._context.milestone.name
badges.append(self.linked_icon_template % (
canonical_url(self._context.milestone),
milestone_text, "Linked to %s" % milestone_text,
"sprite milestone"))
if self._hasPatch():
badges.append(self.icon_template % (
"haspatch", "Has a patch", "sprite haspatch-icon"))
# Join with spaces to avoid the icons smashing into each other
# when multiple ones are presented.
return " ".join(badges)
class BugTaskListingItemImageDisplayAPI(BugTaskImageDisplayAPI):
"""Formatter for image:badges for BugTaskListingItem.
The BugTaskListingItem has some attributes to decide whether a badge
should be displayed, which don't require a DB query when they are
accessed.
"""
def _hasBugBranch(self):
"""See `BugTaskImageDisplayAPI`"""
return self._context.has_bug_branch
def _hasSpecification(self):
"""See `BugTaskImageDisplayAPI`"""
return self._context.has_specification
def _hasPatch(self):
"""See `BugTaskImageDisplayAPI`"""
return self._context.has_patch
class QuestionImageDisplayAPI(ObjectImageDisplayAPI):
"""Adapter for IQuestion to a formatted string. Used for image:icon."""
def sprite_css(self):
return "sprite question"
class SpecificationImageDisplayAPI(ObjectImageDisplayAPI):
"""Adapter for ISpecification objects to a formatted string. This inherits
from the generic ObjectImageDisplayAPI and overrides the icon
presentation method.
Used for image:icon.
"""
icon_template = (
'<span alt="%s" title="%s" class="%s" />')
def sprite_css(self):
"""Return the CSS class for the sprite"""
if self._context.priority:
priority = self._context.priority.title.lower()
return "sprite blueprint-%s" % priority
else:
return "sprite blueprint"
def badges(self):
badges = ''
if self._context.linked_branches.count() > 0:
badges += self.icon_template % (
"branch", "Branch is available", "sprite branch")
if self._context.informational:
badges += self.icon_template % (
"informational", "Blueprint is purely informational",
"sprite info")
return badges
class KarmaCategoryImageDisplayAPI(ObjectImageDisplayAPI):
"""Adapter for IKarmaCategory objects to an image.
Used for image:icon.
"""
icons_for_karma_categories = {
'bugs': '/@@/bug',
'code': '/@@/branch',
'translations': '/@@/translation',
'specs': '/@@/blueprint',
'soyuz': '/@@/package-source',
'answers': '/@@/question'}
def icon(self):
icon = self.icons_for_karma_categories[self._context.name]
return ('<img height="14" width="14" alt="" title="%s" src="%s" />'
% (self._context.title, icon))
class MilestoneImageDisplayAPI(ObjectImageDisplayAPI):
"""Adapter for IMilestone objects to an image.
Used for image:icon.
"""
def icon(self):
"""Return the appropriate <img> tag for the milestone icon."""
return '<img height="14" width="14" alt="" src="/@@/milestone" />'
class BuildImageDisplayAPI(ObjectImageDisplayAPI):
"""Adapter for IBuild objects to an image.
Used for image:icon.
"""
icon_template = (
'<img width="%(width)s" height="14" alt="%(alt)s" '
'title="%(title)s" src="%(src)s" />')
def icon(self):
"""Return the appropriate <img> tag for the build icon."""
icon_map = {
BuildStatus.NEEDSBUILD: {'src': "/@@/build-needed"},
BuildStatus.FULLYBUILT: {'src': "/@@/build-success"},
BuildStatus.FAILEDTOBUILD: {
'src': "/@@/build-failed",
'width': '16',
},
BuildStatus.MANUALDEPWAIT: {'src': "/@@/build-depwait"},
BuildStatus.CHROOTWAIT: {'src': "/@@/build-chrootwait"},
BuildStatus.SUPERSEDED: {'src': "/@@/build-superseded"},
BuildStatus.BUILDING: {'src': "/@@/processing"},
BuildStatus.UPLOADING: {'src': "/@@/processing"},
BuildStatus.FAILEDTOUPLOAD: {'src': "/@@/build-failedtoupload"},
}
alt = '[%s]' % self._context.status.name
title = self._context.status.title
source = icon_map[self._context.status].get('src')
width = icon_map[self._context.status].get('width', '14')
return self.icon_template % {
'alt': alt,
'title': title,
'src': source,
'width': width,
}
class ArchiveImageDisplayAPI(ObjectImageDisplayAPI):
"""Adapter for IArchive objects to an image.
Used for image:icon.
"""
icon_template = """
<img width="14" height="14" alt="%s" title="%s" src="%s" />
"""
def icon(self):
"""Return the appropriate <img> tag for an archive."""
icon_map = {
ArchivePurpose.PRIMARY: '/@@/distribution',
ArchivePurpose.PARTNER: '/@@/distribution',
ArchivePurpose.PPA: '/@@/ppa-icon',
ArchivePurpose.COPY: '/@@/distribution',
ArchivePurpose.DEBUG: '/@@/distribution',
}
alt = '[%s]' % self._context.purpose.title
title = self._context.purpose.title
source = icon_map[self._context.purpose]
return self.icon_template % (alt, title, source)
class BadgeDisplayAPI:
"""Adapter for IHasBadges to the images for the badges.
Used for context/badges:small and context/badges:large.
"""
def __init__(self, context):
# Adapt the context.
self.context = IHasBadges(context)
def small(self):
"""Render the visible badge's icon images."""
badges = self.context.getVisibleBadges()
return ''.join([badge.renderIconImage() for badge in badges])
def large(self):
"""Render the visible badge's heading images."""
badges = self.context.getVisibleBadges()
return ''.join([badge.renderHeadingImage() for badge in badges])
class PersonFormatterAPI(ObjectFormatterAPI):
"""Adapter for `IPerson` objects to a formatted string."""
traversable_names = {'link': 'link', 'url': 'url', 'api_url': 'api_url',
'icon': 'icon',
'displayname': 'displayname',
'unique_displayname': 'unique_displayname',
'link-display-name-id': 'link_display_name_id',
}
final_traversable_names = {'local-time': 'local_time'}
final_traversable_names.update(ObjectFormatterAPI.final_traversable_names)
def local_time(self):
"""Return the local time for this person."""
time_zone = 'UTC'
if self._context.time_zone is not None:
time_zone = self._context.time_zone
return datetime.now(pytz.timezone(time_zone)).strftime('%T %Z')
def url(self, view_name=None, rootsite='mainsite'):
"""See `ObjectFormatterAPI`.
The default URL for a person is to the mainsite.
"""
return super(PersonFormatterAPI, self).url(view_name, rootsite)
def _makeLink(self, view_name, rootsite, text):
person = self._context
url = self.url(view_name, rootsite)
custom_icon = ObjectImageDisplayAPI(person)._get_custom_icon_url()
if custom_icon is None:
css_class = ObjectImageDisplayAPI(person).sprite_css()
return (u'<a href="%s" class="%s">%s</a>') % (
url, css_class, cgi.escape(text))
else:
return (u'<a href="%s" class="bg-image" '
'style="background-image: url(%s)">%s</a>') % (
url, custom_icon, cgi.escape(text))
def link(self, view_name, rootsite='mainsite'):
"""See `ObjectFormatterAPI`.
Return an HTML link to the person's page containing an icon
followed by the person's name. The default URL for a person is to
the mainsite.
"""
return self._makeLink(view_name, rootsite, self._context.displayname)
def displayname(self, view_name, rootsite=None):
"""Return the displayname as a string."""
person = self._context
return person.displayname
def unique_displayname(self, view_name):
"""Return the unique_displayname as a string."""
person = self._context
return person.unique_displayname
def icon(self, view_name):
"""Return the URL for the person's icon."""
custom_icon = ObjectImageDisplayAPI(
self._context)._get_custom_icon_url()
if custom_icon is None:
css_class = ObjectImageDisplayAPI(self._context).sprite_css()
return '<span class="' + css_class + '"></span>'
else:
return '<img src="%s" width="14" height="14" />' % custom_icon
def link_display_name_id(self, view_name):
"""Return a link to the user's profile page.
The link text uses both the display name and Launchpad id to clearly
indicate which user profile is linked.
"""
from lp.services.features import getFeatureFlag
if bool(getFeatureFlag('disclosure.picker_enhancements.enabled')):
text = self.unique_displayname(None)
# XXX sinzui 2011-05-31: Remove this next line when the feature
# flag is removed.
view_name = None
elif view_name == 'id-only':
# XXX sinzui 2011-05-31: remove this block and /id-only from
# launchpad-loginstatus.pt whwn the feature flag is removed.
text = self._context.name
view_name = None
else:
text = self._context.displayname
return self._makeLink(view_name, 'mainsite', text)
class TeamFormatterAPI(PersonFormatterAPI):
"""Adapter for `ITeam` objects to a formatted string."""
hidden = u'<hidden>'
def url(self, view_name=None, rootsite='mainsite'):
"""See `ObjectFormatterAPI`.
The default URL for a team is to the mainsite. None is returned
when the user does not have permission to review the team.
"""
if not check_permission('launchpad.View', self._context):
# This person has no permission to view the team details.
return None
return super(TeamFormatterAPI, self).url(view_name, rootsite)
def api_url(self, context):
"""See `ObjectFormatterAPI`."""
if not check_permission('launchpad.View', self._context):
# This person has no permission to view the team details.
return None
return super(TeamFormatterAPI, self).api_url(context)
def link(self, view_name, rootsite='mainsite'):
"""See `ObjectFormatterAPI`.
The default URL for a team is to the mainsite. None is returned
when the user does not have permission to review the team.
"""
person = self._context
if not check_permission('launchpad.View', person):
# This person has no permission to view the team details.
return '<span class="sprite team">%s</span>' % cgi.escape(
self.hidden)
return super(TeamFormatterAPI, self).link(view_name, rootsite)
def displayname(self, view_name, rootsite=None):
"""See `PersonFormatterAPI`."""
person = self._context
if not check_permission('launchpad.View', person):
# This person has no permission to view the team details.
return self.hidden
return super(TeamFormatterAPI, self).displayname(view_name, rootsite)
def unique_displayname(self, view_name):
"""See `PersonFormatterAPI`."""
person = self._context
if not check_permission('launchpad.View', person):
# This person has no permission to view the team details.
return self.hidden
return super(TeamFormatterAPI, self).unique_displayname(view_name)
class CustomizableFormatter(ObjectFormatterAPI):
"""A ObjectFormatterAPI that is easy to customize.
This provides fmt:url and fmt:link support for the object it
adapts.
For most object types, only the _link_summary_template class
variable and _link_summary_values method need to be overridden.
This assumes that:
1. canonical_url produces appropriate urls for this type,
2. the launchpad.View permission alone is required to view this
object's url, and,
3. if there is an icon for this object type, image:icon is
implemented and appropriate.
For greater control over the summary, overrride
_make_link_summary.
If a different permission is required, override _link_permission.
"""
_link_permission = 'launchpad.View'
def _link_summary_values(self):
"""Return a dict of values to use for template substitution.
These values should not be escaped, as this will be performed later.
For this reason, only string values should be supplied.
"""
raise NotImplementedError(self._link_summary_values)
def _make_link_summary(self):
"""Create a summary from _template and _link_summary_values().
This summary is for use in fmt:link, which is meant to be used in
contexts like lists of items.
"""
values = {}
for key, value in self._link_summary_values().iteritems():
if value is None:
values[key] = ''
else:
values[key] = cgi.escape(value)
return self._link_summary_template % values
def _title_values(self):
"""Return a dict of values to use for template substitution.
These values should not be escaped, as this will be performed later.
For this reason, only string values should be supplied.
"""
return {}
def _make_title(self):
"""Create a title from _title_template and _title_values().
This title is for use in fmt:link, which is meant to be used in
contexts like lists of items.
"""
title_template = getattr(self, '_title_template', None)
if title_template is None:
return None
values = {}
for key, value in self._title_values().iteritems():
if value is None:
values[key] = ''
else:
values[key] = cgi.escape(value)
return title_template % values
def sprite_css(self):
"""Retrieve the icon for the _context, if any.
:return: The icon css or None if no icon is available.
"""
return queryAdapter(self._context, IPathAdapter, 'image').sprite_css()
def link(self, view_name, rootsite=None):
"""Return html including a link, description and icon.
Icon and link are optional, depending on type and permissions.
Uses self._make_link_summary for the summary, self._get_icon
for the icon, self._should_link to determine whether to link, and
self.url() to generate the url.
"""
sprite = self.sprite_css()
if sprite is None:
css = ''
else:
css = ' class="' + sprite + '"'
summary = self._make_link_summary()
title = self._make_title()
if title is None:
title = ''
else:
title = ' title="%s"' % title
if check_permission(self._link_permission, self._context):
url = self.url(view_name, rootsite)
else:
url = ''
if url:
return '<a href="%s"%s%s>%s</a>' % (url, css, title, summary)
else:
return summary
class PillarFormatterAPI(CustomizableFormatter):
"""Adapter for IProduct, IDistribution and IProjectGroup objects to a
formatted string."""
_link_summary_template = '%(displayname)s'
_link_permission = 'zope.Public'
def _link_summary_values(self):
displayname = self._context.displayname
return {'displayname': displayname}
def url(self, view_name=None, rootsite=None):
"""See `ObjectFormatterAPI`.
The default URL for a pillar is to the mainsite.
"""
return super(PillarFormatterAPI, self).url(view_name, rootsite)
def link(self, view_name, rootsite='mainsite'):
"""The html to show a link to a Product, ProjectGroup or distribution.
In the case of Products or ProjectGroups we display the custom
icon, if one exists. The default URL for a pillar is to the mainsite.
"""
html = super(PillarFormatterAPI, self).link(view_name)
context = self._context
custom_icon = ObjectImageDisplayAPI(
context)._get_custom_icon_url()
url = self.url(view_name, rootsite)
summary = self._make_link_summary()
if custom_icon is None:
css_class = ObjectImageDisplayAPI(context).sprite_css()
html = (u'<a href="%s" class="%s">%s</a>') % (
url, css_class, summary)
else:
html = (u'<a href="%s" class="bg-image" '
'style="background-image: url(%s)">%s</a>') % (
url, custom_icon, summary)
return html
class DistroSeriesFormatterAPI(CustomizableFormatter):
"""Adapter for IDistroSeries objects to a formatted string."""
_link_summary_template = '%(displayname)s'
_link_permission = 'zope.Public'
def _link_summary_values(self):
displayname = self._context.displayname
return {'displayname': displayname}
class SourcePackageReleaseFormatterAPI(CustomizableFormatter):
"""Adapter for ISourcePackageRelease objects to a formatted string."""
_link_summary_template = '%(sourcepackage)s %(version)s'
def _link_summary_values(self):
return {'sourcepackage':
self._context.distrosourcepackage.displayname,
'version': self._context.version}
class ProductReleaseFileFormatterAPI(ObjectFormatterAPI):
"""Adapter for `IProductReleaseFile` objects to a formatted string."""
traversable_names = {'link': 'link', 'url': 'url'}
def link(self, view_name):
"""A hyperlinked ProductReleaseFile.
This consists of a download icon, the link to the ProductReleaseFile
itself (with a tooltip stating its size) and links to that file's
signature and MD5 hash.
"""
file_ = self._context
file_size = NumberFormatterAPI(
file_.libraryfile.content.filesize).bytes()
if file_.description is not None:
description = cgi.escape(file_.description)
else:
description = file_.libraryfile.filename
link_title = "%s (%s)" % (description, file_size)
download_url = self._getDownloadURL(file_.libraryfile)
md5_url = urlappend(download_url, '+md5')
replacements = dict(
url=download_url, filename=file_.libraryfile.filename,
md5_url=md5_url, link_title=link_title)
html = (
'<img alt="download icon" src="/@@/download" />'
'<strong>'
' <a title="%(link_title)s" href="%(url)s">%(filename)s</a> '
'</strong>'
'(<a href="%(md5_url)s">md5</a>')
if file_.signature is not None:
html += ', <a href="%(signature_url)s">sig</a>)'
replacements['signature_url'] = self._getDownloadURL(
file_.signature)
else:
html += ')'
return html % replacements
def url(self, view_name=None, rootsite=None):
"""Return the URL to download the file."""
return self._getDownloadURL(self._context.libraryfile)
@property
def _release(self):
return self._context.productrelease
def _getDownloadURL(self, lfa):
"""Return the download URL for the given `LibraryFileAlias`."""
url = urlappend(canonical_url(self._release), '+download')
# Quote the filename to eliminate non-ascii characters which
# are invalid in the url.
url = urlappend(url, urllib.quote(lfa.filename.encode('utf-8')))
return str(URI(url).replace(scheme='http'))
class BranchFormatterAPI(ObjectFormatterAPI):
"""Adapter for IBranch objects to a formatted string."""
traversable_names = {
'link': 'link', 'url': 'url', 'project-link': 'projectLink',
'title-link': 'titleLink', 'bzr-link': 'bzrLink',
'api_url': 'api_url'}
def _args(self, view_name):
"""Generate a dict of attributes for string template expansion."""
branch = self._context
return {
'bzr_identity': branch.bzr_identity,
'display_name': cgi.escape(branch.displayname),
'name': branch.name,
'unique_name': branch.unique_name,
'url': self.url(view_name),
}
def link(self, view_name):
"""A hyperlinked branch icon with the displayname."""
return (
'<a href="%(url)s" class="sprite branch">'
'%(display_name)s</a>' % self._args(view_name))
def bzrLink(self, view_name):
"""A hyperlinked branch icon with the bazaar identity."""
# Defer to link.
return self.link(view_name)
def projectLink(self, view_name):
"""A hyperlinked branch icon with the name and title."""
return (
'<a href="%(url)s" title="%(display_name)s">'
'<img src="/@@/branch" alt=""/>'
' %(name)s</a>: %(title)s' % self._args(view_name))
def titleLink(self, view_name):
"""A hyperlinked branch name with following title."""
return (
'<a href="%(url)s" title="%(display_name)s">'
'%(name)s</a>: %(title)s' % self._args(view_name))
class BranchSubscriptionFormatterAPI(CustomizableFormatter):
"""Adapter for IBranchSubscription objects to a formatted string."""
_link_summary_template = _('Subscription of %(person)s to %(branch)s')
def _link_summary_values(self):
"""Provide values for template substitution"""
return {
'person': self._context.person.displayname,
'branch': self._context.branch.displayname,
}
class BranchMergeProposalFormatterAPI(CustomizableFormatter):
_link_summary_template = _('%(title)s')
def _link_summary_values(self):
return {
'title': self._context.title,
}
class BugBranchFormatterAPI(CustomizableFormatter):
"""Adapter providing fmt support for BugBranch objects"""
def _get_task_formatter(self):
task = self._context.bug.getBugTask(self._context.branch.product)
if task is None:
task = self._context.bug.bugtasks[0]
return BugTaskFormatterAPI(task)
def _make_link_summary(self):
"""Return the summary of the related product's bug task"""
return self._get_task_formatter()._make_link_summary()
def _get_icon(self):
"""Return the icon of the related product's bugtask"""
return self._get_task_formatter()._get_icon()
class BugFormatterAPI(CustomizableFormatter):
"""Adapter for IBug objects to a formatted string."""
_link_summary_template = 'Bug #%(id)s: %(title)s'
def _link_summary_values(self):
"""See CustomizableFormatter._link_summary_values."""
return {'id': str(self._context.id), 'title': self._context.title}
class BugTaskFormatterAPI(CustomizableFormatter):
"""Adapter for IBugTask objects to a formatted string."""
_title_template = '%(importance)s - %(status)s'
def _title_values(self):
return {'importance': self._context.importance.title,
'status': self._context.status.title}
def _make_link_summary(self):
return BugFormatterAPI(self._context.bug)._make_link_summary()
class CodeImportFormatterAPI(CustomizableFormatter):
"""Adapter providing fmt support for CodeImport objects"""
_link_summary_template = _('Import of %(target)s: %(branch)s')
_link_permission = 'zope.Public'
def _link_summary_values(self):
"""See CustomizableFormatter._link_summary_values."""
return {'target': self._context.branch.target.displayname,
'branch': self._context.branch.bzr_identity,
}
def url(self, view_name=None, rootsite=None):
"""See `ObjectFormatterAPI`."""
# The url of a code import is the associated branch.
# This is still here primarily for supporting branch deletion,
# which does a fmt:link of the other entities that will be deleted.
url = canonical_url(
self._context.branch, path_only_if_possible=True,
view_name=view_name)
return url
class PackageBuildFormatterAPI(ObjectFormatterAPI):
"""Adapter providing fmt support for `IPackageBuild` objects."""
def _composeArchiveReference(self, archive):
if archive.is_ppa:
return " [%s/%s]" % (
cgi.escape(archive.owner.name), cgi.escape(archive.name))
else:
return ""
def link(self, view_name, rootsite=None):
build = self._context
if not check_permission('launchpad.View', build):
return 'private source'
url = self.url(view_name=view_name, rootsite=rootsite)
title = cgi.escape(build.title)
archive = self._composeArchiveReference(build.archive)
return '<a href="%s">%s</a>%s' % (url, title, archive)
class CodeImportMachineFormatterAPI(CustomizableFormatter):
"""Adapter providing fmt support for CodeImport objects"""
_link_summary_template = _('%(hostname)s')
_link_permission = 'zope.Public'
def _link_summary_values(self):
"""See CustomizableFormatter._link_summary_values."""
return {'hostname': self._context.hostname}
class MilestoneFormatterAPI(CustomizableFormatter):
"""Adapter providing fmt support for Milestone objects."""
_link_summary_template = _('%(title)s')
_link_permission = 'zope.Public'
def _link_summary_values(self):
"""See CustomizableFormatter._link_summary_values."""
return {'title': self._context.title}
class ProductReleaseFormatterAPI(CustomizableFormatter):
"""Adapter providing fmt support for Milestone objects."""
_link_summary_template = _('%(displayname)s %(code_name)s')
_link_permission = 'zope.Public'
def _link_summary_values(self):
"""See CustomizableFormatter._link_summary_values."""
code_name = self._context.milestone.code_name
if code_name is None or code_name.strip() == '':
code_name = ''
else:
code_name = '(%s)' % code_name.strip()
return dict(displayname=self._context.milestone.displayname,
code_name=code_name)
class ProductSeriesFormatterAPI(CustomizableFormatter):
"""Adapter providing fmt support for ProductSeries objects"""
_link_summary_template = _('%(product)s %(series)s series')
def _link_summary_values(self):
"""See CustomizableFormatter._link_summary_values."""
return {'series': self._context.name,
'product': self._context.product.displayname}
class QuestionFormatterAPI(CustomizableFormatter):
"""Adapter providing fmt support for question objects."""
_link_summary_template = _('%(id)s: %(title)s')
_link_permission = 'zope.Public'
def _link_summary_values(self):
"""See CustomizableFormatter._link_summary_values."""
return {'id': str(self._context.id), 'title': self._context.title}
class SourcePackageRecipeFormatterAPI(CustomizableFormatter):
"""Adapter providing fmt support for ISourcePackageRecipe objects."""
_link_summary_template = 'Recipe %(name)s for %(owner)s'
def _link_summary_values(self):
return {'name': self._context.name,
'owner': self._context.owner.displayname}
class SpecificationFormatterAPI(CustomizableFormatter):
"""Adapter providing fmt support for Specification objects"""
_link_summary_template = _('%(title)s')
_link_permission = 'zope.Public'
def _link_summary_values(self):
"""See CustomizableFormatter._link_summary_values."""
return {'title': self._context.title}
class CodeReviewCommentFormatterAPI(CustomizableFormatter):
"""Adapter providing fmt support for CodeReviewComment objects"""
_link_summary_template = _('Comment by %(author)s')
_link_permission = 'zope.Public'
def _link_summary_values(self):
"""See CustomizableFormatter._link_summary_values."""
return {'author': self._context.message.owner.displayname}
class PPAFormatterAPI(CustomizableFormatter):
"""Adapter providing fmt support for `IPPA` objects."""
_link_summary_template = '%(display_name)s'
_link_permission = 'launchpad.View'
_reference_template = "ppa:%(owner_name)s/%(ppa_name)s"
final_traversable_names = {
'reference': 'reference',
}
final_traversable_names.update(
CustomizableFormatter.final_traversable_names)
def _link_summary_values(self):
"""See CustomizableFormatter._link_summary_values."""
return {
'display_name': self._context.displayname,
}
def link(self, view_name):
"""Return html including a link for the context PPA.
Render a link using CSS sprites for users with permission to view
the PPA.
Disabled PPAs are listed with sprites but not linkified.
Unaccessible private PPA are not rendered at all (empty string
is returned).
"""
summary = self._make_link_summary()
css = self.sprite_css()
if check_permission(self._link_permission, self._context):
url = self.url(view_name)
return '<a href="%s" class="%s">%s</a>' % (url, css, summary)
else:
if not self._context.private:
return '<span class="%s">%s</span>' % (css, summary)
else:
return ''
def reference(self, view_name=None, rootsite=None):
"""Return the text PPA reference for a PPA."""
# XXX: noodles 2010-02-11 bug=336779: This following check
# should be replaced with the normal check_permission once
# permissions for archive subscribers has been resolved.
if self._context.private:
request = get_current_browser_request()
person = IPerson(request.principal)
subscriptions = getUtility(IArchiveSubscriberSet).getBySubscriber(
person, self._context)
if subscriptions.is_empty():
return ''
return self._reference_template % {
'owner_name': self._context.owner.name,
'ppa_name': self._context.name,
}
class SpecificationBranchFormatterAPI(CustomizableFormatter):
"""Adapter for ISpecificationBranch objects to a formatted string."""
def _make_link_summary(self):
"""Provide the summary of the linked spec"""
formatter = SpecificationFormatterAPI(self._context.specification)
return formatter._make_link_summary()
def _get_icon(self):
"""Provide the icon of the linked spec"""
formatter = SpecificationFormatterAPI(self._context.specification)
return formatter._get_icon()
def sprite_css(self):
return queryAdapter(
self._context.specification, IPathAdapter, 'image').sprite_css()
class BugTrackerFormatterAPI(ObjectFormatterAPI):
"""Adapter for `IBugTracker` objects to a formatted string."""
final_traversable_names = {
'aliases': 'aliases',
'external-link': 'external_link',
'external-title-link': 'external_title_link'}
final_traversable_names.update(ObjectFormatterAPI.final_traversable_names)
def link(self, view_name):
"""Return an HTML link to the bugtracker page.
If the user is not logged-in, the title of the bug tracker is
modified to obfuscate all email addresses.
"""
url = self.url(view_name)
title = self._context.title
if getUtility(ILaunchBag).user is None:
title = FormattersAPI(title).obfuscate_email()
return u'<a href="%s">%s</a>' % (escape(url), escape(title))
def external_link(self):
"""Return an HTML link to the external bugtracker.
If the user is not logged-in, and the URL of the bugtracker
contains an email address, this returns the obfuscated URL as
text (i.e. no <a/> link).
"""
url = self._context.baseurl
if url.startswith('mailto:') and getUtility(ILaunchBag).user is None:
return escape(u'mailto:<email address hidden>')
else:
href = escape(url)
return u'<a class="link-external" href="%s">%s</a>' % (href, href)
def external_title_link(self):
"""Return an HTML link to the external bugtracker.
If the user is not logged-in, the title of the bug tracker is
modified to obfuscate all email addresses. Additonally, if the
URL is a mailto: address then no link is returned, just the
title text.
"""
url = self._context.baseurl
title = self._context.title
if getUtility(ILaunchBag).user is None:
title = FormattersAPI(title).obfuscate_email()
if url.startswith('mailto:'):
return escape(title)
return u'<a class="link-external" href="%s">%s</a>' % (
escape(url), escape(title))
def aliases(self):
"""Generate alias URLs, obfuscating where necessary.
If the user is not logged-in, email addresses should be
hidden.
"""
anonymous = getUtility(ILaunchBag).user is None
for alias in self._context.aliases:
if anonymous and alias.startswith('mailto:'):
yield escape(u'mailto:<email address hidden>')
else:
yield alias
class BugWatchFormatterAPI(ObjectFormatterAPI):
"""Adapter for `IBugWatch` objects to a formatted string."""
final_traversable_names = {
'external-link': 'external_link',
'external-link-short': 'external_link_short'}
final_traversable_names.update(ObjectFormatterAPI.final_traversable_names)
def _make_external_link(self, summary=None):
"""Return an external HTML link to the target of the bug watch.
If a summary is not specified or empty, an em-dash is used as
the content of the link.
If the user is not logged in and the URL of the bug watch is
an email address, only the summary is returned (i.e. no link).
"""
if summary is None or len(summary) == 0:
summary = u'—'
else:
summary = escape(summary)
url = self._context.url
if url.startswith('mailto:') and getUtility(ILaunchBag).user is None:
return summary
else:
return u'<a class="link-external" href="%s">%s</a>' % (
escape(url), summary)
def external_link(self):
"""Return an HTML link with a detailed link text.
The link text is formed from the bug tracker name and the
remote bug number.
"""
summary = self._context.bugtracker.name
remotebug = self._context.remotebug
if remotebug is not None and len(remotebug) > 0:
summary = u'%s #%s' % (summary, remotebug)
return self._make_external_link(summary)
def external_link_short(self):
"""Return an HTML link with a short link text.
The link text is formed from the bug tracker name and the
remote bug number.
"""
return self._make_external_link(self._context.remotebug)
class NumberFormatterAPI:
"""Adapter for converting numbers to formatted strings."""
implements(ITraversable)
def __init__(self, number):
self._number = number
def traverse(self, name, furtherPath):
if name == 'float':
if len(furtherPath) != 1:
raise TraversalError(
"fmt:float requires a single decimal argument")
# coerce the argument to float to ensure it's safe
format = furtherPath.pop()
return self.float(float(format))
elif name == 'bytes':
return self.bytes()
elif name == 'intcomma':
return self.intcomma()
else:
raise TraversalError(name)
def intcomma(self):
"""Return this number with its thousands separated by comma.
This can only be used for integers.
"""
if not isinstance(self._number, int):
raise AssertionError("This can't be used with non-integers")
L = []
for index, char in enumerate(reversed(str(self._number))):
if index != 0 and (index % 3) == 0:
L.insert(0, ',')
L.insert(0, char)
return ''.join(L)
def bytes(self):
"""Render number as byte contractions according to IEC60027-2."""
# See http://en.wikipedia.org/wiki
# /Binary_prefixes#Specific_units_of_IEC_60027-2_A.2
# Note that there is a zope.app.size.byteDisplay() function, but
# it really limited and doesn't work well enough for us here.
assert not float(self._number) < 0, "Expected a non-negative number."
n = int(self._number)
if n == 1:
# Handle the singular case.
return "1 byte"
if n == 0:
# To avoid math.log(0, X) blowing up.
return "0 bytes"
suffixes = ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]
exponent = int(math.log(n, 1024))
exponent = min(len(suffixes), exponent)
if exponent < 1:
# If this is less than 1 KiB, no need for rounding.
return "%s bytes" % n
return "%.1f %s" % (n / 1024.0 ** exponent, suffixes[exponent - 1])
def float(self, format):
"""Use like tal:content="context/foo/fmt:float/.2".
Will return a string formatted to the specification provided in
the manner Python "%f" formatter works. See
http://docs.python.org/lib/typesseq-strings.html for details and
doc.displaying-numbers for various examples.
"""
value = "%" + str(format) + "f"
return value % float(self._number)
class DateTimeFormatterAPI:
"""Adapter from datetime objects to a formatted string."""
def __init__(self, datetimeobject):
self._datetime = datetimeobject
def time(self):
if self._datetime.tzinfo:
value = self._datetime.astimezone(
getUtility(ILaunchBag).time_zone)
return value.strftime('%T %Z')
else:
return self._datetime.strftime('%T')
def date(self):
value = self._datetime
if value.tzinfo:
value = value.astimezone(
getUtility(ILaunchBag).time_zone)
return value.strftime('%Y-%m-%d')
def _now(self):
# This method exists to be overridden in tests.
if self._datetime.tzinfo:
# datetime is offset-aware
return datetime.now(pytz.timezone('UTC'))
else:
# datetime is offset-naive
return datetime.utcnow()
def displaydate(self):
delta = abs(self._now() - self._datetime)
if delta > timedelta(1, 0, 0):
# far in the past or future, display the date
return 'on ' + self.date()
return self.approximatedate()
def approximatedate(self):
delta = self._now() - self._datetime
if abs(delta) > timedelta(1, 0, 0):
# far in the past or future, display the date
return self.date()
future = delta < timedelta(0, 0, 0)
delta = abs(delta)
days = delta.days
hours = delta.seconds / 3600
minutes = (delta.seconds - (3600 * hours)) / 60
seconds = delta.seconds % 60
result = ''
if future:
result += 'in '
if days != 0:
amount = days
unit = 'day'
elif hours != 0:
amount = hours
unit = 'hour'
elif minutes != 0:
amount = minutes
unit = 'minute'
else:
if seconds <= 10:
result += 'a moment'
if not future:
result += ' ago'
return result
else:
amount = seconds
unit = 'second'
if amount != 1:
unit += 's'
result += '%s %s' % (amount, unit)
if not future:
result += ' ago'
return result
def datetime(self):
return "%s %s" % (self.date(), self.time())
def rfc822utcdatetime(self):
return formatdate(
rfc822.mktime_tz(self._datetime.utctimetuple() + (0, )))
def isodate(self):
return self._datetime.isoformat()
class SeriesSourcePackageBranchFormatter(ObjectFormatterAPI):
"""Formatter for a SourcePackage, Pocket -> Branch link.
Since the link object is never really interesting in and of itself, we
always link to the source package instead.
"""
def url(self, view_name=None, rootsite=None):
return queryAdapter(
self._context.sourcepackage, IPathAdapter, 'fmt').url(
view_name, rootsite)
def link(self, view_name):
return queryAdapter(
self._context.sourcepackage, IPathAdapter, 'fmt').link(view_name)
class DurationFormatterAPI:
"""Adapter from timedelta objects to a formatted string."""
implements(ITraversable)
def __init__(self, duration):
self._duration = duration
def traverse(self, name, furtherPath):
if name == 'exactduration':
return self.exactduration()
elif name == 'approximateduration':
return self.approximateduration()
else:
raise TraversalError(name)
def exactduration(self):
"""Format timedeltas as "v days, w hours, x minutes, y.z seconds"."""
parts = []
minutes, seconds = divmod(self._duration.seconds, 60)
hours, minutes = divmod(minutes, 60)
seconds = seconds + (float(self._duration.microseconds) / 10 ** 6)
if self._duration.days > 0:
if self._duration.days == 1:
parts.append('%d day' % self._duration.days)
else:
parts.append('%d days' % self._duration.days)
if parts or hours > 0:
if hours == 1:
parts.append('%d hour' % hours)
else:
parts.append('%d hours' % hours)
if parts or minutes > 0:
if minutes == 1:
parts.append('%d minute' % minutes)
else:
parts.append('%d minutes' % minutes)
if parts or seconds > 0:
parts.append('%0.1f seconds' % seconds)
return ', '.join(parts)
def approximateduration(self):
"""Return a nicely-formatted approximate duration.
E.g. '1 hour', '3 minutes', '1 hour 10 minutes' and so forth.
See https://launchpad.canonical.com/PresentingLengthsOfTime.
"""
# NOTE: There are quite a few "magic numbers" in this
# implementation; they are generally just figures pulled
# directly out of the PresentingLengthsOfTime spec, and so
# it's not particularly easy to give each and every number of
# a useful name. It's also unlikely that these numbers will be
# changed.
# Calculate the total number of seconds in the duration,
# including the decimal part.
seconds = self._duration.days * (3600 * 24)
seconds += self._duration.seconds
seconds += (float(self._duration.microseconds) / 10 ** 6)
# First we'll try to calculate an approximate number of
# seconds up to a minute. We'll start by defining a sorted
# list of (boundary, display value) tuples. We want to show
# the display value corresponding to the lowest boundary that
# 'seconds' is less than, if one exists.
representation_in_seconds = [
(1.5, '1 second'),
(2.5, '2 seconds'),
(3.5, '3 seconds'),
(4.5, '4 seconds'),
(7.5, '5 seconds'),
(12.5, '10 seconds'),
(17.5, '15 seconds'),
(22.5, '20 seconds'),
(27.5, '25 seconds'),
(35, '30 seconds'),
(45, '40 seconds'),
(55, '50 seconds'),
(90, '1 minute'),
]
# Break representation_in_seconds into two pieces, to simplify
# finding the correct display value, through the use of the
# built-in bisect module.
second_boundaries, display_values = zip(*representation_in_seconds)
# Is seconds small enough that we can produce a representation
# in seconds (up to '1 minute'?)
if seconds < second_boundaries[-1]:
# Use the built-in bisection algorithm to locate the index
# of the item which "seconds" sorts after.
matching_element_index = bisect.bisect(second_boundaries, seconds)
# Return the corresponding display value.
return display_values[matching_element_index]
# Convert seconds into minutes, and round it.
minutes, remaining_seconds = divmod(seconds, 60)
minutes += remaining_seconds / 60.0
minutes = int(round(minutes))
if minutes <= 59:
return "%d minutes" % minutes
# Is the duration less than an hour and 5 minutes?
if seconds < (60 + 5) * 60:
return "1 hour"
# Next phase: try and calculate an approximate duration
# greater than one hour, but fewer than ten hours, to a 10
# minute granularity.
hours, remaining_seconds = divmod(seconds, 3600)
ten_minute_chunks = int(round(remaining_seconds / 600.0))
minutes = ten_minute_chunks * 10
hours += (minutes / 60)
minutes %= 60
if hours < 10:
if minutes:
# If there is a minutes portion to display, the number
# of hours is always shown as a digit.
if hours == 1:
return "1 hour %s minutes" % minutes
else:
return "%d hours %s minutes" % (hours, minutes)
else:
return "%d hours" % hours
# Is the duration less than ten and a half hours?
if seconds < (10.5 * 3600):
return '10 hours'
# Try to calculate the approximate number of hours, to a
# maximum of 47.
hours = int(round(seconds / 3600.0))
if hours <= 47:
return "%d hours" % hours
# Is the duration fewer than two and a half days?
if seconds < (2.5 * 24 * 3600):
return '2 days'
# Try to approximate to day granularity, up to a maximum of 13
# days.
days = int(round(seconds / (24 * 3600)))
if days <= 13:
return "%s days" % days
# Is the duration fewer than two and a half weeks?
if seconds < (2.5 * 7 * 24 * 3600):
return '2 weeks'
# If we've made it this far, we'll calculate the duration to a
# granularity of weeks, once and for all.
weeks = int(round(seconds / (7 * 24 * 3600.0)))
return "%d weeks" % weeks
class LinkFormatterAPI(ObjectFormatterAPI):
"""Adapter from Link objects to a formatted anchor."""
final_traversable_names = {
'icon': 'icon',
'icon-link': 'link',
'link-icon': 'link',
}
final_traversable_names.update(ObjectFormatterAPI.final_traversable_names)
def icon(self):
"""Return the icon representation of the link."""
request = get_current_browser_request()
return getMultiAdapter(
(self._context, request), name="+inline-icon")()
def link(self, view_name=None, rootsite=None):
"""Return the default representation of the link."""
return self._context.render()
def url(self, view_name=None, rootsite=None):
"""Return the URL representation of the link."""
if self._context.enabled:
return self._context.url
else:
return u''
class RevisionAuthorFormatterAPI(ObjectFormatterAPI):
"""Adapter for `IRevisionAuthor` links."""
traversable_names = {'link': 'link'}
def link(self, view_name=None, rootsite='mainsite'):
"""See `ObjectFormatterAPI`."""
context = self._context
if context.person is not None:
return PersonFormatterAPI(self._context.person).link(
view_name, rootsite)
elif context.name_without_email:
return cgi.escape(context.name_without_email)
elif context.email and getUtility(ILaunchBag).user is not None:
return cgi.escape(context.email)
elif context.email:
return "<email address hidden>"
else:
# The RevisionAuthor name and email is None.
return ''
def clean_path_segments(request):
"""Returns list of path segments, excluding system-related segments."""
proto_host_port = request.getApplicationURL()
clean_url = request.getURL()
clean_path = clean_url[len(proto_host_port):]
clean_path_split = clean_path.split('/')
return clean_path_split
class PageTemplateContextsAPI:
"""Adapter from page tempate's CONTEXTS object to fmt:pagetitle.
This is registered to be used for the dict type.
"""
# 2009-09-08 BarryWarsaw bug 426532. Remove this class, all references
# to it, and all instances of CONTEXTS/fmt:pagetitle
implements(ITraversable)
def __init__(self, contextdict):
self.contextdict = contextdict
def traverse(self, name, furtherPath):
if name == 'pagetitle':
return self.pagetitle()
else:
raise TraversalError(name)
def pagetitle(self):
"""Return the string title for the page template CONTEXTS dict.
Take the simple filename without extension from
self.contextdict['template'].filename, replace any hyphens with
underscores, and use this to look up a string, unicode or
function in the module canonical.launchpad.pagetitles.
If no suitable object is found in canonical.launchpad.pagetitles, emit
a warning that this page has no title, and return the default page
title.
"""
template = self.contextdict['template']
filename = os.path.basename(template.filename)
name, ext = os.path.splitext(filename)
name = name.replace('-', '_')
titleobj = getattr(canonical.launchpad.pagetitles, name, None)
if titleobj is None:
raise AssertionError(
"No page title in canonical.launchpad.pagetitles "
"for %s" % name)
elif isinstance(titleobj, basestring):
return titleobj
else:
context = self.contextdict['context']
view = self.contextdict['view']
title = titleobj(context, view)
if title is None:
return canonical.launchpad.pagetitles.DEFAULT_LAUNCHPAD_TITLE
else:
return title
class PermissionRequiredQuery:
"""Check if the logged in user has a given permission on a given object.
Example usage::
tal:condition="person/required:launchpad.Edit"
"""
implements(ITraversable)
def __init__(self, context):
self.context = context
def traverse(self, name, furtherPath):
if len(furtherPath) > 0:
raise TraversalError(
"There should be no further path segments after "
"required:permission")
return check_permission(name, self.context)
class IMainTemplateFile(Interface):
path = TextLine(title=u'The absolute path to this main template.')
class LaunchpadLayerToMainTemplateAdapter:
adapts(LaunchpadLayer)
implements(IMainTemplateFile)
def __init__(self, context):
here = os.path.dirname(os.path.realpath(__file__))
self.path = os.path.join(
here, '../templates/base-layout.pt')
class PageMacroDispatcher:
"""Selects a macro, while storing information about page layout.
view/macro:page
view/macro:page/main_side
view/macro:page/main_only
view/macro:page/searchless
view/macro:page/locationless
view/macro:pagehas/applicationtabs
view/macro:pagehas/globalsearch
view/macro:pagehas/portlets
view/macro:pagetype
"""
implements(ITraversable)
def __init__(self, context):
# The context of this object is a view object.
self.context = context
@property
def base(self):
return ViewPageTemplateFile(
IMainTemplateFile(self.context.request).path)
def traverse(self, name, furtherPath):
if name == 'page':
if len(furtherPath) == 1:
pagetype = furtherPath.pop()
elif not furtherPath:
pagetype = 'default'
else:
raise TraversalError("Max one path segment after macro:page")
return self.page(pagetype)
elif name == 'pagehas':
if len(furtherPath) != 1:
raise TraversalError(
"Exactly one path segment after macro:haspage")
layoutelement = furtherPath.pop()
return self.haspage(layoutelement)
elif name == 'pagetype':
return self.pagetype()
elif name == 'show_actions_menu':
return self.show_actions_menu()
else:
raise TraversalError(name)
def page(self, pagetype):
if pagetype not in self._pagetypes:
raise TraversalError('unknown pagetype: %s' % pagetype)
self.context.__pagetype__ = pagetype
return self.base.macros['master']
def haspage(self, layoutelement):
pagetype = getattr(self.context, '__pagetype__', None)
if pagetype is None:
pagetype = 'unset'
return self._pagetypes[pagetype][layoutelement]
def pagetype(self):
return getattr(self.context, '__pagetype__', 'unset')
class LayoutElements:
def __init__(self,
applicationtabs=False,
globalsearch=False,
portlets=False,
pagetypewasset=True,
):
self.elements = vars()
def __getitem__(self, name):
return self.elements[name]
_pagetypes = {
'main_side':
LayoutElements(
applicationtabs=True,
globalsearch=True,
portlets=True),
'main_only':
LayoutElements(
applicationtabs=True,
globalsearch=True,
portlets=False),
'searchless':
LayoutElements(
applicationtabs=True,
globalsearch=False,
portlets=False),
'locationless':
LayoutElements(),
}
class TranslationGroupFormatterAPI(ObjectFormatterAPI):
"""Adapter for `ITranslationGroup` objects to a formatted string."""
traversable_names = {
'link': 'link',
'url': 'url',
'displayname': 'displayname',
}
def url(self, view_name=None, rootsite='translations'):
"""See `ObjectFormatterAPI`."""
return super(TranslationGroupFormatterAPI, self).url(
view_name, rootsite)
def link(self, view_name, rootsite='translations'):
"""See `ObjectFormatterAPI`."""
group = self._context
url = self.url(view_name, rootsite)
return u'<a href="%s">%s</a>' % (url, cgi.escape(group.title))
def displayname(self, view_name, rootsite=None):
"""Return the displayname as a string."""
return self._context.title
class LanguageFormatterAPI(ObjectFormatterAPI):
"""Adapter for `ILanguage` objects to a formatted string."""
traversable_names = {
'link': 'link',
'url': 'url',
'displayname': 'displayname',
}
def url(self, view_name=None, rootsite='translations'):
"""See `ObjectFormatterAPI`."""
return super(LanguageFormatterAPI, self).url(view_name, rootsite)
def link(self, view_name, rootsite='translations'):
"""See `ObjectFormatterAPI`."""
url = self.url(view_name, rootsite)
return u'<a href="%s" class="sprite language">%s</a>' % (
url, cgi.escape(self._context.englishname))
def displayname(self, view_name, rootsite=None):
"""See `ObjectFormatterAPI`."""
return self._context.englishname
class POFileFormatterAPI(ObjectFormatterAPI):
"""Adapter for `IPOFile` objects to a formatted string."""
traversable_names = {
'link': 'link',
'url': 'url',
'displayname': 'displayname',
}
def url(self, view_name=None, rootsite='translations'):
"""See `ObjectFormatterAPI`."""
return super(POFileFormatterAPI, self).url(view_name, rootsite)
def link(self, view_name, rootsite='translations'):
"""See `ObjectFormatterAPI`."""
pofile = self._context
url = self.url(view_name, rootsite)
return u'<a href="%s">%s</a>' % (url, cgi.escape(pofile.title))
def displayname(self, view_name, rootsite=None):
"""Return the displayname as a string."""
return self._context.title
class PackageDiffFormatterAPI(ObjectFormatterAPI):
def link(self, view_name, rootsite=None):
diff = self._context
if not diff.date_fulfilled:
return '%s (pending)' % cgi.escape(diff.title)
else:
file_size = NumberFormatterAPI(
diff.diff_content.content.filesize).bytes()
return '<a href="%s">%s</a> (%s)' % (
cgi.escape(diff.diff_content.http_url),
cgi.escape(diff.title), file_size)
class CSSFormatter:
"""A tales path adapter used for CSS rules.
Using an expression like this:
value/css:select/visible/unseen
You will get "visible" if value evaluates to true, and "unseen" if the
value evaluates to false.
"""
implements(ITraversable)
def __init__(self, context):
self.context = context
def select(self, furtherPath):
if len(furtherPath) < 2:
raise TraversalError('select needs two subsequent path elements.')
true_value = furtherPath.pop()
false_value = furtherPath.pop()
if self.context:
return true_value
else:
return false_value
def traverse(self, name, furtherPath):
try:
return getattr(self, name)(furtherPath)
except AttributeError:
raise TraversalError(name)
class IRCNicknameFormatterAPI(ObjectFormatterAPI):
"""Adapter from IrcID objects to a formatted string."""
implements(ITraversable)
traversable_names = {
'displayname': 'displayname',
'formatted_displayname': 'formatted_displayname',
}
def displayname(self, view_name=None):
return "%s on %s" % (self._context.nickname, self._context.network)
def formatted_displayname(self, view_name=None):
return dedent("""\
<strong>%s</strong>
<span class="discreet"> on </span>
<strong>%s</strong>
""" % (escape(self._context.nickname), escape(self._context.network)))
|