Archive for the 'Programming' category

LAMP and SVN on Ubuntu 8.10

published on November 24, 2008.
Heads-up! You're reading an old post and the information in it is quite probably outdated.

This post is a rewrite of one of my older posts, Ubuntu as a dev machine, but this time I’ll explain also how to setup a basic SVN besides the LAMP.

Ubuntu 8.10 was released bout a month ago and today I wasn’t in the mood of doing any coding so I decided to try out the new Ubuntu. Once again, I’m installing it under VirtualBox (VB), cause it seems that they still haven’t fixed the bug related to the rtl8187 chipset. Oh well…

Be sure to use VB v2.x.x. (v2.0.6. is the latest now), cause it’s recognizing the correct screen resolution, not like VB v.1.6.4, whit which I had to configure manually the xorg.conf file…

Setting up LAMP

Here are the commands:

sudo apt-get install apache2
sudo apt-get install php5 libapache2-mod-php5
sudo /etc/init.d/apache2 restart
sudo apt-get install mysql-server
sudo apt-get install libapache2-mod-auth-mysql php5-mysql phpmyadmin
sudo /etc/init.d/apache2 restart
sudo a2enmod rewrite
sudo /etc/init.d/apache2 restart

If mod_rewrite doesn’t work, do the following:

sudo gvim /etc/apache2/sites-available/default

And change AllowOverride None to AllowOverride All.

Setting up SVN

I’m not gonna explain how SVN works or the terms, this is just how to set it up. If you are not familiar with versioning and Subversion, read this book: Version Control with Subversion. It’s free, available for download and contains probably everything you need to know about SVN. Be sure to learn the commands like commit, import, export, checkout, add, info, etc…

There are 2 ways for setting up SVN: as an Apache module or to use svnserve which is designed for SVN. As I already have Apache installed, the best solution is to use Apache for SVN. It’s using a module called mod_dav_svn.

The setup presented here is very basic, it has no authentication and probably is insecure, but it’s good for my needs on localhost.

The commands:

sudo apt-get install subversion
sudo a2enmod dav
sudo /etc/init.d/apache2 restart
sudo apt-get install libapache2-svn
sudo /etc/init.d/apache2 restart

Now we have all packages installed, only the configuration left.

First, I create a folder called svn under the var folder:

sudo mkdir /var/svn

Now I need to create a folder under the svn folder where all my repositories will be:

sudo svnadmin create /var/svn/repos

We use the svnadmin create command to create the repository; mkdir is not good for this.

Next, open up the httpd.conf file and add the following lines to it:

<Location /repos>
    DAV svn
    SVNPath /var/svn/repos
</Location>

I’ve seen people creating a new user and group for SVN. I think (I haven’t looked into it detailed) that’s for the authentication stuff. I did a much simpler thing: I added the ownership over /var/svn to www-data (Apache user):

sudo chown -R www-data /var/svn

This is probably a big security hole, but again: I use it only on localhost so I can live with that.

We are now ready to import a project into SVN, i.e. to add a project to the repository:

svn import -m "First import to SVN" /import/from/here/project file:///var/svn/repos/project/trunk

To start working on that project we need to checkout it:

svn checkout http://localhost/repos/project/trunk /var/www/project

Now the “project” is under SVN which should ease the development process. Since I’m using SVN I have no more backups of projects all over the place; if something goes wrong I know it’s under SVN and I can revert to any older working version of my project.

Cheers!

TickTweet WordPress plug-in

published on November 21, 2008.
Heads-up! You're reading an old post and the information in it is quite probably outdated.

Few weeks ago @imjustcreative mentioned on Twitter that he would like a WordPress plug-in that would scroll (tick) tweets where “soultweet” is mentioned. As I wanted to do a plug-in for some time, but never had any good ideas, I told him that I’ll take up the job. So I started to work on this in my free time.

Before I even started looking at anything, I decided that I want this plug-in to be fast, to work with smallest possible data to save bandwidth and to keep the number of calls towards Twitter low.

First I looked into the Twitter Search API documentation, to see how data can be retrieved from Twitter — in Atom or in JSON.

The first idea...

As a JSON document is smaller than an XML document, I decided to retrieve data in JSON. Of course, once retrieved it would be cached locally in a file for some time (5 minutes is my default).

I also wanted to avoid the possibility of the page waiting to retrieve the data from Twitter, so I figured that it would be the best to call it up with Ajax. That way, when the plug-in is called up, it sends an Ajax request to himself, the page continues loading normally and in the background runs the Ajax request.

The draft was there, I looked at the WordPress writing a plug-in page and in a week or so the first version of the plug-in was ready to go out.

I tested it locally on my Windows machine (a basic WAMP setup) and on my Ubuntu machine (a basic LAMP setup), on this server and on another one which has a ton of security limitations (server of my College). I was glad to see that it worked like a charm on all 4 servers. I put up a TickTweet page, and let it out in the wild through Twitter.

The retweet madness started immediately. @imjustcreative, @jonimueller and @bishop1073 downloaded it right away. Soon as they enabled the plug-in, the short and exciting life of TickTweet started to end. Errors, bugs… Joni’s server is running on PHP 4, and I had a few PHP 5 only functions. My bad. On Graham’s and Bishop’s server who knows what went wrong. Graham helped me a lot tracing down the bugs, a few of them were found and squashed, but that was not enough. So I decided to pull back TickTweet, rethink it and possibly rewrite it.

The second idea...

OK, this JSON — Ajax thingy won’t work. Back to the paper. I started looking at the WordPress core to see what functions and/or classes are available in it for this kind of task… Didn’t took me long to find the fetch_rss() function. Man I was happy to find that! It’s using the MagpieRSS and the Snoopy classes to retrieve the data. I figured, those are included in WP’s core, they’re gonna do the job just fine. So I’ve rewritten it.

Testing again. The College’s server was dropped out right away, no way around that security. On others it worked fine. I tested for a couple of days just to make sure. When I thought it was OK, I’ve let it go once again. I contacted Joni, Graham and Bishop to tell them that the new rewritten version is out. On Joni’s site it worked. Awesome. On Bishop’s site worked. Kinda. On Graham’s site didn’t work. He tried it on another site. Worked. Cool. Finally it works. I was happy.

But not for long. The next day I saw that on my site it’s ticking some ol’ tweets. What?! Then started the bug hunting again. I looked at each line of code, var_dumped every variable. No luck. Somehow, all of a sudden, my server is not getting the data from Twitter. No changes on the server configuration, no change in the code, but it just won’t work.

The third idea...

The third idea is to leave this “plug-in” as—is, and to stop working on it. It just doesn’t pay off. Sure, I could trace down where it hangs on my server, going backwards through the code, but it’s just not worth it. Those who are interested in this plug-in, you can find it at the TickTweet page, use it, rewrite it, change it, trash it.

Cheers!

Project Euler

published on October 27, 2008.
Heads-up! You're reading an old post and the information in it is quite probably outdated.

A few days ago, I found a really great place, full of excellent math and programming problems: Project Euler.

Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.

I was long looking for this kind of place, to get my brain do some serious thinking :) It’s a great way to improve logic and math/programming skills.

The problems can be solved by using any programming language, so as I just started learning Python, thought that this is a great way to start with it. As I suck more in math than in programming, my solutions are brute-forced, but I always go back to the explanation of the problem (can be viewed only after you gave the right answer to the problem), to understand the math behind the problem.

There are currently 214 problems and I’m on number 6 right now. If you into this kind of stuff, be sure to check it out, it’s a lot of fun :)

Happy hacking!

A Zend_Captcha example

published on October 22, 2008.
Heads-up! You're reading an old post and the information in it is quite probably outdated.

Update: I made an error in the example code, regarding the CAPTCHA image URL. I’m sorry for any troubles caused by this mistake.

Update #2: Here’s an example of using Zend_Captcha without the whole Zend Framework stuff.

Update #3: There was an unintentional error in the captchaAction() method, Adam warned me about it in the comments. The error is fixed now. Thanks Adam.

OK, this was a bit tricky and I found no examples about it, so I thought to blog it. I’ll just show a quick example how to implement Zend_Captcha into a Zend_Form, may be useful for someone. There are several CAPTCHA types in ZF, like the Image, Figlet and Dumb. I use Image.

First of all, we’ll use sessions, so we need to change the bootstrap file a little:

<?php
// Put this line somewhere after the Zend_Loader::registerAutoload(); line
Zend_Session::start();

We need to start the session to use it, putting it close to the top will assure that there will be no “Headers already sent by…” errors caused by a wrongly placed session start.

Next we need a folder which has a 777 permission on it (Windows users, you can skip this… Or start using GNU/Linux) where we will put our captcha images for a while… This folder must be in the public folder somewhere. So create one.

How does this work? When a captcha is generated, it generates a unique ID (e.g. 539e517b0c0f4e32ef634dae92f07f77) and the word on the image. That unique ID is used for the file name of the image and for the session namespace (the namespace is like: Zend_Form_Captcha_uniqueId), so it knows which image belongs to which session. Also, the generated word is placed inside it’s own session. That ID is placed on the form in a hidden field, so when the submission is received, we can access the ID and recreate the correct session namespace and access the data in it: the word on the image.

Awesome. Now, to the fun part. I use the Zend_Form_Element_Captcha class, so no additional fooling around is needed to put the captcha in the form. Here’s the code:

<?php
public function indexAction()
{
// Our form object...
$form = new Zend_Form();
// And here's our captcha object...
$captcha = new Zend_Form_Element_Captcha(
        'captcha', // This is the name of the input field
        array('label' => 'Write the chars to the field',
        'captcha' => array( // Here comes the magic...
        // First the type...
        'captcha' => 'Image',
        // Length of the word...
        'wordLen' => 6,
        // Captcha timeout, 5 mins
        'timeout' => 300,
        // What font to use...
        'font' => '/path/to/font/FontName.ttf',
        // Where to put the image
        'imgDir' => '/var/www/project/public/captcha/',
        // URL to the images
        // This was bogus, here's how it should be... Sorry again :S
        'imgUrl' => 'http://project.com/captcha/',
)));
// Add the captcha element to the form...
$form->setAction('/index/captcha/')
        ->setMethod('post')
        // Add the captcha to the form...
        ->addElement($captcha)
        ->addElement('submit','Submit')
// Pass the form to the view...
$this->view->form = $form;
}

On the other side, it goes something like this:

<?php
public function captchaAction()
{
  $request = $this->getRequest();
  // Get out from the $_POST array the captcha part...
  $captcha = $request->getPost('captcha');
  // Actually it's an array, so both the ID and the submitted word
  // is in it with the corresponding keys
  // So here's the ID...
  $captchaId = $captcha['id'];
  // And here's the user submitted word...
  $captchaInput = $captcha['input'];
  // We are accessing the session with the corresponding namespace
  // Try overwriting this, hah!
  $captchaSession = new Zend_Session_Namespace('Zend_Form_Captcha_'.$captchaId);
  // To access what's inside the session, we need the Iterator
  // So we get one...
  $captchaIterator = $captchaSession->getIterator();
  // And here's the correct word which is on the image...

  $captchaWord = $captchaIterator['word']
  // Now just compare them...
  if($captchaInput == $captchaWord)
  {
  // OK
  }
  else
  {
  // NOK
  }
}

Easy, ain’t it?

Happy hacking :)

Tip: Using a monospace or a serif font for the words on the image (like FreeMono.ttf found by default on Ubuntu), makes the word quite unreadable — with the FreeMono.ttf about 8 out of 10 is UNreadable — so use a sans-serif font.

Starting with Zend Framework - part 2

published on October 20, 2008.
Heads-up! You're reading an old post and the information in it is quite probably outdated.

This post is the second part of my introductory text on Zend Framework, Starting with Zend Framework. This time I cover the basics about controllers, actions, view scripts and view helpers. On request routing and the Front Controller I will write one (or more) big post(s), so this part won’t be explained now. I will also skip explaining the models; they deserve their own post :)

If anyone is into writing a guest-post on models, let me know!

The Controllers

The Controllers are the heart of every MVC based application. They control the execution of the application, what to do with the data, what to show the user, what to write to the database, etc. The Controllers that you will write all the time, are called Action Controllers. These Controllers subclass the Zend_Controller_Action abstract class. Every application module must have a default Controller, which will be accessed if no specific Controller is requested. The default name for this default Controller is Index. Examples of the IndexController and FooController:

<?php

// The IndexController class must be placed in the controllers folder
// and saved as IndexController.php
class IndexController extends Zend_Controller_Action
{
    public function init()
    {
    }

    public function indexAction()
    {
    }
}

// The FooController class must be placed in the controllers folder
// and saved as FooController.php
class FooController extends Zend_Controller_Action
{
    public function init()
    {
    }

    public function indexAction()
    {
    }

    public function barAction()
    {
    }

    public function someRandomFunctionDoingSomeFunkyStuff()
    {
    }
}

The Controllers must contain at least the indexAction() function; the others are arbitrary. I always have an init() function, in which I setup the cache object, call up the models, etc. Controller names that are not in the “default” module, must be prefixed with the Title-cased name of the module and an underscore:

<?php

// An example of the IndexController in the
// dummy module
// The file name remains IndexController.php!!!
class Dummy_IndexController extends Zend_Controller_Action
{
}

// An example of the FooController in the
// dummy module
// The file name remains FooController.php!!!
class Dummy_FooController extends Zend_Controller_Action
{
}

The actions

Actions are methods of the Controller class. Use them to do some specific task: show users, list news, insert to database (the actual INSERT SQL statement should be in the model), etc. As stated before, every Controller must have an index action — this one is called if no specific action is requested. By default the view object is instantiated, so if you don’t turn it off, you must create a view script with the same name as the action (without the “Action” word) in the views/scripts/foo/ folder.

Assigning variables to the view scripts is simple:

public function indexAction()
{
    $this->view->someVariable = "some value...";
}

The view scripts

View scripts are, well, for viewing. This is the only place where you should have statements like echo and print. The default templating engine is PHP itself, but it’s possible to change it to something like Smarty. I leave PHP; it has everything for templating, so why would I change it? The default file extension for view scripts is “phtml” — but as with everything, this can also be changed :)

Getting variables that are assigned from the action:

// Output: some value...
<?= this->someVariable ?>

The view helpers

The view helpers are simple classes that help in view scripts with things like formatting dates, creating links, etc. Here’s an example view helper that I use to show dates in “Serbian” format:

File name: views/helpers/SrDateFormat.php
<?php
/**
* View helper for returning dates in Serbian format
* dd.mm.yyyy.
*
*/
class Zend_View_Helper_SrDateFormat
{
    public function srDateFormat($dateToFormat)
    {
        return date('d.m.Y.', strtotime($dateToFormat));
    }
}

Usage is quite simple:

// somewhere in some view script...
<?= $this->srDateFormat($someDateToShow); ?>

Bringing it all together

Just for an overview, here is an example of a Foo Controller in the Dummy module with index and bar actions and their view scripts.

<?php
// File name: application/dummy/controllers/FooController.php
class Dummy_FooController extends Zend_Controller_Action
{
    public function indexAction()
    {
        $this->view->sayHello = "Hi there!";
    }

    public function barAction()
    {
        $this->view->sayHelloAgain = "Hi here :)";
    }
}

And the view scripts:

<!-- File name: application/dummy/views/scripts/foo/index.phtml -->
<h1>Saying hello</h1>
<?= $this->sayHello ?>

<!-- File name: application/dummy/views/scripts/foo/bar.phtml -->
<h1>Saying hello again</h1>
<?= $this->sayHelloAgain ?>

So if you direct your browser to “http://example.com/dummy/foo/&#148; or to “http://example.com/dummy/foo/bar&#148; you should get the “Saying hello” or the “Saying hello again” page…

This would be my introductory text to Zend Framework. Hope it’s not confusing and is easy to follow. I just want to help newcomers to ZF help settling in easily :) For a tutorial application with ZF, I recommend Rob Allen’s Zend Framework tutorial.

In the coming days/weeks I’ll write a detailed post about the Front Controller, so if you wish, grab the feed or subscribe by E-mail to stay tuned.

Cheers!

Robert Basic

Robert Basic

Software engineer, consultant, open source contributor.

Let's work together!

If you require outsourcing or consulting help on your projects, I'm available!

Robert Basic © 2008 — 2019
Get the feed