summaryrefslogtreecommitdiff
path: root/modules/user.module
blob: d9c5caa53abc47380e21062cb9582c647e2c12f4 (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
<?php
// $Id$

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

/**
 * 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);
    }
  }
}

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

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

/**
 * 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();

  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 (db_num_rows($result)) {
    $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.
 *
 * @param $account
 *   The $user object for the user to modify.
 *
 * @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 ($account->uid) {
    user_module_invoke('update', $array, $account, $category);

    $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 (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) {
      db_query('DELETE FROM {sessions} WHERE uid = %d', $account->uid);
    }

    // Refresh user object
    $user = user_load(array('uid' => $account->uid));
  }
  else {
    $array['created'] = time();
    $array['uid'] = db_next_id('{users}_uid');

    // 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 'uid':        case 'mode':     case 'sort':
        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);

    // Reload user roles (delete just to be safe).
    db_query('DELETE FROM {users_roles} WHERE uid = %d', $array['uid']);
    foreach ((array)$array['roles'] as $rid) {
      db_query('INSERT INTO {users_roles} (uid, rid) VALUES (%d, %d)', $array['uid'], $rid);
    }

    // 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);

    // 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 (ereg('  ', $name)) 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}]/u',   // Replacement characters
                   $name)) {
    return t('The username contains an illegal character.');
  }
  if (ereg('@', $name) && !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) > 56) return t('The username %name is too long: it must be less than 56 characters.', array('%name' => theme('placeholder', $name)));
}

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' => theme('placeholder', $mail)));
  }
}

function user_validate_picture($file, &$edit, $user) {
  global $form_values;
  // Initialize the picture:
  $form_values['picture'] = $user->picture;

  // Check that uploaded file is an image, with a maximum file size
  // and maximum height/width.
  $info = image_get_info($file->filepath);
  list($maxwidth, $maxheight) = explode('x', variable_get('user_picture_dimensions', '85x85'));

  if (!$info || !$info['extension']) {
    form_set_error('picture_upload', t('The uploaded file was not an image.'));
  }
  else if (image_get_toolkit()) {
    image_scale($file->filepath, $file->filepath, $maxwidth, $maxheight);
  }
  else if (filesize($file->filepath) > (variable_get('user_picture_file_size', '30') * 1000)) {
    form_set_error('picture_upload', t('The uploaded image is too large; the maximum file size is %size kB.', array('%size' => variable_get('user_picture_file_size', '30'))));
  }
  else if ($info['width'] > $maxwidth || $info['height'] > $maxheight) {
    form_set_error('picture_upload', t('The uploaded image is too large; the maximum dimensions are %dimensions pixels.', array('%dimensions' => variable_get('user_picture_dimensions', '85x85'))));
  }

  if (!form_get_errors()) {
    if ($file = file_save_upload('picture_upload', variable_get('user_picture_path', 'pictures') .'/picture-'. $user->uid . '.' . $info['extension'], 1)) {
      $form_values['picture'] = $file->filepath;
    }
    else {
      form_set_error('picture_upload', t("Failed to upload the picture image; the %directory directory doesn't exist.", array('%directory' => '<em>'. variable_get('user_picture_path', 'pictures') .'</em>')));
    }
  }
}

/**
 * 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) {
  $allow = db_fetch_object(db_query("SELECT * FROM {users} WHERE status = 1 AND name = LOWER('%s')", $name));
  $deny  = db_fetch_object(db_query("SELECT * FROM {users} WHERE status = 0 AND name = LOWER('%s')", $name));

  return $deny && !$allow;
}

/**
 * Send an e-mail message.
 */
function user_mail($mail, $subject, $message, $header) {
  if (variable_get('smtp_library', '') && file_exists(variable_get('smtp_library', ''))) {
   include_once './' . variable_get('smtp_library', '');
    return user_mail_wrapper($mail, $subject, $message, $header);
  }
  else {
    /*
    ** Note: if you are having problems with sending mail, or mails look wrong
    ** when they are received you may have to modify the str_replace to suit
    ** your systems.
    **  - \r\n will work under dos and windows.
    **  - \n will work for linux, unix and BSDs.
    **  - \r will work for macs.
    **
    ** According to RFC 2646, it's quite rude to not wrap your e-mails:
    **
    ** "The Text/Plain media type is the lowest common denominator of
    ** Internet e-mail, with lines of no more than 997 characters (by
    ** convention usually no more than 80), and where the CRLF sequence
    ** represents a line break [MIME-IMT]."
    **
    ** CRLF === \r\n
    **
    ** http://www.rfc-editor.org/rfc/rfc2646.txt
    **
    */
    return mail(
      $mail,
      mime_header_encode($subject),
      str_replace("\r", '', $message),
      "MIME-Version: 1.0\nContent-Type: text/plain; charset=UTF-8; format=flowed\nContent-transfer-encoding: 8Bit\n" . $header
    );
  }
}

function user_fields() {
  static $fields;

  if (!$fields) {
    $result = db_query('SELECT * FROM {users} WHERE uid = 1');
    if (db_num_rows($result)) {
      $fields = array_keys(db_fetch_array($result));
    }
    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) {
  switch ($op) {
    case 'name':
      if (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);
        $result = pager_query("SELECT * 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));
        }
        return $find;
      }
  }
}

/**
 * Implementation of hook_user().
 */
function user_user($type, &$edit, &$user, $category = NULL) {
  if ($type == 'view') {
    $items[] = array('title' => t('Member for'),
      'value' => format_interval(time() - $user->created),
      'class' => 'member',
    );

    return array(t('History') => $items);
  }
  if ($type == 'form' && $category == 'account') {
    return user_edit_form(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));
  }
}

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

  if ($op == 'list') {
     $blocks[0]['info'] = t('User login');
     $blocks[1]['info'] = t('Navigation');
     $blocks[2]['info'] = t('Who\'s new');
     $blocks[3]['info'] = t('Who\'s online');

     return $blocks;
  }
  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 == 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)))) {
          $form['#action'] = url($_GET['q'], drupal_get_destination());
          $form['#id'] = 'user-login-form';
          $form['name'] = array('#type' => 'textfield',
            '#title' => t('Username'),
            '#maxlength' => 60,
            '#size' => 15,
            '#required' => TRUE,
          );
          $form['pass'] = array('#type' => 'password',
            '#title' => t('Password'),
            '#size' => 15,
            '#required' => TRUE,
          );
          $form['submit'] = array('#type' => 'submit',
            '#value' => t('Log in'),
          );

          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));

          $output .= drupal_get_form('user_login_block', $form, 'user_login');

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

      case 1:
        if ($menu = theme('menu_tree')) {
           $block['subject'] = $user->uid ? $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, 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 with activity in the past defined period.
          $time_period = variable_get('user_block_seconds_online', 2700);

          // Perform database queries to gather online user lists.
          $guests = db_fetch_object(db_query('SELECT COUNT(sid) AS count FROM {sessions} WHERE timestamp >= %d AND uid = 0', time() - $time_period));
          $users = db_query('SELECT uid, name, access FROM {users} WHERE access >= %d AND uid != 0 ORDER BY access DESC', time() - $time_period);
          $total_users = db_num_rows($users);

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

          // Display a list of currently online users.
          $max_users = variable_get('user_block_max_list_count', 10);
          $items = array();

          while ($max_users-- && $account = db_fetch_object($users)) {
            $items[] = $account;
          }

          $output .= theme('user_list', $items, t('Online users'));

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

function theme_user_picture($account) {
  if (variable_get('user_pictures', 0)) {
    if ($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', 'Anonymous')));
      $picture = theme('image', $picture, $alt, $alt, '', false);
      if (!empty($account->uid) && user_access('access user profiles')) {
        $picture = l($picture, "user/$account->uid", array('title' => t('View user profile.')), NULL, NULL, FALSE, TRUE);
      }

      return "<div class=\"picture\">$picture</div>";
    }
  }
}

/**
 * Theme a user page
 * @param $account the user object
 * @param $fields a multidimensional array for the fields, in the form of array (
 *   'category1' => array(item_array1, item_array2), 'category2' => array(item_array3,
 *    .. etc.). Item arrays are formatted as array(array('title' => 'item title',
 * 'value' => 'item value', 'class' => 'class-name'), ... etc.). Module names are incorporated
 * into the CSS class.
 *
 * @ingroup themeable
 */
function theme_user_profile($account, $fields) {
  $output = '<div class="profile">';
  $output .= theme('user_picture', $account);
  foreach ($fields as $category => $items) {
    if (strlen($category) > 0) {
      $output .= '<h2 class="title">'. $category .'</h2>';
    }
    $output .= '<dl>';
    foreach ($items as $item) {
      if (isset($item['title'])) {
        $output .= '<dt class="'. $item['class'] .'">'. $item['title'] .'</dt>';
      }
      $output .= '<dd class="'. $item['class'] .'">'. $item['value'] .'</dd>';
    }
    $output .= '</dl>';
  }
  $output .= '</div>';

  return $output;
}

/**
 * Make a list of users.
 * @param $items an array with user objects. Should contain at least the name and uid
 *
 * @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);
}

/**
 * Implementation of hook_menu().
 */
function user_menu($may_cache) {
  global $user;

  $items = array();

  $admin_access = user_access('administer users');
  $access_access = user_access('administer access control');
  $view_access = user_access('access user profiles');

  if ($may_cache) {
    $items[] = array('path' => 'user', 'title' => t('user account'),
      'callback' => 'user_login', 'access' => TRUE, 'type' => MENU_CALLBACK);

    $items[] = array('path' => 'user/autocomplete', 'title' => t('user autocomplete'),
      'callback' => 'user_autocomplete', 'access' => $view_access, 'type' => MENU_CALLBACK);

    // Registration and login pages.
    $items[] = array('path' => 'user/login', 'title' => t('log in'),
      'callback' => 'user_login', 'type' => MENU_DEFAULT_LOCAL_TASK);
    $items[] = array('path' => 'user/register', 'title' => t('register'),
      'callback' => 'user_register', 'access' => $user->uid == 0 && variable_get('user_register', 1), 'type' => MENU_LOCAL_TASK);
    $items[] = array('path' => 'user/password', 'title' => t('request new password'),
      'callback' => 'user_pass', 'access' => $user->uid == 0, 'type' => MENU_LOCAL_TASK);
    $items[] = array('path' => 'user/reset', 'title' => t('reset password'),
      'callback' => 'user_pass_reset', 'access' => TRUE, 'type' => MENU_CALLBACK);
    $items[] = array('path' => 'user/help', 'title' => t('help'),
      'callback' => 'user_help_page', 'type' => MENU_CALLBACK);

    // Admin user pages
    $items[] = array('path' => 'admin/user', 'title' => t('users'),
      'callback' => 'user_admin', 'access' => $admin_access);
    $items[] = array('path' => 'admin/user/list', 'title' => t('list'),
      'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);
    $items[] = array('path' => 'admin/user/create', 'title' => t('add user'),
      'callback' => 'user_admin', 'access' => $admin_access,
      'type' => MENU_LOCAL_TASK);
    $items[] = array('path' => 'admin/settings/user', 'title' => t('users'),
      'callback' => 'user_configure');

    // Admin access pages
    $items[] = array('path' => 'admin/access', 'title' => t('access control'),
      'callback' => 'user_admin_perm', 'access' => $access_access);
    $items[] = array('path' => 'admin/access/permissions', 'title' => t('permissions'),
      'callback' => 'user_admin_perm', 'access' => $access_access,
      'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);
    $items[] = array('path' => 'admin/access/roles', 'title' => t('roles'),
      'callback' => 'user_admin_role', 'access' => $access_access,
      'type' => MENU_LOCAL_TASK);
    $items[] = array('path' => 'admin/access/roles/edit', 'title' => t('edit role'),
      'callback' => 'user_admin_role', 'access' => $access_access,
      'type' => MENU_CALLBACK);
    $items[] = array('path' => 'admin/access/rules', 'title' => t('access rules'),
      'callback' => 'user_admin_access', 'access' => $access_access,
      'type' => MENU_LOCAL_TASK, 'weight' => 10);
    $items[] = array('path' => 'admin/access/rules/list', 'title' => t('list'),
      'access' => $access_access, 'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);
    $items[] = array('path' => 'admin/access/rules/add', 'title' => t('add rule'),
      'callback' => 'user_admin_access_add', 'access' => $access_access,
      'type' => MENU_LOCAL_TASK);
    $items[] = array('path' => 'admin/access/rules/check', 'title' => t('check rules'),
      'callback' => 'user_admin_access_check', 'access' => $access_access,
      'type' => MENU_LOCAL_TASK);
    $items[] = array('path' => 'admin/access/rules/edit', 'title' => t('edit rule'),
      'callback' => 'user_admin_access_edit', 'access' => $access_access,
      'type' => MENU_CALLBACK);
    $items[] = array('path' => 'admin/access/rules/delete', 'title' => t('delete rule'),
      'callback' => 'user_admin_access_delete', 'access' => $access_access,
      'type' => MENU_CALLBACK);

    if (module_exist('search')) {
      $items[] = array('path' => 'admin/user/search', 'title' => t('search'),
        'callback' => 'user_admin', 'access' => $admin_access,
        'type' => MENU_LOCAL_TASK);
    }

    // Your personal page
    if ($user->uid) {
      $items[] = array('path' => 'user/'. $user->uid, 'title' => t('my account'),
        'callback' => 'user_view', 'callback arguments' => array(arg(1)), 'access' => TRUE,
        'type' => MENU_DYNAMIC_ITEM);
    }

    $items[] = array('path' => 'logout', 'title' => t('log out'),
      'access' => $user->uid != 0,
      'callback' => 'user_logout',
      'weight' => 10);
  }
  else {
    if (arg(0) == 'user' && is_numeric(arg(1))) {
      $account = user_load(array('uid' => arg(1)));

      if ($user !== FALSE) {
        // Always let a user view their own account
        $view_access |= $user->uid == arg(1);
        // Only admins can view blocked accounts
        $view_access &= $account->status || $admin_access; 

        $items[] = array('path' => 'user/'. arg(1), 'title' => t('user'),
          'type' => MENU_CALLBACK, 'callback' => 'user_view',
          'callback arguments' => array(arg(1)), 'access' => $view_access);        

        $items[] = array('path' => 'user/'. arg(1) .'/view', 'title' => t('view'),
          'access' => $view_access, 'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);

        $items[] = array('path' => 'user/'. arg(1) .'/edit', 'title' => t('edit'),
          'callback' => 'user_edit', 'access' => $admin_access || $user->uid == arg(1),
          'type' => MENU_LOCAL_TASK);
        $items[] = array('path' => 'user/'. arg(1) .'/delete', 'title' => t('delete'),
          'callback' => 'user_edit', 'access' => $admin_access,
          'type' => MENU_CALLBACK);

        if (arg(2) == 'edit') {
          if (($categories = _user_categories()) && (count($categories) > 1)) {
            foreach ($categories as $key => $category) {
              $items[] = array(
                'path' => 'user/'. arg(1) .'/edit/'. $category['name'],
                'title' => $category['title'],
                'type' => $category['name'] == 'account' ? MENU_DEFAULT_LOCAL_TASK : MENU_LOCAL_TASK,
                'weight' => $category['weight'],
                'access' => ($admin_access || $user->uid == arg(1)));
            }
          }
        }
      }
    }
  }

  return $items;
}

/**
 * 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);
  if (db_num_rows($result) > 0) {
    while ($authmap = db_fetch_object($result)) {
      $authmaps[$authmap->module] = $authmap->authname;
    }
    return $authmaps;
  }
  else {
    return 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_auth_help_links() {
  $links = array();
  foreach (module_list() as $module) {
    if (module_hook($module, 'auth')) {
      $links[] = l(module_invoke($module, 'info', 'name'), "user/help#$module");
    }
  }
  return $links;
}

/*** User features *********************************************************/



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

  // 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>$msg</p>");
  }
  $form['name'] = array('#type' => 'textfield',
    '#title' => t('Username'),
    '#size' => 30,
    '#maxlength' => 60,
    '#required' => TRUE,
    '#attributes' => array('tabindex' => '1'),
  );
  if (variable_get('drupal_authentication_service', FALSE) && count(user_auth_help_links()) > 0) {
    $form['name']['#description'] = t('Enter your %s username, or an ID from one of our affiliates: %a.', array('%s' => variable_get('site_name', 'local'), '%a' => implode(', ', user_auth_help_links())));
  }
  else {
    $form['name']['#description'] = t('Enter your %s username.', array('%s' => variable_get('site_name', 'local')));
  }
  $form['pass'] = array('#type' => 'password',
    '#title' => t('Password'),
    '#description' => t('Enter the password that accompanies your username.'),
    '#required' => TRUE,
    '#attributes' => array('tabindex' => '2'),
  );
  $form['submit'] = array('#type' => 'submit', '#value' => t('Log in'), '#weight' => 2, '#attributes' => array('tabindex' => '3'));
  return drupal_get_form('user_login', $form);
}

function user_login_validate($form_id, $form_values) {
  if ($form_values['name']) {
    if (user_is_blocked($form_values['name'])) {
      // blocked in user administration
      form_set_error('login', t('The username %name has been blocked.', array('%name' => theme('placeholder', $form_values['name']))));
    }
    else if (drupal_is_denied('user', $form_values['name'])) {
      // denied by access controls
      form_set_error('login', t('The name %name is a reserved username.', array('%name' => theme('placeholder', $form_values['name']))));
    }
    else if ($form_values['pass']) {
      $user = user_authenticate($form_values['name'], trim($form_values['pass']));

      if (!$user->uid) {
        form_set_error('login', t('Sorry. Unrecognized username or password.') .' '. l(t('Have you forgotten your password?'), 'user/password'));
        watchdog('user', t('Login attempt failed for %user.', array('%user' => theme('placeholder', $form_values['name']))));
      }
    }
  }
}

function user_login_submit($form_id, $form_values) {
  global $user;
  if ($user->uid) {
    watchdog('user', t('Session opened for %name.', array('%name' => theme('placeholder', $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_values, $user);

    $old_session_id = session_id();
    session_regenerate_id();
    db_query("UPDATE {sessions} SET sid = '%s' WHERE sid = '%s'", session_id(), $old_session_id);

  }
}

function user_authenticate($name, $pass) {
  global $user;

  // Try to log in the user locally. Don't set $user unless successful.
  if ($account = user_load(array('name' => $name, 'pass' => $pass, 'status' => 1))) {
    $user = $account;
  };

  // Strip name and server from ID:
  if ($server = strrchr($name, '@')) {
    $name = substr($name, 0, strlen($name) - strlen($server));
    $server = substr($server, 1);
  }

  // When possible, determine corresponding external auth source. Invoke
  // source, and log in user if successful:
  if (!$user->uid && $server && $result = user_get_authmaps("$name@$server")) {
    if (module_invoke(key($result), 'auth', $name, $pass, $server)) {
      $user = user_external_load("$name@$server");
      watchdog('user', t('External load by %user using module %module.', array('%user' => theme('placeholder', $name .'@'. $server), '%module' => theme('placeholder', key($result)))));
    }
    else {
      $error = t('Invalid password for %s.', array('%s' => theme('placeholder', $name .'@'. $server)));
    }
  }

  // Try each external authentication source in series. Register user if
  // successful.
  else if (!$user->uid && $server) {
    foreach (module_list() as $module) {
      if (module_hook($module, 'auth')) {
        if (module_invoke($module, 'auth', $name, $pass, $server)) {
          if (variable_get('user_register', 1) == 1) {
            $account = user_load(array('name' => "$name@$server"));
            if (!$account->uid) { // Register this new user.
              $user = user_save('', array('name' => "$name@$server", 'pass' => user_password(), 'init' => "$name@$server", 'status' => 1, "authname_$module" => "$name@$server"));
              watchdog('user', t('New external user: %user using module %module.', array('%user' => theme('placeholder', $name .'@'. $server), '%module' => theme('placeholder', $module))), WATCHDOG_NOTICE, l(t('edit'), 'user/'. $user->uid .'/edit'));
              break;
            }
          }
        }
      }
    }
  }
  return $user;
}

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

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

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

  // We have to use $GLOBALS to unset a global variable:
  $user = user_load(array('uid' => 0));

  drupal_goto();
}

function user_pass() {

  // Display form:
  $form['name'] = array('#type' => 'textfield',
    '#title' => t('Username'),
    '#size' => 30,
    '#maxlength' => 60,
  );
  $form['mail'] = array('#type' => 'textfield',
    '#title' => t('E-mail address'),
    '#size' => 30,
    '#maxlength' => 64,
  );
  $form['submit'] = array('#type' => 'submit',
    '#value' => t('E-mail new password'),
    '#weight' => 2,
  );
  return drupal_get_form('user_pass', $form);
}

function user_pass_validate() {
  global $form_values;

  $name = $form_values['name'];
  $mail = $form_values['mail'];
  if ($name && !($form_values['account'] = user_load(array('name' => $name, 'status' => 1)))) {
    form_set_error('name', t('Sorry. The username %name is not recognized.', array('%name' => theme('placeholder', $name))));
  }
  else if ($mail && !($form_values['account'] = user_load(array('mail' => $mail, 'status' => 1)))) {
    form_set_error('mail', t('Sorry. The e-mail address %email is not recognized.', array('%email' => theme('placeholder', $mail))));
  }
  else if (!$mail && !$name) {
    form_set_error('password', t('You must provide either a username or e-mail address.'));
  }
}

function user_pass_submit($form_id, $form_values) {
  global $base_url;

  $account = $form_values['account'];
  $from = variable_get('site_mail', ini_get('sendmail_from'));

  // Mail one time login URL and instructions.
  $variables = 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()), '%login_uri' => url('user', NULL, NULL, TRUE), '%edit_uri' => url('user/'. $account->uid .'/edit', NULL, NULL, TRUE));
  $subject = _user_mail_text('pass_subject', $variables);
  $body = _user_mail_text('pass_body', $variables);
  $headers = "From: $from\nReply-to: $from\nX-Mailer: Drupal\nReturn-path: $from\nErrors-to: $from";
  $mail_success = user_mail($account->mail, $subject, $body, $headers);

  if ($mail_success) {
    watchdog('user', t('Password reset instructions mailed to %name at %email.', array('%name' => '<em>'. $account->name .'</em>', '%email' => '<em>'. $account->mail .'</em>')));
    drupal_set_message(t('Further instructions have been sent to your e-mail address.'));
  }
  else {
    watchdog('user', t('Error mailing password reset instructions to %name at %email.', array('%name' => theme('placeholder', $account->name), '%email' => theme('placeholder', $account->mail))), WATCHDOG_ERROR);
    drupal_set_message(t('Unable to send mail. Please contact the site admin.'));
  }
  return 'user';
}

function theme_user_pass($form) {
  $output = '<p>'. t('Enter your username <strong><em>or</em></strong> your e-mail address.') .'</p>';
  $output .= form_render($form);
  return $output;
}

/**
 * Menu callback; process one time login link and redirects to the user page on success.
 */
function user_pass_reset($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(variable_get('site_frontpage', 'node'));
  }
  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', t('User %name used one-time login link at time %timestamp.', array('%name' => "<em>$account->name</em>", '%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.
          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' => theme('placeholder',$account->name), '%expiration_date' => format_date($timestamp + $timeout))));
          $form['help'] = array('#value' => t('<p>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 drupal_get_form('user_pass_reset', $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), NULL, NULL, 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);
  }

  // Display the registration form.
  if (!$admin) {
    $form['user_registration_help'] = array('#type' => 'markup', '#value' => variable_get('user_registration_help', ''));
  }
  $affiliates = user_auth_help_links();
  if (!$admin && count($affiliates) > 0) {
    $affiliates = implode(', ', $affiliates);
    $form['affiliates'] = array('#type' => 'markup', '#value' => '<p>'. t('Note: if you have an account with one of our affiliates (%s), you may <a href="%login_uri">login now</a> instead of registering.', array('%s' => $affiliates, '%login_uri' => url('user'))) .'</p>');
  }
  $form['name'] = array('#type' => 'textfield',
    '#title' => t('Username'),
    '#size' => 30,
    '#maxlength' => 60,
    '#description' => t('Your full name or your preferred username; only letters, numbers and spaces are allowed.'),
    '#required' => TRUE);
  $form['mail'] = array('#type' => 'textfield',
    '#title' => t('E-mail address'),
    '#size' => 30,
    '#maxlength' => 64,
    '#description' => t('A password and instructions will be sent to this e-mail address, so make sure it is accurate.'),
    '#required' => TRUE,
  );
  if ($admin) {
    $form['pass'] = array('#type' => 'password',
      '#title' => t('Password'),
      '#size' => 30,
      '#description' => t('Provide a password for the new account.'),
      '#required' => TRUE,
    );
    $form['notify'] = array(
     '#type' => 'checkbox', 
     '#title' => t('Notify user of new account')
    );
  }
  $extra = _user_forms($null, $null, $null, 'register');
  
  // Only display form_group around default fields if there are other groups.
  if ($extra) {
    $form['account'] = array('#type' => 'fieldset', '#title' => t('Account information'));
    $form['account']['name'] = $form['name'];
    $form['account']['mail'] = $form['mail'];
    $form['account']['pass'] = $form['pass'];
    $form['account']['notify'] = $form['notify'];
    unset($form['name'], $form['mail'], $form['pass'], $form['notify']);
    $form = array_merge($form, $extra);
  }
  $form['submit'] = array('#type' => 'submit', '#value' => t('Create new account'), '#weight' => 30);

  return drupal_get_form('user_register', $form);
}

function user_register_validate($form_id, $form_values) {
  user_module_invoke('validate', $form_values, $form_values, 'account');
}

function user_register_submit($form_id, $form_values) {
  global $base_url;

  $admin = user_access('administer users');

  $mail = $form_values['mail'];
  $name = $form_values['name'];
  $pass = $admin ? $form_values['pass'] : user_password();
  $notify = $form_values['notify'];
  $from = variable_get('site_mail', ini_get('sendmail_from'));

  if (!$admin && array_intersect(array_keys($form_values), array('uid', 'roles', 'init', 'session', 'status'))) {
    watchdog('security', t('Detected malicious attempt to alter protected user fields.'), WATCHDOG_WARNING);
    return 'user/register';
  }

  $account = user_save('', array_merge($form_values, array('pass' => $pass, 'init' => $mail, 'status' => ($admin || variable_get('user_register', 1) == 1))));
  watchdog('user', t('New user: %name %email.', array('%name' => theme('placeholder', $name), '%email' => theme('placeholder', '<'. $mail .'>'))), WATCHDOG_NOTICE, l(t('edit'), 'user/'. $account->uid .'/edit'));

  $variables = array('%username' => $name, '%site' => variable_get('site_name', 'drupal'), '%password' => $pass, '%uri' => $base_url, '%uri_brief' => substr($base_url, strlen('http://')), '%mailto' => $mail, '%date' => format_date(time()), '%login_uri' => url('user', NULL, NULL, TRUE), '%edit_uri' => url('user/'. $account->uid .'/edit', NULL, NULL, TRUE), '%login_url' => user_pass_reset_url($account));

  // The first user may login immediately, and receives a customized welcome e-mail.
  if ($account->uid == 1) {
    user_mail($mail, t('Drupal user account details for %s', array('%s' => $name)), strtr(t("%username,\n\nYou may now login to %uri using the following username and password:\n\n  username: %username\n  password: %password\n\n%edit_uri\n\n--drupal"), $variables), "From: $from\nReply-to: $from\nX-Mailer: Drupal\nReturn-path: $from\nErrors-to: $from");
    drupal_set_message(t('<p>Welcome to Drupal. You are user #1, which gives you full and immediate access.  All future registrants will receive their passwords via e-mail, so please make sure your website e-mail address is set properly under the general settings on the <a href="%settings">settings page</a>.</p><p> Your password is <strong>%pass</strong>. You may change your password below.</p>', array('%pass' => $pass, '%settings' => url('admin/settings'))));
    user_authenticate($account->name, trim($pass));

    // Set the installed schema version of the system module to the most recent version.
    include_once './includes/install.inc';
    drupal_set_installed_schema_version('system', max(drupal_get_schema_versions('system')));

    return 'user/1/edit';
  }
  else {
    if ($admin && !$notify) {
      drupal_set_message(t('Created a new user account. No e-mail has been sent.'));

      return 'admin/user';
    }
    else if ($account->status || $notify) {
      // Create new user account, no administrator approval required.
      $subject = $notify ? _user_mail_text('admin_subject', $variables) : _user_mail_text('welcome_subject', $variables);
      $body = $notify ? _user_mail_text('admin_body', $variables) : _user_mail_text('welcome_body', $variables);

      user_mail($mail, $subject, $body, "From: $from\nReply-to: $from\nX-Mailer: Drupal\nReturn-path: $from\nErrors-to: $from");
      
      if ($notify) {
        drupal_set_message(t('Password and further instructions have been e-mailed to the new user %user.', array('%user' => theme('placeholder', $name))));
        return 'admin/user';
      }
      else {
        drupal_set_message(t('Your password and further instructions have been sent to your e-mail address.'));
        return '';
      }
    }
    else {
      // Create new user account, administrator approval required.
      $subject = _user_mail_text('approval_subject', $variables);
      $body = _user_mail_text('approval_body', $variables);

      user_mail($mail, $subject, $body, "From: $from\nReply-to: $from\nX-Mailer: Drupal\nReturn-path: $from\nErrors-to: $from");
      user_mail(variable_get('site_mail', ini_get('sendmail_from')), $subject, t("%u has applied for an account.\n\n%uri", array('%u' => $account->name, '%uri' => url("user/$account->uid/edit", NULL, NULL, TRUE))), "From: $from\nReply-to: $from\nX-Mailer: Drupal\nReturn-path: $from\nErrors-to: $from");
      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($uid, $edit) {
  // Account information:
  $form['account'] = array('#type' => 'fieldset',
    '#title' => t('Account information'),
  );
  if (user_access('change own username') || user_access('administer users')) {
    $form['account']['name'] = array('#type' => 'textfield',
      '#title' => t('Username'),
      '#default_value' => $edit['name'],
      '#maxlength' => 60,
      '#description' => t('Your full name or your preferred username: only letters, numbers and spaces are allowed.'),
      '#required' => TRUE,
    );
  }
  $form['account']['mail'] = array('#type' => 'textfield',
    '#title' => t('E-mail address'),
    '#default_value' => $edit['mail'],
    '#maxlength' => 64,
    '#description' => t('Insert 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,
  );
  $form['account']['pass'] = array('#type' => 'password_confirm',
    '#title' => t('Password'),
    '#description' => t('To change the current user password, enter the new password in both fields.'),
  );
  if (user_access('administer users')) {
    $form['account']['status'] = array('#type' => 'radios', '#title' => t('Status'), '#default_value' => $edit['status'], '#options' => array(t('Blocked'), t('Active')));
  }
  if (user_access('administer access control')) {
    $roles = user_roles(1);
    unset($roles[DRUPAL_AUTHENTICATED_RID]);
    if ($roles) {
      $form['account']['roles'] = array('#type' => 'checkboxes', '#title' => t('Roles'), '#default_value' => array_keys((array)$edit['roles']), '#options' => $roles, '#description' => t('The user receives the combined permissions of the %au role, and all roles selected here.', array('%au' => theme('placeholder', t('authenticated user')))));
    }
  }

  // Picture/avatar:
  if (variable_get('user_pictures', 0)) {
    $form['picture'] = array('#type' => 'fieldset', '#title' => t('Picture'), '#weight' => 1);
    $picture = theme('user_picture', (object)$edit);
    if ($picture) {
      $form['picture']['current_picture'] = array('#type' => 'markup', '#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', ''));
  }

  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') || arg(1) == 'register') {
    if ($error = user_validate_name($edit['name'])) {
      form_set_error('name', $error);
    }
    else if (db_num_rows(db_query("SELECT uid 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' => theme('placeholder', $edit['name']))));
    }
    else if (drupal_is_denied('user', $edit['name'])) {
      form_set_error('name', t('The name %name has been denied access.', array('%name' => theme('placeholder', $edit['name']))));
    }
  }

  // Validate the e-mail address:
  if ($error = user_validate_mail($edit['mail'])) {
    form_set_error('mail', $error);
  }
  else if (db_num_rows(db_query("SELECT uid 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 taken.', array('%email' => theme('placeholder', $edit['mail']))));
  }
  else if (drupal_is_denied('mail', $edit['mail'])) {
    form_set_error('mail', t('The e-mail address %email has been denied access.', array('%email' => theme('placeholder', $edit['mail']))));
  }

  // If required, validate the uploaded picture.
  if ($file = file_check_upload('picture_upload')) {
    user_validate_picture($file, $edit, $user);
  }
}

function _user_edit_submit($uid, &$edit) {
  $user = user_load(array('uid' => $uid));
  // Delete picture if requested, and if no replacement picture was given.
  if ($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']);
  }
}

function user_edit($category = 'account') {
  global $user;

  $account = user_load(array('uid' => arg(1)));
  $edit = $_POST['op'] ? $_POST['edit'] : (array)$account;

  if (arg(2) == 'delete') {
    if ($edit['confirm']) {
      db_query('DELETE FROM {users} WHERE uid = %d', $account->uid);
      db_query('DELETE FROM {sessions} WHERE uid = %d', $account->uid);
      db_query('DELETE FROM {users_roles} WHERE uid = %d', $account->uid);
      db_query('DELETE FROM {authmap} WHERE uid = %d', $account->uid);
      watchdog('user', t('Deleted user: %name %email.', array('%name' => theme('placeholder', $account->name), '%email' => theme('placeholder', '<'. $account->mail .'>'))), WATCHDOG_NOTICE);
      drupal_set_message(t('The account has been deleted.'));
      module_invoke_all('user', 'delete', $edit, $account);
      drupal_goto('admin/user');
    }
    else {
      return confirm_form('user_confirm_delete', array(), t('Are you sure you want to delete the account %name?', array('%name' => theme('placeholder', $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'));
    }
  }
  else if ($_POST['op'] == t('Delete')) {
    if ($_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.
    drupal_goto("user/$account->uid/delete", $destination);
  }

  $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('Submit'), '#weight' => 30);
  if (user_access('administer users')) {
    $form['delete'] = array('#type' => 'submit', '#value' => t('Delete'), '#weight' => 31);
  }
  $form['#attributes'] = array('enctype' => 'multipart/form-data');

  drupal_set_title($account->name);
  return drupal_get_form('user_edit', $form);
}

function user_edit_validate($form_id, $form_values) {
  user_module_invoke('validate', $form_values, $form_values['_account'], $form_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_values), array('uid', 'init', 'session'))) || (!user_access('administer access control') && isset($form_values['roles']))) {
    $message = t('Detected malicious attempt to alter protected user fields.');
    watchdog('security', $message, WATCHDOG_WARNING);
    // set this to a value type field
    form_set_error('category', $message);
  }
}

function user_edit_submit($form_id, $form_values) {
  $account = $form_values['_account'];
  $category = $form_values['_category'];
  unset($form_values['_account'], $form_values['submit'], $form_values['delete'], $form_values['form_id'], $form_values['_category']);
  user_module_invoke('submit', $form_values, $account, $category);
  user_save($account, $form_values, $category);
  // Delete that user's menu cache.
  cache_clear_all('menu:'. $account->uid, TRUE);
  drupal_set_message(t('The changes have been saved.'));
  return 'user/'. $account->uid;
}

function user_view($uid = 0) {
  global $user;

  $account = user_load(array('uid' => $uid));
  if ($account === FALSE) {
    return drupal_not_found();
  }
  // Retrieve and merge all profile fields:
  $fields = array();
  foreach (module_list() as $module) {
    if ($data = module_invoke($module, 'user', 'view', '', $account)) {
      foreach ($data as $category => $items) {
        foreach ($items as $item) {
          $item['class'] = "$module-". $item['class'];
          $fields[$category][] = $item;
        }
      }
    }
  }
  drupal_set_title($account->name);
  return theme('user_profile', $account, $fields);
}

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

function _user_mail_text($messageid, $variables = array()) {

  // Check if an admin setting overrides the default string.
  if ($admin_setting = variable_get('user_mail_' . $messageid, FALSE)) {
    return strtr($admin_setting, $variables);
  }
  // No override, return with default strings.
  else {
    switch ($messageid) {
      case 'welcome_subject':
        return t('Account details for %username at %site', $variables);
      case 'welcome_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\nYour new %site membership also enables to you to login to other Drupal powered websites (e.g. http://drupal.org/) without registering. Just use the following Drupal ID and password:\n\nDrupal ID: %username@%uri_brief\npassword: %password\n\n\n--  %site team", $variables);
      case 'admin_subject':
        return t('An administrator created an account for you at %site', $variables);
      case 'admin_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\nYour new %site membership also enables to you to login to other Drupal powered websites (e.g. http://www.drupal.org/) without registering. Just use the following Drupal ID and password:\n\nDrupal ID: %username@%uri_brief\npassword: %password\n\n\n--  %site team", $variables);  
      case 'approval_subject':
        return t('Account details for %username at %site (pending admin approval)', $variables);
      case '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 granted, you may 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 may wish to change your password at %edit_uri\n\nYour new %site membership also enables to you to login to other Drupal powered websites (e.g. http://www.drop.org/) without registering. Just use the following Drupal ID and password:\n\nDrupal ID: %username@%uri_brief\npassword: %password\n\n\n--  %site team", $variables);
      case 'pass_subject':
        return t('Replacement login information for %username at %site', $variables);
      case 'pass_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);
    }
  }
}

function user_configure_settings() {
}

/**
 * Menu callback: check an access rule
 */
function user_admin_access_check() {
  $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' => 64);
  $form['user']['type'] = array('#type' => 'hidden', '#value' => 'user');
  $form['user']['submit'] = array('#type' => 'submit', '#value' => t('Check username'));
  $output .= drupal_get_form('check_user', $form, 'user_admin_access_check');
  unset($form); // prevent endless loop?

  $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' => 64);
  $form['mail']['type'] = array('#type' => 'hidden', '#value' => 'mail');
  $form['mail']['submit'] = array('#type' => 'submit', '#value' => t('Check e-mail'));
  $output .= drupal_get_form('check_mail', $form, 'user_admin_access_check');
  unset($form); // prevent endless loop?

  $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'));
  $output .= drupal_get_form('check_host', $form, 'user_admin_access_check');
  unset($form); // prevent endless loop?

  return $output;
}

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

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

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

  $form = _user_admin_access_form($edit);
  $form['submit'] = array('#type' => 'submit', '#value' => t('Add rule'));

  return drupal_get_form('access_rule', $form);
}

/**
 * Menu callback: delete an access rule
 */
function user_admin_access_delete($aid = 0) {
  $access_types = array('user' => t('username'), 'mail' => t('e-mail'));
  $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('user_admin_access_delete_confirm', $form,
                  t('Are you sure you want to delete the %type rule for %rule?', array('%type' => $access_types[$edit->type], '%rule' => theme('placeholder', $edit->mask))),
                  'admin/access/rules',
                  t('This action cannot be undone.'),
                  t('Delete'),
                  t('Cancel'));
  return $output;
}

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

/**
 * Menu callback: edit an access rule
 */
function user_admin_access_edit($aid = 0) {
  if ($edit = $_POST['edit']) {
    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/access/rules');
    }
  }
  else {
    $edit = db_fetch_array(db_query('SELECT aid, type, status, mask FROM {access} WHERE aid = %d', $aid));
  }
  $form = _user_admin_access_form($edit);
  $form['submit'] = array('#type' => 'submit', '#value' => t('Save rule'));

  return drupal_get_form('access_rule', $form);
}

function _user_admin_access_form($edit) {
  $form['status'] = array(
    '#type' => 'radios',
    '#title' => t('Access type'),
    '#default_value' => 0,
    '#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,
  );
  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/access/rules/edit/'. $rule->aid), l(t('delete'), 'admin/access/rules/delete/'. $rule->aid));
  }
  if (count($rows) == 0) {
    $rows[] = array(array('data' => '<em>'. t('There are currently no access rules.') .'</em>', 'colspan' => 5));
  }
  $output .= theme('table', $header, $rows);

  return $output;
}

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($str_rids = NULL) {
  if (preg_match('/^([0-9]+[+ ])*[0-9]+$/', $str_rids)) {
    // The '+' character in a query string may be parsed as ' '.
    $rids = preg_split('/[+ ]/', $str_rids);
  }

  if($rids) {
    $breadcrumbs = drupal_get_breadcrumb();
    $breadcrumbs[] = l(t('all roles'), 'admin/access');
    drupal_set_breadcrumb($breadcrumbs);
    $result = db_query('SELECT r.rid, p.perm FROM {role} r LEFT JOIN {permission} p ON r.rid = p.rid WHERE r.rid IN (%s) ORDER BY name', implode(', ', $rids));
  }
  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:
  $roles = array();
  while ($role = db_fetch_object($result)) {
    $role_permissions[$role->rid] = $role->perm;
  }

  if($rids) {
    $result = db_query('SELECT rid, name FROM {role} r WHERE r.rid IN (%s) ORDER BY name', implode(', ', $rids));
  }
  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('#type' => 'markup', '#value' => t('%module module', array('%module' => $module)));
      asort($permissions);
      foreach ($permissions as $perm) {
        $options[$perm] = '';
        $form['permission'][$perm] = array('#type' => 'markup', '#value' => t($perm));
        foreach ($role_names as $rid => $name) {
          // Builds arrays for checked boxes for each role
          if (strstr($role_permissions[$rid], $perm)) {
            $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' => $status[$rid]);
    $form['role_names'][$rid] = array('#type' => 'markup', '#value' => l($name, 'admin/access/'. $rid), '#tree' => TRUE);
  }
  $form['submit'] = array('#type' => 'submit', '#value' => t('Save permissions'));

  return drupal_get_form('user_admin_perm', $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' => form_render($form['permission'][$key]), 'class' => 'module', 'colspan' => count($form['role_names']) + 1);
      // Permissions
      }
      else {
        $row[] = array('data' => form_render($form['permission'][$key]), 'class' => 'permission');
        foreach (element_children($form['checkboxes']) as $rid) {
          if (is_array($form['checkboxes'][$rid])) {
            $row[] = array('data' => form_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[] = form_render($form['role_names'][$rid]);
    }
  }
  $output = theme('table', $header, $rows, array('id' => 'permissions'));
  $output .= form_render($form);
  return $output;
}

function user_admin_perm_submit($form_id, $edit) {
  // Save permissions:
  $result = db_query('SELECT * FROM {role}');
  while ($role = db_fetch_object($result)) {
    if(isset($edit[$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);
      foreach ($edit[$role->rid] as $key => $value) {
        if (!$value) {
          unset($edit[$role->rid][$key]);
        }
      }
      if (count($edit[$role->rid])) {
        db_query("INSERT INTO {permission} (rid, perm) VALUES (%d, '%s')", $role->rid, implode(', ', array_keys($edit[$role->rid])));
      }
    }
  }

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

  // Clear the cached pages and menus:
  menu_rebuild();

}

/**
 * Menu callback: administer roles.
 */
function user_admin_role() {
  $edit = isset($_POST['edit']) ? $_POST['edit'] : '';
  $op = isset($_POST['op']) ? $_POST['op'] : '';
  $id = arg(4);

  if ($op == t('Save role')) {
    if ($edit['name']) {
      db_query("UPDATE {role} SET name = '%s' WHERE rid = %d", $edit['name'], $id);
      drupal_set_message(t('The changes have been saved.'));
      drupal_goto('admin/access/roles');
    }
    else {
      form_set_error('name', t('You must specify a valid role name.'));
    }
  }
  else if ($op == t('Delete role')) {
    db_query('DELETE FROM {role} WHERE rid = %d', $id);
    db_query('DELETE FROM {permission} WHERE rid = %d', $id);

    // Update the users who have this role set:
    $result = db_query('SELECT DISTINCT(ur1.uid) FROM {users_roles} ur1 LEFT JOIN {users_roles} ur2 ON ur2.uid = ur1.uid WHERE ur1.rid = %d AND ur2.rid != ur1.rid', $id);
    $uid = array();

    while ($u = db_fetch_object($result)) {
      $uid[] = $u->uid;
    }

    if ($uid) {
      db_query('DELETE FROM {users_roles} WHERE rid = %d AND uid IN (%s)', $id, implode(', ', $uid));
    }

    drupal_set_message(t('The role has been deleted.'));
    drupal_goto('admin/access/roles');
  }
  else if ($op == t('Add role')) {
    if ($edit['name']) {
      db_query("INSERT INTO {role} (name) VALUES ('%s')", $edit['name']);
      drupal_set_message(t('The role has been added.'));
      drupal_goto('admin/access/roles');
    }
    else {
      form_set_error('name', t('You must specify a valid role name.'));
    }
  }
  else if ($id) {
    // Display the 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, '#maxlength' => 64, '#description' => t('The name for this role. Example: "moderator", "editorial board", "site architect".'));
    $form['submit'] = array('#type' => 'submit', '#value' => t('Save role'));
    $form['delete'] = array('#type' => 'submit', '#value' => t('Delete role'));
    return drupal_get_form('user_admin_role', $form);
  }
  $form['name'] = array('#type' => 'textfield', '#size' => 32, '#maxlength' => 64);
  $form['submit'] = array('#type' => 'submit', '#value' => t('Add role'));
  return drupal_get_form('user_admin_new_role', $form);
}

function theme_user_admin_new_role($form) {
  $header = array(t('Name'), t('Operations'));
  foreach (user_roles() as $rid => $name) {
    if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
      $rows[] = array($name, l(t('edit'), 'admin/access/roles/edit/'. $rid));
    }
    else {
      $rows[] = array($name, '<span class="disabled">'. t('locked') .'</span>');
    }
  }
  $rows[] = array(form_render($form['name']), form_render($form['submit']));

  return theme('table', $header, $rows);
}

function user_admin_account() {
  $header = array(
    array('data' => t('Username'), 'field' => 'u.name'),
    array('data' => t('Status'), 'field' => 'u.status'),
    array('data' => t('Member for'), 'field' => 'u.created', 'sort' => 'desc'),
    array('data' => t('Last access'), 'field' => 'u.access'),
    t('Operations')
  );
  $sql = 'SELECT u.uid, u.name, u.status, u.created, u.access FROM {users} u WHERE uid != 0';
  $sql .= tablesort_sql($header);
  $result = pager_query($sql, 50);

  $status = array(t('blocked'), t('active'));
  while ($account = db_fetch_object($result)) {
    $rows[] = array(theme('username', $account),
                    $status[$account->status],
                    format_interval(time() - $account->created),
                    $account->access ? t('%time ago', array('%time' => format_interval(time() - $account->access))) : t('never'),
                    l(t('edit'), "user/$account->uid/edit", array()));
  }

  $output = theme('table', $header, $rows);
  $output .= theme('pager', NULL, 50, 0, tablesort_pager());
  return $output;
}

function user_configure() {
  // 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_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'));
  $form['email']['user_mail_welcome_subject'] = array('#type' => 'textfield', '#title' => t('Subject of welcome e-mail'), '#default_value' => _user_mail_text('welcome_subject'), '#maxlength' => 180, '#description' => t('Customize the subject of your welcome e-mail, which is sent to new members upon registering.') .' '. t('Available variables are:') .' %username, %site, %password, %uri, %uri_brief, %mailto, %date, %login_uri, %edit_uri, %login_url.');
  $form['email']['user_mail_welcome_body'] = array('#type' => 'textarea', '#title' => t('Body of welcome e-mail'), '#default_value' => _user_mail_text('welcome_body'), '#rows' => 15, '#description' => t('Customize the body of the welcome e-mail, which is sent to new members upon registering.') .' '. t('Available variables are:') .' %username, %site, %password, %uri, %uri_brief, %mailto, %login_uri, %edit_uri, %login_url.');
  $form['email']['user_mail_admin_subject'] = array('#type' => 'textfield', '#title' => t('Subject of welcome e-mail (user created by administrator)'), '#default_value' => _user_mail_text('admin_subject'), '#maxlength' => 180, '#description' => t('Customize the subject of your welcome e-mail, which is sent to new member accounts created by an administrator.') .' '. t('Available variables are:') .' %username, %site, %password, %uri, %uri_brief, %mailto, %date, %login_uri, %edit_uri, %login_url.');
  $form['email']['user_mail_admin_body'] = array('#type' => 'textarea', '#title' => t('Body of welcome e-mail (user created by administrator)'), '#default_value' => _user_mail_text('admin_body'), '#rows' => 15, '#description' => t('Customize the body of the welcome e-mail, which is sent to new member accounts created by an administrator.') .' '. t('Available variables are:') .' %username, %site, %password, %uri, %uri_brief, %mailto, %login_uri, %edit_uri, %login_url.');
  $form['email']['user_mail_approval_subject'] = array('#type' => 'textfield', '#title' => t('Subject of welcome e-mail (awaiting admin approval)'), '#default_value' => _user_mail_text('approval_subject'), '#maxlength' => 180, '#description' => t('Customize the subject of your awaiting approval welcome e-mail, which is sent to new members upon registering.') .' '. t('Available variables are:') .' %username, %site, %password, %uri, %uri_brief, %mailto, %date, %login_uri, %edit_uri, %login_url.');
  $form['email']['user_mail_approval_body'] = array('#type' => 'textarea', '#title' => t('Body of welcome e-mail (awaiting admin approval)'), '#default_value' => _user_mail_text('approval_body'), '#rows' => 15, '#description' => t('Customize the body of the awaiting approval welcome e-mail, which is sent to new members upon registering.') .' '. t('Available variables are:') .' %username, %site, %password, %uri, %uri_brief, %mailto, %login_uri, %edit_uri, %login_url.');
  $form['email']['user_mail_pass_subject'] = array('#type' => 'textfield', '#title' => t('Subject of password recovery e-mail'), '#default_value' => _user_mail_text('pass_subject'), '#maxlength' => 180, '#description' => t('Customize the Subject of your forgotten password e-mail.') .' '. t('Available variables are:') .' %username, %site, %login_url, %uri, %uri_brief, %mailto, %date, %login_uri, %edit_uri.');
  $form['email']['user_mail_pass_body'] = array('#type' => 'textarea', '#title' => t('Body of password recovery e-mail'), '#default_value' => _user_mail_text('pass_body'), '#rows' => 15, '#description' => t('Customize the body of the forgotten password e-mail.') .' '. t('Available variables are:') .' %username, %site, %login_url, %uri, %uri_brief, %mailto, %login_uri, %edit_uri.');

  // 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'));
  $form['pictures']['user_pictures'] = array('#type' => 'radios', '#title' => t('Picture support'), '#default_value' => variable_get('user_pictures', 0), '#options' => array(t('Disabled'), t('Enabled')), '#description' => t('Enable picture support.'));
  $form['pictures']['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']['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']['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.'));
  $form['pictures']['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']['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('user_configure_settings', $form);
}

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

  if (empty($op)) {
    $op = arg(2);
  }

  switch ($op) {
    case 'search':
    case t('Search'):
      $output = search_form(url('admin/user/search'), $_POST['edit']['keys'], 'user') . search_data($_POST['edit']['keys'], 'user');
      break;
    case t('Create new account'):
    case 'create':
      $output = user_register();
      break;
    default:
      $output = user_admin_account();
  }
  return $output;
}

/**
 * Implementation of hook_help().
 */
function user_help($section) {
  global $user;

  switch ($section) {
    case 'admin/help#user':
      $output = '<p>'. t('The user module allows users to register, login, and logout. 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 .= t('<p>You can</p>
<ul>
<li>view your <a href="%user">user page</a>.</li>
<li>administer users at <a href="%admin-user">administer &gt;&gt; user</a>.</li>
<li>allow users who have the "select different theme" permission to select themes from their user account by enabling themes in <a href="%admin-themes">administer &gt;&gt; themes</a>.</li>
<li>read user profile help at <a href="%admin-help-profile">administer &gt;&gt; help &gt;&gt; profile</a>.</li>
<li>read about distributed authentication in the system module help at <a href="%admin-help-system">administer &gt;&gt; help &gt;&gt; system</a>.</li>
</ul>
', array('%user' => url('user'), '%admin-user' => url('admin/user'), '%admin-themes' => url('admin/themes'), '%admin-help-profile' => url('admin/help/profile'), '%admin-help-system' => url('admin/help/system')));
      $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/modules#description':
      return t('Manages the user registration and login system.');
    case 'admin/user':
      return t('<p>Drupal allows users to register, login, logout, maintain user profiles, etc. No participant can use his own name to post content until he signs up for a user account.</p>');
    case 'admin/user/create':
    case 'admin/user/account/create':
      return t('<p>This web page allows the administrators to register a 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 strstr($section, 'admin/access/rules'):
      return t('<p>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/access':
      return t('<p>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.</p>', array('%role' => url('admin/access/roles')));
    case 'admin/access/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/access/permissions')));
    case 'admin/user/search':
      return t('<p>Enter a simple pattern ("*" may be used as a wildcard match) to search for a username.  For example, one may search for "br" and Drupal might return "brian", "brad", and "brenda".</p>');
    case 'admin/user/configure':
    case 'admin/user/configure/settings':
      return t('<p>In order to use the full power of Drupal a visitor must sign up for an account. This page lets you setup how a user signs up, logs out, the guidelines from the system about user subscriptions, and the e-mails the system will send to the user.</p>');
    case 'user/help#user':
      $site = variable_get('site_name', 'this website');

      $output = t("
      <h3>Distributed authentication<a id=\"da\"></a></h3>
      <p>One of the more tedious moments in visiting a new website is filling out the registration form. Here at %site, you do not have to fill out a registration form if you are already a member of %help-links. This capability is called <em>distributed authentication</em>, and is unique to <a href=\"%drupal\">Drupal</a>, the software which powers %site.</p>
      <p>Distributed authentication enables a new user to input a username and password into the login box, and immediately be recognized, even if that user never registered at %site. This works because Drupal knows how to communicate with external registration databases. For example, lets say that new user 'Joe' is already a registered member of <a href=\"%delphi-forums\">Delphi Forums</a>. Drupal informs Joe on registration and login screens that he may login with his Delphi ID instead of registering with %site. Joe likes that idea, and logs in with a username of joe@remote.delphiforums.com and his usual Delphi password. Drupal then contacts the <em>remote.delphiforums.com</em> server behind the scenes (usually using <a href=\"%xml\">XML-RPC</a>, <a href=\"%http-post\">HTTP POST</a>, or <a href=\"%soap\">SOAP</a>) and asks: \"Is the password for user Joe correct?\".  If Delphi replies yes, then we create a new %site account for Joe and log him into it.  Joe may keep on logging into %site in the same manner, and he will always be logged into the same account.</p>", array('%help-links' => (implode(', ', user_auth_help_links())), '%site' => "<em>$site</em>", '%drupal' => 'http://drupal.org', '%delphi-forums' => 'http://www.delphiforums.com', '%xml' => 'http://www.xmlrpc.com', '%http-post' => 'http://www.w3.org/Protocols/', '%soap' => 'http://www.soapware.org'));

        foreach (module_list() as $module) {
          if (module_hook($module, 'auth')) {
            $output .= "<h4><a id=\"$module\"></a>". module_invoke($module, 'info', 'name') .'</h4>';
            $output .= module_invoke($module, 'help', "user/help#$module");
          }
        }

        return $output;
  }

}

/**
 * Menu callback; Prints user-specific help information.
 */
function user_help_page() {
  return user_help('user/help#user');
}

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

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

  usort($categories, '_user_sort');

  return $categories;
}

function _user_sort($a, $b) {
  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();
  $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);
  }
  print drupal_to_js($matches);
  exit();
}