summaryrefslogtreecommitdiff
path: root/gnowsys-ndf/gnowsys_ndf/ndf/templatetags/ndf_tags.py
blob: 3530e73fe457925b3281e09c39523ca7e860e4de (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
''' -- imports from python libraries -- '''
import re
# import magic
from collections import OrderedDict
from time import time
import json
import ox

''' -- imports from installed packages -- '''
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.http import Http404
from django.template import Library
from django.template import RequestContext,loader
from django.shortcuts import render_to_response, render

# cache imports
from django.core.cache import cache

from mongokit import paginator
from mongokit import IS

''' -- imports from application folders/files -- '''
from gnowsys_ndf.settings import GAPPS as setting_gapps, GSTUDIO_DEFAULT_GAPPS_LIST, META_TYPE, CREATE_GROUP_VISIBILITY, GSTUDIO_SITE_DEFAULT_LANGUAGE
# from gnowsys_ndf.settings import GSTUDIO_SITE_LOGO,GSTUDIO_COPYRIGHT,GSTUDIO_GIT_REPO,GSTUDIO_SITE_PRIVACY_POLICY, GSTUDIO_SITE_TERMS_OF_SERVICE,GSTUDIO_ORG_NAME,GSTUDIO_SITE_ABOUT,GSTUDIO_SITE_POWEREDBY,GSTUDIO_SITE_PARTNERS,GSTUDIO_SITE_GROUPS,GSTUDIO_SITE_CONTACT,GSTUDIO_ORG_LOGO,GSTUDIO_SITE_CONTRIBUTE,GSTUDIO_SITE_VIDEO,GSTUDIO_SITE_LANDING_PAGE
from gnowsys_ndf.settings import *
try:
	from gnowsys_ndf.local_settings import GSTUDIO_SITE_NAME
except ImportError:
	pass

from gnowsys_ndf.ndf.models import node_collection, triple_collection
from gnowsys_ndf.ndf.models import *
from gnowsys_ndf.ndf.views.methods import check_existing_group, get_gapps, get_all_resources_for_group, get_execution_time
from gnowsys_ndf.ndf.views.methods import get_drawers, get_group_name_id, cast_to_data_type
from gnowsys_ndf.mobwrite.models import TextObj
from pymongo.errors import InvalidId as invalid_id
from django.contrib.sites.models import Site

# from gnowsys_ndf.settings import LANGUAGES
# from gnowsys_ndf.settings import GSTUDIO_GROUP_AGENCY_TYPES,GSTUDIO_AUTHOR_AGENCY_TYPES

from gnowsys_ndf.ndf.node_metadata_details import schema_dict

register = Library()
at_apps_list = node_collection.one({
    "_type": "AttributeType", "name": "apps_list"
})
translation_set=[]
check=[]

@get_execution_time
@register.assignment_tag
def get_site_registration_variable_visibility(registration_variable=None):
    """Returns dictionary variable holding variables defined in settings file
    for Author's class regarding their visibility in registration template

    If looking for value of single variable, then pass that variable name as
    string which will return it's corresponding value. For example,
        bool_val = get_site_registration_variable_visibility(
            registration_variable="GSTUDIO_REGISTRATION_AUTHOR_AGENCY_TYPE"
        )

    Otherwise, if no parameter is passed, then returns a dictionary variable.
    For example,
        site_dict = get_site_registration_variable_visibility()
    In order to fetch given variable's value from above dictionay use following:
        site_registration_dict["AUTHOR_AGENCY_TYPE"]
        site_registration_dict["AFFILIATION"]
    """
    if registration_variable:
        return eval(registration_variable)

    else:
        site_registration_variable_visibility = {}
        site_registration_variable_visibility["AUTHOR_AGENCY_TYPE"] = GSTUDIO_REGISTRATION_AUTHOR_AGENCY_TYPE
        site_registration_variable_visibility["AFFILIATION"] = GSTUDIO_REGISTRATION_AFFILIATION
    return site_registration_variable_visibility


@get_execution_time
@register.assignment_tag
def get_site_variables():
	result = cache.get('site_var')

	if result:
		return result

	site_var = {}
	site_var['ORG_NAME']=GSTUDIO_ORG_NAME
	site_var['LOGO']=GSTUDIO_SITE_LOGO
	site_var['COPYRIGHT']=GSTUDIO_COPYRIGHT
	site_var['GIT_REPO']=GSTUDIO_GIT_REPO
	site_var['PRIVACY_POLICY']=GSTUDIO_SITE_PRIVACY_POLICY
	site_var['TERMS_OF_SERVICE']=GSTUDIO_SITE_TERMS_OF_SERVICE
	site_var['ORG_LOGO']=GSTUDIO_ORG_LOGO
	site_var['ABOUT']=GSTUDIO_SITE_ABOUT
	site_var['SITE_POWEREDBY']=GSTUDIO_SITE_POWEREDBY
	site_var['PARTNERS']=GSTUDIO_SITE_PARTNERS
	site_var['GROUPS']=GSTUDIO_SITE_GROUPS
	site_var['CONTACT']=GSTUDIO_SITE_CONTACT
	site_var['CONTRIBUTE']=GSTUDIO_SITE_CONTRIBUTE
	site_var['SITE_VIDEO']=GSTUDIO_SITE_VIDEO
	site_var['LANDING_PAGE']=GSTUDIO_SITE_LANDING_PAGE
	site_var['HOME_PAGE']=GSTUDIO_SITE_HOME_PAGE
	site_var['SITE_NAME']=GSTUDIO_SITE_NAME

	cache.set('site_var', site_var, 60 * 30)

	return  site_var


@get_execution_time
@register.assignment_tag
def get_author_agency_types():
   return GSTUDIO_AUTHOR_AGENCY_TYPES


@get_execution_time
@register.assignment_tag
def get_group_agency_types():
   return GSTUDIO_GROUP_AGENCY_TYPES


@get_execution_time
@register.assignment_tag
def get_licence():
   return GSTUDIO_LICENCE


@get_execution_time
@register.assignment_tag
def get_agency_type_of_group(group_id):
	'''
	Getting agency_type value of the group.
	'''
	group_obj = node_collection.one({"_id": ObjectId(group_id)})
	group_agency_type = group_obj.agency_type
	# print "group_agency_type : ", group_agency_type
	return group_agency_type


@get_execution_time
@register.assignment_tag
def get_node_type(node):
   if node:
      obj = node_collection.find_one({"_id": ObjectId(node._id)})
      nodetype=node.member_of_names_list[0]
      return nodetype
   else:
      return ""


@get_execution_time
@register.assignment_tag
def get_node(node):
    if node:
        obj = node_collection.one({"_id": ObjectId(node)})
        if obj:
            return obj
        else:
            return ""


@get_execution_time
@register.assignment_tag
def get_schema(node):
   obj = node_collection.find_one({"_id": ObjectId(node.member_of[0])}, {"name": 1})
   nam=node.member_of_names_list[0]
   if(nam == 'Page'):
        return [1,schema_dict[nam]]
   elif(nam=='File'):
	if( 'image' in node.mime_type):
		return [1,schema_dict['Image']]
        elif('video' in node.mime_type or 'Pandora_video' in node.mime_type):
        	return [1,schema_dict['Video']]
	else:
		return [1,schema_dict['Document']]	
   else:
	return [0,""]


@get_execution_time
@register.filter
def is_Page(node):
	Page = node_collection.one({"_type": "GSystemType", "name": "Page"})
	if(Page._id in node.member_of):
		return 1
	else:
		return 0


@get_execution_time
@register.filter
def is_Quiz(node):
	Quiz = node_collection.one({"_type": "GSystemType", "name": "Quiz"})
	if(Quiz._id in node.member_of):
		return 1
	else:
		return 0


@get_execution_time
@register.filter
def is_File(node):
	File = node_collection.one({"_type": "GSystemType", "name": "File"})
	if(File._id in node.member_of):
		return 1
	else:
		return 0


@get_execution_time
@register.inclusion_tag('ndf/userpreferences.html')
def get_user_preferences(group,user):
	return {'groupid':group,'author':user}


@get_execution_time
@register.assignment_tag
def get_languages():
        return LANGUAGES


@get_execution_time
@register.assignment_tag
def get_node_ratings(request,node):
        try:
                user=request.user
                node = node_collection.one({'_id': ObjectId(node._id)})
                sum=0
                dic={}
                cnt=0
                userratng=0
                tot_ratng=0
                for each in node.rating:
                     if each['user_id'] == user.id:
                             userratng=each['score']
                     if each['user_id']==0:
                             cnt=cnt+1
                     sum=sum+each['score']
                if len(node.rating)==1 and cnt==1:
                        tot_ratng=0
                        avg_ratng=0.0
                else:
                        if node.rating:
                           tot_ratng=len(node.rating)-cnt
                        if tot_ratng:
                           avg_ratng=float(sum)/tot_ratng
                        else:
                           avg_ratng=0.0
                dic['avg']=avg_ratng
                dic['tot']=tot_ratng
                dic['user_rating']=userratng
                return dic
        except Exception as e:
                print "Error in get_node_ratings "+str(e)


@get_execution_time
@register.assignment_tag
def get_group_resources(group):
	try:
		res=get_all_resources_for_group(group['_id'])
		return res.count
	except Exception as e:
		print "Error in get_group_resources "+str(e)


@get_execution_time
@register.assignment_tag
def all_gapps():
	try:
		return get_gapps()
	except Exception as expt:
		print "Error in get_gapps "+str(expt)


@get_execution_time
@register.assignment_tag
def get_create_group_visibility():
	if CREATE_GROUP_VISIBILITY:
		return True
	else:
		return False


@get_execution_time
@register.assignment_tag
def get_site_info():
	sitename = Site.objects.all()[0].name.__str__()
	return sitename


@get_execution_time
@register.assignment_tag
def check_is_user_group(group_id):
	try:
		lst_grps=[]
		all_user_grps=get_all_user_groups()
		grp = node_collection.one({'_id':ObjectId(group_id)})
		for each in all_user_grps:
			lst_grps.append(each.name)
		if grp.name in lst_grps:
			return True
		else:
			return False
	except Exception as exptn:
		print "Exception in check_user_group "+str(exptn)


@get_execution_time
@register.assignment_tag
def switch_group_conditions(user,group_id):
	try:
		ret_policy=False
		req_user_id=User.objects.get(username=user).id
		group = node_collection.one({'_id':ObjectId(group_id)})
		if req_user_id in group.author_set and group.group_type == 'PUBLIC':
			ret_policy=True
		return ret_policy
	except Exception as ex:
		print "Exception in switch_group_conditions"+str(ex)


@get_execution_time
@register.assignment_tag
def get_all_user_groups():
	try:
		all_groups = node_collection.find({'_type':'Author'}).sort('name', 1)
		return list(all_groups)
	except:
		print "Exception in get_all_user_groups"


@get_execution_time
@register.assignment_tag
def get_group_object(group_id = None):
	try:
		if group_id == None :
			group_object = node_collection.one({'$and':[{'_type':u'Group'},{'name':u'home'}]})
		else:
			group_object = node_collection.one({'_id':ObjectId(group_id)})
		return group_object
	except invalid_id:
		group_object = node_collection.one({'$and':[{'_type':u'Group'},{'name':u'home'}]})
		return group_object


@get_execution_time
@register.assignment_tag
def get_states_object(request):
   group_object = node_collection.one({'$and':[{'_type':u'Group'},{'name':u'State Partners'}]})
   return group_object


@get_execution_time
@register.simple_tag
def get_all_users_to_invite():
	try:
		inv_users = {}
		users = User.objects.all()
		for each in users:
			inv_users[each.username.__str__()] = each.id.__str__()
		return str(inv_users)
	except Exception as e:
		print str(e)


@get_execution_time
@register.assignment_tag
def get_all_users_int_count():
	'''
	get integer count of all the users
	'''
	all_users = len(User.objects.all())
	return all_users


@get_execution_time
@register.inclusion_tag('ndf/twist_replies.html')
def get_reply(request, thread,parent,forum,token,user,group_id):
	return {'request':request, 'thread':thread,'reply': parent,'user':user,'forum':forum,'csrf_token':token,'eachrep':parent,'groupid':group_id}


@get_execution_time
@register.assignment_tag
def get_all_replies(parent):
	 ex_reply=""
	 if parent:
		 ex_reply = node_collection.find({'$and':[{'_type':'GSystem'},{'prior_node':ObjectId(parent._id)}],'status':{'$nin':['HIDDEN']}})
		 ex_reply.sort('created_at',-1)
	 return ex_reply


@get_execution_time
@register.assignment_tag
def get_metadata_values():

	metadata = {"educationaluse": GSTUDIO_RESOURCES_EDUCATIONAL_USE, "interactivitytype": GSTUDIO_RESOURCES_INTERACTIVITY_TYPE, "curricular": GSTUDIO_RESOURCES_CURRICULAR,
				"educationallevel": GSTUDIO_RESOURCES_EDUCATIONAL_LEVEL, "educationalsubject": GSTUDIO_RESOURCES_EDUCATIONAL_SUBJECT, "language": GSTUDIO_RESOURCES_LANGUAGES,
				"timerequired": GSTUDIO_RESOURCES_TIME_REQUIRED, "audience": GSTUDIO_RESOURCES_AUDIENCE , "textcomplexity": GSTUDIO_RESOURCES_TEXT_COMPLEXITY,
				"age_range": GSTUDIO_RESOURCES_AGE_RANGE ,"readinglevel": GSTUDIO_RESOURCES_READING_LEVEL, "educationalalignment": GSTUDIO_RESOURCES_EDUCATIONAL_ALIGNMENT}
	return metadata


@get_execution_time
@register.assignment_tag
def get_attribute_value(node_id, attr):

	node_attr = None
	if node_id:
		node = node_collection.one({'_id': ObjectId(node_id) })
		gattr = node_collection.one({'_type': 'AttributeType', 'name': unicode(attr) })
        # print "node: ",node.name,"\n"
        # print "attr: ",attr,"\n"

		if node and gattr:
			node_attr = triple_collection.one({'_type': "GAttribute", "subject": node._id, 'attribute_type.$id': gattr._id})	

	if node_attr:
		attr_val = node_attr.object_value
	else:
		attr_val = ""

	# print "attr_val: ",attr_val,"\n"
	return attr_val


@get_execution_time
@register.inclusion_tag('ndf/drawer_widget.html')
def edit_drawer_widget(field, group_id, node=None, page_no=1, checked=None, **kwargs):
	drawers = None
	drawer1 = None
	drawer2 = None
	user_type = None

	# Special case used while dealing with RelationType widget
	left_drawer_content = None
	paged_resources = ""
	if node:
		if field == "collection":
			if checked == "Quiz":
				checked = "QuizItem"
			elif checked == "Theme":
				checked = "Theme"
			else:
				checked = None
			drawers, paged_resources = get_drawers(group_id, node._id, node.collection_set, page_no, checked)

		elif field == "prior_node":
			checked = None
			drawers, paged_resources = get_drawers(group_id, node._id, node.prior_node, checked)

		elif field == "Group":
			checked = checked
			if kwargs.has_key("user_type"):
				user_type = kwargs["user_type"]

			drawers, paged_resources = get_drawers(group_id, node._id, node.group_admin, page_no, checked)

		elif field == "module":
			checked = "Module"
			drawers, paged_resources = get_drawers(group_id, node._id, node.collection_set, checked)

		elif field == "RelationType" or field == "CourseUnits":
			# Special case used while dealing with RelationType widget
			if kwargs.has_key("left_drawer_content"):
				widget_for = checked
				checked = field
				field = widget_for
				left_drawer_content = kwargs["left_drawer_content"]

				drawers = get_drawers(group_id, nid=node["_id"], nlist=node[field], checked=checked, left_drawer_content=left_drawer_content)
		
		drawer1 = drawers['1']
		drawer2 = drawers['2']

	else:
		if field == "collection" and checked == "Quiz":
			checked = "QuizItem"

		elif field == "collection" and checked == "Theme":
			checked = "Theme"
			
		elif field == "module":
			checked = "Module"

		elif field == "RelationType" or field == "CourseUnits":
			# Special case used while dealing with RelationType widget
			if kwargs.has_key("left_drawer_content"):
				widget_for = checked
				checked = field
				field = widget_for
				left_drawer_content = kwargs["left_drawer_content"]
		else:
			# To make the collection work as Heterogenous one, by default
			checked = None

		if checked == "RelationType" or checked == "CourseUnits" :
			drawer1 = get_drawers(group_id, checked=checked, left_drawer_content=left_drawer_content)
		else:
			drawer1, paged_resources = get_drawers(group_id, page_no=page_no, checked=checked)

	return {'template': 'ndf/drawer_widget.html', 
					'widget_for': field, 'drawer1': drawer1, 'drawer2': drawer2, 'page_info': paged_resources, 
					'is_RT': checked, 'group_id': group_id, 'groupid': group_id, 'user_type': user_type 
				}


@get_execution_time
@register.inclusion_tag('tags/dummy.html')
def list_widget(fields_name, fields_type, fields_value, template1='ndf/option_widget.html',template2='ndf/drawer_widget.html'):
	drawer1 = {}
	drawer2 = None
	groupid = ""
	group_obj = node_collection.find({'$and':[{"_type":u'Group'},{"name":u'home'}]})

	if group_obj:
		groupid = str(group_obj[0]._id)

	alltypes = ["GSystemType","MetaType","AttributeType","RelationType"]

	fields_selection1 = ["subject_type","language","object_type","applicable_node_type","subject_applicable_nodetype","object_applicable_nodetype","data_type"]

	fields_selection2 = ["meta_type_set","attribute_type_set","relation_type_set","prior_node","member_of","type_of"]

	fields = {"subject_type":"GSystemType", "object_type":"GSystemType", "meta_type_set":"MetaType", "attribute_type_set":"AttributeType", "relation_type_set":"RelationType", "member_of":"MetaType", "prior_node":"all_types", "applicable_node_type":"NODE_TYPE_CHOICES", "subject_applicable_nodetype":"NODE_TYPE_CHOICES", "object_applicable_nodetype":"NODE_TYPE_CHOICES", "data_type": "DATA_TYPE_CHOICES", "type_of": "GSystemType","language":"GSystemType"}
	types = fields[fields_name]

	if fields_name in fields_selection1:
		if fields_value:
			dummy_fields_value = fields_value
			fields_value = []
			for v in dummy_fields_value:
				fields_value.append(v.__str__())

		if fields_name in ("applicable_node_type","subject_applicable_nodetype","object_applicable_nodetype"):
			for each in NODE_TYPE_CHOICES:
				drawer1[each] = each
		elif fields_name in ("data_type"):
			for each in DATA_TYPE_CHOICES:
				drawer1[each] = each
		elif fields_name in ("language"):
				drawer1['hi']='hi'
				drawer1['en']='en'
				drawer1['mar']='mar'
		else:
			#drawer = node_collection.find({"_type":types,'name':{'$nin':[u'Voluntary Teacher']}})
			drawer = node_collection.find({"_type":types})
			for each in drawer:
				drawer1[str(each._id)]=each
		return {'template': template1, 'widget_for': fields_name, 'drawer1': drawer1, 'selected_value': fields_value}

	
	if fields_name in fields_selection2:
		fields_value_id_list = []

		if fields_value:
			for each in fields_value:
				if type(each) == ObjectId:
					fields_value_id_list.append(each)
				else:
					fields_value_id_list.append(each._id)

		if types in alltypes:
			for each in node_collection.find({"_type": types}):
				if fields_value_id_list:
					if each._id not in fields_value_id_list:
						drawer1[each._id] = each
				else:
					drawer1[each._id] = each

		if types in ["all_types"]:
			for each in alltypes:
				for eachnode in node_collection.find({"_type": each}):
					if fields_value_id_list:
						if eachnode._id not in fields_value_id_list:
							drawer1[eachnode._id] = eachnode
					else:
						drawer1[eachnode._id] = eachnode

		if fields_value_id_list:
			drawer2 = []
			for each_id in fields_value_id_list:
				each_node = node_collection.one({'_id': each_id})
				if each_node:
					drawer2.append(each_node)

		return {'template': template2, 'widget_for': fields_name, 'drawer1': drawer1, 'drawer2': drawer2, 'group_id': groupid, 'groupid': groupid}


@get_execution_time
@register.assignment_tag
def shelf_allowed(node):
	page_GST = node_collection.one({'_type': 'GSystemType', 'name': 'Page'})
	file_GST = node_collection.one({'_type': 'GSystemType', 'name': 'File'})
	course_GST = node_collection.one({'_type': 'GSystemType', 'name': 'Course'})
	quiz_GST= node_collection.one({'_type': 'GSystemType', 'name': 'Quiz'})
	topic_GST = node_collection.one({'_type': 'GSystemType', 'name': 'Topic'})

	allowed_list = [page_GST._id,file_GST._id,course_GST._id,quiz_GST._id,topic_GST._id]
	if node:
		for each in node.member_of:
			if each in allowed_list :
				allowed = "True"
				return allowed


# This function is a duplicate of get_gapps_menubar and modified for the gapps_iconbar.html template to shows apps in the sidebar instead
@get_execution_time
@register.inclusion_tag('ndf/gapps_iconbar.html')
def get_gapps_iconbar(request, group_id):
    """Get GApps menu-bar
    """
    try:
    	group_name, group_id = get_group_name_id(group_id)
        selected_gapp = request.META["PATH_INFO"]
        if len(selected_gapp.split("/")) > 2:
            selected_gapp = selected_gapp.split("/")[2]
        else:
            selected_gapp = selected_gapp.split("/")[1]

        # If apps_list are set for given group
        # then list them
        # Otherwise fetch default apps list
        gapps_list = []

        group_name = ""
        group_id = ObjectId(group_id)
        # Fetch group
        group_obj = node_collection.one({
            "_id": group_id
        }, {
            "name": 1, "attribute_set.apps_list": 1, '_type': 1
        })
        if group_obj:
            group_name = group_obj.name

            # Look for list of gapps already set for group
            for attr in group_obj.attribute_set:
                if attr and "apps_list" in attr:
                    gapps_list = attr["apps_list"]
                    break
        if not gapps_list:
            # If gapps not found for group, then make use of default apps list
            gapps_list = get_gapps(default_gapp_listing=True)

        i = 0
        gapps = {}
        for node in gapps_list:
            if node:
                i += 1
                gapps[i] = {"id": node["_id"], "name": node["name"].lower()}

        if group_obj._type == "Author":
			# user_gapps = ["page", "file"]
			user_gapps = [gapp_name.lower() for gapp_name in GSTUDIO_USER_GAPPS_LIST]
			for k, v in gapps.items():
				for k1, v1 in v.items():
					if k1 == "name":
						if v1.lower() not in user_gapps:
							del gapps[k]

        return {
            "template": "ndf/gapps_iconbar.html",
            "request": request,
            "groupid": group_id, "group_name_tag": group_name,
            "gapps": gapps, "selectedGapp": selected_gapp
        }

    except invalid_id:
        gpid = node_collection.one({
            "_type": u"Group"
        }, {
            "name": u"home"
        })
        group_id = gpid._id
        return {
            'template': 'ndf/gapps_iconbar.html',
            'request': request, 'gapps': gapps, 'selectedGapp': selected_gapp,
            'groupid': group_id
        }


@get_execution_time
@register.assignment_tag
def get_nroer_menu(request, group_name):

	gapps = GSTUDIO_NROER_GAPPS

	url_str = request.META["PATH_INFO"]
	url_split = url_str.split("/")

	# removing "" in the url_split
	url_split = filter(lambda x: x != "", url_split)
	# print "url_split : ", url_split

	nroer_menu_dict = {}
	top_menu_selected = ""
	selected_gapp = ""

	if (len(url_split) > 1) and (url_split[1] != "dashboard"):
		selected_gapp = url_split[1]  # expecting e-library etc. type of extract

		# handling conditions of "e-library" = "file" and vice-versa.
		selected_gapp = "e-library" if (selected_gapp == "file") else selected_gapp

		# for deciding/confirming selected gapp
		for each_gapp in gapps:
			temp_val = each_gapp.values()[0]
			if temp_val == selected_gapp:
				nroer_menu_dict["selected_gapp"] = temp_val
				break

		# print "selected_gapp : ", selected_gapp
	if (selected_gapp == "partner") and (len(url_split) > 2) and (url_split[2] in ["Partners", "Groups"]):
		top_menu_selected = url_split[2]

	mapping = GSTUDIO_NROER_MENU_MAPPINGS

	# deciding "top level menu selection"
	if ((group_name == "home") and nroer_menu_dict.has_key("selected_gapp")) or (selected_gapp == "repository"):
		top_menu_selected = "Repository"
		# print top_menu_selected
		
	elif (group_name in mapping.values()):
		sub_menu_selected = mapping.keys()[mapping.values().index(group_name)]  # get key of/from mapping
		nroer_menu_dict["sub_menu_selected"] = sub_menu_selected

		# with help of sub_menu_selected get it's parent from GSTUDIO_NROER_MENU
		top_menu_selected = [i.keys()[0] for i in GSTUDIO_NROER_MENU[1:] if sub_menu_selected in i.values()[0]][0]
		# for Partners, "Curated Zone" should not appear
		gapps = gapps[1:] if (top_menu_selected in ["Partners", "Groups"]) else gapps
		
	elif (len(url_split) >= 3) and ("nroer_groups" in url_split) and (url_split[2] in [i.keys()[0] for i in GSTUDIO_NROER_MENU[1:]]):
		# print "top_menu_selected ", top_menu_selected
		top_menu_selected = url_split[2]
		gapps = ""
	# elif - put this for sub groups. Needs to fire queries etc. for future perspective.

	nroer_menu_dict["gapps"] = gapps
	nroer_menu_dict["top_menu_selected"] = top_menu_selected
	nroer_menu_dict["mapping"] = mapping
	nroer_menu_dict["top_menus"] = GSTUDIO_NROER_MENU[1:]

	# print "nroer_menu_dict : ", nroer_menu_dict
	return nroer_menu_dict
# ---------- END of get_nroer_menu -----------


@get_execution_time
@register.assignment_tag
def get_site_name_from_settings():
	# print "GSTUDIO_SITE_NAME : ", GSTUDIO_SITE_NAME
	# print "site name",GSTUDIO_SITE_NAME
	return GSTUDIO_SITE_NAME


global_thread_rep_counter = 0	# global variable to count thread's total reply
global_thread_latest_reply = {"content_org":"", "last_update":"", "user":""}
@get_execution_time
def thread_reply_count( oid ):
	'''
	Method to count total replies for the thread.
	'''
	thr_rep = node_collection.find({'$and':[{'_type':'GSystem'},{'prior_node':ObjectId(oid)}],'status':{'$nin':['HIDDEN']}})
	global global_thread_rep_counter		# to acces global_thread_rep_counter as global and not as local, 
	global global_thread_latest_reply

	if thr_rep and (thr_rep.count() > 0):
		for each in thr_rep:

			global_thread_rep_counter += 1

			if not global_thread_latest_reply["content_org"]:
				global_thread_latest_reply["content_org"] = each.content_org
				global_thread_latest_reply["last_update"] = each.last_update
				global_thread_latest_reply["user"] = User.objects.get(pk=each.created_by).username
			else:
				if global_thread_latest_reply["last_update"] < each.last_update:
					global_thread_latest_reply["content_org"] = each.content_org
					global_thread_latest_reply["last_update"] = each.last_update
					global_thread_latest_reply["user"] = User.objects.get(pk=each.created_by).username
					
			thread_reply_count(each._id)
	
	return global_thread_rep_counter


# To get all the discussion replies
# global variable to count thread's total reply
# global_disc_rep_counter = 0	
# global_disc_all_replies = []
reply_st = node_collection.one({ '_type':'GSystemType', 'name':'Reply'})
@get_execution_time
@register.assignment_tag
def get_disc_replies( oid, group_id, global_disc_all_replies, level=1 ):
	'''
	Method to count total replies for the disc.
	'''

	ins_objectid  = ObjectId()
	if ins_objectid.is_valid(group_id) is False:
		group_ins = node_collection.find_one({'_type': "Group","name": group_id})
        # auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
		if group_ins:
			group_id = str(group_ins._id)
		else:
			auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
			if auth :
				group_id = str(auth._id)
	else:
		pass

	# thr_rep = node_collection.find({'$and':[ {'_type':'GSystem'}, {'prior_node':ObjectId(oid)}, {'member_of':ObjectId(reply_st._id)} ]})#.sort({'created_at': -1})
	thr_rep = node_collection.find({'_type':'GSystem', 'group_set':ObjectId(group_id), 'prior_node':ObjectId(oid), 'member_of':ObjectId(reply_st._id)}).sort('created_at', -1)

	# to acces global_disc_rep_counter as global and not as local
	# global global_disc_rep_counter 
	# global global_disc_all_replies

	if thr_rep and (thr_rep.count() > 0):

		for each in thr_rep:

			# print "\n\n",each.created_at
			# if level == 1:
			# 	global_disc_all_replies = temp_list + global_disc_all_replies
			# 	temp_list = []

			# global_disc_rep_counter += 1
			temp_disc_reply = {"content":"", "last_update":"", "user":"", "oid":"", "prior_node":""}

			temp_disc_reply["HTMLcontent"] = each.content
			temp_disc_reply["ORGcontent"] = each.content_org
			temp_disc_reply["last_update"] = each.last_update
			temp_disc_reply["username"] = User.objects.get(pk=each.created_by).username
			temp_disc_reply["userid"] = int(each.created_by)
			temp_disc_reply["oid"] = str(each._id)
			temp_disc_reply["prior_node"] = str(each.prior_node[0])
			temp_disc_reply["level"] = level

			# to avoid redundancy of dicts, it checks if any 'oid' is not equals to each._id. Then only append to list
			if not any( d['oid'] == str(each._id) for d in global_disc_all_replies ):
				if type(global_disc_all_replies) == str:
					global_disc_all_replies = list(global_disc_all_replies)
				global_disc_all_replies.append(temp_disc_reply)
				# global_disc_all_replies.insert(0, temp_disc_reply)
				# temp_list.append(temp_disc_reply)
				# print "\n\n", temp_list
								
			# print "\n\n---- : ", level, " : ", each.content_org, temp_disc_reply
			# get_disc_replies(each._id, (level+1), temp_list)
			get_disc_replies(each._id, group_id, global_disc_all_replies, (level+1) )
	
	# print global_disc_all_replies
	return global_disc_all_replies
# global_disc_all_replies = []

	
@get_execution_time
@register.assignment_tag
def get_forum_twists(forum):
	ret_replies = []
	exstng_reply = node_collection.find({'$and':[{'_type':'GSystem'},{'prior_node':ObjectId(forum._id)}],'status':{'$nin':['HIDDEN']}})
	exstng_reply.sort('created_at')
	global global_thread_rep_counter 		# to acces global global_thread_rep_counter and reset it to zero
	global global_thread_latest_reply
	# for loop to get count of each thread's total reply
	for each in exstng_reply:
		global_thread_rep_counter = 0		# reset global_thread_rep_counter to zero
		global_thread_latest_reply = {"content_org":"", "last_update":"", "user":""}

		# as each thread is dict, adding one more field of thread_reply_count
		each['thread_reply_count'] = thread_reply_count(each._id)
		each['latest_reply'] = global_thread_latest_reply
		ret_replies.append(each)
	return ret_replies


lp=[]
@get_execution_time
def get_rec_objs(ob_id):
	lp.append(ob_id)
	exstng_reply = node_collection.find({'$and':[{'_type':'GSystem'},{'prior_node':ObjectId(ob_id)}]})
	for each in exstng_reply:
		get_rec_objs(each)
	return lp


@get_execution_time
@register.assignment_tag
def get_twist_replies(twist):
	ret_replies={}
	entries=[]
	exstng_reply = node_collection.find({'$and':[{'_type':'GSystem'},{'prior_node':ObjectId(twist._id)}]})
	for each in exstng_reply:
		lst=get_rec_objs(each)
	return ret_replies


@get_execution_time
@register.assignment_tag
def check_user_join(request,group_id):
	if not request.user:
		return "null"
	user=request.user
	usern=User.objects.filter(username=user)
	if usern:
		usern=User.objects.get(username=user)
		user_id=usern.id
	else:
		return "null"
	if group_id == '/home/'or group_id == "":
		colg = node_collection.one({'$and':[{'_type':u'Group'},{'name':u'home'}]})
	else:
		colg = node_collection.one({'_id':ObjectId(group_id)})
	if colg:
		if colg.created_by == user_id:
			return "author"
		if colg.author_set:
			if user_id in colg.group_admin or user_id in colg.author_set:
				return "joined"
			else:
				return "not"
		else:
			return "not"
	else:
		return "nullobj"
	

@get_execution_time
@register.assignment_tag
def check_group(group_id):
	if group_id:
		fl = check_existing_group(group_id)
		return fl
	else:
		return ""


@get_execution_time
@register.assignment_tag
def get_existing_groups():
	group = []
	colg = node_collection.find({'_type': u'Group'})
	colg.sort('name')
	gr = list(colg)
	for items in gr:
		if items.name:
			group.append(items)
	return group


@get_execution_time
@register.assignment_tag
def get_existing_groups_excluding_username():
	group = []
	user_list=[]
	users=User.objects.all()
	for each in users:
		user_list.append(each.username)
	colg = node_collection.find({'$and':[{'_type': u'Group'},{'name':{'$nin':user_list}}]})
	colg.sort('name')
	gr = list(colg)
	for items in gr:
		if items.name:
			group.append(items)
	return group


@get_execution_time
@register.assignment_tag
def get_existing_groups_excluded(grname):
  """
  Returns only first 10 public group(s) (sorted by last_update field in descending order) 
  excluding the currently selected group if it comes under the searching criteria

  Keyword arguments:
  grname -- name of the group which is currently selected

  Returns:
  list of group node(s) resulted after given searching criteria
  """
  group_cur = node_collection.find({'_type':u"Group", 'name': {'$nin': [u"home", grname]}, 'group_type': "PUBLIC"}).sort('last_update', -1).limit(10)

  if group_cur.count() <= 0:
    return "None"

  return group_cur


@get_execution_time
@register.assignment_tag
def get_group_policy(group_id,user):
	try:
		policy = ""
		colg = node_collection.one({'_id':ObjectId(group_id)})
		if colg:
			policy = str(colg.subscription_policy)
	except:
		pass
	return policy


@get_execution_time
@register.assignment_tag
def get_user_group(user, selected_group_name):
  """
  Returns first 10 group(s) to which logged-in user is subscribed to (sorted by last_update field in descending order) 
  excluding the currently selected group if it comes under the searching criteria

  Keyword arguments:
  user -- django's user object

  selected_group_name -- name of the group which is currently selected

  Returns:
  list of group and/or author (logged-in) node(s) resulted after given searching criteria
  """
  group_list = []
  auth_group = None
  
  group_cur = node_collection.find({'_type': "Group", 'name': {'$nin': ["home", selected_group_name]}, 
  									'$or': [{'group_admin': user.id}, {'author_set': user.id}],
  								}).sort('last_update', -1).limit(9)

  auth_group = node_collection.one({'_type': "Author", '$and': [{'name': unicode(user.username)}, {'name': {'$ne': selected_group_name}}]})

  if group_cur.count():
    for g in group_cur:
      group_list.append(g)

  if auth_group:
    # Appends author node at the bottom of the list, if it exists
    group_list.append(auth_group)

  if not group_list:
    return "None"

  return group_list


@get_execution_time
@register.assignment_tag
def get_profile_pic(user_pk):
    """
    This returns file document if exists, otherwise None value.
    """
    profile_pic_image = None
    ID = int(user_pk)
    auth = node_collection.one({'_type': "Author", 'created_by': ID}, {'_id': 1, 'relation_set': 1})

    if auth:
        for each in auth.relation_set:
            if "has_profile_pic" in each:
                profile_pic_image = node_collection.one(
                    {'_type': "File", '_id': each["has_profile_pic"][0]}
                )

                break

    return profile_pic_image


@get_execution_time
@register.assignment_tag
def get_theme_node(groupid, node):

	topic_GST = node_collection.one({'_type': 'GSystemType', 'name': 'Topic'})
	theme_GST = node_collection.one({'_type': 'GSystemType', 'name': 'Theme'})
	theme_item_GST = node_collection.one({'_type': 'GSystemType', 'name': 'theme_item'})

	# code for finding nodes collection has only topic instances or not
	# It checks if first element in collection is theme instance or topic instance accordingly provide checks
	if node.collection_set:
		collection_nodes = node_collection.one({'_id': ObjectId(node.collection_set[0]) })
		if theme_GST._id in collection_nodes.member_of:
			return "Theme_Enabled"
		if theme_item_GST._id in collection_nodes.member_of:
			return "Theme_Item_Enabled"
		if topic_GST._id in collection_nodes.member_of:
			return "Topic_Enabled"
		
	else:
		return True


# @register.assignment_tag
# def get_group_name(val):
#          GroupName = []

# 	 for each in val.group_set: 

# 		grpName = node_collection.one({'_id': ObjectId(each) }).name.__str__()
# 		GroupName.append(grpName)
# 	 return GroupName


@get_execution_time
@register.assignment_tag
def get_edit_url(groupid):

	node = node_collection.one({'_id': ObjectId(groupid) }) 
	if node._type == 'GSystem':

		type_name = node_collection.one({'_id': node.member_of[0]}).name
                
		if type_name == 'Quiz':
			return 'quiz_edit'    
		elif type_name == 'Page':
			return 'page_create_edit' 
		elif type_name == 'Term':
			return 'term_create_edit' 
		elif type_name == 'Theme' or type_name == 'Topic':
			return 'theme_topic_create'
		elif type_name == 'QuizItem':
			return 'quiz_item_edit'
                elif type_name == 'Forum':
                        return 'edit_forum'
                elif type_name == 'Twist' or type_name == 'Thread':
                        return 'edit_thread'


	elif node._type == 'Group' or node._type == 'Author' :
		return 'edit_group'

	elif node._type == 'File':
		if node.mime_type == 'video':      
			return 'video_edit'       
		elif 'image' in node.mime_type:
			return 'image_edit'
		else:
			return 'file_edit'

@get_execution_time
@register.assignment_tag
def get_event_type(node):
    event = node_collection.one({'_id':{'$in':node.member_of}})
    return event._id

@get_execution_time
@register.assignment_tag
def get_url(groupid):
     
    node = node_collection.one({'_id': ObjectId(groupid) }) 
    
    if node._type == 'GSystem':

		type_name = node_collection.one({'_id': node.member_of[0]})
                if type_name.name == 'Exam' or type_name.name == "Classroom Session":
                   return ('event_app_instance_detail')
                if type_name.name == 'Quiz':
                   return 'quiz_details'
                elif type_name.name == 'Page':
                   return 'page_details' 
                elif type_name.name == 'Theme' or type_name == 'theme_item':
                   return 'theme_page'
                elif type_name.name == 'Forum':
	                 return 'show'
                elif type_name.name == 'Task' or type_name.name == 'task_update_history':
	                 return 'task_details'
                else:
	                  return 'None'    
    elif node._type == 'Group' :
                    return 'group'
    elif node._type == 'File':
		if (node.mime_type) == ("application/octet-stream"): 
			return 'video_detail'       
		elif 'image' in node.mime_type:
			return 'file_detail'
		else:
			return 'file_detail'
    else:
			return 'group'

@get_execution_time
@register.assignment_tag
def get_create_url(groupid):

  node = node_collection.one({'_id': ObjectId(groupid) }) 
  if node._type == 'GSystem':

    type_name = node_collection.one({'_id': node.member_of[0]}).name

    if type_name == 'Quiz':
      return 'quiz_create'    
    elif type_name == 'Page':
      return 'page_create_edit' 
    elif type_name == 'Term':
      return 'term_create_edit' 
    elif type_name == 'Theme' or type_name == 'Topic':
		return 'theme_topic_create'
    elif type_name == 'QuizItem':
      return 'quiz_item_create'

  elif node._type == 'Group' or node._type == 'Author' :
    return 'create_group'

  elif node._type == 'File':
    return 'uploadDoc'
	
@get_execution_time
@register.assignment_tag
def get_prior_node(node_id):

	obj = node_collection.one({'_id':ObjectId(node_id) })
	prior = []
	topic_GST = node_collection.one({'_type': 'GSystemType', 'name': 'Topic'})
	if topic_GST._id in obj.member_of:

		if obj.prior_node:
			for each in obj.prior_node:
				node = node_collection.one({'_id': ObjectId(each) })
				prior.append(( node._id , node.name ))

		return prior

	return prior


# method fist get all possible translations associated with current node &
# return the set of resources by using get_resources method
@get_execution_time
@register.assignment_tag
def get_all_resources(request,node_id):
        obj_set=[]
        keys=[] # set of keys used for creating the fieldset in template
        result_set=[]
        node=node_collection.one({'_id':ObjectId(node_id)})
        result_set=get_possible_translations(node)
        if node._id not in obj_set:
                obj_set.append(node._id)
                for item in result_set:
                        obj_set.extend(item.keys())
        resources={'Images':[],'Documents':[],'Audios':[],'Videos':[],'Interactives':[], 'eBooks':[]}
        for each in obj_set:
                n=node_collection.one({'_id':ObjectId(each)})
                resources_dict=get_resources(each,resources)
        res_dict={'Images':[],'Documents':[],'Audios':[],'Videos':[],'Interactives':[], 'eBooks':[]}
        
        for k,v in res_dict.items():
                res_dict[k]={'fallback_lang':[],'other_languages':[]}
        for key,val in resources_dict.items():
                if val:
                        keys.append(key)
                        for res in val:
                                if res.language == request.LANGUAGE_CODE:
                                        res_dict[key]['fallback_lang'].append(res)
                                else:
                                        res_dict[key]['other_languages'].append(res)
                                        
        for k1,v1 in res_dict.items():
                if k1 not in keys :
                        del res_dict[k1]
        return res_dict
# method returns resources associated with node
@get_execution_time
@register.assignment_tag
def get_resources(node_id,resources):
    	node = node_collection.one({'_id': ObjectId(node_id)})
        RT_teaches = node_collection.one({'_type':'RelationType', 'name': 'teaches'})
        RT_translation_of = node_collection.one({'_type':'RelationType','name': 'translation_of'})
        teaches_grelations = triple_collection.find({'_type': 'GRelation', 'right_subject': node._id, 'relation_type.$id': RT_teaches._id })
        AT_educationaluse = node_collection.one({'_type': 'AttributeType', 'name': u'educationaluse'})
        for each in teaches_grelations:
                obj=node_collection.one({'_id':ObjectId(each.subject)}) 
                mime_type=triple_collection.one({'_type': "GAttribute", 'attribute_type.$id': AT_educationaluse._id, "subject":each.subject})       
                for k,v in resources.items():
                        if mime_type.object_value == k:
                                if obj.name not in resources[k]:
                                        resources.setdefault(k,[]).append(obj)
    
        return resources


@get_execution_time
@register.assignment_tag
def get_contents(node_id, selected=None, choice=None):

	contents = {}
	image_contents = []
	video_contents = []
	document_contents = []
	page_contents = []
	audio_contents = []
	interactive_contents = []
	ebook_contents = []
	name = ""
	ob_id = ""

	# print "node_id:",node_id,"\n"
	obj = node_collection.one({'_id': ObjectId(node_id) })

	RT_teaches = node_collection.one({'_type':'RelationType', 'name': 'teaches'})
	RT_translation_of = node_collection.one({'_type':'RelationType','name': 'translation_of'})

	# "right_subject" is the translated node hence to find those relations which has translated nodes with RT 'translation_of'
	# These are populated when translated topic clicked.
	trans_grelations = triple_collection.find({'_type':'GRelation','right_subject':obj._id,'relation_type.$id':RT_translation_of._id })               
	# If translated topic then, choose its subject value since subject value is the original topic node for which resources are attached with RT teaches. 
	if trans_grelations.count() > 0:
		obj = node_collection.one({'_id': ObjectId(trans_grelations[0].subject)})

	# If no translated topic then, take the "obj" value mentioned above which is original topic node for which resources are attached with RT teaches
	list_grelations = triple_collection.find({'_type': 'GRelation', 'right_subject': obj._id, 'relation_type.$id': RT_teaches._id })

	for rel in list_grelations:
		rel_obj = node_collection.one({'_id': ObjectId(rel.subject)})

		if rel_obj._type == "File":
			gattr = node_collection.one({'_type': 'AttributeType', 'name': u'educationaluse'})
			# list_gattr = triple_collection.find({'_type': "GAttribute", 'attribute_type.$id': gattr._id, "subject":rel_obj._id, 'object_value': selected })
			list_gattr = triple_collection.find({'_type': "GAttribute", 'attribute_type.$id': gattr._id, "subject":rel_obj._id })

			for attr in list_gattr:
				left_obj = node_collection.one({'_id': ObjectId(attr.subject) })
				
				if selected and left_obj and selected != "language":
					AT = node_collection.one({'_type':'AttributeType', 'name': unicode(selected) })
					att = cast_to_data_type(choice, AT.data_type)
					attr_dict = {unicode(selected): att}

					for m in left_obj.attribute_set:
						if attr_dict == m:

							name = str(left_obj.name)
							ob_id = str(left_obj._id)

							if attr.object_value == "Images":
								image_contents.append((name, ob_id))
							elif attr.object_value == "Videos":
								video_contents.append((name, ob_id))
							elif attr.object_value == "Audios":
								audio_contents.append((name, ob_id))
							elif attr.object_value == "Interactives":
								interactive_contents.append((name, ob_id))
							elif attr.object_value == "Documents":
								document_contents.append((name, ob_id))
							elif attr.object_value == "eBooks":
								ebook_contents.append((name, ob_id))

				else:
					if not selected or choice == left_obj.language:
						name = str(left_obj.name)
						ob_id = str(left_obj._id)

						if attr.object_value == "Images":
							image_contents.append((name, ob_id))
						elif attr.object_value == "Videos":
							video_contents.append((name, ob_id))
						elif attr.object_value == "Audios":
							audio_contents.append((name, ob_id))
						elif attr.object_value == "Interactives":
							interactive_contents.append((name, ob_id))
						elif attr.object_value == "Documents":
							document_contents.append((name, ob_id))
						elif attr.object_value == "eBooks":
								ebook_contents.append((name, ob_id))

							
	if image_contents:
		contents['Images'] = image_contents
	
	if video_contents:
		contents['Videos'] = video_contents

	if audio_contents:
		contents['Audios'] = audio_contents		
	
	if document_contents:
		contents['Documents'] = document_contents
	
	if interactive_contents:
		contents['Interactives'] = interactive_contents

	if ebook_contents:
		contents['eBooks'] = ebook_contents
	
	# print "\n",contents,"\n"
	return contents
	

@get_execution_time
@register.assignment_tag
def get_topic_res_count(node_id):
	'''
	This function returns the count of resources holding by topic
	'''
	contents = {}
	image_contents = []
	video_contents = []
	document_contents = []
	page_contents = []
	audio_contents = []
	interactive_contents = []
	name = ""
	ob_id = ""

	# print "node_id: ",node_id,"\n"
	obj = node_collection.one({'_id': ObjectId(node_id) })

	RT_teaches = node_collection.one({'_type':'RelationType', 'name': 'teaches'})

	if obj.language == u"hi":
		# "right_subject" is the translated node hence to find those relations which has translated nodes with RT 'translation_of'
		# These are populated when translated topic clicked.
		trans_grelations = triple_collection.find({'_type':'GRelation','right_subject':obj._id,'relation_type.$id':RT_translation_of._id })               
		# If translated topic then, choose its subject value since subject value is the original topic node for which resources are attached with RT teaches. 
		if trans_grelations.count() > 0:
			obj = node_collection.one({'_id': ObjectId(trans_grelations[0].subject)})

	# If no translated topic then, take the "obj" value mentioned above which is original topic node for which resources are attached with RT teaches
	list_grelations = triple_collection.find({'_type': 'GRelation', 'right_subject': obj._id, 'relation_type.$id': RT_teaches._id })

	count = list_grelations.count()


	# print "count: ",count,"\n"
	return count


@get_execution_time
@register.assignment_tag
def get_teaches_list(node):
	
	teaches_list = []
	if node:
		relationtype = node_collection.one({"_type":"RelationType","name":"teaches"})
        list_grelations = triple_collection.find({"_type":"GRelation","subject":node._id,"relation_type":relationtype.get_dbref()})
        for relation in list_grelations:
        	obj = node_collection.one({'_id': ObjectId(relation.right_subject) })
          	teaches_list.append(obj)

	return teaches_list

@get_execution_time
@register.assignment_tag
def get_assesses_list(node):
	
	assesses_list = []
	if node:
		relationtype = node_collection.one({"_type":"RelationType","name":"assesses"})
        list_grelations = triple_collection.find({"_type":"GRelation","subject":node._id,"relation_type":relationtype.get_dbref()})
        for relation in list_grelations:
        	obj = node_collection.one({'_id': ObjectId(relation.right_subject) })
          	assesses_list.append(obj)

	return assesses_list

@get_execution_time
@register.assignment_tag
def get_group_type(group_id, user):
    """This function checks for url's authenticity

    """
    try:
        # Splitting url-content based on backward-slashes
        split_content = group_id.strip().split("/")
        
        # Holds primary key, group's ObjectId or group's name
        g_id = ""
        if split_content[0] != "":
            g_id = split_content[0]
        else:
            g_id = split_content[1]

        group_node = None

        if g_id.isdigit() and 'dashboard' in group_id:
            # User Dashboard url found
            u_id = int(g_id)
            user_obj = User.objects.get(pk=u_id)

            if not user_obj.is_active:
                error_message = "\n Something went wrong: Either url is invalid or such group/user doesn't exists !!!\n"
                raise Http404(error_message)

        else:
            # Group's url found
            if ObjectId.is_valid(g_id):
                # Group's ObjectId found
                group_node = node_collection.one({'_type': {'$in': ["Group", "Author"]}, '_id': ObjectId(g_id)})

            else:
                # Group's name found
                group_node = node_collection.one({'_type': {'$in': ["Group", "Author"]}, 'name': g_id})

            if group_node:
                # Check whether Group is PUBLIC or not
                if not group_node.group_type == u"PUBLIC":
                    # If Group other than Public one is found

                    if user.is_authenticated():
                        # Check for user's authenticity & accessibility of the group
                        if user.is_superuser or group_node.created_by == user.id or user.id in group_node.group_admin or user.id in group_node.author_set:
                            pass

                        else:
                            error_message = "\n Something went wrong: Either url is invalid or such group/user doesn't exists !!!\n"
                            raise Http404(error_message)

                    else:
                        # Anonymous user found which cannot access groups other than Public
                        error_message = "\n Something went wrong: Either url is invalid or such group/user doesn't exists !!!\n"
                        raise Http404(error_message)

            else:
                # If Group is not found with either given ObjectId or name in the database
                # Then compare with a given list of names as these were used in one of the urls
                # And still no match found, throw error
                if g_id not in ["online", "i18n", "raw", "r", "m", "t", "new", "mobwrite", "admin", "benchmarker", "accounts", "Beta", "welcome"]:
                    error_message = "\n Something went wrong: Either url is invalid or such group/user doesn't exists !!!\n"
                    raise Http404(error_message)

        return True

    except Exception as e:
        raise Http404(e)


@get_execution_time
@register.assignment_tag
def get_possible_group_type_values():
	'''
	Returns TYPES_OF_GROUP defined in models.py 
	'''
	return TYPES_OF_GROUP


@get_execution_time
@register.assignment_tag
def get_possible_edit_policy_values():
	'''
	Returns EDIT_POLICY defined in models.py 
	'''
	return EDIT_POLICY


@get_execution_time
@register.assignment_tag
def get_allowed_moderation_levels():
	'''
	Returns GSTUDIO_ALLOWED_GROUP_MODERATION_LEVELS from settings.
	'''
	return GSTUDIO_ALLOWED_GROUP_MODERATION_LEVELS


@get_execution_time
@register.assignment_tag
def check_accounts_url(url_path):
	'''
	Checks whether the given path is of accounts related or not
	Accounts means regarding account's registrtion/activation, 
	login/logout or password-reset and all!

	Arguments:
	path -- Visited url by the user taken from request object

	Returns:
	A boolean value indicating the same
	'''
	if "accounts" in url_path and "/group" not in url_path:
		return True

	else:
		return False


'''this template function is used to get the user object from template''' 
@get_execution_time
@register.assignment_tag 
def get_user_object(user_id):
	user_obj=""
	try:
		user_obj=User.objects.get(id=user_id)
	except Exception as e:
		print "User Not found in User Table",e
	return user_obj

@get_execution_time
@register.assignment_tag
def get_grid_fs_object(f):
    """
    Get the gridfs object by object id
    """
    grid_fs_obj = ""
    try:
        file_obj = node_collection.one({
            '_id': ObjectId(f['_id'])
        })
        if file_obj.mime_type == 'video':
            if len(file_obj.fs_file_ids) > 2:
                if (file_obj.fs.files.exists(file_obj.fs_file_ids[2])):
                    grid_fs_obj = file_obj.fs.files.get(ObjectId(file_obj.fs_file_ids[2]))
        else:
            grid_fs_obj = file_obj.fs.files.get(file_obj.fs_file_ids[0])
    except Exception as e:
        print "Object does not exist", e

    return grid_fs_obj

@get_execution_time
@register.inclusion_tag('ndf/admin_class.html')
def get_class_list(group_id,class_name):
	"""Get list of class 
	"""
	class_list = ["GSystem", "File", "Group", "GSystemType", "RelationType", "AttributeType", "MetaType", "GRelation", "GAttribute"]
	return {'template': 'ndf/admin_class.html', "class_list": class_list, "class_name":class_name,"url":"data","groupid":group_id}


@get_execution_time
@register.inclusion_tag('ndf/admin_class.html')
def get_class_type_list(group_id,class_name):
	"""Get list of class 
	"""
	class_list = ["GSystemType", "RelationType", "AttributeType"]
	return {'template': 'ndf/admin_class.html', "class_list": class_list, "class_name":class_name,"url":"designer","groupid":group_id}

@get_execution_time
@register.assignment_tag
def get_Object_count(key):
		try:
				return node_collection.find({'_type':key}).count()
		except:
				return 'null'

@get_execution_time
@register.assignment_tag
def get_memberof_objects_count(key,group_id):
	try:
		return node_collection.find({'member_of': {'$all': [ObjectId(key)]},'group_set': {'$all': [ObjectId(group_id)]}}).count()
	except:
		return 'null'


'''Pass the ObjectId and get the name of it's first member_of element'''
@get_execution_time
@register.assignment_tag
def get_memberof_name(node_id):
	try:
		node_obj = node_collection.one({'_id': ObjectId(node_id)})
		member_of_name = ""
		if node_obj.member_of:
			member_of_name = node_collection.one({'_id': ObjectId(node_obj.member_of[0]) }).name
		return member_of_name
	except:
		return 'null'

@get_execution_time
@register.filter
def get_dict_item(dictionary, key):
	return dictionary.get(key)


@get_execution_time
@register.assignment_tag
def get_policy(group, user):
  if group.group_type =='PUBLIC':
    return False
  elif user.is_superuser:
    return True
  elif user.id in group.author_set:
    return True
  elif user.id == group.created_by:
    return True
  else:
    return False


@get_execution_time
@register.inclusion_tag('ndf/admin_fields.html')
def get_input_fields(fields_type,fields_name,translate=None):
	"""Get html tags 
	"""
	field_type_list = ["meta_type_set","attribute_type_set","relation_type_set","prior_node","member_of","type_of"]
	return {'template': 'ndf/admin_fields.html', 
					"fields_name":fields_name, "fields_type": fields_type[0], "fields_value": fields_type[1], 
					"field_type_list":field_type_list,"translate":translate}
	

@get_execution_time
@register.assignment_tag
def group_type_info(groupid,user=0):

	cache_key = "group_type_" + str(groupid)
	cache_result = cache.get(cache_key)

	if cache_result:
		return cache_result

	group_gst = node_collection.one({'_id': ObjectId(groupid)},
		{'post_node': 1, 'prior_node': 1, 'group_type': 1})
	
	group_type = ""

	if group_gst.post_node:
		group_type = "BaseModerated"
	elif group_gst.prior_node:
		group_type = "Moderated"
	else:
		group_type = group_gst.group_type

	if cache_result != group_type:
		cache.set(cache_key, group_type)

	return group_type


@get_execution_time			
@register.assignment_tag
def user_access_policy(node, user):
  """
  Returns status whether logged-in user is able to access any resource.

  Check is performed in given sequence as follows (sequence has importance):
  - If user is superuser, then he/she is allowed
  - Else if user is creator or admin of the group, then he/she is allowed
  - Else if group's edit-policy is "NON_EDITABLE" (currently "home" is such group), then user is NOT allowed
  - Else if user is member of the group, then he/she is allowed
  - Else user is NOT allowed!

  Arguments:
  node -- group's node that is currently selected by the user_access
  user -- user's node that is currently logged-in

  Returns:
  string value (allow/disallow), i.e. whether user is allowed or not!
  """
  user_access = False

  try:
  	# Please make a note, here the order in which check is performed is IMPORTANT!

    if user.is_superuser:
      user_access = True

    else:
      # group_node = node_collection.one({'_type': {'$in': ["Group", "Author"]}, '_id': ObjectId(node)})
      group_name, group_id = get_group_name_id(node)
      group_node = node_collection.one({"_id": ObjectId(group_id)})

      if user.id == group_node.created_by:
        user_access = True

      elif user.id in group_node.group_admin:
        user_access = True

      elif group_node.edit_policy == "NON_EDITABLE":
        user_access = False

      elif user.id in group_node.author_set:
        user_access = True

      else:
        user_access = False

    if user_access:
      return "allow"

    else:
      return "disallow"

  except Exception as e:
    error_message = "\n UserAccessPolicyError: " + str(e) + " !!!\n"
    raise Exception(error_message)
			
@get_execution_time		
@register.assignment_tag
def resource_info(node):
		col_Group=db[Group.collection_name]
		try:
			group_gst=col_Group.Group.one({'_id':ObjectId(node._id)})
		except:
			grname=re.split(r'[/=]',node)
			group_gst=col_Group.Group.one({'_id':ObjectId(grname[1])})
		return group_gst

		
@get_execution_time
@register.assignment_tag
def edit_policy(groupid,node,user):
	group_access= group_type_info(groupid,user)
	resource_infor=resource_info(node)
	#code for public Groups and its Resources
	
	if group_access == "PUBLIC":
			#user_access=user_access_policy(groupid,user)
			#if user_access == "allow":
			return "allow"
	elif group_access == "PRIVATE":
			return "allow"
	elif group_access == "BaseModerated":
			 user_access=user_access_policy(groupid,user)
			 if user_access == "allow":
					resource_infor=resource_info(node)
					#code for exception 
					if resource_infor._type == "Group":
							return "allow"
					elif resource_infor.created_by == user.id:
							return "allow"    
					elif resource_infor.status == "PUBLISHED":    
							return "allow"
	elif group_access == "Moderated": 
			 return "allow"
	elif resource_infor.created_by == user.id:
							return "allow"    
						
@get_execution_time		
@register.assignment_tag
def get_prior_post_node(group_id):
	col_Group = db[Group.collection_name]
	prior_post_node=col_Group.Group.one({'_type': 'Group',"_id":ObjectId(group_id)})
	#check wheather we got the Group name       
	if prior_post_node is not  None:
			 #first check the prior node id  and take the id
			 Prior_nodeid=prior_post_node.prior_node
			 #once you have the id check search for the base node
			 base_colg=col_Group.Group.one({'_type':u'Group','_id':{'$in':Prior_nodeid}})
			 
			 if base_colg is None:
					#check for the Post Node id
					 Post_nodeid=prior_post_node.post_node
					 Mod_colg=col_Group.Group.find({'_type':u'Group','_id':{'$in':Post_nodeid}})
                                         Mod_colg=list(Mod_colg)
					 if list(Mod_colg) is not None:
                                        	#return node of the Moderated group            
						return Mod_colg
			 else:
					#return node of the base group
					return base_colg
	
@get_execution_time
@register.assignment_tag
def Group_Editing_policy(groupid,node,user):
	col_Group = db[Group.collection_name]
	node=col_Group.Group.one({"_id":ObjectId(groupid)})

	if node.edit_policy == "EDITABLE_MODERATED":
		 status=edit_policy(groupid,node,user)
		 if status is not None:
				return "allow"
	elif node.edit_policy == "NON_EDITABLE":
		status=non_editable_policy(groupid,user.id)
		if status is not None:
				return "allow"
	elif node.edit_policy == "EDITABLE_NON_MODERATED":  
		 status=edit_policy(groupid,node,user)
		 if status is not None:
				return "allow"
	elif node.edit_policy is None:
		return "allow"      
	
@get_execution_time
@register.assignment_tag
def check_is_gstaff(groupid, user):
  """
  Checks whether given user belongs to GStaff.
  GStaff includes only those members which belongs to following criteria:
    1) User should be a super-user (Django's superuser)
    2) User should be a creator of the group (created_by field)
    3) User should be an admin-user of the group (group_admin field)
  
  Other memebrs (author_set field) doesn't belongs to GStaff.

  Arguments:
  groupid -- ObjectId of the currently selected group
  user -- User object taken from request object

  Returns:
  True -- If user is one of them, from the above specified list of categories.
  False -- If above criteria is not met (doesn't belongs to any of the category, mentioned above)!
  """

  try:
    group_node = node_collection.one({'_id': ObjectId(groupid)})

    if group_node:
      return group_node.is_gstaff(user)

    else:
      error_message = "No group exists with this id ("+str(groupid)+") !!!"
      raise Exception(error_message)

  except Exception as e:
    error_message = "\n IsGStaffCheckError: " + str(e) + " \n"
    raise Http404(error_message)

@get_execution_time
@register.assignment_tag
def check_is_gapp_for_gstaff(groupid, app_dict, user):
    """
    This restricts view of MIS & MIS-PO GApp to only GStaff members
    (super-user, creator, admin-user) of the group.
    That is, other subscribed-members of the group can't even see these GApps.

    Arguments:
    groupid -- ObjectId of the currently selected group
    app_dict -- A dictionary consisting of following key-value pair
                - 'id': ObjectId of the GApp
                - 'name': name of the GApp
    user - User object taken from request object

    Returns:
    A bool value indicating:-
    True --  if user is superuser, creator or admin of the group
    False -- if user is just a subscribed-member of the group
    """

    try:
        if app_dict["name"].lower() in ["mis", "mis-po", "batch"]:
            return check_is_gstaff(groupid, user)

        else:
            return True

    except Exception as e:
        error_message = "\n GroupAdminCheckError (For MIS): " + str(e) + " \n"
        raise Http404(error_message)


@get_execution_time
@register.assignment_tag
def get_publish_policy(request, groupid, res_node):
	resnode = node_collection.one({"_id": ObjectId(res_node._id)})

	if resnode.status == "DRAFT":
	    
	    # node = node_collection.one({"_id": ObjectId(groupid)})
		
		group_name, group_id = get_group_name_id(groupid)
		node = node_collection.one({"_id": ObjectId(group_id)})

		group_type = group_type_info(groupid)
		group = user_access_policy(groupid,request.user)
		ver = node.current_version

		if request.user.id:
			if group_type == "Moderated":
				base_group=get_prior_post_node(groupid)
                                #if base_group and (base_group[len(base_group) - 1] is not None):
                                # comment as it throws key error 45
                                if base_group : 
					#if base_group[len(base_group) - 1].status == "DRAFT" or node.status == "DRAFT":
                                        if base_group.status == "DRAFT" or node.status == "DRAFT":
						return "allow"

			elif node.edit_policy == "NON_EDITABLE":
				if resnode._type == "Group":
					if ver == "1.1" or (resnode.created_by != request.user.id and not request.user.is_superuser):
						return "stop"
		        if group == "allow":          
		        	if resnode.status == "DRAFT": 
		        			return "allow"    

			elif node.edit_policy == "EDITABLE_NON_MODERATED":
		        #condition for groups
				if resnode._type == "Group":
					if ver == "1.1" or (resnode.created_by != request.user.id and not request.user.is_superuser):
		            	# print "\n version = 1.1\n"
						return "stop"

		        if group == "allow":
		          # print "\n group = allow\n"
		          if resnode.status == "DRAFT": 
		            return "allow"


@get_execution_time
@register.assignment_tag
def get_resource_collection(groupid, resource_type):
  """
  Returns collections of given resource-type belonging to currently selected group

  Arguments:
  groupid -- ObjectId (in string format) of currently selected group
  resource_type -- Type of resource (Page/File) whose collections need to find

  Returns:
  Mongodb's cursor object holding nodes having collections
  """
  try:
    gst = node_collection.one({'_type': "GSystemType", 'name': unicode(resource_type)})

    res_cur = node_collection.find({'_type': {'$in': [u"GSystem", u"File"]},
                                    'member_of': gst._id,
                                    'group_set': ObjectId(groupid),
                                    'collection_set': {'$exists': True, '$not': {'$size': 0}}
                                  })
    return res_cur

  except Exception as e:
    error_message = "\n CollectionsFindError: " + str(e) + " !!!\n"
    raise Exception(error_message)

@get_execution_time
@register.assignment_tag
def get_all_file_int_count():
	'''
	getting all the file/e-library type resource
	'''
	all_files = node_collection.find({ "_type": "File", "access_policy": "PUBLIC" })
	return all_files.count()

@get_execution_time
@register.assignment_tag
def app_translations(request, app_dict):
   app_id=app_dict['id']
   get_translation_rt = node_collection.one({'$and':[{'_type':'RelationType'},{'name':u"translation_of"}]})
   if request.LANGUAGE_CODE != GSTUDIO_SITE_DEFAULT_LANGUAGE:
      get_rel = triple_collection.one({'$and':[{'_type':"GRelation"},{'relation_type.$id':get_translation_rt._id},{'subject':ObjectId(app_id)}]})
      if get_rel:
         get_trans=node_collection.one({'_id':get_rel.right_subject})
         if get_trans.language == request.LANGUAGE_CODE:
            return get_trans.name
         else:
            app_name=node_collection.one({'_id':ObjectId(app_id)})
            return app_name.name
      else:
         app_name=node_collection.one({'_id':ObjectId(app_id)})
         return app_name.name
   else:
      app_name=node_collection.one({'_id':ObjectId(app_id)})
      return app_name.name

@get_execution_time
@register.assignment_tag
def get_preferred_lang(request, group_id, nodes, node_type):
   group = node_collection({'_id':(ObjectId(group_id))})
   get_translation_rt = node_collection.one({'$and':[{'_type':'RelationType'},{'name':u"translation_of"}]})
   uname=node_collection.one({'name':str(request.user.username), '_type': {'$in': ["Group", "Author"]}})
   preferred_list=[]
   primary_list=[]
   default_list=[]
   node=node_collection.one({'_type':'GSystemType','name':node_type,})
   if uname:
      if uname.has_key("preferred_languages"):
		pref_lan=uname.preferred_languages
		
		if pref_lan.keys():
			if pref_lan['primary'] != request.LANGUAGE_CODE:
				uname.preferred_languages['primary'] = request.LANGUAGE_CODE
				uname.save()

		else:
			pref_lan={}
			pref_lan['primary']=request.LANGUAGE_CODE
			pref_lan['default']=u"en"
			uname.preferred_languages=pref_lan
			uname.save()   
      else:
         pref_lan={}
         pref_lan['primary']=request.LANGUAGE_CODE
         pref_lan['default']=u"en"
         uname.preferred_languages=pref_lan
         uname.save()
   else:
      pref_lan={}
      pref_lan[u'primary']=request.LANGUAGE_CODE
      pref_lan[u'default']=u"en"
   try:
      for each in nodes:
         get_rel = triple_collection.find({'$and':[{'_type':"GRelation"},{'relation_type.$id':get_translation_rt._id},{'subject':each._id}]})
         if get_rel.count() > 0:
            for rel in list(get_rel):
               rel_node = node_collection.one({'_id':rel.right_subject})
               if rel_node.language == pref_lan['primary']:
                  primary_nodes = node_collection.one({'$and':[{'member_of':node._id},{'group_set':group._id},{'language':pref_lan['primary']},{'_id':rel_node._id}]})
                  if primary_nodes:
                     preferred_list.append(primary_nodes)
                    
               else:
                  default_nodes=node_collection.one({'$and':[{'member_of':node._id},{'group_set':group._id},{'language':pref_lan['default']},{'_id':each._id}]})
                  if default_nodes:
                     preferred_list.append(default_nodes)
              
         elif get_rel.count() == 0:
            default_nodes = node_collection.one({'$and':[{'member_of':node._id},{'group_set':group._id},{'language':pref_lan['default']},{'_id':each._id}]})
            if default_nodes:
               preferred_list.append(default_nodes)
                  
      if preferred_list:
         return preferred_list
      
   except Exception as e:
      return 'error'


# getting video metadata from wetube.gnowledge.org
@get_execution_time
@register.assignment_tag
def get_pandoravideo_metadata(src_id):
  try:
    api=ox.api.API("http://wetube.gnowledge.org/api")
    data=api.get({"id":src_id,"keys":""})
    mdata=data.get('data')
    return mdata
  except Exception as e:
    return 'null'

@get_execution_time
@register.assignment_tag
def get_source_id(obj_id):
  try:
    source_id_at = node_collection.one({'$and':[{'name':'source_id'},{'_type':'AttributeType'}]})
    att_set = triple_collection.one({'_type': 'GAttribute', 'subject': ObjectId(obj_id), 'attribute_type.$id': source_id_at._id})
    return att_set.object_value
  except Exception as e:
    return 'null'

@get_execution_time
def get_translation_relation(obj_id, translation_list = [], r_list = []):
   get_translation_rt = node_collection.one({'$and':[{'_type':'RelationType'},{'name':u"translation_of"}]})
   if obj_id not in r_list:
      r_list.append(obj_id)
      node_sub_rt = triple_collection.find({'$and':[{'_type':"GRelation"},{'relation_type.$id':get_translation_rt._id},{'subject':obj_id}]})
      node_rightsub_rt = triple_collection.find({'$and':[{'_type':"GRelation"},{'relation_type.$id':get_translation_rt._id},{'right_subject':obj_id}]})
      
      if list(node_sub_rt):
         node_sub_rt.rewind()
         for each in list(node_sub_rt):
            right_subject = node_collection.one({'_id':each.right_subject})
            if right_subject._id not in r_list:
               r_list.append(right_subject._id)
      if list(node_rightsub_rt):
         node_rightsub_rt.rewind()
         for each in list(node_rightsub_rt):
            right_subject = node_collection.one({'_id':each.subject})
            if right_subject._id not in r_list:
               r_list.append(right_subject._id)
      if r_list:
         r_list.remove(obj_id)
         for each in r_list:
            dic={}
            node = node_collection.one({'_id':each})
            dic[node._id]=node.language
            translation_list.append(dic)
            get_translation_relation(each,translation_list, r_list)
   return translation_list


# returns object value of attribute 
@get_execution_time
@register.assignment_tag
def get_object_value(node):
   at_set = ['contact_point','house_street','town_city','state','pin_code','email_id','telephone','website']
   att_name_value= OrderedDict()
           
   for each in at_set:
      attribute_type = node_collection.one({'_type':"AttributeType" , 'name':each}) 
      if attribute_type:
      	get_att = triple_collection.one({'_type':"GAttribute", 'subject':node._id, 'attribute_type.$id': attribute_type._id})
      	if get_att:
        	att_name_value[attribute_type.altnames] = get_att.object_value
         
   return att_name_value


@get_execution_time
@register.assignment_tag
# return json data of object
def get_json(node):
   node_obj = node_collection.one({'_id':ObjectId(str(node))})
   return json.dumps(node_obj, cls=NodeJSONEncoder, sort_keys = True)  


@get_execution_time
@register.filter("is_in")
# filter added to test if vaiable is inside of list or dict
def is_in(var, args):
    if args is None:
        return False
    arg_list = [arg.strip() for arg in args.split(',')]
    return var in arg_list


@get_execution_time
@register.filter("del_underscore")
# filter added to remove underscore from string
def del_underscore(var):
   var = var.replace("_"," ")   
   return var 

@get_execution_time
@register.assignment_tag
# this function used for info-box implementation 
# which convert str to dict type & returns dict which used for rendering in template 
def str_to_dict(str1):
    dict_format = json.loads(str1, object_pairs_hook = OrderedDict)
    keys_to_remove = ('_id','access_policy','rating', 'fs_file_ids', 'content_org', 'content', 'comment_enabled', 'annotations', 'login_required','status','featured','module_set','property_order','url') # keys needs to hide
    keys_by_ids = ('member_of', 'group_set', 'collection_set','prior_node') # keys holds list of ids
    keys_by_userid = ('modified_by', 'contributors', 'created_by', 'author_set') # keys holds dada from User table
    keys_by_dict = ('attribute_set', 'relation_set')
    keys_by_filesize = ('file_size')
    for k in keys_to_remove:
      dict_format.pop(k, None)
    for k, v in dict_format.items():
      if type(dict_format[k]) == list :
          if len(dict_format[k]) == 0:
                  dict_format[k] = "None"
      if k in keys_by_ids:
        name_list = []
        if "None" not in dict_format[k]:
                for ids in dict_format[k]:
                        node = node_collection.one({'_id':ObjectId(ids)})
                        if node:
                                name_list.append(node)
                                dict_format[k] = name_list
              
      if k in keys_by_userid:
       
              if type(dict_format[k]) == list :
                      for userid in dict_format[k]:
                      		  if User.objects.filter(id = userid).exists():
	                              user = User.objects.get(id = userid)
	                              if user:
	                                dict_format[k] = user.get_username()
              else: 
                      # if v != [] and v != "None":
                      if v:
                      		  if User.objects.filter(id = v).exists():
	                              user = User.objects.get(id = v)
	                              if user:
	                                dict_format[k] = user.get_username()

      if k in keys_by_dict:
              att_dic = {}
              if "None" not in dict_format[k]:
                      if type(dict_format[k]) != str and k == "attribute_set":
                              for att in dict_format[k]:
                                      for k1, v1 in att.items():
                                        if type(v1) == list:
                                                str1 = ""
                                                if type(v1[0]) in [OrderedDict, dict]:
                                                    for each in v1:
                                                        str1 += each["name"] + ", "
                                                else:
                                                    str1 = ",".join(v1)
                                                att_dic[k1] = str1
                                                dict_format[k] = att_dic
                                        else:
                                                att_dic[k1] = v1
                                                dict_format[k] = att_dic
                      if k == "relation_set":
                              for each in dict_format[k]:
                                      for k1, v1 in each.items():
                                              for rel in v1:
                                                      rel = node_collection.one({'_id':ObjectId(rel)})
                                                      if rel:
                                                      	att_dic[k1] = rel.name
                                      dict_format[k] = att_dic
                                
      if k in keys_by_filesize:
              filesize_dic = {}
              for k1, v1 in dict_format[k].items():
                      filesize_dic[k1] = v1
              dict_format[k] = filesize_dic
    order_dict_format = OrderedDict()
    order_val=['altnames','language','plural','_type','member_of','created_by','created_at','tags','modified_by','author_set','group_set','collection_set','contributors','last_update','start_publication','location','license','attribute_set','relation_set']
    for each in order_val:
            order_dict_format[each]=dict_format[each]
    return order_dict_format
    
@get_execution_time
@register.assignment_tag
def get_possible_translations(obj_id):
        translation_list = []
	r_list1 = []
        return get_translation_relation(obj_id._id,r_list1,translation_list)


#textb
@get_execution_time
@register.filter("mongo_id")
def mongo_id(value):
		 # Retrieve _id value
		if type(value) == type({}):
				if value.has_key('_id'):
						value = value['_id']
	 
		# Return value
		return unicode(str(value))

@get_execution_time
@register.simple_tag
def check_existence_textObj_mobwrite(node_id):
		'''
	to check object already created or not, if not then create 
	input nodeid 
		'''		
		check = ""
		system = node_collection.find_one({"_id":ObjectId(node_id)})
		filename = TextObj.safe_name(str(system._id))
		textobj = TextObj.objects.filter(filename=filename)
		if textobj:
			textobj = TextObj.objects.get(filename=filename)
			pass
		else:
			if system.content_org == None:
				content_org = "None"
			else :
		 		content_org = system.content_org
			textobj = TextObj(filename=filename,text=content_org)
			textobj.save()
		check = textobj.filename
		return check
#textb 

@get_execution_time
@register.assignment_tag
def get_version_of_module(module_id):
	''''
	This method will return version number of module
	'''
	ver_at = node_collection.one({'_type':'AttributeType','name':'version'})
	if ver_at:
		attr = triple_collection.one({'_type':'GAttribute','attribute_type.$id':ver_at._id,'subject':ObjectId(module_id)})
		if attr:
			return attr.object_value
		else:
			return ""
	else:
		return ""

@get_execution_time
@register.assignment_tag
def get_group_name(groupid):
	# group_name = ""
	# ins_objectid  = ObjectId()
	# if ins_objectid.is_valid(groupid) is True :
	# 	group_ins = node_collection.find_one({'_type': "Group","_id": ObjectId(groupid)})
	# 	if group_ins:
	# 		group_name = group_ins.name
	# 	else :
	# 		auth = node_collection.one({'_type': 'Author', "_id": ObjectId(groupid) })
	# 		if auth :
	# 			group_name = auth.name

	# else :
	# 	pass
	
	group_name, group_id = get_group_name_id(groupid)

	return group_name 


@register.filter
def concat(value1, value2):
    """concatenate multiple received args
    """
    return_str = value1.__str__()
    value2 = value2.__str__()
    return return_str + value2


@get_execution_time
@register.filter
def get_field_type(node_structure, field_name):
  """Returns data-type value associated with given field_name.
  """
  return node_structure.get(field_name)

@get_execution_time
@register.inclusion_tag('ndf/html_field_widget.html')
# def html_widget(node_id, field, field_type, field_value):
# def html_widget(node_id, node_member_of, field, field_value):
def html_widget(groupid, node_id, field):
  """
  Returns html-widget for given attribute-field; that is, passed in form of
  field_name (as attribute's name) and field_type (as attribute's data-type)
  """
  # gs = None
  field_value_choices = []

  # This field is especially required for drawer-widets to work used in cases of RelationTypes
  # Represents a dummy document that holds node's _id and node's right_subject value(s) from it's GRelation instance
  node_dict = {}

  is_list_of = False
  LIST_OF = [ "[<class 'bson.objectid.ObjectId'>]",
              "[<type 'unicode'>]", "[<type 'basestring'>]",
              "[<type 'int'>]", "[<type 'float'>]", "[<type 'long'>]",
              "[<type 'datetime.datetime'>]"
            ]

  is_special_field = False
  included_template_name = ""
  SPECIAL_FIELDS = {"location": "ndf/location_widget.html",
                    "content_org": "ndf/add_editor.html"
                    # "attendees": "ndf/attendees_widget.html"  # Uncomment this to make attendance-widget working
                    }

  is_required_field = False

  is_mongokit_is_radio = False # False for drop-down True for radio buttons

  try:
    if node_id:
      node_id = ObjectId(node_id)
      node_dict['_id'] = node_id

    # if node_member_of:
    #   gs = node_collection.collection.GSystem()
    #   gs.get_neighbourhood(node_member_of)

    # field_type = gs.structure[field['name']]
    field_type = field['data_type']
    field_altnames = field['altnames']
    field_value = field['value']

    if type(field_type) == IS:
      field_value_choices = field_type._operands

      if len(field_value_choices) == 2:
        is_mongokit_is_radio = True

    elif field_type == bool:
      field_value_choices = [True, False]

    if field.has_key('_id'):
      field = node_collection.one({'_id': field['_id']})

    field['altnames'] = field_altnames

    if not field_value:
      if type(field_type) == IS:
      	field_value = [] 
      else:
      	field_value = ""

    if type(field_type) == type:
      field_type = field_type.__name__
    else:
      field_type = field_type.__str__()

    is_list_of = (field_type in LIST_OF)

    is_special_field = (field['name'] in SPECIAL_FIELDS.keys())
    if is_special_field:
      included_template_name = SPECIAL_FIELDS[field['name']]

    is_AT_RT_base = field["_type"]

    is_attribute_field = False
    is_relation_field = False
    is_base_field = False
    if is_AT_RT_base == "BaseField":
      is_base_field = True
      is_required_field = field["required"]

    elif is_AT_RT_base == "AttributeType":
      is_attribute_field = True
      is_required_field = field["required"]

    elif is_AT_RT_base == "RelationType":
      is_relation_field = True
      is_required_field = True
      #patch
      group = node_collection.find({"_id":ObjectId(groupid)})
      person = node_collection.find({"_id":{'$in': field["object_type"]}},{"name":1})
      
      if person[0].name == "Author":
          if field.name == "has_attendees":
              field_value_choices.extend(list(node_collection.find({'member_of': {'$in':field["object_type"]},
                                                                  'created_by':{'$in':group[0]["group_admin"]+group[0]["author_set"]},
                                                                  
                                                                 })
                                                                 ))
          else:       
              field_value_choices.extend(list(node_collection.find({'member_of': {'$in':field["object_type"]},
                                                            'created_by':{'$in':group[0]["group_admin"]},                                																														}).sort('name', 1)
                                      )
                                )
      #End path
      else:
        field_value_choices.extend(list(node_collection.find({'member_of': {'$in': field["object_type"]},
                                                              'status': u"PUBLISHED",
                                                              'group_set': ObjectId(groupid)
                                                               }).sort('name', 1)
                                      )
                                )
      
      if field_value:
	      if type(field_value[0]) == ObjectId or ObjectId.is_valid(field_value[0]):
	      	field_value = [str(each) for each in field_value]

	      else:
	      	field_value = [str(each._id) for each in field_value]

      if node_id:
      	node_dict[field['name']] = [ObjectId(each) for each in field_value]

    return {'template': 'ndf/html_field_widget.html',
            'field': field, 'field_type': field_type, 'field_value': field_value,
            'node_id': node_id, 'group_id': groupid, 'groupid': groupid, 'node_dict': node_dict,
            'field_value_choices': field_value_choices,
            'is_base_field': is_base_field,
            'is_attribute_field': is_attribute_field,
            'is_relation_field': is_relation_field,
            'is_list_of': is_list_of,
            'is_mongokit_is_radio': is_mongokit_is_radio,
            'is_special_field': is_special_field, 'included_template_name': included_template_name,
            'is_required_field': is_required_field
            # 'is_special_tab_field': is_special_tab_field
    }

  except Exception as e:
    error_message = " HtmlWidgetTagError: " + str(e) + " !!!"
    raise Exception(error_message)

@get_execution_time  
@register.assignment_tag
def check_node_linked(node_id):
  """
  Checks whether the passed node is linked with it's corresponding author node (i.e via "has_login" relationship)

  Arguments:
  node_id -- ObjectId of the node

  Returns:
  A bool value, i.e.
  True: if linked (i.e. relationship is created for the given node)
  False: if not linked (i.e. relationship is not created)
  """

  try:
    node = node_collection.one({'_id': ObjectId(node_id)}, {'_id': 1})
    relation_type_node = node_collection.one({'_type': "RelationType", 'name': "has_login"})
    is_linked = triple_collection.one({'_type': "GRelation", 'subject': node._id, 'relation_type': relation_type_node.get_dbref()})

    if is_linked:
      return True

    else:
      return False

  except Exception as e:
    error_message = " NodeUserLinkFindError - " + str(e)
    raise Exception(error_message)

@get_execution_time
@register.assignment_tag
def get_file_node(request, file_name=""):
	file_list = []
	new_file_list = []

	a = str(file_name).split(',')

	for i in a:
		k = str(i.strip('   [](\'u\'   '))
		file_list.append(k)

	for each in file_list:
		if ObjectId.is_valid(each) is False:
			filedoc = node_collection.find({'_type':'File','name':unicode(each)})

		else:
			filedoc = node_collection.find({'_type':'File','_id':ObjectId(each)})			

		if filedoc:
			for i in filedoc:
				new_file_list.append(i)	

	return new_file_list	

@get_execution_time
@register.filter(name='jsonify')
def jsonify(value):
    """Parses python value into json-type (useful in converting
    python list/dict into javascript/json object).
    """

    return json.dumps(value, cls=NodeJSONEncoder)

@get_execution_time
@register.assignment_tag
def get_university(college_name):
    """
    Returns university name to which given college is affiliated to.
    """
    try:
        college = node_collection.one({
            '_type': "GSystemType", 'name': u"College"
        })

        sel_college = node_collection.one({
            'member_of': college._id, 'name': unicode(college_name)
        })

        university_name = None
        if sel_college:
            university = node_collection.one({
                '_type': "GSystemType", 'name': u"University"
            })
            sel_university = node_collection.one({
                'member_of': university._id,
                'relation_set.affiliated_college': sel_college._id
            })
            university_name = sel_university.name

        return university_name
    except Exception as e:
        error_message = "UniversityFindError: " + str(e) + " !!!"
        raise Exception(error_message)

@get_execution_time
@register.assignment_tag
def get_features_with_special_rights(group_id_or_name, user):
    """Returns list of features with special rights.

    If group is MIS_admin and user belongs to gstaff, then only give
    creation rights to list of feature(s) within MIS GApp shown as following:
      1. StudentCourseEnrollment

    For feature(s) included in list, don't provide creation rights.

    Arguments:
    group_id_or_name -- Name/ObjectId of the group
    user -- Logged-in user object (django-specific)

    Returns:
    List having names of feature(s) included in MIS GApp
    """
    # List of feature(s) for which creation rights should not be given
    features_with_special_rights = ["StudentCourseEnrollment"]

    mis_admin = node_collection.one({
        "_type": "Group", "name": "MIS_admin"
    })

    if (group_id_or_name == mis_admin.name or
            group_id_or_name == str(mis_admin._id)):
        if mis_admin.is_gstaff(user):
            features_with_special_rights = []

    return features_with_special_rights

@get_execution_time
@register.assignment_tag
def get_filters_data(gst_name):
	'''
	Returns the static data needed by filters. The data to be return will in following format:
	{ 
		"key_name": { "data_type": "<int>/<string>/<...>", "type": "attribute/field", "value": ["val1", "val2"]},
		... ,
		... ,
		"key_name": { "data_type": "<int>/<string>/<...>", "type": "attribute/field", "value": ["val1", "val2"]} 
	}
	'''

	static_mapping = {
                    "educationalsubject": GSTUDIO_RESOURCES_EDUCATIONAL_SUBJECT,
                    "language": GSTUDIO_RESOURCES_LANGUAGES,
                    # "educationaluse": GSTUDIO_RESOURCES_EDUCATIONAL_USE,
                    "interactivitytype": GSTUDIO_RESOURCES_INTERACTIVITY_TYPE,
                    # "educationalalignment": GSTUDIO_RESOURCES_EDUCATIONAL_ALIGNMENT,
                    "educationallevel": GSTUDIO_RESOURCES_EDUCATIONAL_LEVEL,
                    # "curricular": GSTUDIO_RESOURCES_CURRICULAR,
                    "audience": GSTUDIO_RESOURCES_AUDIENCE,
                    # "textcomplexity": GSTUDIO_RESOURCES_TEXT_COMPLEXITY
				}

	# following attr's values need to be get/not in settings:
	# timerequired, other_contributors, creator, age_range, readinglevel, adaptation_of, source, basedonurl

	filter_dict = {}

	gst = node_collection.one({'_type':"GSystemType", "name": unicode(gst_name)})
	poss_attr = gst.get_possible_attributes(gst._id)

	exception_list = ["educationaluse"]

	for k, v in poss_attr.iteritems():

		if (k in exception_list) or not static_mapping.has_key(k):
			continue

		filter_dict[k] = {
	    					"data_type": v["data_type"].__name__,
	    					"altnames": v['altnames'],
	    					"type" : "attribute",
	    					"value": json.dumps(static_mapping.get(k, []))
	    				}

	# additional filters:

	filter_dict["language"] = { 
								"data_type": "basestring", "type": "field",
								"value": json.dumps(static_mapping["language"]) 
							}

	return filter_dict