Created
May 13, 2020 09:28
-
-
Save sbrajesh/ca13abd1a890b628f55fc444c957e645 to your computer and use it in GitHub Desktop.
Rate limiting based on member type using bp-activity-rate-limiter
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
/** | |
* Get time/count for the user | |
* | |
* @param int $user_id user id. | |
* | |
* @return array | |
*/ | |
function buddydev_get_activity_mtype_based_rates( $user_id ) { | |
// define a map from 'member_type' => array( 'time' => 'minutes', 'max' => 'how_many' ) | |
$settings = array( | |
'student' => array( | |
'time' => 60, // 60 minutes | |
'max' => 5, // maximum 5 in 1 hour. | |
), | |
'teacher' => array( | |
'time' => 60, | |
'max' => 20, // 20 updates. | |
), // repeat for others. | |
); | |
$member_types = bp_get_member_type( $user_id, false ); | |
// user does not have a member type. | |
if ( empty( $member_types ) ) { | |
return array(); | |
} | |
foreach ( $member_types as $member_type ) { | |
if ( isset( $settings[ $member_type ] ) ) { | |
return $settings[ $member_type ]; | |
} | |
} | |
return array();// no match. | |
} | |
// filter allowed count. | |
add_filter( 'bp_rate_limit_activity_throttle_duration', function ( $allowed_time, $user_id ) { | |
$settings = buddydev_get_activity_mtype_based_rates( $user_id ); | |
if ( ! empty( $settings ) ) { | |
$allowed_time = $settings['time']; | |
} | |
return $allowed_time; | |
}, 10, 2 ); | |
// filter allowed count. | |
add_filter( 'bp_rate_limit_activity_count', function ( $allowed_count, $user_id ) { | |
$settings = buddydev_get_activity_mtype_based_rates( $user_id ); | |
if ( ! empty( $settings ) ) { | |
$allowed_count = $settings['max']; | |
} | |
return $allowed_count; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment