Un poco de html
refrescar diferentes divs con javascript y ajax
En un POST anterior les deje un tutorial de como refrescar un div tag sin necesidad de refrescar la pagina completa, bien en esta ocasión e pulido mejor el código y e creado una función que refresque cualquier cantidad de DIVs sin necesidad que se refresque la pagina completa..
Esto facilita el uso del código para cualquier circunstancia que nos enfrentemos al crear nuestra web..
Refrescando diferentes div tags usando javascript y ajax.
La función que usaremos se llama refreshDivs(divid , secs , url) , la función acepta 3 parámetros mandatarios:
- divid = este es el ID del div que quieres refrescar.
- secs = los segundo en que deseas que el div se refresque.
- url = La dirección del documento que deseas que aparezca en el DIV.
El URL puede ser cualquier clase de documento, sea php, html, shtml etc ..
Ok ahora el paso a seguir es colocar en tu html entre los “<head>” tags el siguiente código abajo mostrado.
<script type="text/javascript" language="javascript">
function refreshDivs(divid,secs,url)
{
// define our vars
var divid,secs,url,fetch_unix_timestamp;
// Chequeamos que las variables no esten vacias..
if(divid == ""){ alert('Error: escribe el id del div que quieres refrescar'); return;}
else if(!document.getElementById(divid)){ alert('Error: el Div ID selectionado no esta definido: '+divid); return;}
else if(secs == ""){ alert('Error: indica la cantidad de segundos que quieres que el div se refresque'); return;}
else if(url == ""){ alert('Error: la URL del documento que quieres cargar en el div no puede estar vacia.'); return;}
// The XMLHttpRequest object
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Tu explorador no soporta AJAX.");
return false;
}
}
}
// Timestamp para evitar que se cachee el array GET
fetch_unix_timestamp = function()
{
return parseInt(new Date().getTime().toString().substring(0, 10))
}
var timestamp = fetch_unix_timestamp();
var nocacheurl = url+"?t="+timestamp;
// the ajax call
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
document.getElementById(divid).innerHTML=xmlHttp.responseText;
setTimeout(function(){refreshDivs(divid,secs,url);},secs*1000);
}
}
xmlHttp.open("GET",nocacheurl,true);
xmlHttp.send(null);
}
// LLamamos las funciones con los repectivos parametros de los DIVs que queremos refrescar.
window.onload = function startrefresh(){
refreshDivs('div1',5,'div1.php');
refreshDivs('div2',3,'div2.php');
refreshDivs('div3',10,'div3.php');
}
</script>
La parte del código donde indicamos que divs hay que refrescar es la siguiente:
window.onload = function startrefresh(){
refreshDivs('div1',5,'div1.php');
refreshDivs('div2',3,'div2.php');
refreshDivs('div3',10,'div3.php');
}
Utilizando el evento window.onload hacemos que nuestro explorador corra la función y esta nos refresque los divs que deseamos que sean refrescado sin necesidad de recargar o refrescar la pagina completa..
Repite las funciones con diferentes div, tiempos y urls no hay limitaciones a la cantidad de veces que quieras usarla.
En nuestro ejemplo, usare documentos php, pero no es necesario puede ser cualquier clase de documentos mientra sean soportados por tu webserver o hosting service.
div1.php
div1.php sera un simple script que cambiara números al azar, como verán este es el documento llamado en la función arriba que es refreshDivs(‘div1′,5,’div1.php’).
Este documento sera llamado cada 5 segundos y se mostrara en el div1
Los otros dos ejemplos son similares a este primero, solo cambian el ID del DIV el tiempo en segundos y la url o la dirección del documento PHP.
<?php echo "<p style=\"background-color:#FF7400\">Aquí obtendremos números al asar ".rand(1, 1000)."</p>"; ?>
div2.php
div2.php repetirá las palabras “Por favor repite me” tantas veces como la variable $veces sea definida por la funcion rand() .
<?php
$veces = rand(1,20);
for($i= 0; $i <= $veces; $i++)
{
echo "<p style=\"background-color:#356AA0\">".$i." Por favor repite me, ".$veces." veces.</p>";
}
?>
div3.php
Es el mismo caso para el div3.php, repetirá las palabras “Por favor repite me” tantas veces como la variable $veces sea definida por la funcion rand() , con la única diferencia que el color de el fondo es diferente y la cantidad de segundos a refrescar…
<?php
$veces = rand(1,20);
for($i= 0; $i <= $veces; $i++)
{
echo "<p style=\"background-color:#C79810\">".$i." Por favor repite me, ".$veces." veces.</p>";
}
?>
Estos son simples ejemplos donde podrás observar como trabaja la función de la que hablamos..
Otros usos
No solo puedes refrescar con Ajax divs si no también otros html tags, como span , form, tablas, H, P y otros mas , tan solo tienes que definir un id para esa tag, una nota importante es que al documento que se llame debe correr o parsear el contenido en tu servidor, ya que el Ajax es en el Cliente osea tu explorador.
Si este documento es un archivo TXT y tiene código javascript es posible que tu explorador lo corra pero si es archivo TXT tiene código PHP, JSP o u otros no sera parseado por el Ajax, lo que pinteara en tu pagina es el código en si tal cual..
Veamos todo el código con el HTML:
<html>
<head>
<title>Ejemplos de como refrescar varios div tags usando javascript y ajax.</title>
<script language="Javascript" type="text/javascript">
function refreshDivs(divid,secs,url)
{
// define our vars
var divid,secs,url,fetch_unix_timestamp;
// Chequeamos que las variables no esten vacias..
if(divid == ""){ alert('Error: escribe el id del div que quieres refrescar'); return;}
else if(!document.getElementById(divid)){ alert('Error: el Div ID selectionado no esta definido: '+divid); return;}
else if(secs == ""){ alert('Error: indica la cantidad de segundos que quieres que el div se refresque'); return;}
else if(url == ""){ alert('Error: la URL del documento que quieres cargar en el div no puede estar vacia.'); return;}
// The XMLHttpRequest object
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Tu explorador no soporta AJAX.");
return false;
}
}
}
// Timestamp para evitar que se cachee el array GET
fetch_unix_timestamp = function()
{
return parseInt(new Date().getTime().toString().substring(0, 10))
}
var timestamp = fetch_unix_timestamp();
var nocacheurl = url+"?t="+timestamp;
// the ajax call
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
document.getElementById(divid).innerHTML=xmlHttp.responseText;
setTimeout(function(){refreshDivs(divid,secs,url);},secs*1000);
}
}
xmlHttp.open("GET",nocacheurl,true);
xmlHttp.send(null);
}
// LLamamos las funciones con los repectivos parametros de los DIVs que queremos refrescar.
window.onload = function startrefresh(){
refreshDivs('div1',5,'div1.php');
refreshDivs('div2',3,'div2.php');
refreshDivs('div3',10,'div3.php');
}
</script>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
</body>
</html>
Puedes ver los ejemplos funcionando dando click en Refrescar varios Divs tags con javascript y ajax.
La función esta completa pues chequea que los parámetros estén definidos si no lo están un javascript alert te advetira del problema y el script terminara su función..
Por favor si te a gustado el código deja tu mensaje, y si encuentras algún problema no temas en postear aquí mismo gracias por Leer..
Actualiza un DIV usando menus y ajax.
Bueno,
Un amigo que posteo por acá, me pidió que como le aria para que se actualizara un DIV usando un evento onClick de un Menú y que cuando este se presionara este llenara con el contenido de otro documento un respectivo DIV..
Como actualiza un DIV con un documento determinado , dependiendo de el enlace o hyperlink que fue cliqueado, usando AJAX..
Cliquea aquí para ver una demostración de como quedo..
Entonces me vi en la tarea de hacerlo un echo e aquí el resultado:
- Primero, nuestro interés esque cada hyperlink en el Menú, lleve respectivamente a una pagina HTML, PHP o TXT.
- Segundo, saber el ID del DIV donde quieras que aparezca.
- Tercero crear los documentos y colocar su ubicación el los “lis “del menu.
Ahora en una pagina html, php, shtml. copia y pega esto:
<html>
<title>Request a page onclick Menu</title>
<head>
<script type="text/javascript">
function getPages(divid,url)
{
if(divid !="" && url != "")
{
var ob= AjaxObject();
var unixTimeStamp= fetch_unix_timestamp();
var nocacheurl = url+ "?t=" + unixTimeStamp;
ob.onreadystatechange=function()
{
if(ob.readyState==4)
{
if(ob.status == 200)
{
if(ob.responseText != null)
{
document.getElementById(divid).innerHTML=ob.responseText;
}else
{
alert('There was an error: no data was received');
}
}else
{
alert('Ajax error:' + ob.statusText);
}
}
}
ob.open("GET",nocacheurl,true);
ob.send(null);
}else{
alert('Se te a olvidado colocar el id del DIV o el URL en el href del achor tag, en el evento de onClick ');
}
}
function fetch_unix_timestamp()
{
return parseInt(new Date().getTime().toString().substring(0, 10))
}
function AjaxObject()
{
var xmlHttp;
try{
return xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
}
catch (e){
try{
return xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
}
catch (e){
try{
return xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Sorry AJAX is not supported by your browser.");
return false;
}
}
}
}
</script>
</head>
<body>
<ul>
<li><a href="my_text.txt" onClick="getPages('response',this); return false" >Cliqueame porfavor</a></li>
<li><a href="second_text.txt" onClick="getPages('response',this); return false" >Cliqueame aqui tambien.</a></li>
</ul>
<div id="response"></div>
</body>
</html>
Ahora explico la función getPages(divid,url) es la que ara todo el trabajo por nosotros, esta función puede ser pasada en el onclick de un boton o de A (anchor tag) de un hyperlink.
Solo pasas en el primer argumento el id del DIV donde quieres que aparezca el contenido del documento y en el segundo el url del documento que aparecerá en el DIV del primer argumento , que en este caso esta definido en el HTML markup, que es el DIV id=”response”.
Entonces en el href del anchor tag colocas el onClick=”getPages(‘response’,this)” donde el “response” es el ID del DIV, y this es referido al objeto que es el URL del href.
Así mismo si quieres usarlo en diferentes DIV también funcionaria solo colocas el ID del DIV donde quieras que el conteniendo del documento aparezca..
Así si lo deseas puedes colocar el contendido de cualquier documentos en diferentes DIVs sin ningún problema..
Bueno hasta la próxima, gracias por leer este tutorial..
Flashchat 6.0.8 and PHP-FUSION 7 integration.
Flashchat 6.0.8 and PHP-FUSION v7.01.04 Integration.
So here is goes, this is the integration of Flashchat 6.0.8 and PHP-FUSION V7.
Disclaimer:
FLASHCHAT is property of http://tufat.com, this integration is done in good faith, and so I have no responsibility of any kind and I not claiming is my script.. I've made this fix for the community of PHP-FUSION.
Flashchat is a very nice Chat interface made with flash.. I really like it a lot one of the most full featured FLASH CHAT there is although in beta stage as it is right now is really complete and stable..
What was missing is the PHP-FUSION v 7 connection with the usernames stored in the Mysql Database, there is a new version of PHP-FUSION v7.01.05 and it should also work with this integration ..
So I decided to fix the integration and finally was able to finish it, the team of PHP-FUSION changed the way to encrypt the user password..
The following are the features of the integration.
- Connect the usernames from database.
- Super Admin becomes Admin in Flashchat 6.0.8
- Admin user Without any privileges in PHP-FUSION becomes Moderator in Flashchat 6.0.8
- Auto login when user is logged in PHP-FUSION V7 site.
- User login also works using Flashchat 6.0.8 flash login form..
You can download the integration and drop it in the right place in your Flaschat 6.0.8 or you can copy paste the below code..
If you want to download please click Flashchat 6.0.8 and PHP-FUSION v7.01.04 .
Manual creation of the Integration for FLASHCHAT 6.0.8 and PHP-FUSIONv7.
Create a PHP document in the folder “./chat/inc/cmses/” the PHP document must be called “fusion7CMS.php”.
Copy paste this code..
<?php
/*
* Integration fix by Neumann Valle aka utan, september 26, 2011
* original code and post at http://vcomputadoras.com/flashchat-6-0-8-and-php-fusion-7/
* where php-fusion was still using md5() hashes.
*
* */
$fusion_root_path = realpath(dirname(__FILE__) . '/../../../') . '/';
require_once($fusion_root_path . 'config.php');
class FusionCMS {
var $userid;
var $loginStmt;
var $getUserStmt;
var $getUsersStmt;
function FusionCMS() {
$this->loginStmt = new Statement('SELECT user_id AS id, user_name AS login, user_password, user_level FROM '.DB_PREFIX.'users WHERE user_name=? AND user_password=? LIMIT 1');
$this->getUserStmt = new Statement('SELECT user_id AS id, user_name AS login, user_level FROM '.DB_PREFIX.'users WHERE user_id=? LIMIT 1');
$this->getUsersStmt = new Statement('SELECT user_id AS id, user_name as login FROM '.DB_PREFIX.'users');
$this->userid = NULL;
if (isset($_COOKIE['fusion_user'])) {
$cookie_vars = explode('.', $_COOKIE['fusion_user']);
$cookie_1 = is_numeric($cookie_vars['0']) ? $cookie_vars['0'] : NULL;
$cookie_2 = (preg_match('/^[0-9a-z]{32}$/', $cookie_vars['1']) ? $cookie_vars['1'] : '');
$this->userid = $cookie_1;
}
}
function isLoggedIn() {
return $this->userid;
}
function getRoles($group) {
$rv = ROLE_USER;
if ($group == 101)
{
$rv = ROLE_USER;
}
if ($GLOBALS['fc_config']['liveSupportMode'] && $group == 101)
{
$rv = ROLE_CUSTOMER;
}
if ($group == 102)
{
$rv = ROLE_MODERATOR;
}
if ($group == 103)
{
$rv = ROLE_ADMIN;
}
return $rv;
}
function getUserProfile($userid) {
if ($userid == SPY_USERID) $rv = NULL;
elseif ($user = $this->getUser($userid)) {
$rv = ($id = $this->isLoggedIn() && ($id == $userid)) ? '../edit_profile.php' : '../profile.php?lookup=' . $userid;
return $rv;
}
}
function getUser($userid) {
// if ($userid == SPY_USERID) return NULL;
$rv = NULL;
if(($rs = $this->getUserStmt->process($userid)) && ($rec = $rs->next())) {
$rec['roles'] = $this->getRoles($rec['user_level']);
$rv = $rec;
}
return $rv;
}
function login($login, $password) {
if (($rs = $this->loginStmt->process($login, md5(md5($password)))) && ($rec = $rs->next())) {
if ($rec['user_ban']) return NULL; /* user is banned from the site */
$cookie_value = $rec['id'] . '.' . md5(md5($password));
setcookie('fusion_user', $cookie_value, time() + 3600*3, '/', '', '0');
return $rec['id'];
}
}
function userInRole($userid, $role) {
if($user = $this->getUser($userid)) {
return ($user['roles'] == $role);
}
return false;
}
function logout() {
}
function getUsers() {
$rv = $this->getUsersStmt->process();
return $rv;
}
function getGender($userid) {
// 'M' for Male, 'F' for Female, NULL for undefined
return NULL;
}
}
$GLOBALS['fc_config']['db'] = array(
'host' => $db_host,
'user' => $db_user,
'pass' => $db_pass,
'base' => $db_name,
'pref' => DB_PREFIX . 'fc_'
);
$GLOBALS['fc_config']['cms'] = new FusionCMS();
foreach($GLOBALS['fc_config']['languages'] as $k => $v) {
$GLOBALS['fc_config']['languages'][$k]['dialog']['login']['moderator'] = '';
}
?>
Now done the above edit a PHP document in the folder “/chat/install_files/” the PHP document is called “consts.php” .
copy paste the following code:
<?php
/**
** Constants used for installation file.
**/
define('INC_DIR', dirname(__FILE__) . '/../inc/');//for config.php
define('NAVY_FILE_SIZE', 1992);//necessary for check uploaded in binary mode
define('CHAT_ROOMS', 'The Lounge, Hollywood, Tech Talk, Current Events');//default rooms
define('CONFIG_FILE', INC_DIR . 'config.php');
define('INST_DIR', './install_files/');
$cmss = array(
//'aedatingCMS' => 'aeDating 2.0/3.0 (FlashChat is built in to aeDating 3.x)',
//'aedatingCMS2'=> 'aeDating 2.0/3.0 (which only permits access to Gold members)',
//'aedating4CMS'=> 'aeDating 4.0',
'azdgCMS' => 'AZDG Dating Lite 2.1.2',
'cpgNukeCMS' => 'CPGNuke',
'cpgNukeDragonfly921CMS' => 'CPGNuke Dragonfly 9.2.1',
'datingProCMS'=> 'Dating Pro',
'e107CMS' => 'e107 0.617',
'eMeetingCMS' => 'eMeeting',
'efriendsCMS497' => 'Alstrasoft E-friends 4.9.7',
'fusionCMS' => 'PHP Fusion 4.0.0',
'fusionCMS2' => 'PHP Fusion 5.0.1',
'fusion6CMS' => 'PHP Fusion 6',
'fusion7CMS' => 'PHP Fusion 7',
'geeklogCMS' => 'GeekLog 1.3.9',
'joomlaCMS' => 'Joomla 1.1',
'ipbCMS' => 'Invision Power Board (IPB) 2.0.0',
'ipbCMS2' => 'Invision Power Board (IPB) 2.0.3',
'ipbCMS2' => 'Invision Power Board (IPB) 2.1.0',
'ipb30CMS' => 'Invision Power Board (IPB) 3.0.3',
'lunabyteCMS' => 'LunaByte / Enigma 1.3',
'mamboCMS' => 'Mambo 4.5.0',
'mamboCMS2' => 'Mambo 4.5.2',
'mambo465CMS' => 'Mambo 4.6.5',
'mdproCMS' => 'MD-Pro 1.0.7',
'mdpro1081CMS' => 'MD-Pro 1.0.81',
'moodleCMS' => 'Moodle',
'moodle16CMS' => 'Moodle 1.6',
'moodle17CMS' => 'Moodle 1.7',
'moodle18CMS' => 'Moodle 1.8',
'moodle19CMS' => 'Moodle 1.9',
'osdateCMS' => 'osDate Dating System',
'phpBB2CMS' => 'phpBB 2.0.10 and above',
'phpBB3CMS' => 'phpBB 3.0.B2 and above',
'phpBB307CMS' => 'phpBB 3.0.2 and above',
'phpBB305CMS' => 'phpBB 3.0.5 and above',
//'phpNukeModCMS' => 'PHP-Nuke 7.3(module version)',
'phpNukeCMS73' => 'PHP-Nuke 7.3',
'phpNukeCMS76' => 'PHP-Nuke 7.6',
'phpNukeCMS78' => 'PHP-Nuke 7.8',
//'postNukeModCMS' => 'PostNuke 0.726-3(module version)',
'postNukeCMS' => 'PostNuke 0.726-3',
'postNukeCMS0762' => 'PostNuke 0.762',
'phorumCMS518' => 'Phorum 5.1.8',
'phorumCMS527' => 'Phorum 5.2.7',
'smfCMS' => 'Simple Machines 1.0',
'smfCMS2' => 'Simple Machines 1.1',
'smfCMS20' => 'Simple Machines 2.0',
'ubbCMS' => 'UBB.Threads 6.5',
'ubb70CMS' => 'UBB.Threads 7.0',
'ubb71CMS' => 'UBB.Threads 7.1',
'ubb74CMS' => 'UBB.Threads 7.4',
'vbulletin30CMS'=> 'vBulletin 3.0',
'vbulletin35CMS'=> 'vBulletin 3.5',
'vbulletin36CMS'=> 'vBulletin 3.6',
'vbulletin37CMS'=> 'vBulletin 3.7',
'vbulletin38CMS'=> 'vBulletin 3.8',
'vbulletin40CMS'=> 'vBulletin 4.0',
'webDateCMS' => 'Web Date',
'wotCMS2' => 'WoltLab Burning Board 2.3.4',
'wowCMS' => 'WowBB 1.6.1',
'wowCMS2' => 'WowBB 1.6.2',
'wowCMS165' => 'WowBB 1.6.5',
'wowCMS170' => 'WowBB 1.7',
'xmbCMS' => 'XMB 1.9.1',
'xoopsCMS' => 'Xoops 2.0.7',
'xoops2016CMS' => 'Xoops 2.0.16',
'phpkitCMS' => 'phpkit 1.6.1',
'MyBBCMS' => 'MyBB 1.0',
'easysiteCMS' => 'EasySite 3.2.5',
'SBDatingCMS' => 'Softbiz Dating',
'phpFox108' => 'phpFox 1.0.8',
'phpFox11' => 'phpFox 1.1',
'phpFox16CMS' => 'phpFox 1.6',
'inspirations31CMS' => 'Inspirations 3.1',
'drupalCMS' => 'Drupal',
'drupal613CMS' => 'Drupal 6.1.3',
'punbbCMS' => 'punBB 1.2.10',
'wordpress22CMS' => 'WordPress 2.1.0 - 2.7',
);
?>
That’s all, install the chat and everything should work..
please comment about it.. thanks.
Integrate PHP-Fusion with ajax_chat
PHP-Fusion is Content Management System,
note: Since my folder path are not the same as others in the web, please find the real path for your installation otherwise you would think that the integration doesn't work which it does it.
This integration is for PHP-Fusion v7.01.04 and AJAX CHAT version 0.8.3 .
note: latest PHP-Fusion v7.02.01 also works with this integration.
A little of info from the official Website.
a light-weight open-source content management system (CMS). PHP-Fusion is written in PHP and MySQL and includes a simple, comprehensive administration system as well as Forum, Photogallery, Articles, FAQ and much more.
Unfortunately his founder and lead coder MR Nick Jones passed away and the users and community is mourning this lost, Descanse en Paz..
This integration has the following features,
- Set user admin
- Set user moderator
- Set the regular chatters username
- Check if guest login usernick is registered in the Fusion database.
Now SuperAdmin becomes Admin in ajax chat, userAdmin becomes Moderator in the ajax chat and regular user becomes regular users.
in order to have a moderator you need to set a regular user as admin, you can do that in the control panel of PHP-FUSION CMS , its up to you if you want this user have all the admin privileges, in my testing I lef the boxes to give all privileges blank so it could only have the admin flag but not all privileges..
So please be careful when setting this up.. this is in a default installation, and with the most uptodate PHP-FUSION CMS..
Please install ajax chat as described in the readme.txt .
PHP-FUSION is installed in its own folder and Ajax Chat is also in its own folder, so PHP-FUSION -> /Webroot/php-fusion/ and
Ajax Chat -> /Webroot/php-fusion/chat/.
Please make sure you know how you set up the chat and PHP-FUSION,
now let go to start editing:
open up “/chat/lib/custom.php” :
NOTE: I have made a few changes so people don’t have PHP error when they don’t set correctly the maincore.php path.
Again the maincore.php its the important piece in the integration if you set it incorrectly the integration will not work at all, and a bunch of PHP error will come up.
<?php
$maincore_path="/maincore.php"; // change your path here
if(file_exists($_SERVER{'DOCUMENT_ROOT'} . $maincore_path )){
require_once(($_SERVER{'DOCUMENT_ROOT'} . "/config.php"));
define('DB_HOST', $db_host);define('DB_USER', $db_user);define('DB_PASS', $db_pass);define('DB_NAME', $db_name);
require_once(($_SERVER{'DOCUMENT_ROOT'} . $maincore_path));
}else{
exit("<span style=\"color:red;\">The maincore.php was not found.<br> Please make sure the path is correct in your installation.</span>");
}
// lets create our vars for login, username, userID
if(defined('iUSER'))
{
$fusionUserName=$userdata['user_name'];
$fusionUserId=$userdata['user_id'];
}
?>
Now we got set up some variables that we will need, basically we put the username and user ID from PHP-FUSION in variables for easy accessing.
Next we need to open “/chat/lib/class/CustomAJAXCHAT.php”.
highlight line 11 to line 72 and paste the code below.
make sure you do correctly or else you will get a nasty error..
// auto login PHP-fusion CMS
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
function getValidLoginUserData() {
// globalize the important variables from fusion cms
global $fusionUserName,$fusionUserId;
// Check if we have a valid registered user:
$customUsers = $this->getCustomUsers();
if(iUSER){
$userData = array();
$userData['userID'] =$fusionUserId;
$userData['userName'] =$fusionUserName;
$user_name=$this->trimUserName($userData['userName']);
if(iSUPERADMIN){
$userData['userRole'] = AJAX_CHAT_ADMIN;
}elseif(iADMIN){
$userData['userRole'] = AJAX_CHAT_MODERATOR;
}elseif(iMEMBER){
$userData['userRole'] = AJAX_CHAT_USER;
}
return $userData;
}// Check if we have a valid registered user using the ajax chat form:
elseif($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();
}
}
// 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) {
// 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) || $value == $this->getConfig('defaultChannelID')) {
$this->_channels[$key] = $value;
}
}
}
return $this->_channels;
}
All good so far, now lets edit another PHP class document, important so we can check if user guest nick is a registered username, if used we get an error and the user wont be able to login in the chat..
Unless of course he changes for a different nickname.
Now Open “/chat/lib/class/AJAXChat.php”
Highlight from line 3179 to line 3207 paste the following code below:
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'));
// Trim guest userName:
$userName=$this->getRequestVar('userName');
if($this->IfUserExist($userName)){
return null;
}
$userName = $this->trimString($this->getRequestVar('userName'), null, $maxLength, true, true);
// 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;
}
/* lets create a custom function that will check if username exist in database.. PHP 4.0.3 , PHP 5*/
function IfUserExist($username){
$link = mysql_connect(DB_HOST,DB_USER, DB_PASS);
if($link)
{
$username=mysql_real_escape_string(stripslashes($username));
mysql_select_db(DB_NAME, $link);
$db_table=DB_PREFIX."users";
$query = "SELECT user_name FROM $db_table WHERE user_name='$username'";
$result= mysql_query($query);
if(mysql_num_rows($result) > 0)
{
return true;
mysql_close($link);
}else{
return false;
}
}else{
die('There is an error in the custom function IfUserExist()' . mysql_error());
}
}
There is a new function called IfUserExist(); that will check if usernick that the guest user is trying to use is or not registered in the PHP-FUSION.. very important so we don’t have people impersonating other registered user in the chat..
So there it is, your chat its fully connected to PHP-FUSION CMS..
hope you like, please comment and forgive my English since is not my primary speaking language…
Please, comment the integration so I know is working for all thanks again for reading..

