AjaxChat WordPress Integration

This integration have been tested with Ajax Chat v 0.8.7 and WordPress 3.8.1.

This integration have been tested with Ajax Chat v 0.8.7 and WordPress 3.8.1,

It has the following features:

  • Auto login.
  • Administration based on WordPress management system.
  • Admin and Moderation based on WordPress system, Admin->install_plugins,
    Moderator->edit_published_post or Moderator->edit_posts.
  • Nickname in use.
  • Ajax Chat form integration with word press.

Previous integration http://vcomputadoras.com/integrar-ajaxchat-con-wordpress/ is deprecated, it shouldn’t work with newer Ajax Chat and WordPress versions.

No core file has been touched from standalone Ajax Chat but the custom files needed to integrate..
The code is cleaner and easy to read and maintain..

You will have the option to download the integration and read and or edit tru the tutorial.

Downloading:

Download the file ajaxChat.zip and uncompress chat folder in your WordPress folder root installation, then install as usual, read installation steps in readme file in the chat folder.

Using the tutorial:
This tutorial was done using the normal installation of WordPress, the following installation structure must be consider:

  • All WordPress file resides in the web folder
  • Ajax Chat files and folders are placed in a folder called “chat“, this folder resides along with WordPress files and folders.

Lets get down to editing now.

Open custom.php located in ‘/lib’ folder in your ‘chat‘ folder, we are going to add the following code:

<?php
/*
 * @package AJAX_Chat
 * @author Sebastian Tschan
 * @copyright (c) Sebastian Tschan
 * @license Modified MIT License
 * @link https://blueimp.net/ajax/
 * 
 * WordPress integration
 * @author  Neumann Valle
 * @link http://vcomputadoras.com/ajaxchat-wordpress-integration/
 */

// Include custom libraries and initialization code here
	
	// init WordPress
	if( isset( $_SERVER['DOCUMENT_ROOT'] ) ){
		$file	= $_SERVER['DOCUMENT_ROOT'].'wp-config.php';
		if( !file_exists( $file ) ){
			exit( 'wp-config.ph couldn\'t be found in your WordPress installation, please fix $file variable with correct one.');
		}
	}else{
			exit( 'your server could be misconfigurated , DOCUMENT_ROOT was not available in server globals.' );
	}
	// require wp-config.php
	require_once( $file );
	// initiate $current_user var
	global $current_user;
	get_currentuserinfo();
	
?>

That should be sufficient to require our WordPress initiation vars and functions, if you get an error like.
wp-config.php couldn’t be found in your WordPress installation, please fix $file variable with correct one.

Check and fix your require path in $file variable, eg, if you have WordPress installed in /blog folder then you need to fix the path like this.

$file	= $_SERVER['DOCUMENT_ROOT'].'blog/'.'wp-config.php';

That should help, if it doesn’t and you get a different error then make sure your $_SERVER vars are correctly set in your server..

Now that custom.php is out of the way, open CustomAJAXChat.php located in ‘/lib/clasess/’ folder, lets do it easy remember that we are working on AjaxChat v 0.8.7 , delete all its content and copy paste this code onto the file.

<?php
/*
 * @package AJAX_Chat
 * @author Sebastian Tschan
 * @copyright (c) Sebastian Tschan
 * @license Modified MIT License
 * @link https://blueimp.net/ajax/
 * 
 * WordPress integration
 * @author  Neumann Valle
 * @link http://vcomputadoras.com/ajaxchat-wordpress-integration/
 */

class CustomAJAXChat extends AJAXChat {

	function initCustomRequestVars(){
		if( !$this->getRequestVar('logout') && is_user_logged_in() ) {
			$this->setRequestVar('login', true);
		}
	}
	/**
	 * Returns an associative array containing userName, userID and userRole
	 * Returns guest login if null
	**/
	function getValidLoginUserData() {
		// globalize the important variables from WP
		global $current_user;
		// Check if we have a valid registered user:
		$customUsers = $this->getCustomUsers();
		if( isset( $current_user ) && is_user_logged_in() ){
			$userData 				= 	array();
			$userData['userID']		=	$current_user->data->ID;
			$userData['userName']	=	$this->trimUserName( $current_user->data->display_name );
			if( current_user_can('install_plugins') ){
				$userData['userRole'] = AJAX_CHAT_ADMIN;
			}else if( current_user_can('edit_published_posts') || 
						current_user_can('edit_posts') ){ 
				$userData['userRole'] = AJAX_CHAT_MODERATOR;
				}else{
				$userData['userRole'] = AJAX_CHAT_USER;
			}
			//echo '<script>console.log('.json_encode( $userData ).')</script>';
			return $userData;
		}
		if( $this->getRequestVar('password') ) {
				$userName = $this->getRequestVar('userName');
				$userName = $this->convertEncoding($userName, $this->getConfig('contentEncoding'), $this->getConfig('sourceEncoding'));
				
				$password = $this->getRequestVar('password');
				$password = $this->convertEncoding($password, $this->getConfig('contentEncoding'), $this->getConfig('sourceEncoding'));
				
				foreach( $customUsers as $key => $value ) {
					if( ($value['userName'] == $userName) && ($value['password'] == $password) ) {
						$userData = array();
						$userData['userID'] = $key;
						$userData['userName'] = $this->trimUserName($value['userName']);
						
						$userData['userRole'] = $value['userRole'];
						return $userData;
					}
				}
				return null;
			}else{
				// Guest users:
				return $this->getGuestUser();
			}
	}
	function getGuestUser() {
		if(!$this->getConfig('allowGuestLogins'))
		return null;
		
		if($this->getConfig('allowGuestUserName')) {
			$maxLength =	$this->getConfig('userNameMaxLength')
			- $this->stringLength($this->getConfig('guestUserPrefix'))
			- $this->stringLength($this->getConfig('guestUserSuffix'));
			
			$userName	=$this->getRequestVar('userName');
			
			// Trim guest userName:
			$userName = $this->trimString($this->getRequestVar('userName'), null, $maxLength, true, true);
			
			// check if usernick choosen as guest is in the WP database.. if its is Deny access.
			if( username_exists( $userName ) ){
				return null;
			}
			
			// If given userName is invalid, create one:
			if(!$userName) {
				$userName = $this->createGuestUserName();
			} else {
				// Add the guest users prefix and suffix to the given userName:
				$userName = $this->getConfig('guestUserPrefix').$userName.$this->getConfig('guestUserSuffix');	
			}
		} else {
			$userName = $this->createGuestUserName();
		}
		
		$userData = array();
		$userData['userID'] = $this->createGuestUserID();
		$userData['userName'] = $userName;
		$userData['userRole'] = AJAX_CHAT_GUEST;
		return $userData;		
	}
	
	/**
	 * Store the channels the current user has access to
	 * Make sure channel names don't contain any whitespace
	 **/
	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'];
				$validChannels = $customUsers[0]['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
	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;
	}

	function &getCustomUsers() {
		// List containing the registered chat users:
		$users = null;
		require(AJAX_CHAT_PATH.'lib/data/users.php');
		return $users;
	}
	
	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);
	}

}

Make sure you pasted it correctly… save it and let’s continue with the tutorial.

Now open the document loggedOut.html located in ‘/lib/template/’ folder, do the same process as in previous file, delete all its content and paste the following onto it..

<?xml version="1.0" encoding="[CONTENT_ENCODING/]"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="[LANG_CODE/]" lang="[LANG_CODE/]" dir="[BASE_DIRECTION/]">

<head>
	<meta http-equiv="Content-Type" content="[CONTENT_TYPE/]" />
	<title>[LANG]title[/LANG]</title>
	<style type="text/css">
		body {
			padding:0;
			margin:0;
		}
	</style>
	[STYLE_SHEETS/]
	<!--[if lt IE 7]>
		<link rel="stylesheet" type="text/css" href="css/ie5-6.css"/>
	<![endif]-->
	<script src="js/chat.js" type="text/javascript" charset="UTF-8"></script>
	<script src="js/lang/[LANG_CODE/].js" type="text/javascript" charset="UTF-8"></script>
	<script src="js/config.js" type="text/javascript" charset="UTF-8"></script>
	<script type="text/javascript">
		// <![CDATA[
			function initializeLoginPage() {
				document.getElementById('userNameField').focus();
				if(!ajaxChat.isCookieEnabled()) {
					var node = document.createElement('div');
					var text = document.createTextNode(ajaxChatLang['errorCookiesRequired']);
					node.appendChild(text);
					document.getElementById('errorContainer').appendChild(node);
				}
				// set action post and redirect to, wordpress integration
				ajaxChat_loginform();
			}
			// set wordpress specifics
			function ajaxChat_loginform(){
			var loginForm	=	document.getElementById('loginForm');
				if( typeof loginForm === 'object' ){
					loginForm.action 						= ajaxChatConfig.wplogin_path;
					loginForm.elements['redirect_to'].value = ajaxChatConfig.afterwpLoginRedirect;
				}
			}
			
			ajaxChatConfig.sessionName = '[SESSION_NAME/]';
			ajaxChatConfig.cookieExpiration = parseInt('[COOKIE_EXPIRATION/]');
			ajaxChatConfig.cookiePath = '[COOKIE_PATH/]';
			ajaxChatConfig.cookieDomain = '[COOKIE_DOMAIN/]';
			ajaxChatConfig.cookieSecure = '[COOKIE_SECURE/]';

			ajaxChat.init(ajaxChatConfig, ajaxChatLang, true, true, false);
		// ]]>
	</script>
	<script type="text/javascript">
		// <![CDATA[
		function handleLogin() {
			var loginForm = document.getElementById('loginForm');
			var userNameField = document.getElementById('userNameField');
			var passwordField = document.getElementById('passwordField');
			var channelField = document.getElementById('channelField');
			var redirectField = document.getElementById('redirectField');
			if(passwordField.value.length == 0) {
				loginForm.setAttribute('action', '[LOGIN_URL/]');
				userNameField.setAttribute('name', 'userName');
			} else {
				var channelRequest = 'channelName=' + encodeURIComponent(channelField.value);
				var regExp = /\?/;
				if(regExp.test(redirectField.value)) {
					redirectField.value += '&';
				} else {
					redirectField.value += '?';
				}
				redirectField.value += channelRequest;
			}
			return true;
		}
		// ]]>
	</script>
</head>

<body onload="initializeLoginPage();">
	<div id="loginContent">
		<div id="loginHeadlineContainer">
			<h1>[LANG]title[/LANG]</h1>
		</div>
		<form id="loginForm" action="" method="post" enctype="application/x-www-form-urlencoded" onsubmit="return handleLogin();">
			<div id="loginFormContainer">
				<input type="hidden" name="login" id="loginField" value="login"/>
				<input type="hidden" name="redirect" id="redirectField" value="[REDIRECT_URL/]"/>
				<div><label for="userNameField">[LANG]userName[/LANG]:</label><br />
				<input type="text" name="log" id="userNameField" maxlength="[USER_NAME_MAX_LENGTH/]"/></div>
				<div><label for="passwordField">[LANG]password[/LANG]*:</label><br />
				<input type="password" name="pwd" id="passwordField"/></div>
				<div><label><input name="rememberme" type="checkbox" id="rememberme" value="forever" tabindex="90" /> Remember Me?</label></div>
				<div><label for="channelField">[LANG]channel[/LANG]:</label><br />
				<select name="channelName" id="channelField">[CHANNEL_OPTIONS/]</select></div>
				<div><label for="languageSelection">[LANG]language[/LANG]:</label><br />
				<select id="languageSelection" name="lang" onchange="ajaxChat.switchLanguage(this.value);">[LANGUAGE_OPTIONS/]</select></div>
				<div><input type="submit" name="submit" id="loginButton" value="[LANG]login[/LANG]"/></div>
				<div><input type="hidden" name="redirect_to" value="" /></div>
				<div id="loginRegisteredUsers">* [LANG]registeredUsers[/LANG]</div>
			</div>
		</form>
		<div id="errorContainer">[ERROR_MESSAGES/]<noscript><div>[LANG]requiresJavaScript[/LANG]</div></noscript></div>
		<!--
			Please retain the full copyright notice below including the link to blueimp.net.
			This not only gives respect to the amount of time given freely by the developer
			but also helps build interest, traffic and use of AJAX Chat.
			
			Thanks,
			Sebastian Tschan
			
			Ajax integration with WordPress
			Neumann Valle
			
AjaxChat WordPress Integration
//--> <div id="copyright"><a href="https://blueimp.net/ajax/">AJAX Chat</a> &copy; <a href="https://blueimp.net">blueimp.net</a></div> </div> </body> </html>

This last edit is really important because it has new code that logins against WordPress , ‘wp-login.php‘ which authenticates and set credentials, if the user tries a name registered and want to use as guest nickname will get an error the name is invalid, but if he tries his/her WordPress credential it will be logged in and redirected to the chat..

Last but not least open config.js located in the JS folder of ‘chat‘ find the following var:

// The base URL of the chat directory, used to retrieve media files (images, sound files, etc.):
	baseURL: './'

After that variable paste the following without touching any other var:

	// base url where your wp-login.php reside that is used for the login ajax login form
	wplogin_path : '../../wp-login.php',
	
	// url where the browser should redirect after a sucessful login to wordpress
	afterwpLoginRedirect: 'chat/',

This two new var tells the login form where to POST and to redirect after a successful authentication in WordPress.

wplogin_path : '../../wp-login.php',

Tells the action form and where wp-login.php is located, fix it if your installations isn’t the same as the tutorial.

afterwpLoginRedirect: 'chat/',

Tells where to redirect after the login succeed , replace it with the path of your chat folder..

and that’s it, install the chat as directed in the read me file.

You found bugs post them here.. comments welcome.