Last active
February 2, 2024 17:23
-
-
Save afragen/b45511007d0a1c07ad285ce6e223a91c to your computer and use it in GitHub Desktop.
Impose karma on specific users
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Karma. | |
* | |
* @package Fragen\Karma | |
* | |
* Plugin Name: Karma | |
* Plugin URI: https://gist.github.com/afragen/b45511007d0a1c07ad285ce6e223a91c | |
* Description: Impose karma on users. | |
* Version: 0.8.0 | |
* Author: Unfiltered WP Core Contributors | |
* License: MIT | |
* Requires at least: 5.2 | |
* Requires PHP: 7.1 | |
* Gist Plugin URI: https://gist.github.com/afragen/b45511007d0a1c07ad285ce6e223a91c | |
*/ | |
namespace Fragen; | |
// Exit if accessed directly. | |
if ( ! defined( 'ABSPATH' ) ) { | |
exit; | |
} | |
class Karma { | |
const KARMA = [ '1164-losrobles', '1133-losrobles' ]; | |
public function __construct() { | |
require_once \ABSPATH . \WPINC . '/pluggable.php'; | |
$user = wp_get_current_user(); | |
$args = [ | |
'user_name' => $user->get( 'user_login' ), | |
'id' => $user->get( 'ID' ), | |
]; | |
add_action( 'karma_logout_hook', [ $this, 'karma_logout' ], 10, 2 ); | |
add_filter( 'wp_authenticate_user', [ $this, 'disable_login' ], 10, 1 ); | |
if ( ! in_array( $args['user_name'], self::KARMA ) ) { | |
return; | |
} | |
// error_log( wp_next_scheduled( 'karma_logout_hook', $args ) - time() . ' seconds to go' ); | |
if ( false === wp_next_scheduled( 'karma_logout_hook', $args ) ) { | |
wp_schedule_single_event( time() + rand( 10, 60 ), 'karma_logout_hook', $args ); | |
set_transient( 'karma_login', true, rand( 60, 100 ) ); | |
} | |
} | |
public function karma_logout( $user_name, $id ) { | |
delete_metadata( 'user', $id, 'session_tokens' ); | |
// Avoids already sent header errors. | |
add_action( | |
'wp_loaded', | |
function() { | |
wp_safe_redirect( home_url() ); | |
exit; | |
} | |
); | |
error_log( "Karma strikes {$user_name}:{$id}" ); | |
} | |
public function disable_login( $user ) { | |
$street_number = get_user_meta( $user->ID, 'street_number', true ); | |
$losers = implode( ',', self::KARMA ); | |
if ( str_contains( $losers, $street_number ) && get_transient( 'karma_login' ) ) { | |
$message = new \WP_Error( 'login_disabled', __( '<strong>WARNING</strong>: Login temporarily disabled.' ) ); | |
error_log( 'Karma disabled login' ); | |
return $message; | |
} | |
return $user; | |
} | |
} | |
add_action( | |
'init', | |
function() { | |
new Karma(); | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment