data && $data = unserialize($user->data)) {
foreach ($data as $key => $value) {
if (!isset($user->$key)) {
$user->$key = $value;
}
}
}
return !empty($user->session) ? $user->session : '';
}
function sess_write($key, $value) {
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());
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());
}
return '';
}
function sess_destroy($key) {
db_query("DELETE FROM {sessions} WHERE sid = '$key'");
}
function sess_gc($lifetime) {
/*
** 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);
return 1;
}
/*** Common functions ******************************************************/
function user_external_load($authname) {
$arr_uid = db_query("SELECT uid FROM {authmap} WHERE authname = '%s'", $authname);
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:
*/
$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) {
$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:
*/
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.");
if (ereg("[^ a-zA-Z0-9@_\.\-]", $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" => "$authname"));
}
}
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;
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) {
if ($user->uid) {
$perm = db_result(db_query("SELECT p.perm FROM {role} r, {permission} p WHERE r.rid = p.rid AND name = '%s'", $user->role), 0);
}
else {
$perm = db_result(db_query("SELECT p.perm FROM {role} r, {permission} p WHERE r.rid = p.rid AND name = 'anonymous user'"), 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
);
}
}
// Original code by $msg ". sprintf(t("Enter your username %sor%s your e-mail address."), "", "") ." 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. Your password is $pass. You may change your password on the next page. Please login below. " . 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)) ." %: " . t("Matches any number of characters, even zero characters") . ". One of the more tedious moments in visiting a new website is filling out the
registration form. Here at %s, you do not have to fill out a registration form
if you are already a member of ";
$output .= implode(", ", user_auth_help_links());
$output .= ". This capability is called Distributed
Authentication, and is unique to Drupal,
the software which powers %s. 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 %s. 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 %s. Joe likes that idea, and logs in with a username
of joe@remote.delphiforums.com and his usual Delphi password. Drupal then contacts
the remote.delphiforums.com server behind the scenes (usually using XML-RPC,
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 %s in the same manner, and he will always be logged into the
same account. Drupal offers a powerful access system that allows users to register, login, logout, maintain user profiles, etc. By using \"". l ("roles", "admin/user/role") ."\" you can setup fine grained ". l("permissions", "admin/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. 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. Registered users need to authenticate by supplying either a local username and password, or a remote username and password such as a ". l("jabber", "www.jabber.org") .", ". l("Delphi", "www.delphiforums.com") .", or one from another ". l("Drupal", "www.drupal.org") ." website. See ". l("distributed authentication", "#da") ." 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 ". l("PHP's session support", "www.php.net/manual/en/ref.session.php") .". 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's side. 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. Each Drupal user has a profile, and a set of preferences which may be edited by clicking on the ". l("user account", "user") ." 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, homepage, and ". l("distributed authentication", "#da") ." names. Changes made here take effect immediately. Also, administrators may make profile and preferences changes in the ". l("Admin Center", "admin/user") ." on behalf of their users. 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 ". l("Drupal documentation", "drupal.org/node/view/316") .". For an example, see the 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. 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 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 ". l("XML-RPC","www.xmlrpc.com") ." ". l("HTTP POST", "www.w3.org/Protocols/") .", or ". l("SOAP", "www.soapware.org") .") behind the scenes and asks "is this password for username=joe?" 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. 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. universal 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. To disable distributed authentication, simply ". l("disable", "admin/system/modules") ." or remove all DA modules. For a virgin install, that means removing/disabling jabber.module and drupal.module 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 ... Drupal is specifically architected to enable easy authoring of new authentication modules. I'll deconstruct the ". l("Blogger", "www.blogger.com") ." 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 ". l("Blogger source", "cvs.drupal.org/viewcvs.cgi/contributions/modules/authentication/Blogger/?cvsroot=contrib") ." in the ". l("Drupal contributions CVS repository", "cvs.drupal.org/viewcvs/contributions/?cvsroot=contrib") .". The first line of every Drupal module, including the authentication modules, is the same. It is the standard processing instruction for any PHP file. Authentication modules are always written in PHP, although they typically interact with systems written in many different programming languages and operating systems languages. The _info function is always the first function defined in your module. This function populates an array called \$info with various pieces of data. Some of this data is used by Drupal ("name", "link"), and some of it just informs the users of your module. Simply copy the blogger_info function in your module - but wherever it says blogger here, substitute your own module name. The _auth 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: So now lets use that \$name, \$pass, and \$server which was passed to our _auth function. Blogger authenticates users via ". l("XML-RPC", "www.xmlrpc.org") .". Your module may authenticate using a different technique. Drupal doesn't reallly care how your module communicates with its registration source. It just trusts the module. The lines above illustrate a typical ". l("XML-RPC", "www.xmlrpc.org") ." method call. Here we build up a message and send it to Blogger, storing the response in a variable called \$response. The message we pass conforms to the published ". l("Blogger XML-RPC Application Programmers Interface (API)", "plant.blogger.com/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 plant.blogger.com, so we hard-code that value into the xmlrpc_client() function. A more typical example might be the jabber module, which uses the \$server parameter to determine where to send the authentication request. Also of note is the '5' parameter in the \$client->send\(\) 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. This second half of the _auth function examines the \$response 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. 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 blogger. The _auth_help 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. 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 ". l("Drupal contributions CVS repository", "cvs.drupal.org/viewcvs.cgi/contributions/modules/authentication?cvsroot=contrib") .". You'll need to request priveleges to this repository - see ". l("the README file", "cvs.drupal.org/viewcvs.cgi/contributions/README?rev=HEAD&cvsroot=contrib&content-type=text/vnd.viewcvs-markup") ." for the details. Then you should announce your contribution on the ". l("drupal-devel and drupal-support mailing lists", "drupal.org/node/view/322") .". You might also want to post a story on ". l("Drupal.org", "www.drupal.org") .". The _user() hook provides a mechanism for inserting text and form fields into the ". l("registration","user/register") .", ". l("user account view/edit", "user") .", and ". l("administer users", "admin/user") ." pages. This is useful if you want to add a custom field for your particular community. This is best illustrated by the ". l("profile.module", "cvs.drupal.org/viewcvs/drupal/modules/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. 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 julia.module. That file does the following:
In the meantime, your password and further instructions have been sent to your e-mail address.");
}
}
}
else {
if ($error) {
$output .= theme("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 .= "" . t("E-mail rules") . "
";
}
if ($type == "user") {
$output .= "" . t("Username rules") . "
";
}
if ($op == t("Add rule")) {
db_query("INSERT INTO {access} (mask, type, status) VALUES ('%s', '%s', %d)", $edit["mask"], $type, $edit["status"]);
}
else if ($op == t("Check")) {
if (user_deny($type, $edit["test"])) {
$message = "'". $edit["test"] ."' is not allowed.";
}
else {
$message = "'". $edit["test"] ."' is allowed.";
}
}
else if ($id) {
db_query("DELETE FROM {access} WHERE aid = %d", $id);
}
$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"));
}
$rows[] = array("", "", "");
$output .= table($header, $rows);
$output .= "
_: " . t("Matches exactly one character.") . "" . t("Check e-mail address") . "
";
}
else {
$output .= "" . t("Check username") . "
";
}
$output .= "$message";
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(" "), $role_names);
foreach ($perms as $perm) {
$row[] = t($perm);
foreach ($role_names as $rid => $name) {
$row[] = "";
}
$rows[] = $row;
unset($row);
}
$output = 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" => "". t("locked") ."", "align" => "center"));
}
}
$rows[] = array("", "");
$output = 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) {
// do nothing
}
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("your user information changes have been saved."));
}
else {
$output .= theme("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 .= t("The account has been deleted.");
}
else {
$output .= t("Failed to delete account: the account has to be blocked first.");
}
}
/*
** 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));
$options = "\n";
foreach (theme_list() as $key => $value) {
$options .= "\n";
}
$output .= form_item(t("Theme"), "", t("Selecting a different theme will change the look and feel of the site."));
for ($zone = -43200; $zone <= 46800; $zone += 3600) $zones[$zone] = date("l, F dS, Y - h:i A", time() - date("Z") + $zone) ." (GMT ". $zone / 3600 .")";
$output .= form_select(t("Time zone"), "timezone", $account->timezone, $zones, t("Select what time you currently have and your time zone settings will be set appropriate."));
$output .= form_select(t("Language"), "language", $account->language, $languages, t("Selecting a different language will change the language of the site."));
$output .= form_item(t("Password"), " ", 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_select(t("Status"), "status", $account->status, array(t("Blocked"), t("Active")));
$output .= form_select(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, "enctype=\"multipart/form-data\"");
}
else {
$output = t("No such user");
}
return $output;
}
function user_admin_account() {
$query = arg(3);
$queries[] = "";
$queries[] = "WHERE u.status = 0";
foreach (user_roles(1) as $key => $value) {
$queries[] = "WHERE r.name = '$value'";
}
$sql = "SELECT u.uid, u.name, u.timestamp FROM {role} r INNER JOIN {users} u ON r.rid = u.rid ". $queries[$query ? $query : 0];
$header = array(
array ("data" => t("uid"), "field" => "u.uid"),
array ("data" => t("username"), "field" => "u.name"),
array ("data" => t("last access"), "field" => "u.timestamp", "sort" => "desc"),
t("operations")
);
$sql .= tablesort_sql($header);
$result = pager_query($sql, 50);
while ($account = db_fetch_object($result)) {
$rows[] = array($account->uid, format_name($account), 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" => 4));
}
return 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"):
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"):
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;
}
}
// this help is for end users
function user_help_users_da() {
$site = "". variable_get("site_name", "this website"). "";
$output = "
Distributed authentication
" . module_invoke($module, "info", "name") . "
";
$output .= module_invoke($module, "auth_help");
}
}
return $output;
}
// the following functions comprise help for admins and developers
function user_help($section = "admin/user/help") {
switch ($section) {
case "admin/user/help":
$output = user_help_admin();
$output .= user_help_admin_da();
$output .= user_help_devel_da();
$output .= user_help_devel_userhook();
return t($output);
case "admin/user":
return t("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.
Click on either the \"username\" or \"edit account\" to edit a user's information.");
case "admin/user/account":
return t("This page allows you to review and edit any user's profile. To edit a profile click on either the \"username\" or \"edit account\".");
case "admin/user/account/create":
return t("This web page allows the administrators to register a new users by hand.
Note:
");
case "admin/user/account/0":
return t("This page allows you to review and edit an active user's profile. To edit a profile click on either the \"username\" or \"edit account\".");
case "admin/user/account/1":
return t("This page allows you to review and edit a new user's profile. To edit a profile click on either the \"username\" or \"edit account\".");
case "admin/user/account/2":
return t("This page allows you to review and edit a blocked user's profile. To edit a profile click on either the \"username\" or \"edit account\".");
case "admin/user/access":
return 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 rules, for the username mask click on username rules.", array("%e-mail" => url("admin/user/access/mail"), "%username" => url("admin/user/access/user")));
case "admin/user/access/mail":
return t("Setup and test the e-mail access rules. The access function checks if you match a deny and not an allow. If you match only a deny then it is denied. Any other case, such as both a deny and an allow pattern matching, allows the pattern.
Notes:
");
case "admin/user/access/user":
return t("Setup and test the Username access rules. The access function checks if you match a deny and not an allow. If you do then it is denied. Any other case, such as a deny pattern and an allow pattern, allows the pattern.
Notes:
");
case "admin/user/permission":
return t("In this area you will define the permissions for each user role (role names are defined on the user roles page). 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" => url("admin/user/role")));
case "admin/user/role":
return t("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 user permissions. Examples of roles include: anonymous user, authenticated user, moderator, administrator and so on. In this area you will define the names of the various roles. To delete a role choose \"edit role\"
By default, Drupal comes with two user roles:
", array("%permission" => url("admin/user/permission")));
case "admin/user/search":
return 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'.");
}
}
function user_help_admin() {
$output .= "Introduction
User preferences and profiles
jabber_user()
function in /modules/jabber.module.Distributed authentication
" . module_invoke($module, "info", "name") . "
";
$output .= module_invoke($module, "auth_help");
}
}
return $output;
}
function user_help_devel_da() {
$output .= "Writing distributed authentication modules
Code review
<?php
function blogger_info(\$field = NULL) {
\$info[\"name\"] = \"Blogger\";
\$info[\"protocol\"] = \"XML-RPC\";
\$info[\"link\"] = \"Blogger\";
\$info[\"maintainer\"] = \"Moshe Weitzman\";
\$info[\"maintaineremail\"] = \"weitzman at tejasa.com\";
if (\$field) return \$info[\$field];
else return \$info;
}
";
$output .= "function blogger_auth(\$name, \$pass, \$server) {
// user did not present a Blogger ID so don't bother trying.
if (\$server !== "blogger.com") {
return 0;
}
//provided to Drupal by Ev@Blogger
\$appkey = "6D4A2D6811A6E1F75148DC1155D33C0C958107BC"
\$message = new xmlrpcmsg("blogger.getUsersBlogs",
array(new xmlrpcval(\$appkey, "string"),
new xmlrpcval(\$name, "string"),
new xmlrpcval(\$pass, "string")));
\$client = new xmlrpc_client("/api/RPC2", "plant.blogger.com");
// \$client->setDebug(1);
\$result = \$client->send(\$message, 5);
// Since Blogger doesn't return a properly formed FaultCode, we just search for the string 'fault'.
if (\$result && !stristr(\$result->serialize(), "fault")) {
// 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;
}
}
";
$output .= "
";
$output .= "_auth function parameters \$name The substring before the final '@' character in the username field \$pass The whole string submitted by the user in the password field \$server The substring after the final '@' symbol in the username field
if (\$result && !stristr(\$result->serialize(), "fault")) {
// 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;
}
";
$output .= "function blogger_page() {
theme("header");
theme("box", "Blogger", blogger_auth_help());
theme("footer");
}
";
$output .= "function blogger_auth_help() {
";
$output .= "
\$site = variable_get("site_name", "this web site");
\$html_output = "
<p>You may login to <i>%s</i> using a <b>Blogger ID</b> and password. A Blogger ID consists of your Blogger username followed by <i>@blogger.com</i>. So a valid blogger ID is mwlily@blogger.com. If you are a Blogger member, go ahead and login now.</p>
<p>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. <a href=\"http://www.blogger.com/about.pyra\">Learn more about it</a>.";
return sprintf(t(\$html_output), \$site);
}Publishing your module
module_user()
Julia achieves this with the following code. The comments below should help you understand what is going on.
"; $output .= "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 Julia's Kitchen 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\"])); } }"; return $output; } ?>