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

/*** Common functions ******************************************************/

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

function user_load($array = array()) {

  /*
  ** Dynamically compose a SQL query:
  */

  $query = "";

  foreach ($array as $key => $value) {
    if ($key == "pass") {
      $query .= "u.$key = '". md5($value) ."' AND ";
    }
    else {
      $query .= "u.$key = '". check_query($value) ."' AND ";
    }
  }
  $result = db_query_range("SELECT u.*, r.name AS role FROM {role} r INNER JOIN {users} u ON r.rid = u.rid WHERE $query u.status < 3", 0, 1);

  $user = db_fetch_object($result);
  if ($user->data && $data = unserialize($user->data)) {
    foreach ($data as $key => $value) {
      if (!isset($user->$key)) {
        $user->$key = $value;
      }
    }
  }

  return $user;
}

function user_save($account, $array = array()) {
  /*
  ** Dynamically compose a SQL query:
  */

  $user_fields = user_fields();
  if ($account->uid) {
    $data = unserialize(db_result(db_query("SELECT data FROM {users} WHERE uid = %d", $account->uid)));
    foreach ($array as $key => $value) {
      if ($key == "pass") {
        $query .= "$key = '%s', ";
        $v[] = md5($value);
      }
      else if (substr($key, 0, 4) !== "auth") {
        if (in_array($key, $user_fields)) {
          // escape '%'s:
          $value = str_replace("%", "%%", $value);
          $query .= "$key = '%s', ";
          $v[] = $value;
        }
        else {
          $data[$key] = $value;
        }
      }
    }
    $query .= "data = '%s', ";
    $v[] = serialize($data);

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

    $user = user_load(array("uid" => $account->uid));
  }
  else {
    $array["timestamp"] = time();
    $array["uid"] = db_next_id("{users}_uid");

    foreach ($array as $key => $value) {
      if ($key == "pass") {
        $fields[] = check_query($key);
        $values[] = md5($value);
        $s[] = "'%s'";
      }
      else if (substr($key, 0, 4) !== "auth") {
        if (in_array($key, $user_fields)) {
          $fields[] = check_query($key);
          $values[] = $value;
          $s[] = "'%s'";
        }
        else {
          $data[$key] = $value;
        }
      }
    }

    $fields[] = "data";
    $values[] = serialize($data);
    $s[] = "'%s'";

    db_query("INSERT INTO {users} (". implode(", ", $fields) .") VALUES (". implode(", ", $s) .")", $values);

    $user = user_load(array("name" => $array["name"]));
  }

  foreach ($array as $key => $value) {
    if (substr($key, 0, 4) == "auth") {
      $authmaps[$key] = $value;
    }
  }

  if ($authmaps) {
    user_set_authmaps($user, $authmaps);
  }

  return $user;
}

function user_validate_name($name) {

  /*
  ** Verify the syntax of the given name:
  */

  if (!$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('[^ [:alnum:]@_.-]', $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" => $name));
}

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

function user_validate_authmap($account, $authname, $module) {
  $result = db_query("SELECT COUNT(*) from {authmap} WHERE uid != %d AND authname = '%s'", $account->uid, $authname);
  if (db_result($result) > 0) {
    $name = module_invoke($module, "info", "name");
    return t("The %u ID %s is already taken.", array("%u" => ucfirst($name), "%s" => "<i>$authname</i>"));
  }
}

function user_password($length = 10) {

  /*
  ** Generate a random alphanumeric password.
  */

  // 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' and 1.
  $allowable_characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
  // We see how many characters are in the allowable list:
  $len = strlen($allowable_characters);

  // Seed the random number generator with the microtime stamp:
  mt_srand((double)microtime() * 1000000);

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

  return $pass;
}

function user_access($string) {
  global $user;
  static $perm = 0;

  // User #1 has all priveleges:
  if ($user->uid == 1) {
    return 1;
  }

  /*
  ** To reduce the number of SQL queries, we cache the user's permissions
  ** in a static variable.
  */

  if ($perm === 0) {
    $perm = db_result(db_query("SELECT p.perm FROM {role} r, {permission} p WHERE r.rid = p.rid AND r.rid = %d", $user->rid), 0);
  }

  return strstr($perm, $string);
}

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 recieved 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 email, 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,
      user_mail_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_mail_encode($string, $charset = "UTF-8") {
  /*
  ** Used to encodes mail headers that contain non US- ASCII
  ** characters.
  ** http://www.rfc-editor.org/rfc/rfc2047.txt
  **
  ** Notes:
  **   - The chunks come in groupings of 4 bytes when using base64
  **     encoded.
  **   - trim() is used to ensure that no extra spacing is added by
  **     chunk_split() or preg_replace().
  **   - Using \n as the chunk separator may cause problems on some
  **     systems and may have to be changed to \r\n or \r.
  */
  $chunk_size = 75 - 7 - strlen($charset);
  $chunk_size -= $chunk_size % 4;
  $string = trim(chunk_split(base64_encode($string), $chunk_size, "\n"));
  $string = trim(preg_replace('/^(.*)$/m', " =?$charset?B?\\1?=", $string));
  return $string;
}

function user_deny($type, $mask) {
  $allow = db_fetch_object(db_query("SELECT * FROM {access} WHERE status = '1' AND type = '%s' AND LOWER('%s') LIKE LOWER(mask)", $type, $mask));
  $deny = db_fetch_object(db_query("SELECT * FROM {access} WHERE status = '0' AND type = '%s' AND LOWER('%s') LIKE LOWER(mask)", $type, $mask));

  return $deny && !$allow;
}

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", "mode", "sort", "threshold", "theme", "signature", "timestamp", "status", "timezone", "language", "init", "data", "rid");
    }
  }

  return $fields;
}

/*** Module hooks **********************************************************/

function user_perm() {
  return array("administer users");
}

function user_search($keys) {
  $find = array();
  $result = db_query_range("SELECT * FROM {users} WHERE name LIKE '%%%s%%'", $keys, 0, 20);
  while ($account = db_fetch_object($result)) {
    $find[] = array("title" => $account->name, "link" => (strstr(request_uri(), "admin") ? url("admin/user/edit/$account->uid") : url("user/view/$account->uid")), "user" => $account->name);
  }
  return $find;
}

function user_block($op = "list", $delta = 0) {
  global $user;

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

     return $blocks;
  }
  else {
    switch ($delta) {
      case 0:
        if (!$user->uid) {
          /*
          ** For usability's sake, avoid showing two login forms on one
          ** page.
          */

          if (arg(0) == "user" && arg(1) != "view") {
            return;
          }

          $edit = $_POST["edit"];

          $output = "<div class=\"user-login-block\">\n";

          /*
          ** Save the referer.  We record where the user came from such
          ** that we/ can redirect him after having completed the login
          ** form.
          */

          if (empty($edit)) {
            $edit["destination"] = url($_GET["q"]);
          }
          // NOTE: special care needs to be taken because on pages with forms, such as node and comment submission pages, the $edit variable might already be set.

          $form = form_hidden("destination", $edit["destination"]);
          $form .= form_textfield(t("Username"), "name", $edit["name"], 15, 64);
          $form .= form_password(t("Password"), "pass", $pass, 15, 64);

          if (variable_get("user_remember", 0) == 0) {
            $form .= form_checkbox(t("Remember me"), "remember_me", 1, 0, 0);
          }
          elseif (variable_get("user_remember", 1) == 1) {
            $form .= form_hidden("remember_me", 1);
          }

          $form .= form_submit(t("Log in"));

          $output .= form($form, "post", url("user/login"));

          $output .= "</div>\n";

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

          $output .= theme("item_list", $items);

          $block["subject"] = t("User login");
          $block["content"] = "<div class=\"user-login-link\">$output</div>";
        }
        return $block;
      case 1:
        if ($menu = menu_tree()) {
           $block["subject"] = $user->uid ? $user->name : t("Navigation");
           $block["content"] = "<div class=\"menu\">". $menu ."</div>";
        }

        return $block;
      case 2:
        if (user_access("access content")) {
          $result = db_query_range("SELECT uid, name FROM {users} WHERE status != '0' ORDER BY uid DESC", 0, 5);
          while ($account = db_fetch_object($result)) {
            $items[] = l((strlen($account->name) > 15 ? substr($account->name, 0, 15) . '...' : $account->name), "user/view/$account->uid");
          }

          $output = theme("user_list", $items);

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

function theme_user_list($items, $title = NULL) {
  return theme("item_list", $items, $title);
}

function user_link($type) {

  $links = array();

  if ($type == "page") {
    $links[] = l(t("my account"), "user", array("title" => t("Create a user account, request a new password or edit your account settings.")));
  }

  if ($type == "system") {
    global $user;
    if ($user->uid) {
      menu("user", t("my account"), "page", 8);
      menu("user/edit", t("edit account"), "page", 0);
      menu("user/logout", t("log out"), "page", 10);
    }

    if (user_access("administer users")) {
      menu("admin/user", t("accounts"), "user_admin", 2);
      menu("admin/user/create", t("new user"), "user_admin", 1);
      menu("admin/user/access", t("access rules"), NULL, 3);
      menu("admin/user/access/mail", t("e-mail rules"), "user_admin");
      menu("admin/user/access/user", t("name rules"), "user_admin");
      menu("admin/user/role", t("roles"), "user_admin", 4);
      menu("admin/user/permission", t("permissions"), "user_admin", 5);
      menu("admin/user/search", t("search"), "user_admin", 8);
      menu("admin/user/help", t("help"), "user_help", 9);
      menu("admin/user/edit", t("edit user account"), "user_admin", 0, 1); // hidden menu
    }
  }

  return $links;
}

/*** Authentication methods ************************************************/

function user_get_authname($account, $module) {

  /*
  **  Called by authentication modules in order to edit/view their authmap information.
  */

  $result = db_query("SELECT authname FROM {authmap} WHERE uid = %d AND module = '%s'", $account->uid, $module);
  return db_result($result);
}


function user_get_authmaps($authname = NULL) {

  /*
  ** Accepts an user object, $account, or an DA name and returns an
  ** associtive array of modules and DA names. Called at external login.
  */

  $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($edit = array(), $msg = "") {
  global $user, $base_url;

  /*
  ** If we are already logged on, go to the user page instead.
  */

  if ($user->uid) {
    drupal_goto(url("user"));
  }

  if (user_deny("user", $edit["name"])) {
    $error = t("The name '%s' has been denied access.", array("%s" => $edit["name"]));
  }
  else if ($edit["name"] && $edit["pass"]) {

    /*
    ** Try to log in the user locally:
    */

    if (!$user->uid) {
      $name = $edit["name"];
      $pass = $edit["pass"];
      $user = user_load(array("name" => $name, "pass" => $pass, "status" => 1));
    }

    /*
    ** Strip name and server from ID:
    */

    if ($server = strrchr($edit["name"], "@")) {
      $name = substr($edit["name"], 0, strlen($edit["name"]) - strlen($server));
      $server = substr($server, 1);
      $pass = $edit["pass"];
    }

    /*
    ** When possible, determine corresponding external auth source. Invoke source, and login 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", "external load: $name@$server, module: ". key($result));
      }
      else {
        $error = t("Invalid password for %s.", array("%s" => "<i>$name@$server</i>"));
      }
    }

     /*
    ** 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 && !user_load(array("name" => "$name@$server"))) { //register this new user
              $user = user_save("", array("name" => "$name@$server", "pass" => user_password(), "init" => "$name@$server", "status" => 1, "authname_$module" => "$name@$server", "rid" => _user_authenticated_id()));
              watchdog("user", "new user: $name@$server ($module ID)", l(t("edit user"), "admin/user/edit/$user->uid"));
              break;
            }
          }
        }
      }
    }

    if ($user->uid) {
      watchdog("user", "session opened for '$user->name'");

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

      /*
      ** If the user wants to be remembered, set the proper cookie such
      ** that the session won't expire.
      */

      $path = preg_replace("/.+\/\/[^\/]+(.*)/", "\$1/", $base_url);
      if ($edit["remember_me"]) {
        setcookie(session_name(), session_id(), time() + 3600 * 24 * 365, $path);
      }
      else {
        setcookie(session_name(), session_id(), FALSE, $path);
      }

      /*
      ** Redirect the user to the page he logged on from.
      */

      drupal_goto($edit["destination"]);
    }
    else {
      if (!$error) {
        $error = t("Sorry.  Unrecognized username or password.") ." ". l(t("Have you forgotten your password?"), "user/password");
      }
      if ($server) {
        watchdog("user", "failed login for '$name@$server': $error");
      }
      else {
        watchdog("user", "failed login for '$name': $error");
      }
    }
  }

  /*
  ** Display error message (if any):
  */

  if ($error) {
    $output .= theme("error", $error);
  }

  /*
  ** Save the referrer.  We record where the user came from such that we
  ** can redirect him after having completed the login form.
  */

  if (empty($edit)) {
    $edit["destination"] = url($_GET["q"]);
  }
  $output .= form_hidden("destination", $edit["destination"]);

  /*
  ** Display login form:
  */

  if ($msg) {
    $output .= "<p>$msg</p>";
  }
  if (count(user_auth_help_links()) > 0) {
    $output .= form_textfield(t("Username"), "name", $edit["name"], 30, 64, 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 {
    $output .= form_textfield(t("Username"), "name", $edit["name"], 30, 64, t("Enter your %s username.", array("%s" => variable_get("site_name", "local"))));
  }
  $output .= form_password(t("Password"), "pass", $pass, 30, 64, t("Enter the password that accompanies your username."));
  $output .= form_checkbox(t("Remember me"), "remember_me", 1, 0, 0);
  $output .= form_submit(t("Log in"));
  $items[] = l(t("Request new password"), "user/password");
  if (variable_get("user_register", 1)) {
    $items[] = l(t("Create new account"), "user/register");
  }
  $output .= theme("item_list", $items);

  return form($output, "post", url("user"));
}

function _user_authenticated_id() {
  return db_result(db_query("SELECT rid FROM {role} WHERE name = 'authenticated user'"));
}

function user_logout() {
  global $user;

  if ($user->uid) {
    watchdog("user", "session closed for user '$user->name'");

    /*
    ** Destroy the current session:
    */

    session_destroy();
    unset($user);
  }

  drupal_goto(url());

}

function user_pass($edit = array()) {
  global $base_url;

  if ($edit["name"]) {
    $account = db_fetch_object(db_query("SELECT uid, name, mail FROM {users} WHERE name = '%s'", $edit["name"]));
    if (!$account) $error = t("Sorry. The username <i>%s</i> is not recognized.", array("%s" => $edit["name"]));
  }
  else if ($edit["mail"]) {
    $account = db_fetch_object(db_query("SELECT uid, name, mail FROM {users} WHERE mail = '%s'", $edit["mail"]));
    if (!$account) $error = t("Sorry. The e-mail address <i>%s</i> is not recognized.", array("%s" => $edit["mail"]));
  }
  if ($account) {

      $from = variable_get("site_mail", ini_get("sendmail_from"));
      $pass = user_password();

      /*
      ** Save new password:
      */

      user_save($account, array("pass" => $pass));

      /*
      ** Mail new password:
      */

      $variables = array("%username" => $account->name, "%site" => variable_get("site_name", "drupal"), "%password" => $pass, "%uri" => $base_url, "%uri_brief" => substr($base_url, strlen("http://")), "%mailto" => $account->mail, "%date" => format_date(time()));
      $subject = strtr(variable_get("user_mail_pass_subject", _user_mail_text("pass_subject")), $variables);
      $body = strtr(variable_get("user_mail_pass_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", "mail password: '". $account->name ."' &lt;". $account->mail ."&gt;");
        return t("Your password and further instructions have been sent to your e-mail address.");
      }
      else {
        watchdog("error", "error mailing new password: '". $account->name ."' &lt;". $account->mail ."&gt;");
        return t("Unable to send mail. Please contact the site admin.");
      }
    }
    else {

    // Display error message if necessary.
    if ($error) {
      $output .= theme("error", $error);
    }

    /*
    ** Display form:
    */

    $output .= "<p>". sprintf(t("Enter your username %sor%s your e-mail address."), "<b><i>", "</i></b>") ."</p>";
    $output .= form_textfield(t("Username"), "name", $edit["name"], 30, 64);
    $output .= form_textfield(t("E-mail address"), "mail", $edit["mail"], 30, 64);
    $output .= form_submit(t("E-mail new password"));
    $items[] = l(t("Log in"), "user/login");
    if (variable_get("user_register", 1)) {
      $items[] = l(t("Create new account"), "user/register");
    }
    $output .= theme("item_list", $items);

    return form($output, "post", url("user"));
  }
}

function user_register($edit = array()) {
  global $user, $base_url;

  /*
  ** If we are already logged on, go to the user page instead.
  */

  if ($user->uid) {
    drupal_goto(url("user/edit"));
  }

  if ($edit["name"] && $edit["mail"]) {
    if ($error = user_validate_name($edit["name"])) {
      // do nothing
    }
    else if ($error = user_validate_mail($edit["mail"])) {
      // do nothing
    }
    else if (user_deny("user", $edit["name"])) {
      $error = t("The name '%s' has been denied access.", array("%s" => $edit["name"]));
    }
    else if (user_deny("mail", $edit["mail"])) {
      $error = t("The e-mail address '%s' has been denied access.", array("%s" => $edit["mail"]));
    }
    else if (db_num_rows(db_query("SELECT name FROM {users} WHERE LOWER(name) = LOWER('%s')", $edit["name"])) > 0) {
      $error = t("The name '%s' is already taken.", array("%s" => $edit["name"]));
    }
    else if (db_num_rows(db_query("SELECT mail FROM {users} WHERE LOWER(mail) = LOWER('%s') OR LOWER(init) = LOWER('%s')", $edit["mail"], $edit["mail"])) > 0) {
      $error = t("The e-mail address '%s' is already taken.", array("%s" => $edit["mail"]));
    }
    else if (variable_get("user_register", 1) == 0) {
      $error = t("Public registrations have been disabled by the site administrator.");
    }
    else {
      foreach (module_list() as $module) {
        if (module_hook($module, "user")) {
          $result = module_invoke($module, "user", "register_validate", $edit, $user);
          if (is_array($result)) {
            $data = array_merge($data, $result);
          }
          elseif (is_string($result)) {
            $error = $result;
            break;
          }
        }
      }
      if (!$error) {
        $success = 1;
      }
    }
  }

  if ($success) {

    $from = variable_get("site_mail", ini_get("sendmail_from"));
    $pass = user_password();

    // create new user account, noting whether administrator approval is required
    user_role_init();
    // TODO: is this necessary? Won't session_write replicate this?
    unset($edit["session"]);
    $account = user_save("", array_merge(array("name" => $edit["name"], "pass" => $pass, "init" => $edit["mail"], "mail" => $edit["mail"], "rid" => _user_authenticated_id(), "status" => (variable_get("user_register", 1) == 1 ? 1 : 0)), $data));
    watchdog("user", "new user: '". $edit["name"] ."' &lt;". $edit["mail"] ."&gt;", l(t("edit user"), "admin/user/edit/$account->uid"));

    $variables = array("%username" => $edit["name"], "%site" => variable_get("site_name", "drupal"), "%password" => $pass, "%uri" => $base_url, "%uri_brief" => substr($base_url, strlen("http://")), "%mailto" => $edit["mail"], "%date" => format_date(time()));

    //the first user may login immediately, and receives a customized welcome e-mail.
    if ($account->uid == 1) {
      user_mail($edit["mail"], t("drupal user account details for %s", array("%s" => $edit["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". url("user/edit") ."\n\n--drupal"), $variables), "From: $from\nReply-to: $from\nX-Mailer: Drupal\nReturn-path: $from\nErrors-to: $from");
      // This should not be t()'ed. No point as its only shown once in the sites lifetime, and it would be bad to store the password
      $output .= "<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 configure your e-mail settings using the Administration pages.</p><p> Your password is <b>$pass</b>. You may change your password on the next page.</p><p>Please login below.</p>";
      $output .= form_hidden("destination", url("user/edit"));
      $output .= form_hidden("name", $account->name);
      $output .= form_hidden("pass", $pass);
      $output .= form_submit(t("Log in"));
      return form($output);
    }
    else {
      if ($account->status) {
        /*
        ** Create new user account, no administrator approval required:
        */

        $subject = strtr(variable_get("user_mail_welcome_subject", _user_mail_text("welcome_subject")), $variables);
        $body = strtr(variable_get("user_mail_welcome_body", _user_mail_text("welcome_body")), $variables);
        user_mail($edit["mail"], $subject, $body, "From: $from\nReply-to: $from\nX-Mailer: Drupal\nReturn-path: $from\nErrors-to: $from");
        return t("Your password and further instructions have been sent to your e-mail address.");
      }
      else {
        /*
        ** Create new user account, administrator approval required:
        */
        $subject = strtr(variable_get("user_mail_approval_subject", _user_mail_text("welcome_approval_subject")), $variables);
        $body = strtr(variable_get("user_mail_approval_body", _user_mail_text("welcome_approval_body")), $variables);
        user_mail($edit["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("admin/user/edit/$account->uid"))), "From: $from\nReply-to: $from\nX-Mailer: Drupal\nReturn-path: $from\nErrors-to: $from");
        return 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.");
      }
    }
  }
  else {
    if ($error) {
      $output .= theme("error", $error);
    }
  }

  // display the registration form
  $output .= variable_get("user_registration_help", "");
  $affiliates = user_auth_help_links();
  if (count($affiliates) > 0) {
    $affiliates = implode(", ", $affiliates);
    $output .= "<p>". t("Note: If you have an account with one of our affiliates (%s), you may ". l("login now", "user/login") ." instead of registering.", array("%s" => $affiliates)) ."</p>";
  }
  $output .= form_textfield(t("Username"), "name", $edit["name"], 30, 64, t("Your full name or your preferred username: only letters, numbers and spaces are allowed."));
  $output .= form_textfield(t("E-mail address"), "mail", $edit["mail"], 30, 64, t("A password and instructions will be sent to this e-mail address, so make sure it is accurate."));
  foreach (module_list() as $module) {
    if (module_hook($module, "user")) {
      $output .= module_invoke($module, "user", "register_form", $edit, $user);
    }
  }
  $output .= form_submit(t("Create new account"));
  $items[] = l(t("Request new password"), "user/password");
  $items[] = l(t("Log in"), "user/login");
  $output .= theme("item_list", $items);

  return form($output);
}

function user_edit($edit = array()) {
  global $user;

  if ($user->uid) {
    if ($edit["name"]) {
      if ($error = user_validate_name($edit["name"])) {
        // do nothing
      }
      else if ($error = user_validate_mail($edit["mail"])) {
        // do nothing
      }
      else if (db_num_rows(db_query("SELECT uid FROM {users} WHERE uid != '$user->uid' AND LOWER(name) = LOWER('%s')", $edit["name"])) > 0) {
        $error = t("The name '%s' is already taken.", array("%s" => $edit["name"]));
      }
      else if ($edit["mail"] && db_num_rows(db_query("SELECT uid FROM {users} WHERE uid != '$user->uid' AND LOWER(mail) = LOWER('%s')", $edit["mail"])) > 0) {
        $error = t("The e-mail address '%s' is already taken.", array("%s" => $edit["mail"]));
      }
      else if ($user->uid) {
        /*
        ** If required, check that proposed passwords match.  If so,
        ** add new password to $edit.
        */

        if ($edit["pass1"]) {
          if ($edit["pass1"] == $edit["pass2"]) {
            $edit["pass"] = $edit["pass1"];
          }
          else {
            $error = t("The specified passwords do not match.");
          }
        }
        unset($edit["pass1"], $edit["pass2"]);

        /*
        ** Validate input fields to make sure users don't submit
        ** invalid form data.
        */

        if (!user_access("administer users")) {
           if (array_intersect(array_keys($edit), array("rid", "init", "session"))) {
             watchdog("warning", "detected malicious attempt to alter a protected database field");
           }

           $edit["rid"] = $user->rid;
           $edit["init"] = $user->init;
           $edit["session"] = $user->session;
        }

        /*
        ** Have the modules that extend the user information validate
        ** their data.
        */

        foreach (module_list() as $module) {
          if (module_hook($module, "user")) {
            $result = module_invoke($module, "user", "edit_validate", $edit, $user);
          }
          if (is_array($result)) {
            $data = array_merge($data, $result);
          }
          elseif (is_string($result)) {
            $error = $result;
            break;
          }
        }

        if (!$error) {
          /*
          ** Save user information:
          */

          $user = user_save($user, array_merge($edit, $data));

          $output .= status(t("your user information changes have been saved."));
        }
      }
    }

    if ($error) {
      $output .= theme("error", $error);
    }

    if (!$edit) {
      $edit = object2array($user);
    }

    $output .= form_textfield(t("Username"), "name", $edit["name"], 30, 55, t("Your full name or your preferred username: only letters, numbers and spaces are allowed."));
    $output .= form_textfield(t("E-mail address"), "mail", $edit["mail"], 30, 55, 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."));

    $output .= implode("\n", module_invoke_all("user", "edit_form", $edit, $user));

    $output .= form_item(t("Password"), "<input type=\"password\" name=\"edit[pass1]\" size=\"12\" maxlength=\"24\" /> <input type=\"password\" name=\"edit[pass2]\" size=\"12\" maxlength=\"24\" />", t("Enter your new password twice if you want to change your current password or leave it blank if you are happy with your current password."));
    $output .= form_submit(t("Save user information"));

    $output = form($output, "post", 0, array("enctype" => "multipart/form-data"));
      // the "enctype" attribute is required to upload files such as avatars
  }
  else {
    $output = user_login();
  }

  return $output;
}

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

  if (!$uid) {
    $uid = $user->uid;
  }

  if ($user->uid && $user->uid == $uid) {
    $output = form_item(t("Name"), "$user->name ($user->init)");
    $output .= form_item(t("E-mail address"), $user->mail, t("Please note that only you can see your own e-mail address - it is not publicly visible."));

    $output .= implode("\n", module_invoke_all("user", "view_private", "", $user));

    print theme("header", $user->name);
    print theme("box", $user->name, $output);
    print theme("footer");
  }
  else if ($uid && $account = user_load(array("uid" => $uid, "status" => 1))) {
    $output = form_item(t("Name"), $account->name);

    $output .= implode("\n", module_invoke_all("user", "view_public", "", $account));

    if (user_access("administer users")) {
      $output .= form_item(t("Administration"), l(t("edit account"), "admin/user/edit/$account->uid"));
    }

    print theme("header", $account->name);
    print theme("box", $account->name, $output);
    print theme("footer");
  }
  else {
    $output = user_login();
    print theme("header", t("User login"));
    print theme("box", t("User login"), $output);
    if (variable_get("user_register", 1)) {
      print theme("box", t("Create new user account"), user_register());
    }
    print theme("box", t("Request new password"), user_pass());
    print theme("footer");
  }
}

function user_page() {

  $edit = $_POST["edit"];
  $op = $_POST["op"];

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

  switch ($op) {
    case t("E-mail new password"):
    case "password":
      print theme("header", t("E-mail new password"));
      print theme("box", t("E-mail new password"), user_pass($edit));
      print theme("footer");
      break;
    case t("Create new account"):
    case "register":
      $output = user_register($edit);
      print theme("header", t("Create new account"));
      if (variable_get("user_register", 1)) {
        print theme("box", t("Create new account"), $output);
      }
      else {
        print message_access();
      }
      print theme("footer");
      break;
    case t("Log in"):
    case "login":
      $output = user_login($edit);
      print theme("header", t("Log in"));
      print theme("box", t("Log in"), $output);
      print theme("footer");
      break;
    case t("Save user information"):
    case "edit":
      $output = user_edit($edit);
      $GLOBALS["theme"] = init_theme();
      print theme("header", t("Edit user information"));
      print theme("box", t("Edit user information"), $output);
      print theme("footer");
      break;
    case "view":
      user_view(arg(2));
      break;
    case t("Logout"):
    case "logout":
      print user_logout();
      break;
    case "help":
      print theme("header");
      print theme("box", t("Distributed authentication"), user_help("user/help#user"));
      print theme("footer");
      break;
    default:
      print user_view();
  }

}

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

function _user_mail_text($message) {
  switch ($message) {
    case "welcome_subject":
      return "Account details for %username at %site";

    case "welcome_body":
    return t("%username,\n\nThank you for registering at %site. You may now log in to ". url("user/login") ." using the following username and password:\n\nusername: %username\npassword: %password\n\nAfter logging in, you may wish to change your password at ". url("user/edit") ."\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");

    case "welcome_approval_subject":
      return "Account details for %username at %site (pending admin approval)";

    case "welcome_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 ". url("user/login") ." using the following username and password:\n\nusername: %username\npassword: %password\n\nAfter logging in, you may wish to change your password at ". url("user/edit") ."\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");

    case "pass_subject":
      return "Replacement login information for %username at %site";

    case "pass_body":
      return t("%username,\n\nHere is your new password for %site. You may now login to ". url("user/login") ." using the following username and password:\n\nusername: %username\npassword: %password\n\nAfter logging in, you may wish to change your password at "). url("user/edit");
  }
}

function user_settings() {
  $output = form_radios(t("Public registrations"), "user_register", variable_get("user_register", 1), 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.")));

  $output .= form_radios(t("Remember authenticated users"), "user_remember", variable_get("user_remember", 0), array(t("Let the user decide whether he should be logged out when leaving the site."), t("Authenticated users are not logged out upon leaving the site."), t("Authenticated users are logged out upon leaving the site.")));

  $output .= form_textarea(t("User registration guidelines"), "user_registration_help", variable_get("user_registration_help", ""), 70, 4, t("This text is displayed at the top of the user registration form.  It's useful for helping or instructing your users."));

  $output .= form_textfield(t("Subject of welcome e-mail"), "user_mail_welcome_subject", variable_get("user_mail_welcome_subject", _user_mail_text("welcome_subject")), 70, 180, 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");

  $output .= form_textarea(t("Body of welcome e-mail"), "user_mail_welcome_body", variable_get("user_mail_welcome_body", _user_mail_text("welcome_body")), 70, 10, 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");

  $output .= form_textfield(t("Subject of welcome e-mail (awaiting admin approval)"), "user_mail_approval_subject", variable_get("user_mail_approval_subject", _user_mail_text("welcome_approval_subject")), 70, 180, 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");

  $output .= form_textarea(t("Body of welcome e-mail (awaiting admin approval)"), "user_mail_approval_body", variable_get("user_mail_approval_body", _user_mail_text("welcome_approval_body")), 70, 10, 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");

  $output .= form_textfield(t("Subject of password recovery e-mail"), "user_mail_pass_subject", variable_get("user_mail_pass_subject", _user_mail_text("pass_subject")), 70, 180, t("Customize the Subject of your forgotten password e-mail.") ." ". t("Available variables are:") ." ". "%username, %site, %password, %uri, %uri_brief, %mailto, %date");

  $output .= form_textarea(t("Body of password recovery e-mail"), "user_mail_pass_body", variable_get("user_mail_pass_body", _user_mail_text("pass_body")), 70, 10, t("Customize the body of the forgotten password e-mail.") ." ". t("Available variables are:") ." ". "%username, %site, %password, %uri, %uri_brief, %mailto");

  return $output;
}

function user_admin_create($edit = array()) {
  if ($edit["name"] || $edit["mail"]) {
    if ($error = user_validate_name($edit["name"])) {
      // do nothing
    }
    else if ($error = user_validate_mail($edit["mail"])) {
      // do nothing
    }
    else if (db_num_rows(db_query("SELECT name FROM {users} WHERE LOWER(name) = LOWER('%s')", $edit["name"])) > 0) {
      $error = t("The name '%s' is already taken.", array("%s" => $edit["name"]));
    }
    else if (db_num_rows(db_query("SELECT mail FROM {users} WHERE LOWER(mail) = LOWER('%s')", $edit["mail"])) > 0) {
      $error = t("The e-mail address '%s' is already taken.", array("%s" => $edit["mail"]));
    }
    else {
      $success = 1;
    }
  }

  if ($success) {
    watchdog("user", "new user: '". $edit["name"] ."' &lt;". $edit["mail"] ."&gt;");

    user_save("", array("name" => $edit["name"], "pass" => $edit["pass"], "init" => $edit["mail"], "mail" => $edit["mail"], "rid" => _user_authenticated_id(), "status" => 1));

    return "Created a new user '". $edit["name"] ."'.  No e-mail has been sent.";
  }
  else {

    if ($error) {
      $output .= theme("error", $error);
    }

    $output .= form_textfield(t("Username"), "name", $edit["name"], 30, 55, t("Provide the username of the new account."));
    $output .= form_textfield(t("E-mail address"), "mail", $edit["mail"], 30, 55, t("Provide the e-mail address associated with the new account."));
    $output .= form_textfield(t("Password"), "pass", $edit["pass"], 30, 55, t("Provide a password for the new account."));
    $output .= form_submit(t("Create account"));

    return form($output);
  }
}

function user_admin_access($edit = array()) {
  $type = arg(3);

  if (empty($type)) {
    return;
  }

  $op = $_POST["op"];
  $id = arg(4);

  if ($op == t("Add rule")) {
    $aid = db_next_id("{access}_aid");
    db_query("INSERT INTO {access} (aid, mask, type, status) VALUES ('%s', '%s', '%s', %d)", $aid, $edit["mask"], $type, $edit["status"]);
    $output .= status(t("access rule added."));
  }
  else if ($op == t("Check")) {
    if (user_deny($type, $edit["test"])) {
      $output .= status(t("<i>%test</i> is not allowed.", array ("%test" => $edit["test"])));
    }
    else {
      $output .= status(t("<i>%test</i> is allowed.", array ("%test" => $edit["test"])));
    }
  }
  else if ($id) {
    db_query("DELETE FROM {access} WHERE aid = %d", $id);
    $output .= status(t("access rule deleted."));
  }

  $header = array(t("type"), t("mask"), t("operations"));
  $result = db_query("SELECT * FROM {access} WHERE type = '%s' AND status = '1' ORDER BY mask", $type);
  while ($rule = db_fetch_object($result)) {
    $rows[] = array(t("Allow"), $rule->mask, array("data" => l(t("delete rule"), "admin/user/access/$type/$rule->aid"), "align" => "center"));
  }

  $result = db_query("SELECT * FROM {access} WHERE type = '%s' AND status = '0' ORDER BY mask", $type);
  while ($rule = db_fetch_object($result)) {
    $rows[] = array(t("Deny"), $rule->mask, l(t("delete rule"), "admin/user/access/$type/$rule->aid"));
  }

  $options = array ("1" => t("Allow"), "0" => t("Deny"));
  $rows[] = array(form_radios(NUll, "status", $edit["status"], $options), form_textfield(NULL, "mask", $edit["mask"], 32, 64), form_submit(t("Add rule")));
  $output .= theme("table", $header, $rows);

  $output .= "<p><small>%: ". t("Matches any number of characters, even zero characters") .".<br />_: ". t("Matches exactly one character.") ."</small></p>";

  if ($type != "user") {
    $title = t("Check e-mail address");
  }
  else {
    $title = t("Check username");
  }
  $output .= form_textfield($title, "test", $edit["test"], 32, 64). form_submit(t("Check"));

  return form($output);
}

function user_roles($membersonly = 0) {
  $result = db_query("SELECT * FROM {role} ORDER BY name");
  while ($role = db_fetch_object($result)) {
    if (!$membersonly || ($membersonly && $role->name != "anonymous user")) {
      $roles[$role->rid] = $role->name;
    }
  }
  return $roles;
}

function user_admin_perm($edit = array()) {
  if ($edit) {

    /*
    ** Save permissions:
    */

    $result = db_query("SELECT * FROM {role} ");
    while ($role = db_fetch_object($result)) {
      // 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);
      $perm = $edit[$role->rid] ? implode(", ", array_keys($edit[$role->rid])) : "";
      if ($perm) {
        db_query("INSERT INTO {permission} (rid, perm) VALUES (%d, '%s')", $role->rid, $perm);
      }
    }
  }

  /*
  ** Compile permission array:
  */

  $perms = module_invoke_all("perm");
  asort($perms);

  /*
  ** Compile role array:
  */

  $result = db_query("SELECT r.rid, p.perm FROM {role} r LEFT JOIN {permission} p ON r.rid = p.rid ORDER BY name");
  $roles = array();
  while ($role = db_fetch_object($result)) {
    $role_perms[$role->rid] = $role->perm;
  }

  $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 roles / permission overview:
  */

  $header = array_merge(array("&nbsp;"), $role_names);

  foreach ($perms as $perm) {
    $row[] = t($perm);
    foreach ($role_names as $rid => $name) {
      $row[] = "<input type=\"checkbox\" name=\"edit[$rid][$perm]\"". (strstr($role_perms[$rid], $perm) ? " checked=\"checked\"" : "") ." />";
    }
    $rows[] = $row;
    unset($row);
  }

  $output = theme("table", $header, $rows);
  $output .= form_submit(t("Save permissions"));

  return form($output);
}

function user_admin_role($edit = array()) {
  $op = $_POST["op"];
  $id = arg(3);

  if ($op == t("Save role")) {
    db_query("UPDATE {role} SET name = '%s' WHERE rid = %d", $edit["name"], $id);
  }
  else if ($op == t("Delete role")) {
    db_query("DELETE FROM {role} WHERE rid = %d", $id);
    db_query("DELETE FROM {permission} WHERE rid = %d", $id);
  }
  else if ($op == t("Add role")) {
    db_query("INSERT INTO {role} (name) VALUES ('%s')", $edit["name"]);
  }
  else if ($id) {
    /*
    ** Display role form:
    */

    $role = db_fetch_object(db_query("SELECT * FROM {role} WHERE rid = %d", $id));

    $output .= form_textfield(t("Role name"), "name", $role->name, 32, 64, t("The name for this role.  Example: 'moderator', 'editorial board', 'site architect'."));
    $output .= form_submit(t("Save role"));
    $output .= form_submit(t("Delete role"));

    $output = form($output);
  }

  if (!$output) {
    /*
    ** Render role overview:
    */

    $result = db_query("SELECT * FROM {role} ORDER BY name");

    $header = array(t("name"), t("operations"));
    while ($role = db_fetch_object($result)) {
      if ($role->name != "anonymous user" && $role->name != "authenticated user") {
        $rows[] = array($role->name, array("data" => l(t("edit role"), "admin/user/role/$role->rid"), "align" => "center"));
      }
      else {
        $rows[] = array($role->name, array("data" => "<span class=\"disabled\">". t("locked") ."</span>", "align" => "center"));
      }
    }
    $rows[] = array("<input type=\"text\" size=\"32\" maxlength=\"64\" name=\"edit[name]\" />", "<input type=\"submit\" name=\"op\" value=\"". t("Add role") ."\" />");

    $output = theme("table", $header, $rows);
    $output = form($output);
  }

  return $output;
}

function user_admin_edit($edit = array()) {
  $op = $_POST["op"];
  $id = arg(3);

  if ($account = user_load(array("uid" => $id))) {

    if ($op == t("Save account")) {
      foreach (module_list() as $module) {
        if (module_hook($module, "user")) {
          $result = module_invoke($module, "user", "edit_validate", $edit, $account);
        }
        if (is_array($result)) {
          $data = array_merge($data, $result);
        }
        elseif (is_string($result)) {
          $error = $result;
          break;
        }
      }

      // TODO: this display/edit/validate should be moved to a new profile module implementing the _user hooks
      if ($error = user_validate_name($edit["name"])) {
        // do nothing
      }
      else if ($error = user_validate_mail($edit["mail"])) {
        // do nothing
      }
      else if (db_num_rows(db_query("SELECT uid FROM {users} WHERE uid != %d AND LOWER(name) = LOWER('%s')", $account->uid, $edit["name"])) > 0) {
        $error = t("The name '%s' is already taken.", array("%s" => $edit["name"]));
      }
      else if ($edit["mail"] && db_num_rows(db_query("SELECT uid FROM {users} WHERE uid != %d AND LOWER(mail) = LOWER('%s')", $account->uid, $edit["mail"])) > 0) {
        $error = t("The e-mail address '%s' is already taken.", array("%s" => $edit["mail"]));
      }

      /*
      ** If required, check that proposed passwords match.  If so,
      ** add new password to $edit.
      */

      if ($edit["pass1"]) {
        if ($edit["pass1"] == $edit["pass2"]) {
          $edit["pass"] = $edit["pass1"];
        }
        else {
          $error = t("The specified passwords do not match.");
        }
      }

      unset($edit["pass1"], $edit["pass2"]);
      if (!$error) {
        $account = user_save($account, array_merge($edit, $data));
        $output .= status(t("user information changes have been saved."));
      }
      else {
        $output .= theme("error", $error);
      }
    }
    else if ($op == t("Delete account")) {
      if ($edit["status"] == 0) {
        db_query("DELETE FROM {users} WHERE uid = %d", $account->uid);
        db_query("DELETE FROM {authmap} WHERE uid = %d", $account->uid);
        $output .= status(t("the account has been deleted."));
      }
      else {
        $error = t("Failed to delete account: the account has to be blocked first.");
        $output .= theme("error", $error);
      }
    }

    if (!$edit) {
      $edit = object2array($account);
    }

    /*
    ** Display user form:
    */

    $output .= form_item(t("User ID"), $account->uid);
    $output .= form_textfield(t("Username"), "name", $account->name, 30, 55, t("Your full name or your preferred username: only letters, numbers and spaces are allowed."));
    $output .= form_textfield(t("E-mail address"), "mail", $account->mail, 30, 55, 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."));

    $output .= implode("\n", module_invoke_all("user", "edit_form", $edit, $account));

    $output .= form_item(t("Password"), "<input type=\"password\" name=\"edit[pass1]\" size=\"12\" maxlength=\"24\" /> <input type=\"password\" name=\"edit[pass2]\" size=\"12\" maxlength=\"24\" />", t("Enter a new password twice if you want to change the current password for this user or leave it blank if you are happy with the current password."));
    $output .= form_radios(t("Status"), "status", $account->status, array(t("Blocked"), t("Active")));
    $output .= form_radios(t("Role"), "rid", $account->rid, user_roles(1));

    $output .= form_submit(t("Save account"));
    $output .= form_submit(t("Delete account"));

    $output = form($output, "post", 0, array("enctype" => "multipart/form-data"));
  }
  else {
    $output = t("No such user");
  }

  return $output;
}

function user_admin_account() {
  $header = array(
    array ("data" => t("ID"), "field" => "u.uid"),
    array ("data" => t("username"), "field" => "u.name"),
    array ("data" => t("status"), "field" => "u.status"),
    array ("data" => t("role"), "field" => "u.rid"),
    array ("data" => t("last access"), "field"  => "u.timestamp", "sort" => "desc"),
    t("operations")
  );
  $sql = "SELECT u.uid, u.name, u.status, u.timestamp, r.name AS rolename FROM {role} r INNER JOIN {users} u ON r.rid = u.rid 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($account->uid, format_name($account), $status[$account->status], $account->rolename, format_date($account->timestamp, "small"), l(t("edit account"), "admin/user/edit/$account->uid"));
  }

  $pager = pager_display(NULL, 50, 0, "admin", tablesort_pager());
  if (!empty($pager)) {
    $rows[] = array(array("data" => $pager, "colspan" => 6));
  }
  return theme("table", $header, $rows);
}

function user_role_init() {
  $role = db_fetch_object(db_query("SELECT * FROM {role} WHERE name = 'anonymous user'"));
  if (!$role) {
    db_query("INSERT INTO {role} (name) VALUES ('anonymous user')");
  }

  $role = db_fetch_object(db_query("SELECT * FROM {role} WHERE name = 'authenticated user'"));
  if (!$role) {
    db_query("INSERT INTO {role} (name) VALUES ('authenticated user')");
  }
}

function user_admin() {
  $op = $_POST["op"];
  $edit = $_POST["edit"];

  if (user_access("administer users")) {
    /*
    ** Initialize all the roles and permissions:
    */

    user_role_init();

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

    switch ($op) {
      case "search":
        $output = search_type("user", url("admin/user/search"), $_POST["keys"]);
        break;
      case t("Add rule"):
      case t("Check"):
      case "access":
        $output .= user_admin_access($edit);
        break;
      case t("Save permissions"):
        $output = status(t("user permissions saved."));
      case "permission":
        $output .= user_admin_perm($edit);
        break;
      case t("Create account"):
      case "create":
        $output = user_admin_create($edit);
        break;
      case t("Add role"):
      case t("Delete role"):
      case t("Save role"):
        $output = status(t("your role changes were saved."));
      case "role":
        $output .= user_admin_role($edit);
        break;
      case t("Delete account"):
      case t("Save account"):
      case "edit":
        $output = user_admin_edit($edit);
        break;
      default:
        if ($op == "account" && arg(3) == "create") {
          $output = user_admin_create($edit);
        }
        else {
          $output = user_admin_account();
        }
    }
    return $output;
  }
}
// the following functions comprise help for admins and developers
function user_help($section = "admin/help#user") {
  $output = "";

  switch ($section) {
    case 'admin/user':
      $output .= 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>");
      $output .= t("<p>Click on either the <i>username</i> or <i>edit account</i> to edit a user's information.</p>");
      $output .= t("<p>Sort accounts by registration time by clicking on the <i>ID</i> header.</p>");
      break;
    case 'admin/user/create':
    case 'admin/user/account/create':
      $output .= t("This web page allows the administrators to register a new users by hand.<br />Note:<ul><li>You cannot have a user where either the e-mail address or the username match another user in the system.</li></ul>");
      break;
    case 'admin/user/access':
      $output .= t("Access rules allow Drupal administrators to choose usernames and e-mail address that are prevented from using drupal. To enter the mask for e-mail addresses click on %e-mail, for the username mask click on %username.", array("%e-mail" => l(t("e-mail rules"), "admin/user/access/mail"), "%username" => l(t("name rules"), "admin/user/access/user")));
      break;
    case 'admin/user/access/mail':
      $output .= t("Setup and test the e-mail access rules. The access function checks if you match a deny and <b>not</b> an allow. If you match <b>only</b> a deny then it is denied. Any other case, such as both a deny and an allow pattern matching, allows the pattern.<br />Notes: <ul><li>To delete a rule click on \"delete rule\".</li><li>The order of the rules does <b>not</b> matter.</li></ul>");
      break;
    case 'admin/user/access/user':
      $output .= t("Setup and test the Username access rules. The access function checks if you match a deny and <b>not</b> an allow. If you do then it is denied. Any other case, such as a deny pattern and an allow pattern, allows the pattern.<br />Notes: <ul><li>To delete a rule click on \"delete rule\".</li><li>The order of the rules does <b>not</b> matter.</li></ul>");
      break;
    case 'admin/user/permission':
      $output .= t("In this area you will define the <b>permissions</b> for each user role (role names are defined on the %role). Each permission describes a fine-grained logical operation, such as being able to access the administration pages, or adding/modifying a user account. You could say a permission represents access granted to a user to perform a set of operations.", array("%role" => l(t("user roles page"), "admin/user/role")));
      break;
    case 'admin/user/role':
      $output .= "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 %permission.  Examples of roles include: anonymous user, authenticated user, moderator, administrator and so on. In this area you will define the <b>names</b> of the various roles. To delete a role choose \"edit role\".<br />By default, Drupal comes with two user roles:";
      $output .= "<ul>";
      $output .= "<li>Anonymous user: this role is used for users that don't have a user account or that are not authenticated.</li>";
      $output .= "<li>Authenticated user: this role is assigned automatically to authenticated users.  Most registered users will belong to this user role unless specified otherwise.</li>";
      $output .= "</ul>";
      $output = t($output, array("%permission" => l(t("user permissions"), "admin/user/permission")));
      break;
    case 'admin/user/search':
      $output .= t("Enter a simple pattern ( '*' may be user as a wildcard match) to search for a username.  For example, one may search for 'br' and Drupal might return 'brian', 'brad', and 'brenda'.");
      break;
    case 'admin/system/modules#description':
      $output .= t("Enables the user registration and login system.");
      break;
    case 'admin/system/modules/user':
      $output .= t("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.");
      break;
    case 'user/help#user':
      $site = variable_get("site_name", "this website");

      $output .= "<h3>Distributed authentication<a id=\"da\"></a></h3>";
      $output .= "<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 <i>Distributed Authentication</i>, and is unique to %drupal, the software which powers %site.</p>";
      $output .= "<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 %delphi-forums. 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 <i>remote.delphiforums.com</i> server behind the scenes (usually using %xml, %http-post, or %soap) 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>";

      $output = t($output, array("%help-links" => (implode(", ", user_auth_help_links())), "%site" => "<i>$site</i>", "%drupal" => "<a href=\"http://www.drupal.org\">Drupal</a>", "%delphi-forums" => "<a href=\"http://www.delphiforums.com\">Delphi Forums</a>", "%xml" => "<a href=\"http://www.xmlrpc.com\">XML-RPC</a>", "%http-post" => "<a href=\"http://www.w3.org/Protocols/\">HTTP POST</a>", "%soap" => "<a href=\"http://www.soapware.org\">SOAP</a>"));

        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");
          }
        }
      break;
    case 'admin/help#user':

      // Start of user_help_admin
      $output .= "<h3>Introduction</h3><p>Drupal offers a powerful access system that allows users to register, login, logout, maintain user profiles, etc. By using \"%user-role\" you can setup fine grained %user-permission allowing each role to do only what you want them to. Each user is assigned to a role. By default there are two roles \"anonymous\" - a user who has not logged in, and \"authorized\" a user who has signed up and who has been authorized. As anonymous users, participants suffer numerous disadvantages, for example they cannot sign their names to nodes, and their moderated posts beginning at a lower score.</p>";
      $output .= "<p>In contrast, those with a user account can use their own name or handle and are granted various privileges: the most important is probably the ability to moderate new submissions, to rate comments, and to fine-tune the site to their personal liking, with saved personal settings.  Drupal themes make fine tuning quite a pleasure.</p>";
      $output .= "<p>Registered users need to authenticate by supplying either a local username and password, or a remote username and password such as a %jabber, %delphiforums, or one from another %drupal website. See %da-auth for more information on this innovative feature.";
      $output .= "The local username and password, hashed with Message Digest 5 (MD5), are stored in your database. When you enter a password it is also hashed with MD5 and compaired with what is in the database. If the hashes match, the username and password are correct. Once a user authenticated session is started, and until that session is over, the user won't have to re-authenticate. To keep track of the individual sessions, Drupal relies on %php-sess. 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. When a visitor accesses your site, Drupal will check whether a specific session ID has been sent with the request. If this is the case, the prior saved environment is recreated.</p>";
      $output .= "<h3>User preferences and profiles</h3><p>Each Drupal user has a profile, and a set of preferences which may be edited by clicking on the %user-prefs link. Of course, a user must be logged into reach those pages. There, users will find a page for changing their preferred time zone, language, username, e-mail address, password, theme, signature, and %da-auth names. Changes made here take effect immediately. Also, administrators may make profile and preferences changes in %admin-user on behalf of their users.</p>";
      $output .= "<p>Module developers are provided several hooks for adding custom fields to the user view/edit pages. These hooks are described in the Developer section of the %da-devel. For an example, see the <code>jabber_user()</code> function in <i>/modules/jabber.module</i>.</p>";
      //end of user_help_admin

      //start of user_help_admin_da
      $output .= "<h3>Distributed authentication<a id=\"da\"></a></h3>";
      $output .= "<p>One of the more tedious moments in visiting a new website is filling out the registration form. The reg form provides helpful information to the website owner, but not much value for the user. The value for the end user is usually the ability to post a messages or receive personalized news, etc. Distributed authentication (DA) gives the user what they want without having to fill out the reg form. Removing this obstacle yields more registered and active users for the website.</p>";
      $output .= "<p>DA enables a new user to input a username and password into the login box and immediately be recognized, even if that user never registered on your site. This works because Drupal knows how to communicate with external registration databases. For example, lets say that your new user 'Joe' is already a registered member of Delphi Forums. If your Drupal has the delphi module installed, then Drupal will inform Joe on the registration and login screens that he may login with his Delphi ID instead of registering with your Drupal instance. Joe likes that idea, and logs in with a username of joe@remote.delphiforums.com and his usual Delphi password. Drupal then communicates with remote.delphiforums.com (usually using %xml, %http-post, or %soap) behind the scenes and asks &quot;is this password for username=joe?&quot; If Delphi replies yes, then Drupal will create a new local account for joe and log joe into it. Joe may keep on logging into your Drupal instance in the same manner, and he will be logged into the same joe@remote.delphiforums.com account.</p>";
      $output .= "<p>One key element of DA is the 'authmap' table, which maps a user's authname (e.g. joe@remote.delphiforums.com) to his local UID (i.e. user identification number). This map is checked whenever a user successfully logs into an external authentication source. Once Drupal knows that the current user is definately joe@remote.delphiforums.com (because Delphi says so), he looks up Joe's UID and logs Joe into that account.</p>";
      $output .= "<p>To disable distributed authentication, simply %dis-module or remove all DA modules. For a virgin install, that means removing/disabling the jabber module and the drupal module.</p>";
      $output .= "<p>Drupal is setup so that it is very easy to add support for any external authentication source. You currently have the following authentication modules installed ...</p>";
      $output .= "%module-list";
      // end of user_help_admin_da

      // start of user_help_devel_da
      $output .= "<h3>Writing distributed authentication modules</h3><p>Drupal is specifically architected to enable easy authoring of new authentication modules. I'll deconstruct the %blogger authentication module, and hopefully provide all the details you'll need to write your own auth module. If you want to download the full text of this module, visit the %blogger-source in the %contrib-cvs.</p>";
      $output .= "<h4>Code review</h4>";
      $output .= "<pre>function blogger_auth(\$name, \$pass, \$server) {
  // user did not present a Blogger ID so don't bother trying.
  if (\$server !== &quot;blogger.com&quot;) {
    return 0;
  }
  //provided to Drupal by Ev@Blogger
  \$appkey = &quot;6D4A2D6811A6E1F75148DC1155D33C0C958107BC&quot;

  \$message = new xmlrpcmsg(&quot;blogger.getUsersBlogs&quot;,
                           array(new xmlrpcval(\$appkey, &quot;string&quot;),
                           new xmlrpcval(\$name, &quot;string&quot;),
                           new xmlrpcval(\$pass, &quot;string&quot;)));
  \$client = new xmlrpc_client(&quot;/api/RPC2&quot;, &quot;plant.blogger.com&quot;);
  // \$client->setDebug(1);
  \$result = \$client-&gt;send(\$message, 5);
  // Since Blogger doesn't return a properly formed FaultCode, we just search for the string 'fault'.
  if (\$result &amp;&amp; !stristr(\$result-&gt;serialize(), &quot;fault&quot;)) {
    // watchdog(\"user\", \"Success Blogger Auth. Response: \" . \$result->serialize());
    return 1;
  }
  else if (\$result) {
    // watchdog(\"user\", \"Blogger Auth failure. Response was \" . \$result->serialize());
    return 0;
  }
  else {
    // watchdog(\"user\", \"Blogger Auth failure. Could not connect.\");
    return 0;
  }
}</pre>";
      $output .= "<p>The <i>_auth</i> function is the heart of any authentication module. This function is called whenever a user is attempting to login using your authentication module. For successful authentications, this function returns TRUE. Otherwise, it returns FALSE. This function always accepts 3 parameters, as shown above. These parameters are passed by the user system (user module). The user system parses the username as typed by the user into 2 substrings - \$name and \$server. The parsing rules are:</p>";
      $output .= "<table border=\"0\" cellspacing=\"4\" cellpadding=\"4\" style=\"margin: auto; width: 80%;\"><tr><th colspan=\"2\" style=\"text-align: left;\">_auth function parameters</th></tr><tr><th>\$name</th><td>The substring before the final <i>'@'</i> character in the username field</td></tr><tr><th>\$pass</th><td>The whole string submitted by the user in the password field</td></tr><tr><th>\$server</th><td>The substring after the final <i>'@'</i> symbol in the username field</td></tr></table>";
      $output .= "<p>So now lets use that \$name, \$pass, and \$server which was passed to our <i>_auth</i> function. Blogger authenticates users via %xml. Your module may authenticate using a different technique. Drupal doesn't reallly care how your module communicates with its registration source. It just <b>trusts</b> the module.</p>";
      $output .= "<p>The lines above illustrate a typical %xml method call. Here we build up a message and send it to Blogger, storing the response in a variable called <i>\$response</i>. The message we pass conforms to the published %blogger-api. Your module will no doubt implement a different API. One peculiarity of this module is that we don't actually use the \$server parameter. Blogger only accepts authentication at <i>plant.blogger.com</i>, so we hard-code that value into the <i>xmlrpc_client()</i> function. A more typical example might be the jabber module, which uses the <i>\$server</i> parameter to determine where to send the authentication request. Also of note is the '5'th parameter in the <i>\$client-&gt;send\(\)</i> call. This is a timeout value in seconds. All authentication modules should implement a timeout on their external calls. This makes sure to return control to the user module if your registration database has become inoperable or unreachable.</p>";
      $output .= "<pre>
  if (\$result &amp;&amp; !stristr(\$result-&gt;serialize(), &quot;fault&quot;)) {
    // watchdog(\"user\", \"Success Blogger Auth. Response: \" . \$result->serialize());
    return 1;
  }
  else if (\$result) {
    // watchdog(\"user\", \"Blogger Auth failure. Response was \" . \$result->serialize());
    return 0;
  }
  else {
    // watchdog(\"user\", \"Blogger Auth failure. Could not connect.\");
    return 0;
  }
</pre>";
      $output .= "<p>This second half of the <i>_auth</i> function examines the <i>\$response</i> from plant.blogger.com and returns a TRUE (1) or FALSE (0) as appropriate. This is a critical decision, so be sure that you have good logic here, and perform sufficient testing for all cases. In the case of Blogger, we search for the string 'fault' in the response. If that string is present, or there is no repsonse, our function returns FALSE. Otherwise, Blogger has returned valid data to our method request and we return TRUE. Note: Everything starting with \"//\" is a comment and is not executed.</p>";
      $output .= "<pre>function blogger_page() {

  print theme(&quot;header&quot;);
  print theme(&quot;box&quot;, &quot;Blogger&quot;, blogger_help(\"user/help\"));
  print theme(&quot;footer&quot;);
}</pre>";
      $output .= "<p>The _page function is not currently used, but it might be in the future. For now, just copy what you see here, substituting your module name for <i>blogger</i>.</p>";
      $output .= "<pre><code>function blogger_help(\$section) {
  \$output = &quot;&quot;;

  switch (\$section) {
    case 'user/help':
      \$site = variable_get(&quot;site_name&quot;, &quot;this web site&quot;);<br />
      \$output .= &quot;&lt;p&gt;You may login to %site using a &lt;b&gt;Blogger ID&lt;/b&gt; and password. A Blogger ID consists of your Blogger username followed by &lt;i&gt;@blogger.com&lt;/i&gt;. So a valid blogger ID is &lt;i&gt;mwlily&lt;/i&gt;@&lt;b&gt;blogger.com&lt;/b&gt;. If you are a Blogger member, go ahead and login now.&lt;/p&gt;&quot;;
      \$output .= &quot&lt;p&gt;Blogger offers you instant communication power by letting you post your thoughts to the web whenever the urge strikes. Blogger will publish to your current web site or help you create one. &lt;a href=\&quot;http://www.blogger.com/about.pyra\&quot;&gt;Learn more about it&lt;/a&gt;.&quot;;
      \$output = t(\$output, array(\"%site\" =&gt; \"&lt;i&gt;\$site&lt;/i&gt;\"));
  }

  return output;
}</code></pre>";
      $output .= "<p>The <i>_help</i> function is prominently linked within Drupal, so you'll want to write the best possible user help here. You'll want to tell users what a proper username looks like and you may also want to advertise a bit about your service at the end. Note that your help text is passed through a t() function in the last line. This is Drupal's localization function. Translators may localize your help text just like any other text in Drupal.</p>";
      $output .= "<h4>Publishing your module</h4><p>Once you've written and tested your authentication module, you'll usually want to share it with the world. The best way to do this is to add the module to the %contrib-cvs. You'll need to request priveleges to this repository - see %cvs for the details. Then you should announce your contribution on the %drupal-lists. You might also want to post a story on %drupal-org.</p>";
      // end of user_help_devel_da

      // start of user_help_devel_userhook
      $output .= "<h3><a id=\"userhook\">module_user()</a></h3><p>The <b>_user()</b> hook provides a mechanism for inserting text and form fields into the %registration, %user-acct, and %user-admin pages. This is useful if you want to add a custom field for your particular community. This is best illustrated by the %profile-module. The profile module is meant to be customized for your needs. Please download it and hack away until it does what you need.</p>";

      $output .= "<p>Consider this simpler example from a fictional recipe community web site called Julia's Kitchen. Julia customizes her Drupal powered site by creating a new file called <i>julia.module</i>. That file does the following:<ul>";
      $output .= "<li>new members must agree to Julia's Privacy Policy on the reg page.</li>";
      $output .= "<li>members may list their favorite ingredients on their public user profile page</li>";
      $output .= "</ul></p>";
      $output .= "<p>Julia achieves this with the following code. The comments below should help you understand what is going on.</p>";

      $output .= "<pre>
function julia_user(\$type, \$edit, &\$user) {
    // What type of registration action are we taking?
    switch (\$type) {
      case t(\"register_form\"):
        // Add two items to the resigtration form.
        \$output .= form_item(\"Privacy Policy\",
                             \"Julia would never sell your user information. She is just a nice \".
                             \"old French chef who lives near me in Cambridge, Massachussetts USA.\");
        \$output .= form_checkbox(\"Accept <i>Julia's Kitchen</i> privacy policy.\",
                                 julia_accept, 1, \$edit[\"julia_accept\"]);
        return \$output;
      case t(\"register_validate\"):
        // The user has filled out the form and checked the \"accept\" box.
        if (\$edit[\"julia_accept\"] == \"1\") {
          // on success return the values you want to store
          return array(\"julia_accept\" => 1);
        }
        else {
          // on error return an error message
          return \"You must accept the Julia's Kitchen privacy policy to register.\";
        }
      case t(\"view_public\"):
        // when others look at user data
        return form_item(\"Favorite Ingredient\", \$user->julia_favingredient);
      case t(\"view_private\"):
        // when user tries to view his own user page.
        return form_item(\"Favorite Ingredient\", \$user->julia_favingredient);
      case t(\"edit_form\"):
        // when user tries to edit his own user page.
        return form_textfield(\"Favorite Ingredient\", \"julia_favingredient\",
                             \$user->julia_favingredient, 50, 65,
                             \"Tell everyone your secret spice\");
      case t(\"edit_validate\"): // Make sure the data they edited is \"valid\".
        return user_save(\$user, array(\"julia_favingredient\" => \$edit[\"julia_favingredient\"]));
    }
  }
</pre>";
      // end of user_help_devel_userhook
      $output = t($output, array("%user-role" => l(t("roles"), "admin/user/role"), "%user-permission" => l(t("permission"), "admin/user/permission"), "%jabber" => "<a href=\"http://www.jabber.org\">jabber</a>", "%delphiforums" => "<a href=\"http://www.delphiforums.com/\">Delphi Forums</a>", "%drupal" => "<a href=http:\"http://www.drupal.org/\">Drupal</a>", "%da-auth" => l(t("distributed authentication"), "user/help#da"), "%php-sess" => "<a href=\"http://www.php.net/manual/en/ref.session.php\">". t("PHP's session support") ."</a>", "%user-prefs" => l(t("my account"), "user/edit"), "%admin-user" => l(t("administer") ." &raquo; ". t("accounts") ." &raquo; ". t("users"), "admin/user"), "%da-devel" => "<a href=\"http://www.drupal.org/node/view/316\">". t("Drupal documentation") ."</a>", "%xml" => "<a href=\"http://www.xmlrpc.org\">XML-RPC</a>", "%http-post" => "<a href=\"http://www.w3.org/Protocols/\">HTTP POST</a>", "%soap" => "<a href=\"http://www.soapware.org\">SOAP</a>", "%dis-module" => l(t("disable"), "admin/system/modules"), "%blogger" => "<a href=\"http://www.blogger.com\">Blogger</a>", "%blogger-source" => "<a href=\"http://cvs.drupal.org/viewcvs.cgi/contributions/modules/authentication/Bloggar/?cvsroot=contrib\">". t("Bloggar source") ."</a>", "%contrib-cvs" => "<a href=\"http://cvs.drupal.org/veiwcvs/contributions/?cvsroot=contrib\">". t("Drupal contributions CVS repository") ."</a>", "%blogger-api" => "<a href=\"http://plant.blogger.com/API\">". t("Blogger XML-RPC Application Programmers Interface (API)") ."</a>", "%cvs" => "<a href=\"http://cvs.drupal.org/viewcvs.cgi/contributions/README?rev=HEAD&amp;cvsroot=contrib&amp;content-type=text/vnd.viewcvs-markup\">the CVS README file</a>", "%drupal-lists" => "<a href=\"http://drupal.org/mailing-lists\">drupal-devel and drupal-support mailing lists</a>", "%drupal-org" => "<a href=\"http://www.drupal.org\">Drupal.org</a>", "%registration" => l(t("registration"), "user/register"), "%user-acct" => l(t("user account view/edit"), "user"), "%user-admin" => l(t("administer") ." &raquo; ". t("acounts"), "admin/user"), "%profile-module" => "<a href=\"http://cvs.drupal.org/viewcvs/drupal/modules/profile.module\">profile module</a>"));

      foreach (module_list() as $module) {
        if (module_hook($module, "auth")) {
          $output = strtr($output, array("%module-list" => "<h4>". module_invoke($module, "info", "name") ."</h4>\n%module-list"));
          $output = strtr($output, array("%module-list" => module_invoke($module, "help", "user/help") . "\n%module-list"));
        }
      }
      $output = strtr($output, array("%module-list" => ""));
      break;
  }

  return $output;
}

?>