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

/**
 * @file
 * Enables the user registration and login system.
 */

define('USERNAME_MAX_LENGTH', 60);
define('EMAIL_MAX_LENGTH', 64);

/**
 * Invokes hook_user() in every module.
 *
 * We cannot use module_invoke() for this, because the arguments need to
 * be passed by reference.
 */
function user_module_invoke($type, &$array, &$user, $category = NULL) {
  foreach (module_list() as $module) {
    $function = $module .'_user';
    if (function_exists($function)) {
      $function($type, $array, $user, $category);
    }
  }
}

/**
 * Implementation of hook_theme()
 */
function user_theme() {
  return array(
    'user_picture' => array(
      'arguments' => array('account' => NULL),
      'template' => 'user-picture',
    ),
    'user_profile' => array(
      'arguments' => array('account' => NULL),
      'template' => 'user-profile',
    ),
    'user_profile_category' => array(
      'arguments' => array('element' => NULL),
      'template' => 'user-profile-category',
    ),
    'user_profile_item' => array(
      'arguments' => array('element' => NULL),
      'template' => 'user-profile-item',
    ),
    'user_list' => array(
      'arguments' => array('users' => NULL, 'title' => NULL),
    ),
    'user_admin_perm' => array(
      'arguments' => array('form' => NULL),
    ),
    'user_admin_new_role' => array(
      'arguments' => array('form' => NULL),
    ),
    'user_admin_account' => array(
      'arguments' => array('form' => NULL),
    ),
    'user_filter_form' => array(
      'arguments' => array('form' => NULL),
    ),
    'user_filters' => array(
      'arguments' => array('form' => NULL),
    ),
    'user_signature' => array(
      'arguments' => array('signature' => NULL),
    ),
  );
}

function user_external_load($authname) {
  $result = db_query("SELECT uid FROM {authmap} WHERE authname = '%s'", $authname);

  if ($user = db_fetch_array($result)) {
    return user_load($user);
  }
  else {
    return 0;
  }
}

/**
 * Perform standard Drupal login operations for a user object.  The
 * user object must already be authenticated. This function verifies
 * that the user account is not blocked/denied and then performs the login,
 * updates the login timestamp in the database, invokes hook_user('login'),
 * regenerates the session, etc.
 *
 * @param $account
 *    An authenticated user object to be set as the currently logged
 *    in user.
 * @param $edit
 *    The array of form values submitted by the user, if any.
 * @return boolean
 *    TRUE if the login succeeds, FALSE otherwise.
 */
function user_external_login($account, $edit = array()) {
  $form = drupal_get_form('user_login');

  $state['values'] = $edit;
  if (empty($state['values']['name'])) {
    $state['values']['name'] = $account->name;
  }

  user_login_name_validate($form, $state, (array)$account);
  if (form_get_errors()) {
    return FALSE;
  }
  global $user;
  $user = $account;
  user_login_submit($form, $state, (array)$account);
  return TRUE;
}

/**
 * Fetch a user object.
 *
 * @param $array
 *   An associative array of attributes to search for in selecting the
 *   user, such as user name or e-mail address.
 *
 * @return
 *   A fully-loaded $user object upon successful user load or FALSE if user cannot be loaded.
 */
function user_load($array = array()) {
  // Dynamically compose a SQL query:
  $query = array();
  $params = array();

  if (is_numeric($array)) {
    $array = array('uid' => $array);
  }
  elseif (!is_array($array)) {
    return FALSE;
  }

  foreach ($array as $key => $value) {
    if ($key == 'uid' || $key == 'status') {
      $query[] = "$key = %d";
      $params[] = $value;
    }
    else if ($key == 'pass') {
      $query[] = "pass = '%s'";
      $params[] = md5($value);
    }
    else {
      $query[]= "LOWER($key) = LOWER('%s')";
      $params[] = $value;
    }
  }
  $result = db_query('SELECT * FROM {users} u WHERE '. implode(' AND ', $query), $params);

  if ($user = db_fetch_object($result)) {
    $user = drupal_unpack($user);

    $user->roles = array();
    if ($user->uid) {
      $user->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
    }
    else {
      $user->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
    }
    $result = db_query('SELECT r.rid, r.name FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid = %d', $user->uid);
    while ($role = db_fetch_object($result)) {
      $user->roles[$role->rid] = $role->name;
    }
    user_module_invoke('load', $array, $user);
  }
  else {
    $user = FALSE;
  }

  return $user;
}

/**
 * Save changes to a user account or add a new user.
 *
 * @param $account
 *   The $user object for the user to modify or add. If $user->uid is
 *   omitted, a new user will be added.
 *
 * @param $array
 *   An array of fields and values to save. For example array('name' => 'My name');
 *   Setting a field to NULL deletes it from the data column.
 *
 * @param $category
 *   (optional) The category for storing profile information in.
 */
function user_save($account, $array = array(), $category = 'account') {
  // Dynamically compose a SQL query:
  $user_fields = user_fields();
  if (is_object($account) && $account->uid) {
    user_module_invoke('update', $array, $account, $category);
    if (isset($array['status']) && $array['status'] != $account->status) {
      // The user's status is changing, conditionally send notification email.
      $op = $array['status'] == 1 ? 'status_activated' : 'status_blocked';
      _user_mail_notify($op, $account);
    }
    $query = '';
    $data = unserialize(db_result(db_query('SELECT data FROM {users} WHERE uid = %d', $account->uid)));
    foreach ($array as $key => $value) {
      if ($key == 'pass' && !empty($value)) {
        $query .= "$key = '%s', ";
        $v[] = md5($value);
      }
      else if ((substr($key, 0, 4) !== 'auth') && ($key != 'pass')) {
        if (in_array($key, $user_fields)) {
          // Save standard fields
          $query .= "$key = '%s', ";
          $v[] = $value;
        }
        else if ($key != 'roles') {
          // Roles is a special case: it used below.
          if ($value === NULL) {
            unset($data[$key]);
          }
          else {
            $data[$key] = $value;
          }
        }
      }
    }
    $query .= "data = '%s' ";
    $v[] = serialize($data);

    db_query("UPDATE {users} SET $query WHERE uid = %d", array_merge($v, array($account->uid)));

    // Reload user roles if provided
    if (isset($array['roles']) && is_array($array['roles'])) {
      db_query('DELETE FROM {users_roles} WHERE uid = %d', $account->uid);

      foreach (array_keys($array['roles']) as $rid) {
        if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
          db_query('INSERT INTO {users_roles} (uid, rid) VALUES (%d, %d)', $account->uid, $rid);
        }
      }
    }

    // Delete a blocked user's sessions to kick them if they are online.
    if (isset($array['status']) && $array['status'] == 0) {
      sess_destroy_uid($account->uid);
    }

    // If the password changed, delete all open sessions and recreate
    // the current one.
    if (!empty($array['pass'])) {
      sess_destroy_uid($account->uid);
      sess_regenerate();
    }

    // Refresh user object
    $user = user_load(array('uid' => $account->uid));
    user_module_invoke('after_update', $array, $user, $category);
  }
  else {
    if (!isset($array['created'])) {    // Allow 'created' to be set by the caller
      $array['created'] = time();
    }

    // Note, we wait with saving the data column to prevent module-handled
    // fields from being saved there. We cannot invoke hook_user('insert') here
    // because we don't have a fully initialized user object yet.
    foreach ($array as $key => $value) {
      switch ($key) {
        case 'pass':
          $fields[] = $key;
          $values[] = md5($value);
          $s[] = "'%s'";
          break;
        case 'mode':       case 'sort':     case 'timezone':
        case 'threshold':  case 'created':  case 'access':
        case 'login':      case 'status':
          $fields[] = $key;
          $values[] = $value;
          $s[] = "%d";
          break;
        default:
          if (substr($key, 0, 4) !== 'auth' && in_array($key, $user_fields)) {
            $fields[] = $key;
            $values[] = $value;
            $s[] = "'%s'";
          }
          break;
      }
    }
    db_query('INSERT INTO {users} ('. implode(', ', $fields) .') VALUES ('. implode(', ', $s) .')', $values);
    $array['uid'] = db_last_insert_id('users', 'uid');

    // Build the initial user object.
    $user = user_load(array('uid' => $array['uid']));

    user_module_invoke('insert', $array, $user, $category);

    // Build and save the serialized data field now
    $data = array();
    foreach ($array as $key => $value) {
      if ((substr($key, 0, 4) !== 'auth') && ($key != 'roles') && (!in_array($key, $user_fields)) && ($value !== NULL)) {
        $data[$key] = $value;
      }
    }
    db_query("UPDATE {users} SET data = '%s' WHERE uid = %d", serialize($data), $user->uid);

    // Save user roles (delete just to be safe).
    if (isset($array['roles']) && is_array($array['roles'])) {
      db_query('DELETE FROM {users_roles} WHERE uid = %d', $array['uid']);
      foreach (array_keys($array['roles']) as $rid) {
        if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
          db_query('INSERT INTO {users_roles} (uid, rid) VALUES (%d, %d)', $array['uid'], $rid);
        }
      }
    }

    // Build the finished user object.
    $user = user_load(array('uid' => $array['uid']));
  }

  // Save distributed authentication mappings
  $authmaps = array();
  foreach ($array as $key => $value) {
    if (substr($key, 0, 4) == 'auth') {
      $authmaps[$key] = $value;
    }
  }
  if (sizeof($authmaps) > 0) {
    user_set_authmaps($user, $authmaps);
  }

  return $user;
}

/**
 * Verify the syntax of the given name.
 */
function user_validate_name($name) {
  if (!strlen($name)) return t('You must enter a username.');
  if (substr($name, 0, 1) == ' ') return t('The username cannot begin with a space.');
  if (substr($name, -1) == ' ') return t('The username cannot end with a space.');
  if (strpos($name, '  ') !== FALSE) return t('The username cannot contain multiple spaces in a row.');
  if (ereg("[^\x80-\xF7 [:alnum:]@_.-]", $name)) return t('The username contains an illegal character.');
  if (preg_match('/[\x{80}-\x{A0}'.          // Non-printable ISO-8859-1 + NBSP
                   '\x{AD}'.                 // Soft-hyphen
                   '\x{2000}-\x{200F}'.      // Various space characters
                   '\x{2028}-\x{202F}'.      // Bidirectional text overrides
                   '\x{205F}-\x{206F}'.      // Various text hinting characters
                   '\x{FEFF}'.               // Byte order mark
                   '\x{FF01}-\x{FF60}'.      // Full-width latin
                   '\x{FFF9}-\x{FFFD}'.      // Replacement characters
                   '\x{0}]/u',               // NULL byte
                   $name)) {
    return t('The username contains an illegal character.');
  }
  if (strpos($name, '@') !== FALSE && !eregi('@([0-9a-z](-?[0-9a-z])*.)+[a-z]{2}([zmuvtg]|fo|me)?$', $name)) return t('The username is not a valid authentication ID.');
  if (strlen($name) > USERNAME_MAX_LENGTH) return t('The username %name is too long: it must be %max characters or less.', array('%name' => $name, '%max' => USERNAME_MAX_LENGTH));
}

function user_validate_mail($mail) {
  if (!$mail) return t('You must enter an e-mail address.');
  if (!valid_email_address($mail)) {
    return t('The e-mail address %mail is not valid.', array('%mail' => $mail));
  }
}

function user_validate_picture(&$form, &$form_state) {
  // If required, validate the uploaded picture.
  $validators = array(
    'file_validate_is_image' => array(),
    'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')),
    'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024),
  );
  if ($file = file_save_upload('picture_upload', $validators)) {
    // The image was saved using file_save_upload() and was added to the
    // files table as a temporary file. We'll make a copy and let the garbage
    // collector delete the original upload.
    $info = image_get_info($file->filepath);
    $destination = variable_get('user_picture_path', 'pictures') .'/picture-'. $form['#uid'] .'.'. $info['extension'];
    if (file_copy($file, $destination, FILE_EXISTS_REPLACE)) {
      $form_state['values']['picture'] = $file->filepath;
    }
    else {
      form_set_error('picture_upload', t("Failed to upload the picture image; the %directory directory doesn't exist or is not writable.", array('%directory' => variable_get('user_picture_path', 'pictures'))));
    }
  }
}

/**
 * Generate a random alphanumeric password.
 */
function user_password($length = 10) {
  // This variable contains the list of allowable characters for the
  // password. Note that the number 0 and the letter 'O' have been
  // removed to avoid confusion between the two. The same is true
  // of 'I', 1, and l.
  $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';

  // Zero-based count of characters in the allowable list:
  $len = strlen($allowable_characters) - 1;

  // Declare the password as a blank string.
  $pass = '';

  // Loop the number of times specified by $length.
  for ($i = 0; $i < $length; $i++) {

    // Each iteration, pick a random character from the
    // allowable string and append it to the password:
    $pass .= $allowable_characters[mt_rand(0, $len)];
  }

  return $pass;
}

/**
 * Determine whether the user has a given privilege.
 *
 * @param $string
 *   The permission, such as "administer nodes", being checked for.
 * @param $account
 *   (optional) The account to check, if not given use currently logged in user.
 *
 * @return
 *   boolean TRUE if the current user has the requested permission.
 *
 * All permission checks in Drupal should go through this function. This
 * way, we guarantee consistent behavior, and ensure that the superuser
 * can perform all actions.
 */
function user_access($string, $account = NULL) {
  global $user;
  static $perm = array();

  if (is_null($account)) {
    $account = $user;
  }

  // User #1 has all privileges:
  if ($account->uid == 1) {
    return TRUE;
  }

  // To reduce the number of SQL queries, we cache the user's permissions
  // in a static variable.
  if (!isset($perm[$account->uid])) {
    $result = db_query("SELECT DISTINCT(p.perm) FROM {role} r INNER JOIN {permission} p ON p.rid = r.rid WHERE r.rid IN (%s)", implode(',', array_keys($account->roles)));

    $perm[$account->uid] = '';
    while ($row = db_fetch_object($result)) {
      $perm[$account->uid] .= "$row->perm, ";
    }
  }

  if (isset($perm[$account->uid])) {
    return strpos($perm[$account->uid], "$string, ") !== FALSE;
  }

  return FALSE;
}

/**
 * Checks for usernames blocked by user administration
 *
 * @return boolean TRUE for blocked users, FALSE for active
 */
function user_is_blocked($name) {
  $deny  = db_fetch_object(db_query("SELECT name FROM {users} WHERE status = 0 AND name = LOWER('%s')", $name));

  return $deny;
}

function user_fields() {
  static $fields;

  if (!$fields) {
    $result = db_query('SELECT * FROM {users} WHERE uid = 1');
    if ($field = db_fetch_array($result)) {
      $fields = array_keys($field);
    }
    else {
      // Make sure we return the default fields at least
      $fields = array('uid', 'name', 'pass', 'mail', 'picture', 'mode', 'sort', 'threshold', 'theme', 'signature', 'created', 'access', 'login', 'status', 'timezone', 'language', 'init', 'data');
    }
  }

  return $fields;
}

/**
 * Implementation of hook_perm().
 */
function user_perm() {
  return array('administer access control', 'administer users', 'access user profiles', 'change own username');
}

/**
 * Implementation of hook_file_download().
 *
 * Ensure that user pictures (avatars) are always downloadable.
 */
function user_file_download($file) {
  if (strpos($file, variable_get('user_picture_path', 'pictures') .'/picture-') === 0) {
    $info = image_get_info(file_create_path($file));
    return array('Content-type: '. $info['mime_type']);
  }
}

/**
 * Implementation of hook_search().
 */
function user_search($op = 'search', $keys = NULL, $skip_access_check = FALSE) {
  switch ($op) {
    case 'name':
      if ($skip_access_check || user_access('access user profiles')) {
        return t('Users');
      }
    case 'search':
      if (user_access('access user profiles')) {
        $find = array();
        // Replace wildcards with MySQL/PostgreSQL wildcards.
        $keys = preg_replace('!\*+!', '%', $keys);
        if (user_access('administer users')) {
          // Administrators can also search in the otherwise private email field.
          $result = pager_query("SELECT name, uid, mail FROM {users} WHERE LOWER(name) LIKE LOWER('%%%s%%') OR LOWER(mail) LIKE LOWER('%%%s%%')", 15, 0, NULL, $keys, $keys);
          while ($account = db_fetch_object($result)) {
            $find[] = array('title' => $account->name .' ('. $account->mail .')', 'link' => url('user/'. $account->uid, array('absolute' => TRUE)));
          }
        }
        else {
          $result = pager_query("SELECT name, uid FROM {users} WHERE LOWER(name) LIKE LOWER('%%%s%%')", 15, 0, NULL, $keys);
          while ($account = db_fetch_object($result)) {
            $find[] = array('title' => $account->name, 'link' => url('user/'. $account->uid, array('absolute' => TRUE)));
          }
        }
        return $find;
      }
  }
}

/**
 * Implementation of hook_elements().
 */
function user_elements() {
  return array(
    'user_profile_category' => array(),
    'user_profile_item' => array(),
  );
}

/**
 * Implementation of hook_user().
 */
function user_user($type, &$edit, &$account, $category = NULL) {
  if ($type == 'view') {
    $account->content['user_picture'] = array(
      '#value' => theme('user_picture', $account),
      '#weight' => -10,
    );
    if (!isset($account->content['summary'])) {
      $account->content['summary'] = array();
    }
    $account->content['summary'] += array(
      '#type' => 'user_profile_category',
      '#attributes' => array('class' => 'user-member'),
      '#weight' => -5,
      '#title' => t('History'),
    );
    $account->content['summary']['member_for'] =  array(
      '#type' => 'user_profile_item',
      '#title' => t('Member for'),
      '#value' => format_interval(time() - $account->created),
    );
  }
  if ($type == 'form' && $category == 'account') {
    $form_state = array();
    return user_edit_form($form_state, arg(1), $edit);
  }

  if ($type == 'validate' && $category == 'account') {
    return _user_edit_validate(arg(1), $edit);
  }

  if ($type == 'submit' && $category == 'account') {
    return _user_edit_submit(arg(1), $edit);
  }

  if ($type == 'categories') {
    return array(array('name' => 'account', 'title' => t('Account settings'), 'weight' => 1));
  }
}

function user_login_block() {
  $form = array(
    '#action' => url($_GET['q'], array('query' => drupal_get_destination())),
    '#id' => 'user-login-form',
    '#validate' => user_login_default_validators(),
    '#submit' => array('user_login_submit'),
  );
  $form['name'] = array('#type' => 'textfield',
    '#title' => t('Username'),
    '#maxlength' => USERNAME_MAX_LENGTH,
    '#size' => 15,
    '#required' => TRUE,
  );
  $form['pass'] = array('#type' => 'password',
    '#title' => t('Password'),
    '#maxlength' => 60,
    '#size' => 15,
    '#required' => TRUE,
  );
  $form['submit'] = array('#type' => 'submit',
    '#value' => t('Log in'),
  );
  $items = array();
  if (variable_get('user_register', 1)) {
    $items[] = l(t('Create new account'), 'user/register', array('title' => t('Create a new user account.')));
  }
  $items[] = l(t('Request new password'), 'user/password', array('title' => t('Request new password via e-mail.')));
  $form['links'] = array('#value' => theme('item_list', $items));
  return $form;
}

/**
 * Implementation of hook_block().
 */
function user_block($op = 'list', $delta = 0, $edit = array()) {
  global $user;

  if ($op == 'list') {
     $blocks[0]['info'] = t('User login');
     // Not worth caching.
     $blocks[0]['cache'] = BLOCK_NO_CACHE;

     $blocks[1]['info'] = t('Navigation');
      // Menu blocks can't be cached because each menu item can have
      // a custom access callback. menu.inc manages its own caching.
     $blocks[1]['cache'] = BLOCK_NO_CACHE;

     $blocks[2]['info'] = t('Who\'s new');

     // Too dynamic to cache.
     $blocks[3]['info'] = t('Who\'s online');
     $blocks[3]['cache'] = BLOCK_NO_CACHE;
     return $blocks;
  }
  else if ($op == 'configure' && $delta == 2) {
    $form['user_block_whois_new_count'] = array(
      '#type' => 'select',
      '#title' => t('Number of users to display'),
      '#default_value' => variable_get('user_block_whois_new_count', 5),
      '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)),
    );
    return $form;
  }
  else if ($op == 'configure' && $delta == 3) {
    $period = drupal_map_assoc(array(30, 60, 120, 180, 300, 600, 900, 1800, 2700, 3600, 5400, 7200, 10800, 21600, 43200, 86400), 'format_interval');
    $form['user_block_seconds_online'] = array('#type' => 'select', '#title' => t('User activity'), '#default_value' => variable_get('user_block_seconds_online', 900), '#options' => $period, '#description' => t('A user is considered online for this long after they have last viewed a page.'));
    $form['user_block_max_list_count'] = array('#type' => 'select', '#title' => t('User list length'), '#default_value' => variable_get('user_block_max_list_count', 10), '#options' => drupal_map_assoc(array(0, 5, 10, 15, 20, 25, 30, 40, 50, 75, 100)), '#description' => t('Maximum number of currently online users to display.'));

    return $form;
  }
  else if ($op == 'save' && $delta == 2) {
    variable_set('user_block_whois_new_count', $edit['user_block_whois_new_count']);
  }
  else if ($op == 'save' && $delta == 3) {
    variable_set('user_block_seconds_online', $edit['user_block_seconds_online']);
    variable_set('user_block_max_list_count', $edit['user_block_max_list_count']);
  }
  else if ($op == 'view') {
    $block = array();

    switch ($delta) {
      case 0:
        // For usability's sake, avoid showing two login forms on one page.
        if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) {

          $block['subject'] = t('User login');
          $block['content'] = drupal_get_form('user_login_block');
        }
        return $block;

      case 1:
        if ($menu = menu_tree()) {
           $block['subject'] = $user->uid ? check_plain($user->name) : t('Navigation');
           $block['content'] = $menu;
        }
        return $block;

      case 2:
        if (user_access('access content')) {
          // Retrieve a list of new users who have subsequently accessed the site successfully.
          $result = db_query_range('SELECT uid, name FROM {users} WHERE status != 0 AND access != 0 ORDER BY created DESC', 0, variable_get('user_block_whois_new_count', 5));
          while ($account = db_fetch_object($result)) {
            $items[] = $account;
          }
          $output = theme('user_list', $items);

          $block['subject'] = t('Who\'s new');
          $block['content'] = $output;
        }
        return $block;

      case 3:
        if (user_access('access content')) {
          // Count users active within the defined period.
          $interval = time() - variable_get('user_block_seconds_online', 900);

          // Perform database queries to gather online user lists.  We use s.timestamp
          // rather than u.access because it is much faster.
          $anonymous_count = sess_count($interval);
          $authenticated_users = db_query('SELECT DISTINCT u.uid, u.name, s.timestamp FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.timestamp >= %d AND s.uid > 0 ORDER BY s.timestamp DESC', $interval);
          $authenticated_count = 0;
          $max_users = variable_get('user_block_max_list_count', 10);
          $items = array();
          while ($account = db_fetch_object($authenticated_users)) {
            if ($max_users > 0) {
              $items[] = $account;
              $max_users--;
            }
            $authenticated_count++;
          }

          // Format the output with proper grammar.
          if ($anonymous_count == 1 && $authenticated_count == 1) {
            $output = t('There is currently %members and %visitors online.', array('%members' => format_plural($authenticated_count, '1 user', '@count users'), '%visitors' => format_plural($anonymous_count, '1 guest', '@count guests')));
          }
          else {
            $output = t('There are currently %members and %visitors online.', array('%members' => format_plural($authenticated_count, '1 user', '@count users'), '%visitors' => format_plural($anonymous_count, '1 guest', '@count guests')));
          }

          // Display a list of currently online users.
          $max_users = variable_get('user_block_max_list_count', 10);
          if ($authenticated_count && $max_users) {
            $output .= theme('user_list', $items, t('Online users'));
          }

          $block['subject'] = t('Who\'s online');
          $block['content'] = $output;
        }
        return $block;
    }
  }
}

/**
 * Process variables for user-picture.tpl.php.
 *
 * The $variables array contains the following arguments:
 * - $account
 *
 * @see user-picture.tpl.php
 */
function template_preprocess_user_picture(&$variables) {
  $variables['picture'] = '';
  if (variable_get('user_pictures', 0)) {
    $account = $variables['account'];
    if (!empty($account->picture) && file_exists($account->picture)) {
      $picture = file_create_url($account->picture);
    }
    else if (variable_get('user_picture_default', '')) {
      $picture = variable_get('user_picture_default', '');
    }

    if (isset($picture)) {
      $alt = t("@user's picture", array('@user' => $account->name ? $account->name : variable_get('anonymous', t('Anonymous'))));
      $variables['picture'] = theme('image', $picture, $alt, $alt, '', FALSE);
      if (!empty($account->uid) && user_access('access user profiles')) {
        $attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE);
        $variables['picture'] = l($variables['picture'], "user/$account->uid", $attributes);
      }
    }
  }
}

/**
 * Make a list of users.
 *
 * @param $users
 *   An array with user objects. Should contain at least the name and uid.
 * @param $title
 *  (optional) Title to pass on to theme_item_list().
 *
 * @ingroup themeable
 */
function theme_user_list($users, $title = NULL) {
  if (!empty($users)) {
    foreach ($users as $user) {
      $items[] = theme('username', $user);
    }
  }
  return theme('item_list', $items, $title);
}

/**
 * Process variables for user-profile.tpl.php.
 *
 * The $variables array contains the following arguments:
 * - $account
 *
 * @see user-picture.tpl.php
 */
function template_preprocess_user_profile(&$variables) {
  $variables['profile'] = array();
  // Provide keyed variables so themers can print each section independantly.
  foreach (element_children($variables['account']->content) as $key) {
    $variables['profile'][$key] = drupal_render($variables['account']->content[$key]);
  }
  // Collect all profiles to make it easier to print all items at once.
  $variables['user_profile'] = implode($variables['profile']);
}

/**
 * Process variables for user-profile-item.tpl.php.
 *
 * The $variables array contains the following arguments:
 * - $element
 *
 * @see user-profile-item.tpl.php
 */
function template_preprocess_user_profile_item(&$variables) {
  $variables['title'] = $variables['element']['#title'];
  $variables['value'] = $variables['element']['#value'];
  $variables['attributes'] = '';
  if (isset($variables['element']['#attributes'])) {
    $variables['attributes'] = drupal_attributes($variables['element']['#attributes']);
  }
}

/**
 * Process variables for user-profile-category.tpl.php.
 *
 * The $variables array contains the following arguments:
 * - $element
 *
 * @see user-profile-category.tpl.php
 */
function template_preprocess_user_profile_category(&$variables) {
  $variables['title'] = $variables['element']['#title'];
  $variables['profile_items'] = $variables['element']['#children'];
  $variables['attributes'] = '';
  if (isset($variables['element']['#attributes'])) {
    $variables['attributes'] = drupal_attributes($variables['element']['#attributes']);
  }
}

function user_is_anonymous() {
  return !$GLOBALS['user']->uid;
}

function user_is_logged_in() {
  return (bool)$GLOBALS['user']->uid;
}

function user_register_access() {
  return !$GLOBALS['user']->uid && variable_get('user_register', 1);
}

function user_view_access($account) {
  return $account && $account->uid &&
    (
      // Always let users view their own profile.
      ($GLOBALS['user']->uid == $account->uid) ||
      // Administrators can view all accounts.
      user_access('administer users') ||
      // The user is not blocked and logged in at least once.
      ($account->access && $account->status && user_access('access user profiles'))
    );
}

function user_edit_access($account) {
  return ($GLOBALS['user']->uid == $account->uid) || user_access('administer users');
}

function user_load_self($arg) {
  $arg[1] = user_load($GLOBALS['user']->uid);
  return $arg;
}

/**
 * Implementation of hook_menu().
 */
function user_menu() {
  $items['user/autocomplete'] = array(
    'title' => 'User autocomplete',
    'page callback' => 'user_autocomplete',
    'access callback' => 'user_access',
    'access arguments' => array('access user profiles'),
    'type' => MENU_CALLBACK,
  );

  // Registration and login pages.
  $items['user'] = array(
    'title' => 'Log in',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_login'),
    'access callback' => 'user_is_anonymous',
    'type' => MENU_CALLBACK,
  );

  $items['user/login'] = array(
    'title' => 'Log in',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );

  $items['user/register'] = array(
    'title' => 'Create new account',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_register'),
    'access callback' => 'user_register_access',
    'type' => MENU_LOCAL_TASK,
  );

  $items['user/password'] = array(
    'title' => 'Request new password',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_pass'),
    'access callback' => 'user_is_anonymous',
    'type' => MENU_LOCAL_TASK,
  );
  $items['user/reset/%/%/%'] = array(
    'title' => 'Reset password',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_pass_reset', 2, 3, 4),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  // Admin user pages
  $items['admin/user'] = array(
    'title' => 'User management',
    'description' => "Manage your site's users, groups and access to site features.",
    'position' => 'left',
    'page callback' => 'system_admin_menu_block_page',
    'access arguments' => array('administer site configuration'),
    'file' => 'system.admin.inc',
    'file path' => drupal_get_path('module', 'system'),
  );
  $items['admin/user/user'] = array(
    'title' => 'Users',
    'description' => 'List, add, and edit users.',
    'page callback' => 'user_admin',
    'page arguments' => array('list'),
    'access arguments' => array('administer users'));
  $items['admin/user/user/list'] = array(
    'title' => 'List',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/user/user/create'] = array(
    'title' => 'Add user',
    'page arguments' => array('create'),
    'type' => MENU_LOCAL_TASK,
  );
  $items['admin/user/settings'] = array(
    'title' => 'User settings',
    'description' => 'Configure default behavior of users, including registration requirements, e-mails, and user pictures.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_admin_settings'),
  );

  // Admin access pages
  $items['admin/user/access'] = array(
    'title' => 'Access control',
    'description' => 'Determine access to features by selecting permissions for roles.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_admin_perm'),
    'access arguments' => array('administer access control'),
  );
  $items['admin/user/roles'] = array(
    'title' => 'Roles',
    'description' => 'List, edit, or add user roles.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_admin_new_role'),
    'access arguments' => array('administer access control'),
  );
  $items['admin/user/roles/edit'] = array(
    'title' => 'Edit role',
    'page arguments' => array('user_admin_role'),
    'type' => MENU_CALLBACK,
  );
  $items['admin/user/rules'] = array(
    'title' => 'Access rules',
    'description' => 'List and create rules to disallow usernames, e-mail addresses, and IP addresses.',
    'page callback' => 'user_admin_access',
    'access arguments' => array('administer access control'),
  );
  $items['admin/user/rules/list'] = array(
    'title' => 'List',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/user/rules/add'] = array(
    'title' => 'Add rule',
    'page callback' => 'user_admin_access_add',
    'type' => MENU_LOCAL_TASK,
  );
  $items['admin/user/rules/check'] = array(
    'title' => 'Check rules',
    'page callback' => 'user_admin_access_check',
    'type' => MENU_LOCAL_TASK,
  );
  $items['admin/user/rules/edit'] = array(
    'title' => 'Edit rule',
    'page callback' => 'user_admin_access_edit',
    'type' => MENU_CALLBACK,
  );
  $items['admin/user/rules/delete'] = array(
    'title' => 'Delete rule',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_admin_access_delete_confirm'),
    'type' => MENU_CALLBACK,
  );

  if (module_exists('search')) {
    $items['admin/user/search'] = array(
      'title' => 'Search users',
      'description' => 'Search users by name or e-mail address.',
      'page callback' => 'user_admin',
      'page arguments' => array('search'),
      'access arguments' => array('administer users'),
    );
  }

  $items['logout'] = array(
    'title' => 'Log out',
    'access callback' => 'user_is_logged_in',
    'page callback' => 'user_logout',
    'weight' => 10,
  );

  $items['user/%user_current'] = array(
    'title' => 'My account',
    'page callback' => 'user_view',
    'page arguments' => array(1),
    'access callback' => 'user_view_access',
    'access arguments' => array(1),
    'parent' => '',
  );

  $items['user/%user/view'] = array(
    'title' => 'View',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );

  $items['user/%user/delete'] = array(
    'title' => 'Delete',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_confirm_delete', 1),
    'access callback' => 'user_access',
    'access arguments' => array('administer users'),
    'type' => MENU_CALLBACK,
  );

  $items['user/%user/edit'] = array(
    'title' => 'Edit',
    'page callback' => 'user_edit',
    'page arguments' => array(1),
    'access callback' => 'user_edit_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
  );

  $items['user/%user/edit/account'] = array(
    'title' => 'Account',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );

  $empty_account = new stdClass();
  if (($categories = _user_categories($empty_account)) && (count($categories) > 1)) {
    foreach ($categories as $key => $category) {
      // 'account' is already handled by the MENU_DEFAULT_LOCAL_TASK.
      if ($category['name'] != 'account') {
        $items['user/%user/edit/'. $category['name']] = array(
          'title callback' => 'check_plain',
          'title arguments' => array($category['title']),
          'page callback' => 'user_edit',
          'page arguments' => array(1, 3),
          'type' => MENU_LOCAL_TASK,
          'weight' => $category['weight'],
        );
      }
    }
  }
  return $items;
}

function user_init() {
  drupal_add_css(drupal_get_path('module', 'user') .'/user.css', 'module');
}

function user_current_load($arg) {
  return $arg ? user_load($arg) : user_load($GLOBALS['user']->uid);
}

function user_current_to_arg($arg) {

  if (is_numeric($arg)) {
    return $arg;
  }
  return $GLOBALS['user']->uid;
}

/**
 * Accepts an user object, $account, or a DA name and returns an associative
 * array of modules and DA names. Called at external login.
 */
function user_get_authmaps($authname = NULL) {
  $result = db_query("SELECT authname, module FROM {authmap} WHERE authname = '%s'", $authname);
  $authmaps = array();
  $has_rows = FALSE;
  while ($authmap = db_fetch_object($result)) {
    $authmaps[$authmap->module] = $authmap->authname;
    $has_rows = TRUE;
  }
  return $has_rows ? $authmaps : 0;
}

function user_set_authmaps($account, $authmaps) {
  foreach ($authmaps as $key => $value) {
    $module = explode('_', $key, 2);
    if ($value) {
      db_query("UPDATE {authmap} SET authname = '%s' WHERE uid = %d AND module = '%s'", $value, $account->uid, $module[1]);
      if (!db_affected_rows()) {
        db_query("INSERT INTO {authmap} (authname, uid, module) VALUES ('%s', %d, '%s')", $value, $account->uid, $module[1]);
      }
    }
    else {
      db_query("DELETE FROM {authmap} WHERE uid = %d AND module = '%s'", $account->uid, $module[1]);
    }
  }
}

function user_login(&$form_state, $msg = '') {
  global $user;

  // If we are already logged on, go to the user page instead.
  if ($user->uid) {
    drupal_goto('user/'. $user->uid);
  }

  // Display login form:
  if ($msg) {
    $form['message'] = array('#value' => '<p>'. check_plain($msg) .'</p>');
  }
  $form['name'] = array('#type' => 'textfield',
    '#title' => t('Username'),
    '#size' => 60,
    '#maxlength' => USERNAME_MAX_LENGTH,
    '#required' => TRUE,
    '#attributes' => array('tabindex' => '1'),
  );

  $form['name']['#description'] = t('Enter your @s username.', array('@s' => variable_get('site_name', 'Drupal')));
  $form['pass'] = array('#type' => 'password',
    '#title' => t('Password'),
    '#description' => t('Enter the password that accompanies your username.'),
    '#required' => TRUE,
    '#attributes' => array('tabindex' => '2'),
  );
  $form['#validate'] = user_login_default_validators();
  $form['submit'] = array('#type' => 'submit', '#value' => t('Log in'), '#weight' => 2, '#attributes' => array('tabindex' => '3'));

  return $form;
}

/**
 * Setup a series for validators which check for blocked/denied users,
 * then authenticate against local database, then return an error if
 * authentication fails. Distributed authentication modules (e.g.
 * drupal.module) are welcome to use hook_form_alter() to change this
 * series in order to authenticate against their user database instead
 * of local users table.
 *
 * We use three validators instead of one since external authentication
 * modules usually only need to alter the second validator. See
 * drupal_form_alter() in drupal.module for an example of altering
 * this series of validators.
 *
 * @return array
 *   A simple list of validate functions.
 **/
function user_login_default_validators() {
  return array('user_login_name_validate', 'user_login_authenticate_validate', 'user_login_final_validate');
}

/**
 * A FAPI validate handler. Sets an error is supplied username has been blocked or denied access.
 *
 * @return void
 **/
function user_login_name_validate($form, &$form_state) {
  if (isset($form_state['values']['name'])) {
    if (user_is_blocked($form_state['values']['name'])) {
      // blocked in user administration
      form_set_error('name', t('The username %name has not been activated or is blocked.', array('%name' => $form_state['values']['name'])));
    }
    else if (drupal_is_denied('user', $form_state['values']['name'])) {
      // denied by access controls
      form_set_error('name', t('The name %name is a reserved username.', array('%name' => $form_state['values']['name'])));
    }
  }
}

/**
 * A validate handler on the login form. Check supplied username/password against local users table.
 * If successful, sets the global $user object.

 * @return void
 **/
function user_login_authenticate_validate($form, &$form_state) {
  user_authenticate($form_state['values']['name'], trim($form_state['values']['pass']));
}

/**
 * A validate handler on the login form. Should be the last validator. Sets an error if
 * user has not been authenticated yet.
 *
 * @return void
 **/
function user_login_final_validate($form, &$form_state) {
  global $user;
  if (!$user->uid) {
    form_set_error('name', t('Sorry, unrecognized username or password. <a href="@password">Have you forgotten your password?</a>', array('@password' => url('user/password'))));
    watchdog('user', 'Login attempt failed for %user.', array('%user' => $form_state['values']['name']));
  }
}

/**
 * Try to log in the user locally.
 *
 * @return
 *   A $user object, if successful.
 **/
function user_authenticate($name, $pass) {
  global $user;

  if ($account = user_load(array('name' => $name, 'pass' => $pass, 'status' => 1))) {
    $user = $account;
    return $user;
  }
}

/**
 * A validate handler on the login form. Update user's login timestamp, fire hook_user('login), and generate new session ID.
 *
 * @return void
 **/
function user_login_submit($form, &$form_state) {
  global $user;
  if ($user->uid) {
    watchdog('user', 'Session opened for %name.', array('%name' => $user->name));

    // Update the user table timestamp noting user has logged in.
    db_query("UPDATE {users} SET login = %d WHERE uid = %d", time(), $user->uid);

    user_module_invoke('login', $form_state['values'], $user);

    sess_regenerate();
    $form_state['redirect'] = 'user/'. $user->uid;
    return;
  }
}

/**
 * Helper function for authentication modules. Either login in or registers the current user, based on username.
 * Either way, the global $user object is populated based on $name.
 *
 * @return void
 **/
function user_external_login_register($name, $module) {
  global $user;

  $user = user_load(array('name' => $name));
  if (!isset($user->uid)) {
    // Register this new user.
    $userinfo = array('name' => $name, 'pass' => user_password(), 'init' => $name, 'status' => 1, "authname_$module" => $name);
    $user = user_save('', $userinfo);
    watchdog('user', 'New external user: %name using module %module.', array('%name' => $name, '%module' => $module), WATCHDOG_NOTICE, l(t('edit'), 'user/'. $user->uid .'/edit'));
  }
}

/**
 * Menu callback; logs the current user out, and redirects to the home page.
 */
function user_logout() {
  global $user;

  watchdog('user', 'Session closed for %name.', array('%name' => $user->name));

  // Destroy the current session:
  session_destroy();
  module_invoke_all('user', 'logout', NULL, $user);

  // Load the anonymous user
  $user = drupal_anonymous_user();

  drupal_goto();
}

function user_pass() {
  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Username or e-mail address'),
    '#size' => 60,
    '#maxlength' => max(USERNAME_MAX_LENGTH, EMAIL_MAX_LENGTH),
    '#required' => TRUE,
  );
  $form['submit'] = array('#type' => 'submit', '#value' => t('E-mail new password'));

  return $form;
}

function user_pass_validate($form, &$form_state) {
  $name = trim($form_state['values']['name']);
  if (valid_email_address($name)) {
    $account = user_load(array('mail' => $name, 'status' => 1));
  }
  else {
    $account = user_load(array('name' => $name, 'status' => 1));
  }
  if (isset($account->uid)) {
    form_set_value(array('#parents' => array('account')), $account, $form_state);
  }
  else {
    form_set_error('name', t('Sorry, %name is not recognized as a user name or an e-mail address.', array('%name' => $name)));
  }
}

function user_pass_submit($form, &$form_state) {
  global $language;

  $account = $form_state['values']['account'];
  // Mail one time login URL and instructions using current language.
  $mail_success = _user_mail_notify('password_reset', $account, $language);
  if ($mail_success) {
    watchdog('user', 'Password reset instructions mailed to %name at %email.', array('%name' => $account->name, '%email' => $account->mail));
    drupal_set_message(t('Further instructions have been sent to your e-mail address.'));
  }
  else {
    watchdog('user', 'Error mailing password reset instructions to %name at %email.', array('%name' => $account->name, '%email' => $account->mail), WATCHDOG_ERROR);
    drupal_set_message(t('Unable to send mail. Please contact the site admin.'));
  }
  $form_state['redirect'] = 'user';
  return;
}

/**
 * Menu callback; process one time login link and redirects to the user page on success.
 */
function user_pass_reset(&$form_state, $uid, $timestamp, $hashed_pass, $action = NULL) {
  global $user;

  // Check if the user is already logged in. The back button is often the culprit here.
  if ($user->uid) {
    drupal_set_message(t('You have already used this one-time login link. It is not necessary to use this link to login anymore. You are already logged in.'));
    drupal_goto();
  }
  else {
    // Time out, in seconds, until login URL expires. 24 hours = 86400 seconds.
    $timeout = 86400;
    $current = time();
    // Some redundant checks for extra security ?
    if ($timestamp < $current && $account = user_load(array('uid' => $uid, 'status' => 1)) ) {
      // No time out for first time login.
      if ($account->login && $current - $timestamp > $timeout) {
        drupal_set_message(t('You have tried to use a one-time login link that has expired. Please request a new one using the form below.'));
        drupal_goto('user/password');
      }
      else if ($account->uid && $timestamp > $account->login && $timestamp < $current && $hashed_pass == user_pass_rehash($account->pass, $timestamp, $account->login)) {
        // First stage is a confirmation form, then login
        if ($action == 'login') {
          watchdog('user', 'User %name used one-time login link at time %timestamp.', array('%name' => $account->name, '%timestamp' => $timestamp));
          // Update the user table noting user has logged in.
          // And this also makes this hashed password a one-time-only login.
          db_query("UPDATE {users} SET login = %d WHERE uid = %d", time(), $account->uid);
          // Now we can set the new user.
          $user = $account;
          // And proceed with normal login, going to user page.
          $edit = array();
          user_module_invoke('login', $edit, $user);
          drupal_set_message(t('You have just used your one-time login link. It is no longer necessary to use this link to login. Please change your password.'));
          drupal_goto('user/'. $user->uid .'/edit');
        }
        else {
          $form['message'] = array('#value' => t('<p>This is a one-time login for %user_name and will expire on %expiration_date</p><p>Click on this button to login to the site and change your password.</p>', array('%user_name' => $account->name, '%expiration_date' => format_date($timestamp + $timeout))));
          $form['help'] = array('#value' => '<p>'. t('This login can be used only once.') .'</p>');
          $form['submit'] = array('#type' => 'submit', '#value' => t('Log in'));
          $form['#action'] = url("user/reset/$uid/$timestamp/$hashed_pass/login");
          return $form;
        }
      }
      else {
        drupal_set_message(t('You have tried to use a one-time login link which has either been used or is no longer valid. Please request a new one using the form below.'));
        drupal_goto('user/password');
      }
    }
    else {
      // Deny access, no more clues.
      // Everything will be in the watchdog's URL for the administrator to check.
      drupal_access_denied();
    }
  }
}

function user_pass_reset_url($account) {
  $timestamp = time();
  return url("user/reset/$account->uid/$timestamp/". user_pass_rehash($account->pass, $timestamp, $account->login), array('absolute' => TRUE));
}

function user_pass_rehash($password, $timestamp, $login) {
  return md5($timestamp . $password . $login);
}

function user_register() {
  global $user;

  $admin = user_access('administer users');

  // If we aren't admin but already logged on, go to the user page instead.
  if (!$admin && $user->uid) {
    drupal_goto('user/'. $user->uid);
  }

  $form = array();

  // Display the registration form.
  if (!$admin) {
    $form['user_registration_help'] = array('#value' => filter_xss_admin(variable_get('user_registration_help', '')));
  }

  // Merge in the default user edit fields.
  $form = array_merge($form, user_edit_form($form_state, NULL, NULL, TRUE));
  if ($admin) {
    $form['account']['notify'] = array(
     '#type' => 'checkbox',
     '#title' => t('Notify user of new account')
    );
    // Redirect back to page which initiated the create request; usually admin/user/user/create
    $form['destination'] = array('#type' => 'hidden', '#value' => $_GET['q']);
  }

  // Create a dummy variable for pass-by-reference parameters.
  $null = NULL;
  $extra = _user_forms($null, NULL, NULL, 'register');

  // Remove form_group around default fields if there are no other groups.
  if (!$extra) {
    foreach (array('name', 'mail', 'pass', 'status', 'roles', 'notify') as $key) {
      if (isset($form['account'][$key])) {
        $form[$key] = $form['account'][$key];
      }
    }
    unset($form['account']);
  }
  else {
    $form = array_merge($form, $extra);
  }

  if (variable_get('configurable_timezones', 1)) {
    // Override field ID, so we only change timezone on user registration,
    // and never touch it on user edit pages.
    $form['timezone'] = array(
      '#type' => 'hidden',
      '#default_value' => variable_get('date_default_timezone', NULL),
      '#id' => 'edit-user-register-timezone',
    );

    // Add the JavaScript callback to automatically set the timezone.
    drupal_add_js('
// Global Killswitch
if (Drupal.jsEnabled) {
  $(document).ready(function() {
    Drupal.setDefaultTimezone();
  });
}', 'inline');
  }

  $form['submit'] = array('#type' => 'submit', '#value' => t('Create new account'), '#weight' => 30);
  $form['#validate'][] = 'user_register_validate';

  return $form;
}

function user_register_validate($form, &$form_state) {
  user_module_invoke('validate', $form_state['values'], $form_state['values'], 'account');
}

function user_register_submit($form, &$form_state) {
  global $base_url;
  $admin = user_access('administer users');

  $mail = $form_state['values']['mail'];
  $name = $form_state['values']['name'];
  if (!variable_get('user_email_verification', TRUE) || $admin) {
    $pass = $form_state['values']['pass'];
  }
  else {
    $pass = user_password();
  };
  $notify = isset($form_state['values']['notify']) ? $form_state['values']['notify'] : NULL;
  $from = variable_get('site_mail', ini_get('sendmail_from'));
  if (isset($form_state['values']['roles'])) {
    $roles = array_filter($form_state['values']['roles']);     // Remove unset roles
  }
  else {
    $roles = array();
  }

  if (!$admin && array_intersect(array_keys($form_state['values']), array('uid', 'roles', 'init', 'session', 'status'))) {
    watchdog('security', 'Detected malicious attempt to alter protected user fields.', array(), WATCHDOG_WARNING);
    $form_state['redirect'] = 'user/register';
    return;
  }
  //the unset below is needed to prevent these form values from being saved as user data
  unset($form_state['values']['form_token'], $form_state['values']['submit'], $form_state['values']['op'], $form_state['values']['notify'], $form_state['values']['form_id'], $form_state['values']['affiliates'], $form_state['values']['destination']);

  $merge_data = array('pass' => $pass, 'init' => $mail, 'roles' => $roles);
  if (!$admin) {
    // Set the user's status because it was not displayed in the form.
    $merge_data['status'] = variable_get('user_register', 1) == 1;
  }
  $account = user_save('', array_merge($form_state['values'], $merge_data));
  $form_state['user'] = $account;

  watchdog('user', 'New user: %name (%email).', array('%name' => $name, '%email' => $mail), WATCHDOG_NOTICE, l(t('edit'), 'user/'. $account->uid .'/edit'));

  // The first user may login immediately, and receives a customized welcome e-mail.
  if ($account->uid == 1) {
    drupal_set_message(t('Welcome to Drupal. You are now logged in as user #1, which gives you full control over your website.'));
    if (variable_get('user_email_verification', TRUE)) {
      drupal_set_message(t('</p><p> Your password is <strong>%pass</strong>. You may change your password below.</p>', array('%pass' => $pass)));
    }

    user_authenticate($account->name, trim($pass));

    $form_state['redirect'] = 'user/1/edit';
    return;
  }
  else {
    // Add plain text password into user account to generate mail tokens.
    $account->password = $pass;
    if ($admin && !$notify) {
      drupal_set_message(t('Created a new user account for <a href="@url">%name</a>. No e-mail has been sent.', array('@url' => url("user/$account->uid"), '%name' => $account->name)));
    }
    else if (!variable_get('user_email_verification', TRUE) && $account->status && !$admin) {
      // No e-mail verification is required, create new user account, and login user immediately.
      _user_mail_notify('register_no_approval_required', $account);
      if (user_authenticate($account->name, trim($pass))) {
        drupal_set_message(t('Registration succesful. You are now logged in.'));
      }
      $form_state['redirect'] = '';
      return;
    }
    else if ($account->status || $notify) {
      // Create new user account, no administrator approval required.
      $op = $notify ? 'register_admin_created' : 'register_no_approval_required';
      _user_mail_notify($op, $account);
      if ($notify) {
        drupal_set_message(t('Password and further instructions have been e-mailed to the new user <a href="@url">%name</a>.', array('@url' => url("user/$account->uid"), '%name' => $account->name)));
      }
      else {
        drupal_set_message(t('Your password and further instructions have been sent to your e-mail address.'));
        $form_state['redirect'] = '';
        return;
      }
    }
    else {
      // Create new user account, administrator approval required.
      _user_mail_notify('register_pending_approval', $account);
      drupal_set_message(t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.<br />In the meantime, your password and further instructions have been sent to your e-mail address.'));

    }
  }
}

function user_edit_form(&$form_state, $uid, $edit, $register = FALSE) {
  _user_password_dynamic_validation();
  $admin = user_access('administer users');

  // Account information:
  $form['account'] = array('#type' => 'fieldset',
    '#title' => t('Account information'),
    '#weight' => -10,
  );
  if (user_access('change own username') || $admin || $register) {
    $form['account']['name'] = array('#type' => 'textfield',
      '#title' => t('Username'),
      '#default_value' => $edit['name'],
      '#maxlength' => USERNAME_MAX_LENGTH,
      '#description' => t('Your preferred username; punctuation is not allowed except for periods, hyphens, and underscores.'),
      '#required' => TRUE,
    );
  }
  $form['account']['mail'] = array('#type' => 'textfield',
    '#title' => t('E-mail address'),
    '#default_value' => $edit['mail'],
    '#maxlength' => EMAIL_MAX_LENGTH,
    '#description' => t('A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.'),
    '#required' => TRUE,
  );
  if (!$register) {
    $form['account']['pass'] = array('#type' => 'password_confirm',
      '#description' => t('To change the current user password, enter the new password in both fields.'),
      '#size' => 25,
    );
  }
  elseif (!variable_get('user_email_verification', TRUE) || $admin) {
    $form['account']['pass'] = array(
      '#type' => 'password_confirm',
      '#description' => t('Provide a password for the new account in both fields.'),
      '#required' => TRUE,
      '#size' => 25,
    );
  }
  if ($admin) {
    $form['account']['status'] = array('#type' => 'radios', '#title' => t('Status'), '#default_value' => isset($edit['status']) ? $edit['status'] : 1, '#options' => array(t('Blocked'), t('Active')));
  }
  if (user_access('administer access control')) {
    $roles = user_roles(1);
    unset($roles[DRUPAL_AUTHENTICATED_RID]);
    if ($roles) {
      $default = empty($edit['roles']) ? array() : array_keys($edit['roles']);
      $form['account']['roles'] = array('#type' => 'checkboxes', '#title' => t('Roles'), '#default_value' => $default, '#options' => $roles, '#description' => t('The user receives the combined permissions of the %au role, and all roles selected here.', array('%au' => t('authenticated user'))));
    }
  }

  // Signature:
  if (variable_get('user_signatures', 0) && module_exists('comment') && !$register) {
    $form['signature_settings'] = array(
      '#type' => 'fieldset',
      '#title' => t('Signature settings'),
      '#weight' => 1,
    );
    $form['signature_settings']['signature'] = array(
      '#type' => 'textarea',
      '#title' => t('Signature'),
      '#default_value' => $edit['signature'],
      '#description' => t('Your signature will be publicly displayed at the end of your comments.'),
    );
  }

  // Picture/avatar:
  if (variable_get('user_pictures', 0) && !$register) {
    $form['picture'] = array('#type' => 'fieldset', '#title' => t('Picture'), '#weight' => 1);
    $picture = theme('user_picture', (object)$edit);
    if ($picture) {
      $form['picture']['current_picture'] = array('#value' => $picture);
      $form['picture']['picture_delete'] = array('#type' => 'checkbox', '#title' => t('Delete picture'), '#description' => t('Check this box to delete your current picture.'));
    }
    else {
      $form['picture']['picture_delete'] = array('#type' => 'hidden');
    }
    $form['picture']['picture_upload'] = array('#type' => 'file', '#title' => t('Upload picture'), '#size' => 48, '#description' => t('Your virtual face or picture. Maximum dimensions are %dimensions and the maximum size is %size kB.', array('%dimensions' => variable_get('user_picture_dimensions', '85x85'), '%size' => variable_get('user_picture_file_size', '30'))) .' '. variable_get('user_picture_guidelines', ''));
    $form['#validate'][] = 'user_validate_picture';
  }
  $form['#uid'] = $uid;

  return $form;
}

function _user_edit_validate($uid, &$edit) {
  $user = user_load(array('uid' => $uid));
  // Validate the username:
  if (user_access('change own username') || user_access('administer users') || !$user->uid) {
    if ($error = user_validate_name($edit['name'])) {
      form_set_error('name', $error);
    }
    else if (db_result(db_query("SELECT COUNT(*) FROM {users} WHERE uid != %d AND LOWER(name) = LOWER('%s')", $uid, $edit['name'])) > 0) {
      form_set_error('name', t('The name %name is already taken.', array('%name' => $edit['name'])));
    }
    else if (drupal_is_denied('user', $edit['name'])) {
      form_set_error('name', t('The name %name has been denied access.', array('%name' => $edit['name'])));
    }
  }

  // Validate the e-mail address:
  if ($error = user_validate_mail($edit['mail'])) {
    form_set_error('mail', $error);
  }
  else if (db_result(db_query("SELECT COUNT(*) FROM {users} WHERE uid != %d AND LOWER(mail) = LOWER('%s')", $uid, $edit['mail'])) > 0) {
    form_set_error('mail', t('The e-mail address %email is already registered. <a href="@password">Have you forgotten your password?</a>', array('%email' => $edit['mail'], '@password' => url('user/password'))));
  }
  else if (drupal_is_denied('mail', $edit['mail'])) {
    form_set_error('mail', t('The e-mail address %email has been denied access.', array('%email' => $edit['mail'])));
  }
}

function _user_edit_submit($uid, &$edit) {
  $user = user_load(array('uid' => $uid));
  // Delete picture if requested, and if no replacement picture was given.
  if (!empty($edit['picture_delete'])) {
    if ($user->picture && file_exists($user->picture)) {
      file_delete($user->picture);
    }
    $edit['picture'] = '';
  }
  if (isset($edit['roles'])) {
    $edit['roles'] = array_filter($edit['roles']);
  }
}

/**
 * Menu callback; edit a user account or one of their profile categories.
 */
function user_edit($account, $category = 'account') {
  drupal_set_title(check_plain($account->name));
  return drupal_get_form('user_profile_form', $account, $category);
}

/**
 * Form builder; edit a user account or one of their profile categories.
 *
 * @ingroup forms
 * @see user_profile_form_validate()
 * @see user_profile_form_submit().
 * @see user_edit_delete_submit().
 */
function user_profile_form($form_state, $account, $category = 'account') {

  $edit = (empty($form_state['values'])) ? (array)$account : $form_state['values'];

  $form = _user_forms($edit, $account, $category);
  $form['_category'] = array('#type' => 'value', '#value' => $category);
  $form['_account'] = array('#type' => 'value', '#value' => $account);
  $form['submit'] = array('#type' => 'submit', '#value' => t('Save'), '#weight' => 30);
  if (user_access('administer users')) {
    $form['delete'] = array(
      '#type' => 'submit',
      '#value' => t('Delete'),
      '#weight' => 31,
      '#submit' => array('user_edit_delete_submit'),
    );
  }
  $form['#attributes']['enctype'] = 'multipart/form-data';

  return $form;
}

/**
 * Validation function for the user account and profile editing form.
 */
function user_profile_form_validate($form, &$form_state) {
  user_module_invoke('validate', $form_state['values'], $form_state['values']['_account'], $form_state['values']['_category']);
  // Validate input to ensure that non-privileged users can't alter protected data.
  if ((!user_access('administer users') && array_intersect(array_keys($form_state['values']), array('uid', 'init', 'session'))) || (!user_access('administer access control') && isset($form_state['values']['roles']))) {
    watchdog('security', 'Detected malicious attempt to alter protected user fields.', array(), WATCHDOG_WARNING);
    // set this to a value type field
    form_set_error('category', t('Detected malicious attempt to alter protected user fields.'));
  }
}

/**
 * Submit function for the user account and profile editing form.
 */
function user_profile_form_submit($form, &$form_state) {
  $account = $form_state['values']['_account'];
  $category = $form_state['values']['_category'];
  unset($form_state['values']['_account'], $form_state['values']['op'], $form_state['values']['submit'], $form_state['values']['delete'], $form_state['values']['form_token'], $form_state['values']['form_id'], $form_state['values']['_category']);
  user_module_invoke('submit', $form_state['values'], $account, $category);
  user_save($account, $form_state['values'], $category);

  // Clear the page cache because pages can contain usernames and/or profile information:
  cache_clear_all();

  drupal_set_message(t('The changes have been saved.'));
  return;
}

/**
 * Submit function for the 'Delete' button on the user edit form.
 */
function user_edit_delete_submit($form, &$form_state) {
  $destination = '';
  if (isset($_REQUEST['destination'])) {
    $destination = drupal_get_destination();
    unset($_REQUEST['destination']);
  }
  // Note: We redirect from user/uid/edit to user/uid/delete to make the tabs disappear.
  $form_state['redirect'] = array("user/". $form_state['values']['_account']->uid ."/delete", $destination);
}

/**
 * Form builder; confirm form for user deletion.
 *
 * @ingroup forms
 * @see user_confirm_delete_submit().
 */
function user_confirm_delete(&$form_state, $account) {

  $form['_account'] = array('#type' => 'value', '#value' => $account);

  return confirm_form($form,
    t('Are you sure you want to delete the account %name?', array('%name' => $account->name)),
    'user/'. $account->uid,
    t('All submissions made by this user will be attributed to the anonymous account. This action cannot be undone.'),
    t('Delete'), t('Cancel'));
}

/**
 * Submit function for the confirm form for user deletion.
 */
function user_confirm_delete_submit($form, &$form_state) {
  user_delete($form_state['values'], $form_state['values']['_account']->uid);
  if (!isset($_REQUEST['destination'])) {
    $form_state['redirect'] = 'admin/user/user';
  }
}

/**
 * Delete a user.
 *
 * @param $edit An array of submitted form values.
 * @param $uid The user ID of the user to delete.
 */
function user_delete($edit, $uid) {
  $account = user_load(array('uid' => $uid));
  sess_destroy_uid($uid);
  _user_mail_notify('status_deleted', $account);
  db_query('DELETE FROM {users} WHERE uid = %d', $uid);
  db_query('DELETE FROM {users_roles} WHERE uid = %d', $uid);
  db_query('DELETE FROM {authmap} WHERE uid = %d', $uid);
  $variables = array('%name' => $account->name, '%email' => '<'. $account->mail .'>');
  watchdog('user', 'Deleted user: %name %email.', $variables, WATCHDOG_NOTICE);
  drupal_set_message(t('%name has been deleted.', $variables));
  module_invoke_all('user', 'delete', $edit, $account);
}

function user_view($account) {
  drupal_set_title(check_plain($account->name));
  // Retrieve all profile fields and attach to $account->content.
  user_build_content($account);
  /**
   * To theme user profiles, copy modules/user/user_profile.tpl.php
   * to your theme directory, and edit it as instructed in that file's comments.
   */
  return theme('user_profile', $account);
}

/**
 * Builds a structured array representing the profile content.
 *
 * @param $account
 *   A user object.
 *
 * @return
 *   A structured array containing the individual elements of the profile.
 */
function user_build_content(&$account) {
  $edit = NULL;
  user_module_invoke('view', $edit, $account);
  // Allow modules to modify the fully-built profile.
  drupal_alter('profile', $edit, $account);

  return $account->content;
}

/**
 * Implementation of hook_mail().
 */
function user_mail($key, &$message, $params) {
  $language = $message['language'];
  $variables = user_mail_tokens($params['account'], $language);
  $message['subject'] .= _user_mail_text($key .'_subject', $language, $variables);
  $message['body'][] = _user_mail_text($key .'_body', $language, $variables);
}

/**
 * Returns a mail string for a variable name.
 *
 * Used by user_mail() and the settings forms to retrieve strings.
 */
function _user_mail_text($key, $language = NULL, $variables = array()) {
  $langcode = isset($language) ? $language->language : NULL;

  if ($admin_setting = variable_get('user_mail_'. $key, FALSE)) {
    // An admin setting overrides the default string.
    return strtr($admin_setting, $variables);
  }
  else {
    // No override, return default string.
    switch ($key) {
      case 'register_no_approval_required_subject':
        return t('Account details for !username at !site', $variables, $langcode);
      case 'register_no_approval_required_body':
        return t("!username,\n\nThank you for registering at !site. You may now log in to !login_uri using the following username and password:\n\nusername: !username\npassword: !password\n\nYou may also log in by clicking on this link or copying and pasting it in your browser:\n\n!login_url\n\nThis is a one-time login, so it can be used only once.\n\nAfter logging in, you will be redirected to !edit_uri so you can change your password.\n\n\n--  !site team", $variables, $langcode);
      case 'register_admin_created_subject':
        return t('An administrator created an account for you at !site', $variables, $langcode);
      case 'register_admin_created_body':
        return t("!username,\n\nA site administrator at !site has created an account for you. You may now log in to !login_uri using the following username and password:\n\nusername: !username\npassword: !password\n\nYou may also log in by clicking on this link or copying and pasting it in your browser:\n\n!login_url\n\nThis is a one-time login, so it can be used only once.\n\nAfter logging in, you will be redirected to !edit_uri so you can change your password.\n\n\n--  !site team", $variables, $langcode);
      case 'register_pending_approval_subject':
      case 'pending_approval_admin_subject':
        return t('Account details for !username at !site (pending admin approval)', $variables, $langcode);
      case 'register_pending_approval_body':
        return t("!username,\n\nThank you for registering at !site. Your application for an account is currently pending approval. Once it has been approved, you will receive another e-mail containing information about how to log in, set your password, and other details.\n\n\n--  !site team", $variables, $langcode);
      case 'register_pending_approval_admin_body':
        return t("!username has applied for an account.\n\n!edit_uri", $variables, $langcode);
      case 'password_reset_subject':
        return t('Replacement login information for !username at !site', $variables, $langcode);
      case 'password_reset_body':
        return t("!username,\n\nA request to reset the password for your account has been made at !site.\n\nYou may now log in to !uri_brief clicking on this link or copying and pasting it in your browser:\n\n!login_url\n\nThis is a one-time login, so it can be used only once. It expires after one day and nothing will happen if it's not used.\n\nAfter logging in, you will be redirected to !edit_uri so you can change your password.", $variables, $langcode);
      case 'status_activated_subject':
        return t('Account details for !username at !site (approved)', $variables, $langcode);
      case 'status_activated_body':
        return t("!username,\n\nYour account at !site has been activated.\n\nYou may now log in by clicking on this link or copying and pasting it in your browser:\n\n!login_url\n\nThis is a one-time login, so it can be used only once.\n\nAfter logging in, you will be redirected to !edit_uri so you can change your password.\n\nOnce you have set your own password, you will be able to log in to !login_uri in the future using the following username:\n\nusername: !username\n", $variables, $langcode);
      case 'status_blocked_subject':
        return t('Account details for !username at !site (blocked)', $variables, $langcode);
      case 'status_blocked_body':
        return t("!username,\n\nYour account on !site has been blocked.", $variables, $langcode);
      case 'status_deleted_subject':
        return t('Account details for !username at !site (deleted)', $variables, $langcode);
      case 'status_deleted_body':
        return t("!username,\n\nYour account on !site has been deleted.", $variables, $langcode);
    }
  }
}

/*** Administrative features ***********************************************/

function user_admin_check_user() {
  $form['user'] = array('#type' => 'fieldset', '#title' => t('Username'));
  $form['user']['test'] = array('#type' => 'textfield', '#title' => '', '#description' => t('Enter a username to check if it will be denied or allowed.'), '#size' => 30, '#maxlength' => USERNAME_MAX_LENGTH);
  $form['user']['type'] = array('#type' => 'hidden', '#value' => 'user');
  $form['user']['submit'] = array('#type' => 'submit', '#value' => t('Check username'));
  $form['#submit'][] = 'user_admin_access_check_submit';
  $form['#validate'][] = 'user_admin_access_check_validate';
  $form['#theme'] = 'user_admin_access_check';
  return $form;
}

function user_admin_check_mail() {
  $form['mail'] = array('#type' => 'fieldset', '#title' => t('E-mail'));
  $form['mail']['test'] = array('#type' => 'textfield', '#title' => '', '#description' => t('Enter an e-mail address to check if it will be denied or allowed.'), '#size' => 30, '#maxlength' => EMAIL_MAX_LENGTH);
  $form['mail']['type'] = array('#type' => 'hidden', '#value' => 'mail');
  $form['mail']['submit'] = array('#type' => 'submit', '#value' => t('Check e-mail'));
  $form['#submit'][] = 'user_admin_access_check_submit';
  $form['#validate'][] = 'user_admin_access_check_validate';
  $form['#theme'] = 'user_admin_access_check';
  return $form;
}

function user_admin_check_host() {
  $form['host'] = array('#type' => 'fieldset', '#title' => t('Hostname'));
  $form['host']['test'] = array('#type' => 'textfield', '#title' => '', '#description' => t('Enter a hostname or IP address to check if it will be denied or allowed.'), '#size' => 30, '#maxlength' => 64);
  $form['host']['type'] = array('#type' => 'hidden', '#value' => 'host');
  $form['host']['submit'] = array('#type' => 'submit', '#value' => t('Check hostname'));
  $form['#submit'][] = 'user_admin_access_check_submit';
  $form['#validate'][] = 'user_admin_access_check_validate';
  $form['#theme'] = 'user_admin_access_check';
  return $form;
}

/**
 * Menu callback: check an access rule
 */
function user_admin_access_check() {
  $output = drupal_get_form('user_admin_check_user');
  $output .= drupal_get_form('user_admin_check_mail');
  $output .= drupal_get_form('user_admin_check_host');
  return $output;
}

function user_admin_access_check_validate($form, &$form_state) {
  if (empty($form_state['values']['test'])) {
    form_set_error($form_state['values']['type'], t('No value entered. Please enter a test string and try again.'));
  }
}

function user_admin_access_check_submit($form, &$form_state) {
  switch ($form_state['values']['type']) {
    case 'user':
      if (drupal_is_denied('user', $form_state['values']['test'])) {
        drupal_set_message(t('The username %name is not allowed.', array('%name' => $form_state['values']['test'])));
      }
      else {
        drupal_set_message(t('The username %name is allowed.', array('%name' => $form_state['values']['test'])));
      }
      break;
    case 'mail':
      if (drupal_is_denied('mail', $form_state['values']['test'])) {
        drupal_set_message(t('The e-mail address %mail is not allowed.', array('%mail' => $form_state['values']['test'])));
      }
      else {
        drupal_set_message(t('The e-mail address %mail is allowed.', array('%mail' => $form_state['values']['test'])));
      }
      break;
    case 'host':
      if (drupal_is_denied('host', $form_state['values']['test'])) {
        drupal_set_message(t('The hostname %host is not allowed.', array('%host' => $form_state['values']['test'])));
      }
      else {
        drupal_set_message(t('The hostname %host is allowed.', array('%host' => $form_state['values']['test'])));
      }
      break;
    default:
      break;
  }
}

/**
 * Menu callback: add an access rule
 */
function user_admin_access_add($mask = NULL, $type = NULL) {
  if ($edit = $_POST) {
    if (!$edit['mask']) {
      form_set_error('mask', t('You must enter a mask.'));
    }
    else {
      db_query("INSERT INTO {access} (aid, mask, type, status) VALUES ('%s', '%s', '%s', %d)", $aid, $edit['mask'], $edit['type'], $edit['status']);
      $aid = db_last_insert_id('access', 'aid');
      drupal_set_message(t('The access rule has been added.'));
      drupal_goto('admin/user/rules');
    }
  }
  else {
    $edit['mask'] = $mask;
    $edit['type'] = $type;
  }
  return drupal_get_form('user_admin_access_add_form', $edit, t('Add rule'));
}

/**
 * Menu callback: delete an access rule
 */
function user_admin_access_delete_confirm($aid = 0) {
  $access_types = array('user' => t('username'), 'mail' => t('e-mail'), 'host' => t('host'));
  $edit = db_fetch_object(db_query('SELECT aid, type, status, mask FROM {access} WHERE aid = %d', $aid));

  $form = array();
  $form['aid'] = array('#type' => 'hidden', '#value' => $aid);
  $output = confirm_form($form,
                  t('Are you sure you want to delete the @type rule for %rule?', array('@type' => $access_types[$edit->type], '%rule' => $edit->mask)),
                  'admin/user/rules',
                  t('This action cannot be undone.'),
                  t('Delete'),
                  t('Cancel'));
  return $output;
}

function user_admin_access_delete_confirm_submit($form, &$form_state) {
  db_query('DELETE FROM {access} WHERE aid = %d', $form_state['values']['aid']);
  drupal_set_message(t('The access rule has been deleted.'));
  $form_state['redirect'] = 'admin/user/rules';
  return;
}

/**
 * Menu callback: edit an access rule
 */
function user_admin_access_edit($aid = 0) {
  if ($edit = $_POST) {
    if (!$edit['mask']) {
      form_set_error('mask', t('You must enter a mask.'));
    }
    else {
      db_query("UPDATE {access} SET mask = '%s', type = '%s', status = '%s' WHERE aid = %d", $edit['mask'], $edit['type'], $edit['status'], $aid);
      drupal_set_message(t('The access rule has been saved.'));
      drupal_goto('admin/user/rules');
    }
  }
  else {
    $edit = db_fetch_array(db_query('SELECT aid, type, status, mask FROM {access} WHERE aid = %d', $aid));
  }
  return drupal_get_form('user_admin_access_edit_form', $edit, t('Save rule'));
}

function user_admin_access_form(&$form_state, $edit, $submit) {
  $form['status'] = array(
    '#type' => 'radios',
    '#title' => t('Access type'),
    '#default_value' => isset($edit['status']) ? $edit['status'] : array(),
    '#options' => array('1' => t('Allow'), '0' => t('Deny')),
  );
  $type_options = array('user' => t('Username'), 'mail' => t('E-mail'), 'host' => t('Host'));
  $form['type'] = array(
    '#type' => 'radios',
    '#title' => t('Rule type'),
    '#default_value' => (isset($type_options[$edit['type']]) ? $edit['type'] : 'user'),
    '#options' => $type_options,
  );
  $form['mask'] = array(
    '#type' => 'textfield',
    '#title' => t('Mask'),
    '#size' => 30,
    '#maxlength' => 64,
    '#default_value' => $edit['mask'],
    '#description' => '%: '. t('Matches any number of characters, even zero characters') .'.<br />_: '. t('Matches exactly one character.'),
    '#required' => TRUE,
  );
  $form['submit'] = array('#type' => 'submit', '#value' => $submit);

  return $form;
}

/**
 * Menu callback: list all access rules
 */
function user_admin_access() {
  $header = array(array('data' => t('Access type'), 'field' => 'status'), array('data' => t('Rule type'), 'field' => 'type'), array('data' => t('Mask'), 'field' => 'mask'), array('data' => t('Operations'), 'colspan' => 2));
  $result = db_query("SELECT aid, type, status, mask FROM {access}". tablesort_sql($header));
  $access_types = array('user' => t('username'), 'mail' => t('e-mail'), 'host' => t('host'));
  $rows = array();
  while ($rule = db_fetch_object($result)) {
    $rows[] = array($rule->status ? t('allow') : t('deny'), $access_types[$rule->type], $rule->mask, l(t('edit'), 'admin/user/rules/edit/'. $rule->aid), l(t('delete'), 'admin/user/rules/delete/'. $rule->aid));
  }
  if (empty($rows)) {
    $rows[] = array(array('data' => '<em>'. t('There are currently no access rules.') .'</em>', 'colspan' => 5));
  }
  return theme('table', $header, $rows);
}

/**
 * Retrieve an array of roles matching specified conditions.
 *
 * @param $membersonly
 *   Set this to TRUE to exclude the 'anonymous' role.
 * @param $permission
 *   A string containing a permission. If set, only roles containing that permission are returned.
 *
 * @return
 *   An associative array with the role id as the key and the role name as value.
 */
function user_roles($membersonly = 0, $permission = 0) {
  $roles = array();

  if ($permission) {
    $result = db_query("SELECT r.* FROM {role} r INNER JOIN {permission} p ON r.rid = p.rid WHERE p.perm LIKE '%%%s%%' ORDER BY r.name", $permission);
  }
  else {
    $result = db_query('SELECT * FROM {role} ORDER BY name');
  }
  while ($role = db_fetch_object($result)) {
    if (!$membersonly || ($membersonly && $role->rid != DRUPAL_ANONYMOUS_RID)) {
      $roles[$role->rid] = $role->name;
    }
  }
  return $roles;
}

/**
 * Menu callback: administer permissions.
 */
function user_admin_perm($rid = NULL) {
  if (is_numeric($rid)) {
    $result = db_query('SELECT r.rid, p.perm FROM {role} r LEFT JOIN {permission} p ON r.rid = p.rid WHERE r.rid = %d', $rid);
  }
  else {
    $result = db_query('SELECT r.rid, p.perm FROM {role} r LEFT JOIN {permission} p ON r.rid = p.rid ORDER BY name');
  }

  // Compile role array:
  // Add a comma at the end so when searching for a permission, we can
  // always search for "$perm," to make sure we do not confuse
  // permissions that are substrings of each other.
  while ($role = db_fetch_object($result)) {
    $role_permissions[$role->rid] = $role->perm .',';
  }

  if (is_numeric($rid)) {
    $result = db_query('SELECT rid, name FROM {role} r WHERE r.rid = %d ORDER BY name', $rid);
  }
  else {
    $result = db_query('SELECT rid, name FROM {role} ORDER BY name');
  }

  $role_names = array();
  while ($role = db_fetch_object($result)) {
    $role_names[$role->rid] = $role->name;
  }

  // Render role/permission overview:
  $options = array();
  foreach (module_list(FALSE, FALSE, TRUE) as $module) {
    if ($permissions = module_invoke($module, 'perm')) {
      $form['permission'][] = array(
        '#value' => $module,
      );
      asort($permissions);
      foreach ($permissions as $perm) {
        $options[$perm] = '';
        $form['permission'][$perm] = array('#value' => t($perm));
        foreach ($role_names as $rid => $name) {
          // Builds arrays for checked boxes for each role
          if (strpos($role_permissions[$rid], $perm .',') !== FALSE) {
            $status[$rid][] = $perm;
          }
        }
      }
    }
  }

  // Have to build checkboxes here after checkbox arrays are built
  foreach ($role_names as $rid => $name) {
    $form['checkboxes'][$rid] = array('#type' => 'checkboxes', '#options' => $options, '#default_value' => isset($status[$rid]) ? $status[$rid] : array());
    $form['role_names'][$rid] = array('#value' => $name, '#tree' => TRUE);
  }
  $form['submit'] = array('#type' => 'submit', '#value' => t('Save permissions'));

  return $form;
}

function theme_user_admin_perm($form) {
  foreach (element_children($form['permission']) as $key) {
    // Don't take form control structures
    if (is_array($form['permission'][$key])) {
      $row = array();
      // Module name
      if (is_numeric($key)) {
        $row[] = array('data' => t('@module module', array('@module' => drupal_render($form['permission'][$key]))), 'class' => 'module', 'id' => 'module-'. $form['permission'][$key]['#value'], 'colspan' => count($form['role_names']) + 1);
      }
      else {
        $row[] = array('data' => drupal_render($form['permission'][$key]), 'class' => 'permission');
        foreach (element_children($form['checkboxes']) as $rid) {
          if (is_array($form['checkboxes'][$rid])) {
            $row[] = array('data' => drupal_render($form['checkboxes'][$rid][$key]), 'align' => 'center', 'title' => t($key));
          }
        }
      }
      $rows[] = $row;
    }
  }
  $header[] = (t('Permission'));
  foreach (element_children($form['role_names']) as $rid) {
    if (is_array($form['role_names'][$rid])) {
      $header[] = drupal_render($form['role_names'][$rid]);
    }
  }
  $output = theme('table', $header, $rows, array('id' => 'permissions'));
  $output .= drupal_render($form);
  return $output;
}

function user_admin_perm_submit($form, &$form_state) {
  // Save permissions:
  $result = db_query('SELECT * FROM {role}');
  while ($role = db_fetch_object($result)) {
    if (isset($form_state['values'][$role->rid])) {
      // Delete, so if we clear every checkbox we reset that role;
      // otherwise permissions are active and denied everywhere.
      db_query('DELETE FROM {permission} WHERE rid = %d', $role->rid);
      $form_state['values'][$role->rid] = array_filter($form_state['values'][$role->rid]);
      if (count($form_state['values'][$role->rid])) {
        db_query("INSERT INTO {permission} (rid, perm) VALUES (%d, '%s')", $role->rid, implode(', ', array_keys($form_state['values'][$role->rid])));
      }
    }
  }

  drupal_set_message(t('The changes have been saved.'));

  // Clear the cached pages
  cache_clear_all();

}

/**
 * Menu callback: administer roles.
 */
function user_admin_role() {
  $id = arg(4);
  if ($id) {
    if (DRUPAL_ANONYMOUS_RID == $id || DRUPAL_AUTHENTICATED_RID == $id) {
      drupal_goto('admin/user/roles');
    }
    // Display the edit role form.
    $role = db_fetch_object(db_query('SELECT * FROM {role} WHERE rid = %d', $id));
    $form['name'] = array(
      '#type' => 'textfield',
      '#title' => t('Role name'),
      '#default_value' => $role->name,
      '#size' => 30,
      '#required' => TRUE,
      '#maxlength' => 64,
      '#description' => t('The name for this role. Example: "moderator", "editorial board", "site architect".'),
    );
    $form['rid'] = array(
      '#type' => 'value',
      '#value' => $id,
    );
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Save role'),
    );
    $form['delete'] = array(
      '#type' => 'submit',
      '#value' => t('Delete role'),
    );
  }
  else {
    $form['name'] = array(
      '#type' => 'textfield',
      '#size' => 32,
      '#maxlength' => 64,
    );
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Add role'),
    );
    $form['#submit'][] = 'user_admin_role_submit';
    $form['#validate'][] = 'user_admin_role_validate';
  }
  return $form;
}

function user_admin_role_validate($form, &$form_state) {
  if ($form_state['values']['name']) {
    if ($form_state['values']['op'] == t('Save role')) {
      if (db_result(db_query("SELECT COUNT(*) FROM {role} WHERE name = '%s' AND rid != %d", $form_state['values']['name'], $form_state['values']['rid']))) {
        form_set_error('name', t('The role name %name already exists. Please choose another role name.', array('%name' => $form_state['values']['name'])));
      }
    }
    else if ($form_state['values']['op'] == t('Add role')) {
      if (db_result(db_query("SELECT COUNT(*) FROM {role} WHERE name = '%s'", $form_state['values']['name']))) {
        form_set_error('name', t('The role name %name already exists. Please choose another role name.', array('%name' => $form_state['values']['name'])));
      }
    }
  }
  else {
    form_set_error('name', t('You must specify a valid role name.'));
  }
}

function user_admin_role_submit($form, &$form_state) {
  if ($form_state['values']['op'] == t('Save role')) {
    db_query("UPDATE {role} SET name = '%s' WHERE rid = %d", $form_state['values']['name'], $form_state['values']['rid']);
    drupal_set_message(t('The role has been renamed.'));
  }
  else if ($form_state['values']['op'] == t('Delete role')) {
    db_query('DELETE FROM {role} WHERE rid = %d', $form_state['values']['rid']);
    db_query('DELETE FROM {permission} WHERE rid = %d', $form_state['values']['rid']);
    // Update the users who have this role set:
    db_query('DELETE FROM {users_roles} WHERE rid = %d', $form_state['values']['rid']);

    drupal_set_message(t('The role has been deleted.'));
  }
  else if ($form_state['values']['op'] == t('Add role')) {
    db_query("INSERT INTO {role} (name) VALUES ('%s')", $form_state['values']['name']);
    drupal_set_message(t('The role has been added.'));
  }
  $form_state['redirect'] = 'admin/user/roles';
  return;
}

function theme_user_admin_new_role($form) {
  $header = array(t('Name'), array('data' => t('Operations'), 'colspan' => 2));
  foreach (user_roles() as $rid => $name) {
    $edit_permissions = l(t('edit permissions'), 'admin/user/access/'. $rid);
    if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
      $rows[] = array($name, l(t('edit role'), 'admin/user/roles/edit/'. $rid), $edit_permissions);
    }
    else {
      $rows[] = array($name, t('locked'), $edit_permissions);
    }
  }
  $rows[] = array(drupal_render($form['name']), array('data' => drupal_render($form['submit']), 'colspan' => 2));

  $output = drupal_render($form);
  $output .= theme('table', $header, $rows);

  return $output;
}

function user_admin_account() {
  $filter = user_build_filter_query();

  $header = array(
    array(),
    array('data' => t('Username'), 'field' => 'u.name'),
    array('data' => t('Status'), 'field' => 'u.status'),
    t('Roles'),
    array('data' => t('Member for'), 'field' => 'u.created', 'sort' => 'desc'),
    array('data' => t('Last access'), 'field' => 'u.access'),
    t('Operations')
  );

  $sql = 'SELECT DISTINCT u.uid, u.name, u.status, u.created, u.access FROM {users} u LEFT JOIN {users_roles} ur ON u.uid = ur.uid '. $filter['join'] .' WHERE u.uid != 0 '. $filter['where'];
  $sql .= tablesort_sql($header);
  $result = pager_query($sql, 50, 0, NULL, $filter['args']);

  $form['options'] = array(
    '#type' => 'fieldset',
    '#title' => t('Update options'),
    '#prefix' => '<div class="container-inline">',
    '#suffix' => '</div>',
  );
  $options = array();
  foreach (module_invoke_all('user_operations') as $operation => $array) {
    $options[$operation] = $array['label'];
  }
  $form['options']['operation'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#default_value' => 'unblock',
  );
  $form['options']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Update'),
  );

  $destination = drupal_get_destination();

  $status = array(t('blocked'), t('active'));
  $roles = user_roles(1);
  $accounts = array();
  while ($account = db_fetch_object($result)) {
    $accounts[$account->uid] = '';
    $form['name'][$account->uid] = array('#value' => theme('username', $account));
    $form['status'][$account->uid] =  array('#value' => $status[$account->status]);
    $users_roles = array();
    $roles_result = db_query('SELECT rid FROM {users_roles} WHERE uid = %d', $account->uid);
    while ($user_role = db_fetch_object($roles_result)) {
      $users_roles[] = $roles[$user_role->rid];
    }
    asort($users_roles);
    $form['roles'][$account->uid][0] = array('#value' => theme('item_list', $users_roles));
    $form['member_for'][$account->uid] = array('#value' => format_interval(time() - $account->created));
    $form['last_access'][$account->uid] =  array('#value' => $account->access ? t('@time ago', array('@time' => format_interval(time() - $account->access))) : t('never'));
    $form['operations'][$account->uid] = array('#value' => l(t('edit'), "user/$account->uid/edit", array('query' => $destination)));
  }
  $form['accounts'] = array(
    '#type' => 'checkboxes',
    '#options' => $accounts
  );
  $form['pager'] = array('#value' => theme('pager', NULL, 50, 0));

  return $form;
}

/**
 * Theme user administration overview.
 */
function theme_user_admin_account($form) {
  // Overview table:
  $header = array(
    theme('table_select_header_cell'),
    array('data' => t('Username'), 'field' => 'u.name'),
    array('data' => t('Status'), 'field' => 'u.status'),
    t('Roles'),
    array('data' => t('Member for'), 'field' => 'u.created', 'sort' => 'desc'),
    array('data' => t('Last access'), 'field' => 'u.access'),
    t('Operations')
  );

  $output = drupal_render($form['options']);
  if (isset($form['name']) && is_array($form['name'])) {
    foreach (element_children($form['name']) as $key) {
      $rows[] = array(
        drupal_render($form['accounts'][$key]),
        drupal_render($form['name'][$key]),
        drupal_render($form['status'][$key]),
        drupal_render($form['roles'][$key]),
        drupal_render($form['member_for'][$key]),
        drupal_render($form['last_access'][$key]),
        drupal_render($form['operations'][$key]),
      );
    }
  }
  else  {
    $rows[] = array(array('data' => t('No users available.'), 'colspan' => '7'));
  }

  $output .= theme('table', $header, $rows);
  if ($form['pager']['#value']) {
    $output .= drupal_render($form['pager']);
  }

  $output .= drupal_render($form);

  return $output;
}

/**
 * Submit the user administration update form.
 */
function user_admin_account_submit($form, &$form_state) {
  $operations = module_invoke_all('user_operations', $form_state);
  $operation = $operations[$form_state['values']['operation']];
  // Filter out unchecked accounts.
  $accounts = array_filter($form_state['values']['accounts']);
  if ($function = $operation['callback']) {
    // Add in callback arguments if present.
    if (isset($operation['callback arguments'])) {
      $args = array_merge(array($accounts), $operation['callback arguments']);
    }
    else {
      $args = array($accounts);
    }
    call_user_func_array($function, $args);

    drupal_set_message(t('The update has been performed.'));
  }
}

function user_admin_account_validate($form, &$form_state) {
  $form_state['values']['accounts'] = array_filter($form_state['values']['accounts']);
  if (count($form_state['values']['accounts']) == 0) {
    form_set_error('', t('No users selected.'));
  }
}

/**
 * Implementation of hook_user_operations().
 */
function user_user_operations($form_state = array()) {
  $operations = array(
    'unblock' => array(
      'label' => t('Unblock the selected users'),
      'callback' => 'user_user_operations_unblock',
    ),
    'block' => array(
      'label' => t('Block the selected users'),
      'callback' => 'user_user_operations_block',
    ),
    'delete' => array(
      'label' => t('Delete the selected users'),
    ),
  );

  if (user_access('administer access control')) {
    $roles = user_roles(1);
    unset($roles[DRUPAL_AUTHENTICATED_RID]);  // Can't edit authenticated role.

    $add_roles = array();
    foreach ($roles as $key => $value) {
      $add_roles['add_role-'. $key] = $value;
    }

    $remove_roles = array();
    foreach ($roles as $key => $value) {
      $remove_roles['remove_role-'. $key] = $value;
    }

    if (count($roles)) {
      $role_operations = array(
        t('Add a role to the selected users') => array(
          'label' => $add_roles,
        ),
        t('Remove a role from the selected users') => array(
          'label' => $remove_roles,
        ),
      );

      $operations += $role_operations;
    }
  }

  // If the form has been posted, we need to insert the proper data for role editing if necessary.
  if (!empty($form_state['submitted'])) {
    $operation_rid = explode('-', $form_state['values']['operation']);
    $operation = $operation_rid[0];
    if ($operation == 'add_role' || $operation == 'remove_role') {
      $rid = $operation_rid[1];
      if (user_access('administer access control')) {
        $operations[$form_state['values']['operation']] = array(
          'callback' => 'user_multiple_role_edit',
          'callback arguments' => array($operation, $rid),
        );
      }
      else {
        watchdog('security', 'Detected malicious attempt to alter protected user fields.', array(), WATCHDOG_WARNING);
        return;
      }
    }
  }

  return $operations;
}

/**
 * Callback function for admin mass unblocking users.
 */
function user_user_operations_unblock($accounts) {
  foreach ($accounts as $uid) {
    $account = user_load(array('uid' => (int)$uid));
    // Skip unblocking user if they are already unblocked.
    if ($account !== FALSE && $account->status == 0) {
      user_save($account, array('status' => 1));
    }
  }
}

/**
 * Callback function for admin mass blocking users.
 */
function user_user_operations_block($accounts) {
  foreach ($accounts as $uid) {
    $account = user_load(array('uid' => (int)$uid));
    // Skip blocking user if they are already blocked.
    if ($account !== FALSE && $account->status == 1) {
      user_save($account, array('status' => 0));
    }
  }
}

/**
 * Callback function for admin mass adding/deleting a user role.
 */
function user_multiple_role_edit($accounts, $operation, $rid) {
  // The role name is not necessary as user_save() will reload the user
  // object, but some modules' hook_user() may look at this first.
  $role_name = db_result(db_query('SELECT name FROM {role} WHERE rid = %d', $rid));

  switch ($operation) {
    case 'add_role':
      foreach ($accounts as $uid) {
        $account = user_load(array('uid' => (int)$uid));
        // Skip adding the role to the user if they already have it.
        if ($account !== FALSE && !isset($account->roles[$rid])) {
          $roles = $account->roles + array($rid => $role_name);
          user_save($account, array('roles' => $roles));
        }
      }
      break;
    case 'remove_role':
      foreach ($accounts as $uid) {
        $account = user_load(array('uid' => (int)$uid));
        // Skip removing the role from the user if they already don't have it.
        if ($account !== FALSE && isset($account->roles[$rid])) {
          $roles = array_diff($account->roles, array($rid => $role_name));
          user_save($account, array('roles' => $roles));
        }
      }
      break;
  }
}

function user_multiple_delete_confirm(&$form_state) {
  $edit = $form_state['post'];

  $form['accounts'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
  // array_filter returns only elements with TRUE values
  foreach (array_filter($edit['accounts']) as $uid => $value) {
    $user = db_result(db_query('SELECT name FROM {users} WHERE uid = %d', $uid));
    $form['accounts'][$uid] = array('#type' => 'hidden', '#value' => $uid, '#prefix' => '<li>', '#suffix' => check_plain($user) ."</li>\n");
  }
  $form['operation'] = array('#type' => 'hidden', '#value' => 'delete');

  return confirm_form($form,
                      t('Are you sure you want to delete these users?'),
                      'admin/user/user', t('This action cannot be undone.'),
                      t('Delete all'), t('Cancel'));
}

function user_multiple_delete_confirm_submit($form, &$form_state) {
  if ($form_state['values']['confirm']) {
    foreach ($form_state['values']['accounts'] as $uid => $value) {
      user_delete($form_state['values'], $uid);
    }
    drupal_set_message(t('The users have been deleted.'));
  }
  $form_state['redirect'] = 'admin/user/user';
  return;
}

function user_admin_settings() {
  // User registration settings.
  $form['registration'] = array('#type' => 'fieldset', '#title' => t('User registration settings'));
  $form['registration']['user_register'] = array('#type' => 'radios', '#title' => t('Public registrations'), '#default_value' => variable_get('user_register', 1), '#options' => array(t('Only site administrators can create new user accounts.'), t('Visitors can create accounts and no administrator approval is required.'), t('Visitors can create accounts but administrator approval is required.')));
  $form['registration']['user_email_verification'] = array('#type' => 'checkbox', '#title' => t('Require e-mail verification when a visitor creates an account'), '#default_value' => variable_get('user_email_verification', TRUE), '#description' => t('If this box is checked, new users will be required to validate their e-mail address prior to logging into to the site, and will be assigned a system-generated password. With it unchecked, users will be logged in immediately upon registering, and may select their own passwords during registration.'));
  $form['registration']['user_registration_help'] = array('#type' => 'textarea', '#title' => t('User registration guidelines'), '#default_value' => variable_get('user_registration_help', ''), '#description' => t("This text is displayed at the top of the user registration form. It's useful for helping or instructing your users."));

  // User e-mail settings.
  $form['email'] = array(
    '#type' => 'fieldset',
    '#title' => t('User e-mail settings'),
    '#description' => t('Drupal sends emails whenever new users register on your site. Here you can customize the contents of these messages. You can also set notifications for user account changes, which is useful when your site requires administrator approval for new accounts.'),
  );
  // These email tokens are shared for all settings, so just define
  // the list once to help ensure they stay in sync.
  $email_token_help = t('Available variables are:') .' !username, !site, !password, !uri, !uri_brief, !mailto, !date, !login_uri, !edit_uri, !login_url.';

  $form['email']['admin_created'] = array(
    '#type' => 'fieldset',
    '#title' => t('Welcome, new user created by administrator'),
    '#collapsible' => TRUE,
    '#collapsed' => (variable_get('user_register', 1) != 0),
    '#description' => t('Customize the welcome e-mail message that is sent to new member accounts created by an administrator.') .' '. $email_token_help,
  );
  $form['email']['admin_created']['user_mail_register_admin_created_subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Subject'),
    '#default_value' => _user_mail_text('register_admin_created_subject'),
    '#maxlength' => 180,
  );
  $form['email']['admin_created']['user_mail_register_admin_created_body'] = array(
    '#type' => 'textarea',
    '#title' => t('Body'),
    '#default_value' => _user_mail_text('register_admin_created_body'),
    '#rows' => 15,
  );

  $form['email']['no_approval_required'] = array(
    '#type' => 'fieldset',
    '#title' => t('Welcome, no approval required'),
    '#collapsible' => TRUE,
    '#collapsed' => (variable_get('user_register', 1) != 1),
    '#description' => t('Customize the welcome e-mail message that is sent to new members upon registering when no administrator approval is required.') .' '. $email_token_help
  );
  $form['email']['no_approval_required']['user_mail_register_no_approval_required_subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Subject'),
    '#default_value' => _user_mail_text('register_no_approval_required_subject'),
    '#maxlength' => 180,
  );
  $form['email']['no_approval_required']['user_mail_register_no_approval_required_body'] = array(
    '#type' => 'textarea',
    '#title' => t('Body'),
    '#default_value' => _user_mail_text('register_no_approval_required_body'),
    '#rows' => 15,
  );

  $form['email']['pending_approval'] = array(
    '#type' => 'fieldset',
    '#title' => t('Welcome, awaiting administrator approval'),
    '#collapsible' => TRUE,
    '#collapsed' => (variable_get('user_register', 1) != 2),
    '#description' => t('Customize the welcome message which is sent to new members that are awaiting approval.') .' '. $email_token_help,
  );
  $form['email']['pending_approval']['user_mail_register_pending_approval_subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Subject'),
    '#default_value' => _user_mail_text('register_pending_approval_subject'),
    '#maxlength' => 180,
  );
  $form['email']['pending_approval']['user_mail_register_pending_approval_body'] = array(
    '#type' => 'textarea',
    '#title' => t('Body'),
    '#default_value' => _user_mail_text('register_pending_approval_body'),
    '#rows' => 8,
  );

  $form['email']['password_reset'] = array(
    '#type' => 'fieldset',
    '#title' => t('Password recovery email'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#description' => t('Customize the e-mail message sent to users that request a new password.') .' '. $email_token_help,
  );
  $form['email']['password_reset']['user_mail_password_reset_subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Subject'),
    '#default_value' => _user_mail_text('password_reset_subject'),
    '#maxlength' => 180,
  );
  $form['email']['password_reset']['user_mail_password_reset_body'] = array(
    '#type' => 'textarea',
    '#title' => t('Body'),
    '#default_value' => _user_mail_text('password_reset_body'),
    '#rows' => 12,
  );

  $form['email']['activated'] = array(
    '#type' => 'fieldset',
    '#title' => t('Account activation email'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#description' => t('Configure if an e-mail message should be sent to users when their accounts are activated, and if so, what the subject and body should be. This is particularly useful if your site requires administrator approval for new account requests.') .' '. $email_token_help,
  );
  $form['email']['activated']['user_mail_status_activated_notify'] = array(
    '#type' => 'checkbox',
    '#title' => t('Notify user when account is activated.'),
    '#default_value' => variable_get('user_mail_status_activated_notify', TRUE),
  );
  $form['email']['activated']['user_mail_status_activated_subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Subject'),
    '#default_value' => _user_mail_text('status_activated_subject'),
    '#maxlength' => 180,
  );
  $form['email']['activated']['user_mail_status_activated_body'] = array(
    '#type' => 'textarea',
    '#title' => t('Body'),
    '#default_value' => _user_mail_text('status_activated_body'),
    '#rows' => 15,
  );

  $form['email']['blocked'] = array(
    '#type' => 'fieldset',
    '#title' => t('Account blocked email'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#description' => t('Configure if an e-mail message should be sent to users when their accounts are blocked, and if so, what the subject and body should be.') .' '. $email_token_help,
  );
  $form['email']['blocked']['user_mail_status_blocked_notify'] = array(
    '#type' => 'checkbox',
    '#title' => t('Notify user when account is blocked.'),
    '#default_value' => variable_get('user_mail_status_blocked_notify', FALSE),
  );
  $form['email']['blocked']['user_mail_status_blocked_subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Subject'),
    '#default_value' => _user_mail_text('status_blocked_subject'),
    '#maxlength' => 180,
  );
  $form['email']['blocked']['user_mail_status_blocked_body'] = array(
    '#type' => 'textarea',
    '#title' => t('Body'),
    '#default_value' => _user_mail_text('status_blocked_body'),
    '#rows' => 3,
  );

  $form['email']['deleted'] = array(
    '#type' => 'fieldset',
    '#title' => t('Account deleted email'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#description' => t('Configure if an e-mail message should be sent to users when their accounts are deleted, and if so, what the subject and body should be.') .' '. $email_token_help,
  );
  $form['email']['deleted']['user_mail_status_deleted_notify'] = array(
    '#type' => 'checkbox',
    '#title' => t('Notify user when account is deleted.'),
    '#default_value' => variable_get('user_mail_status_deleted_notify', FALSE),
  );
  $form['email']['deleted']['user_mail_status_deleted_subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Subject'),
    '#default_value' => _user_mail_text('status_deleted_subject'),
    '#maxlength' => 180,
  );
  $form['email']['deleted']['user_mail_status_deleted_body'] = array(
    '#type' => 'textarea',
    '#title' => t('Body'),
    '#default_value' => _user_mail_text('status_deleted_body'),
    '#rows' => 3,
  );

  // User signatures.
  $form['signatures'] = array(
    '#type' => 'fieldset',
    '#title' => t('Signatures'),
  );
  $form['signatures']['user_signatures'] = array(
    '#type' => 'radios',
    '#title' => t('Signature support'),
    '#default_value' => variable_get('user_signatures', 0),
    '#options' => array(t('Disabled'), t('Enabled')),
  );

  // If picture support is enabled, check whether the picture directory exists:
  if (variable_get('user_pictures', 0)) {
    $picture_path = file_create_path(variable_get('user_picture_path', 'pictures'));
    file_check_directory($picture_path, 1, 'user_picture_path');
  }

  $form['pictures'] = array(
    '#type' => 'fieldset',
    '#title' => t('Pictures'),
  );
  $picture_support = variable_get('user_pictures', 0);
  $form['pictures']['user_pictures'] = array(
    '#type' => 'radios',
    '#title' => t('Picture support'),
    '#default_value' => $picture_support,
    '#options' => array(t('Disabled'), t('Enabled')),
    '#prefix' => '<div class="user-admin-picture-radios">',
    '#suffix' => '</div>',
  );
  drupal_add_js(drupal_get_path('module', 'user') .'/user.js');
  // If JS is enabled, and the radio is defaulting to off, hide all
  // the settings on page load via .css using the js-hide class so
  // that there's no flicker.
  $css_class = 'user-admin-picture-settings';
  if (!$picture_support) {
    $css_class .= ' js-hide';
  }
  $form['pictures']['settings'] = array(
    '#prefix' => '<div class="'. $css_class .'">',
    '#suffix' => '</div>',
  );
  $form['pictures']['settings']['user_picture_path'] = array(
    '#type' => 'textfield',
    '#title' => t('Picture image path'),
    '#default_value' => variable_get('user_picture_path', 'pictures'),
    '#size' => 30,
    '#maxlength' => 255,
    '#description' => t('Subdirectory in the directory %dir where pictures will be stored.', array('%dir' => file_directory_path() .'/')),
  );
  $form['pictures']['settings']['user_picture_default'] = array(
    '#type' => 'textfield',
    '#title' => t('Default picture'),
    '#default_value' => variable_get('user_picture_default', ''),
    '#size' => 30,
    '#maxlength' => 255,
    '#description' => t('URL of picture to display for users with no custom picture selected. Leave blank for none.'),
  );
  $form['pictures']['settings']['user_picture_dimensions'] = array(
    '#type' => 'textfield',
    '#title' => t('Picture maximum dimensions'),
    '#default_value' => variable_get('user_picture_dimensions', '85x85'),
    '#size' => 15,
    '#maxlength' => 10,
    '#description' => t('Maximum dimensions for pictures, in pixels.'),
  );
  $form['pictures']['settings']['user_picture_file_size'] = array(
    '#type' => 'textfield',
    '#title' => t('Picture maximum file size'),
    '#default_value' => variable_get('user_picture_file_size', '30'),
    '#size' => 15,
    '#maxlength' => 10,
    '#description' => t('Maximum file size for pictures, in kB.'),
  );
  $form['pictures']['settings']['user_picture_guidelines'] = array(
    '#type' => 'textarea',
    '#title' => t('Picture guidelines'),
    '#default_value' => variable_get('user_picture_guidelines', ''),
    '#description' => t("This text is displayed at the picture upload form in addition to the default guidelines. It's useful for helping or instructing your users."),
  );

  return system_settings_form($form);
}

function user_admin($callback_arg = '') {
  $op = isset($_POST['op']) ? $_POST['op'] : $callback_arg;

  switch ($op) {
    case 'search':
    case t('Search'):
      $keys = isset($_POST['keys']) ? $_POST['keys'] : NULL;
      $output = drupal_get_form('search_form', url('admin/user/search'), $keys, 'user') . search_data($keys, 'user');
      break;
    case t('Create new account'):
    case 'create':
      $output = drupal_get_form('user_register');
      break;
    default:
      if (!empty($_POST['accounts']) && isset($_POST['operation']) && ($_POST['operation'] == 'delete')) {
        $output = drupal_get_form('user_multiple_delete_confirm');
      }
      else {
        $output = drupal_get_form('user_filter_form');
        $output .= drupal_get_form('user_admin_account');
      }
  }
  return $output;
}

/**
 * Implementation of hook_help().
 */
function user_help($path, $arg) {
  global $user;

  switch ($path) {
    case 'admin/help#user':
      $output = '<p>'. t('The user module allows users to register, login, and log out. Users benefit from being able to sign on because it associates content they create with their account and allows various permissions to be set for their roles. The user module supports user roles which can setup fine grained permissions allowing each role to do only what the administrator wants them to. Each user is assigned to one or more roles. By default there are two roles <em>anonymous</em> - a user who has not logged in, and <em>authenticated</em> a user who has signed up and who has been authorized.') .'</p>';
      $output .= '<p>'. t('Users can use their own name or handle and can fine tune some personal configuration settings through their individual my account page. Registered users need to authenticate by supplying either a local username and password, or a remote username and password such as DelphiForums ID, or one from a Drupal powered website. A visitor accessing your website is assigned an unique ID, the so-called session ID, which is stored in a cookie. For security\'s sake, the cookie does not contain personal information but acts as a key to retrieve the information stored on your server.') .'</p>';
      $output .= '<p>'. t('For more information please read the configuration and customization handbook <a href="@user">User page</a>.', array('@user' => 'http://drupal.org/handbook/modules/user/')) .'</p>';
      return $output;
    case 'admin/user/user':
      return '<p>'. t('Drupal allows users to register, login, log out, maintain user profiles, etc. Users of the site may not use their own names to post content until they have signed up for a user account.') .'</p>';
    case 'admin/user/user/create':
    case 'admin/user/user/account/create':
      return '<p>'. t('This web page allows the administrators to register new users by hand. Note that you cannot have a user where either the e-mail address or the username match another user in the system.') .'</p>';
    case 'admin/user/rules':
      return '<p>'. t('Set up username and e-mail address access rules for new <em>and</em> existing accounts (currently logged in accounts will not be logged out). If a username or e-mail address for an account matches any deny rule, but not an allow rule, then the account will not be allowed to be created or to log in. A host rule is effective for every page view, not just registrations.') .'</p>';
    case 'admin/user/access':
      return '<p>'. t('Permissions let you control what users can do on your site. Each user role (defined on the <a href="@role">user roles page</a>) has its own set of permissions. For example, you could give users classified as "Administrators" permission to "administer nodes" but deny this power to ordinary, "authenticated" users. You can use permissions to reveal new features to privileged users (those with subscriptions, for example). Permissions also allow trusted users to share the administrative burden of running a busy site.', array('@role' => url('admin/user/roles'))) .'</p>';
    case 'admin/user/roles':
      return t('<p>Roles allow you to fine tune the security and administration of Drupal. A role defines a group of users that have certain privileges as defined in <a href="@permissions">user permissions</a>. Examples of roles include: anonymous user, authenticated user, moderator, administrator and so on. In this area you will define the <em>role names</em> of the various roles. To delete a role choose "edit".</p><p>By default, Drupal comes with two user roles:</p>
      <ul>
      <li>Anonymous user: this role is used for users that don\'t have a user account or that are not authenticated.</li>
      <li>Authenticated user: this role is automatically granted to all logged in users.</li>
      </ul>', array('@permissions' => url('admin/user/access')));
    case 'admin/user/search':
      return '<p>'. t('Enter a simple pattern ("*" may be used as a wildcard match) to search for a username or e-mail address. For example, one may search for "br" and Drupal might return "brian", "brad", and "brenda@example.com".') .'</p>';
  }
}

/**
 * Retrieve a list of all user setting/information categories and sort them by weight.
 */
function _user_categories($account) {
  $categories = array();

  foreach (module_list() as $module) {
    if ($data = module_invoke($module, 'user', 'categories', NULL, $account, '')) {
      $categories = array_merge($data, $categories);
    }
  }

  usort($categories, '_user_sort');

  return $categories;
}

function _user_sort($a, $b) {
  $a = (array)$a + array('weight' => 0, 'title' => '');
  $b = (array)$b + array('weight' => 0, 'title' => '');
  return $a['weight'] < $b['weight'] ? -1 : ($a['weight'] > $b['weight'] ? 1 : ($a['title'] < $b['title'] ? -1 : 1));
}

/**
 * Retrieve a list of all form elements for the specified category.
 */
function _user_forms(&$edit, $account, $category, $hook = 'form') {
  $groups = array();
  foreach (module_list() as $module) {
    if ($data = module_invoke($module, 'user', $hook, $edit, $account, $category)) {
      $groups = array_merge_recursive($data, $groups);
    }
  }
  uasort($groups, '_user_sort');

  return empty($groups) ? FALSE : $groups;
}

/**
 * Retrieve a pipe delimited string of autocomplete suggestions for existing users
 */
function user_autocomplete($string = '') {
  $matches = array();
  if ($string) {
    $result = db_query_range("SELECT name FROM {users} WHERE LOWER(name) LIKE LOWER('%s%%')", $string, 0, 10);
    while ($user = db_fetch_object($result)) {
      $matches[$user->name] = check_plain($user->name);
    }
  }

  drupal_json($matches);
}

/**
 * List user administration filters that can be applied.
 */
function user_filters() {
  // Regular filters
  $filters = array();
  $roles = user_roles(1);
  unset($roles[DRUPAL_AUTHENTICATED_RID]); // Don't list authorized role.
  if (count($roles)) {
    $filters['role'] = array(
      'title' => t('role'),
      'where' => "ur.rid = %d",
      'options' => $roles,
      'join' => '',
    );
  }

  $options = array();
  $t_module = t('module');
  foreach (module_list() as $module) {
    if ($permissions = module_invoke($module, 'perm')) {
      asort($permissions);
      foreach ($permissions as $permission) {
        $options["$module $t_module"][$permission] = t($permission);
      }
    }
  }
  ksort($options);
  $filters['permission'] = array(
    'title' => t('permission'),
    'join' => 'LEFT JOIN {permission} p ON ur.rid = p.rid',
    'where' => " ((p.perm IS NOT NULL AND p.perm LIKE '%%%s%%') OR u.uid = 1) ",
    'options' => $options,
  );

  $filters['status'] = array(
    'title' => t('status'),
    'where' => 'u.status = %d',
    'join' => '',
    'options' => array(1 => t('active'), 0 => t('blocked')),
  );
  return $filters;
}

/**
 * Build query for user administration filters based on session.
 */
function user_build_filter_query() {
  $filters = user_filters();

  // Build query
  $where = $args = $join = array();
  foreach ($_SESSION['user_overview_filter'] as $filter) {
    list($key, $value) = $filter;
    // This checks to see if this permission filter is an enabled permission for the authenticated role.
    // If so, then all users would be listed, and we can skip adding it to the filter query.
    if ($key == 'permission') {
      $account = new stdClass();
      $account->uid = 'user_filter';
      $account->roles = array(DRUPAL_AUTHENTICATED_RID => 1);
      if (user_access($value, $account)) {
        continue;
      }
    }
    $where[] = $filters[$key]['where'];
    $args[] = $value;
    $join[] = $filters[$key]['join'];
  }
  $where = !empty($where) ? 'AND '. implode(' AND ', $where) : '';
  $join = !empty($join) ? ' '. implode(' ', array_unique($join)) : '';

  return array('where' => $where,
           'join' => $join,
           'args' => $args,
         );
}

/**
 * Return form for user administration filters.
 */
function user_filter_form() {
  $session = &$_SESSION['user_overview_filter'];
  $session = is_array($session) ? $session : array();
  $filters = user_filters();

  $i = 0;
  $form['filters'] = array('#type' => 'fieldset',
                       '#title' => t('Show only users where'),
                       '#theme' => 'user_filters',
                     );
  foreach ($session as $filter) {
    list($type, $value) = $filter;
    $string = ($i++ ? '<em>and</em> where <strong>%a</strong> is <strong>%b</strong>' : '<strong>%a</strong> is <strong>%b</strong>');
    // Merge an array of arrays into one if necessary.
    $options = $type == 'permission' ? call_user_func_array('array_merge', $filters[$type]['options']) : $filters[$type]['options'];
    $form['filters']['current'][] = array('#value' => t($string, array('%a' => $filters[$type]['title'] , '%b' => $options[$value])));
  }

  foreach ($filters as $key => $filter) {
    $names[$key] = $filter['title'];
    $form['filters']['status'][$key] = array('#type' => 'select',
                                         '#options' => $filter['options'],
                                       );
  }

  $form['filters']['filter'] = array('#type' => 'radios',
                                 '#options' => $names,
                               );
  $form['filters']['buttons']['submit'] = array('#type' => 'submit',
                                            '#value' => (count($session) ? t('Refine') : t('Filter'))
                                          );
  if (count($session)) {
    $form['filters']['buttons']['undo'] = array('#type' => 'submit',
                                            '#value' => t('Undo')
                                          );
    $form['filters']['buttons']['reset'] = array('#type' => 'submit',
                                             '#value' => t('Reset')
                                           );
  }

  return $form;
}

/**
 * Theme user administration filter form.
 */
function theme_user_filter_form($form) {
  $output = '<div id="user-admin-filter">';
  $output .= drupal_render($form['filters']);
  $output .= '</div>';
  $output .= drupal_render($form);
  return $output;
}

/**
 * Theme user administration filter selector.
 */
function theme_user_filters($form) {
  $output = '<ul class="clear-block">';
  if (!empty($form['current'])) {
    foreach (element_children($form['current']) as $key) {
      $output .= '<li>'. drupal_render($form['current'][$key]) .'</li>';
    }
  }

  $output .= '<li><dl class="multiselect">'. (!empty($form['current']) ? '<dt><em>'. t('and') .'</em> '. t('where') .'</dt>' : '') .'<dd class="a">';
  foreach (element_children($form['filter']) as $key) {
    $output .= drupal_render($form['filter'][$key]);
  }
  $output .= '</dd>';

  $output .= '<dt>'. t('is') .'</dt><dd class="b">';

  foreach (element_children($form['status']) as $key) {
    $output .= drupal_render($form['status'][$key]);
  }
  $output .= '</dd>';

  $output .= '</dl>';
  $output .= '<div class="container-inline" id="user-admin-buttons">'. drupal_render($form['buttons']) .'</div>';
  $output .= '</li></ul>';

  return $output;
}

/**
 * Process result from user administration filter form.
 */
function user_filter_form_submit($form, &$form_state) {
  $op = $form_state['values']['op'];
  $filters = user_filters();
  switch ($op) {
    case t('Filter'): case t('Refine'):
      if (isset($form_state['values']['filter'])) {
        $filter = $form_state['values']['filter'];
        // Merge an array of arrays into one if necessary.
        $options = $filter == 'permission' ? call_user_func_array('array_merge', $filters[$filter]['options']) : $filters[$filter]['options'];
        if (isset($options[$form_state['values'][$filter]])) {
          $_SESSION['user_overview_filter'][] = array($filter, $form_state['values'][$filter]);
        }
      }
      break;
    case t('Undo'):
      array_pop($_SESSION['user_overview_filter']);
      break;
    case t('Reset'):
      $_SESSION['user_overview_filter'] = array();
      break;
    case t('Update'):
      return;
  }

  $form_state['redirect'] = 'admin/user/user';
  return;
}


function user_forms() {
  $forms['user_admin_access_add_form']['callback'] = 'user_admin_access_form';
  $forms['user_admin_access_edit_form']['callback'] = 'user_admin_access_form';
  $forms['user_admin_new_role']['callback'] = 'user_admin_role';
  return $forms;
}

/**
 * Implementation of hook_comment().
 */
function user_comment(&$comment, $op) {
  // Validate signature.
  if ($op == 'view') {
    if (variable_get('user_signatures', 0) && !empty($comment->signature)) {
      $comment->signature = check_markup($comment->signature, $comment->format);
    }
    else {
      $comment->signature = '';
    }
  }
}

/**
 * Theme output of user signature.
 *
 * @ingroup themeable
 */
function theme_user_signature($signature) {
  $output = '';
  if ($signature) {
    $output .= '<div class="clear">';
    $output .= '<div>—</div>';
    $output .= $signature;
    $output .= '</div>';
  }

  return $output;
}

/**
 * Return an array of token to value mappings for user e-mail messages.
 *
 * @param $account
 *  The user object of the account being notified.  Must contain at
 *  least the fields 'uid', 'name', and 'mail'.
 * @param $language
 *  Language object to generate the tokens with.
 * @return
 *  Array of mappings from token names to values (for use with strtr()).
 */
function user_mail_tokens($account, $language) {
  global $base_url;
  $tokens = array(
    '!username' => $account->name,
    '!site' => variable_get('site_name', 'Drupal'),
    '!login_url' => user_pass_reset_url($account),
    '!uri' => $base_url,
    '!uri_brief' => substr($base_url, strlen('http://')),
    '!mailto' => $account->mail,
    '!date' => format_date(time(), 'medium', '', NULL, $language->language),
    '!login_uri' => url('user', array('absolute' => TRUE, 'language' => $language)),
    '!edit_uri' => url('user/'. $account->uid .'/edit', array('absolute' => TRUE, 'language' => $language)),
  );
  if (!empty($account->password)) {
    $tokens['!password'] = $account->password;
  }
  return $tokens;
}

/**
 * Get the language object preferred by the user. This user preference can
 * be set on the user account editing page, and is only available if there
 * are more than one languages enabled on the site. If the user did not
 * choose a preferred language, or is the anonymous user, the $default
 * value, or if it is not set, the site default language will be returned.
 *
 * @param $account
 *   User account to look up language for.
 * @param $default
 *   Optional default language object to return if the account
 *   has no valid language.
 */
function user_preferred_language($account, $default = NULL) {
  $language_list = language_list();
  if ($account->language && isset($language_list[$account->language])) {
    return $language_list[$account->language];
  }
  else {
    return $default ? $default : language_default();
  }
}

/**
 * Conditionally create and send a notification email when a certain
 * operation happens on the given user account.
 *
 * @see user_mail_tokens()
 * @see drupal_mail()
 *
 * @param $op
 *  The operation being performed on the account.  Possible values:
 *  'register_admin_created': Welcome message for user created by the admin
 *  'register_no_approval_required': Welcome message when user self-registers
 *  'register_pending_approval': Welcome message, user pending admin approval
 *  'password_reset': Password recovery request
 *  'status_activated': Account activated
 *  'status_blocked': Account blocked
 *  'status_deleted': Account deleted
 *
 * @param $account
 *  The user object of the account being notified.  Must contain at
 *  least the fields 'uid', 'name', and 'mail'.
 * @param $language
 *  Optional language to use for the notification, overriding account language.
 * @return
 *  The return value from drupal_mail_send(), if ends up being called.
 */
function _user_mail_notify($op, $account, $language = NULL) {
  // By default, we always notify except for deleted and blocked.
  $default_notify = ($op != 'status_deleted' && $op != 'status_blocked');
  $notify = variable_get('user_mail_'. $op .'_notify', $default_notify);
  if ($notify) {
    $params['account'] = $account;
    $language = $language ? $language : user_preferred_language($account);
    $mail = drupal_mail('user', $op, $account->mail, $language, $params);
    if ($op == 'register_pending_approval') {
      // If a user registered requiring admin approval, notify the admin, too.
      // We use the site default language for this.
      drupal_mail('user', 'register_pending_approval_admin', variable_get('site_mail', ini_get('sendmail_from')), language_default(), $params);
    }
  }
  return empty($mail) ? NULL : $mail['result'];
}

/**
 * Add javascript and string translations for dynamic password validation (strength and confirmation checking).
 *
 * This is an internal function that makes it easier to manage the translation
 * strings that need to be passed to the javascript code.
 */
function _user_password_dynamic_validation() {
  static $complete = FALSE;
  global $user;
  // Only need to do once per page.
  if (!$complete) {
    drupal_add_js(drupal_get_path('module', 'user') .'/user.js', 'module');

    drupal_add_js(array(
      'password' => array(
        'strengthTitle' => t('Password strength:'),
        'lowStrength' => t('Low'),
        'mediumStrength' => t('Medium'),
        'highStrength' => t('High'),
        'tooShort' => t('It is recommended to choose a password that contains at least six characters. It should include numbers, punctuation, and both upper and lowercase letters.'),
        'needsMoreVariation' => t('The password does not include enough variation to be secure. Try:'),
        'addLetters' => t('Adding both upper and lowercase letters.'),
        'addNumbers' => t('Adding numbers.'),
        'addPunctuation' => t('Adding punctuation.'),
        'sameAsUsername' => t('It is recommended to choose a password different from the username.'),
        'confirmSuccess' => t('Yes'),
        'confirmFailure' => t('No'),
        'confirmTitle' => t('Passwords match:'),
        'username' => (isset($user->name) ? $user->name : ''))),
      'setting');
    $complete = TRUE;
  }
}



/**
 * Implementation of hook_hook_info().
 */
function user_hook_info() {
  return array(
    'user' => array(
      'user' => array(
        'insert' => array(
          'runs when' => t('When a user account has been created'),
        ),
        'update' => array(
          'runs when' => t('When a user account has been updated'),
        ),
        'delete' => array(
          'runs when' => t('When a user account has been deleted')
        ),
        'login' => array(
          'runs when' => t('When a user has logged in')
        ),
        'logout' => array(
          'runs when' => t('When a user has logged out')
        ),
        'view' => array(
          'runs when' => t("When a user's account information is displayed")
        ),
      ),
    ),
  );
}

/**
 * Implementation of hook_action_info().
 */
function user_action_info() {
  return array(
    'user_block_user_action' => array(
      'description' => t('Block current user'),
      'type' => 'user',
      'configurable' => FALSE,
      'hooks' => array(
        'nodeapi' => array('presave', 'delete', 'insert', 'update', 'view'),
        'comment' => array('view', 'insert', 'update', 'delete'),
        'user' => array('logout'),
        ),
      ),
    'user_block_ip_action' => array(
      'description' => t('Ban IP address of current user'),
      'type' => 'user',
      'configurable' => FALSE,
      'hooks' => array(
        'nodeapi' => array('presave', 'delete', 'insert', 'update', 'view'),
        'comment' => array('view', 'insert', 'update', 'delete'),
        'user' => array('logout'),
      )
    )
  );
}

/**
 * Implementation of a Drupal action.
 * Blocks the current user.
 */
function user_block_user_action(&$object, $context = array()) {
  if (isset($object->uid)) {
    $uid = $object->uid;
  }
  elseif (isset($context['uid'])) {
    $uid = $context['uid'];
  }
  else {
    global $user;
    $uid = $user->uid;
  }
  db_query("UPDATE {users} SET status = 0 WHERE uid = %d", $uid);
  sess_destroy_uid($uid);
  watchdog('action', 'Blocked user %name.', array('%name' => check_plain($user->name)));
}

/**
 * Implementation of a Drupal action.
 * Adds an access rule that blocks the user's IP address.
 */
function user_block_ip_action() {
  db_query("INSERT INTO {access} (mask, type, status) VALUES ('%s', '%s', %d)", $_SERVER['REMOTE_ADDR'], 'host', 0);
  watchdog('action', 'Banned IP address %ip', array('%ip' => $_SERVER['REMOTE_ADDR']));
}