user.module 85.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
<?php
// $Id$

session_set_save_handler("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc");
session_start();

/*** Session functions *****************************************************/

function sess_open($save_path, $session_name) {
  return 1;
}

function sess_close() {
  return 1;
}

function sess_read($key) {
  global $user;
19 20 21

  $result = db_query_range("SELECT u.*, s.*, r.name AS role FROM {users} u INNER JOIN {role} r ON u.rid = r.rid INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = '". check_query($key) ."' AND u.status < 3", 0, 1);
  $user = db_fetch_object($result);
22 23 24 25 26 27 28
  if ($user->data && $data = unserialize($user->data)) {
    foreach ($data as $key => $value) {
      if (!isset($user->$key)) {
        $user->$key = $value;
      }
    }
  }
29

30
  return !empty($user->session) ? $user->session : '';
31 32 33
}

function sess_write($key, $value) {
Dries's avatar
Dries committed
34 35 36
  global $user;

  db_query("UPDATE {sessions} SET uid = %d, hostname = '%s', session = '%s', timestamp = %d WHERE sid = '$key'", $user->uid, $_SERVER["REMOTE_ADDR"], $value, time());
37

Dries's avatar
Dries committed
38 39 40
  if (!db_affected_rows()) {
    db_query("INSERT INTO {sessions} (uid, sid, hostname, session, timestamp) values(%d, '%s', '%s', '%s', %d)", $user->uid, $key, $_SERVER["REMOTE_ADDR"], $value, time());
  }
Dries's avatar
Dries committed
41

42 43 44 45 46
  return '';
}

function sess_destroy($key) {

47 48
  db_query("DELETE FROM {sessions} WHERE sid = '$key'");

49 50 51
}

function sess_gc($lifetime) {
52 53 54 55 56 57 58 59 60 61

  /*
  **  Be sure to adjust 'php_value session.gc_maxlifetime' to a large enough
  **   value.  For example, if you want user sessions to stay in your database
  **   for three weeks before deleting them, you need to set gc_maxlifetime
  **   to '1814400'.  At that value, only after a user doesn't log in after
  **   three weeks (1814400 seconds) will his/her session be removed.
  */
  db_query("DELETE FROM {sessions} WHERE timestamp < %d", time() - $lifetime);

62
  return 1;
63

64 65 66 67 68
}

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

function user_external_load($authname) {
69
  $arr_uid = db_query("SELECT uid FROM {authmap} WHERE authname = '%s'", $authname);
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85

  if (db_fetch_object($arr_uid)) {
    $uid = db_result($arr_uid);
    return user_load(array("uid" => $uid));
  }
  else {
    return 0;
  }
}

function user_load($array = array()) {

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

Dries's avatar
Dries committed
86 87
  $query = "";

88 89
  foreach ($array as $key => $value) {
    if ($key == "pass") {
Kjartan's avatar
Kjartan committed
90
      $query .= "u.$key = '". md5($value) ."' AND ";
91
    }
92
    else {
93
      $query .= "u.$key = '". check_query($value) ."' AND ";
94 95
    }
  }
96
  $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);
97 98

  $user = db_fetch_object($result);
99
  if ($user->data && $data = unserialize($user->data)) {
100 101 102 103 104 105
    foreach ($data as $key => $value) {
      if (!isset($user->$key)) {
        $user->$key = $value;
      }
    }
  }
106 107 108 109 110 111 112 113 114

  return $user;
}

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

Kjartan's avatar
Kjartan committed
115
  $user_fields = user_fields();
116
  if ($account->uid) {
117
    $data = unserialize(db_result(db_query("SELECT data FROM {users} WHERE uid = %d", $account->uid)));
118 119
    foreach ($array as $key => $value) {
      if ($key == "pass") {
120 121
        $query .= "$key = '%s', ";
        $v[] = md5($value);
122 123
      }
      else if (substr($key, 0, 4) !== "auth") {
Kjartan's avatar
Kjartan committed
124
        if (in_array($key, $user_fields)) {
125 126
          // escape '%'s:
          $value = str_replace("%", "%%", $value);
127 128
          $query .= "$key = '%s', ";
          $v[] = $value;
129 130 131 132
        }
        else {
          $data[$key] = $value;
        }
133 134
      }
    }
135 136
    $query .= "data = '%s', ";
    $v[] = serialize($data);
137

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

    $user = user_load(array("uid" => $account->uid));
  }
  else {
    $array["timestamp"] = time();
Dries's avatar
Dries committed
144
    $array["uid"] = db_next_id("users_uid");
145 146 147 148

    foreach ($array as $key => $value) {
      if ($key == "pass") {
        $fields[] = check_query($key);
149 150
        $values[] = md5($value);
        $s[] = "'%s'";
151 152
      }
      else if (substr($key, 0, 4) !== "auth") {
Kjartan's avatar
Kjartan committed
153
        if (in_array($key, $user_fields)) {
154
          $fields[] = check_query($key);
155 156
          $values[] = $value;
          $s[] = "'%s'";
157 158 159 160
        }
        else {
          $data[$key] = $value;
        }
161 162 163
      }
    }

164
    $fields[] = "data";
165 166
    $values[] = serialize($data);
    $s[] = "'%s'";
167

168
    db_query("INSERT INTO {users} (". implode(", ", $fields) .") VALUES (". implode(", ", $s) .")", $values);
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

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

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

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

  return $user;
}

function user_set($account, $key, $value) {
  $account->data[$key] = $value;
  return $account;
}

function user_get($account, $key) {
  return $account->data[$key];
}

function user_validate_name($name) {

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

201 202 203 204
  if (!$name) return t("You must enter a username.");
  if (ereg("^ ", $name)) return t("The username cannot begin with a space.");
  if (ereg(" \$", $name)) return t("The username cannot end with a space.");
  if (ereg("  ", $name)) return t("The username cannot contain multiple spaces in a row.");
205
  if (ereg("[^ a-zA-Z0-9@_\.\-]", $name)) return t("The username contains an illegal character.");
206
  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.");
Dries's avatar
Dries committed
207
  if (strlen($name) > 56) return t("The username '%name' is too long: it must be less than 56 characters.", array("%name" => $name));
208 209 210 211
}

function user_validate_mail($mail) {

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

217
function user_validate_authmap($account, $authname, $module) {
218
  $result = db_query("SELECT COUNT(*) from {authmap} WHERE uid != %d AND authname = '%s'", $account->uid, $authname);
219 220 221 222
  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>"));
  }
223 224
}

225
function user_password($length = 10) {
226 227

  /*
228
  ** Generate a random alphanumeric password.
229 230
  */

231 232 233 234 235 236 237 238 239
  // 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:
240
  mt_srand((double)microtime() * 1000000);
241 242 243 244 245 246 247 248 249 250 251 252 253

  // 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;
254 255 256 257 258 259
}

function user_access($string) {

  global $user;
  static $perm;
260
  static $cache;
261

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

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

272
  if (!$cache) {
273
    if ($user->uid) {
274
      $perm = db_result(db_query("SELECT p.perm FROM {role} r, {permission} p WHERE r.rid = p.rid AND name = '%s'", $user->role), 0);
275 276
    }
    else {
277
      $perm = db_result(db_query("SELECT p.perm FROM {role} r, {permission} p WHERE r.rid = p.rid AND name = 'anonymous user'"), 0);
278
    }
279 280 281 282 283 284 285

    /*
    ** We use a separate $cache variable because $perm might be empty when a
    ** user has no access rights.
    */

    $cache = 1;
286 287
  }

288
  return strstr($perm, $string);
289 290 291 292 293
}

function user_mail($mail, $subject, $message, $header) {
  if (variable_get("smtp_library", "") && file_exists(variable_get("smtp_library", ""))) {
    include_once variable_get("smtp_library", "");
294
    return user_mail_wrapper($mail, $subject, $message, $header);
295 296
  }
  else {
297 298 299 300 301 302 303
    /*
    ** 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.
304 305 306 307 308 309 310 311 312 313 314 315
    **
    ** 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
    **
316
    */
317 318 319 320
    return mail(
      $mail,
      user_mail_encode($subject),
      str_replace("\r", "", $message),
Kjartan's avatar
Kjartan committed
321
      "MIME-Version: 1.0\nContent-type: text/plain; charset=UTF-8; format=flowed\nContent-transfer-encoding: 8Bit\n" . $header
322
    );
323 324 325
  }
}

Kjartan's avatar
Kjartan committed
326 327 328 329 330
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
Kjartan's avatar
Kjartan committed
331 332 333 334 335 336 337 338
  **
  ** 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.
Kjartan's avatar
Kjartan committed
339
  */
Kjartan's avatar
Kjartan committed
340 341 342
  $chunk_size = 75 - 7 - strlen($charset);
  $chunk_size -= $chunk_size % 4;
  $string = trim(chunk_split(base64_encode($string), $chunk_size, "\n"));
Kjartan's avatar
Kjartan committed
343 344
  $string = trim(preg_replace('/^(.*)$/m', " =?$charset?B?\\1?=", $string));
  return $string;
345 346
}

347 348
function user_deny($type, $mask) {

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

351
  $deny = db_fetch_object(db_query("SELECT * FROM {access} WHERE status = '0' AND type = '%s' AND LOWER('%s') LIKE LOWER(mask)", $type, $mask));
352 353 354 355 356 357 358 359 360

  if ($deny && !$allow) {
    return 1;
  }
  else {
    return 0;
  }
}

361 362
function user_fields() {
  static $fields;
363

364
  if (!$fields) {
365
    $result = db_query("SELECT * FROM {users} WHERE uid = 1");
Kjartan's avatar
Kjartan committed
366 367 368
    if (db_num_rows($result)) {
      $fields = array_keys(db_fetch_array($result));
    }
369
  }
370

Kjartan's avatar
Kjartan committed
371
  // Make sure we return the default fields at least
372
  return is_array($fields) ? $fields: array("uid", "name", "pass", "mail", "mode", "sort", "threshold", "theme", "signature", "timestamp", "status", "timezone", "language", "init", "data", "rid");
373 374
}

375 376 377 378 379 380 381
/*** Module hooks **********************************************************/

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

function user_search($keys) {
382

383
  $result = db_query_range("SELECT * FROM {users} WHERE name LIKE '%". check_query($keys) ."%'", 0, 20);
384
  while ($account = db_fetch_object($result)) {
385
    $find[$i++] = array("title" => $account->name, "link" => (strstr(request_uri(), "admin") ? url("admin/user/edit/$account->uid") : url("user/view/$account->uid")), "user" => $account->name);
386 387 388 389
  }
  return $find;
}

Dries's avatar
Dries committed
390
function user_block($op = "list", $delta = 0) {
391 392 393
  global $user;

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

Dries's avatar
Dries committed
395
  if ($op == "list") {
396
     $blocks[0]["info"] = t("User login");
397
     $blocks[1]["info"] = t("Navigation");
398
     $blocks[2]["info"] = t("Who's new");
399

400
     return $blocks;
401 402
  }
  else {
Dries's avatar
Dries committed
403 404
    switch ($delta) {
      case 0:
405
        if (!$user->uid) {
406 407 408 409 410 411 412 413 414
          /*
          ** For usability's sake, avoid showing two login forms on one
          ** page.
          */

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

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

417
          /*
Dries's avatar
Dries committed
418 419
          ** Save the referer.  We record where the user came from such
          ** that we/ can redirect him after having completed the login
420 421
          ** form.
          */
Dries's avatar
Dries committed
422

423
          if (empty($edit)) {
424
            $edit["destination"] = url($_GET["q"]);
425 426
          }
          // 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.
Dries's avatar
Dries committed
427

428 429 430
          $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);
Dries's avatar
Dries committed
431 432

          if (variable_get("user_remember", 0) == 0) {
433
            $form .= form_checkbox(t("Remember me"), "remember_me", 1, 0, 0);
Dries's avatar
Dries committed
434 435
          }
          elseif (variable_get("user_remember", 1) == 1) {
436
            $form .= form_hidden("remember_me", 1);
Dries's avatar
Dries committed
437
          }
438

439 440 441 442 443
          $form .= form_submit(t("Log in"));

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

          $output .= "</div>\n";
Dries's avatar
Dries committed
444

Dries's avatar
Dries committed
445
          if (variable_get("user_register", 1)) {
Dries's avatar
Dries committed
446
            $items[] = l(t("Create new account"), "user/register", array("title" => t("Create a new user account.")));
Dries's avatar
Dries committed
447
          }
Dries's avatar
Dries committed
448
          $items[] = l(t("Request new password"), "user/password", array("title" => t("Request new password via e-mail.")));
Dries's avatar
Dries committed
449

450
          $output .= theme("theme_item_list", $items);
451

452
          $block["subject"] = t("User login");
453
          $block["content"] = "<div class=\"user-login-link\">$output</div>";
Dries's avatar
Dries committed
454
        }
Dries's avatar
Dries committed
455
        return $block;
456
      case 1:
457 458 459 460 461
        if ($menu = menu_tree()) {
           $block["subject"] = $user->uid ? $user->name : t("Navigation");
           $block["content"] = "<div id=\"menu\">". $menu ."</div>";
        }

462
        return $block;
Dries's avatar
Dries committed
463
      case 2:
464 465 466 467 468
        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");
          }
Dries's avatar
Dries committed
469

470
          $output = theme("theme_user_list", $items);
Dries's avatar
Dries committed
471

472 473 474 475
          $block["subject"] = t("Who's new");
          $block["content"] = $output;
          return $block;
        }
Dries's avatar
Dries committed
476 477
    }
  }
478 479
}

480
function theme_user_list($items, $title = NULL) {
481
  return theme("theme_item_list", $items, $title);
482 483
}

484
function theme_menu_list($items, $title = NULL) {
485
  return theme("theme_item_list", $items, $title);
486 487
}

488
function user_link($type) {
Dries's avatar
Dries committed
489 490 491

  $links = array();

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

496
  if ($type == "system") {
Dries's avatar
Dries committed
497 498
    global $user;
    if ($user->uid) {
499 500
      menu("user/edit", t("my account"), "user_page", 8);
      menu("user/logout", t("log out"), "user_page", 10);
Dries's avatar
Dries committed
501
    }
502
    if (user_access("administer users")) {
503 504 505
      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);
506 507
      menu("admin/user/access/mail", t("e-mail rules"), "user_admin");
      menu("admin/user/access/user", t("name rules"), "user_admin");
508 509 510 511 512
      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
513
    }
514 515
  }

Dries's avatar
Dries committed
516
  return $links;
517 518 519 520
}

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

521
function user_get_authname($account, $module) {
522 523

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

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

531

532 533 534 535 536 537 538
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.
  */

539
  $result = db_query("SELECT authname, module FROM {authmap} WHERE authname = '%s'", $authname);
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
  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) {
555
      $result = db_query("SELECT COUNT(*) from {authmap} WHERE uid = %d AND module = '%s'", $account->uid, $module["1"]);
556
      if (db_result($result) == 0) {
557
        $result = db_query("INSERT INTO {authmap} (authname, uid, module) VALUES ('%s', %d, '%s')", $value, $account->uid, $module[1]);
558 559
      }
      else {
560
        $result = db_query("UPDATE {authmap} SET authname = '%s' WHERE uid = %d AND module = '%s'", $value, $account->uid, $module["1"]);
561 562 563
      }
    }
    else {
564
      $result = db_query("DELETE FROM {authmap} WHERE uid = %d AND module = '%s'", $account->uid, $module["1"]);
565 566 567 568 569 570
    }
  }
  return $result;
}

function user_auth_help_links() {
571
  $links = array();
572
  foreach (module_list() as $module) {
573
    if (module_hook($module, "auth")) {
Dries's avatar
Dries committed
574
      $links[] = l(module_invoke($module, "info", "name"), "user/help#$module");
575 576 577 578 579 580 581
    }
  }
  return $links;
}

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

582
function user_login($edit = array(), $msg = "") {
583
  global $user, $base_url;
584 585 586 587 588 589

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

  if ($user->uid) {
Dries's avatar
Dries committed
590
    drupal_goto(url("user"));
591 592 593
  }

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

    /*
599
    ** Try to log in the user locally:
600 601
    */

Dries's avatar
Dries committed
602
    if (!$user->uid) {
603 604
      $name = $edit["name"];
      $pass = $edit["pass"];
605 606 607 608 609 610 611 612
      $user = user_load(array("name" => $name, "pass" => $pass, "status" => 1));
    }

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

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

618 619 620 621
    /*
    ** When possible, determine corrosponding external auth source. Invoke source, and login user if successful:
    */

Dries's avatar
Dries committed
622
    if (!$user->uid && $server && $result = user_get_authmaps("$name@$server")) {
623 624
      if (module_invoke(key($result), "auth", $name, $pass, $server)) {
        $user = user_external_load("$name@$server");
625
        watchdog("user", "external load: $name@$server, module: ". key($result));
626 627
      }
      else {
628
        $error = t("Invalid password for %s.", array("%s" => "<i>$name@$server</i>"));
629 630 631 632 633 634 635
      }
    }

     /*
    ** Try each external authentication source in series. Register user if successful.
    */

Dries's avatar
Dries committed
636
    else if (!$user->uid && $server) {
637 638 639 640
      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
Dries's avatar
Dries committed
641
              $user = user_save("", array("name" => "$name@$server", "pass" => user_password(), "init" => "$name@$server", "status" => 1, "authname_$module" => "$name@$server", "rid" => _user_authenticated_id()));
642
              watchdog("user", "new user: $name@$server ($module ID)", l(t("edit user"), "admin/user/edit/$user->uid"));
643 644 645 646 647 648 649 650 651 652
              break;
            }
          }
        }
      }
    }

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

Dries's avatar
Dries committed
653 654
      // update the user table timestamp noting user has logged in
      db_query("UPDATE {users} SET timestamp = '%d' WHERE uid = '%s'", time(), $user->uid);
655 656 657 658 659 660

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

661
      $path = preg_replace("/.+\/\/[^\/]+(.*)/", "\$1/", $base_url);
662
      if ($edit["remember_me"]) {
663
        setcookie(session_name(), session_id(), time() + 3600 * 24 * 365, $path);
Dries's avatar
Dries committed
664
      }
665
      else {
666
        setcookie(session_name(), session_id(), FALSE, $path);
667 668 669
      }

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

673
      drupal_goto($edit["destination"]);
674 675 676
    }
    else {
      if (!$error) {
Dries's avatar
Dries committed
677
        $error = t("Sorry.  Unrecognized username or password.") ." ". l(t("Have you forgotten your password?"), "user/password");
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
      }
      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) {
693
    $output .= theme("theme_error", $error);
694 695
  }

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

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

706 707 708 709
  /*
  ** Display login form:
  */

710 711 712
  if ($msg) {
    $output .= "<p>$msg</p>";
  }
713
  if (count(user_auth_help_links()) > 0) {
714
    $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()))));
715 716
  }
  else {
717
    $output .= form_textfield(t("Username"), "name", $edit["name"], 30, 64, t("Enter your %s username.", array("%s" => variable_get("site_name", "local"))));
718
  }
719
  $output .= form_password(t("Password"), "pass", $pass, 30, 64, t("Enter the password that accompanies your username."));
720
  $output .= form_checkbox(t("Remember me"), "remember_me", 1, 0, 0);
721
  $output .= form_submit(t("Log in"));
722
  $items[] = l(t("Request new password"), "user/password");
723
  if (variable_get("user_register", 1)) {
724
    $items[] = l(t("Create new account"), "user/register");
725
  }
726
  $output .= theme("theme_item_list", $items);
727

Dries's avatar
Dries committed
728
  return form($output, "post", url("user"));
729 730
}

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

735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
function user_logout() {
  global $user;

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

    /*
    ** Destroy the current session:
    */

    session_destroy();
    unset($user);
  }

  /*
  ** Redirect the user to his personal information page:
  */

753
  drupal_goto(url());
754 755 756 757 758

}

function user_pass($edit = array()) {

759 760
  global $base_url;

Kjartan's avatar
Kjartan committed
761
  if ($edit["name"]) {
762
    $account = db_fetch_object(db_query("SELECT uid, name, mail FROM {users} WHERE name = '%s'", $edit["name"]));
763
    if (!$account) $error = t("Sorry. The username <i>%s</i> is not recognized.", array("%s" => $edit["name"]));
764
  }
Kjartan's avatar
Kjartan committed
765
  else if ($edit["mail"]) {
766
    $account = db_fetch_object(db_query("SELECT uid, name, mail FROM {users} WHERE mail = '%s'", $edit["mail"]));
767
    if (!$account) $error = t("Sorry. The e-mail address <i>%s</i> is not recognized.", array("%s" => $edit["mail"]));
Kjartan's avatar
Kjartan committed
768 769
  }
  if ($account) {
770

771
      $from = variable_get("site_mail", ini_get("sendmail_from"));
772 773 774 775 776 777 778 779 780 781 782 783
      $pass = user_password();

      /*
      ** Save new password:
      */

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

      /*
      ** Mail new password:
      */

784
      $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()));
785 786
      $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);
787
      $headers = "From: $from\nReply-to: $from\nX-Mailer: Drupal\nReturn-path: $from\nErrors-to: $from";
788
      $mail_success = user_mail($account->mail, $subject, $body, $headers);
789

790 791 792 793 794 795 796 797
      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.");
      }
798 799
    }
    else {
800

Kjartan's avatar
Kjartan committed
801 802
    // Display error message if necessary.
    if ($error) {
803
      $output .= theme("theme_error", $error);
804 805 806 807 808 809
    }

    /*
    ** Display form:
    */

810
    $output .= "<p>". sprintf(t("Enter your username %sor%s your e-mail address."), "<b><i>", "</i></b>") ."</p>";
811 812 813
    $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"));
814
    $items[] = l(t("Log in"), "user/login");
815
    if (variable_get("user_register", 1)) {
816
      $items[] = l(t("Create new account"), "user/register");
817
    }
818
    $output .= theme("theme_item_list", $items);
819

Dries's avatar
Dries committed
820
    return form($output, "post", url("user"));
821 822 823 824
  }
}

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

827
  $edit = $_POST["edit"];
828 829 830 831 832
  /*
  ** If we are already logged on, go to the user page instead.
  */

  if ($user->uid) {
Dries's avatar
Dries committed
833
    drupal_goto(url("user/edit"));
834
  }
835 836 837 838 839 840 841 842 843

  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"])) {
844
      $error = t("The name '%s' has been denied access.", array("%s" => $edit["name"]));
845 846
    }
    else if (user_deny("mail", $edit["mail"])) {
847
      $error = t("The e-mail address '%s' has been denied access.", array("%s" => $edit["mail"]));
848
    }
849
    else if (db_num_rows(db_query("SELECT name FROM {users} WHERE LOWER(name) = LOWER('%s')", $edit["name"])) > 0) {
850
      $error = t("The name '%s' is already taken.", array("%s" => $edit["name"]));
851
    }
852
    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) {
853
      $error = t("The e-mail address '%s' is already taken.", array("%s" => $edit["mail"]));
854
    }
855
    else if (variable_get("user_register", 1) == 0) {
856 857 858
      $error = t("Public registrations have been disabled by the site administrator.");
    }
    else {
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
      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;
      }
874 875 876 877 878
    }
  }

  if ($success) {

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

882
    // create new user account, noting whether administrator approval is required
883 884 885
    user_role_init();
    // TODO: is this necessary? Won't session_write replicate this?
    unset($edit["session"]);
886
    $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));
887
    watchdog("user", "new user: '". $edit["name"] ."' &lt;". $edit["mail"] ."&gt;", l(t("edit user"), "admin/user/edit/$account->uid"));
888

889
    $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()));
890

891
    //the first user may login immediately, and receives a customized welcome e-mail.
892
    if ($account->uid == 1) {
Dries's avatar
Dries committed
893
      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");
894
      // 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
895
      $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>";
896
      $output .= form_hidden("destination", url("user/edit"));
897
      $output .= form_hidden("name", $account->name);
898 899 900 901 902
      $output .= form_hidden("pass", $pass);
      $output .= form_submit(t("Log in"));
      return form($output);
    }
    else {
903 904 905 906 907
      if ($account->status) {
        /*
        ** Create new user account, no administrator approval required:
        */

908 909
        $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);
910 911 912 913 914 915 916
        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:
        */
917 918
        $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);
919
        user_mail($edit["mail"], $subject, $body, "From: $from\nReply-to: $from\nX-Mailer: Drupal\nReturn-path: $from\nErrors-to: $from");
920
        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");
921
        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.");
922
      }
923
    }
924 925 926
  }
  else {
    if ($error) {
927
      $output .= theme("theme_error", $error);
928
    }
929
  }
930

931
  // display the registration form
932
  $output .= variable_get("user_registration_help", "");
933
  $affiliates = user_auth_help_links();
934
  if (count($affiliates) > 0) {
935
    $affiliates = implode(", ", $affiliates);
936
    $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>";
937
  }
938
  $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."));
939 940 941 942
  $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);
943
    }
944
  }
945
  $output .= form_submit(t("Create new account"));
946
  $items[] = l(t("Request new password"), "user/password");
947 948
  $items[] = l(t("Log in"), "user/login");
  $output .= theme("theme_item_list", $items);
Kjartan's avatar
Kjartan committed
949

950
  return form($output);
951 952
}

Kjartan's avatar
Kjartan committed
953 954

function user_delete() {
955 956
  global $user;

957
  $edit = $_POST["edit"];
958

Kjartan's avatar
Kjartan committed
959
  if ($edit["confirm"]) {
960
    watchdog("user", "$user->name deactivated her own account.");
961
    db_query("UPDATE {users} SET mail = 'deleted', status = '0' WHERE uid = %d", $user->uid);
Kjartan's avatar
Kjartan committed
962 963 964
    $output .= t("Your account has been deactivated.");
  }
  else {
965
    $output .= form_item(t("Confirm Deletion"), t("You are about to deactivate your own user account. In addition, your e-mail address will be removed from the database."));
Kjartan's avatar
Kjartan committed
966 967 968 969 970 971 972
    $output .= form_hidden("confirm", 1);
    $output .= form_submit(t("Delete account"));
    $output = form($output);
  }
  return $output;
}

973
function user_edit($edit = array()) {
974
  global $user;
975 976 977 978 979 980 981 982 983

  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
      }
984
      else if (db_num_rows(db_query("SELECT uid FROM {users} WHERE uid != '$user->uid' AND LOWER(name) = LOWER('%s')", $edit["name"])) > 0) {
985
        $error = t("The name '%s' is already taken.", array("%s" => $edit["name"]));
986
      }
987
      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) {
988
        $error = t("The e-mail address '%s' is already taken.", array("%s" => $edit["mail"]));
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
      }
      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"]);

Dries's avatar
Dries committed
1006 1007 1008 1009 1010 1011
        /*
        ** Validate input fields to make sure users don't submit
        ** invalid form data.
        */

        if (!user_access("administer users")) {
1012
           if (array_intersect(array_keys($edit), array("rid", "init", "session"))) {
Dries's avatar
Dries committed
1013 1014 1015 1016 1017 1018 1019
             watchdog("warning", "detected malicious attempt to alter a protected database field");
           }

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

1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
        /*
        ** 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;
          }
        }

1039 1040 1041 1042
        if (!$error) {
          /*
          ** Save user information:
          */
1043

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

1046
          $output .= status(t("Your user information changes have been saved."));
1047
        }
1048 1049 1050 1051
      }
    }

    if ($error) {
1052
      $output .= theme("theme_error", $error);
1053 1054
    }

Kjartan's avatar
Kjartan committed
1055 1056 1057 1058
    if (!$edit) {
      $edit = object2array($user);
    }

1059
    $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."));
Kjartan's avatar
Kjartan committed
1060
    $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."));
1061

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

1064
    $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."));
1065
    $output .= form_submit(t("Save user information"));
1066

1067
    $output = form($output, "post", 0, "enctype=\"multipart/form-data\"");
Dries's avatar
Dries committed
1068
      // the "enctype" attribute is required to upload files such as avatars