user.install 28.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
<?php

/**
 * @file
 * Install, update and uninstall functions for the user module.
 */

/**
 * Implements hook_schema().
 */
function user_schema() {
  $schema['authmap'] = array(
    'description' => 'Stores distributed authentication mapping.',
    'fields' => array(
      'aid' => array(
        'description' => 'Primary Key: Unique authmap ID.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'uid' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => "User's {users}.uid.",
      ),
      'authname' => array(
        'type' => 'varchar',
        'length' => 128,
        'not null' => TRUE,
        'default' => '',
        'description' => 'Unique authentication name.',
      ),
      'module' => array(
        'type' => 'varchar',
        'length' => 128,
        'not null' => TRUE,
        'default' => '',
        'description' => 'Module which is controlling the authentication.',
      ),
    ),
    'unique keys' => array(
      'authname' => array('authname'),
    ),
    'primary key' => array('aid'),
    'foreign keys' => array(
      'user' => array(
        'table' => 'users',
        'columns' => array('uid' => 'uid'),
      ),
    ),
  );

  $schema['role_permission'] = array(
    'description' => 'Stores the permissions assigned to user roles.',
    'fields' => array(
      'rid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'description' => 'Foreign Key: {role}.rid.',
      ),
      'permission' => array(
        'type' => 'varchar',
        'length' => 128,
        'not null' => TRUE,
        'default' => '',
        'description' => 'A single permission granted to the role identified by rid.',
      ),
      'module' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => "The module declaring the permission.",
      ),
    ),
    'primary key' => array('rid', 'permission'),
    'indexes' => array(
      'permission' => array('permission'),
    ),
    'foreign keys' => array(
      'role' => array(
        'table' => 'roles',
        'columns' => array('rid' => 'rid'),
      ),
    ),
  );

  $schema['role'] = array(
    'description' => 'Stores user roles.',
    'fields' => array(
      'rid' => array(
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'description' => 'Primary Key: Unique role ID.',
      ),
      'name' => array(
        'type' => 'varchar',
        'length' => 64,
        'not null' => TRUE,
        'default' => '',
        'description' => 'Unique role name.',
        'translatable' => TRUE,
      ),
      'weight' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The weight of this role in listings and the user interface.',
      ),
    ),
    'unique keys' => array(
      'name' => array('name'),
    ),
    'primary key' => array('rid'),
    'indexes' => array(
      'name_weight' => array('name', 'weight'),
    ),
  );

  // The table name here is plural, despite Drupal table naming standards,
  // because "user" is a reserved word in many databases.
  $schema['users'] = array(
    'description' => 'Stores user data.',
    'fields' => array(
      'uid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'description' => 'Primary Key: Unique user ID.',
        'default' => 0,
      ),
      'name' => array(
        'type' => 'varchar',
        'length' => 60,
        'not null' => TRUE,
        'default' => '',
        'description' => 'Unique user name.',
      ),
      'pass' => array(
        'type' => 'varchar',
        'length' => 128,
        'not null' => TRUE,
        'default' => '',
        'description' => "User's password (hashed).",
      ),
      'mail' => array(
        'type' => 'varchar',
        'length' => 254,
        'not null' => FALSE,
        'default' => '',
        'description' => "User's e-mail address.",
      ),
      'theme' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => "User's default theme.",
      ),
      'signature' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => "User's signature.",
      ),
      'signature_format' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => FALSE,
        'description' => 'The {filter_format}.format of the signature.',
      ),
      'created' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'Timestamp for when user was created.',
      ),
      'access' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'Timestamp for previous time user accessed the site.',
      ),
      'login' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => "Timestamp for user's last login.",
      ),
      'status' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'size' => 'tiny',
        'description' => 'Whether the user is active(1) or blocked(0).',
      ),
      'timezone' => array(
        'type' => 'varchar',
        'length' => 32,
        'not null' => FALSE,
        'description' => "User's time zone.",
      ),
      'language' => array(
        'type' => 'varchar',
        'length' => 12,
        'not null' => TRUE,
        'default' => '',
        'description' => "User's default language.",
      ),
      'picture' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => "Foreign key: {file_managed}.fid of user's picture.",
      ),
      'init' => array(
        'type' => 'varchar',
        'length' => 254,
        'not null' => FALSE,
        'default' => '',
        'description' => 'E-mail address used for initial account creation.',
      ),
      'data' => array(
        'type' => 'blob',
        'not null' => FALSE,
        'size' => 'big',
        'serialize' => TRUE,
        'description' => 'A serialized array of name value pairs that are related to the user. Any form values posted during user edit are stored and are loaded into the $user object during user_load(). Use of this field is discouraged and it will likely disappear in a future version of Drupal.',
      ),
    ),
    'indexes' => array(
      'access' => array('access'),
      'created' => array('created'),
      'mail' => array('mail'),
      'picture' => array('picture'),
    ),
    'unique keys' => array(
      'name' => array('name'),
    ),
    'primary key' => array('uid'),
    'foreign keys' => array(
      'signature_format' => array(
        'table' => 'filter_format',
        'columns' => array('signature_format' => 'format'),
      ),
    ),
  );

  $schema['users_roles'] = array(
    'description' => 'Maps users to roles.',
    'fields' => array(
      'uid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
        'description' => 'Primary Key: {users}.uid for user.',
      ),
      'rid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
        'description' => 'Primary Key: {role}.rid for role.',
      ),
    ),
    'primary key' => array('uid', 'rid'),
    'indexes' => array(
      'rid' => array('rid'),
    ),
    'foreign keys' => array(
      'user' => array(
        'table' => 'users',
        'columns' => array('uid' => 'uid'),
      ),
      'role' => array(
        'table' => 'roles',
        'columns' => array('rid' => 'rid'),
      ),
    ),
  );

  return $schema;
}

/**
 * Implements hook_install().
 */
function user_install() {
  // Insert a row for the anonymous user.
  db_insert('users')
    ->fields(array(
      'uid' => 0,
      'name' => '',
      'mail' => '',
    ))
    ->execute();

  // We need some placeholders here as name and mail are uniques and data is
  // presumed to be a serialized array. This will be changed by the settings
  // form in the installer.
  db_insert('users')
    ->fields(array(
      'uid' => 1,
      'name' => 'placeholder-for-uid-1',
      'mail' => 'placeholder-for-uid-1',
      'created' => REQUEST_TIME,
      'status' => 1,
      'data' => NULL,
    ))
    ->execute();

  // Built-in roles.
  $rid_anonymous = db_insert('role')
    ->fields(array('name' => 'anonymous user', 'weight' => 0))
    ->execute();
  $rid_authenticated = db_insert('role')
    ->fields(array('name' => 'authenticated user', 'weight' => 1))
    ->execute();

  // Sanity check to ensure the anonymous and authenticated role IDs are the
  // same as the drupal defined constants. In certain situations, this will
  // not be true.
  if ($rid_anonymous != DRUPAL_ANONYMOUS_RID) {
    db_update('role')
      ->fields(array('rid' => DRUPAL_ANONYMOUS_RID))
      ->condition('rid', $rid_anonymous)
      ->execute();
  }
  if ($rid_authenticated != DRUPAL_AUTHENTICATED_RID) {
    db_update('role')
      ->fields(array('rid' => DRUPAL_AUTHENTICATED_RID))
      ->condition('rid', $rid_authenticated)
      ->execute();
  }
}

/**
 * Implements hook_update_dependencies().
 */
function user_update_dependencies() {
  // user_update_7006() updates data in the {role_permission} table, so it must
  // run after system_update_7007(), which populates that table.
  $dependencies['user'][7006] = array(
    'system' => 7007,
  );

  // user_update_7010() needs to query the {filter_format} table to get a list
  // of existing text formats, so it must run after filter_update_7000(), which
  // creates that table.
  $dependencies['user'][7010] = array(
    'filter' => 7000,
  );

  // user_update_7012() uses the file API, which relies on the {file_managed}
  // table, so it must run after system_update_7034(), which creates that
  // table.
  $dependencies['user'][7012] = array(
    'system' => 7034,
  );

  // user_update_7013() uses the file usage API, which relies on the
  // {file_usage} table, so it must run after system_update_7059(), which
  // creates that table.
  $dependencies['user'][7013] = array(
    'system' => 7059,
  );

  return $dependencies;
}

/**
 * Utility function: grant a set of permissions to a role during update.
 *
 * This function is valid for a database schema version 7000.
 *
 * @param $rid
 *   The role ID.
 * @param $permissions
 *   An array of permissions names.
 * @param $module
 *   The name of the module defining the permissions.
 * @ingroup update_api
 */
function _update_7000_user_role_grant_permissions($rid, array $permissions, $module) {
  // Grant new permissions for the role.
  foreach ($permissions as $name) {
    db_merge('role_permission')
      ->key(array(
        'rid' => $rid,
        'permission' => $name,
      ))
      ->fields(array(
        'module' => $module,
      ))
      ->execute();
  }
}

/**
 * @addtogroup updates-6.x-to-7.x
 * @{
 */

/**
 * Increase the length of the password field to accommodate better hashes.
 *
 * Also re-hashes all current passwords to improve security. This may be a
 * lengthy process, and is performed batch-wise.
 */
function user_update_7000(&$sandbox) {
  $sandbox['#finished'] = 0;
  // Lower than DRUPAL_HASH_COUNT to make the update run at a reasonable speed.
  $hash_count_log2 = 11;
  // Multi-part update.
  if (!isset($sandbox['user_from'])) {
    db_change_field('users', 'pass', 'pass', array('type' => 'varchar', 'length' => 128, 'not null' => TRUE, 'default' => ''));
    $sandbox['user_from'] = 0;
    $sandbox['user_count'] = db_query("SELECT COUNT(uid) FROM {users}")->fetchField();
  }
  else {
    require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
    //  Hash again all current hashed passwords.
    $has_rows = FALSE;
    // Update this many per page load.
    $count = 1000;
    $result = db_query_range("SELECT uid, pass FROM {users} WHERE uid > 0 ORDER BY uid", $sandbox['user_from'], $count);
    foreach ($result as $account) {
      $has_rows = TRUE;

      // If the $account->pass value is not a MD5 hash (a 32 character
      // hexadecimal string) then skip it.
      if (!preg_match('/^[0-9a-f]{32}$/', $account->pass)) {
        continue;
      }

      $new_hash = user_hash_password($account->pass, $hash_count_log2);
      if ($new_hash) {
        // Indicate an updated password.
        $new_hash  = 'U' . $new_hash;
        db_update('users')
          ->fields(array('pass' => $new_hash))
          ->condition('uid', $account->uid)
          ->execute();
      }
    }
    $sandbox['#finished'] = $sandbox['user_from']/$sandbox['user_count'];
    $sandbox['user_from'] += $count;
    if (!$has_rows) {
      $sandbox['#finished'] = 1;
      return t('User passwords rehashed to improve security');
    }
  }
}

/**
 * Remove the 'threshold', 'mode' and 'sort' columns from the {users} table.
 *
 * These fields were previously used to store per-user comment settings.
 */

function user_update_7001() {
  db_drop_field('users', 'threshold');
  db_drop_field('users', 'mode');
  db_drop_field('users', 'sort');
}

/**
 * Convert user time zones from time zone offsets to time zone names.
 */
function user_update_7002(&$sandbox) {
  $sandbox['#finished'] = 0;

  // Multi-part update.
  if (!isset($sandbox['user_from'])) {
    db_change_field('users', 'timezone', 'timezone', array('type' => 'varchar', 'length' => 32, 'not null' => FALSE));
    $sandbox['user_from'] = 0;
    $sandbox['user_count'] = db_query("SELECT COUNT(uid) FROM {users}")->fetchField();
    $sandbox['user_not_migrated'] = 0;
  }
  else {
    $timezones = system_time_zones();
    // Update this many per page load.
    $count = 10000;
    $contributed_date_module = db_field_exists('users', 'timezone_name');
    $contributed_event_module = db_field_exists('users', 'timezone_id');

    $results = db_query_range("SELECT uid FROM {users} ORDER BY uid", $sandbox['user_from'], $count);
    foreach ($results as $account) {
      $timezone = NULL;
      // If the contributed Date module has created a users.timezone_name
      // column, use this data to set each user's time zone.
      if ($contributed_date_module) {
        $date_timezone = db_query("SELECT timezone_name FROM {users} WHERE uid = :uid", array(':uid' => $account->uid))->fetchField();
        if (isset($timezones[$date_timezone])) {
          $timezone = $date_timezone;
        }
      }
      // If the contributed Event module has stored user time zone information
      // use that information to update the user accounts.
      if (!$timezone && $contributed_event_module) {
        try {
          $event_timezone = db_query("SELECT t.name FROM {users} u LEFT JOIN {event_timezones} t ON u.timezone_id = t.timezone WHERE u.uid = :uid", array(':uid' => $account->uid))->fetchField();
          $event_timezone = str_replace(' ', '_', $event_timezone);
          if (isset($timezones[$event_timezone])) {
            $timezone = $event_timezone;
          }
        }
        catch (PDOException $e) {
          // Ignore error if event_timezones table does not exist or unexpected
          // schema found.
        }
      }
      if ($timezone) {
        db_update('users')
          ->fields(array('timezone' => $timezone))
          ->condition('uid', $account->uid)
          ->execute();
      }
      else {
        $sandbox['user_not_migrated']++;
        db_update('users')
          ->fields(array('timezone' => NULL))
          ->condition('uid', $account->uid)
          ->execute();
      }
      $sandbox['user_from']++;
    }

    $sandbox['#finished'] = $sandbox['user_from'] / $sandbox['user_count'];
    if ($sandbox['user_from'] == $sandbox['user_count']) {
      if ($sandbox['user_not_migrated'] > 0) {
        variable_set('empty_timezone_message', 1);
        drupal_set_message(format_string('Some user time zones have been emptied and need to be set to the correct values. Use the new <a href="@config-url">time zone options</a> to choose whether to remind users at login to set the correct time zone.', array('@config-url' => url('admin/config/regional/settings'))), 'warning');
      }
      return t('Migrated user time zones');
    }
  }
}

/**
 * Update user settings for cancelling user accounts.
 *
 * Prior to 7.x, users were not able to cancel their accounts. When
 * administrators deleted an account, all contents were assigned to uid 0,
 * which is the same as the 'user_cancel_reassign' method now.
 */
function user_update_7003() {
  // Set the default account cancellation method.
  variable_set('user_cancel_method', 'user_cancel_reassign');
  // Re-assign notification setting.
  if ($setting = variable_get('user_mail_status_deleted_notify', FALSE)) {
    variable_set('user_mail_status_canceled_notify', $setting);
    variable_del('user_mail_status_deleted_notify');
  }
  // Re-assign "Account deleted" mail strings to "Account canceled" mail.
  if ($setting = variable_get('user_mail_status_deleted_subject', FALSE)) {
    variable_set('user_mail_status_canceled_subject', $setting);
    variable_del('user_mail_status_deleted_subject');
  }
  if ($setting = variable_get('user_mail_status_deleted_body', FALSE)) {
    variable_set('user_mail_status_canceled_body', $setting);
    variable_del('user_mail_status_deleted_body');
  }
}

/**
 * Changes the users table to allow longer e-mail addresses.
 */
function user_update_7005(&$sandbox) {
  $mail_field = array(
    'type' => 'varchar',
    'length' => 254,
    'not null' => FALSE,
    'default' => '',
    'description' => "User's e-mail address.",
  );
  $init_field = array(
    'type' => 'varchar',
    'length' => 254,
    'not null' => FALSE,
    'default' => '',
    'description' => 'E-mail address used for initial account creation.',
  );
  db_drop_index('users', 'mail');
  db_change_field('users', 'mail', 'mail', $mail_field, array('indexes' => array('mail' => array('mail'))));
  db_change_field('users', 'init', 'init', $init_field);
}

/**
 * Add module data to {role_permission}.
 */
function user_update_7006(&$sandbox) {
  $module_field = array(
    'type' => 'varchar',
    'length' => 255,
    'not null' => TRUE,
    'default' => '',
    'description' => "The module declaring the permission.",
  );
  // Check that the field hasn't been updated in an aborted run of this
  // update.
  if (!db_field_exists('role_permission', 'module')) {
    // Add a new field for the fid.
    db_add_field('role_permission', 'module', $module_field);
  }
}

/**
 * Add a weight column to user roles.
 */
function user_update_7007() {
  db_add_field('role', 'weight', array('type' => 'int', 'not null' => TRUE, 'default' => 0));
  db_add_index('role', 'name_weight', array('name', 'weight'));
}

/**
 * If 'user_register' variable was unset in Drupal 6, set it to be the same as
 * the Drupal 6 default setting.
 */
function user_update_7008() {
  if (!isset($GLOBALS['conf']['user_register'])) {
    // Set to the Drupal 6 default, "visitors can create accounts".
    variable_set('user_register', USER_REGISTER_VISITORS);
  }
}

/**
 * Converts fields that store serialized variables from text to blob.
 */
function user_update_7009() {
  $spec = array(
    'type' => 'blob',
    'not null' => FALSE,
    'size' => 'big',
    'serialize' => TRUE,
    'description' => 'A serialized array of name value pairs that are related to the user. Any form values posted during user edit are stored and are loaded into the $user object during user_load(). Use of this field is discouraged and it will likely disappear in a future version of Drupal.',
  );
  db_change_field('users', 'data', 'data', $spec);
}

/**
 * Update the {user}.signature_format column.
 */
function user_update_7010() {
  // Update the database column to allow NULL values.
  db_change_field('users', 'signature_format', 'signature_format', array(
    'type' => 'int',
    'unsigned' => TRUE,
    'not null' => FALSE,
    'description' => 'The {filter_format}.format of the signature.',
  ));

  // Replace the signature format with NULL if the signature is empty and does
  // not already have a stored text format.
  //
  // In Drupal 6, "0" (the former FILTER_FORMAT_DEFAULT constant) could be used
  // to indicate this situation, but in Drupal 7, only NULL is supported. This
  // update therefore preserves the ability of user accounts which were never
  // given a signature (for example, if the site did not have user signatures
  // enabled, or if the user never edited their account information) to not
  // have a particular text format assumed for them the first time the
  // signature is edited.
  db_update('users')
    ->fields(array('signature_format' => NULL))
    ->condition('signature', '')
    ->condition('signature_format', 0)
    ->execute();

  // There are a number of situations in which a Drupal 6 site could store
  // content with a nonexistent text format. This includes text formats that
  // had later been deleted, or non-empty content stored with a value of "0"
  // (the former FILTER_FORMAT_DEFAULT constant). Drupal 6 would filter this
  // content using whatever the site-wide default text format was at the moment
  // the text was being displayed.
  //
  // In Drupal 7, this behavior is no longer supported, and all content must be
  // stored with an explicit text format (or it will not be displayed when it
  // is filtered). Therefore, to preserve the behavior of the site after the
  // upgrade, we must replace all instances described above with the current
  // value of the (old) site-wide default format at the moment of the upgrade.
  $existing_formats = db_query("SELECT format FROM {filter_format}")->fetchCol();
  $default_format = variable_get('filter_default_format', 1);
  db_update('users')
    ->fields(array('signature_format' => $default_format))
    ->isNotNull('signature_format')
    ->condition('signature_format', $existing_formats, 'NOT IN')
    ->execute();
}

/**
 * Placeholder function.
 *
 * As a fix for user_update_7011() not updating email templates to use the new
 * tokens, user_update_7017() now targets email templates of Drupal 6 sites and
 * already upgraded sites.
 */
function user_update_7011() {
}

/**
 * Add the user's pictures to the {file_managed} table and make them managed
 * files.
 */
function user_update_7012(&$sandbox) {

  $picture_field = array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'description' => "Foreign key: {file_managed}.fid of user's picture.",
  );

  if (!isset($sandbox['progress'])) {
    // Check that the field hasn't been updated in an aborted run of this
    // update.
    if (!db_field_exists('users', 'picture_fid')) {
      // Add a new field for the fid.
      db_add_field('users', 'picture_fid', $picture_field);
    }

    // Initialize batch update information.
    $sandbox['progress'] = 0;
    $sandbox['last_user_processed'] = -1;
    $sandbox['max'] = db_query("SELECT COUNT(*) FROM {users} WHERE picture <> ''")->fetchField();
  }

  // As a batch operation move the photos into the {file_managed} table and
  // update the {users} records.
  $limit = 500;
  $result = db_query_range("SELECT uid, picture FROM {users} WHERE picture <> '' AND uid > :uid ORDER BY uid", 0, $limit, array(':uid' => $sandbox['last_user_processed']));
  foreach ($result as $user) {
    // Don't bother adding files that don't exist.
    if (file_exists($user->picture)) {

      // Check if the file already exists.
      $files = file_load_multiple(array(), array('uri' => $user->picture));
      if (count($files)) {
        $file = reset($files);
      }
      else {
        // Create a file object.
        $file = new stdClass();
        $file->uri      = $user->picture;
        $file->filename = drupal_basename($file->uri);
        $file->filemime = file_get_mimetype($file->uri);
        $file->uid      = $user->uid;
        $file->status   = FILE_STATUS_PERMANENT;
        $file = file_save($file);
      }

      db_update('users')
        ->fields(array('picture_fid' => $file->fid))
        ->condition('uid', $user->uid)
        ->execute();
    }

    // Update our progress information for the batch update.
    $sandbox['progress']++;
    $sandbox['last_user_processed'] = $user->uid;
  }

  // Indicate our current progress to the batch update system. If there's no
  // max value then there's nothing to update and we're finished.
  $sandbox['#finished'] = empty($sandbox['max']) ? 1 : ($sandbox['progress'] / $sandbox['max']);

  // When we're finished, drop the old picture field and rename the new one to
  // replace it.
  if (isset($sandbox['#finished']) && $sandbox['#finished'] == 1) {
    db_drop_field('users', 'picture');
    db_change_field('users', 'picture_fid', 'picture', $picture_field);
  }
}

/**
 * Add user module file usage entries.
 */
function user_update_7013(&$sandbox) {
  if (!isset($sandbox['progress'])) {
    // Initialize batch update information.
    $sandbox['progress'] = 0;
    $sandbox['last_uid_processed'] = -1;
    $sandbox['max'] = db_query("SELECT COUNT(*) FROM {users} u WHERE u.picture <> 0")->fetchField();
  }

  // Add usage entries for the user picture files.
  $limit = 500;
  $result = db_query_range('SELECT f.*, u.uid as user_uid FROM {users} u INNER JOIN {file_managed} f ON u.picture = f.fid WHERE u.picture <> 0 AND u.uid > :uid ORDER BY u.uid', 0, $limit, array(':uid' => $sandbox['last_uid_processed']))->fetchAllAssoc('fid', PDO::FETCH_ASSOC);
  foreach ($result as $row) {
    $uid = $row['user_uid'];
    $file = (object) $row;
    file_usage_add($file, 'user', 'user', $uid);

    // Update our progress information for the batch update.
    $sandbox['progress']++;
    $sandbox['last_uid_processed'] = $uid;
  }

  // Indicate our current progress to the batch update system.
  $sandbox['#finished'] = empty($sandbox['max']) || ($sandbox['progress'] / $sandbox['max']);
}

/**
 * Rename the 'post comments without approval' permission.
 *
 * In Drupal 7, this permission has been renamed to 'skip comment approval'.
 */
function user_update_7014() {
  db_update('role_permission')
        ->fields(array('permission' => 'skip comment approval'))
        ->condition('permission', 'post comments without approval')
        ->execute();

  return t("Renamed the 'post comments without approval' permission to 'skip comment approval'.");
}

/**
 * Change {users}.signature_format into varchar.
 */
function user_update_7015() {
  db_change_field('users', 'signature_format', 'signature_format', array(
    'type' => 'varchar',
    'length' => 255,
    'not null' => FALSE,
    'description' => 'The {filter_format}.format of the signature.',
  ));
}

/**
 * @} End of "addtogroup updates-6.x-to-7.x".
 */

/**
 * @addtogroup updates-7.x-extra
 * @{
 */

/**
 * Update the database to match the schema.
 */
function user_update_7016() {
  // Add field default.
  db_change_field('users', 'uid', 'uid', array(
    'type' => 'int',
    'unsigned' => TRUE,
    'not null' => TRUE,
    'default' => 0,
  ));
}

/**
 * Update email templates to use new tokens.
 *
 * This function upgrades customized email templates from the old !token format
 * to the new core tokens format. Additionally, in Drupal 7 we no longer e-mail
 * plain text passwords to users, and there is no token for a plain text
 * password in the new token system. Therefore, it also modifies any saved
 * templates using the old '!password' token such that the token is removed, and
 * displays a warning to users that they may need to go and modify the wording
 * of their templates.
 */
function user_update_7017() {
  $message = '';

  $tokens = array(
    '!site' => '[site:name]',
    '!username' => '[user:name]',
    '!mailto' => '[user:mail]',
    '!login_uri' => '[site:login-url]',
    '!uri_brief' => '[site:url-brief]',
    '!edit_uri' => '[user:edit-url]',
    '!login_url' => '[user:one-time-login-url]',
    '!uri' => '[site:url]',
    '!date' => '[date:medium]',
    '!password' => '',
  );

  $result = db_select('variable', 'v')
    ->fields('v', array('name'))
    ->condition('name', db_like('user_mail_') . '%', 'LIKE')
    ->execute();

  foreach ($result as $row) {
    // Use variable_get() to get the unserialized value for free.
    if ($value = variable_get($row->name, FALSE)) {

      if (empty($message) && (strpos($value, '!password') !== FALSE)) {
        $message = t('The ability to send users their passwords in plain text has been removed in Drupal 7. Your existing email templates have been modified to remove it. You should <a href="@template-url">review these templates</a> to make sure they read properly.', array('@template-url' => url('admin/config/people/accounts')));
      }

      variable_set($row->name, str_replace(array_keys($tokens), $tokens, $value));
    }
  }

  return $message;
}

/**
 * Ensure there is an index on {users}.picture.
 */
function user_update_7018() {
  if (!db_index_exists('users', 'picture')) {
    db_add_index('users', 'picture', array('picture'));
  }
}

/**
 * @} End of "addtogroup updates-7.x-extra".
 */