Moving…

April 28, 2010 Comments off

This is a great day for me! I’m moving this blog, until I’ll get my own domain, to http://criss-dev.com/kos/blog/.

Hope to see you all there 🙂

Categories: Global

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:

MakeGallery – a simple jQuery gallery plug in

February 14, 2010 Comments off

MakeGallery – a simple jQuery gallery plug in

gallery.js


/*
*	MakeGallery
*	
*		A jQuery gallery plug in.
*
* @author:    Costin Trifan
* @date:      14.02.2010
* @license:   MIT License  http://en.wikipedia.org/wiki/MIT_License
* @version:   1.0
*/

(function($)
{
	$.fn.MakeGallery = function( options )
	{
		var defaults = {
			baseImageRef: $('#gallery_MainImage'),
			thumbsImgPath: 'thumbs/',
			largeImgPath: 'large/'
		};

		var options = $.extend(defaults, options);  

		if (options.baseImage == '') {
			options.baseImage = defaults.baseImage;
		}
		if (options.largeImgPath == '') {
			options.largeImgPath = defaults.largeImgPath;
		}
		if (options.thumbsImgPath == '') {
			options.thumbsImgPath = defaults.thumbsImgPath;
		}

		return this.each(function()
		{
			var  mainWrapper = $(this)
				,mainImg = options.baseImageRef
				,mainImgSrc = mainImg.attr('src')
				,path = '#' + $(this).attr('id'); /*[ get the ID of the main container. ]*/
				;

				// add the click event handler to all thumbs
				$(path+' .gallery_thumb').each(function()
				{
					$(this).click(function( event )
					{
						event.stopPropagation();

						var src = $(this).attr('src');
						src = src.replace(options.thumbsImgPath, options.largeImgPath);

						// update main image
						mainImg.attr('src', src);
					});
				});

			// reset main image
			$(path).hover(function(){}, function(){
				mainImg.attr('src', mainImgSrc);
			});

		}); /*[ end return ]*/
	}; /*[ end $.fn.MakeGallery ]*/
})(jQuery);

Usage


<!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>Image Gallery - jQuery Plugin</title>

<style type="text/css">
/*
*	SET THE STYLES TO MATCH THE DESIGN
*/
div#gallery_MainWrapper { float: none; display: block; overflow: hidden; min-height: 1px; }
div#gallery_MainWrapper > div {
	width: 350px; height: 200px;
	margin: 0 auto;
}
ul, li { list-style-type: none; overflow: hidden; min-height: 1px; }
li { margin: 2px; padding: 2px; float: left; display: block; }
li img { border: none; cursor: pointer; }

img#gallery_MainImage { width: 350px; height: 200px; }
img.gallery_thumb { width: 125px; height: 94px; }

/*[ END GALLERY ]*/
</style>

	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script>
	<script src="gallery.js" type="text/javascript"></script>
	<script type="text/javascript">
    
		jQuery().ready(function($)
		{
			$('#gallery_MainWrapper').MakeGallery({
				baseImageRef: $('#gallery_MainImage')
				/*[, thumbsImgPath: 'thumbs/'
				   , largeImgPath: 'large/' ]*/
			});
		});
    
    </script>
</head>
<body>


	<div id="gallery_MainWrapper">
    
    	<div><img id="gallery_MainImage" alt="" title="" src="large/CIMG5233.gif" /></div>
    
    	<ul>
        	<li><img class="gallery_thumb" alt="" title="" src="thumbs/CIMG5233.gif" /></li>
        	<li><img class="gallery_thumb" alt="" title="" src="thumbs/CIMG5234.gif" /></li>
        	<li><img class="gallery_thumb" alt="" title="" src="thumbs/CIMG5254.gif" /></li>
        	<li><img class="gallery_thumb" alt="" title="" src="thumbs/CIMG5255.gif" /></li>
        	<li><img class="gallery_thumb" alt="" title="" src="thumbs/CIMG5256.gif" /></li>
        </ul>
    </div>


</body>
</html>

For this plug in to work, the thumbs and the large images should share the same name and extension!

Thumbs should be found in the thumbs folder and the large images in the large folder respectively.

Compress output

January 18, 2010 Comments off

Remove new lines && multiple consecutive whitespaces from content


/**
 * Remove new lines && multiple consecutive whitespaces from content
 */
function compress( $content )
{
	$content = trim(ereg_replace("\n|\r|\r\n|\n\r", '', preg_replace('/\s+/', ' ', $content)));
	return $content;
}