<?php
/**
 * $Source: /home/cvs/nukescripts/kernel/security.php,v $
 * $Revision: 1.1.0a-1 $
 * $Author: cyril $
 * $Date: 2007/04/05 10:03:21 $
 *
 */
/************************************************************************/
/* Maximus CMS: Web Portal System                                       */
/* ==============================                                       */
/*                                                                      */
/* Copyright (c) 2002 - 2006                                            */
/* http://www.php-maximus.fr                                            */
/* dev@php-maximus.org                                                  */
/*                                                                      */
/* This program is free software. You can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 2 of the License.       */
/************************************************************************/
/* Based on PHP-NUKE: Web Portal System                                 */
/************************************************************************/
defined('MAXIMUS') or die ('Access denied security MAXIMUS directly...');

// We want to use the function stripos,
// but thats only available since PHP5.
// So we cloned the function...
if(!function_exists('stripos')) {
  function stripos_clone($haystack, $needle, $offset=0) {
    return strpos(strtoupper($haystack), strtoupper($needle), $offset);
  }
} else {
// But when this is PHP5, we use the original function
  function stripos_clone($haystack, $needle, $offset=0) {
    return stripos($haystack, $needle, $offset=0);
  }
}

// Posting from other servers in not allowed
// Fix by Quake
// Bug found by PeNdEjO
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  if (isset($_SERVER['HTTP_REFERER'])) {
    if (!stripos_clone($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'])) {
        die('Posting from another server not allowed!');
    }
  } else {
    die($posttags);
  }
}
// Speed up this function with stripos_clone and str_replace
function FixQuotes ($what = "") {
	$what = str_replace("'","''",$what);
	while (stripos_clone($what, "\\\\'")) {
		$what = str_replace("\\\\'","'",$what);
	}
	return $what;
}


function check_words($Message) {
    if (empty($Message)) { return NULL; }
	global $CensorMode, $CensorReplace, $EditedMessage;
	include('config.php');
	$EditedMessage = $Message;
	if ($CensorMode != 0) {
		if (is_array($CensorList)) {
			$Replace = $CensorReplace;
			if ($CensorMode == 1) {
				for ($i = 0; $i < count($CensorList); $i++) {
					$EditedMessage = eregi_replace("$CensorList[$i]([^a-zA-Z0-9])","$Replace\\1",$EditedMessage);
				}
			} elseif ($CensorMode == 2) {
				for ($i = 0; $i < count($CensorList); $i++) {
					$EditedMessage = eregi_replace("(^|[^[:alnum:]])$CensorList[$i]","\\1$Replace",$EditedMessage);
				}
			} elseif ($CensorMode == 3) {
				for ($i = 0; $i < count($CensorList); $i++) {
					$EditedMessage = eregi_replace("$CensorList[$i]","$Replace",$EditedMessage);
				}
			}
		}
	}
	return ($EditedMessage);
}

function delQuotes($string){
    if (empty($string)) { return NULL; }
    	/* no recursive function to add quote to an HTML tag if needed */
	/* and delete duplicate spaces between attribs. */
	$tmp="";    # string buffer
	$result=""; # result string
	$i=0;
	$attrib=-1; # Are us in an HTML attrib ?   -1: no attrib   0: name of the attrib   1: value of the atrib
	$quote=0;   # Is a string quote delimited opened ? 0=no, 1=yes
	$len = strlen($string);
	while ($i<$len) {
		switch($string[$i]) { # What car is it in the buffer ?
		case "\"": #"       # a quote.
		if ($quote==0) {
			$quote=1;
		} else {
			$quote=0;
			if (($attrib>0) && ($tmp != "")) { $result .= "=\"$tmp\""; }
			$tmp="";
			$attrib=-1;
		}
		break;
		case "=":           # an equal - attrib delimiter
		if ($quote==0) {  # Is it found in a string ?
		$attrib=1;
		if ($tmp!="") $result.=" $tmp";
		$tmp="";
		} else $tmp .= '=';
		break;
		case " ":           # a blank ?
		if ($attrib>0) {  # add it to the string, if one opened.
		$tmp .= $string[$i];
		}
		break;
		default:            # Other
		if ($attrib<0)    # If we weren't in an attrib, set attrib to 0
		$attrib=0;
		$tmp .= $string[$i];
		break;
		}
		$i++;
	}
	if (($quote!=0) && ($tmp != "")) {
		if ($attrib==1) $result .= "=";
		/* If it is the value of an atrib, add the '=' */
		$result .= "\"$tmp\"";  /* Add quote if needed (the reason of the function ;-) */
	}
	return $result;
}

function check_html($str, $strip="") {
  //  if (empty($str)) { return NULL; }
    //include_once('kernel/fly/check_html.php');
	include('config.php');
	if ($strip == "nohtml")
	$AllowableHTML=array('');
	$str = stripslashes($str);
	$str = eregi_replace("<[[:space:]]*([^>]*)[[:space:]]*>",'<\\1>', $str);
	// Delete all spaces from html tags .
	$str = eregi_replace("<a[^>]*href[[:space:]]*=[[:space:]]*\"?[[:space:]]*([^\" >]*)[[:space:]]*\"?[^>]*>",'<a href="\\1">', $str);
	// Delete all attribs from Anchor, except an href, double quoted.
	$str = eregi_replace("<[[:space:]]* img[[:space:]]*([^>]*)[[:space:]]*>", '', $str);
	// Delete all img tags
	$str = eregi_replace("<a[^>]*href[[:space:]]*=[[:space:]]*\"?javascript[[:punct:]]*\"?[^>]*>", '', $str);
	// Delete javascript code from a href tags -- Zhen-Xjell @ http://nukecops.com
	$tmp = "";
	while (ereg("<(/?[[:alpha:]]*)[[:space:]]*([^>]*)>",$str,$reg)) {
		$i = strpos($str,$reg[0]);
		$l = strlen($reg[0]);
		if ($reg[1][0] == "/") $tag = strtolower(substr($reg[1],1));
		else $tag = strtolower($reg[1]);
		if ($a = $AllowableHTML[$tag])
		if ($reg[1][0] == "/") $tag = "</$tag>";
		elseif (($a == 1) || ($reg[2] == "")) $tag = "<$tag>";
		else {
			# Place here the double quote fix function.
			$attrb_list=delQuotes($reg[2]);
			// A VER
			$attrb_list = ereg_replace("&","&amp;",$attrb_list);
			$tag = "<$tag" . $attrb_list . ">";
		} # Attribs in tag allowed
		else $tag = "";
		$tmp .= substr($str,0,$i) . $tag;
		$str = substr($str,$i+$l);
	}
	$str = $tmp . $str;
	return $str;
	exit;
	/* Squash PHP tags unconditionally */
	$str = ereg_replace("<\?","",$str);
	return $str;
}

function filter_text($Message, $strip="") {
    if (empty($Message)) { return NULL; }
    	global $EditedMessage;
	check_words($Message);
	$EditedMessage=check_html($EditedMessage, $strip);
	return ($EditedMessage);
}

function removecrlf($str) {
	// Function for Security Fix by Ulf Harnhammar, VSU Security 2002
	// Looks like I don't have so bad track record of security reports as Ulf believes
	// He decided to not contact me, but I'm always here, digging on the net
	return strtr($str, "\015\012", ' ');
}

// Updated by Quake 24/7/05
function validate_mail($email) {
    if (empty($email)) { return NULL; }
    include_once(INCLUDE_PATH.'kernel/fly/validate_mail.php');
}

function encode_mail($email) {
    if (empty($email)) { return NULL; }
    include_once(INCLUDE_PATH.'kernel/fly/encode_mail.php');
}

if (!defined('FORUM_ADMIN')) {
  if(empty($admin_file)) {
    die ('You must set a value for admin_file in config.php');
  } elseif (!empty($admin_file) && !file_exists($admin_file.".php")) {
    die ('The admin_file you defined in config.php does not exist');
  }
}

function secure( $data, $type, $nohtml=false, $save=false ) {
	$data = check_words( trim( $data ) );
	if ( $type == 'num' ) {
		$data = $GLOBALS['db']->XMFnum( $data );
 	} elseif ( $type == 'bin' ) {
		$data = $GLOBALS['db']->XMFbin( $data );
 	} elseif ( $type == 'lang' ) {
		$data = $GLOBALS['db']->XMFlang( $data );
 	} elseif ( $type == 'strip' ) {
		$data = stripslashes( $data );
	}
	if ( $nohtml == 1 ) {
		$data = check_html( $data, "nohtml" );
	} elseif ( $nohtml == "html" ) {
		$data = check_html( $data, "" );
	}
	if ( $save == 'fck' ) {
		$data = stripslashes( FixQuotes( $data ) );
	} elseif ( $save == 'sec' ) {
		$data = addslashes( htmlentities( $data, ENT_QUOTES ) );
	}
	return $data;
}
