<?php

/**
 *  Implements hook_user_insert().
 */
function password_policy_history_user_insert($account) {
  _password_policy_history_insert_password_hash($account);
}

/**
 *  Implements hook_user_update().
 */
function password_policy_history_user_update($account) {
  _password_policy_history_insert_password_hash($account);
}

/**
 *  Get hashed password and insert it into the history table
 */
function _password_policy_history_insert_password_hash($account) {
  $connection = \Drupal\Core\Database\Database::getConnection();
  if(empty($_POST['pass']['pass1']) || empty($_POST['pass']['pass2'])) {
    return;
  }

  $hashed_pass = $account->getPassword();
  $values = array(
    $account->id(),
    $hashed_pass,
    time(),
  );
  $connection->insert('password_policy_history')
    ->fields(array('uid', 'pass_hash', 'timestamp'), $values)
    ->execute();
}

/**
 *  Implements hook_user_delete().
 */
function password_policy_history_user_delete($account) {
  db_delete('password_policy_history')
    ->condition('uid', $account->id())
    ->execute();
}