~nursix.org/sahana-eden/vita

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
# -*- coding: utf-8 -*-

"""
    GIS Controllers

    @author: Fran Boon <fran@aidiq.com>
"""

module = request.controller
resourcename = request.function

# Options Menu (available in all Functions' Views)
s3_menu(module)

#if not deployment_settings.get_security_map() or s3_has_role(MAP_ADMIN):
#   response.menu_options.append([T("Service Catalogue"), False, URL(f="map_service_catalogue")])
#   # Not yet ready for Production
#   response.menu_options.append([T("De-duplicator"), False, URL(f="location_duplicates")])

# -----------------------------------------------------------------------------
def index():
    """
       Module's Home Page
    """

    module_name = deployment_settings.modules[module].name_nice
    response.title = module_name

    # Include an embedded Map on the index page

    # Icon toolbar?
    toolbar = True

    map = define_map(window=False,
                     toolbar=toolbar)

    # Don't bother with breadcrumbs as they use up real-estate needlessly
    breadcrumbs = []

    # Provide access to the Personalised config
    pconfig = ""
    config_id = session.s3.gis_config_id
    if auth.is_logged_in():
        if config_id == 1:
            pconfig = T("You are using the site-wide map configuration. To create or use a personal map configuration, click %(here)s") % \
                        dict(here=A(T("here"),
                                    _class="marron",
                                    _style="font-weight:bold;",
                                    _href=URL(c="pr", f="person",
                                              args=["config"],
                                              vars={"person.uid":auth.user.person_uuid})))
        else:
            table = s3db.gis_config
            query = (table.id == config_id)
            config = db(query).select(table.pe_id,
                                      limitby=(0, 1)).first()
            if config and config.pe_id:
                table = s3db.pr_person
                query = (table.uuid == auth.user.person_uuid)
                person = db(query).select(table.pe_id,
                                          limitby=(0, 1)).first()
                if person and person.pe_id == config.pe_id:
                    pconfig = T("You are using a personal map configuration. To edit your personal configuration, click %(here)s") % \
                                dict(here=A(T("here"),
                                            _class="marron",
                                            _style="font-weight:bold;",
                                            _href=URL(c="pr", f="person",
                                                      args=["config"],
                                                      vars={"person.uid":auth.user.person_uuid})))

    return dict(map=map, breadcrumbs=breadcrumbs, pconfig=pconfig)

# =============================================================================
def map_viewing_client():
    """
        Map Viewing Client.
        UI for a user to view the overall Maps with associated Features
    """

    map = define_map(window=True,
                     toolbar=True)

    response.title = T("Map Viewing Client")
    return dict(map=map)

# -----------------------------------------------------------------------------
def define_map(window=False, toolbar=False, config=None):
    """
        Define the main Situation Map
        This can then be called from both the Index page (embedded)
        & the Map_Viewing_Client (fullscreen)
    """

    if not config:
        config = gis.get_config()

    if not deployment_settings.get_security_map() or s3_has_role(MAP_ADMIN):
        catalogue_toolbar = True
    else:
        catalogue_toolbar = False

    # @ToDo: Make these configurable
    search = True
    legend = True
    googleEarth = True
    googleStreetview = True
    catalogue_layers = True

    if config.wmsbrowser_url:
        wms_browser = {"name" : config.wmsbrowser_name,
                       "url" : config.wmsbrowser_url}
    else:
        wms_browser = None

    # 'normal', 'mgrs' or 'off'
    mouse_position = deployment_settings.get_gis_mouse_position()

    # http://eden.sahanafoundation.org/wiki/BluePrintGISPrinting
    print_service = deployment_settings.get_gis_print_service()
    if print_service:
        print_tool = {"url": print_service}
    else:
        print_tool = {}

    map = gis.show_map(
                       window=window,
                       catalogue_toolbar=catalogue_toolbar,
                       wms_browser = wms_browser,
                       toolbar=toolbar,
                       legend=legend,
                       search=search,
                       catalogue_layers=catalogue_layers,
                       mouse_position = mouse_position,
                       print_tool = print_tool
                      )

    return map

# =============================================================================
def location():
    """ RESTful CRUD controller for Locations """

    tablename = "%s_%s" % (module, resourcename)
    table = s3db[tablename]

    # Location Search Method
    gis_location_search = s3base.S3LocationSearch(
        simple = (s3base.S3SearchSimpleWidget(
            name="location_search_text_simple",
            label = T("Search"),
            #comment = T("Search for a Location by name, including local names."),  # How? These aren't fields in this table or in a table that we link to.
            comment = T("To search for a location, enter the name. You may use % as wildcard. Press 'Search' without input to list all locations."),
            field = [ "name" ]
            )
        ),
        advanced = (s3base.S3SearchSimpleWidget(
            name = "location_search_text_advanced",
            label = T("Search"),
            #comment = T("Search for a Location by name, including local names."),
            comment = T("To search for a location, enter the name. You may use % as wildcard. Press 'Search' without input to list all locations."),
            field = [ "name"]
            ),
            s3base.S3SearchOptionsWidget(
                name = "location_search_level",
                label = T("Level"),
                field = ["level"],
                cols = 2
            ),
            # NB This currently only works for locations with the country as direct parent (i.e. mostly L1s)
            #s3base.S3SearchOptionsWidget(
            #    name = "location_search_country",
            #    label = T("Country"),
            #    field = ["parent"],
            #    cols = 2
            #),
        )
    )

    s3mgr.configure(tablename,
                    # Don't include Bulky Location Selector in List Views
                    listadd=False,
                    # Custom Search Method
                    search_method=gis_location_search)

    # Custom Method
    s3mgr.model.set_method("gis", "location", method="parents",
                           action=s3_gis_location_parents)

    # Pre-processor
    # Allow prep to pass vars back to the controller
    vars = {}
    # @ToDo: Clean up what needs to be done only for interactive views,
    # vs. what needs to be done generally. E.g. some tooltips are defined
    # for non-interactive.
    def prep(r, vars):

        def get_location_info():
            table = s3db.gis_location
            query = (table.id == r.id)
            return db(query).select(table.lat,
                                    table.lon,
                                    table.level,
                                    limitby=(0, 1)).first()

        # Restrict access to Polygons to just MapAdmins
        if deployment_settings.get_security_map() and not s3_has_role(MAP_ADMIN):
            table.code.writable = False
            if r.method == "create":
                table.code.readable = False
            table.gis_feature_type.writable = table.gis_feature_type.readable = False
            table.wkt.writable = table.wkt.readable = False
        elif r.interactive:
            table.code.comment = DIV(_class="tooltip",
                                     _title="%s|%s" % (T("Code"),
                                                       T("For a country this would be the ISO2 code, for a Town, it would be the Airport Locode.")))
            table.wkt.comment = DIV(_class="stickytip",
                                    _title="WKT|%s %s%s %s%s" % (T("The"),
                                                               "<a href='http://en.wikipedia.org/wiki/Well-known_text' target=_blank>",
                                                               T("Well-Known Text"),
                                                               "</a>",
                                                               T("representation of the Polygon/Line.")))
            table.members.comment = DIV(_class="tooltip",
                      _title="%s|%s|%s|%s|%s" % (T("Members"),
                                                 T("A location group is a set of locations (often, a set of administrative regions representing a combined area)."),
                                                 T("Location groups may be used to filter what is shown on the map and in search results to only entities covered by locations in the group."),
                                                 T("A location group can be used to define the extent of an affected area, if it does not fall within one administrative region."),
                                                 T("Location groups can be used in the Regions menu.")))



        if r.method == "update" and r.id:
            # We don't allow converting a location group to non-group and
            # vice versa. We also don't allow taking away all the members of
            # a group -- setting "notnull" gets the "required" * displayed.
            # Groups don't have parents. (This is all checked in onvalidation.)
            # NB r.id is None for update.url
            location = get_location_info()
            if location.level == "GR":
                table.level.writable = False
                table.parent.readable = table.parent.writable = False
                table.members.notnull = True
                # Record that this is a group location. Since we're setting
                # level to not writable, it won't be in either form.vars or
                # request.vars. Saving it while we have it avoids another
                # db access.
                response.s3.location_is_group = True
            else:
                table.members.writable = table.members.readable = False
                response.s3.location_is_group = False

        if r.interactive:
            if not "group" in r.vars:
                # Hide the Members List (a big download when many records are entered)
                table.members.writable = table.members.readable = False
            # Don't show street address, postcode for hierarchy on read or update.
            if r.method != "create" and r.id:
                try:
                    location
                except:
                    location = get_location_info()
                if location.level:
                    table.addr_street.writable = table.addr_street.readable = False
                    table.addr_postcode.writable = table.addr_postcode.readable = False

            # Options which are only required in interactive HTML views
            table.level.comment = DIV(_class="tooltip",
                                      _title="%s|%s" % (T("Level"),
                                                        T("If the location is a geographic area, then state at what level here.")))
            parent_comment = DIV(_class="tooltip",
                                 _title="%s|%s" % (T("Parent"),
                                                   T("The Area which this Site is located within.")))
            if r.representation == "popup":
                table.parent.comment = parent_comment
            else:
                # Include 'Add Location' button
                table.parent.comment = DIV(A(ADD_LOCATION,
                                             _class="colorbox",
                                             _href=URL(c="gis", f="location",
                                                       args="create",
                                                       vars=dict(format="popup",
                                                                 child="parent")),
                                             _target="top",
                                             _title=ADD_LOCATION),
                                           parent_comment),
            table.osm_id.comment = DIV(_class="stickytip",
                                       _title="OpenStreetMap ID|%s%s%s" % (T("The"),
                                                                           " <a href='http://openstreetmap.org' target=_blank>OpenStreetMap</a> ID. ",
                                                                           T("If you know what the OSM ID of this location is then you can enter it here.")))
            table.geonames_id.comment = DIV(_class="stickytip",
                                            _title="Geonames ID|%s%s%s" % (T("The"),
                                                                           " <a href='http://geonames.org' target=_blank>Geonames</a> ID. ",
                                                                           T("If you know what the Geonames ID of this location is then you can enter it here.")))
            table.comments.comment = DIV(_class="tooltip",
                                         _title="%s|%s" % (T("Comments"),
                                                           T("Please use this field to record any additional information, such as Ushahidi instance IDs. Include a history of the record if it is updated.")))

            if r.representation == "iframe":
                # De-duplicator needs to be able to access UUID fields
                table.uuid.readable = table.uuid.writable = True
                table.uuid.label = "UUID"
                table.uuid.comment = DIV(_class="stickytip",
                                         _title="UUID|%s%s%s" % (T("The"),
                                                                 " <a href='http://eden.sahanafoundation.org/wiki/UUID#Mapping' target=_blank>Universally Unique ID</a>. ",
                                                                 T("Suggest not changing this field unless you know what you are doing.")))

            if r.method in (None, "list") and r.record is None:
                # List
                pass
            elif r.method in ("delete", "search"):
                pass
            else:
                # Add Map to allow locations to be found this way
                config = gis.get_config()
                lat = config.lat
                lon = config.lon
                zoom = config.zoom
                feature_queries = []

                if r.method == "create":
                    add_feature = True
                    add_feature_active = True
                else:
                    if r.method == "update":
                        add_feature = True
                        add_feature_active = False
                    else:
                        # Read
                        add_feature = False
                        add_feature_active = False

                    try:
                        location
                    except:
                        location = get_location_info()
                    if location and location.lat is not None and location.lon is not None:
                        lat = location.lat
                        lon = location.lon
                    # Same as a single zoom on a cluster
                    zoom = zoom + 2

                # @ToDo: Does map make sense if the user is updating a group?
                # If not, maybe leave it out. OTOH, might be nice to select
                # admin regions to include in the group by clicking on them in
                # the map. Would involve boundaries...
                _map = gis.show_map(lat = lat,
                                    lon = lon,
                                    zoom = zoom,
                                    feature_queries = feature_queries,
                                    add_feature = add_feature,
                                    add_feature_active = add_feature_active,
                                    toolbar = True,
                                    collapsed = True)

                # Pass the map back to the main controller
                vars.update(_map=_map)
        elif r.representation == "json":
            # Path field should be visible
            table.path.readable = True
        return True
    response.s3.prep = lambda r, vars=vars: prep(r, vars)

    # Options
    _vars = request.vars
    filters = []

    parent = _vars.get("parent_", None)
    # Don't use 'parent' as the var name as otherwise it conflicts with the form's var of the same name & hence this will be triggered during form submission
    if parent:
        # We want to do case-insensitive searches
        # (default anyway on MySQL/SQLite, but not PostgreSQL)
        _parent = parent.lower()

        # Can't do this using a JOIN in DAL syntax
        # .belongs() not GAE-compatible!
        query = (table.name.lower().like(_parent))
        filters.append((table.parent.belongs(db(query).select(table.id))))
        # ToDo: Make this recursive - want descendants not just direct children!
        # Use new gis.get_children() function

    if filters:
        from operator import __and__
        response.s3.filter = reduce(__and__, filters)

    caller = _vars.get("caller", None)
    if caller:
        # We've been called as a Popup
        if "gis_location_parent" in caller:
            # Hide unnecessary rows
            table.addr_street.readable = table.addr_street.writable = False
        else:
            parent = _vars.get("parent_", None)
            # Don't use 'parent' as the var name as otherwise it conflicts with the form's var of the same name & hence this will be triggered during form submission
            if parent:
                table.parent.default = parent

            # Hide unnecessary rows
            table.level.readable = table.level.writable = False
            table.geonames_id.readable = table.geonames_id.writable = False
            table.osm_id.readable = table.osm_id.writable = False
            table.source.readable = table.source.writable = False
            table.url.readable = table.url.writable = False

    level = _vars.get("level", None)
    if level:
        # We've been called from the Location Selector widget
        table.addr_street.readable = table.addr_street.writable = False

        
    country = S3ReusableField("country", "string", length=2,
                              label = T("Country"),
                              requires = IS_NULL_OR(IS_IN_SET_LAZY(
                                    lambda: gis.get_countries(key_type="code"),
                                    zero = SELECT_LOCATION)),
                              represent = lambda code: \
                                    gis.get_country(code, key_type="code") or UNKNOWN_OPT)

    output = s3_rest_controller(csv_extra_fields = [
                                    dict(label="Country",
                                         field=country())
                                ])

    _map = vars.get("_map", None)
    if _map and isinstance(output, dict):
        output["_map"] = _map

    return output

# -----------------------------------------------------------------------------
def s3_gis_location_parents(r, **attr):
    """
        Custom S3Method

        Return a list of Parents for a Location
    """

    resource = r.resource
    table = resource.table

    # Check permission
    if not s3_has_permission("read", table):
        r.unauthorised()

    if r.representation == "html":

        # @ToDo
        output = dict()
        #return output
        raise HTTP(501, body=s3mgr.ERROR.BAD_FORMAT)

    elif r.representation == "json":

        if r.id:
            # Get the parents for a Location
            parents = gis.get_parents(r.id)
            if parents:
                _parents = {}
                for parent in parents:
                    _parents[parent.level] = parent.id
                output = json.dumps(_parents)
                return output
            else:
                raise HTTP(404, body=s3mgr.ERROR.NO_MATCH)
        else:
            raise HTTP(404, body=s3mgr.ERROR.BAD_RECORD)

    else:
        raise HTTP(501, body=s3mgr.ERROR.BAD_FORMAT)

# -----------------------------------------------------------------------------
def l0():
    """
        A specialised controller to return details for an L0 location
        - suitable for use with the LocationSelector

        arg: ID of the L0 location
        returns JSON
    """

    try:
        record_id = request.args[0]
    except:
        item = s3mgr.xml.json_message(False, 400, "Need to specify a record ID!")
        raise HTTP(400, body=item)

    table = s3db.gis_location
    query = (table.id == record_id) & \
            (table.deleted == False) & \
            (table.level == "L0")
    record = db(query).select(table.id,
                              table.name,
                              # Code for the Geocoder lookup filter
                              table.code,
                              # LatLon for Centering the Map
                              table.lon,
                              table.lat,
                              # Bounds for Zooming the Map
                              table.lon_min,
                              table.lon_max,
                              table.lat_min,
                              table.lat_max,
                              cache = s3db.cache,
                              limitby=(0, 1)).first()
    if not record:
        item = s3mgr.xml.json_message(False, 400, "Invalid ID!")
        raise HTTP(400, body=item)

    result = record.as_dict()

    # Provide the Location Hierarchy for this country
    location_hierarchy = gis.get_location_hierarchy(location=record_id)
    for key in location_hierarchy:
        result[key] = location_hierarchy[key]

    output = json.dumps(result)
    response.headers["Content-Type"] = "application/json"
    return output

# -----------------------------------------------------------------------------
def location_duplicates():
    """
        Handle De-duplication of Locations by comparing the ones which are closest together

        @ToDo: Extend to being able to check locations for which we have no Lat<>Lon info (i.e. just names & parents)
    """

    # @ToDo: Set this via the UI & pass in as a var
    dupe_distance = 50 # km

    # Shortcut
    locations = s3db.gis_location

    table_header = THEAD(TR(TH(T("Location 1")),
                            TH(T("Location 2")),
                            TH(T("Distance(Kms)")),
                            TH(T("Resolve"))))

    # Calculate max possible combinations of records
    # To handle the AJAX requests by the dataTables jQuery plugin.
    totalLocations = db(locations.id > 0).count()

    item_list = []
    if request.vars.iDisplayStart:
        end = int(request.vars.iDisplayLength) + int(request.vars.iDisplayStart)
        locations = db((locations.id > 0) & \
                       (locations.deleted == False) & \
                       (locations.lat != None) & \
                       (locations.lon != None)).select(locations.id,
                                                       locations.name,
                                                       locations.level,
                                                       locations.lat,
                                                       locations.lon)
        # Calculate the Great Circle distance
        count = 0
        for oneLocation in locations[:len(locations) / 2]:
            for anotherLocation in locations[len(locations) / 2:]:
                if count > end and request.vars.max != "undefined":
                    count = int(request.vars.max)
                    break
                if oneLocation.id == anotherLocation.id:
                    continue
                else:
                    dist = gis.greatCircleDistance(oneLocation.lat,
                                                   oneLocation.lon,
                                                   anotherLocation.lat,
                                                   anotherLocation.lon)
                    if dist < dupe_distance:
                        count = count + 1
                        item_list.append([oneLocation.name,
                                          anotherLocation.name,
                                          dist,
                                          "<a href=\"../gis/location_resolve?locID1=%i&locID2=%i\", class=\"action-btn\">Resolve</a>" % (oneLocation.id, anotherLocation.id)
                                         ])
                    else:
                        continue

        item_list = item_list[int(request.vars.iDisplayStart):end]
        # Convert data to JSON
        result  = []
        result.append({
                    "sEcho" : request.vars.sEcho,
                    "iTotalRecords" : count,
                    "iTotalDisplayRecords" : count,
                    "aaData" : item_list
                    })
        output = json.dumps(result)
        # Remove unwanted brackets
        output = output[1:]
        output = output[:-1]
        return output
    else:
        # Don't load records except via dataTables (saves duplicate loading & less confusing for user)
        items = DIV((TABLE(table_header,
                           TBODY(),
                           _id="list",
                           _class="dataTable display")))
        return(dict(items=items))

# -----------------------------------------------------------------------------
def delete_location():
    """
        Delete references to a old record and replacing it with the new one.
    """

    old = request.vars.old
    new = request.vars.new

    # Find all tables which link to the Locations table
    # @ToDo Replace with db.gis_location._referenced_by
    tables = s3_table_links("gis_location")

    for table in tables:
        for count in range(len(tables[table])):
            field = tables[str(db[table])][count]
            query = db[table][field] == old
            db(query).update(**{field:new})

    # Remove the record
    db(s3db.gis_location.id == old).update(deleted=True)
    return "Record Gracefully Deleted"

# -----------------------------------------------------------------------------
def location_resolve():
    """
        Opens a popup screen where the de-duplication process takes place.
    """

    # @ToDo: Error gracefully if conditions not satisfied
    locID1 = request.vars.locID1
    locID2 = request.vars.locID2

    # Shortcut
    locations = s3db.gis_location

    # Remove the comment and replace it with buttons for each of the fields
    count = 0
    for field in locations:
        id1 = str(count) + "Right"      # Gives a unique number to each of the arrow keys
        id2 = str(count) + "Left"
        count  = count + 1

        # Comment field filled with buttons
        field.comment = DIV(TABLE(TR(TD(INPUT(_type="button", _id=id1, _class="rightArrows", _value="-->")),
                                     TD(INPUT(_type="button", _id=id2, _class="leftArrows", _value="<--")))))
        record = locations[locID1]
    myUrl = URL(c="gis", f="location")
    form1 = SQLFORM(locations, record, _id="form1", _action=("%s/%s" % (myUrl, locID1)))

    # For the second location remove all the comments to save space.
    for field in locations:
        field.comment = None
    record = locations[locID2]
    form2 = SQLFORM(locations, record,_id="form2", _action=("%s/%s" % (myUrl, locID2)))
    return dict(form1=form1, form2=form2, locID1=locID1, locID2=locID2)

# -----------------------------------------------------------------------------
def location_links():
    """
        @arg id - the location record id
        Returns a JSON array of records which link to the specified location

        @ToDo: Deprecated with new de-duplicator?
    """

    try:
        record_id = request.args[0]
    except:
        item = s3mgr.xml.json_message(False, 400, "Need to specify a record ID!")
        raise HTTP(400, body=item)

    try:
        # Shortcut
        locations = s3db.gis_location

        deleted = (locations.deleted == False)
        query = (locations.id == record_id)
        query = deleted & query
        record = db(query).select(locations.id, limitby=(0, 1)).first().id
    except:
        item = s3mgr.xml.json_message(False, 404, "Record not found!")
        raise HTTP(404, body=item)

    # Find all tables which link to the Locations table
    # @ToDo: Replace with db.gis_location._referenced_by
    tables = s3_table_links("gis_location")

    results = []
    for table in tables:
        for count in range(len(tables[table])):
            field = tables[str(db[table])][count]
            query = db[table][field] == record_id
            _results = db(query).select()
            module, resourcename = table.split("_", 1)
            for result in _results:
                id = result.id
                # We currently have no easy way to get the default represent for a table!
                try:
                    # Locations & Persons
                    represent = eval("s3_%s_represent(id)" % table)
                except:
                    try:
                        # Organizations
                        represent = eval("s3_%s_represent(id)" % resourcename)
                    except:
                        try:
                            # Many tables have a Name field
                            represent = (id and [db[table][id].name] or ["None"])[0]
                        except:
                            # Fallback
                            represent = id
                results.append({
                    "module" : module,
                    "resource" : resourcename,
                    "id" : id,
                    "represent" : represent
                    })

    output = json.dumps(results)
    return output

# =============================================================================
def map_service_catalogue():
    """
        Map Service Catalogue.
        Allows selection of which Layers are active.
    """

    if deployment_settings.get_security_map() and not s3_has_role(MAP_ADMIN):
        auth.permission.fail()

    subtitle = T("List Layers")
    # Start building the Return with the common items
    output = dict(subtitle=subtitle)

    # Hack: We control all perms from this 1 table
    table = s3db.gis_layer_entity
    authorised = s3_has_permission("update", table)
    item_list = []
    even = True
    ltable = s3db.gis_layer_config
    if authorised:
        # List View with checkboxes to Enable/Disable layers
        for type in response.s3.gis_layer_types:
            table = s3db[type]
            query = (table.id > 0) & (ltable.layer_id == table.layer_id)
            rows = db(query).select(table.id,
                                    table.name,
                                    table.description,
                                    ltable.enabled)
            for row in rows:
                row = row[type]
                lrow = row.gis_layer_config
                if even:
                    theclass = "even"
                    even = False
                else:
                    theclass = "odd"
                    even = True
                description = row.description or ""
                label = "%s_%s" % (type, str(row.id))
                if lrow.enabled:
                    enabled = INPUT(_type="checkbox", value=True, _name=label)
                else:
                    enabled = INPUT(_type="checkbox", _name=label)
                item_list.append(TR(TD(A(row.name,
                                         _href=URL("layer_%s" % type,
                                                   args=row.id))),
                                    TD(description),
                                    TD(enabled),
                                    _class=theclass))
        table_header = THEAD(TR(TH(T("Layer")),
                                TH(T("Description")),
                                TH(T("Enabled?"))))
        table_footer = TFOOT(TR(TD(INPUT(_id="submit_button",
                                         _type="submit",
                                         _value=T("Update")),
                                   _colspan=3)),
                             _align="right")
        items = DIV(FORM(TABLE(table_header,
                               TBODY(item_list),
                               table_footer,
                               _id="table-container"),
                    _name="custom",
                    _method="post",
                    _enctype="multipart/form-data",
                    _action=URL(f="layers_enable")))

    else:
        # Simple List View
        for type in response.s3.gis_layer_types:
            table = s3db[type]
            query = (table.id > 0) & (ltable.layer_id == table.layer_id)
            rows = db(table.id > 0).select(table.id,
                                           table.name,
                                           table.description,
                                           ltable.enabled)
            for row in rows:
                row = row[type]
                lrow = row.gis_layer_config
                if even:
                    theclass = "even"
                    even = False
                else:
                    theclass = "odd"
                    even = True
                description = row.description or ""
                if lrow.enabled:
                    enabled = INPUT(_type="checkbox",
                                    value="on",
                                    _disabled="disabled")
                else:
                    enabled = INPUT(_type="checkbox",
                                    _disabled="disabled")
                item_list.append(TR(TD(A(row.name,
                                         _href=URL("layer_%s" % type,
                                                   args=row.id))),
                                    TD(description),
                                    TD(enabled),
                                    _class=theclass))

        table_header = THEAD(TR(TH(T("Layer")),
                                TH(T("Description")),
                                TH(T("Enabled?"))))
        items = DIV(TABLE(table_header,
                          TBODY(item_list),
                          _id="table-container"))

    output.update(dict(items=items))
    return output

# -----------------------------------------------------------------------------
def layers_enable():
    """
        Enable/Disable Layers
    """

    table = s3db.gis_layer_config
    authorised = s3_has_permission("update", table)
    vars = request.vars
    if authorised:
        for resourcename in response.s3.gis_layer_types:
            table = s3db[resourcename]
            rows = db(table.id > 0).select(table.id)
            for row in rows:
                query_inner = (table.id == row.id)
                var = "%s_%i" % (resourcename, row.id)
                # Read current state
                if db(query_inner).select(table.enabled,
                                          limitby=(0, 1)).first().enabled:
                    # Old state: Enabled
                    if var in vars:
                        # Do nothing
                        pass
                    else:
                        # Disable
                        db(query_inner).update(enabled=False)
                        # Audit
                        s3_audit("update", module, resourcename, record=row.id,
                                 representation="html")
                else:
                    # Old state: Disabled
                    if var in vars:
                        # Enable
                        db(query_inner).update(enabled=True)
                        # Audit
                        s3_audit("update", module, resourcename, record=row.id,
                                 representation="html")
                    else:
                        # Do nothing
                        pass

        session.confirmation = T("Layers updated")

    else:
        session.error = T("Not authorised!")

    redirect(URL(f="map_service_catalogue"))

# -----------------------------------------------------------------------------
def config():
    """ RESTful CRUD controller """

    # Pre-process
    def prep(r):
        if r.interactive:
            if not r.component:
                s3db.gis_config_form_setup()
                if auth.is_logged_in() and not auth.s3_has_role(MAP_ADMIN):
                    # Only Personal Config is accessible
                    # @ToDo: ideal would be to have the SITE_DEFAULT (with any OU configs overlaid) on the left-hand side & then they can see what they wish to override on the right-hand side
                    # - could be easier to put the currently-effective config into the form fields, however then we have to save all this data
                    # - if each field was readable & you clicked on it to make it editable (like RHoK pr_contact), that would solve this
                    ptable = s3db.pr_person
                    query = (ptable.uuid == auth.user.person_uuid)
                    # For Lists
                    response.s3.filter = query & (s3db.gis_config.pe_id == ptable.pe_id)
                    # For Create forms
                    pe = db(query).select(ptable.pe_id,
                                          limitby=(0, 1),
                                          cache=s3db.cache).first()
                    field = r.table.pe_id
                    field.default = pe.pe_id
                    field.writable = False

        return True
    response.s3.prep = prep

    output = s3_rest_controller(rheader=s3db.gis_rheader)
    return output

# -----------------------------------------------------------------------------
def hierarchy():
    """ RESTful CRUD controller """

    s3db.gis_hierarchy_form_setup()

    return s3_rest_controller()

# -----------------------------------------------------------------------------
def symbology():
    """ RESTful CRUD controller """

    if deployment_settings.get_security_map() and not s3_has_role(MAP_ADMIN):
        auth.permission.fail()

    # Pre-process
    def prep(r):
        if r.interactive:
            if r.component_name == "layer_entity":
                # Restrict Layers to those which have Markers
                s3db.gis_layer_symbology.layer_id.requires = IS_ONE_OF(db,
                            "gis_layer_entity.layer_id",
                            "%(name)s",
                            filterby="instance_type",
                            filter_opts=("gis_layer_feature",
                                         "gis_layer_georss",
                                         "gis_layer_geojson",
                                         "gis_layer_kml",
                            ))

        return True
    response.s3.prep = prep

    output = s3_rest_controller(rheader=s3db.gis_rheader)
    return output

# -----------------------------------------------------------------------------
def marker():
    """ RESTful CRUD controller """

    if deployment_settings.get_security_map() and not s3_has_role(MAP_ADMIN):
        auth.permission.fail()

    # Pre-process
    def prep(r):
        if r.interactive:
            if r.method == "create":
                table = r.table
                table.height.readable = False
                table.width.readable = False
        return True
    response.s3.prep = prep

    return s3_rest_controller()

# -----------------------------------------------------------------------------
def projection():
    """ RESTful CRUD controller """

    if deployment_settings.get_security_map() and not s3_has_role(MAP_ADMIN):
        auth.permission.fail()

    return s3_rest_controller()

# -----------------------------------------------------------------------------
def waypoint():
    """ RESTful CRUD controller for GPS Waypoints """

    return s3_rest_controller()

# -----------------------------------------------------------------------------
def waypoint_upload():
    """
        Custom View
        Temporary: Likely to be refactored into the main waypoint controller
    """

    return dict()

# -----------------------------------------------------------------------------
def trackpoint():
    """ RESTful CRUD controller for GPS Track points """

    return s3_rest_controller()

# -----------------------------------------------------------------------------
def track():
    """ RESTful CRUD controller for GPS Tracks (uploaded as files) """

    if deployment_settings.get_security_map() and not s3_has_role(MAP_ADMIN):
        auth.permission.fail()

    return s3_rest_controller()


# =============================================================================
# Common CRUD strings for all layers
ADD_LAYER = T("Add Layer")
LAYER_DETAILS = T("Layer Details")
LAYERS = T("Layers")
EDIT_LAYER = T("Edit Layer")
SEARCH_LAYERS = T("Search Layers")
ADD_NEW_LAYER = T("Add New Layer")
LIST_LAYERS = T("List Layers")
DELETE_LAYER = T("Delete Layer")
LAYER_ADDED = T("Layer added")
LAYER_UPDATED = T("Layer updated")
LAYER_DELETED = T("Layer deleted")
# These may be differentiated per type of layer.
TYPE_LAYERS_FMT = "%s Layers"
ADD_NEW_TYPE_LAYER_FMT = "Add New %s Layer"
EDIT_TYPE_LAYER_FMT = "Edit %s Layer"
LIST_TYPE_LAYERS_FMT = "List %s Layers"
NO_TYPE_LAYERS_FMT = "No %s Layers currently defined"

# -----------------------------------------------------------------------------
def enable_layer(r):
    """
        Enable a Layer
            designed to be a custom method called by an action button
    """

    if not r.id:
        session.error = T("Can only enable 1 record at a time!")
        redirect(URL(args=[]))

    ltable = s3db.gis_layer_config
    query = (r.table.id == r.id) & (ltable.layer_id == table.layer_id)
    #db(query).update(ltable.enabled = True)
    session.confirmation = T("Layer has been Enabled")
    redirect(URL(args=[]))

# -----------------------------------------------------------------------------
def disable_layer(r):
    """
        Disable a Layer
            designed to be a custom method called by an action button
    """

    if not r.id:
        session.error = T("Can only disable 1 record at a time!")
        redirect(URL(args=[]))

    ltable = s3db.gis_layer_config
    query = (r.table.id == r.id) & (ltable.layer_id == table.layer_id)
    #db(query).update(ltable.enabled = False)
    session.confirmation = T("Layer has been Disabled")
    redirect(URL(args=[]))

# -----------------------------------------------------------------------------
def layer_entity():
    """ RESTful CRUD controller """

    if deployment_settings.get_security_map() and not s3_has_role(MAP_ADMIN):
        auth.permission.fail()

    # Custom Method
    s3mgr.model.set_method(module, resourcename,
                           method="disable",
                           action=disable_layer)

    # Post-processor
    def postp(r, output):
        s3_action_buttons(r)
        # Only show the disable button if the layer is not currently disabled
        # @ToDo: Fix for new data model
        ltable = s3db.gis_layer_config
        query = (ltable.enabled != False) & \
                (r.table.layer_id == ltable.layer_id)
        rows = db(query).select(r.table.id)
        restrict = [str(row.id) for row in rows]
        response.s3.actions.append(dict(label=str(T("Disable")),
                                        _class="action-btn",
                                        url=URL(args=["[id]", "disable"]),
                                        restrict = restrict
                                        )
                                    )

        return output
    #response.s3.postp = postp

    output = s3_rest_controller(rheader=s3db.gis_rheader)
    return output

# -----------------------------------------------------------------------------
def layer_config():
    """ RESTful CRUD controller """

    if deployment_settings.get_security_map() and not s3_has_role(MAP_ADMIN):
        auth.permission.fail()

    return s3_rest_controller()

# -----------------------------------------------------------------------------
def layer_symbology():
    """ RESTful CRUD controller """

    if deployment_settings.get_security_map() and not s3_has_role(MAP_ADMIN):
        auth.permission.fail()

    return s3_rest_controller()

# -----------------------------------------------------------------------------
def layer_feature():
    """ RESTful CRUD controller """

    if deployment_settings.get_security_map() and not s3_has_role(MAP_ADMIN):
        auth.permission.fail()

    # Custom Method
    s3mgr.model.set_method(module, resourcename,
                           method="disable",
                           action=disable_layer)

    # Pre-processor
    def prep(r):
        if r.interactive:
            if r.component_name == "config":
                field = s3db.gis_layer_config.base
                field.readable = False
                field.writable = False
            
        return True
    response.s3.prep = prep

    # Post-processor
    def postp(r, output):
        s3_action_buttons(r)
        # Only show the disable button if the layer is not currently disabled
        # @ToDo: Fix for new data model
        ltable = s3db.gis_layer_config
        query = (ltable.enabled != False) & \
                (r.table.layer_id == ltable.layer_id)
        rows = db(query).select(r.table.id)
        restrict = [str(row.id) for row in rows]
        response.s3.actions.append(dict(label=str(T("Disable")),
                                        _class="action-btn",
                                        url=URL(args=["[id]", "disable"]),
                                        restrict = restrict
                                        )
                                    )

        return output
    #response.s3.postp = postp

    output = s3_rest_controller(rheader=s3db.gis_rheader)
    return output

# -----------------------------------------------------------------------------
def layer_openstreetmap():
    """ RESTful CRUD controller """

    if deployment_settings.get_security_map() and not s3_has_role(MAP_ADMIN):
        auth.permission.fail()

    tablename = "%s_%s" % (module, resourcename)
    s3mgr.load(tablename)

    # CRUD Strings
    type = "OpenStreetMap"
    LIST_LAYERS = T(LIST_TYPE_LAYERS_FMT % type)
    EDIT_LAYER = T(EDIT_TYPE_LAYER_FMT % type)
    NO_LAYERS = T(NO_TYPE_LAYERS_FMT % type)
    s3.crud_strings[tablename] = Storage(
        title_create=ADD_LAYER,
        title_display=LAYER_DETAILS,
        title_list=LAYERS,
        title_update=EDIT_LAYER,
        title_search=SEARCH_LAYERS,
        subtitle_create=ADD_NEW_LAYER,
        subtitle_list=LIST_LAYERS,
        label_list_button=LIST_LAYERS,
        label_create_button=ADD_LAYER,
        label_delete_button = DELETE_LAYER,
        msg_record_created=LAYER_ADDED,
        msg_record_modified=LAYER_UPDATED,
        msg_record_deleted=LAYER_DELETED,
        msg_list_empty=NO_LAYERS)

    output = s3_rest_controller(rheader=s3db.gis_rheader)

    return output

# -----------------------------------------------------------------------------
def layer_bing():
    """ RESTful CRUD controller """

    if deployment_settings.get_security_map() and not s3_has_role(MAP_ADMIN):
        auth.permission.fail()

    tablename = "%s_%s" % (module, resourcename)
    s3mgr.load(tablename)

    # CRUD Strings
    type = "Bing"
    EDIT_LAYER = T(EDIT_TYPE_LAYER_FMT % type)
    s3.crud_strings[tablename] = Storage(
        title_create=ADD_LAYER,
        title_update=EDIT_LAYER,
        msg_record_created=LAYER_ADDED,
        msg_record_modified=LAYER_UPDATED)

    s3mgr.configure(tablename,
                    deletable=False,
                    listadd=False)

    # Pre-processor
    def prep(r):
        if r.interactive:
            if r.component_name == "config":
                field = s3db.gis_layer_config.visible
                field.readable = False
                field.writable = False
            
        return True
    response.s3.prep = prep

    output = s3_rest_controller(rheader=s3db.gis_rheader)

    return output

# -----------------------------------------------------------------------------
def layer_google():
    """ RESTful CRUD controller """

    if deployment_settings.get_security_map() and not s3_has_role(MAP_ADMIN):
        auth.permission.fail()

    tablename = "%s_%s" % (module, resourcename)
    s3mgr.load(tablename)

    # CRUD Strings
    type = "Google"
    EDIT_LAYER = T(EDIT_TYPE_LAYER_FMT % type)
    s3.crud_strings[tablename] = Storage(
        title_create=ADD_LAYER,
        title_update=EDIT_LAYER,
        msg_record_created=LAYER_ADDED,
        msg_record_modified=LAYER_UPDATED)

    s3mgr.configure(tablename,
                    deletable=False,
                    listadd=False)

    # Pre-processor
    def prep(r):
        if r.interactive:
            if r.component_name == "config":
                field = s3db.gis_layer_config.visible
                field.readable = False
                field.writable = False
            
        return True
    response.s3.prep = prep

    output = s3_rest_controller(rheader=s3db.gis_rheader)

    return output

# -----------------------------------------------------------------------------
def layer_mgrs():
    """ RESTful CRUD controller """

    if deployment_settings.get_security_map() and not s3_has_role(MAP_ADMIN):
        auth.permission.fail()

    tablename = "%s_%s" % (module, resourcename)
    s3mgr.load(tablename)

    # CRUD Strings
    type = "MGRS"
    LIST_LAYERS = T(LIST_TYPE_LAYERS_FMT % type)
    EDIT_LAYER = T(EDIT_TYPE_LAYER_FMT % type)
    NO_LAYERS = T(NO_TYPE_LAYERS_FMT % type)
    s3.crud_strings[tablename] = Storage(
        title_create=ADD_LAYER,
        title_display=LAYER_DETAILS,
        title_list=LAYERS,
        title_update=EDIT_LAYER,
        title_search=SEARCH_LAYERS,
        subtitle_create=ADD_NEW_LAYER,
        subtitle_list=LIST_LAYERS,
        label_list_button=LIST_LAYERS,
        label_create_button=ADD_LAYER,
        label_delete_button = DELETE_LAYER,
        msg_record_created=LAYER_ADDED,
        msg_record_modified=LAYER_UPDATED,
        msg_record_deleted=LAYER_DELETED,
        msg_list_empty=NO_LAYERS)

    s3mgr.configure(tablename, deletable=False, listadd=False)

    # Pre-processor
    def prep(r):
        if r.interactive:
            if r.component_name == "config":
                field = s3db.gis_layer_config.base
                field.readable = False
                field.writable = False
            
        return True
    response.s3.prep = prep

    output = s3_rest_controller(rheader=s3db.gis_rheader)

    return output

# -----------------------------------------------------------------------------
def layer_geojson():
    """ RESTful CRUD controller """

    if deployment_settings.get_security_map() and not s3_has_role(MAP_ADMIN):
        auth.permission.fail()

    tablename = "%s_%s" % (module, resourcename)
    s3mgr.load(tablename)

    # CRUD Strings
    type = "GeoJSON"
    LAYERS = T(TYPE_LAYERS_FMT % type)
    ADD_NEW_LAYER = T(ADD_NEW_TYPE_LAYER_FMT % type)
    EDIT_LAYER = T(EDIT_TYPE_LAYER_FMT % type)
    LIST_LAYERS = T(LIST_TYPE_LAYERS_FMT % type)
    NO_LAYERS = T(NO_TYPE_LAYERS_FMT % type)
    s3.crud_strings[tablename] = Storage(
        title_create=ADD_LAYER,
        title_display=LAYER_DETAILS,
        title_list=LAYERS,
        title_update=EDIT_LAYER,
        title_search=SEARCH_LAYERS,
        subtitle_create=ADD_NEW_LAYER,
        subtitle_list=LIST_LAYERS,
        label_list_button=LIST_LAYERS,
        label_create_button=ADD_LAYER,
        label_delete_button = DELETE_LAYER,
        msg_record_created=LAYER_ADDED,
        msg_record_modified=LAYER_UPDATED,
        msg_record_deleted=LAYER_DELETED,
        msg_list_empty=NO_LAYERS)

    # Pre-processor
    def prep(r):
        if r.interactive:
            if r.component_name == "config":
                field = s3db.gis_layer_config.base
                field.readable = False
                field.writable = False
            elif r.component_name == "symbology":
                field = s3db.gis_layer_symbology.gps_marker
                field.readable = False
                field.writable = False
            
        return True
    response.s3.prep = prep

    output = s3_rest_controller(rheader=s3db.gis_rheader)

    return output

# -----------------------------------------------------------------------------
def layer_georss():
    """ RESTful CRUD controller """

    if deployment_settings.get_security_map() and not s3_has_role(MAP_ADMIN):
        auth.permission.fail()

    tablename = "%s_%s" % (module, resourcename)
    s3mgr.load(tablename)

    # CRUD Strings
    type = "GeoRSS"
    LAYERS = T(TYPE_LAYERS_FMT % type)
    ADD_NEW_LAYER = T(ADD_NEW_TYPE_LAYER_FMT % type)
    EDIT_LAYER = T(EDIT_TYPE_LAYER_FMT % type)
    LIST_LAYERS = T(LIST_TYPE_LAYERS_FMT % type)
    NO_LAYERS = T(NO_TYPE_LAYERS_FMT % type)
    s3.crud_strings[tablename] = Storage(
        title_create=ADD_LAYER,
        title_display=LAYER_DETAILS,
        title_list=LAYERS,
        title_update=EDIT_LAYER,
        title_search=SEARCH_LAYERS,
        subtitle_create=ADD_NEW_LAYER,
        subtitle_list=LIST_LAYERS,
        label_list_button=LIST_LAYERS,
        label_create_button=ADD_LAYER,
        label_delete_button = DELETE_LAYER,
        msg_record_created=LAYER_ADDED,
        msg_record_modified=LAYER_UPDATED,
        msg_record_deleted=LAYER_DELETED,
        msg_list_empty=NO_LAYERS)

    # Custom Method
    s3mgr.model.set_method(module, resourcename, method="enable",
                           action=enable_layer)

    # Pre-processor
    def prep(r):
        if r.interactive:
            if r.component_name == "config":
                field = s3db.gis_layer_config.base
                field.readable = False
                field.writable = False
            elif r.component_name == "symbology":
                field = s3db.gis_layer_symbology.gps_marker
                field.readable = False
                field.writable = False
            
        return True
    response.s3.prep = prep

    # Post-processor
    def postp(r, output):
        if r.interactive and r.method != "import":
            s3_action_buttons(r)
            # Only show the enable button if the layer is not currently enabled
            # @ToDo: Fix for new data model
            query = (r.table.enabled != True)
            rows = db(query).select(r.table.id)
            restrict = [str(row.id) for row in rows]
            response.s3.actions.append(dict(label=str(T("Enable")),
                                            _class="action-btn",
                                            url=URL(args=["[id]", "enable"]),
                                            restrict = restrict
                                            )
                                        )
        return output
    #response.s3.postp = postp

    output = s3_rest_controller(rheader=s3db.gis_rheader)

    return output

# -----------------------------------------------------------------------------
def layer_gpx():
    """ RESTful CRUD controller """

    if deployment_settings.get_security_map() and not s3_has_role(MAP_ADMIN):
        auth.permission.fail()

    tablename = "%s_%s" % (module, resourcename)
    s3mgr.load(tablename)

    # Model options
    # Needed in multiple controllers, so defined in Model

    # CRUD Strings
    type = "GPX"
    LAYERS = T(TYPE_LAYERS_FMT % type)
    ADD_NEW_LAYER = T(ADD_NEW_TYPE_LAYER_FMT % type)
    EDIT_LAYER = T(EDIT_TYPE_LAYER_FMT % type)
    LIST_LAYERS = T(LIST_TYPE_LAYERS_FMT % type)
    NO_LAYERS = T(NO_TYPE_LAYERS_FMT % type)
    s3.crud_strings[tablename] = Storage(
        title_create=ADD_LAYER,
        title_display=LAYER_DETAILS,
        title_list=LAYERS,
        title_update=EDIT_LAYER,
        title_search=SEARCH_LAYERS,
        subtitle_create=ADD_NEW_LAYER,
        subtitle_list=LIST_LAYERS,
        label_list_button=LIST_LAYERS,
        label_create_button=ADD_LAYER,
        label_delete_button = DELETE_LAYER,
        msg_record_created=LAYER_ADDED,
        msg_record_modified=LAYER_UPDATED,
        msg_record_deleted=LAYER_DELETED,
        msg_list_empty=NO_LAYERS)

    # Pre-processor
    def prep(r):
        if r.interactive:
            if r.component_name == "config":
                field = s3db.gis_layer_config.base
                field.readable = False
                field.writable = False
            
        return True
    response.s3.prep = prep

    output = s3_rest_controller(rheader=s3db.gis_rheader)

    return output

# -----------------------------------------------------------------------------
def layer_kml():
    """ RESTful CRUD controller """

    if deployment_settings.get_security_map() and not s3_has_role(MAP_ADMIN):
        auth.permission.fail()

    tablename = "%s_%s" % (module, resourcename)
    s3mgr.load(tablename)

    # CRUD Strings
    type = "KML"
    LAYERS = T(TYPE_LAYERS_FMT % type)
    ADD_NEW_LAYER = T(ADD_NEW_TYPE_LAYER_FMT % type)
    EDIT_LAYER = T(EDIT_TYPE_LAYER_FMT % type)
    LIST_LAYERS = T(LIST_TYPE_LAYERS_FMT % type)
    NO_LAYERS = T(NO_TYPE_LAYERS_FMT % type)
    s3.crud_strings[tablename] = Storage(
        title_create=ADD_LAYER,
        title_display=LAYER_DETAILS,
        title_list=LAYERS,
        title_update=EDIT_LAYER,
        title_search=SEARCH_LAYERS,
        subtitle_create=ADD_NEW_LAYER,
        subtitle_list=LIST_LAYERS,
        label_list_button=LIST_LAYERS,
        label_create_button=ADD_LAYER,
        label_delete_button = DELETE_LAYER,
        msg_record_created=LAYER_ADDED,
        msg_record_modified=LAYER_UPDATED,
        msg_record_deleted=LAYER_DELETED,
        msg_list_empty=NO_LAYERS)

    # Pre-processor
    def prep(r):
        if r.interactive:
            if r.component_name == "config":
                field = s3db.gis_layer_config.base
                field.readable = False
                field.writable = False
            elif r.component_name == "symbology":
                field = s3db.gis_layer_symbology.gps_marker
                field.readable = False
                field.writable = False
            
        return True
    response.s3.prep = prep

    # Post-processor
    def postp(r, output):
        if r.interactive and r.method != "import":
            s3_action_buttons(r, copyable=True)
        return output
    response.s3.postp = postp

    output = s3_rest_controller(rheader=s3db.gis_rheader)

    return output

# -----------------------------------------------------------------------------
def layer_tms():
    """ RESTful CRUD controller """

    if deployment_settings.get_security_map() and not s3_has_role(MAP_ADMIN):
        auth.permission.fail()

    tablename = "%s_%s" % (module, resourcename)
    s3mgr.load(tablename)

    # CRUD Strings
    type = "TMS"
    LAYERS = T(TYPE_LAYERS_FMT % type)
    ADD_NEW_LAYER = T(ADD_NEW_TYPE_LAYER_FMT % type)
    EDIT_LAYER = T(EDIT_TYPE_LAYER_FMT % type)
    LIST_LAYERS = T(LIST_TYPE_LAYERS_FMT % type)
    NO_LAYERS = T(NO_TYPE_LAYERS_FMT % type)
    s3.crud_strings[tablename] = Storage(
        title_create=ADD_LAYER,
        title_display=LAYER_DETAILS,
        title_list=LAYERS,
        title_update=EDIT_LAYER,
        title_search=SEARCH_LAYERS,
        subtitle_create=ADD_NEW_LAYER,
        subtitle_list=LIST_LAYERS,
        label_list_button=LIST_LAYERS,
        label_create_button=ADD_LAYER,
        label_delete_button = DELETE_LAYER,
        msg_record_created=LAYER_ADDED,
        msg_record_modified=LAYER_UPDATED,
        msg_record_deleted=LAYER_DELETED,
        msg_list_empty=NO_LAYERS)

    # Custom Method
    s3mgr.model.set_method(module, resourcename,
                           method="enable",
                           action=enable_layer)

    # Pre-processor
    def prep(r):
        if r.interactive:
            if r.component_name == "config":
                field = s3db.gis_layer_config.visible
                field.readable = False
                field.writable = False
            
        return True
    response.s3.prep = prep

    # Post-processor
    def postp(r, output):
        if r.interactive and r.method != "import":
            s3_action_buttons(r, copyable=True)
            # Only show the enable button if the layer is not currently enabled
            #query = (r.table.enabled != True)
            #rows = db(query).select(r.table.id)
            #restrict = [str(row.id) for row in rows]
            #response.s3.actions.append(dict(label=str(T("Enable")),
            #                                _class="action-btn",
            #                                url=URL(args=["[id]", "enable"]),
            #                                restrict = restrict
            #                                )
            #                            )
        return output
    response.s3.postp = postp

    output = s3_rest_controller(rheader=s3db.gis_rheader)

    return output

# -----------------------------------------------------------------------------
def layer_wfs():
    """ RESTful CRUD controller """

    if deployment_settings.get_security_map() and not s3_has_role(MAP_ADMIN):
        auth.permission.fail()

    tablename = "%s_%s" % (module, resourcename)
    s3mgr.load(tablename)

    # CRUD Strings
    type = "WFS"
    LAYERS = T(TYPE_LAYERS_FMT % type)
    ADD_NEW_LAYER = T(ADD_NEW_TYPE_LAYER_FMT % type)
    EDIT_LAYER = T(EDIT_TYPE_LAYER_FMT % type)
    LIST_LAYERS = T(LIST_TYPE_LAYERS_FMT % type)
    NO_LAYERS = T(NO_TYPE_LAYERS_FMT % type)
    s3.crud_strings[tablename] = Storage(
        title_create=ADD_LAYER,
        title_display=LAYER_DETAILS,
        title_list=LAYERS,
        title_update=EDIT_LAYER,
        title_search=SEARCH_LAYERS,
        subtitle_create=ADD_NEW_LAYER,
        subtitle_list=LIST_LAYERS,
        label_list_button=LIST_LAYERS,
        label_create_button=ADD_LAYER,
        label_delete_button = DELETE_LAYER,
        msg_record_created=LAYER_ADDED,
        msg_record_modified=LAYER_UPDATED,
        msg_record_deleted=LAYER_DELETED,
        msg_list_empty=NO_LAYERS)

    # Pre-processor
    def prep(r):
        if r.interactive:
            if r.component_name == "config":
                field = s3db.gis_layer_config.base
                field.readable = False
                field.writable = False
            
        return True
    response.s3.prep = prep

    # Post-processor
    def postp(r, output):
        if r.interactive and r.method != "import":
            s3_action_buttons(r, copyable=True)
        return output
    response.s3.postp = postp

    output = s3_rest_controller(rheader=s3db.gis_rheader)

    return output

# -----------------------------------------------------------------------------
def layer_wms():
    """ RESTful CRUD controller """

    if deployment_settings.get_security_map() and not s3_has_role(MAP_ADMIN):
        auth.permission.fail()

    tablename = "%s_%s" % (module, resourcename)
    s3mgr.load(tablename)

    # CRUD Strings
    type = "WMS"
    LAYERS = T(TYPE_LAYERS_FMT % type)
    ADD_NEW_LAYER = T(ADD_NEW_TYPE_LAYER_FMT % type)
    EDIT_LAYER = T(EDIT_TYPE_LAYER_FMT % type)
    LIST_LAYERS = T(LIST_TYPE_LAYERS_FMT % type)
    NO_LAYERS = T(NO_TYPE_LAYERS_FMT % type)
    s3.crud_strings[tablename] = Storage(
        title_create=ADD_LAYER,
        title_display=LAYER_DETAILS,
        title_list=LAYERS,
        title_update=EDIT_LAYER,
        title_search=SEARCH_LAYERS,
        subtitle_create=ADD_NEW_LAYER,
        subtitle_list=LIST_LAYERS,
        label_list_button=LIST_LAYERS,
        label_create_button=ADD_LAYER,
        label_delete_button = DELETE_LAYER,
        msg_record_created=LAYER_ADDED,
        msg_record_modified=LAYER_UPDATED,
        msg_record_deleted=LAYER_DELETED,
        msg_list_empty=NO_LAYERS)

    # Custom Method
    s3mgr.model.set_method(module, resourcename,
                           method="enable",
                           action=enable_layer)

    # Post-processor
    def postp(r, output):
        if r.interactive and r.method != "import":
            s3_action_buttons(r, copyable=True)
            # Only show the enable button if the layer is not currently enabled
            #query = (r.table.enabled != True)
            #rows = db(query).select(r.table.id)
            #restrict = [str(row.id) for row in rows]
            #response.s3.actions.append(dict(label=str(T("Enable")),
            #                                _class="action-btn",
            #                                url=URL(args=["[id]","enable"]),
            #                                restrict = restrict
            #                                )
            #                            )
        return output
    response.s3.postp = postp

    output = s3_rest_controller(rheader=s3db.gis_rheader)

    return output

# -----------------------------------------------------------------------------
@auth.s3_requires_membership("MapAdmin")
def layer_js():
    """ RESTful CRUD controller """

    tablename = "%s_%s" % (module, resourcename)
    s3mgr.load(tablename)

    # CRUD Strings
    type = "JS"
    LAYERS = T(TYPE_LAYERS_FMT % type)
    ADD_NEW_LAYER = T(ADD_NEW_TYPE_LAYER_FMT % type)
    EDIT_LAYER = T(EDIT_TYPE_LAYER_FMT % type)
    LIST_LAYERS = T(LIST_TYPE_LAYERS_FMT % type)
    NO_LAYERS = T(NO_TYPE_LAYERS_FMT % type)
    s3.crud_strings[tablename] = Storage(
        title_create=ADD_LAYER,
        title_display=LAYER_DETAILS,
        title_list=LAYERS,
        title_update=EDIT_LAYER,
        title_search=SEARCH_LAYERS,
        subtitle_create=ADD_NEW_LAYER,
        subtitle_list=LIST_LAYERS,
        label_list_button=LIST_LAYERS,
        label_create_button=ADD_LAYER,
        label_delete_button = DELETE_LAYER,
        msg_record_created=LAYER_ADDED,
        msg_record_modified=LAYER_UPDATED,
        msg_record_deleted=LAYER_DELETED,
        msg_list_empty=NO_LAYERS)

    output = s3_rest_controller(rheader=s3db.gis_rheader)

    return output

# =============================================================================
def cache_feed():
    """
        RESTful CRUD controller
        - cache GeoRSS/KML feeds &
          make them available to the Map Viewing Client as GeoJSON

        The create.georss/create.kml methods are designed to be called
        asynchronously using S3Task

        This allows:
        * Feed can be refreshed on a schedule rather than every client request
          - especially useful when unzipping or following network links
        * BBOX strategy can be used to allow clients to only download the
          features in their area of interest
        * Can parse the feed using XSLT to extract whatever information we
          want from the feed
        * Can unify the client-side support for Markers & Popups
        * Slightly smaller OpenLayers.js
        * Remove dependency from filesystem to support scaling
          - EC2, GAE or clustering
        * Possible to Cluster multiple feeds together
          - will require rewriting the way we turn layers on/off if we wish
            to retain the ability to do so independently
        * Can have dynamic Layer Filtering
          - change layer.protocol.url
          - call refresh strategy

        NB This can't be simply called 'cache' as this conflicts with the
        global cache object
    """

    resourcename = "cache"

    # Load Models
    #s3mgr.load("gis_cache")

    #if kml:
        # Unzip & Follow Network Links
        #download_kml.delay(url)

    output = s3_rest_controller(module, resourcename)
    return output

# =============================================================================
def feature_query():
    """
        RESTful CRUD controller
        - cache Feature Queries &
          make them available to the Map Viewing Client as GeoJSON

        This allows:
        * Feed can be refreshed on a schedule rather than every client request
          - especially useful when unzipping or following network links
        * BBOX strategy can be used to allow clients to only download the
          features in their area of interest
        * Can parse the feed using XSLT to extract whatever information we
          want from the feed
        * Can unify the client-side support for Markers & Popups
        * Slightly smaller OpenLayers.js
        * Remove dependency from filesystem to support scaling
          - EC2, GAE or clustering
        * Possible to Cluster multiple feeds together
          - will require rewriting the way we turn layers on/off if we wish
            to retain the ability to do so independently
        * Can have dynamic Layer Filtering
          - change layer.protocol.url
          - call refresh strategy

        The create.georss/create.kml methods are designed to be called
        asynchronously using S3Task
    """

    table = s3db.gis_feature_query

    # Filter out any records without LatLon
    response.s3.filter = (table.lat != None) & (table.lon != None)

    # Parse the Request
    r = s3mgr.parse_request()

    if r.representation != "geojson":
        session.error = BADFORMAT
        redirect(URL(c="default", f="index", args=None, vars=None))

    # Execute the request
    output = r()

    return output

# =============================================================================
def display_feature():
    """
        Cut-down version of the Map Viewing Client.
        Used by gis_location_represent() to show just this feature on the map.
        Called by the s3_viewMap() JavaScript
    """

    # The Feature
    feature_id = request.args[0]

    table = s3db.gis_location

    # Check user is authorised to access record
    if not s3_has_permission("read", table, feature_id):
        session.error = T("No access to this record!")
        raise HTTP(401, body=s3mgr.xml.json_message(False, 401, session.error))

    feature = db(table.id == feature_id).select(limitby=(0, 1)).first()

    config = gis.get_config()

    try:
        # Centre on Feature
        lat = feature.lat
        lon = feature.lon
        if (lat is None) or (lon is None):
            if feature.get("parent"):
                # Skip the current record if we can
                latlon = gis.get_latlon(feature.parent)
            elif feature.get("id"):
                latlon = gis.get_latlon(feature.id)
            else:
                # nothing we can do!
                raise
            if latlon:
                lat = latlon["lat"]
                lon = latlon["lon"]
            else:
                # nothing we can do!
                raise
    except:
        lat = config.lat
        lon = config.lon

    # Default zoom +2 (same as a single zoom on a cluster)
    zoom = config.zoom + 2

    map = gis.show_map(
        features = [{"lat"  : lat,
                     "lon"  : lon}],
        lat = lat,
        lon = lon,
        zoom = zoom,
        window = True,
        closable = False,
        collapsed = True
    )

    return dict(map=map)

# -----------------------------------------------------------------------------
def display_features():
    """
        Cut-down version of the Map Viewing Client.
        Used as a link from the RHeader.
            URL generated server-side
        Shows all locations matching a query.
        @ToDo: Most recent location is marked using a bigger Marker.
        @ToDo: Move to S3Method (will then use AAA etc).
    """

    ltable = s3db.gis_location

    # Parse the URL, check for implicit resources, extract the primary record
    # http://127.0.0.1:8000/eden/gis/display_features&module=pr&resource=person&instance=1&jresource=presence
    ok = 0
    if "module" in request.vars:
        res_module = request.vars.module
        ok +=1
    if "resource" in request.vars:
        resource = request.vars.resource
        ok +=1
    if "instance" in request.vars:
        instance = int(request.vars.instance)
        ok +=1
    if "jresource" in request.vars:
        jresource = request.vars.jresource
        ok +=1
    if ok != 4:
        session.error = T("Insufficient vars: Need module, resource, jresource, instance")
        raise HTTP(400, body=s3mgr.xml.json_message(False, 400, session.error))

    tablename = "%s_%s" % (res_module, resource)
    s3mgr.load(tablename)
    table = db[table]
    component, pkey, fkey = s3mgr.model.get_component(table, jresource)
    jtable = db[str(component.table)]
    query = (jtable[fkey] == table[pkey]) & (table.id == instance)
    # Filter out deleted
    deleted = (table.deleted == False)
    query = query & deleted
    # Filter out inaccessible
    query2 = (ltable.id == jtable.location_id)
    accessible = s3_accessible_query("read", ltable)
    query2 = query2 & accessible

    features = db(query).select(ltable.ALL, left = [ltable.on(query2)])

    # Calculate an appropriate BBox
    bounds = gis.get_bounds(features=features)

    map = gis.show_map(
        features = features,
        bbox = bounds,
        window = True,
        closable = False,
        collapsed = True
    )

    return dict(map=map)

# =============================================================================
def geocode():

    """
        Call a Geocoder service

        @param location: a string to search for
        @param service: the service to call (defaults to Google)
    """

    if "location" in request.vars:
        location = request.vars.location
    else:
        session.error = T("Need to specify a location to search for.")
        redirect(URL(f="index"))

    if "service" in request.vars:
        service = request.vars.service
    else:
        # @ToDo: service=all should be default
        service = "google"

    if service == "google":
        return s3base.GoogleGeocoder(location).get_json()

    if service == "yahoo":
        # @ToDo: Convert this to JSON
        return s3base.YahooGeocoder(location).get_xml()

# -----------------------------------------------------------------------------
def geocode_manual():

    """
        Manually Geocode locations

        @ToDo: make this accessible by Anonymous users?
    """

    table = s3db.gis_location

    # Filter
    query = (table.level == None)
    # @ToDo: make this role-dependent
    # - Normal users do the Lat/Lons
    # - Special users do the Codes
    _filter = (table.lat == None)
    response.s3.filter = (query & _filter)

    # Hide unnecessary fields
    table.code.readable = table.code.writable = False # @ToDo: Role-dependent
    table.level.readable = table.level.writable = False
    table.members.readable = table.members.writable = False
    table.gis_feature_type.readable = table.gis_feature_type.writable = False
    table.wkt.readable = table.wkt.writable = False
    table.url.readable = table.url.writable = False
    table.geonames_id.readable = table.geonames_id.writable = False
    table.osm_id.readable = table.osm_id.writable = False
    table.source.readable = table.source.writable = False
    table.comments.readable = table.comments.writable = False

    # Customise Labels for specific use-cases
    #table.name.label = T("Building Name") # Building Assessments-specific
    #table.parent.label = T("Suburb") # Christchurch-specific

    # For Special users doing codes
    #table.code.label = T("Property reference in the council system") # Christchurch-specific 'prupi'
    #table.code2.label = T("Polygon reference of the rating unit") # Christchurch-specific 'gisratingid'

    # Allow prep to pass vars back to the controller
    vars = {}

    # Pre-processor
    def prep(r, vars):
        def get_location_info():
            table = s3db.gis_location
            return db(table.id == r.id).select(table.lat,
                                               table.lon,
                                               table.level,
                                               limitby=(0, 1)).first()

        if r.method in (None, "list") and r.record is None:
            # List
            pass
        elif r.method in ("delete", "search"):
            pass
        else:
            # Add Map to allow locations to be found this way
            # @ToDo: DRY with one in location()
            config = gis.get_config()
            lat = config.lat
            lon = config.lon
            zoom = config.zoom
            feature_queries = []

            if r.method == "create":
                add_feature = True
                add_feature_active = True
            else:
                if r.method == "update":
                    add_feature = True
                    add_feature_active = False
                else:
                    # Read
                    add_feature = False
                    add_feature_active = False

                try:
                    location
                except:
                    location = get_location_info()
                if location and location.lat is not None and location.lon is not None:
                    lat = location.lat
                    lon = location.lon
                # Same as a single zoom on a cluster
                zoom = zoom + 2

            # @ToDo: Does map make sense if the user is updating a group?
            # If not, maybe leave it out. OTOH, might be nice to select
            # admin regions to include in the group by clicking on them in
            # the map. Would involve boundaries...
            _map = gis.show_map(lat = lat,
                                lon = lon,
                                zoom = zoom,
                                feature_queries = feature_queries,
                                add_feature = add_feature,
                                add_feature_active = add_feature_active,
                                toolbar = True,
                                collapsed = True)

            # Pass the map back to the main controller
            vars.update(_map=_map)
        return True
    response.s3.prep = lambda r, vars=vars: prep(r, vars)

    s3mgr.configure(table._tablename,
                    listadd=False,
                    list_fields=["id",
                                 "name",
                                 "address",
                                 "parent"
                                ])

    output = s3_rest_controller("gis", "location")

    _map = vars.get("_map", None)
    if _map and isinstance(output, dict):
        output.update(_map=_map)

    return output

# =============================================================================
def geoexplorer():

    """
        Embedded GeoExplorer: https://github.com/opengeo/GeoExplorer

        This is used as a demo of GXP components which we want to pull into
        the Map Viewing Client.

        No real attempt to integrate/optimise.

        @ToDo: Get working
        If gxp is loaded in debug mode then it barfs Ext:
            ext-all-debug.js (line 10535)
                types[config.xtype || defaultType] is not a constructor
                [Break On This Error] return config.render ? con...config.xtype || defaultType](config);
        In non-debug mode, the suite breaks, but otherwise the UI loads fine & is operational.
        However no tiles are ever visible!
    """

    # @ToDo: Optimise to a single query of table
    bing_key = deployment_settings.get_gis_api_bing()
    google_key = deployment_settings.get_gis_api_google()
    yahoo_key = deployment_settings.get_gis_api_yahoo()

    # http://eden.sahanafoundation.org/wiki/BluePrintGISPrinting
    print_service = deployment_settings.get_gis_print_service()

    geoserver_url = deployment_settings.get_gis_geoserver_url()

    response.title = "GeoExplorer"
    return dict(
                #config=gis.get_config(),
                bing_key=bing_key,
                google_key=google_key,
                yahoo_key=yahoo_key,
                print_service=print_service,
                geoserver_url=geoserver_url
               )

# -----------------------------------------------------------------------------
def about():
    """  Custom View for GeoExplorer """
    return dict()

# -----------------------------------------------------------------------------
def maps():

    """
        Map Save/Publish Handler for GeoExplorer

        NB
            The models for this are currently not enabled in 03_gis.py
            This hasn't been tested at all with the new version of GeoExplorer
    """

    table = s3db.gis_wmc
    ltable = s3db.gis_wmc_layer

    if request.env.request_method == "GET":
        # This is a request to read the config of a saved map

        # Which map are we updating?
        id = request.args[0]
        if not id:
            raise HTTP(501)

        # Read the WMC record
        record = db(table.id == id).select(limitby=(0, 1)).first()
        # & linked records
        #projection = db(db.gis_projection.id == record.projection).select(limitby=(0, 1)).first()

        # Put details into the correct structure
        output = dict()
        output["map"] = dict()
        map = output["map"]
        map["center"] = [record.lat, record.lon]
        map["zoom"] = record.zoom
        # @ToDo: Read Projection (we generally use 900913 & no way to edit this yet)
        map["projection"] = "EPSG:900913"
        map["units"] = "m"
        map["maxResolution"] = 156543.0339
        map["maxExtent"] = [ -20037508.34, -20037508.34, 20037508.34, 20037508.34 ]
        # @ToDo: Read Layers
        map["layers"] = []
        #map["layers"].append(dict(source="google", title="Google Terrain", name="TERRAIN", group="background"))
        #map["layers"].append(dict(source="ol", group="background", fixed=True, type="OpenLayers.Layer", args=[ "None", {"visibility":False} ]))
        for _layer in record.layer_id:
            layer = db(ltable.id == _layer).select(limitby=(0, 1)).first()
            if layer.type_ == "OpenLayers.Layer":
                # Add args
                map["layers"].append(dict(source=layer.source,
                                          title=layer.title,
                                          name=layer.name,
                                          group=layer.group_,
                                          type=layer.type_,
                                          format=layer.img_format,
                                          visibility=layer.visibility,
                                          transparent=layer.transparent,
                                          opacity=layer.opacity,
                                          fixed=layer.fixed,
                                          args=[ "None", {"visibility":False} ]))
            else:
                map["layers"].append(dict(source=layer.source,
                                          title=layer.title,
                                          name=layer.name,
                                          group=layer.group_,
                                          type=layer.type_,
                                          format=layer.img_format,
                                          visibility=layer.visibility,
                                          transparent=layer.transparent,
                                          opacity=layer.opacity,
                                          fixed=layer.fixed))

        # @ToDo: Read Metadata (no way of editing this yet)

        # Encode as JSON
        output = json.dumps(output)

        # Output to browser
        response.headers["Content-Type"] = "application/json"
        return output

    elif request.env.request_method == "POST":
        # This is a request to save/publish a new map

        # Get the data from the POST
        source = request.body.read()
        if isinstance(source, basestring):
            import cStringIO
            source = cStringIO.StringIO(source)

        # Decode JSON
        source = json.load(source)
        # @ToDo: Projection (we generally use 900913 & no way to edit this yet)
        lat = source["map"]["center"][0]
        lon = source["map"]["center"][1]
        zoom = source["map"]["zoom"]
        # Layers
        layers = []
        for layer in source["map"]["layers"]:
            try:
                opacity = layer["opacity"]
            except:
                opacity = None
            try:
                name = layer["name"]
            except:
                name = None
            query = (ltable.source == layer["source"]) & \
                    (ltable.name == name) & \
                    (ltable.visibility == layer["visibility"]) & \
                    (ltable.opacity == opacity)
            _layer = db(query).select(ltable.id,
                                      limitby=(0, 1)).first()
            if _layer:
                # This is an existing layer
                layers.append(_layer.id)
            else:
                # This is a new layer
                try:
                    type_ = layer["type"]
                except:
                    type_ = None
                try:
                    group_ = layer["group"]
                except:
                    group_ = None
                try:
                    fixed = layer["fixed"]
                except:
                    fixed = None
                try:
                    format = layer["format"]
                except:
                    format = None
                try:
                    transparent = layer["transparent"]
                except:
                    transparent = None
                # Add a new record to the gis_wmc_layer table
                _layer = ltable.insert(source=layer["source"],
                                       name=name,
                                       visibility=layer["visibility"],
                                       opacity=opacity,
                                       type_=type_,
                                       title=layer["title"],
                                       group_=group_,
                                       fixed=fixed,
                                       transparent=transparent,
                                       img_format=format)
                layers.append(_layer)

        # @ToDo: Metadata (no way of editing this yet)

        # Save a record in the WMC table
        id = table.insert(lat=lat, lon=lon, zoom=zoom, layer_id=layers)

        # Return the ID of the saved record for the Bookmark
        output = json.dumps(dict(id=id))
        return output

    elif request.env.request_method == "PUT":
        # This is a request to save/publish an existing map

        # Which map are we updating?
        id = request.args[0]
        if not id:
            raise HTTP(501)

        # Get the data from the PUT
        source = request.body.read()
        if isinstance(source, basestring):
            import cStringIO
            source = cStringIO.StringIO(source)

        # Decode JSON
        source = json.load(source)
        # @ToDo: Projection (unlikely to change)
        lat = source["map"]["center"][0]
        lon = source["map"]["center"][1]
        zoom = source["map"]["zoom"]
        # Layers
        layers = []
        for layer in source["map"]["layers"]:
            try:
                opacity = layer["opacity"]
            except:
                opacity = None
            try:
                name = layer["name"]
            except:
                name = None
            query = (ltable.source == layer["source"]) & \
                    (ltable.name == name) & \
                    (ltable.visibility == layer["visibility"]) & \
                    (ltable.opacity == opacity)
            _layer = db(query).select(ltable.id,
                                      limitby=(0, 1)).first()
            if _layer:
                # This is an existing layer
                layers.append(_layer.id)
            else:
                # This is a new layer
                try:
                    type_ = layer["type"]
                except:
                    type_ = None
                try:
                    group_ = layer["group"]
                except:
                    group_ = None
                try:
                    fixed = layer["fixed"]
                except:
                    fixed = None
                try:
                    format = layer["format"]
                except:
                    format = None
                try:
                    transparent = layer["transparent"]
                except:
                    transparent = None
                # Add a new record to the gis_wmc_layer table
                _layer = ltable.insert(source=layer["source"],
                                       name=name,
                                       visibility=layer["visibility"],
                                       opacity=opacity,
                                       type_=type_,
                                       title=layer["title"],
                                       group_=group_,
                                       fixed=fixed,
                                       transparent=transparent,
                                       img_format=format)
                layers.append(_layer)

        # @ToDo: Metadata (no way of editing this yet)

        # Update the record in the WMC table
        db(table.id == id).update(lat=lat, lon=lon, zoom=zoom, layer_id=layers)

        # Return the ID of the saved record for the Bookmark
        output = json.dumps(dict(id=id))
        return output

    # Abort - we shouldn't get here
    raise HTTP(501)

# =============================================================================
def potlatch2():
    """
        Custom View for the Potlatch2 OpenStreetMap editor
        http://wiki.openstreetmap.org/wiki/Potlatch_2
    """

    config = gis.get_config()
    osm_oauth_consumer_key = config.osm_oauth_consumer_key
    osm_oauth_consumer_secret = config.osm_oauth_consumer_secret
    if osm_oauth_consumer_key and osm_oauth_consumer_secret:
        gpx_url = None
        if "gpx_id" in request.vars:
            # Pass in a GPX Track
            # @ToDo: Set the viewport based on the Track, if one is specified
            table = s3db.gis_layer_track
            query = (table.id == request.vars.gpx_id)
            track = db(query).select(table.track,
                                     limitby=(0, 1)).first()
            if track:
                gpx_url = "%s/%s" % (URL(c="default", f="download"),
                                     track.track)

        if "lat" in request.vars:
            lat = request.vars.lat
            lon = request.vars.lon
        else:
            lat = config.lat
            lon = config.lon

        if "zoom" in request.vars:
            zoom = request.vars.zoom
        else:
            # This isn't good as it makes for too large an area to edit
            #zoom = config.zoom
            zoom = 14

        site_name = deployment_settings.get_system_name_short()

        return dict(lat=lat, lon=lon, zoom=zoom,
                    gpx_url=gpx_url,
                    site_name=site_name,
                    key=osm_oauth_consumer_key,
                    secret=osm_oauth_consumer_secret)

    else:
        session.warning = T("To edit OpenStreetMap, you need to edit the OpenStreetMap settings in your Map Config")
        redirect(URL(c="pr", f="person",
                     args=["config"],
                     vars={"person.uid":auth.user.person_uuid}))

# =============================================================================
def proxy():
    """
    Based on http://trac.openlayers.org/browser/trunk/openlayers/examples/proxy.cgi
    This is a blind proxy that we use to get around browser
    restrictions that prevent the Javascript from loading pages not on the
    same server as the Javascript. This has several problems: it's less
    efficient, it might break some sites, and it's a security risk because
    people can use this proxy to browse the web and possibly do bad stuff
    with it. It only loads pages via http and https, but it can load any
    content type. It supports GET and POST requests.
    """

    import socket
    import urllib2
    import cgi

    # @ToDo: Link to map_service_catalogue to prevent Open Proxy abuse
    # (although less-critical since we restrict content type)
    allowedHosts = []
    #allowedHosts = ["www.openlayers.org", "demo.opengeo.org"]

    allowed_content_types = (
        "application/json", "text/json", "text/x-json",
        "application/xml", "text/xml",
        "application/vnd.ogc.se_xml",           # OGC Service Exception
        "application/vnd.ogc.se+xml",           # OGC Service Exception
        "application/vnd.ogc.success+xml",      # OGC Success (SLD Put)
        "application/vnd.ogc.wms_xml",          # WMS Capabilities
        "application/vnd.ogc.context+xml",      # WMC
        "application/vnd.ogc.gml",              # GML
        "application/vnd.ogc.sld+xml",          # SLD
        "application/vnd.google-earth.kml+xml", # KML
    )

    method = request["wsgi"].environ["REQUEST_METHOD"]

    if method == "POST":
        # This can probably use same call as GET in web2py
        qs = request["wsgi"].environ["QUERY_STRING"]

        d = cgi.parse_qs(qs)
        if d.has_key("url"):
            url = d["url"][0]
        else:
            url = "http://www.openlayers.org"
    else:
        # GET
        if "url" in request.vars:
            url = request.vars.url
        else:
            session.error = T("Need a 'url' argument!")
            raise HTTP(400, body=s3mgr.xml.json_message(False, 400, session.error))

    # Debian has no default timeout so connection can get stuck with dodgy servers
    socket.setdefaulttimeout(30)
    try:
        host = url.split("/")[2]
        if allowedHosts and not host in allowedHosts:
            raise(HTTP(403, "Host not permitted: %s" % host))

        elif url.startswith("http://") or url.startswith("https://"):
            if method == "POST":
                length = int(request["wsgi"].environ["CONTENT_LENGTH"])
                headers = {"Content-Type": request["wsgi"].environ["CONTENT_TYPE"]}
                body = request.body.read(length)
                r = urllib2.Request(url, body, headers)
                y = urllib2.urlopen(r)
            else:
                # GET
                y = urllib2.urlopen(url)

            # Check for allowed content types
            i = y.info()
            if i.has_key("Content-Type"):
                ct = i["Content-Type"]
                if not ct.split(";")[0] in allowed_content_types:
                    # @ToDo?: Allow any content type from allowed hosts (any port)
                    #if allowedHosts and not host in allowedHosts:
                    raise(HTTP(403, "Content-Type not permitted"))
            else:
                raise(HTTP(406, "Unknown Content"))

            msg = y.read()
            y.close()

            # Maintain the incoming Content-Type
            response.headers["Content-Type"] = ct
            return msg

        else:
            # Bad Request
            raise(HTTP(400))

    except Exception, E:
        raise(HTTP(500, "Some unexpected error occurred. Error text was: %s" % str(E)))

# END =========================================================================