So, lately I have been playing around with the Go language, and just as a project to keep myself busy, I set out to create a CLI CSS minifier. Very soon, though, I began to realize that, while so far, Go seems to be a fairly nice language to use, the native regular expressions in Go are pretty weak. So, what started as a small project just to get used to the language has now become an attempt at porting PCRE to Go. The work has been slow, seeing as I am pretty much starting from scratch, but so far, its turning out nicely. It is not even close to a viable stable release at the moment, but just in case anyone is interested, the source code is all on GitHub: http://github.com/kbjr/gopcre
Type Hinting and Method Overloading in JavaScript
My latest piece of JavaScript, F.js, creates a simple, intuitive way to use both type hinting and method overloading on your JavaScript functions. Here are some examples:
(function(window, undefined) { /** * Create a function that repeats a string * * @access public * @param String the string to repeat * @param Number the number of times to repeat * @return String */ var strRepeat = F(String, Number, function(str, count) { var newStr = ''; for (var i = 0; i < count; i++) { newStr += str; } return newStr; }); /** * Now, overload it to allow the parameters * in the other order * * @access public * @param Number the number of times to repeat * @param String the string to repeat * @return String */ strRepeat.overload(Number, String, function(count, str) { return strRepeat(str, count); }); // These are valid strRepeat('Hello World! ', 4); strRepeat(4, 'Hello World! '); // These will throw TypeError's strRepeat(3, 4); strRepeat([ 'Hi', 'There' ]); }(window));
CodeIgniter OpenID Library
This is an extension of the library I wrote about a little earlier. I am still in the process of writing all of the documentation, but the code is finished and stable enough that I am calling this a beta release. The source code is all on GitHub and its all packaged up and ready to download. Here is an example of just how easy it is to use:
<?php class OpenID_auth extends Controller { function OpenID_auth() { parent::Controller(); $this->load->library('EasyOpenID'); } function try_auth() { $this->easyopenid ->provider('google') ->required('email') ->return_to('openid_auth/finish_auth') ->make_request(); } function finish_auth() { $result = $this->easyopenid ->fetch_response() ->result(); } } /* End of file openid_auth.php */ /* Location: ./system/application/controllers/openid_auth.php */
There is a more complete example in the GitHub repo’s readme file.
EasyOpenID – OpenID Authentication for CodeIgniter
A more recent post on this topic can be found at http://blog.kbjrweb.com/?p=99
My latest work is EasyOpenID, an OpenID library for CodeIgniter. It is built on top of Janrain’s php-openid library. The database storage option has not yet been tested; however, the file store system does work and the library can be used. For more information, check out the project page on my website. If you would like to contribute in some way, the source code is on GitHub.
And here’s an example:
<?php class Yours extends Controller { function Yours() { parent::Controller(); // load the OpenID library $this->load->library('openid'); } function index() { // get the link data $data['openid_links'] = $this->openid->build_auth( 'yours/try_auth', array('openid', 'google', 'yahoo'), 'yours/load_icon'); // load the sign in page $this->load->view('signin', $data); } function try_auth() { // figure out which provider we're loading $which = $this->uri->segment(3); switch ($which) { // handle standard OpenID case 'openid': if (array_key_exists('openid', $_POST)) { $result = $this->openid->try_auth($_POST['openid'], 'yours/finish_auth'); } else { $data['message'] = 'No Provider Given'; } break; // handle Google Accounts case 'google': $result = $this->openid->try_auth_google('yours/finish_auth'); break; // handle Yahoo! case 'yahoo': $result = $this->openid->try_auth_yahoo('yours/finish_auth'); break; // handle errors default: $data['message'] = 'Invalid Provider'; break; } // handle errors if (isset($result) && is_int($result)) { $data['message'] = $this->openid->last_error(); } $this->load->view('signin', $data); } function finish_auth() { // finish authentication $result = $this->openid->finish_auth(); // check for errors if (is_int($result)) { $data['error'] = $this->openid->last_error(); } else { $data['user_data'] = $result; } // load the next page $this->load->view('next/page', $data); } // create the icon loader function load_icon() { $this->openid->icon_loader(); } } /* End of file */
Git.php – A PHP git repository interface library
My latest work, Git.php has turned out really nice. The release candidate is now up on GitHub and the documentation is on the project home page. I’m going to give a brief few examples below just to whet your appetites.
<?php require_once "Git.php"; // open a repository $repo = Git::open('/path/to/repo'); // or, new GitRepo(...); // `git add *` $repo->add('*'); // `git commit -av -m 'added files'` $repo->commit('added files'); // add a new remote $repo->run('remote add origin git@github.com:kbjr/repo-name'); // push out $repo->run('push origin master'); ?>
Oh, and did I mention that there’s a CodeIgniter version?
<?php $this->load->library('git'); // open a repository $repo = $this->git->open('/path/to/repo'); // `git add *` $repo->add('*'); // `git commit -av -m 'added files'` $repo->commit('added files'); // add a new remote $repo->run('remote add origin git@github.com:kbjr/repo-name'); // push out $repo->run('push origin master'); ?>
Setting the default value of a text field
Making a text field have a default value isn’t all that difficult
<input type="text" value="Some Text" />Not that amazing… but, have you ever wondered how people do that cool effect where the text disappears when you click into the box? And it comes back if you leave the field empty? And maybe it looks different than the normal text, maybe a lighter color? There is definitely more than one way of doing this, but this is the method I came up with and I like it. It comes in the form of a jQuery plugin (sorry for non-jQuery users, I was lazy :p). The source code can be found on GitHub at http://github.com/kbjr/Default
Here is a basic run through of how to use it. The plugin adds a method to jQuery’s $() object. So, say you wanted to set the default value of every text field on the page to “bob”, you could do this like:
$('*').defaultText('Bob', { color: '#888' }); // or, use the '!' option to make them default to their own title attribute $('*').defaultText('!');
Just include the textfields.js file at some point after jQuery and then you’re good.
<html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="textfields.js"></script> </head> <body> <!-- Will default to "Hi Bob" --> <input type="text" id="one" /> <!-- Will default to "Some Text" in '#888' grey --> <input type="text" id="two" title="Some Text" /> <script type="text/javascript"> $('#one').defaultText('Hi Bob'); $('#two').defaultText('!', { color: '#888' }); </script> </body> </html>
Verifying Users Using Some Simple PHP
CAPTCHAs fill a very important role on the internet; They make sure that your users are human, and not computers. For many high-traffic sites, this means using more and more complicated tests due to the more and more sophisticated means of breaking them. However, if you just have a small website, you may not need quite this much power; You might only need something as simple as a basic math problem such as “what is three plus four?”. But if you always use the same question, people will get through that easily enough, so we need to generate a new question each time. That is what I am going to explain in this post.
First, let us start off our PHP file.
<?php class Verifier { /* * Private Properties */ // operators available to the class private static $operators = array( array('plus', '+'), array('minus', '-'), array('times', '*') ); // numbers available to the class private static $numbers = array('zero', 'one', 'two', 'three', 'four', 'five'); /* * Private Methods */ // return an operator from the list, selected by // either index, symbol, or name. private static function getOperator($op) { if (is_int($op)) return self::$operators[$op]; foreach (self::$operators as $operator) { if ($operator[0] == $op || $operator[1] == $op) { return $operator; } } return null; } // return a random operator from the list. private static function randOperator() { $rand = rand(1, count(self::$operators)) - 1; return self::$operators[$rand]; } // store all of the operator symbols in a passed variable. private static function getOperators(&$ops) { $ops = array(); foreach (self::$operators as $operator) { $ops[] = $operator[1]; } } } ?>
Alright, so now we have our verification class with an array of operators and an array of numbers, as well as some methods for accessing them. Now we need to create a method for using these to build a random (or at least pseudo-random) problem for our users to solve.
public static function make_equation() { // we will store the final equation in a session // variable so we can check it later session_start(); // generate our random elements $n1 = rand(0, count(self::$numbers) - 1); $n2 = rand(0, count(self::$numbers) - 1); $op = self::randOperator(); // build the equation in a PHP format and // store it for checking later $equation = $n1 . ' ' . $op[1] . ' ' . $n2; $_SESSION['FormVerify'] = $equation; // return the equation, but using the number // and operator names return self::$numbers[$n1] . ' ' . $op[0] . ' ' . self::$numbers[$n2]; }
So, now we can make equations, but we still need to check if they are correct.
private static function solveEquation($equation) { self::getOperators($ops); // use a regular expression to make sure the equation is // in the expected format to protect against the posiblity // of evaling "bad" code $equationRegex = '/([0-9]+)\s(\\' . implode('|\\', $ops) . ')\s([0-9]+)/'; preg_match($equationRegex, $equation, $match); $answer = false; // if the equation is good, calculate and return the answer if ($match[0]) eval('$answer='.$equation.';'); return $answer; } public static function check_equation($value) { // read the equation from the session variable session_start(); $eq = $_SESSION['FormVerify']; // check for a match and return a bool return (self::solveEquation($eq) == $value); }
So, there it is. A simple way to verify the humanity of your users. It should be noted that this is not fool-proof, but it should be enough for a simple site. Soon, I will make another post about how to do this using image recognition instead of a math problem, a more secure (and for your more math challenged users, easier) way of doing this. Here is the full code:
<?php class Verifier { /* * Private Properties */ // operators available to the class private static $operators = array( array('plus', '+'), array('minus', '-'), array('times', '*') ); // numbers available to the class private static $numbers = array('zero', 'one', 'two', 'three', 'four', 'five'); /* * Private Methods */ // return an operator from the list, selected by // either index, symbol, or name. private static function getOperator($op) { if (is_int($op)) return self::$operators[$op]; foreach (self::$operators as $operator) { if ($operator[0] == $op || $operator[1] == $op) { return $operator; } } return null; } // return a random operator from the list. private static function randOperator() { $rand = rand(1, count(self::$operators)) - 1; return self::$operators[$rand]; } // store all of the operator symbols in a passed variable. private static function getOperators(&$ops) { $ops = array(); foreach (self::$operators as $operator) { $ops[] = $operator[1]; } } private static function solveEquation($equation) { self::getOperators($ops); $equationRegex = '/([0-9]+)\s(\\' . implode('|\\', $ops) . ')\s([0-9]+)/'; preg_match($equationRegex, $equation, $match); $answer = false; if ($match[0]) eval('$answer='.$equation.';'); return $answer; } /* * Public Methods */ public static function make_equation() { session_start(); $n1 = rand(0, count(self::$numbers) - 1); $n2 = rand(0, count(self::$numbers) - 1); $op = self::randOperator(); $equation = $n1 . ' ' . $op[1] . ' ' . $n2; $_SESSION['FormVerify'] = $equation; return self::$numbers[$n1] . ' ' . $op[0] . ' ' . self::$numbers[$n2]; } public static function check_equation($value) { session_start(); $eq = $_SESSION['FormVerify']; return (self::solveEquation($eq) == $value); } } /* * USAGE */ // generate a test equation $equation = Verifier::make_equation(); // and check the answer is correct in your validation script if (Verifier::check_equation($_POST['user_response'])) { die('Hello, Human :)'); } else { die('Go Away, Evil Computer!'); } ?>
JR Network Toolbar / SubWindow Script
So, my latest work is a JavaScript script that creates a toolbar for page navigation and artificial sub-windows. its pretty awesome, so, as long as the demo is still up feel free to look at it.
http://jamiesrebellion.com/toolbar-model/jrnetToolbar.html
when the development is finished, i will put up a link to the actual product site.
Sammy – RESTful Evented JavaScript
I was sent a link earlier today to this website http://code.quirkey.com/sammy/index.html and I have to say that I am quite thoroughly impressed. Sammy is an awesome JavaScript library that works on top of jQuery to create event-based, single page navigation. It REALLY FREAKING AWESOME, so check it out (:


