Tutorial: jQuery Select Box Manipulation Without Plugin

In jQuery, working with select box required some additional knowledge and interaction with jQuery. You may have some problem manipulating select box during your web development on jQuery. In this article we will discuss how you can solve this without any additional plugin to kill efficiency.

Create Selext Box In jQuery

Create a select box is very simple and straight forward. Just write a string with the normal select tag and a select box is created in jQuery

jQuery('#some_element').append('<select></select>');

I bet everyone would have tried this and it work. However, manipulating might be a more challenging task.

Add Option In Select Box With jQuery

One easy way is to create a string with the whole element and create it straight away

//obj is the list of option values
function(obj)
{
	var create = '<select id="test">';
	for(var i = 0; i < obj.length;i++)
	{
		create += '<option value="'+obj[i]+'">'+obj[i]+'</option>';
	}
	create += '</select>';
	jQuery('#some_element').append(create);
}

Another way to create a list of elements is to create its option and append it in using pure jQuery.

function(id, obj)
{
	jQuery('#some_element').append('<select id="'+id+'"></select>');
	jQuery.each(obj, function(val, text) {
		jQuery('#'+id).append(
		jQuery('<option></option').val(val).html(text)
	);})
}

You may not be familiar what i wrote above. Hence, a more javascript approach is shown below.

function(id, obj)
{
	jQuery('#some_element').append('<select id="'+id+'"></select>');
	for(var i = 0; i < obj.length;i++)
	{
		jQuery('#'+id).append('<option value="'+obj[i]+'">'+obj[i]+'</option')
	}
}

Get Select Box Value/Text In jQuery

Sometimes we want to know what is the value of the selected option. This is how we do it. Please bear in mind that there shouldn't be any spaces between the : and selected.

//#selectbox is the id of the select box
jQuery('#selectbox option:selected').val();

On the other hand, we can get the text of the option by doing this.

//#selectbox is the id of the select box
jQuery('#selectbox option:selected').text();

What if you know the value of the options you want to get instead of the one selected?

//#selectbox is the id of the select box
$("#selectList option[value='thisistheone']").text();

How about the first element on the select box?

//#selectbox is the id of the select box
$("#selectList option:first").text()

How about the n element on the select box?

//#selectbox is the id of the select box
$("#selectList option:eq(3)").text()

How about getting all elements but the first and last one in a select box?

//#selectbox is the id of the select box
$("#selectList option:not(option:first, option:last)").each(function(){
$(this).text();
});

Get Multiple Selected Value/Text In jQuery Select Box

Now we want to try to retrieve multiple selected values, we can do it easily with the following code.

	jQuery('#some_element:selected').each(function(){
		alert(jQuery(this).text());
		alert(jQuery(this).val());
	});

How about storing these values?

	var current = [];
	jQuery('#some_element:selected').each(function(index, selectedObj){
		current[index] = $(selectedObj).text();
	});

This way we eliminate the additional index needed to follow through the loop! How about shorten the cold a bit?

var foo = jQuery('#multiple :selected').map(function(){return jQuery(this).val();}).get();

This way we eliminate the need to create an array.

Remove Element In Select Box With jQuery

So we can get and add element into the select box. How about remove them? Basically, you will need to use one of the get element method describe above before applying the remove instruction.

jQuery('#selectbox: selected').remove();

Here we will remove all elements except the first and last one.

//#selectbox is the id of the select box
$("#selectbox option:not(option:first, option:last)").remove();

Select an option in the select box with jQuery

If you want to select an option in the select box, you can do this.

jQuery('#selectbox option[value="something"]').attr('selected', 'selected');

all option will be selected in this case.

UnSelect an option in the select box with jQuery

If you want to unselect an option in the select box, you can do this.

jQuery('#selectbox option[value="something"]').attr('selected', false);

all option will be unselected n this case.

OnChange find selected option from the select box

onchange find select box selected item.

$('#selectbox').change(function(){
	var val = $(this).find('option:selected').text();
	alert('i selected: ' + val);
});

onchange find select box selected items.

$('#selectbox').change(function(){
	$(this).find('option:selected').each(function () {
		alert('i selected: ' + $(this).text());
	}
});

Summary

There are definitely other tricks to manipulate select box. The above are just some of it.

Solutions to Cross-Site Scripting (XSS) Attack

Recently i wrote an article on Solutions to SQL Injection Attack that have all the great solutions to tackle SQL Injection Attack. In this article, i would like to discuss with you about Cross-Site Scription attack which is also known as XSS attack.

Cross-Site Scripting Attack

What is cross-site scripting attack? You can easily get a definition written on Wikipedia. It is a type of computer security vulnerability typically found in web applications which allow code injection by malicious web users into the web pages viewed by other users. Often look perfectly fine on the end-users side who may be subject to unauthorized access, theft of sensitive data, and financial loss. Here are a few cross-site scripting attack scenarios you may find interesting.

Simple persistent attack

  1. Mallory posts a message to a social network.
  2. When Bob reads the message, Mallory's XSS steals Bob's cookie.
  3. Mallory can hijack Bob's session and impersonate Bob.

DOM-based attack

  1. Mallory sends the URL of a maliciously constructed web page to Alice, using email or another mechanism.
  2. Alice clicks on the link.
  3. The malicious web page's JavaScript opens a vulnerable HTML page installed locally on Alice's computer.
  4. The vulnerable HTML page contains JavaScript which executes in Alice's computer's local zone.
  5. Mallory's malicious script now may run commands with the privileges Alice holds on her own computer.

Non-Persistent

  1. Alice often visits a particular website, which is hosted by Bob. Bob's website allows Alice to log in with a username/password pair and store sensitive information, such as billing information.
  2. Mallory observes that Bob's website contains a reflected XSS vulnerability.
  3. Mallory crafts a URL to exploit the vulnerability, and sends Alice an email, enticing her to click on a link for the URL.
  4. Alice visits the URL provided by Mallory while logged into Bob's website.
  5. The malicious script embedded in the URL executes in Alice's browser, as if it came directly from Bob's server. The script can be used to send Alice's session cookie to Mallory. Mallory can then use the session cookie to steal sensitive information available to Alice (authentication credentials, billing info, etc) without Alice's knowledge.

Persistent

  1. Bob hosts a web site which allows users to post messages and other content to the site for later viewing by other members.
  2. Mallory notices that Bob's website is vulnerable to a type 2 XSS attack.
  3. Mallory posts a message to Bob's website.
  4. Later, Alice views Mallory's message.
  5. Alice's session cookies or other credentials can be taken and sent to Mallory, without her knowledge.
  6. Mallory logs into Bob's website as Alice, and can see sensitive information (billing info etc.), or post messages on her behalf.

Identity Attack

  1. Bob hosts a site that allows users to post messages which includes a stored list of user names as recommendations.
  2. Alice is a regular visitor to the recommendation-based site; she uses an alias to protect her identity.
  3. Mallory knows one or more of Alice's email addresses but not her identity alias.
  4. Mallory uses social engineering to send a disguised recommendation link or the link to a carefully constructed redirect page which recommends a staged posting to Bob's site.
  5. Alice clicks on the link. Her session cookies or willing-login trigger the recommendation.
  6. Mallory reads the recommendation list and discovers Alice's online identity.

The above scenarios are taken from Wikipedia itself which i find it most appropriate to demonstrate the danger of XSS attack.

Solutions

It is well said that the responsibility of preventing XSS attack should not only be held by the developers. End user will really required to know this to better protect themselves from such attacks. It is always better to believe in yourself than others when it comes to security. In this article, we will discuss solutions to better secure ourselves and our web application. Although there are many risk with XSS attack, defending against it is much easier than you might though.

Developers

Filter all foreign data

Anything that will store in our database for future display to other user entered by users are consisted as foreign data. Ensure that all these data are being filter correctly will greatly prevent XSS attack from occurring on your website. Although it may sound easy but it does take discipline to always filter these data whenever there is such input. Especially on larger system where many developers are working on it. Simple filter such as htmlentities() can help eliminate many Cross-site scripting concern.

$filter_input = htmlentities($post['userinput'])
#use $filter_input

Use existing functions

Always use existing functions exist on PHP. Functions like htmlentities(), strip_tags(), and utf8_decode() can be useful. Try not to create your own function for filtering purposes as the functions in build in PHP are usually much faster and more secure to be used. Here are some functions that within PHP that are great for valid or filter user input

  • htmlentities()
  • strip_tags ()
  • utf8_decode ()
  • htmlspecialchars()
  • ctype_digit()
  • ctype_alnum()

Use a whitelist approach

Always assume data to be invalid until it is proved valid. This means that checking the length of the given input, validate the correct type, using regular expression to further validate the creditability till the extreme case you can imagine. This will help prevent any circumstances when the filter failed and caused the script to access your website.

Use a strict naming convention

We all know big systems are usually build by a few developers. Hence, it is important to use a strict naming convention so that whenever a developer look at the code he is able to identify what the other developer is trying to accomplished (you never know what some developer will do during refactoring to make the code more efficient. Yes, they remove these important stuff) and whether the data has been tainted.A lack of clarity yields confusion, and this breeds vulnerabilities. It is a good practice for developer to always be suspicious towards these global variables ($_POST, $_GET, $_REQUEST, etc.). An example of such strict naming convention can be illustrate below,

<?php
$clean = array();
#check whether it is a float, this is just a demo and more validation should be applied before it is clean.
if ($_POST['num'] == strval(floatval($_POST['num'])))
{
$clean['num'] = $_POST['num'];
}
#we use clean array onwards.
?>

Initialize your data

It is a good practice to always initialize your data although it is not necessary to do that in PHP. Since any variable that has not been initialize should always be considered as tainted. It is important to untainted it by initialize them. The user does not have another opportunity to send data as the entire HTTP request has been received, hence no data can be injected into your script (even if register_globals is enabled). Assume register_globals is enabled an attacker can easily make our clean variable into a malicious code if we did not initialize it. Consider the following code,

domain.com?clean=malicious_code

because we did not initialize clean array, clean now contains malicious code that may caused damage to our system.

#this part was invalid
if ($_POST['num'] == strval(floatval($_POST['num'])))
{
$clean['num'] = $_POST['num'];
}
#we use clean array onwards.
?>

Cookie Security

Another form of cross-site scripting attack is through cookie security. Many website uses cookie for various reason such as store information, retrieve information, track activities and etc,. However, most web applications rely on session cookies for authentication between individual HTTP requests (the remember me box on login page). We all are aware that client script have access to such cookie and simple XSS script can be made to retrieve such authentication to fake user access. To mitigate this particular threat, we can tie session cookies to the IP address of the user who originally logged in, and only permit that IP to use that cookie. but it will obviously break when an attacker is behind the same NATed IP address or web proxy.

Use BBCode

Many website such as forums, blogs, CMS or other communication system provides the ability to enhance that content by posting formatted text. However, these formatted text is vulnerable against Cross-site scripting attack. Many will uses BBCode on their system to provide user with formatted text and at the same time protect themselves against such attack. Consider the following example of BBCode

[b]bold[/b] text 
to
<b>bold</b> text

[color=blue]blue text[/color]
to
<span style="color: blue">blue text</span>

You can know more about BBCode in Wikipediawhere more example and explanation is being provided on BBCode. However, using such tag doesn't guarantee XSS security. Consider the following attack example within BBCode,

[url=http://hungred.com]Web development bookmark[/url]
to
<a href="http://hungred.com">Web development bookmark</a>.

The above illustrate a normal anchor tag BBCode. However, if i placed a JavaScript into the BBCode, it is still valid in BBCode,

[url=javascript:alert('Got you!')]Web development bookmark[/url]
to
<a href="javascript:alert('Got you!')">Web development bookmark</a>.

That is why whitelist approach is needed to always prevent such attack from coming. Similarly, in some lower versions of Internet Explorer (IE6 and below), URL format is allowed and will execute Javascript which we will have to take care as well.

XSS CheatSheet

For developers who are concern about XSS attack. (which you should) Please visit this XSS (Cross Site Scripting) Cheat Sheet to further test and protect against XSS attack.

End User

Disabled JavaScript

Many end-users (includes developers) who are well aware of XSS attack and the harm that it may bring upon the user will have their JavaScript disabled on their browsers. Since Cross-Site scripting is using JavaScript to harm users. Disabled such feature is the best way to prevent any attack from Cross-Site scripting. Although this will means that many newer site which only deploy JavaScript may not be accessible, this will also means that many developer will have to ensure that their site is fully protected against such attack. Users can disabled JavaScript and only allows those that are trusted. This approach act as a white list approach where only trusted website has JavaScript enabled to prevent any damage from occurring.

Disabled Cookie

User may want to disabled cookie in order to protect themselves against XSS attack or older browser may not even support cookies. Developers will have to think of alternative ways to provides functionality that required cookies than depending on it.

Summary

Developer must ensure the safety of its visitors and build a safer system for end users. On the other hand, end-user (including developers) will need to know the type of attacks used by attackers to prevent such attacks. The solutions above might not be full bullet proof solution for future Cross site scripting attack. Nonetheless, it can be used for discussion on solutions of future such attack.

Solutions to SQL Injection Attack

Security is one of the major issue we want to take care of other than meeting dateline. Especially when it comes to server data. We always want our data to be correct and secure. No one should be able to manipulate these data and these data should only be confine to people that have access to it. One should need to know the attacks on server data in order to better secure them. In this article, we will discuss SQL injection attack on databases.

SQL Injection Attack

SQL Injection Attack is the most common type of problem most web system face. Let's consider the following code

<?php
$name = ''test'; DELETE FROM users;';
mysql_query('SELECT * FROM users WHERE name='.$name.' ');
?>

Basically, the query above will caused all the data in your the users table to be deleted. This is usually due to inconsistency during development by different people. Lucky, there are many ways to prevent this.

The Solutions

Escape Mechanism

In order to prevent SQL injection attack, PHP's automatic input escape mechanism, magic_quotes_gpc, can provides some rudimentary protection (this is required to be enabled on php.ini). The magic quote will append a backslash to characters that is used to break out of a value identifier. eg, ', ", . etc. However, this is not always automatically enabled due to various reason. If you are using MySQL, it has a built-in function mysql_real_escape_string() to escape input characters that are special to MySQL. However, before calling a database's own escaping mechanism, it is important to ensure that no two escape mechanism is being used at the same time.

Escape Without Discipline

We talk about how escape mechanism can help us prevent SQL injection attacks. However, with the help of escape mechanism doesn't means that we are free from SQL Injection. We can still do some code injection even though we have implemented escape mechanism. Let's consider this example,

<?php
$id= '0; DELETE FROM users;';
$id = mysql_real_escape_string($id);
mysql_query('SELECT * FROM users WHERE id='.$id.' ');
?>

Similarly, SQL Injection attack is still possible since the escape mechanism only add additional backslash to characters that is used to break out of a value identifier such as single or double quote. There are no particular character that will need a backslash on the $id variable string. Thus, nothing was being added and the query will run as usual (danagerous). The solution to this situation is pretty simple, Discipline. Many times developers will like to skip the important process of adding quote in the SQL query. Being discipline and add these particular characters into your query will definitely save yourself from SQL injection attack. Example,

<?php
$id= '0; DELETE FROM users;';
$id = mysql_real_escape_string($id);
mysql_query('SELECT * FROM `users` WHERE id="'.$id.'" ');
?>

This will prevent the SQL from running the second query since there is no such id(int) as '0; DELETE FROM users'. The other way is to valid whether the particular $id is an integer.

<?php
$id= '0; DELETE FROM users;';
$id = (int) $id;
$id = mysql_real_escape_string($id);
mysql_query('SELECT * FROM users WHERE id='.$id.' ');
?>

This will cast $id into integer If the input is not entirely numeric, only the leading numeric portion is retrieved. eg, '999; DELETE FROM users;" will return 999. If the input doesn't start with a numeric value or there is no numeric values, 0 is returned. This is the best way to determine whether a particular value is an numeric value. No escape mechanism is required for this method but this can only be used for numeric validation.

LIKES Operator Danger

The LIKES Operator in SQL is a very powerful filter instruction that allows the query to use '%' for any characters that occurs zero or more times or '_' for a single character. However, both magic quote and built-in escape mechanism will skip these two special character. Thus, denial of services attack can be launch into the web server using SQL injection attack. Consider the following example,

$para= mysql_real_escape_string('%12'); // still %12
mysql_query('SELECT * FROM document WHERE number LIKE "'.$para.'%"');

Imagine this is a transaction table which has millions of documents. Searching number 12 in a particular number for a million times will definitely denial the access of this web portal services. Hence, we will need something that will escape these two special characters. We can use addcslashes() in PHP to add the required backslash onto these special characters!

$para= addcslashes mysql_real_escape_string('%12_')); // it will be \%12\_
mysql_query('SELECT * FROM document WHERE number LIKE "'.$para.'%"');

The above correct solution will provides no result due to the additional of \% and \_ into the query.

MySQL Exception

Fortunately, if you use MySQL, the mysql_query() function does not permit executing multiple queries in a single function call. If you try to stack queries, the call fails. However, other PHP database extensions, such as SQLite and PostgreSQL will permit such action.

Base64-encode

A common techniques is to use base64_encode in PHP to encode all data that are stored in the database. This will prevent any special character from damaging your query statement as any new query to the database will have to be encoded before the database recognize.

<?php
mysql_query('INSERT INTO users (name) VALUES "'.base64_encode('test').'"');
$name = base64_encode('test'; DELETE FROM users;');
mysql_query('SELECT * FROM users WHERE name=''.$name.'"');
?>

However, base64 encode will roughly increase data size by 33%, requiring bigger storage space. Moreover, PostgreSQL query with LIKE will fail due to base64.

Prepared Statements

The most efficient and powerful way to solve SQL injection attack, i would said it would be prepard statements. Prepared statements will only required to set up a statement once, and then it can be executed many times with different parameters. They are designed to replace building ad hoc query strings, and do so in a more secure and efficient manner. A typical prepared statement is shown below,

#MySQL
SELECT * FROM Users WHERE name = ?

The ? is what is a called a placeholder. You would need to supply the value for it during execution. You can read more about Prepared statements in MySQL at their website. Here is one example,

<?php
mysql_query('PREPARE search_template FROM "SELECT name FROM Users WHERE name = ?"');
mysql_query('SET @param = "test"');
mysql_query('EXECUTE search_template USING @param');
mysql_query('SET @param = "hello"');
mysql_query('EXECUTE search_template USING @param');
mysql_query('DEALLOCATE PREPARE search_template;');
?>

Unlike ad-hoc query string, the second query being executed with 'hello' as parameter doesn't add on the additional overhead of the search template which was prepared previously.

SQL Error Handling

How do hackers know your table name and the query you wrote? The answer is pretty simple and straight forward. It is mainly due to poor SQL error handling by the developers. The hackers will try their very best to break your SQL query in any way that will result in an error. Once the error is displayed, they will have many information to launch a proper attack. Let's consider an example,

<?php
#query=test;DELETE FROM breakplease;
$query = 'SELECT * FROM user WHERE name ='. base64_decode($_GET['query']);
mysql_query('$query);
?>

This will caused a decent error to be display on the page. And the user will have an idea what is being passed into the query string and what table is being used. Both structure, fields and GET parameter were exposed to the hacker in this way.

The best way is to prevent such embarassement by providing a more end-user type of message with a php error handling function.

function sql_failure_handler($query, $error) {
$msg = htmlspecialchars('Failed Query: {$query}<br>SQL Error: {$error}');
error_log($msg, 3, '/home/site/logs/sql_error_log');
if (defined('debug')) {
return $msg;
}
return 'Requested page is temporarily unavailable, please try again later.';
}

#query=test;DELETE FOM breakplease;
$query = 'SELECT * FROM user WHERE name ='. base64_decode($_GET['query']);
mysql_query('$query) or die(sql_failure_handler($query, mysql_error()));

This will provides us developer with relevant message on our TEST environment and provides the end-users with a more standard message on LIVE environment.

Authenticate Data Connection

This concern on how we store our application's database credentials. Some will placed it into an external files and gives it a non-PHP extension such as .inc. This post a problem as the file can be access directly outside of the server and it will be shown with plain text since it is not interpreted by PHP machine. Hence, we will have to better secure these database credentials from unauthorized access. One solution is to restrict the access of .inc in that particular folder defined in your web server (which many might not have in a shared hosting environment).

<Files ~ '\.inc$'>
Order allow,deny
Deny from all
</Files>

Or just changed it into .php extension so that it will not be exposed in plain text. However, if there is code written in that file, the same issue might still happen. If you have root access, you can do the following in your apache configuration file, httpd.conf

<VirtualHost ilia.ws>
Include /home/ilia/sql.cnf
</VirtualHost>

Now, set the file sql.cnf with the following codes,

SetEnv DB_LOGIN 'login'
SetEnv DB_PASSWD 'password'
SetEnv DB_DB 'my_database'
SetEnv DB_HOST '127.0.0.1'

This way, the details can be access via $_SERVER or getenv() in your PHP script without hardcoding it somewhere in your system.

echo $_SERVER['DB_LOGIN']; // login
echo getenv('DB_LOGIN'); // login

A more powerful way is to hide them even from the script that needs them. How to do that? we stored it into PHP.ini directives by specify the default login. These also can be set inside of Apache configuration file.

php_admin_value mysql.default_host '127.0.0.1'
php_admin_value mysql.default_user 'login'
php_admin_value mysql.default_password 'password'

Now you will connect to your database without any parameter and it will takes the default value from your apache configuration file.

mysql_connect()

Reduce the damage

It is a good practice to always indicate the number of results needed to retrieved from the table. Consider the following example,

<?php
$name = '"test"; SELECT * FROM users;';
mysql_query('SELECT * FROM users WHERE name='.$name.' LIMIT 1');
?>

Limiting the number of result return can help minimize the damage of SQL injection attack. Especially during authentication process. On the other hand, it is also a good idea to restricting the database permissions. By limiting the users permission, the damage of SQL injection attack can greatly minimized. Eg, only select access should be given to the user on the above query. Therefore, if the attacker tried to change the password by doing a SQL injection, it will fail (unauthorizes access).

Another alternative is to enhance the performance between your database and the script. We see Denial of service attack can be launch against the system due to the usage of LIKES operator. Having a good performance between the database and the web server is strongly advisable to minimize the impact on our business. Thus, to minimize database overloading, we can look at a few simple rules.

  1. Only retrieved the field you need. '*' is always misused by lazy developers
  2. try unbuffered query. It speeds up query but limit the work with only one query
  3. You can speed up connection process by using persistence connection. Eg, in MySql
    mysql_pconnect('host', 'login', 'passwd');
    

    However, if the database is not configure to allow many connection, further connection request will be rejected (since persistence connection is hooking the line). Hence, denial of services occurs.

MYSQL User account

For different action in the system, different MYSQL user account should be used. This will greatly help minimize the risk of damage done to the database if certain page was compromised. For example, a login page should only have SELECT access as other action is redundant. However, if you provide a full access level to a simple login page where any unauthorized user can access, malicious user can easily change the password through the text box provided to gain access to your portal if SQL injection vulnerability was found. Hence, brute force is not necessary to break down the door. They simply ring the bell! You are just inviting guess into your portal.

Summary

Although SQL injection attack is a common attack launch against many website, web developers have to ensure that these attack is minimize and eliminated. The solutions above might not be full bullet proof solution for future SQL injection attacks. Nonetheless, it can be used for discussion on solutions of future SQL Injection attack.

Prevent WordPress Plugin Update From Deleting Important Folder In Your Plugin

Many would know that i have build a powerful thumbnail plugin in WordPress. The plugin work perfectly fine for WordPress 2.8 below but once i updated my WordPress to version 2.8, something bad happen. Every single time whenever i update my WordPress plugin, WordPress will delete the plugin folder with everything included and install the latest plugin version. This post a problem to my plugin since all the images are stored inside the plugin folder. I search online but i couldn't get any help anywhere until i investigate the new version 2.8 core codes.

New Hooks in WordPress 2.8

In WordPress 2.8, it has added a new functionality to delete the previous version of the plugin and then install the latest plugin version into the exact same location. Lucky, it also includes a few more filter hook that did the delete and install process. In class-wp-upgrade.php located at /admin/includes/class-wp-upgrade.php, lines 403-409 you will notice the following few codes,

		add_filter('upgrader_pre_install', array(&$this, 'deactivate_plugin_before_upgrade'), 10, 2);
		add_filter('upgrader_clear_destination', array(&$this, 'delete_old_plugin'), 10, 4);
		//'source_selection' => array(&$this, 'source_selection'), //theres a track ticket to move up the directory for zip's which are made a bit differently, useful for non-.org plugins.

		$this->run(array(
					'package' => $r->package,
					'destination' => WP_PLUGIN_DIR,
					'clear_destination' => true,
					'clear_working' => true,
					'hook_extra' => array(
								'plugin' => $plugin
					)
				));

		//Cleanup our hooks, incase something else does a upgrade on this connection.
		remove_filter('upgrader_pre_install', array(&$this, 'deactivate_plugin_before_upgrade'));
		remove_filter('upgrader_clear_destination', array(&$this, 'delete_old_plugin'));

I went to search on Google again for these new hook and it seems like there are a couple more of these new hooks being added into WordPress 2.8. But we are particularly interested on 'upgrader_pre_install' and 'upgrader_post_install' filter hook.

Using upgrade_pre_install filter hook

function hpt_copyr($source, $dest)
{
    // Check for symlinks
    if (is_link($source)) {
        return symlink(readlink($source), $dest);
    }

    // Simple copy for a file
    if (is_file($source)) {
        return copy($source, $dest);
    }

    // Make destination directory
    if (!is_dir($dest)) {
        mkdir($dest);
    }

    // Loop through the folder
    $dir = dir($source);
    while (false !== $entry = $dir->read()) {
        // Skip pointers
        if ($entry == '.' || $entry == '..') {
            continue;
        }

        // Deep copy directories
        hpt_copyr("$source/$entry", "$dest/$entry");
    }

    // Clean up
    $dir->close();
    return true;
}
function hpt_backup()
{
	$to = dirname(__FILE__)."/../hpt_images_backup/";
	$from = dirname(__FILE__)."/images/";
	hpt_copyr($from, $to);
}
function hpt_recover()
{
	$from = dirname(__FILE__)."/../hpt_images_backup/";
	$to = dirname(__FILE__)."/images/";
	hpt_copyr($from, $to);
	if (is_dir($from)) {
		hpt_rmdirr($from);#http://putraworks.wordpress.com/2006/02/27/php-delete-a-file-or-a-folder-and-its-contents/
	}
}
add_filter('upgrader_pre_install', 'hpt_backup', 10, 2);
add_filter('upgrader_post_install', 'hpt_recover', 10, 2);

In order to prevent WordPress plugin update from deleting our important folder within our plugin, we must move that particular folder somewhere safe before it starts deleting everything in our plugin. After the update has completed, we will then move the folder that we want to preserved and overwrite any existing files in that folder. We can't remove the filter action as shown on the core WordPress code was because the filter was not added previously. Thus, removing the filter will not prevent the deletion.

The Secret Arguments Array in JavaScript

Well, this is not really a secret to be exact. Many experience programmers who have worked with JavaScript for many years will surely come across arguments array. Some book may even forgotten the existence of arguments array since it is not widely used. Hence, i believe majority of JavaScript programmers do not actually know the existence of such array in JavaScript. So allow me to explain what is arguments array.

Arguments Array

An arguments array is a predefined array used within a function in JavaScript. Whether you used it or not it will still exist within that function. The main advantage of using arguments array is the unlimited number of argument or parameter you can pass into a function. Let's consider the following example,

function example()
{
	var sum = 0;
	for(i = 0; i < arguments.length;i++)
	{
		sum += arguments[i];
	}
	alert(sum); //45
}
example(1,2,3,4,5,6,7,8,9,0);

i find that the above example will simply get the idea through how arguments array worked. It is an array so whatever we passed in via arguments will be placed into an arguments array within the function. Then, we simple just used it. The above example is an simple addition function. You can see another example at override ‘this’ object in JavaScript

Detect Arguments

What if we want to use the arguments array in certain circumstances but not all the times? Preload with jQuery shows one particular function that uses an array or parameter depend on how users want to use that function (now, you might have guess how a library such as jQuery allows multiple different parameter for a single function). In order to do that, we have to detect what arguments or values been passed on to the function.

In JavaScript, we can detect a particular value by using comparison operators (===, ==, !=, etc.) but there are also other techniques to detect these arguments. We can use in operator which detect whether a given value is in the arguments array (in operator is not widely supported. Thus, you don't see many using it). There are also typeOf operator which determine what is the type of the value (string, object, int, etc.)which you can see from Preload with jQuery article. Lastly, there is Autocasting operator which evaluate whether a variable has a value (NaN, 0, false, undefined, null, or an empty string are considered as no value). Let's look at each new detection method example that i mention here.

//Detect whether there is a "hello" member in the arguments array: 
var parameter = 'hello' in arguments? arguments : "";

//Detect whether arguments contains at least one argument
var parameter = typeof arguments[0] != 'undefined'? arguments : "";

//Detect whether the user passed an object(can be array) or a list of arguments
var parameter = (typeof arguments[0] == 'object')? arguments[0] : arguments;

//Detect whether there is an arguments passed into the function and assign the number of arguments into the variable
var parameter = arguments.length || "";

Summary

Using Argument Array is great as we are not restricted by the number of parameter on a given function. However, many online tutorial on basic JavaScript no longer practice this since it is said that this has been depreciated with new browsers emerged but its still usable in JavaScript up till today (who said its depreciated!).