Guarantee Make WordPress Flash Uploader Work

Hungred Dot Com has always had its flash uploader disabled due to many reason which i personally have no idea why. Many people said it was due to WordPress 2.7 update which caused the incompatibility of flash 10 with the flash uploader, swfupload. And here goes the big discussion on how to make WordPress flash uploader WORK. Of course, i was just a pass by reader and tried some mention methods by the public which still fail. The flash uploader that i have is shown below,

browser-uploader

After WordPress 2.8 was launched which was said that the flash uploader will be back kicking, but it doesn't! And slowly, it seems like my WordPress is getting bit and pieces of errors from firebug whenever I'm on WordPress. Furthermore, it gets really lag on Firefox when I'm on writing post. Very soon, some of the features failed such as the auto draft when you are adding post. But that doesn't bother me! Until i finished update my WordPress theme and fixed many stuff within this blog that i finally decided to solve my WordPress problem (back to topic, haha).

WordPress Flash Uploader Solutions

So i went to Google and perform a simple search which lead me to a lot of duplicate solution mention in the WordPress forum. Hence, i started my journey to resolve all these weird issues here and there in WordPress admin. Here are the solutions mention:

  • You'll have to go back to version 9 of Flash Player
    . Tried that, failed.
  • Check the permissions on the swfupload file. oh boy! moderator speaks up! but still not working.
  • Reuploading wp-includes and wp-admin fixed it. This must be it! still fail.
  • fix it by reuploading:
    /wp-includes/js/swfupload/
    And then clearing my browser cache.

    While everyone said 'it work!' in the forum, i still fail!
  • check swfupload.swf is in the folder of /wp-includes/js/swfupload/. YA! but it still not working!
  • issue was mod_security it was working previously! So i skipped this smartly 😀
  • I don't find that this works. The button is there, but clicking on it does absolutely nothing. It just sits there. God, you are lucky. Mine doesn't even exist.
  • The version of the swfupload in 2.6.5 did not work with Flash 10. 2.7 has the workaround for that. The moderator is back. Man he is one helpful guy! Updated to the latest version. But still fail.
  • Folks, make sure you're uploading the entire swfupload folder from WordPress 2.7, not just the swfupload.swf file.I uploaded the whole cow in and nothing happen!

That's it! Here are all the solution presented by the forum, other site are just copying each other work which still doesn't work for me. Hence, if you are like me then you should read on.

Guarantee Awake The Sleeping WordPress Flash Uploader

From here on, its a personal tried and error thing that will assure Hungred Dot Com safety at the same time guarantee that this flash uploader will work. Please backup both databases and your WordPress files before doing this. The situtation is that I had a few WordPress blog that i either setup for myself or for others after Hungred Dot Com. All other WordPress blog flash uploader work like charm but not this. Therefore, i can conclude something is wrong with this blog and not others (obvious).

According to the forum written above, it seems like everything is surrounding the folder of swfupload in /wp-includes/js/swfupload/. However, replacing it still doesn't work. May be its not that problem. Something else is being modified without me knowing. May be some plugin that i tired on Hungred Dot Com. Hence, i tried to remove the folder on /wp-includes/js/ which means every single JavaScript in WordPress is being removed, the admin site only of course. The removable really doesn't affect the main site. I upload the one in WordPress 2.8 that i downloaded from WordPress but it still doesn't work. The next try were to copy the whole folder /wp-includes/ and /wp-admin/ replacing the one stored on the server. This does takes a while but the site wasn't being affected. After the upload had complete, i tried the flash uploader but it still doesn't work. The folder /wp-content/ shouldn't had affected the admin page so i shouldn't touch that folder.

If my theory is correct, everything should have been replaced by the latest file that i have just uploaded. This means that i am actually performing a re-installation already. However, why is it still not working? My next though is that there exist a file that run in the previous version that wasn't replaced or removed by this sort of re-installation. Therefore, i decide to delete the folder /wp-includes/ and /wp-admin/ and replace with the latest one that i downloaded from WordPress. However, doing that will definitely killed my blog for a while since /wp-includes/ exist files that required for the site to function. My solution was to do it within the file manager provided by my host that allows me to directly interact with the server that is 100x faster than using FTP. Here is a screen shot of it.

file-manager

I upload the zip file through this file manager given by Hostgator and unzip into a folder. Deleting the folder of both /wp-includes/ and /wp-admin/ takes around 1 second and copying the new folder to Hungred Dot Com also takes around 1-2 second. This should be it! The fash uploader should work now! Unfortunately, it still doesn't work. DAMMIT!

However, i can assure that my WordPress is clean and definitely should have the flash uploader i set out for (the clean here refer to any files that might killed my flash uploader that wasn't being deleted previously). The next culprit will be the plugin i have used in WordPress! Some WordPress developers must have done something that caused all this problem! I went over to my WordPress plugin page and deactivate all my WordPress plugin immediately, went to upload a file, and..

flash-uploader

Damn! It was some plugin exist in my WordPress all along (may be not?)! So i hand picked those plugin that associate with WordPress add post page that could caused this. After i enabled most of it, i left the last one plugin that might just be the criminal that does all these. Guess what? None of them were. It seems like after i enabled and disabled all plugin, the flash uploader were enabled again. Other functionality such as auto save draft and stuff were also back online. Confused.

Conclusion

The above method will surely assure that your WordPress is clean again but it might caused you some problem. Depending on how desperate you are (HELL YEAH I WAS!), you might just tried some of the things above or just skipped more of it. Nonetheless, i am just trying to reinstall the whole WordPress and minimize the damage that will caused to the problem. In my case, nothing was missing and everything sail smoothly again. Hope this help! (man, this is one whole story. To the point damnit! *slap myself*)

WordPress Text Formatting Problem – Solved!

In Hungred Dot Com, we have been having problem with text formatting in WordPress for all our codes due to WordPress smart quotes functionality. Most of us who write code for the public usually uses those smart plugin such as 'SyntaxHighlighter Evolved' to present it nicely to our users. The problem with using external plugins such as this is that WordPress smart quotes doesn't see the tag for the plugin in this case,


,
as one of excluding formatting tag. Tag such as 'pre', 'code', 'kbd', 'style', 'script', 'tt' are excluded from smart quotes which you can personally view it on the source code of WordPress located at wp-includes/formatting.php. Hence, your WordPress codes article will not be showing '"' instead of the normal '"' symbol. However, there are ways to solve such problem and here we will present them to you to eliminate all these trouble once and for all!

Include Tag In WordPress Text Formatting Function

One way to solve this problem is to add the plugin tag into the core function wptexturize which locate at wp-includes/formatting.php. In that file you will notice the following function,

/**
 * Replaces common plain text characters into formatted entities
 *
 * As an example,
 * <code>
 * 'cause today's effort makes it worth tomorrow's "holiday"...
 * </code>
 * Becomes:
 * <code>
 * ’cause today’s effort makes it worth tomorrow’s “holiday”…
 * </code>
 * Code within certain html blocks are skipped.
 *
 * @since 0.71
 * @uses $wp_cockneyreplace Array of formatted entities for certain common phrases
 *
 * @param string $text The text to be formatted
 * @return string The string replaced with html entities
 */
function wptexturize($text) {
	global $wp_cockneyreplace;
	$output = '';
	$curl = '';
	$textarr = preg_split('/(<.*>|\[.*\])/Us', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
	$stop = count($textarr);
	
	/* translators: opening curly quote */
	$opening_quote = _x('“', 'opening curly quote');
	/* translators: closing curly quote */
	$closing_quote = _x('”', 'closing curly quote');
	
	$no_texturize_tags = apply_filters('no_texturize_tags', array('pre', 'code', 'kbd', 'style', 'script', 'tt'));
	$no_texturize_shortcodes = apply_filters('no_texturize_shortcodes', array('code'));
	$no_texturize_tags_stack = array();
	$no_texturize_shortcodes_stack = array();

	// if a plugin has provided an autocorrect array, use it
	if ( isset($wp_cockneyreplace) ) {
		$cockney = array_keys($wp_cockneyreplace);
		$cockneyreplace = array_values($wp_cockneyreplace);
	} else {
		$cockney = array("'tain't","'twere","'twas","'tis","'twill","'til","'bout","'nuff","'round","'cause");
		$cockneyreplace = array("’tain’t","’twere","’twas","’tis","’twill","’til","’bout","’nuff","’round","’cause");
	}

	$static_characters = array_merge(array('---', ' -- ', '--', ' - ', 'xn–', '...', '``', '\'s', '\'\'', ' (tm)'), $cockney);
	$static_replacements = array_merge(array('—', ' — ', '–', ' – ', 'xn--', '…', $opening_quote, '’s', $closing_quote, ' ™'), $cockneyreplace);

	$dynamic_characters = array('/\'(\d\d(?:’|\')?s)/', '/(\s|\A|")\'/', '/(\d+)"/', '/(\d+)\'/', '/(\S)\'([^\'\s])/', '/(\s|\A)"(?!\s)/', '/"(\s|\S|\Z)/', '/\'([\s.]|\Z)/', '/(\d+)x(\d+)/');
	$dynamic_replacements = array('’$1','$1‘', '$1″', '$1′', '$1’$2', '$1' . $opening_quote . '$2', $closing_quote . '$1', '’$1', '$1×$2');

	for ( $i = 0; $i < $stop; $i++ ) {
		$curl = $textarr[$i];

		if ( !empty($curl) && '<' != $curl{0} && '[' != $curl{0}
				&& empty($no_texturize_shortcodes_stack) && empty($no_texturize_tags_stack)) { // If it's not a tag
			// static strings
			$curl = str_replace($static_characters, $static_replacements, $curl);
			// regular expressions
			$curl = preg_replace($dynamic_characters, $dynamic_replacements, $curl);
		} else {
			wptexturize_pushpop_element($curl, $no_texturize_tags_stack, $no_texturize_tags, '<', '>');
			wptexturize_pushpop_element($curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes, '[', ']');
		}

		$curl = preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/', '&$1', $curl);
		$output .= $curl;
	}

	return $output;
}

You can add your tag into the function on this link,

$no_texturize_tags = apply_filters('no_texturize_tags', array('pre', 'code', 'kbd', 'style', 'script', 'tt'));

for our example we will add [\php\]

$no_texturize_tags = apply_filters('no_texturize_tags', array('pre', 'code', 'kbd', 'style', 'script', 'tt', ''));

Although this solved your problem but this solution also required you to edit the codes in the WordPress which will be replaced with every new release of WordPress.

Remove WordPress Text Formatting

The most efficient way is to remove the root of the problem! Unless you desperately want WordPress text formatting to be made available, you will want to remove this. Otto42 who is one of the moderator suggested a good way to eliminate such problem. We will add the following two code to remove the function wptexturize in WordPress which perform the formatting in our theme function.php file.

remove_filter('comment_text', 'wptexturize');
remove_filter('the_excerpt', 'wptexturize');
remove_filter('the_content', 'wptexturize');
remove_filter('the_rss_content', 'wptexturize');

This way all your text and code will be safe from formatting on that theme. You can also create a very small plugin that do this by placing the above three links to ANY WordPress plugin (may be you don't even have to create any plugin for this).

Replace WordPress Default Text Formatting

For those who want WordPress smart quote to be enabled but doesn't want it to format your codes, you can try to replace the function wptexturize. You can do this on your theme or any plugin available for you. Basically, you can remove the default function wptexturize through the following code,

remove_filter('comment_text', 'wptexturize');
remove_filter('the_excerpt', 'wptexturize');
remove_filter('the_content', 'wptexturize');
remove_filter('the_rss_content', 'wptexturize');

After that on the same page, you can copy the following code and add the action hook for your new wptexturize solution that cater to your personal need.

function my_wptexturize($text) {
	global $wp_cockneyreplace;
	$output = '';
	$curl = '';
	$textarr = preg_split('/(<.*>|\[.*\])/Us', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
	$stop = count($textarr);
	
	/* translators: opening curly quote */
	$opening_quote = _x('“', 'opening curly quote');
	/* translators: closing curly quote */
	$closing_quote = _x('”', 'closing curly quote');
	
	$no_texturize_tags = apply_filters('no_texturize_tags', array('pre', 'code', 'kbd', 'style', 'script', 'tt', ''));
	$no_texturize_shortcodes = apply_filters('no_texturize_shortcodes', array('code'));
	$no_texturize_tags_stack = array();
	$no_texturize_shortcodes_stack = array();

	// if a plugin has provided an autocorrect array, use it
	if ( isset($wp_cockneyreplace) ) {
		$cockney = array_keys($wp_cockneyreplace);
		$cockneyreplace = array_values($wp_cockneyreplace);
	} else {
		$cockney = array("'tain't","'twere","'twas","'tis","'twill","'til","'bout","'nuff","'round","'cause");
		$cockneyreplace = array("’tain’t","’twere","’twas","’tis","’twill","’til","’bout","’nuff","’round","’cause");
	}

	$static_characters = array_merge(array('---', ' -- ', '--', ' - ', 'xn–', '...', '``', '\'s', '\'\'', ' (tm)'), $cockney);
	$static_replacements = array_merge(array('—', ' — ', '–', ' – ', 'xn--', '…', $opening_quote, '’s', $closing_quote, ' ™'), $cockneyreplace);

	$dynamic_characters = array('/\'(\d\d(?:’|\')?s)/', '/(\s|\A|")\'/', '/(\d+)"/', '/(\d+)\'/', '/(\S)\'([^\'\s])/', '/(\s|\A)"(?!\s)/', '/"(\s|\S|\Z)/', '/\'([\s.]|\Z)/', '/(\d+)x(\d+)/');
	$dynamic_replacements = array('’$1','$1‘', '$1″', '$1′', '$1’$2', '$1' . $opening_quote . '$2', $closing_quote . '$1', '’$1', '$1×$2');

	for ( $i = 0; $i < $stop; $i++ ) {
		$curl = $textarr[$i];

		if ( !empty($curl) && '<' != $curl{0} && '[' != $curl{0}
				&& empty($no_texturize_shortcodes_stack) && empty($no_texturize_tags_stack)) { // If it's not a tag
			// static strings
			$curl = str_replace($static_characters, $static_replacements, $curl);
			// regular expressions
			$curl = preg_replace($dynamic_characters, $dynamic_replacements, $curl);
		} else {
			wptexturize_pushpop_element($curl, $no_texturize_tags_stack, $no_texturize_tags, '<', '>');
			wptexturize_pushpop_element($curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes, '[', ']');
		}

		$curl = preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/', '&$1', $curl);
		$output .= $curl;
	}

	return $output;
}
remove_filter('comment_text', 'wptexturize');
remove_filter('the_excerpt', 'wptexturize');
remove_filter('the_content', 'wptexturize');
remove_filter('the_rss_content', 'wptexturize');

add_filter('comment_text', 'my_wptexturize');
add_filter('the_excerpt', 'my_wptexturize');
add_filter('the_content', 'my_wptexturize');
add_filter('the_rss_content', 'my_wptexturize');

This way you will solved your problem of code being wrongly formatted and at the meantime have the capability of smart quote. The only fall back of this method is that you might need to maintain this code in the future if WordPress ever update this function so that you will always have the latest version of smart quote.

Article Formatted Solution

If your post have many articles and you haven't had this problem solved at the beginning, your visitors will still be seeing formatted code in your article and might just drive your visitors away! Hence, you might want to consider reversing the function of wptexturize to return the format for you. You can do this by adding the reversed version of wptexturize and placed in on either a plugin or your theme.

We used hungred smart quotes to solve our issue on the above mention matters.

Summary

Smart quote in WordPress can be annoying and troublesome. Nonetheless, it also benefits those who truly wanted such function built within WordPress as it might just destroy your layout due to the unencoded tag by other writers. Hence, for those who are troubled by this, hopefully the solutions above help!

WordPress Plugin Development Tips And Tricks

I have been developing WordPress plugin for a while now and it seems like there are always some correct and better ways of writing a particular code in WordPress than mindlessly trying to substitute it with pure PHP. However, these WordPress codes can only be found through countless reading and analyzing of codes from other WordPress sources. In this article, i will present as many tips and tricks i have seen in WordPress that can be very useful for wordpress plugin development.

Find Plugin Directory and URL With WordPress

Previously, i used to hard code the directory by using PHP function. However, after realize there is a better alternative in WordPress, i changed the way i find the plugin directory and URL.

In PHP,

$url = get_bloginfo('url')."/wp-content/plugins/plugin-name/images/hello.jpg";
$directory = dirname(__FILE__)."/plugin-name/images/hello.jpg";

Note: Using dirname(__FILE__) might not always end up on the plugin folder.

In WordPress,

$url = WP_PLUGIN_URL."/plugin-name/images/hello.jpg";
$directory = WP_PLUGIN_DIR."/plugin-name/images/hello.jpg";

Import CSS or JavaScript in WordPress

We love to code these import statement out to the function that performed the action. It can be on the admin page, write post page, home page, etc. But the correct way is to use WordPress action hook and built-in method.

Import CSS/JavaScript to Admin page

function hpt_loadcss()
{
	wp_enqueue_style('hpt_ini', WP_PLUGIN_URL.'/hungred-post-thumbnail/css/hpt_ini.css');
}
function hpt_loadjs()
{
	wp_enqueue_script('jquery');
	wp_enqueue_script('hpt_ini', WP_PLUGIN_URL.'/hungred-post-thumbnail/js/hpt_ini.js');
}
add_action('admin_print_scripts', 'hpt_loadjs');
add_action('admin_print_styles', 'hpt_loadcss');

Import to theme page

function ham_add_style()
{
	$style = WP_PLUGIN_URL . '/hungred-ads-manager/css/ham_template.css';
	$location = WP_PLUGIN_DIR . '/hungred-ads-manager/css/ham_template.css';
	if ( file_exists($location) ) {
		wp_register_style('template', $style);
		wp_enqueue_style( 'template');
	}
}
add_action('wp_print_styles', 'ham_add_style');

Both ways utilize the wp_enqueue_style/wp_enqeue_script method and action hook to import stylesheet and JavaScript properly into WordPress.

Separate Plugin Admin Code

This is only necessary if you are building a large plugin for WordPress. It is efficient to separate the admin codes from others by placing it on an external file so that the admin codes will not be complied by PHP when non-admin user or visitors are accessing your website.

if (is_admin())
include(‘admin.php’);

Secure your WordPress Query

Security something important for all of us. WordPress has a function escape() in their global variable $wpdb. It is best to use this for all data query in your WordPress to better secure your SQL query with the database to prevent any form of security attack. below shows an example,

 $welcome_name = "Mr. WordPress";
  $welcome_text = "Congratulations, you just completed the installation!";

  $insert = "INSERT INTO " . $table_name .
            " (time, name, text) " .
            "VALUES ('" . time() . "','" . $wpdb->escape($welcome_name) . "','" . $wpdb->escape($welcome_text) . "')";

  $results = $wpdb->query( $insert );

You may want to visit the presentation slide that have some interesting WordPress function used for securitySecure Coding with WordPress – WordCamp SF 2008 Slides

Use WordPress For Table Prefix

Never hard code your table prefix in WordPress! WordPress provides a variable in its global variable $wpdb that allows you to easily retrieve your table prefix.

global $wpdb;
$table_name = $wpdb->prefix . "liveshoutbox";

Get Absolute Path In WordPress

In WordPress, you can get the absolute path through the constant ABSPATH which is defined in WordPress.

require_once( ABSPATH . '/wp-includes/classes.php' );
require_once( ABSPATH . '/wp-includes/functions.php' );
require_once( ABSPATH . '/wp-includes/plugin.php' );

Determine Whether a Table Exist In WordPress

Wonder how to determine whether a table exist in your WordPress? You can use the following method to detect whether a particular table exist.

global $wpdb;
$table_name = $wpdb->prefix . "mytable";
if($wpdb->get_var("show tables like '$table_name'") == $table_name) {
	echo 'table exist!';
}

Always Record Table Version

This is an important tips. Always remember to record the version of your plugin table, so you can use that information later if you need to update the table structure. This can help in upgrading your table structure of the plugin in the future.

add_option("hungred_db_version", "1.0");

Create Table Using WordPress Method

This is important for many WordPress developers out there. Although we can create a table using the following method,

	$table = $wpdb->prefix."ham_form";
    $structure = "CREATE TABLE  `".$table."` (
		ham_id DOUBLE NOT NULL DEFAULT 1,
		ham_textarea longtext NOT NULL,
		ham_display longtext NOT NULL,
		UNIQUE KEY id (ham_id)
    );";
    $wpdb->query($structure);

Great! A table is created! Now, tell me how are you going to change this structure in the future? A better alternative is to use the function dbDelta in WordPress.

	$table = $wpdb->prefix."ham_form";
    $structure = "CREATE TABLE  `".$table."` (
		ham_id DOUBLE NOT NULL DEFAULT 1,
		ham_textarea longtext NOT NULL,
		ham_display longtext NOT NULL,
		UNIQUE KEY id (ham_id)
    );";
	require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
	dbDelta($structure);

Directly from WordPress,

The dbDelta function examines the current table structure, compares it to the desired table structure, and either adds or modifies the table as necessary, so it can be very handy for updates (see wp-admin/upgrade-schema.php for more examples of how to use dbDelta). Note that the dbDelta function is rather picky, however. For instance:

* You have to put each field on its own line in your SQL statement.
* You have to have two spaces between the words PRIMARY KEY and the definition of your primary key.
* You must use the key word KEY rather than its synonym INDEX

Hence, any update on the structure of the table will result in a change on the user plugin as well.

Use Nonces During Form Submission

Nonces are used as a security related protection to prevent attacks and mistakes. You can use Nonces to enhance your WordPress form. here is an example,

<form ...>
<?php
if ( function_exists('wp_nonce_field') )
	wp_nonce_field('hungred-post-form'+$uniqueobj);
?>
</form>

We are just using the method wp_nonce_field in WordPress to create a nonce field on the above example. Next, we will need to validate whether the nonce is valid by using the following method after the user have submitted the form. This should be placed before any action began.

<?php check_admin_referer('hungred-post-form'+$uniqueobj); ?>

Pretty easy for enhancing form in your WordPress plugin. But this is not all you can do. There is also Link nonce protection where link is attached with a Nonces. You can read more about Nonces from the below link.

They have better explanation and example to understand Nonce.

Speed up your WordPress plugin development with Ubiquity Firefox add-on

ubiquity

Ubiquity is a Mozilla Firefox add-on, developed by Mozilla Labs. It allows you to search WordPress and PHP (PHP) documentation in an instant. Safe time on Google, more time on development 😀

The Predefined Prototype Object In JavaScript

Most of us learn JavaScript from tutorial website such as w3schools or tizag.com. However, these tutorial site only covered the most fundamental of JavaScript. Many hidden features of JavaScript are usual removed to simplify the tutorial. Although basic does bring us a long way, we still need to read more of these features eventually and improve our coding. In this article, i will cover the predefined prototype object in JavaScript. We will discuss everything we need to know about prototype object and the application in the real world.

The Prototype Object

The prototype object was introduced on JavaScript 1.1 onwards to simplify the process of adding or extending custom properties and methods to ALL instances of an object. In other word, prototype object is used to add or extend object properties or methods so every other object will also have such properties/methods. Let me show you an example. Below listed a few way to extend an object properties.

//adding a custom property to a prebuilt object
var imgObj =new Image();
imgObj.defaultHeight= "150px";

//adding a custom property to the custom object "Shape"
function Shape(){
}
var rectangle =new Shape()
rectangle.defaultColor = 'blue';

From the above example, we are able to extend properties of each object easily. However, if i create a new instances of the same object, the properties will be lost!

var newImg =new Image();
alert(newImg.defaultHeight); //return undefined 'defaultHeight';

var newRec =new Shape()
alert(newRec.defaultColor); //return undefined 'defaultColor';

This is when prototype object comes in. Prototype object is able to add the properties above and extend to other new instances object as well. Hence, the following will allowed all new instances created to contain the properties or methods attached by any previous object. We just have to add the keyword prototype between the object and name of the properties/method to use the prototype object. Using the same example above,

//adding a custom property to a prebuilt object
function check_height(){
 return typeof this.defaultHeight != 'undefined'?true:false;
}
var imgObj =new Image();
imgObj.prototype.defaultHeight= "150px";
imgObj.prototype.hasHeight= check_height;

//adding a custom property to the custom object "Shape"
function Shape(){
}
function color_checker(){
 return typeof this.defaultColor != 'undefined'?true:false;
}
var rectangle =new Shape()
rectangle.prototype.defaultColor = 'blue';
rectangle.prototype.hasColor = color_checker;

var newShape =new Shape()
alert(newShape.defaultColor) // blue
alert(newShape.hasHeight) // true

var newImg =new Image()
alert(newImg.defaultHeight) // 150px
alert(newImg.hasColor()) // true

Now every new instances of Image and Shape will have the properties and methods defined previously by the variables rectangle and imgObj.

Prototype Object Restriction

Prototype object can add or extend properties or methods to any custom object but for predefined object, only those that are created with the new keyword are allowed to use the prototype object in JavaScript. The following list some of these predefined object.

  • The date object
  • The string object
  • The Array object
  • The image object

Prototype Object is an Array

In case you haven't notice, prototype object is actually an array. From all of the above example, we are doing the following declaration to create new properties or method

//declare a function
obj.prototype.name = function(){};
//declare a property
obj.prototype.name = variables;

Notice that we are actually associating a name with a variable or function into the prototype object. Hence, we can also declare prototype with the same way as declaring an array.

obj.prototype ={
name: variables,
name: function(){}
}

The above two methods are similar and can be declare either way. Since both ways are similar, performance wise shouldn't make any big differences.

Priority Between Prototype And Own Property

What if we have both property? If the object itself already has a prototype property and if we redeclare the exact same property again without the keyword prototype, JavaScript will take which property? The answer is own property. In JavaScript, the own property takes precedence over the prototype's. Consider the following example,

function Rectangle(w,h){
	this.area = w*h;
}
var obj = new Rectangle(2,2); //area is 4;
obj.prototype.area = 200; // now we have own and prototype 'area'
alert(obj.area); // 4 will appear instead of 200; Hence, own property takes priority first.

What happened if we delete the property?

delete obj.area
alert(obj.area); // 200 appeared! 

Prototype property will take over again. Hence, we can use the Own property to overwrite prototype property defined in the object.

Identify Own and Prototype Properties

How do we identify whether the given object properties are from own or prototype? In JavaScript, there is a method hasOwnProperty which can be used to identify whether a given property is from own or prototype. Let's look at the following example,

function Rectangle(w,h){
	this.area = w*h;
	this.parameter = w+h;
}
obj.prototype.height = 5; 
obj.prototype.weight = 6; 

var obj = new Rectangle(2,2); 
obj.hasOwnProperty('area');// return true;
obj.hasOwnProperty('parameter');// return true;
obj.hasOwnProperty('height');// return false;
obj.hasOwnProperty('weight');// return false;

Inheritance Using Prototype Object

In the real world, prototype object is usually used as inheritance during OOP (Object Oriented Principle) with JavaScript. In JavaScript, we are not looking at classes inheriting other classes but object inheriting other object since everything in JavaScript is Object. Once we understand this, it will be easier for us to show inheritance example with prototype object.

function Shape(){
}
function color_checker(){
 return typeof this.defaultColor != 'undefined'?true:false;
}
function getArea(){
return this.area;
}

Shape.prototype.defaultColor = 'blue';
Shape.prototype.hasColor = color_checker;
Shape.prototype.getArea = getArea;

function Rectangle(w,h)
{
	this.area = w*h;
}

function Rectangle_getArea()
{
    alert( 'Rectangle area is = '+this.area );
}
Rectangle.prototype = new Shape();
Rectangle.prototype.constructor = Rectangle;
Rectangle.prototype.getArea  = Rectangle_getArea; 

Using the custom object 'Shape' example above, i extend it so that 'Rectangle' will inherit all method and properties of 'Shape'. Inherit can be done through this sentence

Rectangle.prototype = new Shape();

'Rectangle' prototypes are assigned to the prototype of the 'Shape' through an object instance thereby "inheriting" the methods assigned to the prototype array of 'Shape'. After 'Rectangle' has inherit 'Shape', it overwrites the getArea method of 'Shape' through this statement.

Rectangle.prototype. getArea  = Rectangle_getArea; 

Inheritance using prototype object can reduce a lot of unnecessary coding and make your overall code run faster. The constructor on the above code is to overwrite the way Rectangle object is being instantaneous since the Rectangle prototype was overwritten by Shape prototype on the previous statement. Hence, to create a Rectangle object, the constructor for it will be as follow

function Rectangle(w,h)

We can use the above code as follow

var recObj = new Rectangle(20, 20);
rec.getArea(); //return 'Rectangle area is = 400'
rec.hasColor(); // return true;
rec.defaultColor;//return blue;

Check Prototype Inheritance

We can check whether a particular object is another prototype object by using the function isPrototypeOf. In other word, we can check whether a particular object inherit another object properties and methods. Using the previous inheritance explanation, we can check whether Shape is inherited into Rectangle object.

var rec = new Rectangle(5,5);
Shape.isPrototypeOf(rec);// return true;

This shows that Shape is a prototype of rec object. I think the method name said it all.

Tutorial: How to check whether a particular field exist on SQL table

I was doing some plugin enhancement when i needed to find out whether a field exist on the SQL table. Hence, i went Google and search for a good answer. I found two method to solve this problem but i prefer the one using pure SQL query. Hence, i decide to write them down for future use and also make it as a discussion regarding the pros and cons.

PHP Solution

The first solution i found was a method that used PHP and perform a calculation in order to conclude whether the field exist on the SQL table. Here's the snippets:

$fields = mysql_list_fields("databasename", "tablename");
$columns = mysql_num_fields($fields);
for ($i = 0; $i < $columns; $i++) {
    $field_array[] = mysql_field_name($fields, $i);
}
       
if (!in_array(‘list_id’, $field_array)) {
    mysql_query("ALTER TABLE `tablename` ADD `fieldname` INT(11) NOT NULL DEFAULT ‘1′;");
}

From the above snippet provided by Antonie Potgieter, the concept is good but it is still not optimum. A better alternative can be written as follow.

$result = mysql_query("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME ='tablename'");
$field_array = mysql_fetch_array($result);      
if (!in_array(‘list_id’, $field_array)) {
    mysql_query("ALTER TABLE `tablename` ADD `fieldname` INT(11) NOT NULL DEFAULT ‘1′;");
}

The code above have not been tested but the query, yes. Nonetheless, a loop can be removed anyhow by retrieving the set of array resist within the return value of mysql_fetch_array. The objective is to avoid loop and shorten the code as much as possible.

SQL Solution

I found a better alternative on DZone! I find that it is a much effective way to check the existence of a field. Here's the snippets:

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = ‘TEST’ AND COLUMN_NAME = ‘TEST_DATE’)
BEGIN
   ALTER TABLE TEST ADD TEST_DATE DATETIME
END

Since we have taken away all the necessary code, only a direct query is needed in this case.

Summary

Which method would you prefer in this case? Why? Any better method than the one present above? I bet these two are the best we have for checking up a field existence unless you are talking about other languages than PHP. I would love to know your thoughts 🙂