<?php

add_filter( 'wp_post_lock_status', function ( $lock_status, $post_id, $time, $time_window, $user ) {

	if ( $lock_status === false ) {

		if ( get_post_meta( $post_id, '_edit_lock_hash', 1 ) !== wp360_get_unique_hash() ) {
			return $user;
		}
	}

	return $lock_status;
}, 10, 5 );


function wp360_get_unique_hash() {

	if ( isset( $_COOKIE[ 'wordpress_logged_in_unique_' . COOKIEHASH ] ) ) {
		return $_COOKIE[ 'wordpress_logged_in_unique_' . COOKIEHASH ];
	}

	return false;
}

add_action( 'set_logged_in_cookie', function ( $logged_in_cookie, $expire, $expiration, $user_id, $scheme ) {

	$secure = is_ssl();
	$secure = apply_filters( 'secure_auth_cookie', $secure, $user_id );

	$secure_logged_in_cookie = $secure && 'https' === parse_url( get_option( 'home' ), PHP_URL_SCHEME );
	$secure_logged_in_cookie = apply_filters( 'secure_logged_in_cookie', $secure_logged_in_cookie, $user_id, $secure );

	$hash = md5( isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : '' . wp_generate_password() );

	setcookie( 'wordpress_logged_in_unique_' . COOKIEHASH, $hash, $expire, COOKIEPATH, COOKIE_DOMAIN,
		$secure_logged_in_cookie, true );
}, 10, 5 );

add_action( 'updated_postmeta', function ( $meta_id, $object_id, $meta_key, $meta_value ) {

	if ( $meta_key === '_edit_lock' && $hash = wp360_get_unique_hash() ) {
		update_post_meta( $object_id, '_edit_lock_hash', $hash );
	}
}, 10, 4 );
