function user_update_8012

Migrate {users}.picture to 'user_picture' image field.

Related topics

File

drupal/core/modules/user/user.install, line 822
Install, update and uninstall functions for the user module.

Code

function user_update_8012(&$sandbox) {

  // Initialize total values to process.
  if (!isset($sandbox['total'])) {
    $sandbox['total'] = (int) db_query('SELECT COUNT(picture) FROM {users} WHERE picture > 0')
      ->fetchField();
    $sandbox['processed'] = 0;
  }
  if ($sandbox['total']) {

    // Retrieve next 20 rows to migrate.
    $rows = db_query_range('SELECT uid, picture FROM {users} WHERE picture > 0', 0, 20)
      ->fetchAllKeyed();
    foreach ($rows as $uid => $fid) {

      // Add a row to the field data and revision tables.
      db_insert('field_data_user_picture')
        ->fields(array(
        'entity_type' => 'user',
        'bundle' => 'user',
        'entity_id' => $uid,
        'revision_id' => $uid,
        'langcode' => Language::LANGCODE_NOT_SPECIFIED,
        'delta' => 0,
        'user_picture_fid' => $fid,
      ))
        ->execute();
      db_insert('field_revision_user_picture')
        ->fields(array(
        'entity_type' => 'user',
        'bundle' => 'user',
        'entity_id' => $uid,
        'revision_id' => $uid,
        'langcode' => Language::LANGCODE_NOT_SPECIFIED,
        'delta' => 0,
        'user_picture_fid' => $fid,
      ))
        ->execute();

      // Update file usage from user to file module.
      // @see file_field_insert()
      // Old: file_usage_add($picture, 'user', 'user', $entity->uid);
      // New: file_usage_add(file_load($item['fid']), 'file', $entity_type, $id);
      db_update('file_usage')
        ->condition('fid', $fid)
        ->condition('module', 'user')
        ->condition('type', 'user')
        ->condition('id', $uid)
        ->fields(array(
        'module' => 'file',
      ))
        ->execute();
    }

    // Set picture column of the migrated users to 0.
    db_update('users')
      ->fields(array(
      'picture' => 0,
    ))
      ->condition('uid', array_keys($rows))
      ->execute();

    // Report status.
    $sandbox['processed'] += count($rows);
  }
  $sandbox['#finished'] = $sandbox['total'] ? $sandbox['processed'] / $sandbox['total'] : 1;
}