coudenysj Jachim Coudenys on web technology

30Mar/104

Custom URL’s in Zend Framework

I am searching for a url solution in Zend Framework for quite a while now, and I hope the solution I came up with helps other people trying to do the same thing.

More important, I hope more experienced (Zend Framework) developers can point out problems or suggest better solutions for this problem.

The CMS of my company makes it possible for users to create a tree structure of products/sections/chapters/etc... with an unlimited depth. This makes the url they 'generate' very variable.

I've searched the internet for solutions and for quite a while I used the solution of Jani. Because this completely overrides the Router object, I continued my search via the Zend MVC mailing list and had an extensive look at the Zend_Controller_Router manual page.

During the search Ivo Jansch tweeted about ZF URL's and pointed me towards chaining, but the solution for my specific problem lies in adding Routes to the route stack.

I wanted to override the default route so that a language is required in the url. To accomplisch this I added an new function in the Bootstrap.php file:

protected function _initLanguageRoute()
{
    $this->bootstrap('frontController');
    $fc = $this->frontController;
    $router = $fc->getRouter();
    $route = new Zend_Controller_Router_Route(
        ':language/:controller/:action/*',
        array(
            'module' => 'default',
            'language' => 'nl',
            'controller' => 'index',
            'action' => 'index'
        ),
        array(
            'language' => '[a-z]{2}'
        ),
        $translator
    );
    $router->addRoute('default', $route);
}

To add a variable route (calculated by the CMS), I extended the Zend_Controller_Router_Route_Abstract class so the route could also be used by the Url View helper.

The database I use below, has calculated colums already, but a custom mapping can be calculated in the class as well. As long as the request object is pointed to some controller and action.

class Coudenysj_Controller_Router_Route_Mapping extends Zend_Controller_Router_Route_Abstract
{

    private $_db;


    public function __construct($db)
    {
        $this->_db = $db;
    }

    /**
     * A method to publish the way the route operates.
     *
     * @see Zend/Controller/Router/Rewrite.php:392
     *
     * @return int
     */
    public function getVersion()
    {
        return 1;
    }

    /**
     * The required functions (required by Interface).
     *
     * @param Zend_Config $config The config object with defaults.
     *
     * @return void
     */
    public static function getInstance(Zend_Config $config)
    {
        return;
    }

    /**
     * Matches a user submitted path with a previously defined route.
     * Assigns and returns an array of defaults on a successful match.
     *
     * @param string $path Path used to match against this routing map
     *
     * @return array|false An array of assigned values or a false on a mismatch
     */
    public function match($path)
    {
        $path = trim($path, '/');

        return $this->_db->fetchRow(
            'SELECT lang, controller, action, id
            FROM mapping
            WHERE url = ?;',
            array($path)
        );
    }

    /**
     * Assembles a URL path defined by this route
     *
     * @param array   $data    An array of variable and value pairs used as parameters
     * @param boolean $reset   Not used (required by interface)
     * @param boolean $encode  Not used (required by interface)
     * @param boolean $partial Not used (required by interface)
     *
     * @return string|false Route path with user submitted parameters
     */
    public function assemble($data = array(), $reset = false, $encode = false, $partial = false)
    {
        if (!isset($data['language'])) {
            if (Zend_Registry::isRegistered('Zend_Locale')) {
                $locale = Zend_Registry::get('Zend_Locale');
                $data['language'] = $locale->getLanguage();
            } else {
                return false;
            }
        }
        if (   !isset($data['controller'])
            || !isset($data['action'])
            || !isset($data['id'])
        ) {
            return false;
        }

        $result = $this->_db->fetchRow(
            'SELECT url
            FROM mapping
            WHERE lang = ? AND controller = ? AND action = ? AND id = ?;',
            array(
                $data['language'],
                $data['controller'],
                $data['action'],
                $data['id'],
            )
        );
        return $result['url'];
    }
}

Now I can add a new 'cms' route to the Router object in the Bootstrap.php file:

protected function _initMappingRoute()
{
    $db = new Zend_Db::factory(...);
    $this->bootstrap('frontController');
    $fc = $this->frontController;
    $router = $fc->getRouter();
    $router->addRoute(
        'cms', new Coudenysj_Controller_Router_Route_Mapping($db)
    );
}

Remember that the route stack is processed backwards, so the 'cms' route is the first one to try and route the url.

This route can now also be used in the view:

echo $this->url(
    array(
        'id' => $id,
        'controller' => $controller,
        'action' => $action
    ),
    'cms' // the name of our route
);

This solution works for me (for now) and suggestions to improve it are very welcome!

25Mar/100

3 years ago in Cambridge

Studio 24 logoIt has been around three years now, since I started my internship at Studio 24.

Studio 24 is a Cambrigde (UK) based web agency with over 10 years of expierence, happy to share their knowledge with students willing to learn.

In the last year of my training MCT at Howest (University College West Flanders), I decided to do my internship abroad, so I ended up in the beautiful Cambridge for over 3 months.

With the support of my house mates Leena (SE), Chris (AU), Matthew (UK) & Alex (UK) and my bosses/colleagues Simon, Jonathan, Richard, Edward, David, Dave & Gaëlle, I found my way through Cambridge and the professional web world.

A lot of what I learned in those 3 months, I still use and advocate/implement in my current company. Some examples of technologies, procedures, software, etc... I discoverd or worked with:

Using all these things and the variaty of customers Studio 24 has, resulted in an astonishing list of projects I worked on. So much, I only could use a thirth of them in my presentation for the jury back at home.

Here's an extraction:

I had a great time, and encourage every student to have a look at the Lifelon Learning programme of the EU, which helped me pay for my accommodation.

Looking back, I'm glad everyone around me 'pushed' me in the Cambridge adventure and I would do it again, if I had the change!

12Jan/101

Deleting Subversion repository files (for real)

Keeping files and directories in the repository is one of the key principles of Subversion, so once you've committed something, it's there for ever. You can delete files, but they still exist somewhere in the repository, so you can go back in time.

But there is always that time where you've (accidentally) committed a password file, a directory full of hi-res images, or some other contents you don't want other people to see that you want to get rid off. That's where the hard part starts...

After searching the internet and checking the Subversion FAQ it looks quite hard, but with some guidance, you'll find out it's not.

Finding the problems

First you have to do a (complete) checkout of the repository you want to clean:

svn co http://svn.apache.org/repos/asf/ asf

Now you can start to locate the problems and delete the files/directories (not svn delete!):

rm -Rf subversion/trunk/tools/buildbot;
rm -Rf subversion/trunk/README;
rm -Rf subversion/trunk/build;

When you're done delete files and directories, you can generate a list of 'missing' files.

Checking your files:

svn status
!      subversion/trunk/tools/buildbot
!      subversion/trunk/README
!      subversion/trunk/build

Generating that list (outside the working copy):

svn status | sed s/"!      "// > ../filter.txt

Fixing the problems

Now you have a nice list of files to delete (make sure it includes the parent directories, right to the root), you should login on the server hosting the repository.

We first want to make sure there is a backup:

svnadmin dump file:///var/svn/asf > ~/backup_svn/asf.dump

Now we can use that backup file as the input of file for the svndumpfilter command. In combination with the filter list we've generated on the client, we can create a filtered dump version:

svndumpfilter exclude `cat filter.txt` < ~/backup_svn/asf.dump > asf_filtered.dump

To load that file back in the repository, we should 'delete' the original repository. (The httpd commands are just to make sure no one commits while processing the changes).

/etc/init.d/httpd stop;
mv /var/svn/asf ~/backup_svn/asf;
svnadmin create --fs-type fsfs /var/svn/asf;
svnadmin load /var/svn/asf &lt; asf_filtered.dump;
/etc/init.d/httpd start;

Please note that directories and command line options can be different, but the outcome should be the same.

Now we have the same repository, without the (accidentally) committed files/directories!

New problems

After the filtering, it is possible that complete revisions are empty. It is possible to skip empty revisions, but then all revisions are renumbered, and that could be problematic for other software (e.g. Trac).

10Nov/095

Hostnames in Logwatch reports

Where I work, we have a lot of servers to maintain, and only 2 server admins (me and my colleague). We use Nagios to keep us informed about the server status and Logwatch to analyze to server logs on a daily basis.

We have per server a lot of subdomains/vhosts and these virtual hosts all write into their own log (blog.jachim.be_acces_log, www.jachim.be_error_log, etc...).

The log entries look like this:

192.168.200.6 - - [10/Nov/2009:09:55:41 +0100] "GET /a/i/red_cube.png HTTP/1.0" 200 190
192.168.200.6 - - [10/Nov/2009:09:55:41 +0100] "GET /a/i/search/search_icon.gif HTTP/1.0" 200 428
192.168.200.6 - - [10/Nov/2009:09:55:41 +0100] "GET /index.php HTTP/1.0" 200 6541

When Logwatch merges all the httpd log files, the host information (in the log filename) is lost, resulting in Logwatch reports like this:

Requests with error response codes
    401 Unauthorized
       /: 4 Time(s)
       /a/i/blue_cube.png: 1 Time(s)
       /favicon.ico: 2 Time(s)
       /wp/login: 2 Time(s)
...

We actually want reports like this:

Requests with error response codes
    401 Unauthorized
       www.jachim.be/: 4 Time(s)
       jachim.be/a/i/blue_cube.png: 1 Time(s)
       blog.jachim.be/favicon.ico: 2 Time(s)
       blog.jachim.be/wp/login: 2 Time(s)
...

Now we have all the information we want and are able to fix the possible problems much easier.

Because this is not possible in Logwatch (see mailinglist), I've added it in the Apache logs.

I've added a new logformat named logwatch in httpd.conf:

LogFormat "%h %l %u %t \"%m %{Host}i%U%q %H\" %>s %b" logwatch

Now the new format is available and can be used in the Virtual Host:

CustomLog logs/www.jachim.be-access_log logwatch

Resources:

28Oct/090

Random PHP function explained

file1_Open_Source_PHP_logo_667A few weeks ago, Jamie Bicknell notified me he read my article about the Random PHP function. Because I didn't publish any code, he wrote a 3 line implementation of how he would fetch the functions for the randomness.

I promised him I would publish the code that weekend, and here we are, a few weeks later...

The script actually parses the http://php.net/quickref.php page, saves the result, and redirects the user.

$cacheFile './functions.tmp';
if (!
is_file($cacheFile)) {
    
$quickref 'http://php.net/quickref.php';
    
$xml DOMDocument::loadHTMLFile($quickref);
    
$links $xml->getElementsByTagName('a');
    
$functions = array();
    foreach (
$links as $link) {
        if (
substr($link->getAttribute('href'), 08) == '/manual/') {
            
$functions[$link->nodeValue] = $link->getAttribute('href');
        }
    }
    
file_put_contents($cacheFileserialize($functions));
} else {
    
$functions unserialize(file_get_contents($cacheFile));
}
$function $functions[array_rand($functions)];
$function 'http://php.net' $function;
header('Location: ' $functiontrue303);
die();

Some improvements:

  • Invalidate the cache file when a new PHP version is announced.
  • Read random lines from the file (instead of loading the complete array in the memory).

Update: Forgot the mention the actual blogpost of Jamie Bicknell...

14Oct/090

phpBenelux

phpbenelux_logoAs you can see in my Blogroll panel, on my homepage, profile and LinkedIn, I'm a proud member of phpBenelux.

Tuesday there was another meeting, this time in the offices of Netlog, with talks from Ivo Jansch about "PHP and the Cloud" and Felix De Vliegher about "High gear PHP with Gearman".

Because it took me quite a while to figure out what user group was/is the real one and what's the plan for the future, I wanted to share my "knownledge" with you:

  • phpBenelux is the new name after phpBelgium and phpgg merged.
    I'm still waiting for Luxembourg, but they'll come along :).
  • Meetings are held monthly, one month in the Netherlands, the other month in Belgium.
  • A new website (phpBenelux.eu) is on the way, and I'm offering my help, together with my colleague Jochen.

I will post updates on the list above, because there are still some questions that I haven't figured out yet:

  • How the website is working.
  • What should have happened, after I payed € 15.
  • Why the "statutes" are still those of phpgg.

That being said: phpBenelux is a great user group, where I'll offer my help to expand the knowledge of PHP into the benelux.

See you on the next meeting!

25Sep/0941

php msort() – multidimensional array sort

There have been several moments where I had a rowset from a database as a PHP array, and I had to sort it based on some columns.

$tickets = array(
    array(
        
'id' => 13,
        
'owner' => 'jachim',
        
'time' => '2009-09-25 10:39:42.011612',
        
'project' => 'jachim.be',
        
'title' => 'Some random ticket'
    
),
    array(
        
'id' => 31,
        
'owner' => 'jachim',
        
'time' => '2009-09-24 14:38:47.945020',
        
'project' => 'joggink.be',
        
'title' => 'Some other random ticket'
    
),
    array(
        
'id' => 22,
        
'owner' => 'root',
        
'time' => '2009-09-24 10:58:02.904198',
        
'project' => 'joggink.be',
        
'title' => 'A specific ticket'
    
)
);

I searched for functions for a while, and even try to understand/use the array_multisort function, but I never managed to get something working on a simple array (like the one above). The new function msort() should be a solution for this.

The function works normally when you use a string for the second parameter. That way the $sort_flag works like you would expect it. When using an array of keys however, a string key is built to sort the array on. This part could use some improvement.

Here an example of the usage:


var_dump($tickets);

$tickets msort($tickets, array('owner''time'));

var_dump($tickets);

And here's the function itself:

/**
 * Sort a 2 dimensional array based on 1 or more indexes.
 * 
 * msort() can be used to sort a rowset like array on one or more
 * 'headers' (keys in the 2th array).
 * 
 * @param array        $array      The array to sort.
 * @param string|array $key        The index(es) to sort the array on.
 * @param int          $sort_flags The optional parameter to modify the sorting 
 *                                 behavior. This parameter does not work when 
 *                                 supplying an array in the $key parameter. 
 * 
 * @return array The sorted array.
 */
function msort($array$key$sort_flags SORT_REGULAR) {
    if (
is_array($array) && count($array) > 0) {
        if (!empty(
$key)) {
            
$mapping = array();
            foreach (
$array as $k => $v) {
                
$sort_key '';
                if (!
is_array($key)) {
                    
$sort_key $v[$key];
                } else {
                    
// @TODO This should be fixed, now it will be sorted as string
                    
foreach ($key as $key_key) {
                        
$sort_key .= $v[$key_key];
                    }
                    
$sort_flags SORT_STRING;
                }
                
$mapping[$k] = $sort_key;
            }
            
asort($mapping$sort_flags);
            
$sorted = array();
            foreach (
$mapping as $k => $v) {
                
$sorted[] = $array[$k];
            }
            return 
$sorted;
        }
    }
    return 
$array;
}

21Aug/090

Random PHP function

To explore new things, I sometimes use the 'Random article' link on Wikipedia. It is a simple and basic principle, but it gets you to articles you would never get by just browsing the site.

I was looking for something that did the same job for the php.net site, but could not find anything. As a programmer, you're most likely to end up in the same chapters of the manual over and over again, and a 'Random function' link would be nice to find out new stuff.

So I wrote on myself...

The script parses the http://php.net/quickref.php page, and picks a random link to redirect you to. Anyone heard of HaruDoc? 🙂

Try it yourself: Random PHP Function. Good luck!

17Aug/090

Stuff to read from Google

Google

Google has some really nice stuff to read, written in an easy to read way, about all sorts of things. It's a lot about front-end things, but as a back-end developer I'm responsible to build pages & sites with an infrastructure which leverages these things.

The things I found recently:

17Aug/090

We’re sorry, but you typed “Congo”

Just send out an email to promote our event, and I've got an "out of the office" mail back with a SPAM notice:

congo_no_allowed

Tagged as: , No Comments