PHPFusion Integration with Ajax Chat

If you are here it is because you are looking to integrate Ajax Chat and PHPFusion CMS , be able to use PHPFusion credentials with Ajax Chat.

What is PHPFusion CMS? as described in their website.

PHP-Fusion is an all in one integrated and scalable opensource content management system written in PHP. The software is highly extensible with our official core infusions that makes it capable to fit any website purpose whether you are creating community portals or personal sites.

What is Ajax Chat?

is a free and fully customizable open source web chat implemented in JavaScript, PHP and MySQL which integrates nicely with common forum systems like phpBB, MyBB, FluxBB, SMF and vBulletin.

Requirements:

PHPFusion CMS requires PHP 7>= and Ajax Chat can be installed in PHP 5. so the only requirements here is PHP 7>= so bare in mind.. The current version of PHPFusion is 9.03.70 and Ajax Chat version is AJAX-Chat-0.8.8-standalone. Please download the standalone version of Ajax Chat.

Well let’s get to work, integrating PHPFusion with Ajax Chat is not a plugin what it actually is a connection to your PHPFusion so we can use their credential and let Ajax Chat pick their username id and capabilities of the PHPFusion Administrator and Super Administrator.

Now seriously let’s get to work now shall we?

  • Download and install Ajax Chat, follow the instruction in the readme.txt for installation procedures.
  • Once installed and you have make sure its working properly then navigate to chat folder where is installed then go to lib folder you will find a PHP document custom.php .
  • Open custom.php and then copy paste the following code
<?php
/*
 * @package AJAX_Chat
 * @author Sebastian Tschan
 * @copyright (c) Sebastian Tschan
 * @license Modified MIT License
 * @link https://blueimp.net/ajax/
 */

/*
 * Integration with phpfusion
 * @uthor Neumann Valle aka TechUser
 * @date 07/13/2020
 */

// Include custom libraries and initialization code here

if (! file_exists($_SERVER['DOCUMENT_ROOT'] . '/maincore.php')) {
    throw new \Exception('maincore.php was not found in the document root.');
    exit();
}

require $_SERVER{'DOCUMENT_ROOT'} . '/maincore.php' ;
?>

What it does is call the maincore.php that load all classes and internals of PHPFusion, we will have important data available to work with.. if you read at the last comment in the document, variable $userdata will be available and we can work with that to pass it on to Ajax Chat credential logic.

  • We now need to work with a class that Ajax Chat uses to pass credentials to the system.. navigate to lib folder and then browse class folder open it and find CustomAJAXChat.php documents. Open it and then paste the following code:
<?php

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

/*
 * Integration with phpfusion
 * @uthor Neumann Valle aka TechUser
 * @date 07/13/2020
 */
class CustomAJAXChat extends AJAXChat
{

    private $fusiondbinstance = null;

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

    // Returns an associative array containing userName, userID and userRole
    // Returns null if login is invalid
    public function getValidLoginUserData()
    {
        global $userdata;

        $phpfusion_userdata = null;

        if (iUSER) {
            $userData = array();
            $userData['userID'] = $userdata['user_id'];
            $userData['userName'] = $this->trimUserName($userdata['user_name']);

            if (iSUPERADMIN) {
                $userData['userRole'] = AJAX_CHAT_ADMIN;
            } elseif (iADMIN) {
                $userData['userRole'] = AJAX_CHAT_MODERATOR;
            } elseif (iMEMBER) {
                $userData['userRole'] = AJAX_CHAT_USER;
            }
            return $userData;
        } else if ($this->getRequestVar('password')) {

            // init phpfusion conn
            $this->init_phpfusiondb();

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

            // check we have an registered user
            if ($phpfusion_userdata) {

                // prepare to compare passwords
                $passAuth = new PasswordAuth();

                $passAuth->currentAlgo = $phpfusion_userdata["user_algo"];
                $passAuth->currentSalt = $phpfusion_userdata["user_salt"];
                $passAuth->currentPasswordHash = $phpfusion_userdata["user_password"];
                $passAuth->inputPassword = $this->getRequestVar('password');

                // check we got a correct password
                if ($passAuth->isValidCurrentPassword(TRUE)) {

                    $user_role = null;
                    // get the fusion role
                    if (($phpfusion_userdata['user_level'] == USER_LEVEL_SUPER_ADMIN)) {
                        $user_role = AJAX_CHAT_ADMIN;
                    } else if (($phpfusion_userdata['user_level'] == USER_LEVEL_ADMIN)) {
                        $user_role = AJAX_CHAT_MODERATOR;
                    } else if (($phpfusion_userdata['user_level'] == USER_LEVEL_MEMBER)) {
                        $user_role = AJAX_CHAT_USER;
                    }
                    $userData = array();
                    $userData['userID'] = $phpfusion_userdata['user_id'];
                    $userData['userName'] = $this->trimUserName($phpfusion_userdata['user_name']);
                    $userData['userRole'] = $user_role;

                    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);
    }

    /**
     * get our user from PHPFusion
     *
     * @param string $inputUserName
     * @return array|bool
     */
    private function custom_PHPfusion_login($inputUserName)
    {
        $userData = array();

        $where = "user_name";

        $sql = 'SELECT 
                        * 
                FROM 
                    ' . DB_USERS . '
                 WHERE 
                       ' . $where . ' 
                        =' . $this->db->makeSafe($inputUserName) . ' LIMIT 1';

        $result = $this->fusiondbinstance->sqlQuery($sql);

        // Stop if an error occurs:
        if ($result->error()) {
            echo $result->getError();
            die();
        }

        while ($row = $result->fetch()) {
            $userData = $row;
        }

        $result->free();

        return ! empty($userData) ? $userData : false;
    }

    /**
     * Create a new connection for phpfusion db
     * this is due that PHPFusion "dbquery" method don't seem
     * to be working for some reason..
     *
     * @return AJAXChatDataBase
     */
    private function init_phpfusiondb()
    {
        global $db_name;

        if (! $this->fusiondbinstance) {

            // ajax config reloaded?
            // todo what's wrong with this
            $this->initConfig();

            $db_connection = [
                'host' => $this->_config['dbConnection']['host'],
                'user' => $this->_config['dbConnection']['user'],
                'pass' => $this->_config['dbConnection']['pass'],
                'link' => $this->_config['dbConnection']['link'],
                'name' => $db_name
            ];

            $this->fusiondbinstance = new AJAXChatDataBase($db_connection);

            if (! $db_connection['link']) {
                // Connect to the database server:
                $this->fusiondbinstance->connect($db_connection);
                if ($this->fusiondbinstance->error()) {
                    echo $this->fusiondbinstance->getError();
                    die();
                }
                // Select the database:
                $this->fusiondbinstance->select($db_connection['name']);
                if ($this->fusiondbinstance->error()) {
                    echo $this->fusiondbinstance->getError();
                    die();
                }
            }
        }

        return $this->fusiondbinstance;
    }
}
?>

Let me explain a bit what we do here, first we make sure once we navigate to chat folder this lands automatically to the main chat is only a first step. with the help of

    public function initCustomRequestVars(){}
we do actually that, this however doesn\’t do the credential pick up!

We have then

public function getValidLoginUserData(){}
with this method then we check if we have someone registered and logged, meaning it has set cookies in the browser with credential and then we can pick up.

Apart from that we also if the user navigating the chat isn’t logged in and would want to , then we check credentials when he/she uses Ajax Chat login form.

If the credential presented are correct we then pull the data and return it in the method in the proper way Ajax Chat requires it..

At the very last needed to get other methods helper with they don’t come in the class but were created to be uses as helpers.

We create this method to get an Msqli instance so we can work with SQL server.

private function init_phpfusiondb(){}

The this method, check we have the user and if exists then we get its data but we don’t use to check the user credential where correct here.. we get the data to compare it and make sure the user has the correct credentials.

private function custom_PHPfusion_login($inputUserName){}

Can’t explain more in details otherwise this will become three pages.. now if you followed along then you should have now you PHPFusion credential system used with Ajax Chat.

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