Log when a user enters a password on a password protected page

Over at the forums on wordpress.org there was a user who asked if it was possible to log whenever a user entered the password on a password protected page.

To add this kind of log to Simple History is easy, we just need to hook onto an admin filter and do some checks. The final answer, that I also posted to the user in the forums, was this:

// Log when a user enters something into the post password form.
// Both correct and incorrect usage is logged.
add_action( 'login_form_postpass', function() {
    $postPass = isset($_POST['post_password']) ? $_POST['post_password'] : null;

    if (!$postPass) {
        return;
    }

    $urlPath = parse_url(wp_get_referer(), PHP_URL_PATH);
    $pageByPath = get_page_by_path($urlPath);

    if (!$pageByPath) {
        return;
    }

    $correctPasswordEntered = ($pageByPath->post_password === $postPass);

    if ($correctPasswordEntered) {
        apply_filters(
            'simple_history_log',
            'A user correctly entered the password for page "{page_name}"',
            array('page_name' => $pageByPath->post_title)
        );
    } else {
        apply_filters(
            'simple_history_log',
            'A user entered the wrong password for page "{page_name}"',
            array('page_name' => $pageByPath->post_title)
        );
    }
});