Archive

Archive for March, 2010

Protect class’s properties

March 28, 2010 Comments off

The following class can be used to extend your existent class(es) when you want them to disallow run-time properties instantiation.

class SafeObject


<?php
/**
* base class SafeObject
*
* @description: This base class protects other classes from having properties instantiated at run-time
* @author: Costin Trifan
* @date: 28.03.2010
* @version: 1.0
* @status: release
*/
class SafeObject
{
	/**
	* The list of public properties that can be set to this class
	* @type array
	* @access private
	* @see __get(), __set(), AllowedProperties()
	*/
	private $properties = array();

	/**
	* Whether or not to restrict access to class's properties.
	* @type bool
	* @access private
	* @see RestrictedAccess()
	*/
	private $restricted = true;

/**
*  PRIVATE METHODS
*-------------------------------------------
*/
	private function __clone()
	{
		exit('<br/>Error: You are not allowed to use method [__clone] in class: '.get_class($this));
	}
	private function __sleep()
	{
		exit('<br/>Error: You are not allowed to use method [__sleep] in class: '.get_class($this));
	}
	private function __wakeup()
	{
		exit('<br/>Error: You are not allowed to use method [__wakeup] in class: '.get_class($this));
	}

/**
*  PUBLIC METHODS
*-------------------------------------------
*/
	public function __construct(){}
	public function __destruct(){}

	public function __unset( $var )
	{
		if ($this->restricted)
		{
			exit('<br/>Error: You are not allowed to use method [__unset] in class: '.get_class($this));
	        } 
		unset($var);
       }

	public function __isset( $name )
	{
		return isset($this->properties[$name]);
	}

	public function __toString()
	{
		$str = '';
		foreach($this->properties as $key=>$value)
		{
			$str .= $key . ' = '. $value. '<br/>';
		}
		return $str;
	}
	
	final public function __get( $name )
	{
		if ($this->restricted)
		{
			if (array_key_exists($name, $this->properties)) {
				return $this->properties[$name];
			}
		}
		else {
			if ($this->__isset($name)) {
				return $this->name;
			}
		}
		exit("<br/>Error: Property: [{$name}] was not found!");
	}

	final public function __set( $name, $value )
	{
		if ($this->restricted)
		{
			if (array_key_exists($name, $this->properties)) {
				$this->properties[$name] = $value;
			}
			else { exit("<br/>Error: Property: [{$name}] cannot be set!"); }
		}
		else { $this->name = $value; }
	}

	/**
	* Restrict access to class's properties to only the allowed properties.
	* @return $this
	*/
	final public function AllowedProperties( array $properties )
	{
		if ($this->restricted)
		{
			foreach( $properties as $prop )
			{
				$this->properties[$prop] = null;
			}
		}
		return $this;
	}


	/**
	* Whether or not to restrict access to class's properties.
	* @return $this
	*/
	final public function RestrictedAccess( $value )
	{
		$this->restricted = $value;
		return $this;
	}

}

Tests


/*
*    TESTS
*/

class Test extends SafeObject
{
	public function DoSomething() { echo 'Doing something...'; }
	public function DoSomethingElse() { echo 'Doing something else...'; }
}

$o = new Test();

$o->RestrictedAccess(true)
	->AllowedProperties(array('server','username')); /* << class Test can only have these two public properties */


// ok
$o->server = 'localhost';
echo '<br/>server: ' , $o->server;

// ok
$o->username = 'costin';
echo '<br/>username: ' , $o->username;

// NOT ok
unset($o->username);

// NOT ok
$o->test = 'test';
echo '<br/>test: ' , $o->test;

// __toString()
echo '<br/>' , $o;
?>

Note:

When the RestrictedAccess function’s argument is set to FALSE then that class allows the instantiation of public properties at run-time.

Categories: PHP Tags: ,

Protect your pages against sql injections

March 9, 2010 1 comment

The following function inspects the URL and looks for the (‘) apostrophe; if the apostrophe is found the url will be cut and the page reloaded using the cleaned url.

function CleanRequest


/**
* Remove ' (apostrophe) from URL and cut the url at the first occurrence of the apostrophe
* Prevent sql injections.
*
* @author: Costin Trifan
* @date: 06.05.2009
* @status: release
*/
function CleanRequest( $use = 'http' )
{
	$url = $_SERVER['REQUEST_URI'];
	$url = utf8_decode($url);
	if (($pos = strpos($url, '%27')) !== false)
	{
		$url = substr($url, 0, $pos);
		$url = $use.'://'.$_SERVER['HTTP_HOST'].$url;
		header("Location: ".$url); /*[ reload page using the cleaned url ]*/
		exit;
	}
}

This function can be called on individual pages but I find it to be more useful when called in a config.php file so it can be executed on all pages of a website.

Edit: March, 28 The $use argument has been removed.


/**
* Remove ' (apostrophe) from URL and cut the url at the first occurence of the apostrophe
* Prevent sql injections.
*
* @author: Costin Trifan
* @date: 06.05.2009
* @status: release
* @revision: March 28, 2010;
*	The $use argument has been removed.
*/
function CleanRequest()
{
	$use = 'http';
	if (isset($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] == "on")) {$use .= 's';}

	$url = $_SERVER['REQUEST_URI'];
	$url = utf8_decode($_SERVER['REQUEST_URI']);
	if (($pos = strpos($url, '%27')) !== false)
	{
		$url = substr($url, 0, $pos);
		$url = $use.'://'.$_SERVER['HTTP_HOST'].utf8_encode($url);
		header("Location: ".$url); /*[ reload page using the cleaned url ]*/
		exit;
	}
}
Categories: PHP Tags:

JavaScript Event Wrapper

March 6, 2010 Comments off

Event Wrapper

js_event.js


/*
* Cross browser Event wrapper
*
* @author:    Costin Trifan
* @date:      06.03.2010
* @license:   MIT License  http://en.wikipedia.org/wiki/MIT_License
* @version:   1.0
*/
var Event = {
	/**
	* Attach an event listener
	* @return this
	*/
	add : function(el, ev, func, capture)
	{
		if (capture == null) { capture = false; }
		if (window.addEventListener) {
			el.addEventListener(ev, func, capture);
		}
		else if (window.attachEvent) {
			el.attachEvent("on"+ev, func);
		}
		else { el['on'+ev] = func; }

		return this;
	}
	/**
	* Detach an existent event listener
	* @return this
	*/
	,remove : function(el, ev, func)
	{
		if (window.removeEventListener) {
			el.removeEventListener(ev, func, false);
		}
		else if (window.detachEvent) {
			el.detachEvent("on"+ev, func);
		}
		else { el['on'+ev] = func; }

		return this;
	}
	/**
	* Prevent the default action & stop the event from propagating
	* @return bool false
	*/
	,cancel : function(e)
	{
	  if(!e) { e = window.event; }
	  if(e.stopPropagation) { e.stopPropagation(); }
	  if(e.preventDefault) { e.preventDefault(); }

	  e.cancelBubble = true;
	  e.cancel = true;
	  e.returnValue = false;
	  return false;
  	}
};

Example


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Cross browser Event wrapper</title>
	<script src="js_event.js" type="text/javascript"></script>
	<script type="text/javascript">
    
	function toggle(el){
		if (el.style.display != 'none')
			el.style.display = 'none';
		else
			el.style.display = 'block';
	}
	
	
    Event.add(window, 'load', function(){
		var a = document.getElementById('a');
		var p = document.getElementById('p');
		Event
			.add(a, 'click', function(e){
				Event.cancel(e);
				toggle(p);
			})
			.add(p, 'click', function(e){
				alert('paragraph clicked');
			});
	});
    
    </script>
</head>

<body>

<p>
	<a id="a" href="#">Toggle</a>
    <span id="p" style="display: block">
    	Lorem ipsum dolor sit amet, consectetur adipisicing elit,
        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
        nisi ut aliquip ex ea commodo consequat.
    </span>
</p>

</body>
</html>

A simple way of creating a javascript class

March 2, 2010 Comments off

Base class Class

js_class.js


/*
* The base class Class
*
* @author:    Costin Trifan
* @date:      02.03.2010
* @license:   MIT License  http://en.wikipedia.org/wiki/MIT_License
* @version:   1.0
*/
var Class = function( parentClass, methods )
{
	/*
	* Check to see if an Object is an Object or an Object Literal
	* @source: http://stackoverflow.com/
	*/
	var isObject = function( _obj )
	{
	  var _test  = _obj;
	  return (  typeof _obj !== 'object' || _obj === null ?
				  false :  
				  (
					(function () {
					  while (!false) {
						if (  Object.getPrototypeOf( _test = Object.getPrototypeOf(_test)  ) === null) {
						  break;
						}      
					  }
					  return Object.getPrototypeOf(_obj) === _test;
					})()
				  )
			  );
	};

	//*[ If no parentClass is provided add methods to the current constructor ]*/
	if ( parentClass == null )
	{
		if ( isObject(methods) ) {
			var _obj = {};
			for (var propName in methods) {
				_obj[propName] = methods[propName];
			}
		}
		return _obj;
	}
	else {
		/*[ If there are methods, add them to the parentClass ]*/
		if (methods != null)
		{
			if ( ! isObject(methods) ) { throw new Error("The methods object should be an instance of an Object or an Object Literal"); }

			for (var propName in methods) {
				parentClass[propName] = methods[propName];
			}

			return parentClass;
		}
		/*[ Else, return an empty object ]*/
		else { return {}; }
	}
};

Example


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Creating a Class in JavaScript</title>
</head>
<body>
<script type="text/javascript">
/*
**     EXAMPLES
**************************
*/

/*[ Creating class X ]*/
var X = new Class();

X.m = function() {
	alert('Inside m function');
};

X.m(); // alerts: Inside m function

/*[ Creating class F ]*/
var F = new Class(null, {
	 one : function(){alert('F::one');}
	,two : function(){alert('F::two');}
});

F.one(); // alerts F::one
F.two(); // alerts F::two


/*[ Creating class Z and extending class F ]*/
var Z = new Class(F, {
	 three : function(){alert('F/Z::three');}
	,four : function(){alert('F/Z::four');}
});

F.three(); // == Z.three(); alerts F/Z::three
F.four(); // == Z.four(); alerts F/Z::four

</script>
</body>
</html>
Categories: JavaScript Tags: