jQuery apear plugin

Simple jquery plugin used to trigger a function when a specific element apears on viewport, this callback is trigged one time.
This plugin is very useful when you what to preload an image when this apears on the viewport.


$('img[osrc]').apear(function(){
			$(this).load(function(){
				$(this).fadeIn();
			});
			$(this).attr('src',$(this).attr('osrc')).attr('osrc',null);
			console.log('apear item');
		});

In this example the image is printed with osrc attribute wich keeps the path to the image, when the apear plugin callback is trigged the osrc attribute is replaced with src attribute and add new event to loaded function to fade in the image.

Other way to use this is when you have multiple boxes ( widgets ) on the page and its not necessary to apply a javascript code to it before to apear in the viewport.


$('.widget-x').apear(initWidgetX);

Download plugin or try the Demo

Working with JSON RPC from javascript

JSON-RPC is lightweight remote procedure call protocol similar to XML-RPC. Its very simple and its used by alots of web applications at least json wich is very used in modern applications.

To communicate with server in a professional way, json-rpc is a good solution all you need to do is to create server side classes and pass it to an json rpc server class like Zend_Json_Server, read the documentation about how to create the server side.

For the client side you need to create a javascript class witch sends the request to the server and parse the response.

The json request for json-rpc is very simple has three properties in the json object: the method, params and request id.

{method : "Account.login", params : ["user","pass"], id : "194" }

And response contain the result of call, the error if it is, and the request id number.

{"result": "done", "error": null, "id": "194"}

The id of the request and response is used to  match the request and reponse of the current call. For example if you send a request and also add a listener for it, when the response comes call the listener with the specific id. This id is increasing at every request.

I made a simple json-rpc implementation for javscript that handle a json-rpc protocol. Sintax of using this rpc implementation is very simple, its provide a fluent call mode with two functions “call” and “done”.

Rpc.call("Account.login", "username", "password").done( onLoginResponse );

This Rpc class depends by a public json encoder/decoder class, you can find this class here. For this work you must to change the url from ajax call and changed to your url, and thats all.

var Rpc = {
		id   : 0,
		cid  : 0,
		callbacks:[],
		call : function()
		{
			var args = [];

			for(var i=0;i<arguments.length;i++)
				args.push(arguments[i]);

			var method;
			var tosend;
			this.id++;
			this.cid = this.id;

			if(args.length)
			{
				method = args.shift();

				var tosend = {method : method, params : args, id : this.cid };

				jQuery.ajax({
					async: true,
					contentType: 'application/json',
					type: 'POST',
					processData: false,
					dataType: 'json',
					url: '/api/js',
					cache: false,
					data: JSON.stringify(tosend),
					error: function(req,stat,err){
						Boxy.alert(err);
					},
					success: function(data){
						for(i=0;i<public.Rpc.callbacks.length;i++)
						{
							if(public.Rpc.callbacks[i])
							if(public.Rpc.callbacks[i].id == data.id)
							{
								var callback = public.Rpc.callbacks[i].callback;

								if(callback)
								{
									callback.apply(null, [data.result]);
									public.Rpc.callbacks.splice(i,1);
								}
							}
						}
					}
				});
			}

			return this;
		},

		done   : function(callback)
		{
			if(typeof(callback) == 'function')
			this.callbacks.push( { id : this.cid, callback : callback } );
		}
};

Improve Zend Framework application speed by separate static content and using Zend_Cache and Zend_View for static files

Zend Framework Speed UP

Introduction

Why doing this, the reason is simple. We dont need to process all static files in our framework, because this increase loading time of your application. The ideea is to create a separate domain for your application eg. http://s.domain.com wich will render and cache all requested files. I personally used this method and my application wich is based on Zend Framework is considerably faster. The Zend_View is used to merge multiple css or js files and pass parameters. Also compressing and obfuscation classes are used to decrease file sizes.

Create .htaccess

For beggining a .htaccess file is created for redirecting all request to render file. The files that is redirected to the render file is just js and css files, the rest of them like pictures, zip and other binary files are loaded from normal path. Also if apache deflate  module is available we add filters for css,xml and javascript files to compress files.

AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript

RewriteEngine on RewriteRule !\.(swf|xml|jpg|png|PNG|JPG|gif|otf|ttf|htc|ico)$ render.php
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ render.php [NC,L]

Render file

This is the file called render.php wich process all requests sepcified by .htaccess file. For example if request is /css/common.css  this file is loaded into Zend_View and rendered. If the request has some parameters like /css/common.css?foo=1&bar=1 the request is parsed with php function parse_str and passed to the Zend_View.  Before the file is sent to output the content is compressed with specific class, for css i personally used  the CSSCompressor by Stephen Clay and for javascript files JSMinPlus by Tino Zijdel. After the file is compressed the content is cached by Zend_Cache with the md5 of request like id. And finaly send the cache headers for browsers and print it to ouput.

<!?php
error_reporting(E_ALL);
ini_set('display_errors','1');
set_include_path(implode(PATH_SEPARATOR, array(     dirname(__FILE__).'/library',     get_include_path(), ))); 

require_once "Zend/Uri.php";
require_once "Zend/Cache.php";
require_once "Zend/View.php";
require_once 'functions.php'; 

define('CACHE_DAYS', 30);
define('USE_CACHE', false);
define('USE_COMPRESSOR', false); 

$request_file = $_SERVER['REQUEST_URI']; 

if($request_file == "/" || empty($request_file))
{  notFound(); } 

$cache_id = md5($request_file);
$uri = Zend_Uri::factory("http://s.domain.com".$request_file);
parse_str($uri->getQuery(), $uri_params);

$file_parts = explode('.', basename($uri->getPath()));

$extension = $file_parts[ count($file_parts) - 1 ];

$file = basename($uri->getPath());

$file_path = str_replace('\\','/',dirname(__FILE__) . $uri->getPath());

$frontendOptions = array(
   'lifetime' => 3600 * 24 * CACHE_DAYS, // cache lifetime of 2 hours
   'automatic_serialization' => true
);

$backendOptions = array(
	'cache_dir' => dirname(__FILE__).'/cache/' // Directory where to put the cache files
);

// getting a Zend_Cache_Core object
$cache = Zend_Cache::factory('Core',
							 'File',
							 $frontendOptions,
							 $backendOptions);

if(file_exists($file_path) && is_file($file_path))
{
	switch ( $extension )
	{
	    case "css":
	        header("Content-Type: text/css");

			if(USE_COMPRESSOR)
	        require_once "CSSCompressor.php";

			sendHeaders($file_path);

			if( ($result = $cache->load($cache_id)) === false )
			{
				$result = renderView($file_path, $uri_params);

				if(USE_COMPRESSOR)
				$result = CSSCompressor::process($result);

				$result = appendCacheInfo($result);

				if(USE_CACHE)
				$cache->save($result, $cache_id);
			}

			echo $result;

	        break;

	    case "js":
	        header("Content-Type: text/javascript");

			if(USE_COMPRESSOR)
	        require_once "JSMin.php";

			sendHeaders($file_path);

			if( ($result = $cache->load($cache_id)) === false )
			{
				 $result = renderView($file_path, $uri_params);

				 if(USE_COMPRESSOR)
				 $result = JSMin::minify($result);
				 $result = appendCacheInfo($result);

				 if(USE_CACHE)
				 $cache->save($result, $cache_id);
			}
	        echo $result;
	        break;
	    default:
	    	notFound();
	    	break;
	}
}
else
{
	notFound();
}

This steps considerably increase the time of loading of your application. The compressing calsses make files smaller with 20%. Also the big advantage for this is you can use the css and javascript files like php. For example if you want to merge multiple common files into one file, simply use render function from Zend_View

@CHARSET "UTF-8";
<?php echo $this--->render("reset.css"); ?>
<?php echo $this--->render("grid.css"); ?>
<?php echo $this--->render("layout.css"); ?>

This method is very usefully because reduce the number of files loaded trought the network.

To make sure the files are not requested every time and the client browser do its job, we send the caching headers using the below sendHeaders function.

function sendHeaders($file)
{
	$cache_days = CACHE_DAYS;

	if(file_exists($file))
	{
		$filetime = filemtime($file);

		$last_modified = date('D, d M Y H:i:s', $filetime) . ' GMT';
		$expires       = date('D, d M Y H:i:s', strtotime('+30 days',$filetime)) . ' GMT';
		$hasid         = '"' . md5($last_modified) . '"';

		header("Cache-Control:max-age=".($cache_days * 24 * 60 * 60));
		header("Pragma:private");
		header("Last-Modified:".$last_modified);
		header("Expires:".$expires);
		header("Vary: Accept-Encoding");
		header("Etag:".$hasid);

		$PageWasUpdated = !(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) and
			strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified);

		$DoIDsMatch = (isset($_SERVER['HTTP_IF_NONE_MATCH']) and
			@ereg($hasid, $_SERVER['HTTP_IF_NONE_MATCH']));

		// Does one of the two ways apply?
		if (!$PageWasUpdated or $DoIDsMatch)
		{
			header('HTTP/1.1 304 Not Modified');
			header('Connection: close');
			exit(1);
		}
	}

}

To work this function you must have some modules activated in your apache server. The modules are headers_module, expires_module.

Static files rendered like views

With your css and javascript files you cand do alots of things. In fact in your .css and .js files you cand write php code, for eg:

If you request: /js/account.js?logged=1 from the view file you can do somethink like this:

function onSomeButtonClick()
{
var logged = <?php echo ($this--->logged=="1") ? 'true' : 'false'; ?>;
if(logged) {
//do something
} else {
//do something
}
}

Conclusion

For my application this method is very fast and with alots of advantages and functionalities. The filesize is smaler using the compressing classes, also the apache is compress it with defalate module. With this positive points also have some issues, if you what to use the params sent to the view every time you must to disable cache.

Invisible detector made to be simple and user friendly

Today invisible-detector.net is live and is more user friendly and fast then last version. Yesterday i refused to go to club and I decided to restore design to insible-detector.net. I have made ​​it much easier to use and much faster, the results are now directly displayed in the input where you write the id. History is quite different  then others websites, this is with suggestions autocomplete. Enter and tell your opinion! Thanks!

invisible-detector.net

Flash player 10.3 video problem with hardware acceleration

Working on a video player project with osmf and flex i had some strange problems. When going in fullscreen mode the screen it was black or more exactly the video it was not been sown.  After one hour of testing and debugging i found the problem, the problem was that i compiled the video player with 10.3 flash player version and this works with hardware accelerated and if there is no video driver or the driver is out of date the video will not be shown only when the hardware acceleration is disabled or you update your video drivers. The solution for this is to compile with older version 10.2 or below witch is not working with video acceleration.

Hardware Accelerated Setting

Hardware Accelerated Setting

Seo editing tool for fast optimization of meta tags and title

Hi again,

Today i will share a little tool for fast meta tags and title optimization. I use this personally for my websites and helps me very much and i do the seo optimizations just navigating on my website. This tool has three important files, the javascript file wich is loaded in page and builds the editing tool ( SeoBox.js ). For administration purposes you can include this file only if administrator session is created. The second file is the php class witch save and retrieve the data from the database. This class is just a mochup and it can be done with caching system and administrator session check. The third file is that witch is used to make ajax request and there is the SeoBox instance, the class witch acts like a model.

 

SeoBox for fast seo optimizations

SeoBox for fast seo optimizations

All data of this view is stored to the database for a unique url, wich is the current url from navigation. I shared this because for me it was very usefully and im sure it will be the same for others. Take a look at the demo, or download the source code.

Yahoo Messenger Client with Action Script 3

Hello everyone, as I said, my next article is about how to create a Yahoo Messenger client. I quit do the client in php due to loop running problems and I port the code to the action script.
Why am I doing this yahoo messenger client in action script!? All started with my invisible detector website www.yahoo-messenger.ro, before i use a affiliate service for detecting invisible users. One day, I decided to have my own invisible detector. So, I started to look on the internet about yahoo messenger’s protocol and invisible detecting hacking. The founded documentation on this subject is few and unclear. All I found is a few frameworks, like openymsg, a library written in java and a c++ library called ymsg. The next step in my creations was to study about the YMSG protocol packet structure and communication flow. Below, I present you a summery of yahoo messenger packet and communication flow, from my point of view.

Yahoo Messenger Packet Diagram

A – 4 bytes that keeps the “magic packet” which is a string that specify the name of the protocol “ymsg”.
B – 2 bytes with the protocol version
C – 2 bytes with client id
D – 2 bytes with the body size
E – 2 bytes with the service number
F – 4 bytes that keeps the user status
G – 4 bytes with the session id
H – the body of the packet with key value pairs

The work with this packet is very simple when you  use action script, the class which manipulate the bytes is the ByteArray class. For php i personally use the Zend_Io package.
For example, i use a class called Packet which convert raw data to human readable values, and for sending back , i have a method called toRaw().

package albu
{
	import flash.utils.ByteArray;
	import flash.utils.Endian;

	public class Packet
	{
		//body data separator
		public static const SEPARATOR:Array = [0xC0, 0x80];

		//client version
		public static const VERSION:Array = [0x00, 0x10, 0x00, 0x00];

		//service
		public var service:Number;

		//user status
		public var status:uint = 0;

		//session id
		public static var session:Number = 0x00;

		//packet body
		public var _body:PacketBody;

		public function Packet()
		{
			_body = new PacketBody();
		}

		public function get length():Number
		{
			return body.bytes.length;
		}

		public function get body():PacketBody
		{
			return _body;
		}

		public function getBytes():ByteArray
		{
			var ba:ByteArray = new ByteArray();

			var packetBody:ByteArray = body.bytes;

			ba.endian = Endian.BIG_ENDIAN;

			//magic packet
			ba.writeUTFBytes("YMSG");

			// Version
			ByteUtil.writeArray(ba, VERSION);

			//packet length
			ba.writeShort( packetBody.length );

			//service
			ba.writeShort(service);

			//status
			ba.writeInt(status);

			//session
			ba.writeInt(session);

			//body
			ba.writeBytes( packetBody );

			return ba;
		}

		public function toString():String
		{
			var out:String = "";

			out += "----------- PACKET -------------\n";

			out += "Service: " + service + "\n";
			out += "Length: " + length + "\n";
			out += "Body: " + body + "\n";

			out += "----------- PACKET -------------\n";

			return out;
		}
	}
}

Now , that we know how to use a packet for communication with the yahoo messenger servers, we need to understand the communication flow. For me, it  was not so hard to catch it. See the diagram below for a login and retrive the buddy list process.

Next , there are few words about this diagram, because i`m sure the detailed informations is neded. First, we send over the socket created to the yahoo server the checking packet that contains a ket/value pair with key “1” and value the username used for login. This packet is sent with service 0×57. Yeah, about services… Services are like a command used by yahoo servers to communicate with clients. On the internet you  find a lots of articles with the services used and known, i`m sure that are more services and which  are unknown, because the YMSG protocol is not public.

package albu
{
	public class Service
	{
		public static const AUTH:Number = 0x57;

		public static const AUTHRESP:Number = 0x54;

		public static const MESSAGE:Number = 0x6;

		public static const BUDDY_LIST:Number = 241;

		public static const TYPEING:Number = 0x4B;

		public static const KEEPALIVE:Number = 0x8a;
	}
}

This is a minimal list of services used by this example. For a complete list you look here

To continue from the first step when the auth packet is sent, the one with the service 0×57 is the auth packet. If this packet is sending in the right format, next you receive a packet with the session id and the seed used to compute our yahoo messenger password.

https://login.yahoo.com/config/pwtoken_get?src=ymsgr&ts=&login={USERNAME}&passwd={URLENCODED_PASSWORD}&chal={URLENCODED_TOKEN}

The next step is the password computation, and wich is made with a url from the yahoo login process. This url generate a token from password, username and the seed received from the socket. The response of this url is a text with two lines. The first line keeps the response code of authentification process.

A list with response codes:

  • 1235 – Login Failed, Invalid username
  • 1212 – Login Failed, Wrong password
  • 1213 – Login locked: Too many failed login attempts
  • 1236 – Login locked

The second line is the token generated when there is no error response code and wich is used to the next process to finalize the login.

https://login.yahoo.com/config/pwtoken_login?src=ymsgr&ts=&token={TOKEN}

This url will return a four line reponse with the response code a crumb, cookie Y and cookie T.
As i know, the response code 0 is no error and that is enought for me :).  The crumb and the two cookies are used to compute the challenge with yahoo base64 encode algorithm and md5 function.
The result of challange computer is used in the next packet which is the login packet sent over the socket with the service 0×54.

var version:uint = stream.readInt();
var length:uint  = stream.readShort();
var service:uint = stream.readShort();
var status:uint  = stream.readInt();
var session:uint = stream.readInt();

if(stream.bytesAvailable >= length)
{
	var p:Packet = new Packet();

	if(!Packet.session)
	{
		Packet.session = session;
	}

	p.status = status;
	p.service = service;

	//read entire buffer for packet body
	var bodyBytes:ByteArray = new ByteArray();
	stream.readBytes(bodyBytes, stream.position, p.length);

	//set the packet body
	p.body.bytes = bodyBytes;

	var newStream:ByteArray = new ByteArray();

	stream.clear();

	stream.writeBytes(newStream);

	packetStack.push( p );
}

About this packet, i can’t tell you more details out of that are abvious, the username, client version which is what you want to put there, is the version of this client, version name. and the challange response. That will return the chuncked packet with ymsg buddy list. From now, you are connected to the yahoo and you can communicate with servers. You can send, receive messages, send buzz and all features used by yahoo messenger.

//auth packet
var p:Packet = new Packet();
p.body.add(1, _user);
p.body.add(0, _user);
p.body.add(277, chall[0]);
p.body.add(278, chall[1]);
p.body.add(307, chall[2]);
p.body.add(244, CLIENT_VERSION_ID);
p.body.add(2, _user);
p.body.add(2, "1");
p.body.add(135, CLIENT_VERSION);

p.service = Service.AUTHRESP;

network.send( p );

This is a simple example with basic functionality, i`m sure if you are using the wireshark you will find more about ymsg protocol, but this is the basic usage and it is a mochup.

yahoo messenger application in flex

Buddy and BuddyGroups are classes wich is like a value objcts for keeping users data.  Network is the classs wich create the socket connection and send the events to the YMSession. Packet and PacketBody keeps the data for a packet. Service class keeps constants with some of known services. And the most important class is YMSession wich wire rest of the classes. This class makes the login process receiving messages and sending messages, buzz and other services.

For personal testing and debugging download the files

I hope my second post will be usefully to someone :) . If you are something to ask me, don`t hesitate to tell me what do you think about this article.

Using amf in flex

Hi everyone!
My name is Cosmin Albulescu and this is the first time I’m posting on my blog. I’ve been working as a web developer for about 6 years, using common technologies like javascript, php, action script, or flex.

This post may be very useful for those who want to create a simple remote procedure call with amf and flex.

AMF (Action Message Format) is used in action script in order to exchange serialized data between a flash application and a remote server. To find more information about the amf please visit this link

Why using amf protocol, there are lots of advantages.

  • It is faster than usually calling a php file that returns an xml
  • It is more practical because the data is already serialized
  • iIn flex you already have classes that work with amf

The first thing that needs to be done when you want to use amf protocol is to write your server side methods and pass it to the amf protocol hanlder class. The amf handler class receives the binary call from flash or flex application, calls your service method and returns the binary serialized data back to the flash.

There are several classes that do this thing for most of all programming languages. For the php the most known are AMFPHP, SabreAMF, WebORB for PHP, Zend_Amf, php-amf3 extension.

In this example is used the Zend_Amf from the Zend Framework, a framework library written by the zend community.

Steps to build your remote service methods

STEP 1 – Create amf Service file

Create a file called phonebook.php wich holds the main service methods

class Phonebook
{
 const DATA_FILE = "phonebook.dat";

 private $phonebook;

 public function __construct()
 {
 $this->phonebook = unserialize(file_get_contents(self::DATA_FILE));
 session_start();
 }

 public function login($user, $password)
 {
 if($user == "admin" && $password == "1234")
 {
 $_SESSION['logged'] = true;
 return true;
 }

 return false;
 }

 public function sync($phonebook = null)
 {
 if(is_array($phonebook) && count($phonebook))
 {
 $this->phonebook = $phonebook;
 file_put_contents(self::DATA_FILE, serialize($this->phonebook));
 }

 return $this->phonebook;
 }
}
}

The php code above is a simple phonebook application that save your serialized array with phone numbers into a file. This is a fast method just to show how to use the amf. You may also use mysql or other saving methods. The functions of this class must be public to be accesible from flex, you cannot call the private or protected methods.

STEP 2 – Instantiate the Zend_Amf_Server for handling the service class

Now will create a file called api.php with code below wich handle our public methods. For that we need to download the Zend Amf package, a simple way for get this is to use the packageizer application This package generator pack just nedded classes from the framework.

.

    //set your include path to the zend framework
    require "Phonebook.php";
    require "Zend/Amf/Server.php";
    $server = new Zend_Amf_Server();
    $server->setClass('Phonebook');
    $response = $server->handle();
    echo $response;

This class is simple to use just instantiate the Zend_Amf_Server class and pass your class to it. The setProduction method is used for throwing or not the errors generated from Phonebook class. For more documentation about using the Zend_Amf_Server please visit documentation page. From this point your service is functionable and the public methods can be called. From now on will need to do the flex application mxml wich will use this remote file.

STEP 3 – Create flex main file

This is a simple layout  having two states one for logged and other for editing mode with a DataGrid component and buttons for add and remove item. The code below is all needed to do for flex side, create the ui and build the logic for it.

View the mxml source

The class that is used to call remote amf methods is RemoteObject, if this is used from action script make sure you have been imported from the right package. The package for doing with the action script is mx.rpc.messaging. After will done with the RemoteObject initialization we need to create the operation that are linked to server side amf methods.

private function init():void
 {
 rpc = new RemoteObject();

 var channels:ChannelSet = new ChannelSet();
 channels.addChannel( new AMFChannel("api", "api.php") );

 rpc.destination = "api";
 rpc.channelSet = channels;

 rpc_login = rpc.getOperation('Phonebook.login') as Operation;
 rpc_login.addEventListener(ResultEvent.RESULT, onLoginResponse);

 rpc_sync = rpc.getOperation('Phonebook.sync') as Operation;
 rpc_sync.addEventListener(ResultEvent.RESULT, onSyncResponse);

 addEventListener(StateChangeEvent.CURRENT_STATE_CHANGE, onStateChanged);
 }

After the RemoteObject and operation instances are created make sure you add handlers for operations that are waiting for response for example the login method will return true if user has been logged in or false if not. A important think is to create crossdomain.xml on root where api.php file is created, otherwise the remote calls will be blocked by the flash security concern. This is just in case you are using a different domain if all files are in the same path is not necessary.

Try using user admin and password 1234

This is just a demo and data will be deleted after 10 items.

Download the source file

I hope this post is usefully for flex beginners if so i will be glad to hear your comments about it. Stay closed the next article will be about how to create a yahoo messenger client written in php and implemented on the last version of YMSG protocol.