Robert Basic's blog

Posts tagged 'example'

Bad Firebug!

by Robert Basic on December 21, 2009.
Heads-up! You're reading an old post and the information in it is quite probably outdated.

We all know about Firebug, probably the best developer add-on out there, and how awesome it is and how many times it helped us debug some nasty Javascript code, mess around with CSS and HTML on-the-fly, to track the time load of every external page element our app loads… It’s so cool that it even has it’s own add-ons! (FirePHP, YSlow and FireCookie). Really, it helps our developer lives to suck a bit less.

Note: the following text is not about bashing other developers and their works, but to highlight the importance of proper input filtering. I myself have failed on this, several times.

Let’s go back to the part where we mess with the HTML by the means of this, may I say, application. You can add, hide, remove HTML elements, add, alter, remove, attributes from HTML elements… Adding, hiding, deleting - boring; altering - fun! I have this urge to try to break every form on every website I find. Not to do any harm, just to take a look how my fellow developer did his job and if I see anything that’s not right, I try to contact him to fix that, cause, y’know, I’m a nice person… Anyhow, I recently found some sites where all the textfields and textareas were filtered properly and no harm could be done - all my “hack” attempts were caught by their application. Nice. Oh, look, a select box! Right-click, inspect element, value=“xyz”, change that to value=“abc”, submit the form… and poof! A sexy SQL error. All that with the help of our li’l friend, Firebug. The elements where the user is required to provide some information “by hand” were processed correctly, but the select box was not.

OK, let’s take this one step further. On a site where the user can register an account and afterwards can edit his or hers profile. I register, go to the user panel, the usual stuff - change email, password, location, DoB (Date of Birth)… A quick inspection of the source - a hidden field “id” with a number in it. Hmm… Quickly, I register another account, note the “id” on that second account, go back to the first account, change the “id” of the first account to the “id” of the second account, change the DoB (just to see any actual information changing), click submit… “Your profile has been updated successfully.” Mine? Not really, the DoB is like it was in the first place… Go to the second account… Oh boy. I successfully changed the DoB of the second account, with my first account. Now, I haven’t seen their source code, but I can imagine what was going on. Something like this:

<?php
$id = (int)$_POST['id'];
$dob = $_POST['dob'];

$sql = "UPDATE users SET dob = '" . $dob . "' WHERE id = " . $id;

On the positive side, when I entered letters in that hidden field, I was told by the app that I haven’t filled all the fields correctly, which means they filtered even the hidden field, but skipped to check if that “id” is actually me.

OK, I know, the title is “Bad Firebug!” and the problems are actually about filtering user input, but I needed a catchy title to have your attention on Twitter :P

Even tho a field seems “unchangeable”, with a help of an awesome little app, it becomes changeable. And dangerous.

Filter input, escape output :)

P.S.: On the image above you can see my profile on a bulletin board, where I changed my year of birth from 1986 to 986 with Firebug. The years are in a select box; the lowest value is 1910. You can see my actual profile here.

Tags: escaping, example, filter, firebug, php, security.
Categories: Development, Programming, Software.

Chaining routes in Zend Framework

by Robert Basic on November 27, 2009.
Heads-up! You're reading an old post and the information in it is quite probably outdated.

On a forum, there was a question today, about adding language “support” to the routes using Zend Framework. The guy wanted routes like /en/foo/bar or /de/baz. I wrote there an example for that using Zend_Router_Routes_Chain, so just posting that example here, too :)

For what chains are for, is described in the manual, so I won’t be covering that :P

Basically, we’re prepending the language route to the other routes. This way, we have defined the route for the languages in one place only, plus, the other routes don’t have to worry about the language, too.

// this goes in the bootstrap class
<?php
public function _initRoutes()
{
    $this->bootstrap('FrontController');
    $this->_frontController = $this->getResource('FrontController');
    $router = $this->_frontController->getRouter();

    $langRoute = new Zend_Controller_Router_Route(
        ':lang/',
        array(
            'lang' => 'en'
        )
    );
    $contactRoute = new Zend_Controller_Router_Route_Static(
        'contact',
        array('controller'=>'index', 'action'=>'contact')
    );
    $defaultRoute = new Zend_Controller_Router_Route(
        ':controller/:action',
        array(
            'module'=>'default',
            'controller'=>'index',
            'action'=>'index'
        )
    );

    $contactRoute = $langRoute->chain($contactRoute);
    $defaultRoute = $langRoute->chain($defaultRoute);

    $router->addRoute('langRoute', $langRoute);
    $router->addRoute('defaultRoute', $defaultRoute);
    $router->addRoute('contactRoute', $contactRoute);
}

Assuming that we have an Index controller, with actions index and contact and a Foo controller with actions index and bar, paired with the routes from the above example, we could do requests like:

/ => /index/index/lang/en
/de => /index/index/lang/de
/sr/contact => /index/contact/lang/sr
/en/foo => /foo/index/lang/en
/fr/foo/bar => /foo/bar/lang/fr

Requesting a page like, e.g. /de/baz, would give us a 404 page, cause we don’t have a Baz controller.

HTH :)

Happy hacking!

Tags: example, framework, php, route, routing, zend, zf.
Categories: Development, Programming.

Playing with Zend_Navigation and routes

by Robert Basic on August 09, 2009.
Heads-up! You're reading an old post and the information in it is quite probably outdated.

O hai. First things first - someone should slap me for being such a lazy blogger. Somehow I lost all the motivation I had in the beginning, but looks like it’s back now :) I finally had the time to play around with the latest Zend Framework version (v 1.9 now). I managed to skip the whole 1.8.x version, so this whole Zend_Application stuff is quite new to me. I spent a few days poking around the manual and the code to make it work. And it works! Yey for me! And yey for Rob Allen for his post on Bootstrapping modules in ZF 1.8!

Zend_Tool is an awesome tool. Creating a new project is like “zf create project project_name” :) And the new bootstrapping process with the Bootstrap class is somehow much clearer to me now… Anyways, lets skip to the code.

The goal

I wanted to set up routes in such way that when a user requests a page, all requests for non-existing controllers/modules are directed to a specific controller (not the error controller). In other words, if we have controllers IndexController, FooController and PageController, anything but http://example.com/index and http://example.com/foo is directed to the PageController. This can be useful for CMSs or blogs to make pretty links. Here’s where the Zend_Controller_Router_Route_Regex stuff comes in:

<?php
$route = new Zend_Controller_Router_Route_Regex(
    '(?(?=^index$|^foo$)|([a-z0-9-_.]+))',
    array(
        'controller' => 'page',
        'action' => 'view',
        'slug' => null
    ),
    array(
        1 => 'slug',
    ),
    '%s'
    );

$router->addRoute('viewPage', $route);

Basically the regex does the following: if it’s index or foo don’t match anything, thus calling up those controllers, in any other case match what’s requested and pass it to the PageController’s viewAction as the slug parameter. The fourth parameter, the ‘%s’, is needed so that ZF can rebuild the route in components like the Zend_Navigation.

Now, when the PageController, viewAction get’s called up, we can check, for example, if a page with that slug exists (like, in a database). If it exists, show the content, otherwise call up a 404 page with the error controller. In this fancy and sexy way we can call up pages without passing ID’s or even letting the user know what part of the website is working on his request. He just request’s http://example.com/some_random_article and kaboom! he get’s the content :)

Page navigation

Oh the joy when I saw Zend_Navigation in the library! And it even includes view helpers to help us render links and menus and breadcrumbs! Yey! There are a several blog posts which go in details about Zend_Navigation, so I won’t be bothering with that. What I wanted to make with Zend_Navigation is to have a menu of all the pages rendered everywhere. Here’s where action helpers kick in. I made an action helper which makes up the structure of the links/pages. Something like this:

<?php
class Zend_Controller_Action_Helper_LinkStructure extends
        Zend_Controller_Action_Helper_Abstract{
function direct(){
$structure = array(
    array(
         'label'=>'Home page',
         'uri'=>'/'
    ),
    array(
         'label'=>'Articles',
         'uri'=>'',
         'pages'=>array(array(
                                  'label'=>'Article 1',
                                  'uri'=>'article_1'),
                              array(
                                  'label'=>'Article 2',
                                  'uri'=>'article_2'),
                         )
    )
);
return new Zend_Navigation($structure);
}
}

This is a simple example of the structure; I’m actually making it out from the database, with all the categories, subcategories and pages.

Links everywhere

To have this menu on all pages, we need to render it in the layout.phtml. Rendering is quite simple:

<?php
// somewhere in layout.phtml
<?php echo $this->navigation()->menu(); ?>

Of course, we need to pass the menu to the navigation helper somehow. To avoid doing $this->navigation($this->_helper->linkStructure()); in all the controllers, we could do that once in the bootstrap (any other ways to make it happen?):

<?php
// in Bootstrap.php somewhere in the Bootstrap class
function _initView(){

        $view = new Zend_View();
        $view->doctype('XHTML1_STRICT');
        $view->headMeta()->appendHttpEquiv('Content-Type', 'text/html; charset=UTF-8');

        // our helper is in app/controllers/helpers folder, but ZF doesn't know that, so tell him
        Zend_Controller_Action_HelperBroker::addPath(APPLICATION_PATH.'/controllers/helpers');
        // now get the helper
        $linkStructure = Zend_Controller_Action_HelperBroker::getStaticHelper('LinkStructure');
        // and assign it to the navigation helper
        $view->navigation($linkStructure->direct());

        $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
        $viewRenderer->setView($view);

        return $view;
}

There. Now we have our menu rendered on all pages. Sexy isn’t it? :)

That’s it for now. Hope someone will find this useful :) Now I gotta go, need to get ready for a punk rock concert tonight!

Happy hacking!

Tags: example, framework, navigation, php, routing, zend, zf.
Categories: Development, Programming.

Wordpress as CMS tutorial

by Robert Basic on March 14, 2009.
Heads-up! You're reading an old post and the information in it is quite probably outdated.

Wordpress is one of the best blogging platforms out there — if not the best. It’s very powerful, can be easily extended and modified. It’s documentation is very well written and, so far, had answer to all of my crazy questions :)

You know what’s the best part of Wordpress? With some knowledge of PHP and MySql, you can turn it into much more than just a blogging platform. After doing some HTML to WP work for Roger, I thought of one way how could Wordpress be transformed into a CMS. Note the “one way”. This is not the only way for doing this, and, most likely, not the best way.

I didn’t look much, but I think that there are some nice plugins out there that can do this. But, where’s the fun in the download, upload, activate process? Nowhere!

I will show you how to change your Wordpress into a CMS and it really doesn’t take much coding to achieve this! The example presented here is simple and will have a static page for it’s home page, another static page for the “Portfolio” page and the blog. The home and portfolio page will have some of own content and both will include some content from other static pages. You all most likely know the blog part ;)

Static pages

Things you should know: each static page has it’s title, it’s slug or name (the thing that shows up in your browsers address bar: http://example.com/portfolio/ - right there, the portfolio is the slug!), has the parent attribute and the template attribute. The parent attribute is used when it’s needed to make one page a child of another, i.e. to show Page2 as a subpage of Page1. The template attribute is used when we want to apply some different layout and styling to a static page. Read more about static pages and how to create your own page templates.

If you want to, you can download the theme I created for this tutorial from here (it’s not a designers masterpiece, what did you expect?), or you can use any theme you want.

I hope you read the part on creating page templates, I really don’t feel like explaining the next part.

Create 3 new files in your template directory (if you’re using my theme, these files are already there): home.php, portfolio.php and blog.php. Contents of these files are:

// home.php
<?php
/*
Template Name: Home
*/
?>

// portfolio.php
<?php
/*
Template Name: Portfolio
*/
?>

// blog.php
<?php
/*
Template Name: Blog
*/

// Which page of the blog are we on?
$paged = get_query_var('paged');
query_posts('cat=-0&paged='.$paged);

// make posts print only the first part with a link to rest of the post.
global $more;
$more = 0;

//load index to show blog
load_template(TEMPLATEPATH . '/index.php');
?>

To understand the contents of the blog.php file, please take a look at this.

Now, go to the dashboard, the Pages section and write 3 new static pages:

  • Home, with the slug home, for the template choose Home from the drop-down list (it's on the right side) and the parent leave as is (Main Page)
  • Portfolio, with the slug portfolio, for the template choose Portfolio
  • Blog, with the slug blog, for the template choose Blog

You can add some content to the Home and Portfolio pages, but don’t add any to the Blog page.

Organizing links

Now, let’s make that when we are on http://example.com/ it shows us the Home page, instead of the Blog, and when on the http://example.com/blog/ to show us the blog!

Go to Settings->Reading and where it says “First page displays” choose “A static page”, and under the “Front page” drop-down choose “Home”.

Now, go to Settings->Permalinks and change the “Custom structure” to /blog/%postname%/ or whatever is your preferred permalinks structure, but it must start with /blog/! If Wordpress can’t write to your .htaccess file (I hope it can’t!), open it up in your editor and type the following (or similar, depends on your setup):

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /blog/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

The point is in the RewriteBase, with that we’re telling WP where to find the blog. On default setups, when http://example.com/ points to the blog, the RewriteBase is simply / but with the blog located at http://example.com/blog/ we need to change the RewriteBase. If all is well, we’re done with organizing the links.

While you’re still in the dashboard, write some new static pages with content. For the parent of these pages choose Portfolio and leave the template the default (the default page template is page.php).

Time for coding!

Here are two functions I wrote for retrieving content from static pages which will be then included in other static pages:

// functions.php
<?php

/**
* Gets last $number_of_subpages from their $parent_page
* If the <!--more--> tag is ignored ($ignore_more=true) returns the entire content of the subpages
*
* @param mixed $parent_page Contains either the slug of the parent page or it's ID
* @param integer $number_of_subpages Number of subpages to return
* @param boolean $ignore_more Whether to ignore the <!--more--> tag or not
* @return array Contents and titles of subapages
*/
function wpascms_get_subpages($parent_page='portfolio', $number_of_subpages=2, $ignore_more=false)
{
    global $wpdb;

    if(is_string($parent_page))
    {
        $parent_page_ID = wpascms_get_parent_page_ID($parent_page);
    }
    else
    {
        $parent_page_ID = $parent_page;
    }  

    if($number_of_subpages == 0)
    {
        $limit = '';
    }
    else
    {
        $limit = 'LIMIT 0, ' . $number_of_subpages;
    }
    // Get all subpages that are published and are childs of the given parent page
    // and order them by date in descending order (latest first)
    // also, if needed, limit to the latest $number_of_subpages
    $subpages = $wpdb->get_results("SELECT * FROM $wpdb->posts
                                    WHERE `post_parent` = '$parent_page_ID' AND `post_type` = 'page' AND `post_status` = 'publish'
                                    ORDER BY `post_date` DESC $limit");

    if(!$ignore_more)
    {
        foreach($subpages as $key=>$subpage)
            if(strpos($subpage->post_content, '<!--more-->') !== false)
            {
                $short_content = explode('<!--more-->', $subpage->post_content, 2);
                $subpages[$key]->post_content = $short_content[0] . '<a href="' . get_permalink($subpage->ID) . '">Read more...</a>';
            }
        }
    }

    return $subpages;
}

function wpascms_get_parent_page_ID($parent_page)
{
    global $wpdb;

    $id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE `post_name` = %s AND `post_type` = 'page' AND `post_status` = 'publish'", $parent_page));

    return $id;
}

?>

The first function, wpascms_get_subpages() returns the given number of subpages from a specific parent page. By default it will break the content on the tag and append a “Read more…” link. The first parameter can be either a string containing the slug of the parent page, or the ID of the parent page. The second parameter is the number of subpages we want returned. If it’s zero, all subpages will be returned. The second function is merely a helper function, to get the id of the parent page based on it’s slug. To read more on querying the database, read this page.

Here’s how I’m calling this function on my example Home page:

<?php
/*
Template name: Home
*/

get_header();
?>

    <div id="home">
    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>

        <h2><?php the_title(); ?></h2>

        <?php the_content('<p class="serif">Read the rest of this page »</p>'); ?>

    <?php endwhile; endif; ?>
    </div><!-- home -->

    <div id="latest_works">
    <h1>Recent work</h1>
    <?php $subpages = wpascms_get_subpages();
    if(count($subpages) > 0):
        foreach($subpages as $row=>$subpage):
        if($row%2 == 0)
        {
            $class = "left_work";
        }
        else
        {
            $class = "right_work";
        }
    ?>
        <div class="<?php echo $class; ?>">
            <h2><a href=<?php echo get_permalink($subpage->ID); ?>><?php echo $subpage->post_title; ?></a></h2>
                <?php echo $subpage->post_content; ?>
        </div>
    <?php
        endforeach;
    endif;
    ?>
    </div><!-- latest_works -->

<?php
get_footer();
?>

In words: including the header, then showing any content of the home page. After that getting the subpages: by default, wpascms_get_subpages() is getting the newest 2 subpages of the portfolio page. I’m showing the content of the subpages in 2 columns. What we got with this? Add a new subpage to the portfolio and it will automagically show up on the left side column. In the end, including the footer.

Here’s another example from the portfolio page:

<?php
/*
Template name: Portfolio
*/

get_header();
?>

    <div id="portfolio">
    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>

        <h2><?php the_title(); ?></h2>

        <?php the_content('<p class="serif">Read the rest of this page »</p>'); ?>

    <?php endwhile; endif; ?>
    </div><!-- home -->

    <div id="latest_works">

    <?php $subpages = wpascms_get_subpages('portfolio', 0);
    if(count($subpages) > 0):
        foreach($subpages as $row=>$subpage):
    ?>
        <div class="work">
            <h2><a href=<?php echo get_permalink($subpage->ID); ?>><?php echo $subpage->post_title; ?></a></h2>
                <?php echo $subpage->post_content; ?>
        </div>
    <?php
        endforeach;
    endif;
    ?>
    </div><!-- latest_works -->

<?php
get_footer();
?>

Same thing is happening here: including the header, showing the content of the portfolio page. Getting the subpages, but now all of the subpages that are childs of the portfolio page, and showing them one under the other.

All subpages can be viewed each on it’s own page, but that is just a plain ol’ page.php file, so I’ll skip that.

Don’t limit yourself to the existing plugins or waiting for one tutorial/example that will show how you can make everything. Don’t be afraid to get your hands dirty by hacking some code. It really doesn’t take too much to create magic with Wordpress ;)

Cheers!

Tags: blog, cms, example, hack, php, tutorial, wordpress.
Categories: Development, Programming, Software.

Trac on Ubuntu

by Robert Basic on January 27, 2009.
Heads-up! You're reading an old post and the information in it is quite probably outdated.

Today I was messing around with Trac, installing it and doing some basic configuration. While my dev machine gets updated, I want to share my process of installing Trac.

What is Trac?

As said on the Trac homepage:

Trac is an enhanced wiki and issue tracking system for software development projects.

It’s free, it’s open source, it comes under the BSD license and it’s really awesome. You can write a wiki with it, have a ticket system, connect it with SVN, so you can browse the sources from the browser and see all the commit messages, when was something changed, added… It can support one project, it can support multiple projects. It can be viewable/editable by anyone, or you can close it down for your little team…

Trac is big. It has lots of plug-ins, so you can extend and customize your Trac. I haven’t played with them yet, but as soon as I will, you’ll get notified ;)

It’s written in Python. It can run on it’s own server, or it can run under Apache (where there are also several options). It can use SQlite, PostrgeSQL or MySQL databases. Currently it can connect only to SVN.

I’ll show you how to setup a basic Trac 0.11-dot-something-dot-something. It will run under Apache with mod_wsgi, use a SQlite database, connect to the SVN repository and require user authentication.

Installing Trac

Before anything, I want to say that my machine where I installed Trac has LAMP and SVN configured like this. So, this post is kinda the next part of that post.

First, I installed a Python tool, called Easy Install. It’s here to make our installation process easier. Lovely. Go to http://pypi.python.org/pypi/setuptools/, scroll down to the downloads section and choose a Python egg to download (match it to your currently installed Python version — I have Python 2.5 so I downloaded “setuptools-0.6c9-py2.5.egg”).

Fire up a console and type:

sudo sh setuptools-0.6c9-py2.5.egg

Of course, you need to match this to your own setuptools file.

Next, type:

sudo easy_install Trac

EasyInstall will now locate Trac and it’s dependencies, download and install them.

Download the mod_wsgi:

sudo apt-get install libapache2-mod-wsgi

It will install and enable mod_wsgi. And, in my case, it only tried to restart Apache, but for an unknown reason it fails to do so. If that happens, just do a quick:

sudo /etc/init.d/apache2 restart

If you want Subversion with your Trac, you’ll need the python-subversion package:

sudo apt-get install python-subversion

If you have it already, it’ll just skip it. If you want SVN, but you don’t have this package, later on it will show an error message like: Unsupported version control system “svn”.

Now to make a folder for Trac, where it will keep all the Trac projects and stuff.

sudo mkdir /var/trac /var/trac/sites /var/trac/eggs /var/trac/apache
sudo chown -R www-data /var/trac

Under /var/trac/sites will be the files for Trac projects. The /var/trac/eggs folder will be used as a cache folder for Python eggs. /var/trac/apache will hold a wsgi script file.

The wsgi script is actually a Python script, but with the .wsgi extension, used by mod_wsgi. With this script, Trac will be able to run as a WSGI application.
File: /var/trac/apache/trac.wsgi

import sys
sys.stdout = sys.stderr

import os
os.environ['TRAC_ENV_PARENT_DIR'] = '/var/trac/sites'
os.environ['PYTHON_EGG_CACHE'] = '/var/trac/eggs'

import trac.web.main

application = trac.web.main.dispatch_request

With this kind of script, one single Trac installation will be able to manage multiple projects (you can see here some other scripts).

Configure Apache, add this to your httpd.conf file:

WSGIScriptAlias /trac /var/trac/apache/trac.wsgi

<Directory /var/trac/apache>
    WSGIApplicationGroup %{GLOBAL}
    Order deny,allow
    Allow from all
</Directory>

Restart Apache:

sudo /etc/init.d/apache2 restart

If you go to http://localhost/trac/ in your browser, you should see an empty list of Available Projects. It’s empty, cause we haven’t added any project yet.

Now, let’s asume that we have a project called “testProject” with it’s source located in /var/www/testProject and a SVN repo located in /var/svn/repos/testProject. I’ll show how to add that project to Trac.

In console type:

sudo trac-admin /var/trac/sites/testProject initenv

Note that you need to provide the full path to /var/trac/sites, cause it will create a Trac project in the current folder you’re in.

It will ask you now a few things:

  • Project Name — the name of the project, e.g. “Trac testing project”
  • Database connection string — leave it empty, and it will use SQlite
  • Repository type — leave it empty, and it will use SVN
  • Path to repository — path to the project repo, e.g. /var/svn/repos/testProject

It will start to print out a bunch of lines, about what is it doing. In the end you’ll get a message like “Project environment for ‘testProject’ created.” and a few more lines. One more thing. We need to add the whole project to www-data user, so it can manage the files:

sudo chown -R www-data /var/trac/sites/testProject

If you direct your browser again to http://localhost/trac/, you will now see a link for the testProject. Click it. There, a fully working basic Trac environment for your project. A wiki, a ticket/bug tracking system, a repo browser in only a few minutes. How cool is that? Very.

This Trac environment can now be accessible by everyone. If we do not want that, we need to add this to the httdp.conf file:

<Location /trac>
    AuthType Basic
    AuthName "Trac login"
    AuthUserFile /var/trac/.htpasswd
    Require valid-user
</Location>

Create the .htpasswd file:

sudo htpasswd -bcm /var/trac/.htpasswd your_username your_password

All set. You’ll now have to login to Trac to be able to work on it. As I’m the big boss on my localhost, I gave myself some super-power privileges for Trac: TRAC_ADMIN. It’s like root on *NIX.

sudo trac-admin /var/trac/sites/testProject permission add robert TRAC_ADMIN

Read more about privileges.

That would be it. With this kind of setup, for now, it’s working perfectly for me. For Trac that’s available from the whole Internet, more security measures are needed, but this is only on localhost, so this is enough for me.

Comments, thoughts, ideas?

Happy hacking!

Tags: apache, example, lamp, linux, setup, svn, trac, ubuntu.
Categories: Development, Software.