AJAXChat WordPress BuddyPress Integration

Hi welcome back.

In this AJAXChat WordPress BuddyPress integration you are gonna be able to connect AJAXChat with WordPress BuddyPress and be able to use its role system to have Admin, Moderator and normal users for AJAXChat allowing you to easy have a Chat Server in your WordPress without using a plugin.

The requirements:

  • The PHP version I am using is PHP 7, as of right now the recommended version of PHP for WordPress is 7.04 > = .
  • WordPress version 5.4.2
  • download AJAXChat standalone, current version this tutorial was written base on is AJAX-Chat-0.8.8-standalone.
  • Drop AJAXChat content in a folder called CHAT , you can change this if you want but bare in mind the changes you have made.
  • WordPress for this tutorial is installed in a folder called wp-data that lives in the root folder of your webserver.
  • Install AJAXChat following the installation procedures stated in the readme.html .
  • Once installed, check to make sure its working correctly..
  • WordPress roles are implemented as follow install_plugins becomes AJAXChat Admin, edit_published_posts or edit_posts becomes AJAXChat Moderator and finally Subscriber becomes regular AJAXChat user.

If you want to disallow guest users from joining the chat then you will have to disable it going in the folder chat/lib/ and opening config.php if you haven created config.php a this point. please refer how to install the chat in readme.html. change the following in config.php $config['allowGuestLogins'] = true; to $config['allowGuestLogins'] = false;

Once all this is done, its time for editing.

Navigate to /chat/lib/ and edit custom.php then add the following as follow, take in account that we are using wp-data as folder for all our WP documents , reflect changes if you are using differently in your installation.

<?php
/*
 * @package AJAX_Chat
 * @author Sebastian Tschan
 * @copyright (c) Sebastian Tschan
 * @license Modified MIT License
 * @link https://blueimp.net/ajax/
 */

/*
 * AJAXChat WordPress integration
 * @uthor Neumann Valle aka TechUser
 * @date 07/24/2020
 */

// Include custom libraries and initialization code here
define('WP_USE_THEMES', false);

/**
 * define where your wordpress folder is located *
 */
$wp_folder = '/wp-data';

if (! file_exists($_SERVER['DOCUMENT_ROOT'] . $wp_folder . '/wp-blog-header.php')) {
    throw new \Exception('wp-blog-header.php could not be found, fix the correct path to wp-blog-header.php.');
    exit();
}

// require ($_SERVER['DOCUMENT_ROOT'] . '/wp-blog-header.php'); // use if your files are in root folder

require ($_SERVER['DOCUMENT_ROOT'] . $wp_folder . '/wp-blog-header.php');
?>

This tells AJAXChat where we can get WordPress functions and variables to be used in AJAXChat internals. if you get an error stating that path is incorrect then check where wp is installed, if all the files are in the root directory then un-comment require ($_SERVER['DOCUMENT_ROOT'] . '/wp-blog-header.php'); and comment out require ($_SERVER['DOCUMENT_ROOT'] . $wp_folder . '/wp-blog-header.php');

Now, we need to work and edit some more, navigate to /chat/lib/class folder in there look for PHP class document called CustomAJAXChat.php open it and delete everything inside, if you want you can make a backup and rename it anyway you want, if you backed up then you recreate CustomAJAXChat.php inside copy and paste the following class changes.

<?php

/*
 * @package AJAX_Chat
 * @author Sebastian Tschan
 * @copyright (c) Sebastian Tschan
 * @license Modified MIT License
 * @link https://blueimp.net/ajax/
 */

/*
 * AJAXChat WordPress integration
 * @uthor Neumann Valle aka TechUser
 * @date 07/24/2020
 */
class CustomAJAXChat extends AJAXChat
{

    // auto login PHP-fusion CMS
    public function initCustomRequestVars()
    {
        if (! $this->getRequestVar('logout') && is_user_logged_in()) {
            $this->setRequestVar('login', true);
        }

        $this->setheader_200();
    }

    // Returns an associative array containing userName, userID and userRole
    // Returns null if login is invalid
    public function getValidLoginUserData()
    {
        $wp_userdata = null;
        $user_data = false;
        $userData = array();

        // check we are logged in
        if (is_user_logged_in()) {

            $wp_userdata = wp_get_current_user();

            $userData['userID'] = $wp_userdata->ID;
            $userData['userName'] = $this->trimUserName($wp_userdata->user_login);

            if (current_user_can('install_plugins')) { // if can install plugin admin
                $userData['userRole'] = AJAX_CHAT_ADMIN;
            } elseif (current_user_can('edit_published_posts') || current_user_can('edit_posts')) { // if user has this capabilities
                $userData['userRole'] = AJAX_CHAT_MODERATOR;
            } else { // lastly we have normal user
                $userData['userRole'] = AJAX_CHAT_USER;
            }

            return $userData;
        } else if ($this->getRequestVar('password')) {

            $username = $this->trimUserName($this->getRequestVar('userName'));

            // check if the username is even
            // registered
            $user_data = get_user_by('login', $username);

            if ($user_data) {

                // check the password giving is correct
                $pass_valid = wp_check_password($this->getRequestVar('password'), $user_data->data->user_pass, $user_data->ID);

                if ($pass_valid) {
                    // get all the user data
                    $user = get_userdata($user_data->ID);

                    if ($user) {

                        // check user isn't suspended
                        if (! boolval($user->data->user_status)) {
                            $userData['userID'] = $user->ID;
                            $userData['userName'] = $username;

                            if (user_can($user->ID, 'install_plugins')) { // if can install plugin admin
                                $userData['userRole'] = AJAX_CHAT_ADMIN;
                            } elseif (current_user_can($user->ID, 'edit_published_posts') || current_user_can($user->ID, 'edit_posts')) { // if user has this capabilities
                                $userData['userRole'] = AJAX_CHAT_MODERATOR;
                            } else { // lastly we have normal user
                                $userData['userRole'] = AJAX_CHAT_USER;
                            }

                            return $userData;
                        }
                    }
                }
            }

            return null;
        } else {
            // Guest users:
            return $this->getGuestUser();
        }
    }

    // Store the channels the current user has access to
    // Make sure channel names don't contain any whitespace
    public function &getChannels()
    {
        if ($this->_channels === null) {
            $this->_channels = array();

            $customUsers = $this->getCustomUsers();

            // Get the channels, the user has access to:
            if ($this->getUserRole() == AJAX_CHAT_GUEST) {
                $validChannels = $customUsers[0]['channels'];
            } else {
                $validChannels = $customUsers[$this->getUserID()]['channels'];
            }

            // Add the valid channels to the channel list (the defaultChannelID is always valid):
            foreach ($this->getAllChannels() as $key => $value) {
                if ($value == $this->getConfig('defaultChannelID')) {
                    $this->_channels[$key] = $value;
                    continue;
                }
                // Check if we have to limit the available channels:
                if ($this->getConfig('limitChannelList') && ! in_array($value, $this->getConfig('limitChannelList'))) {
                    continue;
                }
                if (in_array($value, $validChannels)) {
                    $this->_channels[$key] = $value;
                }
            }
        }
        return $this->_channels;
    }

    // Store all existing channels
    // Make sure channel names don't contain any whitespace
    public function &getAllChannels()
    {
        if ($this->_allChannels === null) {
            // Get all existing channels:
            $customChannels = $this->getCustomChannels();

            $defaultChannelFound = false;

            foreach ($customChannels as $name => $id) {
                $this->_allChannels[$this->trimChannelName($name)] = $id;
                if ($id == $this->getConfig('defaultChannelID')) {
                    $defaultChannelFound = true;
                }
            }

            if (! $defaultChannelFound) {
                // Add the default channel as first array element to the channel list
                // First remove it in case it appeard under a different ID
                unset($this->_allChannels[$this->getConfig('defaultChannelName')]);
                $this->_allChannels = array_merge(array(
                    $this->trimChannelName($this->getConfig('defaultChannelName')) => $this->getConfig('defaultChannelID')
                ), $this->_allChannels);
            }
        }
        return $this->_allChannels;
    }

    public function &getCustomUsers()
    {
        // List containing the registered chat users:
        $users = null;
        require (AJAX_CHAT_PATH . 'lib/data/users.php');
        return $users;
    }

    public function getCustomChannels()
    {
        // List containing the custom channels:
        $channels = null;
        require (AJAX_CHAT_PATH . 'lib/data/channels.php');
        // Channel array structure should be:
        // ChannelName => ChannelID
        return array_flip($channels);
    }

    /**
     * WordPress return a 404 if header
     * is not set to 200, AJAXChat would
     * trew 404 error code
     */
    private function setheader_200()
    {
        header('HTTP/1.1 200 OK');
    }
}
?>

Once is done, navigate to chat folder and see login automatically if you are already logged in.. if not then you get the AJAXChat login page and you can enter you credentials and then you get logged in, if you opted to have guests then just clicking the login button will allow guest users to be guests in the AJAXChat.

Note : using the AJAXChat login won’t remember your credentials so if you navigate to WordPress site you will still need to log back in.

I am just a Tech User just like you. bye for now!