You are here

function avatar_selection_entity_presave in Avatar Selection 7

Implements hook_entity_presave().

Handle saving of selected avatar. This function is not used if reg_with_pic module is enabled to avoid duplication.

File

./avatar_selection.module, line 373
The Avatar Selection module allows the user to pick an avatar image from a list already loaded by an administrative user, and to the administrator to disable uploading other avatar files by the user.

Code

function avatar_selection_entity_presave($account, $type) {

  // Only handle new users that have an uploaded picture.
  // user_save() will handle old users.
  if ($type != 'user' || !$account->is_new || empty($account->picture) || !is_object($account->picture) || module_exists('reg_with_pic')) {
    return;
  }
  $picture = $account->picture;
  $info = image_get_info($picture->uri);
  $picture_directory = file_default_scheme() . '://' . variable_get('user_picture_path', 'pictures');

  // Set the new uid since it is typically not set at this point. user_save()
  // will use this uid if set so no problems setting it early here.
  if (empty($account->uid)) {
    $account->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')
      ->fetchField());
  }

  // Prepare the pictures directory.
  file_prepare_directory($picture_directory, FILE_CREATE_DIRECTORY);
  $destination = file_stream_wrapper_uri_normalize($picture_directory . '/picture-' . $account->uid . '-' . REQUEST_TIME . '.' . $info['extension']);

  // Move the temporary file into the final location.
  if ($picture = file_move($picture, $destination, FILE_EXISTS_RENAME)) {
    $picture->status = FILE_STATUS_PERMANENT;
    $account->picture = file_save($picture);
    file_usage_add($picture, 'user', 'user', $account->uid);
  }

  // Update user record with picture fid.
  if (isset($account->picture->fid)) {
    $account->picture = $account->picture->fid;
  }
}