Author Archive
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..
WordPress set_magic_quotes_runtime()
Bueno,
esta vez pense en crear este post acerca del el [error] de WordPress que esta inundando muchos blogs en la Internet y que corren la grandiosa máquina de CMS de WordPress..
Si lugar a duda vas y revisas el LOG de tu apache encontraras las lineas siguientes :
PHP Deprecated: Function set_magic_quotes_runtime() is deprecated PHP Deprecated: Function set_magic_quotes_runtime() is deprecated PHP Deprecated: Function set_magic_quotes_runtime() is deprecated
Asi sucesivamente, esto es porque en la version PHP 5.3.0 y mas recientes esta desactivado por defecto, pues a sido retirado de PHP 6 y esta propuesta para eliminación..
La forma en que repare esto Function set_magic_quotes_runtime(),
es encontrando el documento php que lo esta creando, el cual es wp-settings.php en la linea 27 hasta esta fecha actual y en WordPress archivo mas nuevo que es WP3.0.5..
set_magic_quotes_runtime( 0 );
Para eliminar este [error] lo pondremos entre un if statement y chequearemos si nuestro PHP es menor que la version 5.3.0,
Copia y pega el siguiente código, marcando la linea 26 y 27 completamente , de modo que el código nuevo lo reescriba.
if(version_compare(PHP_VERSION, '5.3.0', '<')){
// Disable magic quotes at runtime. Magic quotes are added using wpdb later in wp-settings.php.
set_magic_quotes_runtime( 0 );
}
Salva y retornarlo a tu Webserver y observa que no tengas mas notificaciones, es buena idea hacerlo aunque tengas una versión mas antigua que PHP 5.3.0 en tu servidor web o tu Hosting..
porque es posible que actualices o cambies de hosting que si tenga una versión de PHP mas nueva o igual a PHP 5.3.0.. es recomendable que lo parchees hasta que los coders de WordPress coloquen un parche oficial.. o que actualicen el código de wordpress a los nuevos entandares de PHP.
Y además los hostings siempre actualizan su PHP para evitar cualquier problema de seguridad en sus Servidores..
Si no as chequeado tu Apache log, pues te sugiero que lo hagas , es posible que te lleves una inmensa sorpresa de la cantidad de información acerca de estas notificaciones..
Elimina caracteres no deseados del texto.
Una manera fácil de eliminar caracteres que no son estándares en la tabla ASCII, o que as copiado de Microsoft Word y los quieres meter en una base de datos y quieres estar seguro que no lleva caracteres raros como los siguientes: ⌠,╗,╔,╩ y otros.
entonces esta función de PHP te va a servir para limpiarlas completamente y depurar el string que quieres meter en tu base de datos o en otro proyecto que estés haciendo..
<?php
function CleanNonACIIchar($text){
$input='/[^(\x20-\x7F)]*/';//el rango de caracteres que no queremos
$Text_Output = preg_replace($input,'', $text);
return $Text_Output;
}
?>
Y simplemente sacas la salida del texto(string) en tu HTML.. o lo metes en la base de datos..
<?php
$CleanThis="Estos caracteres no los queremos ⌠,╗,╔,╩";
$Cleaned_string=CleanNonACIIchar($CleanThis);
mysql_select_db('MisDatos', $connect);
$SqlWrite=mysql_query("INSERT INTO MisDatos(DatosDepurados)VALUES('".$Cleaned_string."')");
if (!$SqlWrite)
{
die('<p>Hubo un error al escribir los datos, el error es:</p><br />' . mysql_error());
}else{
echo "Todo bien, se a escrito el texto en la base de datos";
}
mysql_close($connect);
?>
Eso es todo, ya que fácil es limpiar esos caracteres no estándares de la tabla ASCII rápido..
Comentar el código, a ver que les pareció..
Procesa url de videos youtube usando PHP
Bueno,
Andaba buscando la manera de mostrar videos de youtube para mi chat, que es basado en phpfreechat, y resulte con un código en PHP, usando la funcion preg_match().
Fácilmente me resulto factible Procesar un url de videos Youtube que tus usuarios peguen, en el chat ya ahora los usuarios pueden pegar la URL de youtube y el chat muestra el vídeo automáticamente,
sin embargo no solo puede trabajar para phpfreechat sino que en cualquier tipo de script que obtenga información de los usuarios, por ejemplo :
Una Forma de HTML, usando $_POST[] o $_GET[] array de PHP, o alguna pagina que reciba input de los usuarios…se las dejo haber si les sirve..
<?php
/** Created by UTAN aka re*s.t.a.r.s.*2 Neu Valle */
function parseyoutubevid($text){
// algunos settings para el tamaño del video
$height=250;
$width=250;
$MatchThis='/[\\?\\&]v=([^\\?\\&]+)/';
if(preg_match($MatchThis,$text,$matches))
{
// no queremos un enlace como este php?v= sea visto como youtube video!.
if(strlen($vidid=$matches[1]) == 11){
$youtuvideo="<object width=".$width." height=".$height."><param name=\"movie\" value=\"http://www.youtube.com/v/".$vidid."&hl=en&fs=1&rel=0\">
</param><param name=\"allowFullScreen\" value=\"true\">
</param><embed src=\"http://www.youtube.com/v/".$vidid."&hl=en&fs=1&rel=0\"
type=\"application/x-shockwave-flash\" allowfullscreen=\"true\" width=".$width." height=".$height."></embed></object>";
return $youtuvideo;
}else{
return $text;// no paso el text de el ID de youtube..
}
}else{
return $text;// retornamos el texto pues no es un video youtube.
}
}
?>
Cambias algunos settings para el tamaño del video”
$height=250;
$width=250;
$height la altura del video y $width la parte ancha del video, simplemente cambiándolos te da mas control del tamaño del video sin necesidad de cambiar el output the html.
Ahora podes llamar la función ejemplo:
<?php $UserURL=trim($_POST['formInput']); // creamos la variable i quitamos espacios. $UserURL=htmlentities($UserURL);// un poco de limpieza, aunque debes de hacer mas por tu parte.. // lo tenemos todo, pasemos a llamar la función.. echo parseyoutubevid($UserURL); ?>
Creamos el texto usando el Super Global de PHP POST, lo limpiamos y lo pasamos a la función, esta detecta el ID de el URL escrito por el usuario y te printea el resultado usando el ECHO de PHP..
Bueno, ya tenemos el video y todos contentos … comenta porfavor..

