File: ContextHandlers.pm

package info (click to toggle)
movabletype-opensource 5.1.4%2Bdfsg-4%2Bdeb7u3
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 32,996 kB
  • sloc: perl: 197,285; php: 62,405; sh: 166; xml: 117; makefile: 83; sql: 32
file content (5890 lines) | stat: -rw-r--r-- 189,860 bytes parent folder | download
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
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
# Movable Type (r) Open Source (C) 2001-2012 Six Apart Ltd.
# This program is distributed under the terms of the
# GNU General Public License, version 2.
#
# $Id$

package MT::Template::Context;

use strict;

use MT::Util qw( format_ts relative_date );
use Time::Local qw( timelocal );

sub init_default_handlers { }
sub init_default_filters  { }

sub core_tags {
    my $tags = {
        help_url => sub {
            MT->translate(
                'http://www.movabletype.org/documentation/appendices/tags/%t.html'
            );
        },
        block => {

            ## Core
            Ignore    => sub {''},
            'If?'     => \&MT::Template::Tags::Core::_hdlr_if,
            'Unless?' => \&MT::Template::Tags::Core::_hdlr_unless,
            'Else'    => \&MT::Template::Tags::Core::_hdlr_else,
            'ElseIf'  => \&MT::Template::Tags::Core::_hdlr_elseif,
            'IfNonEmpty?'  => \&MT::Template::Tags::Core::_hdlr_if_nonempty,
            'IfNonZero?'   => \&MT::Template::Tags::Core::_hdlr_if_nonzero,
            Loop           => \&MT::Template::Tags::Core::_hdlr_loop,
            'For'          => \&MT::Template::Tags::Core::_hdlr_for,
            SetVarBlock    => \&MT::Template::Tags::Core::_hdlr_set_var,
            SetVarTemplate => \&MT::Template::Tags::Core::_hdlr_set_var,
            SetVars        => \&MT::Template::Tags::Core::_hdlr_set_vars,
            SetHashVar     => \&MT::Template::Tags::Core::_hdlr_set_hashvar,

            ## System
            IncludeBlock => \&MT::Template::Tags::System::_hdlr_include_block,
            IfStatic     => \&slurp,
            IfDynamic    => \&else,
            Section      => \&MT::Template::Tags::System::_hdlr_section,

            ## App
            'App:Setting'   => \&MT::Template::Tags::App::_hdlr_app_setting,
            'App:Widget'    => \&MT::Template::Tags::App::_hdlr_app_widget,
            'App:StatusMsg' => \&MT::Template::Tags::App::_hdlr_app_statusmsg,
            'App:Listing'   => \&MT::Template::Tags::App::_hdlr_app_listing,
            'App:SettingGroup' =>
                \&MT::Template::Tags::App::_hdlr_app_setting_group,
            'App:Form' => \&MT::Template::Tags::App::_hdlr_app_form,

            ## Blog
            Blogs     => '$Core::MT::Template::Tags::Blog::_hdlr_blogs',
            'IfBlog?' => '$Core::MT::Template::Tags::Blog::_hdlr_if_blog',
            'BlogIfCCLicense?' =>
                '$Core::MT::Template::Tags::Blog::_hdlr_blog_if_cc_license',

            ## Website
            Websites => '$Core::MT::Template::Tags::Website::_hdlr_websites',
            'IfWebsite?' =>
                '$Core::MT::Template::Tags::Website::_hdlr_website_id',
            'WebsiteIfCCLicense?' =>
                '$Core::MT::Template::Tags::Website::_hdlr_website_if_cc_license',
            'WebsiteHasBlog?' =>
                '$Core::MT::Template::Tags::Website::_hdlr_website_has_blog',
            BlogParentWebsite =>
                '$Core::MT::Template::Tags::Website::_hdlr_blog_parent_website',

            ## Author
            Authors => '$Core::MT::Template::Tags::Author::_hdlr_authors',
            AuthorNext =>
                '$Core::MT::Template::Tags::Author::_hdlr_author_next_prev',
            AuthorPrevious =>
                '$Core::MT::Template::Tags::Author::_hdlr_author_next_prev',
            'IfAuthor?' =>
                '$Core::MT::Template::Tags::Author::_hdlr_if_author',

            ## Commenter
            'IfExternalUserManagement?' =>
                '$Core::MT::Template::Tags::Commenter::_hdlr_if_external_user_management',
            'IfCommenterRegistrationAllowed?' =>
                '$Core::MT::Template::Tags::Commenter::_hdlr_if_commenter_registration_allowed',
            'IfCommenterTrusted?' =>
                '$Core::MT::Template::Tags::Commenter::_hdlr_commenter_trusted',
            'CommenterIfTrusted?' =>
                '$Core::MT::Template::Tags::Commenter::_hdlr_commenter_trusted',
            'IfCommenterIsAuthor?' =>
                '$Core::MT::Template::Tags::Commenter::_hdlr_commenter_isauthor',
            'IfCommenterIsEntryAuthor?' =>
                '$Core::MT::Template::Tags::Commenter::_hdlr_commenter_isauthor',

            ## Archive
            Archives =>
                '$Core::MT::Template::Tags::Archive::_hdlr_archive_set',
            ArchiveList =>
                '$Core::MT::Template::Tags::Archive::_hdlr_archives',
            ArchiveListHeader => \&slurp,
            ArchiveListFooter => \&slurp,
            ArchivePrevious =>
                '$Core::MT::Template::Tags::Archive::_hdlr_archive_prev_next',
            ArchiveNext =>
                '$Core::MT::Template::Tags::Archive::_hdlr_archive_prev_next',
            'IfArchiveType?' =>
                '$Core::MT::Template::Tags::Archive::_hdlr_if_archive_type',
            'IfArchiveTypeEnabled?' =>
                '$Core::MT::Template::Tags::Archive::_hdlr_archive_type_enabled',
            IndexList =>
                '$Core::MT::Template::Tags::Archive::_hdlr_index_list',

            ## Entry
            Entries => '$Core::MT::Template::Tags::Entry::_hdlr_entries',
            EntriesHeader => \&slurp,
            EntriesFooter => \&slurp,
            EntryPrevious =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entry_previous',
            EntryNext => '$Core::MT::Template::Tags::Entry::_hdlr_entry_next',
            DateHeader => \&slurp,
            DateFooter => \&slurp,
            'EntryIfExtended?' =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entry_if_extended',
            'AuthorHasEntry?' =>
                '$Core::MT::Template::Tags::Entry::_hdlr_author_has_entry',

            ## Comment
            'IfCommentsModerated?' =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comments_moderated',
            'BlogIfCommentsOpen?' =>
                '$Core::MT::Template::Tags::Comment::_hdlr_blog_if_comments_open',
            'WebsiteIfCommentsOpen?' =>
                '$Core::MT::Template::Tags::Comment::_hdlr_blog_if_comments_open',
            Comments => '$Core::MT::Template::Tags::Comment::_hdlr_comments',
            CommentsHeader => \&slurp,
            CommentsFooter => \&slurp,
            CommentEntry =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_entry',
            'CommentIfModerated?' =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_if_moderated',
            CommentParent =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_parent',
            CommentReplies =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_replies',
            'IfCommentParent?' =>
                '$Core::MT::Template::Tags::Comment::_hdlr_if_comment_parent',
            'IfCommentReplies?' =>
                '$Core::MT::Template::Tags::Comment::_hdlr_if_comment_replies',
            'IfRegistrationRequired?' =>
                '$Core::MT::Template::Tags::Comment::_hdlr_reg_required',
            'IfRegistrationNotRequired?' =>
                '$Core::MT::Template::Tags::Comment::_hdlr_reg_not_required',
            'IfRegistrationAllowed?' =>
                '$Core::MT::Template::Tags::Comment::_hdlr_reg_allowed',
            'IfTypeKeyToken?' =>
                '$Core::MT::Template::Tags::Comment::_hdlr_if_typekey_token',
            'IfAllowCommentHTML?' =>
                '$Core::MT::Template::Tags::Comment::_hdlr_if_allow_comment_html',
            'IfCommentsAllowed?' =>
                '$Core::MT::Template::Tags::Comment::_hdlr_if_comments_allowed',
            'IfCommentsAccepted?' =>
                '$Core::MT::Template::Tags::Comment::_hdlr_if_comments_accepted',
            'IfCommentsActive?' =>
                '$Core::MT::Template::Tags::Comment::_hdlr_if_comments_active',
            'IfNeedEmail?' =>
                '$Core::MT::Template::Tags::Comment::_hdlr_if_need_email',
            'IfRequireCommentEmails?' =>
                '$Core::MT::Template::Tags::Comment::_hdlr_if_need_email',
            'EntryIfAllowComments?' =>
                '$Core::MT::Template::Tags::Comment::_hdlr_entry_if_allow_comments',
            'EntryIfCommentsOpen?' =>
                '$Core::MT::Template::Tags::Comment::_hdlr_entry_if_comments_open',

            ## Ping
            Pings       => '$Core::MT::Template::Tags::Ping::_hdlr_pings',
            PingsHeader => \&slurp,
            PingsFooter => \&slurp,
            PingsSent => '$Core::MT::Template::Tags::Ping::_hdlr_pings_sent',
            PingEntry => '$Core::MT::Template::Tags::Ping::_hdlr_ping_entry',
            'IfPingsAllowed?' =>
                '$Core::MT::Template::Tags::Ping::_hdlr_if_pings_allowed',
            'IfPingsAccepted?' =>
                '$Core::MT::Template::Tags::Ping::_hdlr_if_pings_accepted',
            'IfPingsActive?' =>
                '$Core::MT::Template::Tags::Ping::_hdlr_if_pings_active',
            'IfPingsModerated?' =>
                '$Core::MT::Template::Tags::Ping::_hdlr_if_pings_moderated',
            'EntryIfAllowPings?' =>
                '$Core::MT::Template::Tags::Ping::_hdlr_entry_if_allow_pings',
            'CategoryIfAllowPings?' =>
                '$Core::MT::Template::Tags::Ping::_hdlr_category_allow_pings',

            ## Category
            Categories =>
                '$Core::MT::Template::Tags::Category::_hdlr_categories',
            CategoryPrevious =>
                '$Core::MT::Template::Tags::Category::_hdlr_category_prevnext',
            CategoryNext =>
                '$Core::MT::Template::Tags::Category::_hdlr_category_prevnext',
            SubCategories =>
                '$Core::MT::Template::Tags::Category::_hdlr_sub_categories',
            TopLevelCategories =>
                '$Core::MT::Template::Tags::Category::_hdlr_top_level_categories',
            ParentCategory =>
                '$Core::MT::Template::Tags::Category::_hdlr_parent_category',
            ParentCategories =>
                '$Core::MT::Template::Tags::Category::_hdlr_parent_categories',
            TopLevelParent =>
                '$Core::MT::Template::Tags::Category::_hdlr_top_level_parent',
            EntriesWithSubCategories =>
                '$Core::MT::Template::Tags::Category::_hdlr_entries_with_sub_categories',
            'IfCategory?' =>
                '$Core::MT::Template::Tags::Category::_hdlr_if_category',
            'EntryIfCategory?' =>
                '$Core::MT::Template::Tags::Category::_hdlr_if_category',
            'SubCatIsFirst?' =>
                '$Core::MT::Template::Tags::Category::_hdlr_sub_cat_is_first',
            'SubCatIsLast?' =>
                '$Core::MT::Template::Tags::Category::_hdlr_sub_cat_is_last',
            'HasSubCategories?' =>
                '$Core::MT::Template::Tags::Category::_hdlr_has_sub_categories',
            'HasNoSubCategories?' =>
                '$Core::MT::Template::Tags::Category::_hdlr_has_no_sub_categories',
            'HasParentCategory?' =>
                '$Core::MT::Template::Tags::Category::_hdlr_has_parent_category',
            'HasNoParentCategory?' =>
                '$Core::MT::Template::Tags::Category::_hdlr_has_no_parent_category',
            'IfIsAncestor?' =>
                '$Core::MT::Template::Tags::Category::_hdlr_is_ancestor',
            'IfIsDescendant?' =>
                '$Core::MT::Template::Tags::Category::_hdlr_is_descendant',
            EntryCategories =>
                '$Core::MT::Template::Tags::Category::_hdlr_entry_categories',
            EntryPrimaryCategory =>
                '$Core::MT::Template::Tags::Category::_hdlr_entry_primary_category',
            EntryAdditionalCategories =>
                '$Core::MT::Template::Tags::Category::_hdlr_entry_additional_categories',

            ## Page
            'AuthorHasPage?' =>
                '$Core::MT::Template::Tags::Page::_hdlr_author_has_page',
            Pages => '$Core::MT::Template::Tags::Page::_hdlr_pages',
            PagePrevious =>
                '$Core::MT::Template::Tags::Page::_hdlr_page_previous',
            PageNext    => '$Core::MT::Template::Tags::Page::_hdlr_page_next',
            PagesHeader => \&slurp,
            PagesFooter => \&slurp,

            ## Folder
            'IfFolder?' =>
                '$Core::MT::Template::Tags::Folder::_hdlr_if_folder',
            'FolderHeader?' =>
                '$Core::MT::Template::Tags::Folder::_hdlr_folder_header',
            'FolderFooter?' =>
                '$Core::MT::Template::Tags::Folder::_hdlr_folder_footer',
            'HasSubFolders?' =>
                '$Core::MT::Template::Tags::Folder::_hdlr_has_sub_folders',
            'HasParentFolder?' =>
                '$Core::MT::Template::Tags::Folder::_hdlr_has_parent_folder',
            PageFolder =>
                '$Core::MT::Template::Tags::Folder::_hdlr_page_folder',
            Folders => '$Core::MT::Template::Tags::Folder::_hdlr_folders',
            FolderPrevious =>
                '$Core::MT::Template::Tags::Folder::_hdlr_folder_prevnext',
            FolderNext =>
                '$Core::MT::Template::Tags::Folder::_hdlr_folder_prevnext',
            SubFolders =>
                '$Core::MT::Template::Tags::Folder::_hdlr_sub_folders',
            ParentFolders =>
                '$Core::MT::Template::Tags::Folder::_hdlr_parent_folders',
            ParentFolder =>
                '$Core::MT::Template::Tags::Folder::_hdlr_parent_folder',
            TopLevelFolders =>
                '$Core::MT::Template::Tags::Folder::_hdlr_top_level_folders',
            TopLevelFolder =>
                '$Core::MT::Template::Tags::Folder::_hdlr_top_level_folder',

            ## Asset
            EntryAssets => '$Core::MT::Template::Tags::Asset::_hdlr_assets',
            PageAssets  => '$Core::MT::Template::Tags::Asset::_hdlr_assets',
            Assets      => '$Core::MT::Template::Tags::Asset::_hdlr_assets',
            Asset       => '$Core::MT::Template::Tags::Asset::_hdlr_asset',
            AssetIsFirstInRow => \&slurp,
            AssetIsLastInRow  => \&slurp,
            AssetsHeader      => \&slurp,
            AssetsFooter      => \&slurp,

            ## Userpic
            AuthorUserpicAsset =>
                '$Core::MT::Template::Tags::Userpic::_hdlr_author_userpic_asset',
            EntryAuthorUserpicAsset =>
                '$Core::MT::Template::Tags::Userpic::_hdlr_entry_author_userpic_asset',
            CommenterUserpicAsset =>
                '$Core::MT::Template::Tags::Userpic::_hdlr_commenter_userpic_asset',

            ## Tag
            Tags      => '$Core::MT::Template::Tags::Tag::_hdlr_tags',
            EntryTags => '$Core::MT::Template::Tags::Tag::_hdlr_entry_tags',
            PageTags  => '$Core::MT::Template::Tags::Tag::_hdlr_page_tags',
            AssetTags => '$Core::MT::Template::Tags::Tag::_hdlr_asset_tags',
            'EntryIfTagged?' =>
                '$Core::MT::Template::Tags::Tag::_hdlr_entry_if_tagged',
            'PageIfTagged?' =>
                '$Core::MT::Template::Tags::Tag::_hdlr_page_if_tagged',
            'AssetIfTagged?' =>
                '$Core::MT::Template::Tags::Tag::_hdlr_asset_if_tagged',

            ## Calendar
            Calendar => '$Core::MT::Template::Tags::Calendar::_hdlr_calendar',
            CalendarWeekHeader  => \&slurp,
            CalendarWeekFooter  => \&slurp,
            CalendarIfBlank     => \&slurp,
            CalendarIfToday     => \&slurp,
            CalendarIfEntries   => \&slurp,
            CalendarIfNoEntries => \&slurp,

            ## Pager
            'IfMoreResults?' =>
                '$Core::MT::Template::Tags::Pager::_hdlr_if_more_results',
            'IfPreviousResults?' =>
                '$Core::MT::Template::Tags::Pager::_hdlr_if_previous_results',
            PagerBlock =>
                '$Core::MT::Template::Tags::Pager::_hdlr_pager_block',
            IfCurrentPage => \&slurp,

            ## Search
            IfTagSearch         => sub {''},
            SearchResults       => sub {''},
            IfStraightSearch    => sub {''},
            NoSearchResults     => \&slurp,
            NoSearch            => \&slurp,
            SearchResultsHeader => sub {''},
            SearchResultsFooter => sub {''},
            BlogResultHeader    => sub {''},
            BlogResultFooter    => sub {''},
            IfMaxResultsCutoff  => sub {''},

            ## Misc
            'IfImageSupport?' =>
                '$Core::MT::Template::Tags::Misc::_hdlr_if_image_support',
        },
        function => {

            ## Core
            SetVar       => \&MT::Template::Tags::Core::_hdlr_set_var,
            GetVar       => \&MT::Template::Tags::Core::_hdlr_get_var,
            Var          => \&MT::Template::Tags::Core::_hdlr_get_var,
            TemplateNote => sub {''},

            ## System
            Include     => \&MT::Template::Tags::System::_hdlr_include,
            Link        => \&MT::Template::Tags::System::_hdlr_link,
            Date        => \&MT::Template::Tags::System::_hdlr_sys_date,
            AdminScript => \&MT::Template::Tags::System::_hdlr_admin_script,
            CommentScript =>
                \&MT::Template::Tags::System::_hdlr_comment_script,
            TrackbackScript =>
                \&MT::Template::Tags::System::_hdlr_trackback_script,
            SearchScript => \&MT::Template::Tags::System::_hdlr_search_script,
            XMLRPCScript => \&MT::Template::Tags::System::_hdlr_xmlrpc_script,
            AtomScript   => \&MT::Template::Tags::System::_hdlr_atom_script,
            NotifyScript => \&MT::Template::Tags::System::_hdlr_notify_script,
            CGIHost      => \&MT::Template::Tags::System::_hdlr_cgi_host,
            CGIPath      => \&MT::Template::Tags::System::_hdlr_cgi_path,
            AdminCGIPath =>
                \&MT::Template::Tags::System::_hdlr_admin_cgi_path,
            CGIRelativeURL =>
                \&MT::Template::Tags::System::_hdlr_cgi_relative_url,
            CGIServerPath =>
                \&MT::Template::Tags::System::_hdlr_cgi_server_path,
            StaticWebPath => \&MT::Template::Tags::System::_hdlr_static_path,
            StaticFilePath =>
                \&MT::Template::Tags::System::_hdlr_static_file_path,
            SupportDirectoryURL =>
                \&MT::Template::Tags::System::_hdlr_support_directory_url,
            Version     => \&MT::Template::Tags::System::_hdlr_mt_version,
            ProductName => \&MT::Template::Tags::System::_hdlr_product_name,
            PublishCharset =>
                \&MT::Template::Tags::System::_hdlr_publish_charset,
            DefaultLanguage =>
                \&MT::Template::Tags::System::_hdlr_default_language,
            ConfigFile => \&MT::Template::Tags::System::_hdlr_config_file,
            IndexBasename =>
                \&MT::Template::Tags::System::_hdlr_index_basename,
            HTTPContentType =>
                \&MT::Template::Tags::System::_hdlr_http_content_type,
            FileTemplate => \&MT::Template::Tags::System::_hdlr_file_template,
            TemplateCreatedOn =>
                \&MT::Template::Tags::System::_hdlr_template_created_on,
            BuildTemplateID =>
                \&MT::Template::Tags::System::_hdlr_build_template_id,
            ErrorMessage => \&MT::Template::Tags::System::_hdlr_error_message,
            PasswordValidation =>
                \&MT::Template::Tags::System::_hdlr_password_validation_script,
            PasswordValidationRule =>
                \&MT::Template::Tags::System::_hdlr_password_validation_rules,

            ## App

            'App:PageActions' =>
                \&MT::Template::Tags::App::_hdlr_app_page_actions,
            'App:ListFilters' =>
                \&MT::Template::Tags::App::_hdlr_app_list_filters,
            'App:ActionBar' =>
                \&MT::Template::Tags::App::_hdlr_app_action_bar,
            'App:Link' => \&MT::Template::Tags::App::_hdlr_app_link,

            ## Blog
            BlogID   => '$Core::MT::Template::Tags::Blog::_hdlr_blog_id',
            BlogName => '$Core::MT::Template::Tags::Blog::_hdlr_blog_name',
            BlogDescription =>
                '$Core::MT::Template::Tags::Blog::_hdlr_blog_description',
            BlogLanguage =>
                '$Core::MT::Template::Tags::Blog::_hdlr_blog_language',
            BlogURL => '$Core::MT::Template::Tags::Blog::_hdlr_blog_url',
            BlogArchiveURL =>
                '$Core::MT::Template::Tags::Blog::_hdlr_blog_archive_url',
            BlogRelativeURL =>
                '$Core::MT::Template::Tags::Blog::_hdlr_blog_relative_url',
            BlogSitePath =>
                '$Core::MT::Template::Tags::Blog::_hdlr_blog_site_path',
            BlogHost => '$Core::MT::Template::Tags::Blog::_hdlr_blog_host',
            BlogTimezone =>
                '$Core::MT::Template::Tags::Blog::_hdlr_blog_timezone',
            BlogCCLicenseURL =>
                '$Core::MT::Template::Tags::Blog::_hdlr_blog_cc_license_url',
            BlogCCLicenseImage =>
                '$Core::MT::Template::Tags::Blog::_hdlr_blog_cc_license_image',
            CCLicenseRDF =>
                '$Core::MT::Template::Tags::Blog::_hdlr_cc_license_rdf',
            BlogFileExtension =>
                '$Core::MT::Template::Tags::Blog::_hdlr_blog_file_extension',
            BlogTemplateSetID =>
                '$Core::MT::Template::Tags::Blog::_hdlr_blog_template_set_id',
            BlogThemeID =>
                '$Core::MT::Template::Tags::Blog::_hdlr_blog_theme_id',

            ## Website
            WebsiteID =>
                '$Core::MT::Template::Tags::Website::_hdlr_website_id',
            WebsiteName =>
                '$Core::MT::Template::Tags::Website::_hdlr_website_name',
            WebsiteDescription =>
                '$Core::MT::Template::Tags::Website::_hdlr_website_description',
            WebsiteLanguage =>
                '$Core::MT::Template::Tags::Website::_hdlr_website_language',
            WebsiteURL =>
                '$Core::MT::Template::Tags::Website::_hdlr_website_url',
            WebsitePath =>
                '$Core::MT::Template::Tags::Website::_hdlr_website_path',
            WebsiteTimezone =>
                '$Core::MT::Template::Tags::Website::_hdlr_website_timezone',
            WebsiteCCLicenseURL =>
                '$Core::MT::Template::Tags::Website::_hdlr_website_cc_license_url',
            WebsiteCCLicenseImage =>
                '$Core::MT::Template::Tags::Website::_hdlr_website_cc_license_image',
            WebsiteFileExtension =>
                '$Core::MT::Template::Tags::Website::_hdlr_website_file_extension',
            WebsiteHost =>
                '$Core::MT::Template::Tags::Website::_hdlr_website_host',
            WebsiteRelativeURL =>
                '$Core::MT::Template::Tags::Website::_hdlr_website_relative_url',
            WebsiteThemeID =>
                '$Core::MT::Template::Tags::Website::_hdlr_website_theme_id',

            ## Author
            AuthorID => '$Core::MT::Template::Tags::Author::_hdlr_author_id',
            AuthorName =>
                '$Core::MT::Template::Tags::Author::_hdlr_author_name',
            AuthorDisplayName =>
                '$Core::MT::Template::Tags::Author::_hdlr_author_display_name',
            AuthorEmail =>
                '$Core::MT::Template::Tags::Author::_hdlr_author_email',
            AuthorURL =>
                '$Core::MT::Template::Tags::Author::_hdlr_author_url',
            AuthorAuthType =>
                '$Core::MT::Template::Tags::Author::_hdlr_author_auth_type',
            AuthorAuthIconURL =>
                '$Core::MT::Template::Tags::Author::_hdlr_author_auth_icon_url',
            AuthorBasename =>
                '$Core::MT::Template::Tags::Author::_hdlr_author_basename',
            AuthorCommentCount =>
                '$Core::MT::Summary::Author::_hdlr_author_comment_count',
            AuthorEntriesCount =>
                '$Core::MT::Summary::Author::_hdlr_author_entries_count',

            ## Commenter
            CommenterNameThunk =>
                '$Core::MT::Template::Tags::Commenter::_hdlr_commenter_name_thunk',
            CommenterUsername =>
                '$Core::MT::Template::Tags::Commenter::_hdlr_commenter_username',
            CommenterName =>
                '$Core::MT::Template::Tags::Commenter::_hdlr_commenter_name',
            CommenterEmail =>
                '$Core::MT::Template::Tags::Commenter::_hdlr_commenter_email',
            CommenterAuthType =>
                '$Core::MT::Template::Tags::Commenter::_hdlr_commenter_auth_type',
            CommenterAuthIconURL =>
                '$Core::MT::Template::Tags::Commenter::_hdlr_commenter_auth_icon_url',
            CommenterID =>
                '$Core::MT::Template::Tags::Commenter::_hdlr_commenter_id',
            CommenterURL =>
                '$Core::MT::Template::Tags::Commenter::_hdlr_commenter_url',
            UserSessionState =>
                '$Core::MT::Template::Tags::Commenter::_hdlr_user_session_state',
            UserSessionCookieTimeout =>
                '$Core::MT::Template::Tags::Commenter::_hdlr_user_session_cookie_timeout',
            UserSessionCookieName =>
                '$Core::MT::Template::Tags::Commenter::_hdlr_user_session_cookie_name',
            UserSessionCookiePath =>
                '$Core::MT::Template::Tags::Commenter::_hdlr_user_session_cookie_path',
            UserSessionCookieDomain =>
                '$Core::MT::Template::Tags::Commenter::_hdlr_user_session_cookie_domain',

            ## Archive
            ArchiveLink =>
                '$Core::MT::Template::Tags::Archive::_hdlr_archive_link',
            ArchiveTitle =>
                '$Core::MT::Template::Tags::Archive::_hdlr_archive_title',
            ArchiveType =>
                '$Core::MT::Template::Tags::Archive::_hdlr_archive_type',
            ArchiveTypeLabel =>
                '$Core::MT::Template::Tags::Archive::_hdlr_archive_label',
            ArchiveLabel =>
                '$Core::MT::Template::Tags::Archive::_hdlr_archive_label',
            ArchiveCount =>
                '$Core::MT::Template::Tags::Archive::_hdlr_archive_count',
            ArchiveDate => \&build_date,
            ArchiveDateEnd =>
                '$Core::MT::Template::Tags::Archive::_hdlr_archive_date_end',
            ArchiveFile =>
                '$Core::MT::Template::Tags::Archive::_hdlr_archive_file',
            IndexLink =>
                '$Core::MT::Template::Tags::Archive::_hdlr_index_link',
            IndexName =>
                '$Core::MT::Template::Tags::Archive::_hdlr_index_name',

            ## Entry
            EntriesCount =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entries_count',
            EntryID => '$Core::MT::Template::Tags::Entry::_hdlr_entry_id',
            EntryTitle =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entry_title',
            EntryStatus =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entry_status',
            EntryFlag => '$Core::MT::Template::Tags::Entry::_hdlr_entry_flag',
            EntryBody => '$Core::MT::Template::Tags::Entry::_hdlr_entry_body',
            EntryMore => '$Core::MT::Template::Tags::Entry::_hdlr_entry_more',
            EntryExcerpt =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entry_excerpt',
            EntryKeywords =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entry_keywords',
            EntryLink => '$Core::MT::Template::Tags::Entry::_hdlr_entry_link',
            EntryBasename =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entry_basename',
            EntryAtomID =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entry_atom_id',
            EntryPermalink =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entry_permalink',
            EntryClass =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entry_class',
            EntryClassLabel =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entry_class_label',
            EntryAuthor =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entry_author',
            EntryAuthorDisplayName =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entry_author_display_name',
            EntryAuthorNickname =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entry_author_nick',
            EntryAuthorUsername =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entry_author_username',
            EntryAuthorEmail =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entry_author_email',
            EntryAuthorURL =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entry_author_url',
            EntryAuthorLink =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entry_author_link',
            EntryAuthorID =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entry_author_id',

            AuthorEntryCount =>
                '$Core::MT::Template::Tags::Entry::_hdlr_author_entry_count',
            EntryDate => '$Core::MT::Template::Tags::Entry::_hdlr_entry_date',
            EntryCreatedDate =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entry_create_date',
            EntryModifiedDate =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entry_mod_date',

            EntryBlogID =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entry_blog_id',
            EntryBlogName =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entry_blog_name',
            EntryBlogDescription =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entry_blog_description',
            EntryBlogURL =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entry_blog_url',
            EntryEditLink =>
                '$Core::MT::Template::Tags::Entry::_hdlr_entry_edit_link',
            BlogEntryCount =>
                '$Core::MT::Template::Tags::Entry::_hdlr_blog_entry_count',

            ## Comment
            CommentID =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_id',
            CommentBlogID =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_blog_id',
            CommentEntryID =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_entry_id',
            CommentName =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_author',
            CommentIP =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_ip',
            CommentAuthor =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_author',
            CommentAuthorLink =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_author_link',
            CommentAuthorIdentity =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_author_identity',
            CommentEmail =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_email',
            CommentLink =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_link',
            CommentURL =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_url',
            CommentBody =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_body',
            CommentOrderNumber =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_order_num',
            CommentDate =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_date',
            CommentParentID =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_parent_id',
            CommentReplyToLink =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_reply_link',
            CommentPreviewAuthor =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_author',
            CommentPreviewIP =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_ip',
            CommentPreviewAuthorLink =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_author_link',
            CommentPreviewEmail =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_email',
            CommentPreviewURL =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_url',
            CommentPreviewBody =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_body',
            CommentPreviewDate => \&build_date,
            CommentPreviewState =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_prev_state',
            CommentPreviewIsStatic =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_prev_static',
            CommentRepliesRecurse =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_replies_recurse',
            BlogCommentCount =>
                '$Core::MT::Template::Tags::Comment::_hdlr_blog_comment_count',
            WebsiteCommentCount =>
                '$Core::MT::Template::Tags::Comment::_hdlr_blog_comment_count',
            EntryCommentCount =>
                '$Core::MT::Template::Tags::Comment::_hdlr_entry_comments',
            CategoryCommentCount =>
                '$Core::MT::Template::Tags::Comment::_hdlr_category_comment_count',
            TypeKeyToken =>
                '$Core::MT::Template::Tags::Comment::_hdlr_typekey_token',
            CommentFields =>
                '$Core::MT::Template::Tags::Comment::_hdlr_comment_fields',
            RemoteSignOutLink =>
                '$Core::MT::Template::Tags::Comment::_hdlr_remote_sign_out_link',
            RemoteSignInLink =>
                '$Core::MT::Template::Tags::Comment::_hdlr_remote_sign_in_link',
            SignOutLink =>
                '$Core::MT::Template::Tags::Comment::_hdlr_sign_out_link',
            SignInLink =>
                '$Core::MT::Template::Tags::Comment::_hdlr_sign_in_link',
            SignOnURL =>
                '$Core::MT::Template::Tags::Comment::_hdlr_signon_url',

            ## Ping', => {
            PingsSentURL =>
                '$Core::MT::Template::Tags::Ping::_hdlr_pings_sent_url',
            PingTitle => '$Core::MT::Template::Tags::Ping::_hdlr_ping_title',
            PingID    => '$Core::MT::Template::Tags::Ping::_hdlr_ping_id',
            PingURL   => '$Core::MT::Template::Tags::Ping::_hdlr_ping_url',
            PingExcerpt =>
                '$Core::MT::Template::Tags::Ping::_hdlr_ping_excerpt',
            PingBlogName =>
                '$Core::MT::Template::Tags::Ping::_hdlr_ping_blog_name',
            PingIP   => '$Core::MT::Template::Tags::Ping::_hdlr_ping_ip',
            PingDate => '$Core::MT::Template::Tags::Ping::_hdlr_ping_date',
            BlogPingCount =>
                '$Core::MT::Template::Tags::Ping::_hdlr_blog_ping_count',
            WebsitePingCount =>
                '$Core::MT::Template::Tags::Ping::_hdlr_blog_ping_count',
            EntryTrackbackCount =>
                '$Core::MT::Template::Tags::Ping::_hdlr_entry_ping_count',
            EntryTrackbackLink =>
                '$Core::MT::Template::Tags::Ping::_hdlr_entry_tb_link',
            EntryTrackbackData =>
                '$Core::MT::Template::Tags::Ping::_hdlr_entry_tb_data',
            EntryTrackbackID =>
                '$Core::MT::Template::Tags::Ping::_hdlr_entry_tb_id',
            CategoryTrackbackLink =>
                '$Core::MT::Template::Tags::Ping::_hdlr_category_tb_link',
            CategoryTrackbackCount =>
                '$Core::MT::Template::Tags::Ping::_hdlr_category_tb_count',

            ## Category
            CategoryID =>
                '$Core::MT::Template::Tags::Category::_hdlr_category_id',
            CategoryLabel =>
                '$Core::MT::Template::Tags::Category::_hdlr_category_label',
            CategoryBasename =>
                '$Core::MT::Template::Tags::Category::_hdlr_category_basename',
            CategoryDescription =>
                '$Core::MT::Template::Tags::Category::_hdlr_category_desc',
            CategoryArchiveLink =>
                '$Core::MT::Template::Tags::Category::_hdlr_category_archive',
            CategoryCount =>
                '$Core::MT::Template::Tags::Category::_hdlr_category_count',
            SubCatsRecurse =>
                '$Core::MT::Template::Tags::Category::_hdlr_sub_cats_recurse',
            SubCategoryPath =>
                '$Core::MT::Template::Tags::Category::_hdlr_sub_category_path',
            BlogCategoryCount =>
                '$Core::MT::Template::Tags::Category::_hdlr_blog_category_count',
            ArchiveCategory =>
                '$Core::MT::Template::Tags::Category::_hdlr_archive_category',
            EntryCategory =>
                '$Core::MT::Template::Tags::Category::_hdlr_entry_category',

            ## Page
            PageID    => '$Core::MT::Template::Tags::Page::_hdlr_page_id',
            PageTitle => '$Core::MT::Template::Tags::Page::_hdlr_page_title',
            PageBody  => '$Core::MT::Template::Tags::Page::_hdlr_page_body',
            PageMore  => '$Core::MT::Template::Tags::Page::_hdlr_page_more',
            PageDate  => '$Core::MT::Template::Tags::Page::_hdlr_page_date',
            PageModifiedDate =>
                '$Core::MT::Template::Tags::Page::_hdlr_page_modified_date',
            PageKeywords =>
                '$Core::MT::Template::Tags::Page::_hdlr_page_keywords',
            PageBasename =>
                '$Core::MT::Template::Tags::Page::_hdlr_page_basename',
            PagePermalink =>
                '$Core::MT::Template::Tags::Page::_hdlr_page_permalink',
            PageAuthorDisplayName =>
                '$Core::MT::Template::Tags::Page::_hdlr_page_author_display_name',
            PageAuthorEmail =>
                '$Core::MT::Template::Tags::Page::_hdlr_page_author_email',
            PageAuthorLink =>
                '$Core::MT::Template::Tags::Page::_hdlr_page_author_link',
            PageAuthorURL =>
                '$Core::MT::Template::Tags::Page::_hdlr_page_author_url',
            PageExcerpt =>
                '$Core::MT::Template::Tags::Page::_hdlr_page_excerpt',
            BlogPageCount =>
                '$Core::MT::Template::Tags::Page::_hdlr_blog_page_count',
            WebsitePageCount =>
                '$Core::MT::Template::Tags::Page::_hdlr_blog_page_count',

            ## Folder
            FolderBasename =>
                '$Core::MT::Template::Tags::Folder::_hdlr_folder_basename',
            FolderCount =>
                '$Core::MT::Template::Tags::Folder::_hdlr_folder_count',
            FolderDescription =>
                '$Core::MT::Template::Tags::Folder::_hdlr_folder_description',
            FolderID => '$Core::MT::Template::Tags::Folder::_hdlr_folder_id',
            FolderLabel =>
                '$Core::MT::Template::Tags::Folder::_hdlr_folder_label',
            FolderPath =>
                '$Core::MT::Template::Tags::Folder::_hdlr_folder_path',
            SubFolderRecurse =>
                '$Core::MT::Template::Tags::Folder::_hdlr_sub_folder_recurse',

            ## Asset
            AssetID => '$Core::MT::Template::Tags::Asset::_hdlr_asset_id',
            AssetFileName =>
                '$Core::MT::Template::Tags::Asset::_hdlr_asset_file_name',
            AssetLabel =>
                '$Core::MT::Template::Tags::Asset::_hdlr_asset_label',
            AssetURL  => '$Core::MT::Template::Tags::Asset::_hdlr_asset_url',
            AssetType => '$Core::MT::Template::Tags::Asset::_hdlr_asset_type',
            AssetMimeType =>
                '$Core::MT::Template::Tags::Asset::_hdlr_asset_mime_type',
            AssetFilePath =>
                '$Core::MT::Template::Tags::Asset::_hdlr_asset_file_path',
            AssetDateAdded =>
                '$Core::MT::Template::Tags::Asset::_hdlr_asset_date_added',
            AssetAddedBy =>
                '$Core::MT::Template::Tags::Asset::_hdlr_asset_added_by',
            AssetProperty =>
                '$Core::MT::Template::Tags::Asset::_hdlr_asset_property',
            AssetFileExt =>
                '$Core::MT::Template::Tags::Asset::_hdlr_asset_file_ext',
            AssetThumbnailURL =>
                '$Core::MT::Template::Tags::Asset::_hdlr_asset_thumbnail_url',
            AssetLink => '$Core::MT::Template::Tags::Asset::_hdlr_asset_link',
            AssetThumbnailLink =>
                '$Core::MT::Template::Tags::Asset::_hdlr_asset_thumbnail_link',
            AssetDescription =>
                '$Core::MT::Template::Tags::Asset::_hdlr_asset_description',
            AssetCount =>
                '$Core::MT::Template::Tags::Asset::_hdlr_asset_count',

            ## Userpic
            AuthorUserpic =>
                '$Core::MT::Template::Tags::Userpic::_hdlr_author_userpic',
            AuthorUserpicURL =>
                '$Core::MT::Template::Tags::Userpic::_hdlr_author_userpic_url',
            EntryAuthorUserpic =>
                '$Core::MT::Template::Tags::Userpic::_hdlr_entry_author_userpic',
            EntryAuthorUserpicURL =>
                '$Core::MT::Template::Tags::Userpic::_hdlr_entry_author_userpic_url',
            CommenterUserpic =>
                '$Core::MT::Template::Tags::Userpic::_hdlr_commenter_userpic',
            CommenterUserpicURL =>
                '$Core::MT::Template::Tags::Userpic::_hdlr_commenter_userpic_url',

            ## Tag
            TagName  => '$Core::MT::Template::Tags::Tag::_hdlr_tag_name',
            TagLabel => '$Core::MT::Template::Tags::Tag::_hdlr_tag_name',
            TagID    => '$Core::MT::Template::Tags::Tag::_hdlr_tag_id',
            TagCount => '$Core::MT::Template::Tags::Tag::_hdlr_tag_count',
            TagRank  => '$Core::MT::Template::Tags::Tag::_hdlr_tag_rank',
            TagSearchLink =>
                '$Core::MT::Template::Tags::Tag::_hdlr_tag_search_link',

            ## Calendar
            CalendarDay =>
                '$Core::MT::Template::Tags::Calendar::_hdlr_calendar_day',
            CalendarCellNumber =>
                '$Core::MT::Template::Tags::Calendar::_hdlr_calendar_cell_num',
            CalendarDate => \&build_date,

            ## Score
            # Rating related handlers
            EntryScore =>
                '$Core::MT::Template::Tags::Score::_hdlr_entry_score',
            CommentScore =>
                '$Core::MT::Template::Tags::Score::_hdlr_comment_score',
            PingScore => '$Core::MT::Template::Tags::Score::_hdlr_ping_score',
            AssetScore =>
                '$Core::MT::Template::Tags::Score::_hdlr_asset_score',
            AuthorScore =>
                '$Core::MT::Template::Tags::Score::_hdlr_author_score',

            EntryScoreHigh =>
                '$Core::MT::Template::Tags::Score::_hdlr_entry_score_high',
            CommentScoreHigh =>
                '$Core::MT::Template::Tags::Score::_hdlr_comment_score_high',
            PingScoreHigh =>
                '$Core::MT::Template::Tags::Score::_hdlr_ping_score_high',
            AssetScoreHigh =>
                '$Core::MT::Template::Tags::Score::_hdlr_asset_score_high',
            AuthorScoreHigh =>
                '$Core::MT::Template::Tags::Score::_hdlr_author_score_high',

            EntryScoreLow =>
                '$Core::MT::Template::Tags::Score::_hdlr_entry_score_low',
            CommentScoreLow =>
                '$Core::MT::Template::Tags::Score::_hdlr_comment_score_low',
            PingScoreLow =>
                '$Core::MT::Template::Tags::Score::_hdlr_ping_score_low',
            AssetScoreLow =>
                '$Core::MT::Template::Tags::Score::_hdlr_asset_score_low',
            AuthorScoreLow =>
                '$Core::MT::Template::Tags::Score::_hdlr_author_score_low',

            EntryScoreAvg =>
                '$Core::MT::Template::Tags::Score::_hdlr_entry_score_avg',
            CommentScoreAvg =>
                '$Core::MT::Template::Tags::Score::_hdlr_comment_score_avg',
            PingScoreAvg =>
                '$Core::MT::Template::Tags::Score::_hdlr_ping_score_avg',
            AssetScoreAvg =>
                '$Core::MT::Template::Tags::Score::_hdlr_asset_score_avg',
            AuthorScoreAvg =>
                '$Core::MT::Template::Tags::Score::_hdlr_author_score_avg',

            EntryScoreCount =>
                '$Core::MT::Template::Tags::Score::_hdlr_entry_score_count',
            CommentScoreCount =>
                '$Core::MT::Template::Tags::Score::_hdlr_comment_score_count',
            PingScoreCount =>
                '$Core::MT::Template::Tags::Score::_hdlr_ping_score_count',
            AssetScoreCount =>
                '$Core::MT::Template::Tags::Score::_hdlr_asset_score_count',
            AuthorScoreCount =>
                '$Core::MT::Template::Tags::Score::_hdlr_author_score_count',

            EntryRank => '$Core::MT::Template::Tags::Score::_hdlr_entry_rank',
            CommentRank =>
                '$Core::MT::Template::Tags::Score::_hdlr_comment_rank',
            PingRank  => '$Core::MT::Template::Tags::Score::_hdlr_ping_rank',
            AssetRank => '$Core::MT::Template::Tags::Score::_hdlr_asset_rank',
            AuthorRank =>
                '$Core::MT::Template::Tags::Score::_hdlr_author_rank',

            ## Pager
            PagerLink => '$Core::MT::Template::Tags::Pager::_hdlr_pager_link',
            NextLink  => '$Core::MT::Template::Tags::Pager::_hdlr_next_link',
            PreviousLink =>
                '$Core::MT::Template::Tags::Pager::_hdlr_previous_link',
            CurrentPage =>
                '$Core::MT::Template::Tags::Pager::_hdlr_current_page',
            TotalPages =>
                '$Core::MT::Template::Tags::Pager::_hdlr_total_pages',

            ## Search
            # stubs for mt-search tags used in template includes
            SearchString      => sub {''},
            SearchResultCount => sub {0},
            MaxResults        => sub {''},
            SearchMaxResults =>
                '$Core::MT::Template::Tags::Search::_hdlr_search_max_results',
            SearchIncludeBlogs   => sub {''},
            SearchTemplateID     => sub {0},
            SearchTemplateBlogID => sub {0},

            ## Misc
            FeedbackScore =>
                '$Core::MT::Template::Tags::Misc::_hdlr_feedback_score',
            ImageURL => '$Core::MT::Template::Tags::Misc::_hdlr_image_url',
            ImageWidth =>
                '$Core::MT::Template::Tags::Misc::_hdlr_image_width',
            ImageHeight =>
                '$Core::MT::Template::Tags::Misc::_hdlr_image_height',
            WidgetManager =>
                '$Core::MT::Template::Tags::Misc::_hdlr_widget_manager',
            WidgetSet =>
                '$Core::MT::Template::Tags::Misc::_hdlr_widget_manager',
            CaptchaFields =>
                '$Core::MT::Template::Tags::Misc::_hdlr_captcha_fields',
        },
        modifier => {
            'numify'  => '$Core::MT::Template::Tags::Filters::_fltr_numify',
            'mteval'  => '$Core::MT::Template::Tags::Filters::_fltr_mteval',
            'filters' => '$Core::MT::Template::Tags::Filters::_fltr_filters',
            'trim_to' => '$Core::MT::Template::Tags::Filters::_fltr_trim_to',
            'trim'    => '$Core::MT::Template::Tags::Filters::_fltr_trim',
            'ltrim'   => '$Core::MT::Template::Tags::Filters::_fltr_ltrim',
            'rtrim'   => '$Core::MT::Template::Tags::Filters::_fltr_rtrim',
            'decode_html' =>
                '$Core::MT::Template::Tags::Filters::_fltr_decode_html',
            'decode_xml' =>
                '$Core::MT::Template::Tags::Filters::_fltr_decode_xml',
            'remove_html' =>
                '$Core::MT::Template::Tags::Filters::_fltr_remove_html',
            'dirify' => '$Core::MT::Template::Tags::Filters::_fltr_dirify',
            'sanitize' =>
                '$Core::MT::Template::Tags::Filters::_fltr_sanitize',
            'encode_sha1' => '$Core::MT::Template::Tags::Filters::_fltr_sha1',
            'encode_html' =>
                '$Core::MT::Template::Tags::Filters::_fltr_encode_html',
            'encode_xml' =>
                '$Core::MT::Template::Tags::Filters::_fltr_encode_xml',
            'encode_js' =>
                '$Core::MT::Template::Tags::Filters::_fltr_encode_js',
            'encode_php' =>
                '$Core::MT::Template::Tags::Filters::_fltr_encode_php',
            'encode_url' =>
                '$Core::MT::Template::Tags::Filters::_fltr_encode_url',
            'upper_case' =>
                '$Core::MT::Template::Tags::Filters::_fltr_upper_case',
            'lower_case' =>
                '$Core::MT::Template::Tags::Filters::_fltr_lower_case',
            'strip_linefeeds' =>
                '$Core::MT::Template::Tags::Filters::_fltr_strip_linefeeds',
            'space_pad' =>
                '$Core::MT::Template::Tags::Filters::_fltr_space_pad',
            'zero_pad' =>
                '$Core::MT::Template::Tags::Filters::_fltr_zero_pad',
            'sprintf' => '$Core::MT::Template::Tags::Filters::_fltr_sprintf',
            'regex_replace' =>
                '$Core::MT::Template::Tags::Filters::_fltr_regex_replace',
            'capitalize' =>
                '$Core::MT::Template::Tags::Filters::_fltr_capitalize',
            'count_characters' =>
                '$Core::MT::Template::Tags::Filters::_fltr_count_characters',
            'cat' => '$Core::MT::Template::Tags::Filters::_fltr_cat',
            'count_paragraphs' =>
                '$Core::MT::Template::Tags::Filters::_fltr_count_paragraphs',
            'count_words' =>
                '$Core::MT::Template::Tags::Filters::_fltr_count_words',
            'escape'  => '$Core::MT::Template::Tags::Filters::_fltr_escape',
            'indent'  => '$Core::MT::Template::Tags::Filters::_fltr_indent',
            'nl2br'   => '$Core::MT::Template::Tags::Filters::_fltr_nl2br',
            'replace' => '$Core::MT::Template::Tags::Filters::_fltr_replace',
            'spacify' => '$Core::MT::Template::Tags::Filters::_fltr_spacify',
            'string_format' =>
                '$Core::MT::Template::Tags::Filters::_fltr_sprintf',
            'strip' => '$Core::MT::Template::Tags::Filters::_fltr_strip',
            'strip_tags' =>
                '$Core::MT::Template::Tags::Filters::_fltr_strip_tags',
            '_default' => '$Core::MT::Template::Tags::Filters::_fltr_default',
            'nofollowfy' =>
                '$Core::MT::Template::Tags::Filters::_fltr_nofollowfy',
            'wrap_text' =>
                '$Core::MT::Template::Tags::Filters::_fltr_wrap_text',
            'setvar' => '$Core::MT::Template::Tags::Filters::_fltr_setvar',
        },
    };
    return $tags;
}

## used in both Comment.pm and Ping.pm
sub sanitize_on {
    my ( $ctx, $args ) = @_;
    ## backward compatibility. in MT4, this didn't take $ctx.
    if ( !UNIVERSAL::isa( $ctx, 'MT::Template::Context' ) ) {
        $args = $ctx;
    }
    unless ( exists $args->{'sanitize'} ) {

        # Important to come before other manipulation attributes
        # like encode_xml
        unshift @{ $args->{'@'} ||= [] }, [ 'sanitize' => 1 ];
        $args->{'sanitize'} = 1;
    }
}

## used in Ping.pm
sub nofollowfy_on {
    my ( $ctx, $args ) = @_;
    unless ( exists $args->{'nofollowfy'} ) {
        $args->{'nofollowfy'} = 1;
    }
}

## used in both Category.pm and Entry.pm.
sub cat_path_to_category {
    ## for backward compatibility.
    shift if UNIVERSAL::isa( $_[0], 'MT::Template::Context' );
    my ( $path, $blog_id, $class_type ) = @_;

    my $class = MT->model($class_type);

  # The argument version always takes precedence
  # followed by the current category (i.e. MTCategories/MTSubCategories style)
  # then the current category for the archive
  # then undef
    my @cat_path = $path
        =~ m@(\[[^]]+?\]|[^]/]+)@g;    # split on slashes, fields quoted by []
    @cat_path = map { $_ =~ s/^\[(.*)\]$/$1/; $_ } @cat_path;  # remove any []
    my $last_cat_id = 0;
    my $cat;
    my ( %blog_terms, %blog_args );
    if ( ref $blog_id eq 'ARRAY' ) {
        %blog_terms = %{ $blog_id->[0] };
        %blog_args  = %{ $blog_id->[1] };
    }
    elsif ($blog_id) {
        $blog_terms{blog_id} = $blog_id;
    }

    my $top  = shift @cat_path;
    my @cats = $class->load(
        {   label  => $top,
            parent => 0,
            %blog_terms
        },
        \%blog_args
    );
    if (@cats) {
        for my $label (@cat_path) {
            my @parents = map { $_->id } @cats;
            @cats = $class->load(
                {   label  => $label,
                    parent => \@parents,
                    %blog_terms
                },
                \%blog_args
            ) or last;
        }
    }
    if ( !@cats && $path ) {
        @cats = (
            $class->load(
                {   label => $path,
                    %blog_terms,
                },
                \%blog_args
            )
        );
    }
    @cats;
}

## for backward compatibility
sub _hdlr_pass_tokens      { shift->slurp(@_) }
sub _hdlr_pass_tokens_else { shift->else(@_) }

sub build_date {
    my ( $ctx, $args ) = @_;
    my $ts = $args->{ts} || $ctx->{current_timestamp};
    my $tag = $ctx->stash('tag');
    return $ctx->error(
        MT->translate(
            "You used an [_1] tag without a date context set up.", "MT$tag"
        )
    ) unless defined $ts;
    my $blog = $ctx->stash('blog');
    unless ( ref $blog ) {
        my $blog_id = $blog || $args->{offset_blog_id};
        if ($blog_id) {
            $blog = MT->model('blog')->load($blog_id);
            return $ctx->error(
                MT->translate( 'Can\'t load blog #[_1].', $blog_id ) )
                unless $blog;
        }
    }
    my $lang
        = $args->{language}
        || $ctx->var('local_lang_id')
        || ( $blog && $blog->language );
    if ( $args->{utc} ) {
        my ( $y, $mo, $d, $h, $m, $s )
            = $ts
            =~ /(\d\d\d\d)[^\d]?(\d\d)[^\d]?(\d\d)[^\d]?(\d\d)[^\d]?(\d\d)[^\d]?(\d\d)/;
        $mo--;
        my $server_offset = ( $blog && $blog->server_offset )
            || MT->config->TimeOffset;
        if ( ( localtime( timelocal( $s, $m, $h, $d, $mo, $y ) ) )[8] ) {
            $server_offset += 1;
        }
        my $four_digit_offset = sprintf( '%.02d%.02d',
            int($server_offset),
            60 * abs( $server_offset - int($server_offset) ) );
        require MT::DateTime;
        my $tz_secs = MT::DateTime->tz_offset_as_seconds($four_digit_offset);
        my $ts_utc = Time::Local::timegm_nocheck( $s, $m, $h, $d, $mo, $y );
        $ts_utc -= $tz_secs;
        ( $s, $m, $h, $d, $mo, $y ) = gmtime($ts_utc);
        $y += 1900;
        $mo++;
        $ts = sprintf( "%04d%02d%02d%02d%02d%02d", $y, $mo, $d, $h, $m, $s );
    }
    if ( my $format = lc( $args->{format_name} || '' ) ) {
        my $tz = 'Z';
        unless ( $args->{utc} ) {
            my $so = ( $blog && $blog->server_offset )
                || MT->config->TimeOffset;
            my $partial_hour_offset = 60 * abs( $so - int($so) );
            if ( $format eq 'rfc822' ) {
                $tz = sprintf( "%s%02d%02d",
                    $so < 0 ? '-' : '+',
                    abs($so), $partial_hour_offset );
            }
            elsif ( $format eq 'iso8601' ) {
                $tz = sprintf( "%s%02d:%02d",
                    $so < 0 ? '-' : '+',
                    abs($so), $partial_hour_offset );
            }
        }
        if ( $format eq 'rfc822' ) {
            ## RFC-822 dates must be in English.
            $args->{'format'} = '%a, %d %b %Y %H:%M:%S ' . $tz;
            $lang = 'en';
        }
        elsif ( $format eq 'iso8601' ) {
            $args->{format} = '%Y-%m-%dT%H:%M:%S' . $tz;
        }
    }
    if ( my $r = $args->{relative} ) {
        if ( $r eq 'js' ) {

            # output javascript here to render relative date
            my ( $y, $mo, $d, $h, $m, $s )
                = $ts
                =~ /(\d\d\d\d)[^\d]?(\d\d)[^\d]?(\d\d)[^\d]?(\d\d)[^\d]?(\d\d)[^\d]?(\d\d)/;
            $mo--;
            my $fds = format_ts( $args->{'format'}, $ts, $blog, $lang );
            my $js = <<EOT;
<script type="text/javascript">
/* <![CDATA[ */
document.write(mtRelativeDate(new Date($y,$mo,$d,$h,$m,$s), '$fds'));
/* ]]> */
</script><noscript>$fds</noscript>
EOT
            return $js;
        }
        else {
            my $old_lang = MT->current_language;
            MT->set_language($lang) if $lang && ( $lang ne $old_lang );
            my $date = relative_date( $ts, time, $blog, $args->{format}, $r );
            MT->set_language($old_lang) if $lang && ( $lang ne $old_lang );
            if ($date) {
                return $date;
            }
            else {
                if ( !$args->{format} ) {
                    return '';
                }
            }
        }
    }
    my $mail_flag = $args->{mail} || 0;
    return format_ts( $args->{'format'}, $ts, $blog, $lang, $mail_flag );
}

*_hdlr_date = *build_date;

sub cgi_path {
    my ($ctx) = @_;
    my $path = $ctx->{config}->CGIPath;
    if ( $path =~ m!^/! ) {

        # relative path, prepend blog domain
        if ( my $blog = $ctx->stash('blog') ) {
            my ($blog_domain) = $blog->archive_url =~ m|(.+://[^/]+)|;
            $path = $blog_domain . $path;
        }
    }
    $path .= '/' unless $path =~ m{/$};
    return $path;
}

sub check_page {
    my ($ctx) = @_;
    my $e = $ctx->stash('entry')
        or return $ctx->_no_page_error();
    return $ctx->_no_page_error()
        if ref $e ne 'MT::Page';
    1;
}
*_check_page = *check_page;

package MT::Template::Tags::Core;
use strict;

use MT::Util qw(deep_copy);

sub _math_operation {
    my ( $ctx, $op, $lvalue, $rvalue ) = @_;
    return $lvalue
        unless ( $lvalue =~ m/^\-?[\d\.]+$/ )
        && (
        ( defined($rvalue) && ( $rvalue =~ m/^\-?[\d\.]+$/ ) )
        || (   ( $op eq 'inc' )
            || ( $op eq 'dec' )
            || ( $op eq '++' )
            || ( $op eq '--' ) )
        );
    if ( ( '+' eq $op ) || ( 'add' eq $op ) ) {
        return $lvalue + $rvalue;
    }
    elsif ( ( '++' eq $op ) || ( 'inc' eq $op ) ) {
        return $lvalue + 1;
    }
    elsif ( ( '-' eq $op ) || ( 'sub' eq $op ) ) {
        return $lvalue - $rvalue;
    }
    elsif ( ( '--' eq $op ) || ( 'dec' eq $op ) ) {
        return $lvalue - 1;
    }
    elsif ( ( '*' eq $op ) || ( 'mul' eq $op ) ) {
        return $lvalue * $rvalue;
    }
    elsif ( ( '/' eq $op ) || ( 'div' eq $op ) ) {
        return $ctx->error( MT->translate('Division by zero.') )
            if $rvalue == 0;
        return $lvalue / $rvalue;
    }
    elsif ( ( '%' eq $op ) || ( 'mod' eq $op ) ) {

        # Perl % is integer only
        $lvalue = int($lvalue);
        $rvalue = int($rvalue);
        return $ctx->error( MT->translate('Division by zero.') )
            if $rvalue == 0;
        return $lvalue % $rvalue;
    }
    return $lvalue;
}

###########################################################################

=head2 If

A conditional block that is evaluated if the attributes/modifiers evaluate
true. This tag can be used in combination with the L<ElseIf> and L<Else>
tags to test for a variety of cases.

B<Attributes:>

=over 4

=item * name

=item * var

Declares a variable to test. When none of the comparison attributes are
present ("eq", "ne", "lt", etc.) the If tag tests if the variable has
a "true" value, meaning if it is assigned a non-empty, non-zero value.

=item * tag

Declares a MT tag to execute; the value of which is used for testing.
When none of the comparison attributes are present ("eq", "ne", "lt", etc.)
the If tag tests if the specified tag produces a "true" value, meaning if
it produces a non-empty, non-zero value. For MT conditional tags, the
If tag passes through the logical result of that conditional tag.

=item * op

If specified, applies the specified mathematical operator to the value
being tested. 'op' may be one of the following (those that require a
second value use the 'value' attribute):

=over 4

=item * + or add

Addition.

=item * - or sub

Subtraction.

=item * ++ or inc

Adds 1 to the given value.

=item * -- or dec

Subtracts 1 from the given value.

=item * * or mul

Multiplication.

=item * / or div

Division.

=item * % or mod

Issues a modulus operator.

=back

=item * value

Used in conjunction with the 'op' attribute.

=item * eq

Tests whether the given value is equal to the value of the 'eq' attribute.

=item * ne

Tests whether the given value is not equal to the value of the 'ne' attribute.

=item * gt

Tests whether the given value is greater than the value of the 'gt' attribute.

=item * lt

Tests whether the given value is less than the value of the 'lt' attribute.

=item * ge

Tests whether the given value is greater than or equal to the value of the
'ge' attribute.

=item * le

Tests whether the given value is less than or equal to the value of the
'le' attribute.

=item * like

Tests whether the given value matches the regex pattern in the 'like'
attribute.

=item * test

Uses a Perl (or PHP under Dynamic Publishing) expression. For Perl, this
requires the "Safe" Perl module to be installed.

=back

B<Examples:>

If variable "foo" has a non-zero value:

    <mt:SetVar name="foo" value="bar">
    <mt:If name="foo">
        <!-- do something -->
    </mt:If>

If variable "foo" has a value equal to "bar":

    <mt:SetVar name="foo" value="bar">
    <mt:If name="foo" eq="bar">
        <!-- do something -->
    </mt:If>

If variable "foo" has a value that starts with "bar" or "baz":

    <mt:SetVar name="foo" value="barcamp" />
    <mt:If name="foo" like="^(bar|baz)">
        <!-- do something -->
    </mt:If>

If tag <$mt:EntryTitle$> has a value of "hello world":

    <mt:If tag="EntryTitle" eq="hello world">
        <!-- do something -->
    </mt:If>

If tag <$mt:CategoryCount$> is greater than 10 add "(Popular)" after
Category Label:

    <mt:Categories>
        <$mt:CategoryLabel$>
        <mt:If tag="CategoryCount" gt="10">(Popular)</mt:If>
    </mt:Categories>


If tag <$mt:EntryAuthor$> is "Melody" or "melody" and last name is "Nelson"
or "nelson" then do something:

    <mt:Authors>
        <mt:If tag="EntryAuthor" like="/(M|m)elody (N|n)elson/"
            <!-- do something -->
        </mt:If>
    </mt:Authors>

If the <$mt:CommenterEmail$> matches foo@domain.com or bar@domain.com:

    <mt:If tag="CommenterEmail" like="(foo@domain.com|bar@domain.com)">
        <!-- do something -->
    </mt:If>

If the <$mt:CommenterUsername$> matches the username of someone on the
Movable Type team:

    <mt:If tag="CommenterUsername" like="(beau|byrne|brad|jim|mark|fumiaki|yuji|djchall)">
        <!-- do something -->
    </mt:If>

If <$mt:EntryCategory$> is "Comic" then use the Comic template module
otherwise use the default:

    <mt:If tag="EntryCategory" eq="Comic">
        <$mt:Include module="Comic Entry Detail"$>
    <mt:Else>
        <$mt:Include module="Entry Detail"$>
    </mt:If>

If <$mt:EntryCategory$> is "Comic", "Sports", or "News" then link to the
category archive:

    <mt:If tag="EntryCategory" like="(Comic|Sports|News)">
        <a href="<$mt:CategoryArchiveLink$>"><$mt:CategoryLabel$></a>
    <mt:Else>
        <$mt:CategoryLabel$>
    </mt:If>

List all categories and link to categories it the category has one or more
entries:

    <mt:Categories show_empty="1">
        <mt:If name="__first__">
    <ul>
        </mt:If>
        <mt:If tag="CategoryCount" gte="1">
        <li><a href="<$MTCategoryArchiveLink$>"><$MTCategoryLabel$></a></li>
        <mt:Else>
        <li><$MTCategoryLabel$></li>
        </mt:If>
        <mt:If name="__last__">
    </ul>
        </mt:If>
    </mt:Categories>

Test a variable using Perl:

    <mt:If test="length($some_variable) > 10">
        '<$mt:Var name="some_variable"$>' is 11 characters or longer
    </mt:If>

=for tags templating

=cut

sub _hdlr_if {
    my ( $ctx, $args, $cond ) = @_;
    my $var = $args->{name} || $args->{var};
    my $value;
    if ( defined $var ) {

        # pick off any {...} or [...] from the name.
        my ( $index, $key );
        if ( $var =~ m/^(.+)([\[\{])(.+)[\]\}]$/ ) {
            $var = $1;
            my $br  = $2;
            my $ref = $3;
            if ( $ref =~ m/^\$(.+)/ ) {
                $ref = $ctx->var($1);
            }
            $br eq '[' ? $index = $ref : $key = $ref;
        }
        else {
            $index = $args->{index} if exists $args->{index};
            $key   = $args->{key}   if exists $args->{key};
        }

        $value = $ctx->var($var);
        if ( ref($value) ) {
            if ( UNIVERSAL::isa( $value, 'MT::Template' ) ) {
                local $value->{context} = $ctx;
                $value = $value->output();
            }
            elsif ( UNIVERSAL::isa( $value, 'MT::Template::Tokens' ) ) {
                local $ctx->{__stash}{tokens} = $value;
                $value = $ctx->slurp( $args, $cond ) or return;
            }
            elsif ( ref($value) eq 'ARRAY' ) {
                $value = $value->[$index] if defined $index;
            }
            elsif ( ref($value) eq 'HASH' ) {
                $value = $value->{$key} if defined $key;
            }
        }
    }
    elsif ( defined( my $tag = $args->{tag} ) ) {
        $tag =~ s/^MT:?//i;
        require Storable;
        my $local_args = Storable::dclone($args);
        $value = $ctx->tag( $tag, $local_args, $cond );
    }

    $ctx->{__stash}{vars}{__cond_value__} = $value;
    $ctx->{__stash}{vars}{__cond_name__}  = $var;

    if ( my $op = $args->{op} ) {
        my $rvalue = $args->{'value'};
        if ( $op && ( defined $value ) && !ref($value) ) {
            $value = _math_operation( $ctx, $op, $value, $rvalue );
        }
    }

    my $numeric = qr/^[-]?\d+(\.\d+)?$/;
    no warnings;
    if ( exists $args->{eq} ) {
        return 0 unless defined($value);
        my $eq = $args->{eq};
        if ( $value =~ m/$numeric/ && $eq =~ m/$numeric/ ) {
            return $value == $eq;
        }
        else {
            return $value eq $eq;
        }
    }
    elsif ( exists $args->{ne} ) {
        return 0 unless defined($value);
        my $ne = $args->{ne};
        if ( $value =~ m/$numeric/ && $ne =~ m/$numeric/ ) {
            return $value != $ne;
        }
        else {
            return $value ne $ne;
        }
    }
    elsif ( exists $args->{gt} ) {
        return 0 unless defined($value);
        my $gt = $args->{gt};
        if ( $value =~ m/$numeric/ && $gt =~ m/$numeric/ ) {
            return $value > $gt;
        }
        else {
            return $value gt $gt;
        }
    }
    elsif ( exists $args->{lt} ) {
        return 0 unless defined($value);
        my $lt = $args->{lt};
        if ( $value =~ m/$numeric/ && $lt =~ m/$numeric/ ) {
            return $value < $lt;
        }
        else {
            return $value lt $lt;
        }
    }
    elsif ( exists $args->{ge} ) {
        return 0 unless defined($value);
        my $ge = $args->{ge};
        if ( $value =~ m/$numeric/ && $ge =~ m/$numeric/ ) {
            return $value >= $ge;
        }
        else {
            return $value ge $ge;
        }
    }
    elsif ( exists $args->{le} ) {
        return 0 unless defined($value);
        my $le = $args->{le};
        if ( $value =~ m/$numeric/ && $le =~ m/$numeric/ ) {
            return $value <= $le;
        }
        else {
            return $value le $le;
        }
    }
    elsif ( exists $args->{like} ) {
        my $like = $args->{like};
        if ( !ref $like ) {
            if ( $like =~ m!^/.+/([si]+)?$!s ) {
                my $opt = $1;
                $like =~ s!^/|/([si]+)?$!!g;    # /abc/ => abc
                $like = "(?$opt)" . $like if defined $opt;
            }
            my $re = eval {qr/$like/};
            return 0 unless $re;
            $args->{like} = $like = $re;
        }
        return defined($value) && ( $value =~ m/$like/ ) ? 1 : 0;
    }
    elsif ( exists $args->{test} ) {
        my $expr = $args->{'test'};
        my $safe = $ctx->{__safe_compartment};
        if ( !$safe ) {
            $safe = eval { require Safe; new Safe; }
                or return $ctx->error(
                "Cannot evaluate expression [$expr]: Perl 'Safe' module is required."
                );
            $ctx->{__safe_compartment} = $safe;
        }
        my $vars = $ctx->{__stash}{vars};
        my $ns   = $safe->root;
        {
            no strict 'refs';
            foreach my $v ( keys %$vars ) {

                # or should we be using $ctx->var here ?
                # can we limit this step to just the variables
                # mentioned in $expr ??
                ${ $ns . '::' . $v } = $vars->{$v};
            }
        }

        my @warnings;
        my $res;
        {
            local $SIG{__WARN__} = sub { push( @warnings, $_[0] ); };
            $res = $safe->reval($expr);
        }
        if ($@) {
            return $ctx->error("Error in expression [$expr]: $@");
        }

        # THINK: should return error if there are some warnings?
        # if (@warnings) {
        #     return $ctx->error("Warning in expression [$expr]: @warnings");
        # }

        return $res;
    }
    if ( ( defined $value ) && $value ) {
        if ( ref($value) eq 'ARRAY' ) {
            return @$value ? 1 : 0;
        }
        return 1;
    }
    return 0;
}

###########################################################################

=head2 Unless

A conditional tag that is the logical opposite of the L<If> tag. All
attributes supported by the L<If> tag are also supported for this tag.

=for tags templating

=cut

sub _hdlr_unless {
    defined( my $r = &_hdlr_if ) or return;
    !$r;
}

###########################################################################

=head2 Else

A container tag used within If and Unless blocks to output the alternate
case.

This tag supports all of the attributes and logical operators available in
the L<If> tag and can be used multiple times to test for different
scenarios.

B<Example:>

    <mt:If name="some_variable">
        'some_variable' is assigned
    <mt:Else name="some_other_variable">
        'some_other_variable' is assigned
    <mt:Else>
        'some_variable' nor 'some_other_variable' is assigned
    </mt:If>

=for tags templating

=cut

sub _hdlr_else {
    my ( $ctx, $args, $cond ) = @_;
    local $args->{'@'};
    delete $args->{'@'};
    if ( ( keys %$args ) >= 1 ) {
        unless ( $args->{name} || $args->{var} || $args->{tag} ) {
            if ( my $t = $ctx->var('__cond_tag__') ) {
                $args->{tag} = $t;
            }
            elsif ( my $n = $ctx->var('__cond_name__') ) {
                $args->{name} = $n;
            }
        }
    }
    if (%$args) {
        defined( my $res = _hdlr_if(@_) ) or return;
        return $res ? $ctx->slurp(@_) : $ctx->else();
    }
    return $ctx->slurp(@_);
}

###########################################################################

=head2 ElseIf

An alias for the 'Else' tag.

=for tags templating

=cut

sub _hdlr_elseif {
    my ( $ctx, $args, $cond ) = @_;
    unless ( $args->{name} || $args->{var} || $args->{tag} ) {
        if ( my $t = $ctx->var('__cond_tag__') ) {
            $args->{tag} = $t;
        }
        elsif ( my $n = $ctx->var('__cond_name__') ) {
            $args->{name} = $n;
        }
    }
    return _hdlr_else( $ctx, $args, $cond );
}

###########################################################################

=head2 IfNonEmpty

A conditional tag used to test whether a template variable or tag are
non-empty. This tag is considered deprecated, in favor of the L<If> tag.

B<Attributes:>

=over 4

=item * tag

A tag which is evaluated and tested for non-emptiness.

=item * name or var

A variable whose contents are tested for non-emptiness.

=back

=for tags deprecated

=cut

sub _hdlr_if_nonempty {
    my ( $ctx, $args, $cond ) = @_;
    my $value;
    if ( exists $args->{tag} ) {
        $args->{tag} =~ s/^MT:?//i;
        $value = $ctx->tag( $args->{tag}, $args, $cond );
    }
    elsif ( exists $args->{name} ) {
        $value = $ctx->var( $args->{name} );
    }
    elsif ( exists $args->{var} ) {
        $value = $ctx->var( $args->{var} );
    }
    if ( defined($value) && $value ne '' ) {    # want to include "0" here
        return 1;
    }
    else {
        return 0;
    }
}

###########################################################################

=head2 IfNonZero

A conditional tag used to test whether a template variable or tag are
non-zero. This tag is considered deprecated, in favor of the L<If> tag.

B<Attributes:>

=over 4

=item * tag

A tag which is evaluated and tested for non-zeroness.

=item * name or var

A variable whose contents are tested for non-zeroness.

=back

=for tags deprecated

=cut

sub _hdlr_if_nonzero {
    my ( $ctx, $args, $cond ) = @_;
    my $value;
    if ( exists $args->{tag} ) {
        $args->{tag} =~ s/^MT:?//i;
        $value = $ctx->tag( $args->{tag}, $args, $cond );
    }
    elsif ( exists $args->{name} ) {
        $value = $ctx->var( $args->{name} );
    }
    elsif ( exists $args->{var} ) {
        $value = $ctx->var( $args->{var} );
    }
    if ( defined($value) && $value ) {
        return 1;
    }
    else {
        return 0;
    }
}

###########################################################################

=head2 Loop

This tag is primarily used for MT application templates, for processing
a Perl array of hashref data. This tag's heritage comes from the
CPAN HTML::Template module and it's C<TMPL_LOOP> tag and offers similar
capabilities. This tag can also handle a hashref variable, which
causes it to loop over all keys in the hash.

B<Attributes:>

=over 4

=item * name

=item * var

The template variable that contains the array of hashref data to
process.

=item * sort_by (optional)

Causes the data in the given array to be resorted in the manner
specified. The 'sort_by' attribute may specify "key" or "value"
and may additionally include the keywords "numeric" (to imply
a numeric sort instead of the default alphabetic sort) and/or
"reverse" to force the sort to be done in reverse order.

B<Example:>

    sort_by="key reverse"; sort_by="value numeric"

=item * glue (optional)

If specified, this string will be placed inbetween each "row"
of data produced by the loop tag.

=back

Within the tag, the following variables are assigned and may
be used:

=over 4

=item * __first__

Assigned when the loop is in the first iteration.

=item * __last__

Assigned when the loop is in the last iteration.

=item * __odd__

Assigned 1 when the loop is on odd numbered rows, 0 when even.

=item * __even__

Assigned 1 when the loop is on even numbered rows, 0 when odd.

=item * __key__

When looping over a hashref template variable, this variable is
assigned the key currently in context.

=item * __value__

This variable holds the value of the array or hashref element
currently in context.

=back

=for tags loop, templating

=cut

sub _hdlr_loop {
    my ( $ctx, $args, $cond ) = @_;
    my $name = $args->{name} || $args->{var};
    my $var = $ctx->var($name);
    return ''
        unless $var && ( ( ref($var) eq 'ARRAY' ) && ( scalar @$var ) )
            || ( ( ref($var) eq 'HASH' ) && ( scalar( keys %$var ) ) );

    my $hash_var;
    if ( 'HASH' eq ref($var) ) {
        $hash_var = $var;
        my @keys = keys %$var;
        $var = \@keys;
    }
    if ( my $sort = $args->{sort_by} ) {
        $sort = lc $sort;
        if ( $sort =~ m/\bkey\b/ ) {
            @$var = sort { $a cmp $b } @$var;
        }
        elsif ( $sort =~ m/\bvalue\b/ ) {
            no warnings;
            if ( $sort =~ m/\bnumeric\b/ ) {
                no warnings;
                if ( defined $hash_var ) {
                    @$var
                        = sort { $hash_var->{$a} <=> $hash_var->{$b} } @$var;
                }
                else {
                    @$var = sort { $a <=> $b } @$var;
                }
            }
            else {
                if ( defined $hash_var ) {
                    @$var
                        = sort { $hash_var->{$a} cmp $hash_var->{$b} } @$var;
                }
                else {
                    @$var = sort { $a cmp $b } @$var;
                }
            }
        }
        if ( $sort =~ m/\breverse\b/ ) {
            @$var = reverse @$var;
        }
    }

    my $builder = $ctx->stash('builder');
    my $tokens  = $ctx->stash('tokens');
    my $out     = '';
    my $i       = 1;
    my $vars    = $ctx->{__stash}{vars} ||= {};
    my $glue    = $args->{glue};
    foreach my $item (@$var) {
        local $vars->{__first__}   = $i == 1;
        local $vars->{__last__}    = $i == scalar @$var;
        local $vars->{__odd__}     = ( $i % 2 ) == 1;
        local $vars->{__even__}    = ( $i % 2 ) == 0;
        local $vars->{__counter__} = $i;
        my @names;
        if ( ref $item && UNIVERSAL::isa( $item, 'MT::Object' ) ) {
            @names = @{ $item->column_names };
        }
        else {
            if ( ref($item) eq 'HASH' ) {
                @names = keys %$item;
            }
            elsif ($hash_var) {
                @names = ( '__key__', '__value__' );
            }
            else {
                @names = '__value__';
            }
        }
        my @var_names;
        push @var_names, lc $_ for @names;
        local @{$vars}{@var_names};
        if ( ref $item && UNIVERSAL::isa( $item, 'MT::Object' ) ) {
            $vars->{ lc($_) } = $item->column($_) for @names;
        }
        elsif ( ref($item) eq 'HASH' ) {
            $vars->{ lc($_) } = $item->{$_} for @names;
        }
        elsif ($hash_var) {
            $vars->{'__key__'}   = $item;
            $vars->{'__value__'} = $hash_var->{$item};
        }
        else {
            $vars->{'__value__'} = $item;
        }
        my $res = $builder->build( $ctx, $tokens, $cond );
        return $ctx->error( $builder->errstr ) unless defined $res;
        if ( $res ne '' ) {
            $out .= $glue
                if defined $glue && $i > 1 && length($out) && length($res);
            $out .= $res;
            $i++;
        }
    }
    return $out;
}

###########################################################################

=head2 For

Many programming languages support the notion of a "for" loop. In the most
simple use case one could give, a for loop is a way to repeatedly execute a
piece of code n times.

Technically a for loop advances through a sequence (e.g. all odd numbers, all
even numbers, every nth number, etc), giving the programmer greater control
over the seed value (or "index") of each iteration through the loop.

B<Attributes:>

=over 4

=item * var (optional)

If assigned, the current 'index' of the loop is assigned to this template
variable.

=item * from (optional; default "0")

=item * start

Identifies the starting number for the loop.

=item * to

=item * end

Identifies the ending number for the loop. Either 'to' or 'end' must
be specified.

=item * step (optional; default "1")

=item * increment

Provides the amount to increment the loop counter.

=item * glue (optional)

If specified, this string is added inbetween each block of the loop.

=back

Within the tag, the following variables are assigned:

=over 4

=item * __first__

Assigned 1 when the loop is in the first iteration.

=item * __last__

Assigned 1 when the loop is in the last iteration.

=item * __odd__

Assigned 1 when the loop index is odd, 0 when it is even.

=item * __even__

Assigned 1 when the loop index is even, 0 when it is odd.

=item * __index__

Holds the current loop index value, even if the 'var' attribute has
been given.

=item * __counter__

Tracks the number of times the loop has run (starts at 1).

=back

B<Example:>

    <mt:For from="2" to="10" step="2" glue=","><$mt:Var name="__index__"$></mt:For>

Produces:

    2,4,6,8,10

=for tags loop, templating

=cut

sub _hdlr_for {
    my ( $ctx, $args, $cond ) = @_;

    my $start = ( exists $args->{from} ? $args->{from} : $args->{start} )
        || 0;
    $start = 0 unless $start =~ /^-?\d+$/;
    my $end = ( exists $args->{to} ? $args->{to} : $args->{end} ) || 0;
    return q() unless $end =~ /^-?\d+$/;
    my $incr = $args->{increment} || $args->{step} || 1;

    # FIXME: support negative "step" values
    $incr = 1 unless $incr =~ /^\d+$/;
    $incr = 1 unless $incr;

    my $builder = $ctx->stash('builder');
    my $tokens  = $ctx->stash('tokens');
    my $cnt     = 1;
    my $out     = '';
    my $vars    = $ctx->{__stash}{vars} ||= {};
    my $glue    = $args->{glue};
    my $var     = $args->{var};
    for ( my $i = $start; $i <= $end; $i += $incr ) {
        local $vars->{__first__}   = $i == $start;
        local $vars->{__last__}    = $i == $end;
        local $vars->{__odd__}     = ( $cnt % 2 ) == 1;
        local $vars->{__even__}    = ( $cnt % 2 ) == 0;
        local $vars->{__index__}   = $i;
        local $vars->{__counter__} = $cnt;
        local $vars->{$var} = $i if defined $var;
        my $res = $builder->build( $ctx, $tokens, $cond );
        return $ctx->error( $builder->errstr ) unless defined $res;
        $out .= $glue
            if defined $glue && $cnt > 1 && length($out) && length($res);
        $out .= $res;
        $cnt++;
    }
    return $out;
}

###########################################################################

=head2 SetVarBlock

A block tag used to set the value of a template variable. Note that
you can also use the global 'setvar' modifier to achieve the same result
as it can be applied to any MT tag.

B<Attributes:>

=over 4

=item * var or name (required)

Identifies the name of the template variable. See L<Var> for more
information on the format of this attribute.

=item * op (optional)

See the L<Var> tag for more information about this attribute.

=item * prepend (optional)

If specified, places the contents at the front of any existing value
for the template variable.

=item * append (optional)

If specified, places the contents at the end of any existing value
for the template variable.

=back

=for tags templating

=cut

###########################################################################

=head2 SetVarTemplate

Similar to the L<SetVarBlock> tag, but does not evaluate the contents
of the tag, but saves it for later evaluation, when the variable is
requested. This allows you to create inline template modules that you
can use over and over again.

B<Attributes:>

=over 4

=item * var or name (required)

Identifies the name of the template variable. See L<Var> for more
information on the format of this attribute.

=back

B<Example:>

    <mt:SetVarTemplate name="entry_title">
        <h1><$MTEntryTitle$></h1>
    </mt:SetVarTemplate>

    <mt:Entries>
        <$mt:Var name="entry_title"$>
    </mt:Entries>

=for tags templating

=cut

###########################################################################

=head2 SetVars

A block tag that is useful for assigning multiple template variables at
once.

B<Example:>

    <mt:SetVars>
    title=My Favorite Color
    color=Blue
    </mt:SetVars>

Then later:

    <h1><$mt:Var name="title"$></h1>

    <ul><li><$mt:Var name="color"$></li></ul>

=for tags templating

=cut

sub _hdlr_set_vars {
    my ( $ctx, $args ) = @_;
    my $tag = lc $ctx->stash('tag');
    my $val = $ctx->slurp($args);
    $val =~ s/(^\s+|\s+$)//g;
    my @pairs = split /\r?\n/, $val;
    foreach my $line (@pairs) {
        next if $line =~ m/^\s*$/;
        my ( $var, $value ) = split /\s*=/, $line, 2;
        unless ( defined($var) && defined($value) ) {
            return $ctx->error("Invalid variable assignment: $line");
        }
        $var =~ s/^\s+//;
        $ctx->var( $var, $value );
    }
    return '';
}

###########################################################################

=head2 SetHashVar

A block tag that is used for creating a hash template variable. A hash
is a variable that stores many values. You can even nest L<SetHashVar>
tags so you can store hashes inside hashes for more complex structures.

B<Example:>

    <mt:SetHashVar name="my_hash">
        <$mt:Var name="foo" value="bar"$>
        <$mt:Var name="fizzle" value="fozzle"$>
    </mt:SetHashVar>

Then later:

    foo is assigned: <$mt:Var name="my_hash{foo}"$>

=for tags templating

=cut

sub _hdlr_set_hashvar {
    my ( $ctx, $args ) = @_;
    my $tag = lc $ctx->stash('tag');
    my $name = $args->{name} || $args->{var};
    if ( $name =~ m/^\$/ ) {
        $name = $ctx->var($name);
    }
    return $ctx->error(
        MT->translate(
            "You used a [_1] tag without a valid name attribute.", "<MT$tag>"
        )
    ) unless defined $name;

    my $hash = $ctx->var($name) || {};
    return $ctx->error( MT->translate( "[_1] is not a hash.", $name ) )
        unless 'HASH' eq ref($hash);

    {
        local $ctx->{__inside_set_hashvar} = $hash;
        $ctx->slurp($args);
    }
    if ( my $parent_hash = $ctx->{__inside_set_hashvar} ) {
        $parent_hash->{$name} = $hash;
    }
    else {
        $ctx->var( $name, $hash );
    }
    return q();
}

###########################################################################

=head2 SetVar

A function tag used to set the value of a template variable.

For simply setting variables you can use the L<Var> tag with a value attribute to assign template variables.

B<Attributes:>

=over 4

=item * var or name

Identifies the name of the template variable. See L<Var> for more
information on the format of this attribute.

=item * value

The value to assign to the variable.

=item * op (optional)

See the L<Var> tag for more information about this attribute.

=item * prepend (optional)

If specified, places the contents at the front of any existing value
for the template variable.

=item * append (optional)

If specified, places the contents at the end of any existing value
for the template variable.

=back

=for tags

=cut

sub _hdlr_set_var {
    my ( $ctx, $args ) = @_;
    my $tag = lc $ctx->stash('tag');
    my $name = $args->{name} || $args->{var};

    return $ctx->error(
        MT->translate(
            "You used a [_1] tag without a valid name attribute.", "<MT$tag>"
        )
    ) unless defined $name;

    my ( $func, $key, $index, $value );
    if ( $name =~ m/^(\w+)\((.+)\)$/ ) {
        $func = $1;
        $name = $2;
    }
    else {
        $func = $args->{function} if exists $args->{function};
    }

    # pick off any {...} or [...] from the name.
    if ( $name =~ m/^(.+)([\[\{])(.+)[\]\}]$/ ) {
        $name = $1;
        my $br  = $2;
        my $ref = $3;
        if ( $ref =~ m/^\$(.+)/ ) {
            $ref = $ctx->var($1);
            $ref = chr(0) unless defined $ref;
        }
        $br eq '[' ? $index = $ref : $key = $ref;
    }
    else {
        $index = $args->{index} if exists $args->{index};
        $key   = $args->{key}   if exists $args->{key};
    }

    if ( $name =~ m/^\$/ ) {
        $name = $ctx->var($name);
        return $ctx->error(
            MT->translate(
                "You used a [_1] tag without a valid name attribute.",
                "<MT$tag>"
            )
        ) unless defined $name;
    }

    my $val  = '';
    my $data = $ctx->var($name);
    if ( ( $tag eq 'setvar' ) || ( $tag eq 'var' ) ) {
        $val = defined $args->{value} ? $args->{value} : '';
    }
    elsif ( $tag eq 'setvarblock' ) {
        $val = $ctx->slurp($args);
        return unless defined($val);
    }
    elsif ( $tag eq 'setvartemplate' ) {
        $val = $ctx->stash('tokens');
        return unless defined($val);
        $val = bless $val, 'MT::Template::Tokens';
    }

    my $existing = $ctx->var($name);
    $existing = '' unless defined $existing;
    if ( 'HASH' eq ref($existing) ) {
        $existing = $existing->{$key};
    }
    elsif ( 'ARRAY' eq ref($existing) ) {
        $existing
            = ( defined $index && ( $index =~ /^-?\d+$/ ) )
            ? $existing->[$index]
            : undef;
    }
    $existing = '' unless defined $existing;

    if ( $args->{prepend} ) {
        $val = $val . $existing;
    }
    elsif ( $args->{append} ) {
        $val = $existing . $val;
    }
    elsif ( $existing ne '' && ( my $op = $args->{op} ) ) {
        $val = _math_operation( $ctx, $op, $existing, $val );
    }

    $val = deep_copy( $val, MT->config->DeepCopyRecursiveLimit );

    if ( defined $key ) {
        $data ||= {};
        return $ctx->error( MT->translate( "'[_1]' is not a hash.", $name ) )
            unless 'HASH' eq ref($data);

        if (   ( defined $func )
            && ( 'delete' eq lc($func) ) )
        {
            delete $data->{$key};
        }
        else {
            $data->{$key} = $val;
        }
    }
    elsif ( defined $index ) {
        $data ||= [];
        return $ctx->error(
            MT->translate( "'[_1]' is not an array.", $name ) )
            unless 'ARRAY' eq ref($data);
        return $ctx->error( MT->translate("Invalid index.") )
            unless $index =~ /^-?\d+$/;
        $data->[$index] = $val;
    }
    elsif ( defined $func ) {
        if ( 'undef' eq lc($func) ) {
            $data = undef;
        }
        else {
            $data ||= [];
            return $ctx->error(
                MT->translate( "'[_1]' is not an array.", $name ) )
                unless 'ARRAY' eq ref($data);
            if ( 'push' eq lc($func) ) {
                push @$data, $val;
            }
            elsif ( 'unshift' eq lc($func) ) {
                $data ||= [];
                unshift @$data, $val;
            }
            else {
                return $ctx->error(
                    MT->translate( "'[_1]' is not a valid function.", $func )
                );
            }
        }
    }
    else {
        $data = $val;
    }

    if ( my $hash = $ctx->{__inside_set_hashvar} ) {
        $hash->{$name} = $data;
    }
    else {
        $ctx->var( $name, $data );
    }
    return '';
}

###########################################################################

=head2 GetVar

An alias for the 'Var' tag, and considered deprecated in favor of 'Var'.

=for tags deprecated

=cut

###########################################################################

=head2 Var

A B<function tag> used to store and later output data in a template.

B<Attributes:>

=over 4

=item * name (or var)

Identifies the template variable. The 'name' attribute supports a variety
of expressions. In order to not conflict with variable interpolation,
the value of the name attribute should only contain uppercase letters,
lowercase letters, numbers and underscores. The typical case is a simple
variable name:

    <$mt:Var name="foo"$>

Template variables may be arrays, or hash variables, in which case you
may want to reference a specific element instead of the array or hash
itself.

This selects the second element from the 'foo' array template variable:

    <$mt:Var name="foo[1]"$>

This selects the 'bar' element from the 'foo' hash template variable:

    <$mt:Var name="foo{bar}"$>

Sometimes you want to obtain the value of a function that is applied
to a variable (see the 'function' attribute). This will obtain the
number of elements in the 'foo' array:

    <$mt:Var name="count(foo)"$>

Excluding the punctuation required in the examples above, the 'name'
attribute value should contain only alphanumeric characters and,
optionally, underscores.

=item * value

In the simplest case, this attribute triggers I<assignment> of the
specified value to the variable.

    <$mt:Var name="little_pig_count" value="3"$>          # Stores 3

However, if provided with the 'op' attribute (see below), the value becomes
the operand for the specified mathematical operation and no assignment takes
place.

The 'value' attribute can contain anything other than a double quote. If you
need to use a double quote or the value is very long, you may want to use
the L<SetVarBlock> tag or the L<setvar> global modifier instead.

=item * op

Used along with the 'value' attribute to perform a number of mathematical
operations on the value of the variable.  When used in this way, the stored
value of the variable doesn't change but instead gets transformed in the
process of being output.

    <$mt:Var name="little_pig_count">                     # Displays 3
    <$mt:Var name="little_pig_count" value="1" op="sub"$> # Displays 2
    <$mt:Var name="little_pig_count" value="2" op="sub"$> # Displays 1
    <$mt:Var name="little_pig_count" value="3" op="sub"$> # Displays 0

See the L<If> tag for the list of supported operators.

=item * prepend

When used in conjuction with the 'value' attribute to store a value, this
attribute acts as a flag (i.e. 'prepend="1"') to indicate that the new value
should be added to the front of any existing value instead of replacing it.

    <$mt:Var name="greeting" value="World"$>
    <$mt:Var name="greeting" value="Hello " prepend="1"$>
    <$mt:Var name="greeting"$>  # Displays: Hello World

=item * append

When used in conjuction with the 'value' attribute to store a value, this
attribute acts as a flag (i.e. 'append="1"') to indicate that the new value
should be added to the back of any existing value instead of replacing it.

    <$mt:Var name="greeting" value="Hello"$>
    <$mt:Var name="greeting" value=" World" append="1"$>
    <$mt:Var name="greeting"$>  # Displays: Hello World

=item * function

For array template variables, this attribute supports:

=over 4

=item * push

Adds the element to the end of the array (becomes the last element).

=item * pop

Removes an element from the end of the array (last element) and
outputs it.

=item * unshift

Adds the element to the front of the array (index 0).

=item * shift

Takes an element from the front of the array (index 0).

=item * count

Returns the number of elements in the array template variable.

=back

For hash template variables, this attribute supports:

=over 4

=item * delete

Only valid when used with the 'key' attribute, or if a key is present
in the variable name.

=item * count

Returns the number of keys present in the hash template variable.

=back

=item * index

Identifies an element of an array template variable.

=item * key

Identifies a value stored for the key of a hash template variable.

=item * default

If the variable is undefined or empty, this value will be output
instead. Use of the 'default' and 'setvar' attributes together make
for an excellent way to conditionally initialize variables. The
following sets the "max_pages" variable to 10 if and only if it does
not yet have a value.

    <mt:var name="max_pages" default="10" setvar="max_pages">

=item * to_json

Formats the variable in JSON notation.

=item * glue

For array template variables, this attribute is used in joining the
values of the array together.

=back

=for tags templating

=cut

sub _hdlr_get_var {
    my ( $ctx, $args, $cond ) = @_;
    if ( exists( $args->{value} )
        && !exists( $args->{op} ) )
    {
        return &_hdlr_set_var(@_);
    }
    my $name = $args->{name} || $args->{var};
    return $ctx->error(
        MT->translate(
            "You used a [_1] tag without a valid name attribute.",
            "<MT" . $ctx->stash('tag') . ">"
        )
    ) unless defined $name;

    my ( $func, $key, $index, $value );
    if ( $name =~ m/^(\w+)\((.+)\)$/ ) {
        $func = $1;
        $name = $2;
    }
    else {
        $func = $args->{function} if exists $args->{function};
    }

    # pick off any {...} or [...] from the name.
    if ( $name =~ m/^(.+)([\[\{])(.+)[\]\}]$/ ) {
        $name = $1;
        my $br  = $2;
        my $ref = $3;
        if ( $ref =~ m/^\$(.+)/ ) {
            $ref = $ctx->var($1);
            $ref = chr(0) unless defined $ref;
        }
        $br eq '[' ? $index = $ref : $key = $ref;
    }
    else {
        $index = $args->{index} if exists $args->{index};
        $key   = $args->{key}   if exists $args->{key};
    }

    if ( $name =~ m/^\$/ ) {
        $name = $ctx->var($name);
    }

    if ( defined $name ) {
        $value = $ctx->var($name);
        if ( ref($value) eq 'CODE' ) {    # handle coderefs
            $value = $value->(@_);
        }
        if ( ref($value) ) {
            if ( UNIVERSAL::isa( $value, 'MT::Template' ) ) {
                local $args->{name}     = undef;
                local $args->{var}      = undef;
                local $value->{context} = $ctx;
                $value = $value->output($args);
            }
            elsif ( UNIVERSAL::isa( $value, 'MT::Template::Tokens' ) ) {
                local $ctx->{__stash}{tokens} = $value;
                local $args->{name}           = undef;
                local $args->{var}            = undef;

                # Pass through SetVarTemplate arguments as variables
                # so that they do not affect the global stash
                my $vars = $ctx->{__stash}{vars} ||= {};
                my @names = keys %$args;
                my @var_names;
                push @var_names, lc $_ for @names;
                local @{$vars}{@var_names};
                $vars->{ lc($_) } = $args->{$_} for @names;
                $value = $ctx->slurp($args) or return;
            }
            elsif ( ref($value) eq 'ARRAY' ) {
                if ( defined $index ) {
                    if ( $index =~ /^-?\d+$/ ) {
                        $value = $value->[$index];
                    }
                    else {
                        $value = undef;    # fall through to any 'default'
                    }
                }
                elsif ( defined $func ) {
                    $func = lc $func;
                    if ( 'pop' eq $func ) {
                        $value = @$value ? pop @$value : undef;
                    }
                    elsif ( 'shift' eq $func ) {
                        $value = @$value ? shift @$value : undef;
                    }
                    elsif ( 'count' eq $func ) {
                        $value = scalar @$value;
                    }
                    else {
                        return $ctx->error(
                            MT->translate(
                                "'[_1]' is not a valid function for an array.",
                                $func
                            )
                        );
                    }
                }
                else {
                    unless ( $args->{to_json} ) {
                        my $glue = exists $args->{glue} ? $args->{glue} : "";
                        $value = join $glue, @$value;
                    }
                }
            }
            elsif ( ref($value) eq 'HASH' ) {
                if ( defined $key ) {
                    if ( defined $func ) {
                        if ( 'delete' eq lc($func) ) {
                            $value = delete $value->{$key};
                        }
                        else {
                            return $ctx->error(
                                MT->translate(
                                    "'[_1]' is not a valid function for a hash.",
                                    $func
                                )
                            );
                        }
                    }
                    else {
                        if ( $key ne chr(0) ) {
                            $value = $value->{$key};
                        }
                        else {
                            $value = undef;
                        }
                    }
                }
                elsif ( defined $func ) {
                    if ( 'count' eq lc($func) ) {
                        $value = scalar( keys %$value );
                    }
                    else {
                        return $ctx->error(
                            MT->translate(
                                "'[_1]' is not a valid function for a hash.",
                                $func
                            )
                        );
                    }
                }
            }
        }
        if ( my $op = $args->{op} ) {
            my $rvalue = $args->{'value'};
            if ( $op && ( defined $value ) && !ref($value) ) {
                $value = _math_operation( $ctx, $op, $value, $rvalue );
            }
        }
    }
    if ( ( !defined $value ) || ( $value eq '' ) ) {
        if ( exists $args->{default} ) {
            $value = $args->{default};
        }
    }

    if ( ref($value) && $args->{to_json} ) {
        return MT::Util::to_json($value);
    }
    return defined $value ? $value : "";
}

###########################################################################

=head2 Ignore

A block tag that always produces an empty string. This tag is useful
for wrapping template code you wish to disable, or perhaps annotating
sections of your template.

B<Example:>

    <mt:Ignore>
        The API key for the following tag is D3ADB33F.
    </mt:Ignore>

=for tags templating

=cut

###########################################################################

=head2 TemplateNote

A function tag that always returns an empty string. This tag is useful
for placing simple notes in your templates, since it produces nothing.

B<Example:>

    <$mt:TemplateNote note="Hi, mom!"$>

=for tags templating

=cut

package MT::Template::Tags::App;

use strict;

use MT;
use MT::Util qw( encode_html encode_url );

###########################################################################

=head2 App:Setting

An application template tag used to display an application form field.

B<Attributes:>

=over 4

=item * id (required)

Each application setting tag requires a unique 'id' attribute. This id
should not be re-used within the template.

=item * required (optional; default "0")

Controls whether the field is displayed with visual cues that the
field is a required field or not.

=item * label

Supplies the label phrase for the setting.

=item * show_label (optional; default "1")

Controls whether the label portion of the setting is shown or not.

=item * shown (optional; default "1")

Controls whether the setting is visible or not. If specified, adds
a "hidden" class to the outermost C<div> tag produced for the
setting.

=item * label_class (optional)

Allows an additional CSS class to be applied to the label of the
setting.

=item * content_class (optional)

Allows an addtional CSS class to be applied to the contents of the
setting.

=item * hint (optional)

Supplies a "hint" phrase that provides inline instruction to the user.
By default, this hint is hidden, unless the 'show_hint' attribute
forces it to display.

=item * show_hint (optional; default "0")

Controls whether the inline help 'hint' label is shown or not.

=item * warning

Supplies a warning message to the user regarding the use of this setting.

=item * show_warning

Controls whether the warning message is shown or not.

=item * help_page

Identifies a specific page of the MT help documentation for this setting.

=item * help_section

Identifies a section name of the MT help documentation for this setting.

=back

B<Example:>

    <mtapp:Setting
        id="name"
        required="1"
        label="Username"
        hint="The username used to login">
            <input type="text" name="name" id="name" value="<$mt:Var name="name" escape="html"$>" />
    </mtapp:setting>

The basic structural output of a setting tag looks like this:

    <div id="ID-field" class="field pkg">
        <div class="field-inner">
            <div class="field-header">
                <label id="ID-label" for="ID">LABEL</label>
            </div>
            <div class="field-content">
                (content of App:Setting tag)
            </div>
        </div>
    </div>

=for tags application

=cut

sub _hdlr_app_setting {
    my ( $ctx, $args, $cond ) = @_;
    my $id = $args->{id};
    return $ctx->error("'id' attribute missing") unless $id;

    my $label       = $args->{label};
    my $show_label  = exists $args->{show_label} ? $args->{show_label} : 1;
    my $shown       = exists $args->{shown} ? ( $args->{shown} ? 1 : 0 ) : 1;
    my $label_class = $args->{label_class} || "";
    my $content_class = $args->{content_class} || "";
    my $hint          = $args->{hint} || "";
    my $show_hint     = $args->{show_hint} || 0;
    my $warning       = $args->{warning} || "";
    my $show_warning  = $args->{show_warning} || 0;
    my $indent        = $args->{indent};
    my $help;

    # Formatting for help link, placed at the end of the hint.
    if ( $help = $args->{help_page} || "" ) {
        my $section = $args->{help_section} || '';
        $section = qq{, '$section'} if $section;
        $help
            = qq{ <a href="javascript:void(0)" onclick="return openManual('$help'$section)" class="help-link">?</a><br />};
    }
    my $label_help = "";
    if ( $label && $show_label ) {

        # do nothing;
    }
    else {
        $label = '';    # zero it out, because the user turned it off
    }
    if ( $hint && $show_hint ) {
        $hint = "\n<div class=\"hint\">$hint$help</div>";
    }
    else {
        $hint = ''
            ;  # hiding hint because it is either empty or should not be shown
    }
    if ( $warning && $show_warning ) {
        $warning
            = qq{\n<p><img src="<mt:var name="static_uri">images/status_icons/warning.gif" alt="<__trans phrase="Warning">" width="9" height="9" />
<span class="alert-warning-inline">$warning</span></p>\n};
    }
    else {
        $warning = ''
            ;  # hiding hint because it is either empty or should not be shown
    }
    unless ($label_class) {
        $label_class = 'field-left-label';
    }
    else {
        $label_class = 'field-' . $label_class;
    }
    my $indent_css = "";
    if ($indent) {
        $indent_css = " style=\"padding-left: " . $indent . "px;\"";
    }

    # 'Required' indicator plus CSS class
    my $req       = $args->{required} ? " *"        : "";
    my $req_class = $args->{required} ? " required" : "";

    my $insides = $ctx->slurp( $args, $cond );

    # $insides =~ s/^\s*(<textarea)\b/<div class="textarea-wrapper">$1/g;
    # $insides =~ s/(<\/textarea>)\s*$/$1<\/div>/g;

    my $class = $args->{class} || "";
    $class = ( $class eq '' ) ? 'hidden' : $class . ' hidden' unless $shown;

    return $ctx->build(<<"EOT");
<div id="$id-field" class="field$req_class $label_class $class"$indent_css>
    <div class="field-header">
      <label id="$id-label" for="$id">$label$req</label>
    </div>
    <div class="field-content $content_class">
      $insides$hint$warning
    </div>
</div>
EOT
}

###########################################################################

=head2 App:Widget

An application template tag that produces HTML for displaying a MT CMS
dashboard widget. Custom widget templates should utilize this tag to wrap
their widget content.

B<Attributes:>

=over 4

=item * id (optional)

If specified, will be used as the 'id' attribute for the outermost C<div>
tag for the widget. If unspecified, will use the 'widget_id' template
variable instead.

=item * label (required)

The label to display above the widget.

=item * label_link (optional)

If specified, this link will wrap the label for the widget.

=item * label_onclick

If specified, this JavaScript code will be assigned to the 'onclick'
attribute of a link tag wrapping the widget label.

=item * class (optional)

If unspecified, will use the id of the widget. This class is included in the
'class' attribute of the outermost C<div> tag for the widget.

=item * header_action

=item * can_close (optional; default "0")

Identifies whether widget may be closed or not.

=item * tabbed (optional; default "0")

If specified, the widget will be assigned an attribute that gives it
a tabbed interface.

=back

B<Example:>

    <mtapp:Widget class="widget my-widget"
        label="<__trans phrase="All About Me">" can_close="1">
        (contents of widget go here)
    </mtapp:Widget>

=for tags application

=cut

sub _hdlr_app_widget {
    my ( $ctx, $args, $cond ) = @_;
    my $hosted_widget = $ctx->var('widget_id') ? 1 : 0;
    my $id            = $args->{id} || $ctx->var('widget_id') || '';
    my $label         = $args->{label};
    my $class         = $args->{class} || $id;
    my $label_link    = $args->{label_link} || "";
    my $label_onclick = $args->{label_onclick} || "";
    my $header_action = $args->{header_action} || "";
    my $closable      = $args->{can_close} ? 1 : 0;
    if ($closable) {
        $header_action
            = qq{<a title="<__trans phrase="Remove this widget">" onclick="javascript:removeWidget('$id'); return false;" href="javascript:void(0);" class="widget-close-link"><span>close</span></a>};
    }
    my $widget_header = "";
    if ( $label_link && $label_onclick ) {
        $widget_header
            = "\n<h2><a href=\"$label_link\" onclick=\"$label_onclick\"><span>$label</span></a></h2>";
    }
    elsif ($label_link) {
        $widget_header
            = "\n<h2><a href=\"$label_link\"><span>$label</span></a></h2>";
    }
    else {
        $widget_header = "\n<h2><span>$label</span></h2>";
    }
    my $token    = $ctx->var('magic_token')     || '';
    my $scope    = $ctx->var('widget_scope')    || 'system';
    my $singular = $ctx->var('widget_singular') || '';

    # Make certain widget_id is set
    my $vars = $ctx->{__stash}{vars};
    local $vars->{widget_id}     = $id;
    local $vars->{widget_header} = '';
    local $vars->{widget_footer} = '';
    my $app = MT->instance;
    my $blog = $app->can('blog') ? $app->blog : $ctx->stash('blog');
    my $blog_field
        = $blog
        ? qq{<input type="hidden" name="blog_id" value="}
        . $blog->id . q{" />}
        : "";
    local $vars->{blog_id} = $blog->id if $blog;
    my $insides = $ctx->slurp( $args, $cond );
    my $widget_footer = ( $ctx->var('widget_footer') || '' );
    my $var_header    = ( $ctx->var('widget_header') || '' );

    if ( $var_header =~ m/<h2[ >]/i ) {
        $widget_header = $var_header;
    }
    else {
        $widget_header .= $var_header;
    }
    my $corners
        = $args->{corners}
        ? '<div class="corners"><b></b><u></u><s></s><i></i></div>'
        : "";
    my $tabbed       = $args->{tabbed} ? ' mt:delegate="tab-container"' : "";
    my $header_class = $tabbed         ? 'widget-header-tabs'           : '';
    my $return_args = $app->make_return_args;
    $return_args = encode_html($return_args);
    my $cgi = $app->uri;
    if ( $hosted_widget && ( !$insides !~ m/<form\s/i ) ) {
        $insides = <<"EOT";
        <form id="$id-form" method="post" action="$cgi" onsubmit="updateWidget('$id'); return false">
        <input type="hidden" name="__mode" value="update_widget_prefs" />
        <input type="hidden" name="widget_id" value="$id" />
        $blog_field
        <input type="hidden" name="widget_action" value="save" />
        <input type="hidden" name="widget_scope" value="$scope" />
        <input type="hidden" name="widget_singular" value="$singular" />
        <input type="hidden" name="magic_token" value="$token" />
        <input type="hidden" name="return_args" value="$return_args" />
$insides
        </form>
EOT
    }
    return <<"EOT";
<div id="$id" class="widget $class"$tabbed>
  <div class="widget-header $header_class">
    <div class="widget-action">$header_action</div>
    <div class="widget-label">$widget_header</div>
  </div>
  <div class="widget-content">
    $insides
  </div>
  <div class="widget-footer">$widget_footer</div>$corners
</div>
EOT
}

###########################################################################

=head2 App:StatusMsg

An application template tag that outputs a MT status message.

B<Attributes:>

=over 4

=item * id (optional)

=item * class (optional; default "info")

=item * rebuild (optional)

Accepted values: "all", "index".

=item * can_close (optional; default "1")

=back

=for tags application

=cut

sub _hdlr_app_statusmsg {
    my ( $ctx, $args, $cond ) = @_;
    my $app     = MT->instance;
    my $id      = $args->{id};
    my $class   = $args->{class} || 'info';
    my $msg     = $ctx->slurp;
    my $rebuild = $args->{rebuild} || '';
    my $blog_id = $ctx->var('blog_id');
    my $blog    = $ctx->stash('blog');
    if ( !$blog && $blog_id ) {
        $blog = MT->model('blog')->load($blog_id);
    }
    if ( $app->user and $app->user->can_do('rebuild') ) {
        $rebuild = '' if $blog && $blog->custom_dynamic_templates eq 'all';
        $rebuild
            = qq{<__trans phrase="[_1]Publish[_2] your site to see these changes take effect." params="<a href="<mt:var name="mt_url">?__mode=rebuild_confirm&blog_id=<mt:var name="blog_id">" class="mt-rebuild">%%</a>">}
            if $rebuild eq 'all';
        $rebuild
            = qq{<__trans phrase="[_1]Publish[_2] your site to see these changes take effect." params="<a href="<mt:var name="mt_url">?__mode=rebuild_confirm&blog_id=<mt:var name="blog_id">&prompt=index" class="mt-rebuild">%%</a>">}
            if $rebuild eq 'index';
    }
    else {
        $rebuild = '';
    }
    my $close = '';
    if ( $id && ( $args->{can_close} || ( !exists $args->{can_close} ) ) ) {
        $close
            = qq{<span class="mt-close-msg close-link clickable icon-remove icon16 action-icon"><__trans phrase="Close"></span>};
    }
    $id    = defined $id    ? qq{ id="$id"}      : "";
    $class = defined $class ? qq{msg msg-$class} : "msg";
    return $ctx->build(<<"EOT");
    <div$id class="$class"><p class="msg-text">$msg $rebuild</p>$close</div>
EOT
}

###########################################################################

=head2 App:Listing

This application tag is used in MT application templates to produce
a table listing. It expects an C<object_loop> variable to be available,
or you can use the C<loop> attribute to have it use a different source.

It will output it's contents once for each row of the input array. It
produces markup that is compatible with the MT application templates
and CSS structure, so it is not meant for general blog publishing use.

The C<return_args> variable is recognized and will populate a hidden
field in the produced C<form> tag if available.

The C<blog_id> variable is recognized and will populate a hidden
field in the produced C<form> tag if available.

The C<screen_class> variable is recognized and will force the
C<hide_pager> attribute to 1 if it is set to 'search-replace'.

The C<magic_token> variable is recognized and will populate a hidden
field in the produced C<form> tag if available (or will retrieve
a token from the current application if unset).

The C<view_expanded> variable is recognized and will affect the
class name applied to the table. If assigned, the table tag will
receive a 'expanded' class; otherwise, it is given a 'compact'
class.

The C<listing_header> variable is recognized and will be output
in a C<div> tag (classed with 'listing-header') that appears
at the top of the listing. This is only output when 'actions'
are shown (see 'show_actions' attribute).

The structure of the output from a typical use like this:

    <MTApp:Listing type="entry">
        (contents of one row for table)
    </MTApp:Listing>

produces something like this:

    <div id="entry-listing" class="listing">
        <div class="listing-header">
        </div>
        <form id="entry-listing-form" class="listing-form"
            action="..../mt.cgi" method="post"
            onsubmit="return this['__mode'] ? true : false">
            <input type="hidden" name="__mode" value="" />
            <input type="hidden" name="_type" value="entry" />
            <input type="hidden" name="action_name" value="" />
            <input type="hidden" name="itemset_action_input" value="" />
            <input type="hidden" name="return_args" value="..." />
            <input type="hidden" name="blog_id" value="1" />
            <input type="hidden" name="magic_token" value="abcd" />
            <$MTApp:ActionBar bar_position="top"
                form_id="entry-listing-form"$>
            <table id="entry-listing-table"
                class="entry-listing-table compact" cellspacing="0">

                (contents of tag are placed here)

            </table>
            <$MTApp:ActionBar bar_position="bottom"
                form_id="entry-listing-form"$>
        </form>
    </div>

B<Attributes:>

=over 4

=item * type (optional)

The C<MT::Object> object type the listing is processing. If unset,
will use the contents of the C<object_type> variable.

=item * loop (optional)

The source of data to process. This is an array of hashes, similar
to the kind used with the L<Loop> tag. If unset, the C<object_loop>
variable is used instead.

=item * empty_message (optional)

Used when there are no rows to output for the listing. If not set,
it will process any 'else' block that is available instead, or, failing
that, will output an L<App:StatusMsg> tag saying that no data could be
found.

=item * id (optional)

Used to construct the DOM id for the listing. The outer C<div> tag
will use this value. If unset, it will be assigned C<type-listing> (where
'type' is the object type determined for the listing; see 'type'
attribute).

=item * listing_class (optional)

Provides a custom class name that can be applied to the main
C<div> tag produced (this is in addition to the 'listing' class
that is always applied).

=item * action (optional; default 'script_url' variable)

Supplies the 'action' attribute of the C<form> tag produced.

=item * hide_pager (optional; default '0')

Controls whether the pagination controls are shown or not.
If unspecified, pagination is shown.

=item * show_actions (optional; default '1')

Controls whether the actions associated with the object type
processed are shown or not. If unspecified, actions are shown.

=back

=for tags application

=cut

sub _hdlr_app_listing {
    my ( $ctx, $args, $cond ) = @_;

    my $type = $args->{type} || $ctx->var('object_type');
    my $class = MT->model($type) if $type;
    my $loop = $args->{loop} || 'object_loop';
    my $loop_obj = $ctx->var($loop);

    unless ( ( ref($loop_obj) eq 'ARRAY' ) && (@$loop_obj) ) {
        my @else = @{ $ctx->stash('tokens_else') || [] };
        return MT::Template::Context::_hdlr_pass_tokens_else(@_) if @else;
        my $msg = $args->{empty_message} || MT->translate(
            "No [_1] could be found.",
            $class
            ? lc( $class->class_label_plural )
            : ( $type ? $type : MT->translate("records") )
        );
        return $ctx->build(
            qq{<mtapp:statusmsg
            id="zero-state"
            class="info zero-state"
            can_close="0">
            $msg
            </mtapp:statusmsg>}
        );
    }

    my $id = $args->{id} || ( $type ? $type . '-listing' : 'listing' );
    $id =~ s/:/\-/g;    # meta and revision uses colon as a separator
    my $listing_class = $args->{listing_class} || "";
    my $hide_pager    = $args->{hide_pager}    || 0;
    $hide_pager = 1
        if ( $ctx->var('screen_class') || '' ) eq 'search-replace';
    my $show_actions
        = exists $args->{show_actions} ? $args->{show_actions} : 1;
    my $return_args = $ctx->var('return_args') || '';
    my $search_options
        = MT->app->param('__mode') eq 'search_replace'
        ? ( $ctx->var('search_options') || '' )
        : '';
    $return_args = encode_html( $return_args . $search_options );
    $return_args
        = qq{\n        <input type="hidden" name="return_args" value="$return_args" />}
        if $return_args;
    my $blog_id = $ctx->var('blog_id') || '';
    $blog_id
        = qq{\n        <input type="hidden" name="blog_id" value="$blog_id" />}
        if $blog_id;
    my $token = $ctx->var('magic_token') || MT->app->current_magic || '';
    my $action = $args->{action} || '<mt:var name="script_url">' || '';
    my $target
        = defined $args->{target} ? ' target="' . $args->{target} . '"' : '';

    my $actions_top    = "";
    my $actions_bottom = "";
    my $form_id        = "$id-form";
    if ($show_actions) {
        $actions_top
            = qq{<\$MTApp:ActionBar bar_position="top" hide_pager="$hide_pager" form_id="$form_id"\$>};
        $actions_bottom
            = qq{<\$MTApp:ActionBar bar_position="bottom" hide_pager="$hide_pager" form_id="$form_id"\$>};
    }
    else {
        $listing_class .= " hide_actions";
    }

    my $insides;
    {
        local $args->{name} = $loop;
        defined( $insides = $ctx->invoke_handler( 'loop', $args, $cond ) )
            or return;
    }
    my $listing_header = $ctx->var('listing_header') || '';
    my $view = $ctx->var('view_expanded') ? ' expanded' : ' compact';

    my $table = <<TABLE;
        <table id="$id-table" class="legacy listing-table $listing_class $id-table$view">
$insides
        </table>
TABLE

    if ($show_actions) {
        local $ctx->{__stash}{vars}{__contents__} = $table;
        return $ctx->build(<<EOT);
<div id="$id" class="listing line $listing_class">
    <div class="listing-header">
        $listing_header
    </div>
    <form id="$form_id" class="listing-form"
        action="$action" method="post" $target
        onsubmit="return this['__mode'] ? true : false">
        <input type="hidden" name="__mode" value="" />
        <input type="hidden" name="_type" value="$type" />
        <input type="hidden" name="action_name" value="" />
        <input type="hidden" name="itemset_action_input" value="" />
$return_args
$blog_id
        <input type="hidden" name="magic_token" value="$token" />
        $actions_top
        <mt:var name="__contents__">
        $actions_bottom
    </form>
</div>
EOT
    }
    else {
        return <<EOT;
<div id="$id" class="listing $listing_class">
        $table
</div>
EOT
    }
}

###########################################################################

=head2 App:SettingGroup

An application template tag used to wrap a number of L<App:Setting> tags.

B<Attributes:>

=over 4

=item * id (required)

A unique identifier for this group of settings.

=item * class (optional)

If specified, applies this CSS class to the C<fieldset> tag produced.

=item * shown (optional; default "1")

Controls whether the C<fieldset> is initially shown or not. If hidden,
a CSS "hidden" class is applied to the C<fieldset> tag.

=back

B<Example:>

    <MTApp:SettingGroup id="foo">
        <MTApp:Setting ...>
        <MTApp:Setting ...>
        <MTApp:Setting ...>
    </MTApp:SettingGroup>

=for tags application

=cut

sub _hdlr_app_setting_group {
    my ( $ctx, $args, $cond ) = @_;
    my $id = $args->{id};
    return $ctx->error("'id' attribute missing") unless $id;

    my $class = $args->{class} || "";
    my $shown = exists $args->{shown} ? ( $args->{shown} ? 1 : 0 ) : 1;
    $class .= ( $class ne '' ? " " : "" ) . "hidden" unless $shown;
    $class = qq{ class="$class"} if $class ne '';

    my $insides = $ctx->slurp( $args, $cond );
    return <<"EOT";
<fieldset id="$id"$class>
    $insides
</fieldset>
EOT
}

###########################################################################

=head2 App:Form

Used for application templates that need to express a standard MT
application form. This produces certain hidden fields that are typically
required by MT application forms.

B<Attributes:>

=over 4

=item * action (optional)

Identifies the URL to submit the form to. If not given, will use
the current application URI.

=item * method (optional; default "POST")

Supplies the C<form> method. "GET" or "POST" are the typical values
for this, but will accept any HTTP-compatible method (ie: "PUT", "DELETE").

=item * object_id (optional)

Populates a hidden 'id' field in the form. If not given, will also use any
'id' template variable defined.

=item * blog_id (optional)

Populates a hidden 'blog_id' field in the form. If not given, will also use
any 'blog_id' template variable defined.

=item * object_type (optional)

Populates a hidden '_type' field in the form. If not given, will also use
any 'type' template variable defined.

=item * id (optional)

Used to form the 'id' element of the HTML C<form> tag. If not specified,
the C<form> tag 'id' element will be assigned TYPE-form, where TYPE is the
determined object_type.

=item * name (optional)

Supplies the C<form> name attribute. If unspecified, will use the C<id>
attribute, if available.

=item * enctype (optional)

If assigned, sets an 'enctype' attribute on the C<form> tag using the value
supplied. This is typically used to create a form that is capable of
uploading files.

=back

B<Example:>

    <mtapp:Form id="update" mode="update_blog_name">
        Blog Name: <input type="text" name="blog_name" />
        <input type="submit" />
    </mtapp:Form>

Producing:

    <form id="update" name="update" action="/cgi-bin/mt.cgi" method="POST">
    <input type="hidden" name="__mode" value="update_blog_name" />
        Blog Name: <input type="text" name="blog_name" />
        <input type="submit" />
    </form>

=for tags application

=cut

sub _hdlr_app_form {
    my ( $ctx, $args, $cond ) = @_;
    my $app    = MT->instance;
    my $action = $args->{action} || $app->uri;
    my $method = $args->{method} || 'POST';
    my @fields;
    my $token     = $ctx->var('magic_token');
    my $return    = $ctx->var('return_args');
    my $id        = $args->{object_id} || $ctx->var('id');
    my $blog_id   = $args->{blog_id} || $ctx->var('blog_id');
    my $type      = $args->{object_type} || $ctx->var('type');
    my $form_id   = $args->{id} || $type . '-form';
    my $form_name = $args->{name} || $args->{id};
    my $enctype
        = $args->{enctype} ? " enctype=\"" . $args->{enctype} . "\"" : "";
    my $mode = $args->{mode};
    push @fields, qq{<input type="hidden" name="__mode" value="$mode" />}
        if defined $mode;
    push @fields, qq{<input type="hidden" name="_type" value="$type" />}
        if defined $type;
    push @fields, qq{<input type="hidden" name="id" value="$id" />}
        if defined $id;
    push @fields, qq{<input type="hidden" name="blog_id" value="$blog_id" />}
        if defined $blog_id;
    push @fields,
        qq{<input type="hidden" name="magic_token" value="$token" />}
        if defined $token;
    $return = encode_html($return) if $return;
    push @fields,
        qq{<input type="hidden" name="return_args" value="$return" />}
        if defined $return;
    my $fields = '';
    $fields = join( "\n", @fields ) if @fields;
    my $insides = $ctx->slurp( $args, $cond );
    return <<"EOT";
<form id="$form_id" name="$form_name" action="$action" method="$method"$enctype>
$fields
    $insides
</form>
EOT
}

###########################################################################

=head2 App:PageActions

An application template tag used to produce an unordered list of actions
for a given listing screen. The actions are drawn from a C<page_actions>
template variable which is an array of hashes.

B<Example:>

    <$mtapp:PageActions$>

=for tags application

=cut

sub _hdlr_app_page_actions {
    my ( $ctx, $args, $cond ) = @_;
    my $app  = MT->instance;
    my $from = $args->{from} || $app->mode;
    my $loop = $ctx->var('page_actions');
    return '' if ( ref($loop) ne 'ARRAY' ) || ( !@$loop );
    my $mt = '&amp;magic_token=' . $app->current_magic;
    return $ctx->build( <<EOT, $cond );
    <mtapp:widget
        id="page_actions"
        label="<__trans phrase="Actions">">
                <ul>
        <mt:loop name="page_actions">
            <mt:if name="page">
                    <li class="icon-left-xwide icon<mt:unless name="core">-plugin</mt:unless>-action"><a href="<mt:var name="page" escape="html"><mt:if name="page_has_params">&amp;</mt:if>from=$from<mt:if name="id">&amp;id=<mt:var name="id"></mt:if><mt:if name="blog_id">&amp;blog_id=<mt:var name="blog_id"></mt:if>$mt&amp;return_args=<mt:var name="return_args" escape="url">"<mt:if name="continue_prompt"> onclick="return confirm('<mt:var name="continue_prompt" escape="js">');"</mt:if>><mt:var name="label"></a></li>
            <mt:else><mt:if name="link">
                    <li class="icon-left-xwide icon<mt:unless name="core">-plugin</mt:unless>-action"><a href="<mt:var name="link" escape="html">&amp;from=$from<mt:if name="id">&amp;id=<mt:var name="id"></mt:if><mt:if name="blog_id">&amp;blog_id=<mt:var name="blog_id"></mt:if>$mt&amp;return_args=<mt:var name="return_args" escape="url">"<mt:if name="continue_prompt"> onclick="return confirm('<mt:var name="continue_prompt" escape="js">');"</mt:if><mt:if name="dialog"> class="mt-open-dialog"</mt:if>><mt:var name="label"></a></li>
            </mt:if></mt:if>
        </mt:loop>
                </ul>
    </mtapp:widget>
EOT
}

###########################################################################

=head2 App:ListFilters

An application template tag used to produce an unordered list of quickfilters
for a given listing screen. The filters are drawn from a C<list_filters>
template variable which is an array of hashes.

B<Example:>

    <$mtapp:ListFilters$>

=cut

sub _hdlr_app_list_filters {
    my ( $ctx, $args, $cond ) = @_;
    my $app     = MT->app;
    my $filters = $ctx->var("list_filters");
    return '' if ( ref($filters) ne 'ARRAY' ) || ( !@$filters );
    my $mode       = $app->mode;
    my $type       = $app->param('_type');
    my $type_param = "";
    $type_param = "&amp;_type=" . encode_url($type) if defined $type;
    return $ctx->build( <<EOT, $cond );
    <mt:loop name="list_filters">
        <mt:if name="__first__">
    <ul>
        </mt:if>
        <mt:if name="key" eq="\$filter_key"><li class="current-filter"><em><mt:else><li></mt:if><a href="<mt:var name="script_url">?__mode=$mode$type_param<mt:if name="blog_id">&amp;blog_id=<mt:var name="blog_id"></mt:if>&amp;filter_key=<mt:var name="key" escape="url">"><mt:var name="label"></a><mt:if name="key" eq="\$filter_key"></em></mt:if></li>
    <mt:if name="__last__">
    </ul>
    </mt:if>
    </mt:loop>
EOT
}

###########################################################################

=head2 App:ActionBar

Produces markup for application templates for the strip of actions
for a application listing or edit screen.

B<Attributes:>

=over 4

=item * bar_position (optional; default "top")

Assigns a CSS class name indicating whether the control is above or
below the listing or edit form it is associated with.

=item * hide_pager

Assign either 1 or 0 to control whether the pagination controls are
displayed or not.

=item * form_id

Associates the pagition controls and item action widget with the
given form element.

=back

=for tags application

=cut

sub _hdlr_app_action_bar {
    my ( $ctx, $args, $cond ) = @_;
    my $pos = $args->{bar_position} || 'top';
    my $form_id
        = $args->{form_id}
        ? qq{<mt:setvar name="form_id" value="$args->{form_id}">}
        : "";
    my $pager
        = $args->{hide_pager}
        ? ''
        : qq{\n        <mt:include name="include/pagination.tmpl" bar_position="$pos">};
    my $buttons = $ctx->var('action_buttons') || '';
    my $buttons_html
        = $buttons =~ /\S/
        ? qq{<div class="button-actions actions">$buttons</div>}
        : '';

    return $ctx->build(<<EOT);
$form_id
<div id="actions-bar-$pos" class="actions-bar actions-bar-$pos">
    $pager
    $buttons_html
<mt:include name="include/itemset_action_widget.tmpl">
</div>
EOT
}

###########################################################################

=head2 App:Link

Produces a application link to the current script with the mode and
attributes specified.

B<Attributes:>

=over 4

=item * mode

Maps to a '__mode' argument.

=item * type

Maps to a '_type' argument.

=back

B<Example:>

    <$MTApp:Link mode="foo" type="entry" bar="1"$>

produces:

    /cgi-bin/mt/mt.cgi?__mode=foo&_type=entry&bar=1

This tag produces unescaped '&' characters. If you use this tag
in an HTML tag attribute, be sure to add a C<escape="html"> attribute
which will encode these to HTML entities.

=for tags application

=cut

sub _hdlr_app_link {
    my ( $ctx, $args, $cond ) = @_;
    my $app = MT->instance;

    my %args = %$args;

    # eliminate special '@' argument (and anything other refs that may exist)
    ref( $args{$_} ) && delete $args{$_} for keys %args;

    # strip off any arguments that are actually global filters
    my $filters = MT->registry( 'tags', 'modifier' );
    exists( $filters->{$_} ) && delete $args{$_} for keys %args;

    # remap 'type' attribute since we always express this as
    # a '_type' query parameter.
    my $mode = delete $args{mode}
        or return $ctx->error("mode attribute is required");
    $args{_type} = delete $args{type} if exists $args{type};
    if ( exists $args{blog_id} && !( $args{blog_id} ) ) {
        delete $args{blog_id};
    }
    else {
        if ( my $blog_id = $ctx->var('blog_id') ) {
            $args{blog_id} = $blog_id;
        }
    }
    return $app->uri( mode => $mode, args => \%args );
}

package MT::Template::Tags::System;

use strict;

use MT;
use MT::Util qw( offset_time_list );
use MT::Request;

{
    my %include_stack;
    my %restricted_include_filenames = (
        'mt-config.cgi' => 1,
        'passwd'        => 1
    );

###########################################################################

=head2 IncludeBlock

This tag provides MT with the ability to 'wrap' content with an included
module. This behaves much like the MTInclude tag, but it is a container tag.
The contents of the tag are taken and assigned to a variable (either one
explicitly named with a 'var' attribute, or will default to 'contents').
i.e.:

    <mt:IncludeBlock module="Some Module">
        (do something here)
    </mt:IncludeBlock>

In the "Some Module" template module, you would then have the following
template tag allowing you to reference the contents of the L<IncludeBlock>
tag used to include this "Some Module" template module, like so:

    (header stuff)
    <$mt:Var name="contents"$>
    (footer stuff)

B<Important:> Modules used as IncludeBlocks should never be processed as a Server Side Include or be cached.

+B<Attributes:>

=over 4

=item * var (optional)

Supplies a variable name to use for assigning the contents of the
L<IncludeBlock> tag. If unassigned, the "contents" variable is used.

=back

=for tags templating

=cut

    sub _hdlr_include_block {
        my ( $ctx, $args, $cond ) = @_;
        my $name = delete $args->{var} || 'contents';

        # defer the evaluation of the child tokens until used inside
        # the block (so any variables/context changes made in that template
        # affect the contained template code)
        my $tokens = $ctx->stash('tokens');
        local $ctx->{__stash}{vars}{$name} = sub {
            my $builder = $ctx->stash('builder');
            my $html = $builder->build( $ctx, $tokens, $cond );
            return $ctx->error( $builder->errstr ) unless defined $html;
            return $html;
        };
        return $ctx->tag( 'include', $args, $cond );
    }

###########################################################################

=head2 Include

Includes a template module or external file and outputs the result.

B<NOTE:> One and only one of the 'module', 'widget', 'file' and
'identifier' attributes can be specified.

B<Attributes:>

=over 4

=item * module

The name of a template module in the current blog.

=item * widget

The name of the widget in the current blog to include.

=item * file

The path to an external file on the system. The path can be absolute or
relative to the Local Site Path. This file is included at the time your
page is built. It should not be confused with dynamic server side
includes like that found in PHP.

=item * identifier

For selecting Index templates by their unique identifier.

=item * name

For application template use: identifies an application template by
filename to load.

=item * blog_id (optional)

Used to include a template from another blog in the system. Use in
conjunction with the module, widget or identifier attributes.

=item * local (optional)

Forces an Include of a template that exists in the blog that is being
published.

=item * global (optional; default "0")

Forces an Include of a globally defined template even if the
template is also available in the blog currently in context.
(For module, widget and identifier includes.)

=item * parent (optional; default "0")
Forces an include of a template from the parent website or
current website if current context is 'Website'.

=item * ssi (optional; default "0")

If specified, causes the include to be handled as a server-side
include. The value of the 'ssi' attribute determines the type of
include that is produced. Acceptable values are: C<php>, C<asp>,
C<jsp>, C<shtml>. This causes the contents of the include to be
processed and written to a file (stored to the blog's publishing
path, under the 'includes_c' subdirectory). The include tag itself
then returns the include directive appropriate to the 'ssi' type
specified. So, for example:

    <$mt:Include module="Tag Cloud" ssi="php"$>

This would generate the contents for the "Tag Cloud" template module
and write it to a "tag_cloud.php" file. The output of the include
tag would look like this:

    <?php include("/path/to/blog/includes_c/tag_cloud.php") ?>

Suitable for module, widget or identifier includes.

=item * cache (optional; default "0")

Enables caching of the contents of the include. Suitable for module,
widget or identifier includes.

=item * key or cache_key (optional)

Used to cache the template module. Used in conjunction with the 'cache'
attribute. Suitable for module, widget or identifier includes.

=item * ttl (optional)

Specifies the lifetime in seconds of a cached template module. Suitable
for module, widget or identifier includes.

=back

Also, other attributes given to this tag are locally assigned as
variables when invoking the include template.

The contents of the file or module are further evaluated for more Movable
Type template tags.

B<Example:> Including a Widget

    <$mt:Include widget="Search Box"$>

B<Example:> Including a File

    <$mt:Include file="/var/www/html/some-fragment.html"$>

B<Example:> Including a Template Module

    <$mt:Include module="Sidebar - Left Column"$>

B<Example:> Passing Parameters to a Template Module

    <$mt:Include module="Section Header" title="Elsewhere"$>

(from the "Section Header" template module)

    <h2><$mt:Var name="title"$></h2>

=for tags templating

=cut

    sub _hdlr_include {
        my ( $ctx, $arg, $cond ) = @_;

        # Pass through include arguments as variables to included template
        my $vars = $ctx->{__stash}{vars} ||= {};
        my @names = keys %$arg;
        my @var_names;
        push @var_names, lc $_ for @names;
        local @{$vars}{@var_names};
        $vars->{ lc($_) } = $arg->{$_} for @names;

        # Run include process
        my $out
            = $arg->{module}     ? _include_module(@_)
            : $arg->{widget}     ? _include_module(@_)
            : $arg->{identifier} ? _include_module(@_)
            : $arg->{file}       ? _include_file(@_)
            : $arg->{name}       ? _include_name(@_)
            : $ctx->error(
            MT->translate('No template to include was specified') );

        return $out;
    }

    sub _include_module {
        my ( $ctx, $arg, $cond ) = @_;
        my $tmpl_name = $arg->{module} || $arg->{widget} || $arg->{identifier}
            or return;
        my $name
            = $arg->{widget}     ? 'widget'
            : $arg->{identifier} ? 'identifier'
            :                      'module';
        my $type = $arg->{widget} ? 'widget' : 'custom';
        if ( ( $type eq 'custom' ) && ( $tmpl_name =~ m/^Widget:/ ) ) {

            # handle old-style widget include references
            $type = 'widget';
            $tmpl_name =~ s/^Widget: ?//;
        }

        my $_stash_blog = $ctx->stash('blog');
        my $blog_id
            = $arg->{global}             ? 0
            : defined( $arg->{blog_id} ) ? $arg->{blog_id}
            : $_stash_blog               ? $_stash_blog->id
            :                              0;
        $blog_id = $ctx->stash('local_blog_id') if $arg->{local};

        if ( $arg->{parent} ) {
            return $ctx->error(
                MT->translate(
                    "'parent' modifier cannot be used with '[_1]'", 'global'
                )
            ) if $arg->{global};
            return $ctx->error(
                MT->translate(
                    "'parent' modifier cannot be used with '[_1]'", 'local'
                )
            ) if $arg->{local};

            my $local_blog
                = MT->model('blog')->load( $ctx->stash('local_blog_id') );
            $blog_id = $local_blog->website->id;
        }

        ## Don't know why but hash key has to be encoded
        my $stash_id = Encode::encode_utf8(
            'template_' . $type . '::' . $blog_id . '::' . $tmpl_name );
        return $ctx->error(
            MT->translate(
                "Recursion attempt on [_1]: [_2]", MT->translate($name),
                $tmpl_name
            )
        ) if $include_stack{$stash_id};
        local $include_stack{$stash_id} = 1;

        my $req = MT::Request->instance;
        my ( $tmpl, $tokens );
        if ( my $tmpl_data = $req->stash($stash_id) ) {
            ( $tmpl, $tokens ) = @$tmpl_data;
        }
        else {
            my %terms
                = $arg->{identifier}
                ? ( identifier => $tmpl_name )
                : (
                name => $tmpl_name,
                type => $type
                );
            $terms{blog_id}
                = ( exists $arg->{global} && $arg->{global} ) ? 0
                : ( exists $arg->{parent} && $arg->{parent} ) ? $blog_id
                :   [ $blog_id, 0 ];

            ($tmpl) = MT->model('template')->load(
                \%terms,
                {   sort      => 'blog_id',
                    direction => 'descend',
                }
                )
                or return $ctx->error(
                MT->translate(
                    "Can't find included template [_1] '[_2]'",
                    MT->translate($name), $tmpl_name
                )
                );

            my $cur_tmpl = $ctx->stash('template');
            return $ctx->error(
                MT->translate(
                    "Recursion attempt on [_1]: [_2]", MT->translate($name),
                    $tmpl_name
                )
                )
                if $cur_tmpl
                    && $cur_tmpl->id
                    && ( $cur_tmpl->id == $tmpl->id );

            $req->stash( $stash_id, [ $tmpl, undef ] );
        }

        my $blog = $ctx->stash('blog') || MT->model('blog')->load($blog_id);

        my %include_recipe;
        my $use_ssi
            = $blog
            && $blog->include_system
            && ( $arg->{ssi} || $tmpl->include_with_ssi ) ? 1 : 0;
        if ($use_ssi) {

            # disable SSI for templates that are system templates;
            # easiest way to determine this is from the variable
            # space setting.
            if ( $ctx->var('system_template') ) {
                $use_ssi = 0;
            }
            else {
                my $extra_path
                    = ( $arg->{cache_key} || $arg->{key} ) ? $arg->{cache_key}
                    || $arg->{key}
                    : $tmpl->cache_path ? $tmpl->cache_path
                    :                     '';
                %include_recipe = (
                    name    => $tmpl_name,
                    id      => $tmpl->id,
                    path    => $extra_path,
                );
            }
        }

        # Try to read from cache
        my $enc               = MT->config->PublishCharset;
        my $cache_expire_type = 0;
        my $cache_enabled
            = $blog
            && $blog->include_cache
            && (
               ( $arg->{cache} && $arg->{cache} > 0 )
            || $arg->{cache_key}
            || $arg->{key}
            || ( exists $arg->{ttl} )
            || ( ( $cache_expire_type = ( $tmpl->cache_expire_type || 0 ) )
                != 0 )
            ) ? 1 : 0;
        my $cache_key = $arg->{cache_key} || $arg->{key};
        if ( !$cache_key ) {
            require Digest::MD5;
            $cache_key = Digest::MD5::md5_hex(
                Encode::encode_utf8(
                          'blog::'
                        . $blog_id
                        . '::template_'
                        . $type . '::'
                        . $tmpl_name
                )
            );
        }
        my $ttl
            = exists $arg->{ttl}          ? $arg->{ttl}
            : ( $cache_expire_type == 1 ) ? $tmpl->cache_expire_interval
            : ( $cache_expire_type == 2 ) ? 0
            :                               60 * 60;    # default 60 min.

        if ( $cache_expire_type == 2 ) {
            my @types = split /,/, ( $tmpl->cache_expire_event || '' );
            if (@types) {
                require MT::Touch;
                if ( my $latest
                    = MT::Touch->latest_touch( $blog_id, @types ) )
                {
                    if ($use_ssi) {

                        # base cache expiration on physical file timestamp
                        my $include_file
                            = $blog->include_path( \%include_recipe );
                        my $fmgr  = $blog->file_mgr;
                        my $mtime = $fmgr->file_mod_time($include_file);
                        if ( $mtime
                            && ( MT::Util::ts2epoch( undef, $latest )
                                > $mtime ) )
                        {
                            $ttl = 1;    # bound to force an update
                        }
                    }
                    else {
                        $ttl = time - MT::Util::ts2epoch( undef, $latest, 1 );
                        $ttl = 1 if $ttl == 0;    # edited just now.
                    }
                }
            }
        }

        my $cache_driver;
        if ($cache_enabled) {
            my $tmpl_mod = $tmpl->modified_on;
            my $tmpl_ts
                = MT::Util::ts2epoch( $tmpl->blog_id ? $tmpl->blog : undef,
                $tmpl_mod );
            if ( ( $ttl == 0 ) || ( time - $tmpl_ts < $ttl ) ) {
                $ttl = time - $tmpl_ts;
            }
            require MT::Cache::Negotiate;
            $cache_driver = MT::Cache::Negotiate->new( ttl => $ttl );
            my $cache_value = $cache_driver->get($cache_key);
            $cache_value = Encode::decode( $enc, $cache_value );
            if ($cache_value) {
                return $cache_value if !$use_ssi;

              # The template may still be cached from before we were using SSI
              # for this template, so check that it's also on disk.
                my $include_file = $blog->include_path( \%include_recipe );
                if ( $blog->file_mgr->exists($include_file) ) {
                    return $blog->include_statement( \%include_recipe );
                }
            }
        }

        my $builder = $ctx->{__stash}{builder};
        if ( !$tokens ) {

            # Compile the included template against the includ*ing* template's
            # context.
            $tokens = $builder->compile( $ctx, $tmpl->text );
            unless ( defined $tokens ) {
                $req->cache( 'build_template', $tmpl );
                return $ctx->error( $builder->errstr );
            }
            $tmpl->tokens($tokens);

            $req->stash( $stash_id, [ $tmpl, $tokens ] );
        }

     # Build the included template against the includ*ing* template's context.
        my $ret = $tmpl->build( $ctx, $cond );
        if ( !defined $ret ) {
            $req->cache( 'build_template', $tmpl ) if $tmpl;
            return $ctx->error(
                MT->translate(
                    "Error in [_1] [_2]: [_3]", MT->translate($name),
                    $tmpl_name,                 $tmpl->errstr
                )
            );
        }

        if ($cache_enabled) {
            $cache_driver->set( $cache_key, Encode::encode( $enc, $ret ),
                $ttl );
        }

        if ($use_ssi) {
            my ( $include_file, $path, $filename )
                = $blog->include_path( \%include_recipe );
            my $fmgr = $blog->file_mgr;
            if ( !$fmgr->exists($path) ) {
                if ( !$fmgr->mkpath($path) ) {
                    return $ctx->error(
                        MT->translate(
                            "Error making path '[_1]': [_2]", $path,
                            $fmgr->errstr
                        )
                    );
                }
            }
            defined( $fmgr->put_data( $ret, $include_file ) )
                or return $ctx->error(
                MT->translate(
                    "Writing to '[_1]' failed: [_2]", $include_file,
                    $fmgr->errstr
                )
                );

            MT->upload_file_to_sync(
                url  => $blog->include_url( \%include_recipe ),
                file => $include_file,
                blog => $blog,
            );

            my $stat = $blog->include_statement( \%include_recipe );
            return $stat;
        }

        return $ret;
    }

    sub _include_file {
        my ( $ctx, $arg, $cond ) = @_;
        if ( !MT->config->AllowFileInclude ) {
            return $ctx->error(
                'File include is disabled by "AllowFileInclude" config directive.'
            );
        }
        my $file = $arg->{file} or return;
        require File::Basename;
        my $base_filename = File::Basename::basename($file);
        if ( exists $restricted_include_filenames{ lc $base_filename } ) {
            return $ctx->error(
                "You cannot include a file with this name: $base_filename");
        }

        my $blog_id = $arg->{blog_id} || $ctx->{__stash}{blog_id} || 0;
        my $stash_id = 'template_file::' . $blog_id . '::' . $file;
        return $ctx->error( "Recursion attempt on file: [_1]", $file )
            if $include_stack{$stash_id};
        local $include_stack{$stash_id} = 1;
        my $req  = MT::Request->instance;
        my $cref = $req->stash($stash_id);
        my $tokens;
        my $builder = $ctx->{__stash}{builder};

        if ($cref) {
            $tokens = $cref;
        }
        else {
            my $blog = $ctx->stash('blog');
            if ( $blog && $blog->id != $blog_id ) {
                $blog = MT::Blog->load($blog_id)
                    or return $ctx->error(
                    MT->translate( "Can't find blog for id '[_1]", $blog_id )
                    );
            }
            my @paths = ($file);
            push @paths,
                map { File::Spec->catfile( $_, $file ) }
                ( $blog->site_path, $blog->archive_path )
                if $blog;
            my $path;
            for my $p (@paths) {
                $path = $p, last if -e $p && -r _;
            }
            return $ctx->error(
                MT->translate( "Can't find included file '[_1]'", $file ) )
                unless $path;
            local *FH;
            open FH, $path
                or return $ctx->error(
                MT->translate(
                    "Error opening included file '[_1]': [_2]",
                    $path, $!
                )
                );
            my $c;
            local $/;
            $c = <FH>;
            close FH;
            $tokens = $builder->compile( $ctx, $c );
            return $ctx->error( $builder->errstr ) unless defined $tokens;
            $req->stash( $stash_id, $tokens );
        }
        my $ret = $builder->build( $ctx, $tokens, $cond );
        return defined($ret)
            ? $ret
            : $ctx->error( "error in file $file: " . $builder->errstr );
    }

    sub _include_name {
        my ( $ctx, $arg, $cond ) = @_;
        my $app_file = $arg->{name};

        # app template include mode
        my $mt = MT->instance;
        local $mt->{component} = $arg->{component}
            if exists $arg->{component};
        my $stash_id = 'template_file::' . $app_file;
        return $ctx->error(
            MT->translate( "Recursion attempt on file: [_1]", $app_file ) )
            if $include_stack{$stash_id};
        local $include_stack{$stash_id} = 1;
        my $tmpl = $mt->load_tmpl($app_file);
        if ($tmpl) {
            $tmpl->name($app_file);

            my $tmpl_file = $app_file;
            if ($tmpl_file) {
                $tmpl_file = File::Basename::basename($tmpl_file);
                $tmpl_file =~ s/\.tmpl$//;
                $tmpl_file = '.' . $tmpl_file;
            }
            $mt->run_callbacks( 'template_param' . $tmpl_file,
                $mt, $tmpl->param, $tmpl );

            # propagate our context
            local $tmpl->{context} = $ctx;
            my $out = $tmpl->output();
            return $ctx->error( $tmpl->errstr ) unless defined $out;

            $mt->run_callbacks( 'template_output' . $tmpl_file,
                $mt, \$out, $tmpl->param, $tmpl );
            return $out;
        }
        else {
            return defined $arg->{default} ? $arg->{default} : '';
        }
    }
}

###########################################################################

=head2 IfStatic

Returns true if the current publishing context is static publishing,
and false otherwise.

=for tags templating, utility

=cut

###########################################################################

=head2 IfDynamic

Returns true if the current publishing context is dynamic publishing,
and false otherwise.

=for tags templating, utility

=cut

###########################################################################

=head2 Section

A utility block tag that is used to wrap content that can be cached,
or merely manipulated by any of Movable Type's tag modifiers.

B<Attributes:>

=over 4

=item * cache_prefix (optional)

When specified, causes the contents of the section tag to be cached
for some period of time. The 'period' attribute can specify the
cache duration (in seconds), or will use the C<DashboardCachePeriod>
configuration setting as a default (this feature was initially added
to support cacheable portions of the Movable Type Dashboard).

=item * period (optional)

A number in seconds defining the duration to cache the content produced
by the tag. Use in combination with the 'cache_prefix' attribute.

=item * by_blog (optional)

When using the 'cache_prefix' attribute, specifying '1' for this
attribute will cause the content to be cached on a per-blog basis
(otherwise, the default is system-wide).

=item * by_user (optional)

When using the 'cache_prefix' attribute, specifying '1' for this
attribute will cause the content to be cached on a per-user basis
(otherwise, the default is system-wide).

=item * html_tag (optional)

If specified, causes the content of the tag to be enclosed in a
the HTML tag identified. Example:

    <mt:Section html_tag="p">Lorem ipsum...</mt:Section>

Which would output:

    <p>Lorem ipsum...</p>

=item * id (optional)

If specified in combination with the 'html_tag' attribute, this 'id'
is added to the wrapping HTML tag.

=back

=for tags utility, templating

=cut

sub _hdlr_section {
    my ( $ctx, $args, $cond ) = @_;
    my $app = MT->instance;
    my $out;
    my $cache_require;
    my $enc = MT->config->PublishCharset || 'UTF-8';

    # make cache id
    my $cache_id = $args->{cache_prefix} || undef;

    my $tmpl = $ctx->{__stash}{template};
    $cache_id .= ':' . $tmpl->id if $tmpl && $tmpl->id;

    # read timeout. if timeout == 0 then, content is never cached.
    my $timeout = $args->{period};
    $timeout = $app->config('DashboardCachePeriod') if !defined $timeout;
    if ( defined $timeout && ( $timeout > 0 ) ) {
        if ( defined $cache_id ) {
            if ( $args->{by_blog} ) {
                my $blog = $app->blog;
                $cache_id .= ':blog_id=';
                $cache_id .= $blog ? $blog->id : '0';
            }
            if ( $args->{by_user} ) {
                my $author = $app->user
                    or
                    return $ctx->error( MT->translate("Can't load user.") );
                $cache_id .= ':user_id=' . $author->id;
            }

            # try to load from session
            require MT::Session;
            my $sess = MT::Session::get_unexpired_value( $timeout,
                { id => $cache_id, kind => 'CO' } );    # CO == Cache Object
            if ( defined $sess ) {
                ## need to decode by hand for blob typed column.
                my $data = $sess->data();
                $data = MT::I18N::utf8_off($data) if MT::I18N::is_utf8($data);
                my $out = Encode::decode( $enc, $data );
                if ($out) {
                    if ( my $wrap_tag = $args->{html_tag} ) {
                        my $id = $args->{id};
                        $id = " id=\"$id\"" if $id;
                        $id = '' unless defined $id;
                        $out = "<$wrap_tag$id>" . $out . "</$wrap_tag>";
                    }
                    return $out;
                }
            }
        }

        # load failed (timeout or record not found)
        $cache_require = 1;
    }

    # build content
    defined( $out
            = $ctx->stash('builder')
            ->build( $ctx, $ctx->stash('tokens'), $cond ) )
        or return $ctx->error( $ctx->stash('builder')->errstr );

    if ( $cache_require && ( defined $cache_id ) ) {
        my $sess = MT::Session->load( { id => $cache_id, kind => 'CO' } );
        if ($sess) {
            $sess->remove();
        }
        $sess = MT::Session->new;
        $sess->set_values(
            {   id    => $cache_id,
                kind  => 'CO',
                start => time,
                data  => Encode::encode( $enc, $out )
            }
        );
        $sess->save();
    }

    if ( my $wrap_tag = $args->{html_tag} ) {
        my $id = $args->{id};
        $id = " id=\"$id\"" if $id;
        $id = '' unless defined $id;
        $out = "<$wrap_tag$id>" . $out . "</$wrap_tag>";
    }
    return $out;
}

###########################################################################

=head2 Link

Generates the absolute URL to an index template or specific entry in the system.

B<NOTE:> Only one of the 'template' or 'entry_id' attributes can be specified
at a time.

B<Attributes:>

=over 4

=item * template

The index template to which to link. This attribute should be the template's
name, identifier, or outfile.

=item * entry_id

The numeric system ID of the entry. This attribute can not use with blog_id.

=item * blog_id

The numeric system ID of the blog/website. This attribute can not use with entry_id.

=item * with_index (optional; default "0")

If not set to 1, remove index filenames (by default, index.html)
from resulting links.

=back

B<Examples:>

    <a href="<mt:Link template="About Page">">My About Page</a>

    <a href="<mt:Link template="main_index">">Blog Home</a>

    <a href="<mt:Link entry_id="221">">the entry about my vacation</a>

=for tags archives
=cut

sub _hdlr_link {
    my ( $ctx, $arg, $cond ) = @_;
    my $curr_blog = $ctx->stash('blog');
    if ( my $tmpl_name = $arg->{template} ) {
        my $blog
            = $arg->{blog_id}
            ? MT->model('blog')->load( $arg->{blog_id} )
            : $curr_blog;
        my $blog_id = $blog->id;
        require MT::Template;
        my $tmpl = MT::Template->load(
            {   identifier => $tmpl_name,
                type       => 'index',
                blog_id    => $blog_id
            }
            )
            || MT::Template->load(
            {   name    => $tmpl_name,
                type    => 'index',
                blog_id => $blog_id
            }
            )
            || MT::Template->load(
            {   outfile => $tmpl_name,
                type    => 'index',
                blog_id => $blog_id
            }
            )
            or return $ctx->error(
            MT->translate( "Can't find template '[_1]'", $tmpl_name ) );
        my $site_url = $blog->site_url;
        $site_url .= '/' unless $site_url =~ m!/$!;
        my $link = $site_url . $tmpl->outfile;
        $link = MT::Util::strip_index( $link, $curr_blog )
            unless $arg->{with_index};
        $link;
    }
    elsif ( my $entry_id = $arg->{entry_id} ) {
        my $entry = MT::Entry->load($entry_id)
            or return $ctx->error(
            MT->translate( "Can't find entry '[_1]'", $entry_id ) );
        my $link = $entry->permalink;
        $link = MT::Util::strip_index( $link, $curr_blog )
            unless $arg->{with_index};
        $link;
    }
}

###########################################################################

=head2 Date

Outputs the current date.

B<Attributes:>

=over 4

=item * ts (optional)

If specified, will use the given date as the date to publish. Must be
in the format of "YYYYMMDDhhmmss".

=item * relative (optional)

If specified, will publish the date using a phrase, if the date is
less than a week from the current date. Accepted values are "1", "2", "3"
and "js". The options for "1", "2" and "3" affect the style of the phrase.

=over 4

=item * relative="1"

Supports display of one duration: moments ago; N minutes ago; N hours ago; N days ago. For older dates in the same year, the date is shown as the abbreviated month and day of the month ("Jan 3"). For older dates, the year is added to that ("Jan 3 2005").

=item * relative="2"

Supports display of two durations: less than 1 minute ago; N seconds, N minutes ago; N minutes ago; N hours, N minutes ago; N hours ago; N days, N hours ago; N days ago.

=item * relative="3"

Supports display of two durations: N seconds ago; N seconds, N minutes ago;
N minutes ago; N hours, N minutes ago; N hours ago; N days, N hours ago; N days ago.

=item * relative="js"

When specified, publishes the date using JavaScript, which relies on a
MT JavaScript function 'mtRelativeDate' to format the date.

=back

=item * format (optional)

A string that provides the format in which to publish the date. If
unspecified, the default that is appropriate for the language of the blog
is used (for English, this is "%B %e, %Y %l:%M %p"). The format specifiers
supported are:

=over 4

=item * %Y

The 4-digit year. Example: "1999".

=item * %m

The 2-digit month (zero-padded). Example: for a date in September, this would output "09".

=item * %d

The 2-digit day of the month (zero-padded). Example: "05".

=item * %H

The 2-digit hour of the day (24-hour clock, zero-padded). Example: "18".

=item * %M

The 2-digit minute of the hour (zero-padded). Example: "09".

=item * %S

The 2-digit second of the minute (zero-padded). Example: "04".

=item * %w

The numeric day of the week, in the range C<0>-C<6>, where C<0> is
C<Sunday>. Example: "3".

=item * %j

The numeric day of the year, in the range C<0>-C<365>. Zero-padded to
three digits. Example: "040".

=item * %y

The two-digit year, zero-padded. Example: %y for a date in 2008 would
output "08".

=item * %b

The abbreviated month name. Example: %b for a date in January would
output "Jan".

=item * %B

The full month name. Example: "January".

=item * %a

The abbreviated day of the week. Example: %a for a date on a Monday would
output "Mon".

=item * %A

The full day of the week. Example: "Friday".

=item * %e

The numeric day of the month (space-padded). Example: " 8".

=item * %I

The two-digit hour on a 12-hour clock padded with a zero if applicable.
Example: "04".

=item * %k

The two-digit military time hour padded with a space if applicable.
Example: " 9".

=item * %l

The hour on a 12-hour clock padded with a space if applicable.
Example: " 4".

=back

=item * format_name (optional)

Supports date formatting for particular standards.

=over 4

=item * rfc822

Outputs the date in the format: "%a, %d %b %Y %H:%M:%S Z".

=item * iso8601

Outputs the date in the format: "%Y-%m-%dT%H:%M:%SZ".

=back

=item * utc (optional)

Converts the date into UTC time.

=item * offset_blog_id (optional)

Identifies the ID of the blog to use for adjusting the time to
blog time. Will default to the current blog in context if unset.

=item * language (optional)

Used to force localization of the date to a specific language.
Accepted values: "cz" (Czechoslovakian), "dk" (Scandinavian),
"nl" (Dutch), "en" (English), "fr" (French), "de" (German),
"is" (Icelandic), "ja" (Japanese), "it" (Italian), "no" (Norwegian),
"pl" (Polish), "pt" (Portuguese), "si" (Slovenian), "es" (Spanish),
"fi" (Finnish), "se" (Swedish). Will use the blog's date language
setting as a default.

=back

=cut

sub _hdlr_sys_date {
    my ( $ctx, $args ) = @_;
    unless ( $args->{ts} ) {
        my $t = time;
        my @ts = offset_time_list( $t, $ctx->stash('blog_id') );
        $args->{ts} = sprintf "%04d%02d%02d%02d%02d%02d",
            $ts[5] + 1900, $ts[4] + 1, @ts[ 3, 2, 1, 0 ];
    }
    return $ctx->build_date($args);
}

###########################################################################

=head2 AdminScript

Returns the value of the C<AdminScript> configuration setting. The default
for this setting if unassigned is "mt.cgi".

=for tags configuration

=cut

sub _hdlr_admin_script {
    my ($ctx) = @_;
    return $ctx->{config}->AdminScript;
}

###########################################################################

=head2 CommentScript

Returns the value of the C<CommentScript> configuration setting. The
default for this setting if unassigned is "mt-comments.cgi".

=for tags configuration

=cut

sub _hdlr_comment_script {
    my ($ctx) = @_;
    return $ctx->{config}->CommentScript;
}

###########################################################################

=head2 TrackbackScript

Returns the value of the C<TrackbackScript> configuration setting. The
default for this setting if unassigned is "mt-tb.cgi".

=for tags configuration

=cut

sub _hdlr_trackback_script {
    my ($ctx) = @_;
    return $ctx->{config}->TrackbackScript;
}

###########################################################################

=head2 SearchScript

Returns the value of the C<SearchScript> configuration setting. The
default for this setting if unassigned is "mt-search.cgi".

=for tags configuration

=cut

sub _hdlr_search_script {
    my ($ctx) = @_;
    return $ctx->{config}->SearchScript;
}

###########################################################################

=head2 XMLRPCScript

Returns the value of the C<XMLRPCScript> configuration setting. The
default for this setting if unassigned is "mt-xmlrpc.cgi".

=for tags configuration

=cut

sub _hdlr_xmlrpc_script {
    my ($ctx) = @_;
    return $ctx->{config}->XMLRPCScript;
}

###########################################################################

=head2 AtomScript

Returns the value of the C<AtomScript> configuration setting. The
default for this setting if unassigned is "mt-atom.cgi".

=for tags configuration

=cut

sub _hdlr_atom_script {
    my ($ctx) = @_;
    return $ctx->{config}->AtomScript;
}

###########################################################################

=head2 NotifyScript

Returns the value of the C<NotifyScript> configuration setting. The
default for this setting if unassigned is "mt-add-notify.cgi".

=for tags configuration

=cut

sub _hdlr_notify_script {
    my ($ctx) = @_;
    return $ctx->{config}->NotifyScript;
}

###########################################################################

=head2 CGIHost

Returns the domain host from the configuration directive CGIPath. If CGIPath
is defined as a relative path, then the domain is derived from the Site URL
in the blog's "Publishing Settings".

B<Attributes:>

=over 4

=item * exclude_port (optional; default "0")

If set, exclude the port number from the CGIHost.

=back

=for tags configuration

=cut

sub _hdlr_cgi_host {
    my ( $ctx, $args, $cond ) = @_;
    my $path = $ctx->cgi_path;
    if ( $path =~ m!^https?://([^/:]+)(:\d+)?/! ) {
        return $args->{exclude_port} ? $1 : $1 . ( $2 || '' );
    }
    else {
        return '';
    }
}

###########################################################################

=head2 CGIPath

The value of the C<CGIPath> configuration setting. Example (the output
is guaranteed to end with "/", so appending one prior to a script
name is unnecessary):

    <a href="<$mt:CGIPath$>some-cgi-script.cgi">

=for tags configuration

=cut

sub _hdlr_cgi_path { shift->cgi_path }

###########################################################################

=head2 AdminCGIPath

Returns the value of the C<AdminCGIPath> configuration setting if set. Otherwise, the value of the C<CGIPath> setting is returned.

In the event that the configured path has no domain (ie, "/cgi-bin/"), the active blog's domain will be used.

The path produced by this tag will always have an ending '/', even if one does not exist as configured.

B<Example:>

    <$mt:AdminCGIPath$>

=for tags path, configuration

=cut

sub _hdlr_admin_cgi_path {
    my ($ctx) = @_;
    my $cfg = $ctx->{config};
    my $path = $cfg->AdminCGIPath || $cfg->CGIPath;
    if ( $path =~ m!^/! ) {

        # relative path, prepend blog domain
        my $blog = $ctx->stash('blog');
        my ($blog_domain) = $blog->archive_url =~ m|(.+://[^/]+)|;
        $path = $blog_domain . $path;
    }
    $path .= '/' unless $path =~ m!/$!;
    return $path;
}

###########################################################################

=head2 CGIRelativeURL

The relative URL (path) extracted from the CGIPath setting in
mt-config.cgi. This is the same as L<CGIPath>, but without any
domain name. This value is guaranteed to end with a "/" character.

=for tags configuration

=cut

sub _hdlr_cgi_relative_url {
    my ($ctx) = @_;
    my $url = $ctx->{config}->CGIPath;
    $url .= '/' unless $url =~ m!/$!;
    if ( $url =~ m!^https?://[^/]+(/.*)$! ) {
        return $1;
    }
    return $url;
}

###########################################################################

=head2 CGIServerPath

Returns the file path to the directory where Movable Type has been
installed. Any trailing "/" character is removed.

=for tags configuration

=cut

sub _hdlr_cgi_server_path {
    my $path = MT->instance->server_path() || "";
    $path =~ s!/*$!!;
    return $path;
}

###########################################################################

=head2 StaticFilePath

The file path to the directory where Movable Type's static files are
stored (as configured by the C<StaticFilePath> setting, or based on
the location of the MT application files alone). This value is
guaranteed to end with a "/" character.

=for tags configuration

=cut

sub _hdlr_static_file_path {
    my ($ctx) = @_;
    my $cfg   = $ctx->{config};
    my $path  = $cfg->StaticFilePath;
    if ( !$path ) {
        $path = MT->instance->{mt_dir};
        $path .= '/' unless $path =~ m!/$!;
        $path .= 'mt-static/';
    }
    $path .= '/' unless $path =~ m!/$!;
    return $path;
}

###########################################################################

=head2 StaticWebPath

The value of the C<StaticWebPath> configuration setting. If this setting
has no domain, the blog domain is added to it. This value is
guaranteed to end with a "/" character.

B<Example:>

    <img src="<$mt:StaticWebPath$>images/powered.gif"
        alt="Powered by MT" />

=for tags configuration

=cut

sub _hdlr_static_path {
    my ($ctx) = @_;
    my $cfg   = $ctx->{config};
    my $path  = $cfg->StaticWebPath;
    if ( !$path ) {
        $path = $cfg->CGIPath;
        $path .= '/' unless $path =~ m!/$!;
        $path .= 'mt-static/';
    }
    if ( $path =~ m!^/! ) {

        # relative path, prepend blog domain
        my $blog = $ctx->stash('blog');
        if ($blog) {
            my ($blog_domain) = $blog->archive_url =~ m|(.+://[^/]+)|;
            $path = $blog_domain . $path;
        }
    }
    $path .= '/' unless $path =~ m!/$!;
    return $path;
}

###########################################################################

=head2 SupportDirectoryURL

The value of the C<SupportDirectoryURL> configuration setting. This value is
guaranteed to end with a "/" character.

=for tags configuration

=cut

sub _hdlr_support_directory_url {
    my ($ctx) = @_;
    return MT->support_directory_url;
}

###########################################################################

=head2 Version

The version number of the Movable Type system.

B<Example:>

    <mt:Version />

=for tags configuration

=cut

sub _hdlr_mt_version {
    require MT;
    MT->version_id;
}

###########################################################################

=head2 ProductName

The Movable Type edition in use.

B<Attributes:>

=over 4

=item * version (optional; default "0")

If specified, also outputs the version (same as L<Version>).

=back

B<Example:>

    <$mt:ProductName$>

for the MTOS edition, this would output:

    Movable Type Open Source

=for tags configuration

=cut

sub _hdlr_product_name {
    my ( $ctx, $args, $cond ) = @_;
    require MT;
    my $short_name = MT->translate( MT->product_name );
    if ( $args->{version} ) {
        return MT->translate( "[_1] [_2]", $short_name, MT->version_id );
    }
    else {
        return $short_name;
    }
}

###########################################################################

=head2 PublishCharset

The value of the C<PublishCharset> directive in the system configuration.

B<Example:>

    <$mt:PublishCharset$>

=for tags configuration

=cut

sub _hdlr_publish_charset {
    my ($ctx) = @_;
    return $ctx->{config}->PublishCharset || 'utf-8';
}

###########################################################################

=head2 DefaultLanguage

The value of the C<DefaultLanguage> configuration setting.

B<Example:>

    <$mt:DefaultLanguage$>

This outputs a language code, ie: "en_US", "ja", "de", "es", "fr", "nl" or
other installed language.

=for tags configuration

=cut

sub _hdlr_default_language {
    my ($ctx) = @_;
    return $ctx->{config}->DefaultLanguage || 'en_US';
}

###########################################################################

=head2 ConfigFile

Returns the full file path for the Movable Type configuration file
(mt-config.cgi).

=for tags configuration

=cut

sub _hdlr_config_file {
    return MT->instance->{cfg_file};
}

###########################################################################

=head2 IndexBasename

Outputs the C<IndexBasename> MT configuration setting.

B<Attributes:>

=over 4

=item * extension (optional; default "0")

If specified, will append the blog's configured file extension.

=back

=cut

sub _hdlr_index_basename {
    my ( $ctx, $args, $cond ) = @_;
    my $name = $ctx->{config}->IndexBasename;
    if ( !$args->{extension} ) {
        return $name;
    }
    my $blog = $ctx->stash('blog');
    my $ext  = $blog->file_extension;
    $ext = '.' . $ext if $ext;
    $name . $ext;
}

###########################################################################

=head2 HTTPContentType

When this tag is used in a dynamically published index template, the value
specified to the type attribute will be returned in the Content-Type HTTP
header sent to web browser. This content is never displayed directly to the
user but is instead used to signal to the browser the data type of the
response.

When this tag is used in a system template, such as the search results
template, mt-search.cgi will use the value specified to "type" attribute and
returns it in Content-Type HTTP header to web browser.

When this tag is used in statically published template, this template tag
outputs nothing.

B<Attributes:>

=over 4

=item * type

A valid HTTP Content-Type value, for example 'application/xml'. Note that you
must not specify charset portion of Content-Type header value in this
attribute. MT will set the portion automatically by using PublishCharset
configuration directive.

=back

B<Example:>

    <$mt:HTTPContentType type="application/xml"$>

=cut

sub _hdlr_http_content_type {
    my ( $ctx, $args ) = @_;
    my $type = $args->{type};
    $ctx->stash( 'content_type', $type );
    return qq{};
}

###########################################################################

=head2 FileTemplate

Produces a file name and path using the archive file naming specifiers.

B<Attributes:>

=over 4

=item * format

A required attribute that defines the template with a string of specifiers.
The supported specifiers are (B<NOTE:> do not confuse the following
table with the specifiers used for MT date tags. There is no relationship
between these -- any similarities are coincidental. These specifiers are
tuned for publishing filenames and paths for various contexts.)

=over 4

=item * %a

The entry's author's display name passed through the dirify global filter. Example: melody_nelson

=item * %-a

The same as above except using dashes. Example: melody-nelson

=item * %b

For individual archive mappings, this returns the basename of the entry. By
default, this is the first thirty characters of an entry dirified with
underscores. It can be specified by using the basename field on the edit
entry screen. Example: my_summer_vacation

=item * %-b

Same as above but using dashes. Example: my-summer-vacation

=item * %c

The entry's primary category/subcategory path, built using the category
basename field. Example: arts_and_entertainment/tv_and_movies

=item * %-c

Same as above but using dashes. Example: arts-and-entertainment/tv-and-movies

=item * %C

The entry's primary category label passed through the dirify global filter. Example: arts_and_entertainment

=item * %-C

Same as above but using dashes. Example: arts-and-entertainment

=item * %d

2-digit day of the month. Example: 09

=item * %D

3-letter language-dependent abbreviation of the week day. Example: Tue

=item * %e

A numeric entry ID padded with leading zeroes to six digits. Example: 000040

=item * %E

The entry's numeric ID. Example: 40

=item * %f

Archive filename with the specified extension. This can be used instead of
%b or %i and will do the right thing based on the context.
Example: entry_basename.html or index.html

=item * %F

Same as above but without the file extension. Example: filename

=item * %h

2-digit hour on a 24-hour clock with a leading zero if applicable.
Example: 09 for 9am, 16 for 4pm

=item * %H

2-digit hour on a 24-hour clock without a leading zero if applicable.
Example: 9 for 9am, 16 for 4pm

=item * %i

The setting of the IndexBasename configuration directive with the default
file extension appended. Example: index.html

=item * %I

Same as above but without the file extension. Example: index

=item * %j

3-digit day of year, zero-padded. Example: 040

=item * %m

2-digit month, zero-padded. Example: 07

=item * %M

3-letter language-dependent abbreviation of the month. Example: Sep

=item * %n

2-digit minute, zero-padded. Example: 04

=item * %s

2-digit second, zero-padded. Example: 01

=item * %x

File extension with a leading dot (.). If a file extension has not
been specified a blank string is returned. Example: .html

=item * %y

4-digit year. Example: 2005

=item * %Y

2-digit year with zero-padding. Example: 05

=back

=back

B<Example:>

    <$mt:FileTemplate format="%y/%m/%f"$>

=for tags archives

=cut

{
    my %tokens_cache;

    sub _hdlr_file_template {
        my ( $ctx, $args, $cond ) = @_;

        my $at = $ctx->{current_archive_type} || $ctx->{archive_type};
        $at = 'Category' if $ctx->{inside_mt_categories};
        my $format = $args->{format};
        unless ($format) {
            my $archiver = MT->publisher->archiver($at);
            $format = $archiver->default_archive_templates if $archiver;
        }
        return $ctx->error( MT->translate("Unspecified archive template") )
            unless $format;

        my ( $dir, $sep );
        if ( $args->{separator} ) {
            $dir = "dirify='$args->{separator}'";
            $sep = "separator='$args->{separator}'";
        }
        else {
            $dir = "dirify='1'";
            $sep = "";
        }
        my %f = (
            'a'  => "<MTAuthorBasename $dir>",
            '-a' => "<MTAuthorBasename separator='-'>",
            '_a' => "<MTAuthorBasename separator='_'>",
            'b'  => "<MTEntryBasename $sep>",
            '-b' => "<MTEntryBasename separator='-'>",
            '_b' => "<MTEntryBasename separator='_'>",
            'c'  => "<MTSubCategoryPath $sep>",
            '-c' => "<MTSubCategoryPath separator='-'>",
            '_c' => "<MTSubCategoryPath separator='_'>",
            'C'  => "<MTCategoryBasename $sep>",
            '-C' => "<MTCategoryBasename separator='-'>",
            'd'  => "<MTArchiveDate format='%d'>",
            'D'  => "<MTArchiveDate format='%e' trim='1'>",
            'e'  => "<MTEntryID pad='1'>",
            'E'  => "<MTEntryID pad='0'>",
            'f'  => "<MTArchiveFile $sep>",
            '-f' => "<MTArchiveFile separator='-'>",
            'F'  => "<MTArchiveFile extension='0' $sep>",
            '-F' => "<MTArchiveFile extension='0' separator='-'>",
            'h'  => "<MTArchiveDate format='%H'>",
            'H'  => "<MTArchiveDate format='%k' trim='1'>",
            'i'  => '<MTIndexBasename extension="1">',
            'I'  => "<MTIndexBasename>",
            'j' => "<MTArchiveDate format='%j'>",    # 3-digit day of year
            'm' => "<MTArchiveDate format='%m'>",    # 2-digit month
            'M' => "<MTArchiveDate format='%b'>",    # 3-letter month
            'n' => "<MTArchiveDate format='%M'>",    # 2-digit minute
            's' => "<MTArchiveDate format='%S'>",    # 2-digit second
            'x' => "<MTBlogFileExtension>",
            'y' => "<MTArchiveDate format='%Y'>",    # year
            'Y' => "<MTArchiveDate format='%y'>",    # 2-digit year
            'p' =>
                "<mt:PagerBlock><mt:IfCurrentPage><mt:Var name='__value__'></mt:IfCurrentPage></mt:PagerBlock>"
            ,                                        # current page number
        );
        $format =~ s!%([_-]?[A-Za-z])!$f{$1}!g if defined $format;

        # now build this template and return result
        my $builder = $ctx->stash('builder');
        my $tok     = $tokens_cache{$format}
            ||= $builder->compile( $ctx, $format );
        return $ctx->error(
            MT->translate( "Error in file template: [_1]", $args->{format} ) )
            unless defined $tok;
        defined( my $file = $builder->build( $ctx, $tok, $cond ) )
            or return $ctx->error( $builder->errstr );
        $file =~ s!/{2,}!/!g;
        $file =~ s!(^/|/$)!!g;
        $file;
    }
}
###########################################################################

=head2 TemplateCreatedOn

Returns the creation date for the template publishing the current file.

B<Example:>

    <$mt:TemplateCreatedOn$>

=for tags date

=for tags templates

=cut

sub _hdlr_template_created_on {
    my ( $ctx, $args, $cond ) = @_;
    my $template = $ctx->stash('template')
        or return $ctx->error( MT->translate("Can't load template") );
    $args->{ts} = $template->created_on;
    $ctx->build_date($args);
}

###########################################################################

=head2 BuildTemplateID

Returns the ID of the template (index, archive or system template) currently
being built.

=cut

sub _hdlr_build_template_id {
    my ( $ctx, $args, $cond ) = @_;
    my $tmpl = $ctx->stash('template');
    if ( $tmpl && $tmpl->id ) {
        return $tmpl->id;
    }
    return 0;
}

###########################################################################

=head2 ErrorMessage

This tag is used by the system to display the text of any user error
message. Used in system templates, such as the 'Comment Response' template.

=for tags templating

=cut

sub _hdlr_error_message {
    my ($ctx) = @_;
    my $err = $ctx->stash('error_message');
    defined $err ? $err : '';
}

###########################################################################

=head2 PasswordValidation

This tag add a password validation JavaScript to a form (user profile,
new installation) where ever a user need to insert a new password

As one of the rules are that the password should not include the user name,
The script will try to fish inside the form for the username, (checking
name, admin_name) and if not exists will use the logined user name

B<Attributes:>

=over 4

=item * form

The name of the form this tag will letch on

=item * password

The name of the password field in the form this tag will check

=item * username

The name of the usrname field in the form to be checked against the password
If this name is empty string, the username will not be checked.

=back

B<Example:>

    <$mt:PasswordValidation form="profile" password="pass" username="name"$>

=cut

sub _hdlr_password_validation_script {
    my ( $ctx, $args ) = @_;
    my $form_id    = $args->{form};
    my $pass_field = $args->{password};
    my $user_field = $args->{username};
    my $app        = MT->instance;

    return $ctx->error(
        MT->translate(
            "You used an [_1] tag without a valid [_2] attribute.",
            "<MTPasswordValidation>", "form"
        )
    ) unless defined $form_id;

    return $ctx->error(
        MT->translate(
            "You used an [_1] tag without a valid [_2] attribute.",
            "<MTPasswordValidation>", "password"
        )
    ) unless defined $pass_field;

    $user_field ||= '';
    my @constrains = $app->config('UserPasswordValidation');
    my $min_length = $app->config('UserPasswordMinLength');
    if ( ( $min_length =~ m/\D/ ) or ( $min_length < 1 ) ) {
        $min_length = $app->config->default('UserPasswordMinLength');
    }

    my $vs = "\n";
    $vs .= << "JSCRIPT";
        function verify_password(username, passwd) {
          if (passwd.length < $min_length) {
            return "<__trans phrase="Password should be longer than [_1] characters" params="$min_length">";
          }
          if (username && (passwd.toLowerCase().indexOf(username.toLowerCase()) > -1)) {
            return "<__trans phrase="Password should not include your Username">";
          }
JSCRIPT

    if ( grep { $_ eq 'letternumber' } @constrains ) {
        $vs .= << 'JSCRIPT';
            if ((passwd.search(/[a-zA-Z]/) == -1) || (passwd.search(/\d/) == -1)) {
              return "<__trans phrase="Password should include letters and numbers">";
            }
JSCRIPT

    }
    if ( grep { $_ eq 'upperlower' } @constrains ) {
        $vs .= << 'JSCRIPT';
            if (( passwd.search(/[a-z]/) == -1) || (passwd.search(/[A-Z]/) == -1)) {
              return "<__trans phrase="Password should include lowercase and uppercase letters">";
            }
JSCRIPT

    }
    if ( grep { $_ eq 'symbol' } @constrains ) {
        $vs .= << 'JSCRIPT';
            if ( passwd.search(/[!"#$%&'\(\|\)\*\+,-\.\/\\:;<=>\?@\[\]^_`{}~]/) == -1 ) {
              return "<__trans phrase="Password should contain symbols such as #!$%">";
            }
JSCRIPT

    }
    $vs .= << 'JSCRIPT';
          return "";
        }
JSCRIPT

    $vs .= << "JSCRIPT";
        jQuery(document).ready(function() {
            jQuery("form#$form_id").submit(function(e){
                var form = jQuery(this);
                var passwd_input = form.find("input[name=$pass_field]");
                if ( !passwd_input.is(":visible") ) {
                    return true;
                }
                var passwd = passwd_input.val();
                if (passwd == null || passwd == "") {
                    return true;
                }
                var username = "$user_field" ? form.find("input[name=$user_field]").val() : "";
                var error = verify_password(username, passwd);
                if (error == "") {
                    return true;
                }
                alert(error);
                e.preventDefault();
                return false;
            });
        });
JSCRIPT

    return $vs;
}

###########################################################################

=head2 PasswordValidationRule

A string explaining the effective password policy

=cut

sub _hdlr_password_validation_rules {
    my ($ctx) = @_;

    my $app = MT->instance;

    my @constrains = $app->config('UserPasswordValidation');
    my $min_length = $app->config('UserPasswordMinLength');
    if ( ( $min_length =~ m/\D/ ) or ( $min_length < 1 ) ) {
        $min_length = $app->config->default('UserPasswordMinLength');
    }

    my $msg = $app->translate( "minimum length of [_1]", $min_length );
    $msg .= $app->translate(', uppercase and lowercase letters')
        if grep { $_ eq 'upperlower' } @constrains;
    $msg .= $app->translate(', letters and numbers')
        if grep { $_ eq 'letternumber' } @constrains;
    $msg .= $app->translate(', symbols (such as #!$%)')
        if grep { $_ eq 'symbol' } @constrains;

    return $msg;
}

1;
__END__