Category: Programming

PHP: A new kind of template engine

By blobaugh, February 21, 2010 12:09 am

I have been developing a custom Content Management System (CMS) for Blam Designs and though there are several really good templating engines out there for PHP (such as Smarty) I find them usually bulky. Then there is also the need to learn the templating language as well. Though the templating languages are simple, it is one more thing for a designer to worry about knowing that pulls them away from their designs.

With that in mind I set out to find or create a new kind of templating system that works in a way similar to the JavaScript DOM, but works with PHP. The beauty of this sort of a system lies in the fact that a designer can create a layout with all the filler content and dummy text they can imagine and they do not have to remove any of it, or add any special template tags before uploading their snazzy layout to a web server. Simply add a normal HTML id attribute to whatever it is the designer wants to place content in and the template engine will automagically take care of the rest for you!

For example:

 
<div id="content">Lorem ipsum solet dolomar</div>
 

Might be replaced with:

 
<div id="content">Hello World! I am some content</div>
 

Sounds pretty cool doesn't it? I wound up creating my own PHP classes to handle this for me. I ran across a library called PHP Simple HTML DOM Parser (SHDP) which does all the heavy lifting for me. My class it basically a wrapper object that makes it easier to deal with the SHDP, in addition to providing some extra functionality. Using my class it is possible to replace the entire contents of a tag (such as <title>), replace by the element id (such as <span id="myid">), or through the use of "special" tags. The "special" tags I call special because they do not fit inside the rest of the template paradigm. A special tag works in much the same manner as a tag from a normal template system like Smarty would. Tags are created using curly braces and look similar to {{my_tag}}. I needed to keep these in in the case that some special piece of code needs to be dynamically added to the template, but is not an HTML tag or id. This happens with things such as file paths.

Though I may not be fully done tweaking the new template engine it is fully operational and I am going to provide a few code example and a download of my class with SHDP packaged with it. Eventually I would like to setup a new site dedicated to this template engine, and would like to fully re-write SHDP so that the template system is one complete unit, not relying on any external libraries.

HTML File:

 
<html>
<head>
	<title>Template Engine Demo</title>
	<meta name="author" content="Ben Lobaugh">
</head>
<body>
<div id="contents" style="border: 1px dashed #000000">
This is inside the contents div
</div>
<div id="d2" style="margin-top: 20px; border: 1px solid #000000">
This is inside the d2 div
</div>
 
{{special_tag}}
</body>
</html>
 

Replace the contents of a tag:

$t->setTag('title', 'This is a new title');

Replace the contents of an element by id:

$t->setById('contents', 'Hello World! I am new content');

Append the contents of an element by id:

$t->setById('d2', ' I am appended content', 'a');

Set a special tag

$t->setSpecialTag('special_tag', 'I am special!');

Final Output:

 
<html>
<head>
	<title>This is a new title</title>
	<meta name="author" content="Ben Lobaugh">
</head>
<body>
<div id="contents" style="border: 1px dashed #000000">Hello World! I am new content</div>
<div id="d2" style="margin-top: 20px; border: 1px solid #000000">
This is inside the d2 div
 I am appended content</div>
 
I am special!
</body>
</html>
 

Please be sure to template_engine_demo the template engine to see all the working examples.

If you use this template engine on your site please drop me a comment below.

Enjoy :D

C++: Virtual Token Ring Network

By blobaugh, February 2, 2010 10:06 pm

My networking professor handed out a group project to build a virtual token ring network and I thought I would share my findings here. Before you say anything, I know it is not a true token ring network, but it sorta acts like one which was more the goal of the project.

My group partner and I went through several different models, which included; building a virtual DHCP server and virtual cables, telling the program at run time who it's neighbor was, sending out a broadcast and having the virtual nodes organize themselves into a network, and a few others. We finally settled on pulling out a switch and creating a network of static IPs that we controlled. The program attempts to send to the next IP number from itself and if it cannot find it the token is sent to the first node. An unintended side effect is that we have the ability to add and remove machines at the highest IP number without breaking the ring. The requirement was only that it worked with three machines.

This code is not the cleanest, nor is it in any way awesome, and there are probably a ton of things I can take out of it to make it better, but it runs beautifully on the Dell Mini 10s running Ubuntu that I tested it on with a 5 port Netgear switch. Just make sure your network is in the range 192.168.0.1 and the machines go in sequential order (e.g. 192.168.0.1, 192.168.0.2, 192.168.0.3)

 
/*
 * Virtual Token Ring Network
 *
 * Networking II
 * Spring 2009-2010
 * Prof: Xueyi Wang
 * Group: Ben Lobaugh, Jake Bodenstab
 *
 * Project Description: Sorta creates a virtual token
 *      ring network simulation
 */
 
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string>
#include <string.h>
#include <strings.h>
#include <sstream>
#include <iostream>
 
using namespace std;
 
// Global Constants and Variables
int PORT = 55555, node, s_sockfd , s_clilen, s_n;
struct message{
        int sender;
        int receiver;
        string message;
};
struct token{
        int type; // 1 = empty token, 2 = token with data
        int valid;
        message msg;
        int checksum;
        int turn;
};
struct sockaddr_in s_serv_addr, s_cli_addr;
 
// Function Definitions
void getToken(char* token);
void sendToken(char* token);
bool messageExists();
void createServerSocket();
void error(string msg);
 
int main(int argc, char** argv) {
        char* token;
		string start_token;
 
		node = atoi(argv[1]);
		cout << "Node: " << node << endl << endl;
 
		createServerSocket();
 
		if(node == 1) {
			cout << "Start token? (y/n): ";
			cin >> start_token;
 
			if(start_token.compare("y") == 0) {
				cout << "\nInitializing Token\n";
				sendToken(token);
			}
		}
 
		cout << "**** Ctrl-C Terminates **** \n\n";
 
		while(1) {
			getToken(token);
 
			if(token[0] == 2) {
				// Token Contains a message
				if(token[2] == node) {
					// Message is from us. Erase it and change token type to 1
					token[2] = -1;
					token [3] = -1;
					token[4] = -1;
					token[0] = 1;
				} else if(token[3] == node) {
					// Message in token is for us. Display it
					cout << "--------------\n";
					cout << "From: " << token[2] << endl;
					//cout << token.msg.message << endl;
				}
			} else if(token[0] == 1) {
				// Token does not contain a message
				if(messageExists()) {
					// There is a message to send. Load message into token and change type
 
					 // Open file ./message.tok
					 // Read first line as the receiver
					 // Rest of file is message 
 
					token[0]  = 2;
				}
			} else {
				// This token is a type we do not know about
				// Don't worry about this token, just forward it
			}
			sleep(2);
			// Send token along it's merry way
			sendToken(token);
		}
 
       return (EXIT_SUCCESS);
}
 
void getToken(char* token) {
	int newsockfd;
	/*
	 * Create a server socket on PORT
	 * Listen on socket until message is received
	 * If message is of type token load it into token
	 * Close socket
	 * Return filled token
	 */
     listen(s_sockfd,5);
     s_clilen = sizeof(s_cli_addr);
     newsockfd = accept(s_sockfd,
                 (struct sockaddr *) &s_cli_addr,
                 (socklen_t*) &s_clilen);
     if (newsockfd < 0)
          error("ERROR on accept");
     bzero(token,256);
     s_n = read(newsockfd,token,255);
     if (s_n < 0) error("ERROR reading from socket");
 
	cout << "I've got the token\n";
}
 
void createServerSocket() {
 
	s_sockfd = socket(AF_INET, SOCK_STREAM, 0);
     if (s_sockfd < 0)
        error("ERROR opening socket");
 
	int on = 1;
	  if ( setsockopt ( s_sockfd, SOL_SOCKET, SO_REUSEADDR, ( const char* ) &on, sizeof ( on ) ) == -1 )
	    error("ERROR setting socket options");
 
     bzero((char *) &s_serv_addr, sizeof(s_serv_addr));
     s_serv_addr.sin_family = AF_INET;
     s_serv_addr.sin_addr.s_addr = INADDR_ANY;
     s_serv_addr.sin_port = htons(PORT);
 
     if (bind(s_sockfd, (struct sockaddr *) &s_serv_addr, sizeof(s_serv_addr)) < 0)
              error("ERROR on binding");
}
 
void sendToken(char* token) {
	int to;
	string ip = "192.168.0.";
 
	// Start Socket Vars
	int sockfd, n;
    struct sockaddr_in serv_addr;
    struct hostent *server;
	// End Socket Vars
 
	// Find the next node to send to
	to = node + 1;
	std::ostringstream sin;
	sin << to;
	std::string val = sin.str();
	ip.append(val);
 
	/*
	 * Create socket connection to next node
	 * Send token
	 * Close socket
	 */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
        error("ERROR opening socket");
 
	try {
	    server = gethostbyname(ip.c_str());
	    if (server == NULL) {
	        error("ERROR, no such host\n");
	    }
 
	    bzero((char *) &serv_addr, sizeof(serv_addr));
	    serv_addr.sin_family = AF_INET;
	    bcopy((char *)server->h_addr,
	         (char *)&serv_addr.sin_addr.s_addr,
	         server->h_length);
	    serv_addr.sin_port = htons(PORT);
 
	    if (connect(sockfd, (struct sockaddr*) &serv_addr,sizeof(serv_addr)) < 0)
			throw 1;//("ERROR connecting");
 
		cout << "Token Sent To: 192.168.0." << to << endl << endl;
	} catch (int i)  {
		cout << "Could not contact " << ip << " sending to 192.168.0.1\n\n";
		server = gethostbyname("192.168.0.1");
	    if (server == NULL) {
	        error("ERROR, no such host\n");
	    }
 
	    bzero((char *) &serv_addr, sizeof(serv_addr));
	    serv_addr.sin_family = AF_INET;
	    bcopy((char *)server->h_addr,
	         (char *)&serv_addr.sin_addr.s_addr,
	         server->h_length);
	    serv_addr.sin_port = htons(PORT);
 
	    if (connect(sockfd, (struct sockaddr*) &serv_addr,sizeof(serv_addr)) < 0)
	        error("ERROR connecting");
 
	}
 
	bzero(token,256);
    n = write(sockfd,token,strlen(token));
    if (n < 0)
         error("ERROR writing to socket");
 
	close(sockfd);
	unlink(ip.c_str());
}
 
bool messageExists() {
	bool ret = false;
	return ret;
}
 
void error(string msg) {
    perror(msg.c_str());
    exit(0);
}
 

jQuery: Oh How I Love Thee

By blobaugh, November 16, 2009 5:03 pm

I started using jQuery last week and I am finding it to be a great library so far. It is very easy to interact with elements on the page in fun and creative ways.

As a sample, I have been working with the Northwest Nazarene University web team and they wanted to develop a simple wizard they can put on any page that will help prospective students find the degree they are interested in. I decided to tackle that task. At first I was looking at slide show sample, then one of the other developers showed me the beauty of .load(), which allows me to load into any arbitrary element the contents of any file or web address. After playing with .load() and the event handlers for an hour I figured out a way to implement what they wanted. It took me maybe 4 hours going from ground zero of no knowledge on the subject to implementing a working system complete with calls to a backend PHP file that gets the contents for the wizard from the database. jQuery is really neat, I highly encourage other web developers to check it out. A working sample may be found here or on NNU's website.

Here is the jQuery code I used. Try not to be too critical, I am positive there has to be a better way of doing this. I still am learning the vast amount of options available to me in jQuery.

 
<script type="text/javascript">
 
$(document).ready(function() {
	$('#programs').load('programs.php', {}, function() { // Load the degree options
           $('.choice').bind('click', function() { // Load the school in that degree
	        $('.choice').bind('click', function() { // Load the list of degrees
						$('#programs').load($(this).attr('href'), {}, function () {
							$('.choice').bind('click', function() {
								$('#programs').load($(this).attr('href'), {}, function () { // Load a degree
					                        });
							});
					});
				});			
		 });
	});
 });
</script>
 

PHP: Fatal error: Trying to clone an uncloneable object of class mysqli

comments Comments Off
By blobaugh, July 18, 2009 11:20 am

I was working on a report for a client when I discovered this rather odd error: Fatal error: Trying to clone an uncloneable object of class mysqli. I am still not sure what caused this error, but there does seem to be a quick fix for it.

ini_set('zend.ze1_compatibility_mode', 0);

Here is what the PHP manual has to say about zend.ze1_compatibility_mode:

Name  - zend.ze1_compatibility_mode
Default - "0"
Changeable -  	PHP_INI_ALL
Changelog -  	Available since PHP 5.0.0. Removed in PHP 5.3.0

Enable compatibility mode with Zend Engine 1 (PHP 4). It affects the cloning, casting (objects with no properties cast to
FALSE or 0), and comparing of objects. In this mode, objects are passed by value instead of reference by default.

I hope that helps someone out there.

PHP: __call Magic

By blobaugh, July 10, 2009 8:24 am

Lastnight as I was researching how to build a plugin system for a cms I am working on I ran across several implementations using the __call method. I had not used it before myself, but after doing a little googling I devised a test. It really is quite simple and can be a powerhouse in your applications.

First, what is this __call thing even for? Remember those classes you built? Then remember how you were doing something else and forgot you had not yet created a method in the class to handle it and your application blew up? That is where __call comes to the rescue! Whenever a method in your class is called that does not exist PHP automagically sends the request to the __call() method. If __call exists then PHP assumes it knows how to take care of the missing method. If it does not exist is when things get hairy, fatal errors get thrown, the application blows up, and you loose your job cause one of the company execs got a phone call while in Hawaii. Oops, consider using __call in any of your important objects :D

Let's start with an example of the calling code:

$Car = new Car();
$Car-&gt;ZoomZoom(120);
$Car-&gt;Fly('Super Jets');

I am using a Car for this example. Most cars can go pretty fast, but currently there are no cars that can fly. Normally calling Fly() would cause a fatal error right? Not this time.

Take a look at the Car class:

class Car {
 
        // Constructor
        public function __construct() {
                echo "Your car has arrived";
        }
 
        // Let's roll! How fast?
        public function ZoomZoom($Speed) {
                echo "And we're off at an amazing $Speed! Hope you're buckled!";
        }
 
        /*
         * This is a magic function.
         * This function gets called when a method that does
         * not exist in this class is called. Once inside this
         * method you are free to deal with it however you
         * would like
         */
        public function __call($Function, $Args) {
                $Args = implode(', ', $Args);
                echo "I can't $Function you idiot! Especially with $Args! Hoser";
        }
}

Note the two arguments. They do not have to be called that, but it will help you remember what they are in 6 months.

Here is the output:

Your car has arrived
And we're off at an amazing 120! Hope you're buckled!
I can't Fly you idiot! Especially with Super Jets! Hoser

Pretty simple eh? I hope you realize the potentially huge impact the use of this magic method could have on your application. Heck, if nothing else use it with a logger to log errors.

Cheers,

MySQL: Create a Unique Composite Key

By blobaugh, June 3, 2009 11:47 am

I have a lookup table where I am using a composite key which must be unique. I was not sure if MySQL was able to do this or not, but I very quickly found out. It is quite a simple operation actually. I already had a table in existence so I simply altered it.

 
ALTER TABLE `TableName` ADD UNIQUE KEY (KeyOne, KeyTwo, ...);
 

There ya go. Use it, have fun with it. Share it. Try not to eat it. Your boss will not appreciate having to purchase a new monitor.

Crazy NULLs in MySQL

By blobaugh, May 27, 2009 2:40 pm

The topic of MySQL and NULLs came up in my IRC room today. It turns out that MySQL tends to handle NULLs in a rather wonky way at times. Personally, I usually do not like allowing NULLs, and the only time they are ever present would be in a RIGHT or LEFT JOIN that had missing information. There are many people out there, however, that do use NULLs, and love them. I am not knocking the use of NULLs in any way, but before you sit down and use NULLs again be sure you take some time and study this bit of trivia one of the guys in the IRC showed us.

 mysql&gt; SELECT if(NULL=NULL,"yep","nope");
+----------------------------+
 | if(NULL=NULL,"yep","nope") |
 +----------------------------+
| nope                       |
 +----------------------------+

If you think this is strange behavior you are right. According to the MySQL manual on control flow the correct response should be 'yep'.

Automatically Resize an IFrame From It’s Content

By blobaugh, May 23, 2009 7:47 am

I recently had a situation with a client where I needed to use an iframe to pull content from a bulletin board into their main site template. Setting up the iframe was the easy part, then I noticed that the content would auto size the width, but it would not autosize the height. As I wanted this iframe to look like it was part of the page, not an iframe, I started googling. There are lots of "solutions" out there to make the iframe automatically resize the height, but I did not find one that actually worked how I wanted it. The closest I came to finding what I was looking for was creating a div around the iframe, and with javascript get the content of the iframe and replace the content of the div. This actually works out really well, until you clicked a link inside the iframe and it broke out of the iframe. So I did some looking at javascript methods and I came up with a pretty good solution myself. You can use this to automatically resize your height, and still use the links inside the iframe. It looks like the iframe is part of your actual page, and nobody is the wiser.

 
function resizeIFrame() {
     var myIFrame = document.getElementById('YourIframeName');
     myIFrame.height = myIFrame.contentWindow.document.body.scrollHeight + 10;
}
 

Be sure to change the name of the iframe you are trying to get. Here is an example of the HTML I used.

 
<iframe onload="resizeIFrame();" id="YourIframeName" src="content_for_your_iframe" frameborder="no" width="100%" scrolling="no">
 

Be sure to set the id and content of your iframe and you are set!

PHP: Email Validation

By blobaugh, May 15, 2009 3:54 pm

There are an overwhelming number of regex sequences out there to validate an email address against, and frankly I get tired of running through them all trying to find one that fits my situation. I went looking for one that most closely follows the IETF rules and lo and behold I find a document describing exactly what I was after. It is a great article that I encourage all web developers to read regardless of if you are a PHP developer or not. The article steps through some of the most common techiques and shows how they are flawed, then describes in detail how to build a perfect email validation function in PHP. You can find it on the Linux Journal website.

Just in case their site should ever go down I am providing the entire function for reference here:

/**
 * Validate an email address.
 * Provide email address (raw input)
 * Returns true if the email address has the email
 * address format and the domain exists.
 *
 * From: http://www.linuxjournal.com/article/9585
 *
 * @param String $email
 * @return Boolean
*/
function validateEmail($email)
{
   $isValid = true;
   $atIndex = strrpos($email, "@");
   if (is_bool($atIndex) &amp;&amp; !$atIndex)
   {
      $isValid = false;
   }
   else
   {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if ($localLen &lt; 1 || $localLen &gt; 64)
      {
         // local part length exceeded
         $isValid = false;
      }
      else if ($domainLen &lt; 1 || $domainLen &gt; 255)
      {
         // domain part length exceeded
         $isValid = false;
      }
      else if ($local[0] == '.' || $local[$localLen-1] == '.')
      {
         // local part starts or ends with '.'
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $local))
      {
         // local part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
      {
         // character not valid in domain part
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $domain))
      {
         // domain part has two consecutive dots
         $isValid = false;
      }
      else if
(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&amp;`_=\\/$\'*+?^{}|~.-])+$/',
                 str_replace("\\\\","",$local)))
      {
         // character not valid in local part unless
         // local part is quoted
         if (!preg_match('/^"(\\\\"|[^"])+"$/',
             str_replace("\\\\","",$local)))
         {
            $isValid = false;
         }
      }
      // **** NOTE: If you are getting failures you may need to comment out this section
      if ($isValid &amp;&amp; !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
      {
         // domain not found in DNS
         $isValid = false;
      }
   }
   return $isValid;
}

Linux Journal Article

PHP: Random Password Generator

By blobaugh, May 15, 2009 2:59 pm

I find myself wanting random passwords all the time, and on a web project I needed to generate passwords automatically to send out to users. Here is the function I use to create random passwords automatically.

/**
 * Creates a random password
 *
 * @param Integer $length - Default: 9
 * @param Integer $strength - Default: 10
 * @return String
 **/
function generatePassword($length=9, $strength=10) {
	$vowels = 'aeuy';
	$consonants = 'bdghjmnpqrstvz';
	if ($strength &amp; 1) {
		$consonants .= 'BDGHJLMNPQRSTVWXZ';
	}
	if ($strength &amp; 2) {
		$vowels .= "AEUY";
	}
	if ($strength &amp; 4) {
		$consonants .= '23456789';
	}
	if ($strength &amp; 8 ) {
		$consonants .= '@#$%';
	}
 
	$password = '';
	$alt = time() % 2;
	for ($i = 0; $i &lt; $length; $i++) {
		if ($alt == 1) {
			$password .= $consonants[(rand() % strlen($consonants))];
			$alt = 0;
		} else {
			$password .= $vowels[(rand() % strlen($vowels))];
			$alt = 1;
		}
	}
	return $password;
}

Theme by Blam Designs
Based on Themocracy