nabeel shahzad

Breadcrumbs for your Cake (2.1 feature)

without comments

CakePHP 2.1+ (currently in beta) comes with an awesome new feature called view blocks and view extensions (official docs here). This allows you to modify views, append to them, and change them, based on the content that might come later on in your code.

Previously, for building a breadcrumb, there was a giant if/else tree for parsing the request object, and views and helpers all structured to allow for the flexibility. In short, a nightmare. Now with view blocks functionality, it reduces it down to a very simple set of elements, which can be called in meaningful views.

View blocks are built as, you guessed it, blocks. Each block has a name (you chose it, whatever is relevant, “sidebar”, “breadcrumb”). You define a block as such:

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// This goes in a view file
$this->start('breadcrumb');
echo 'Hello';
$this->end();
// You can also append to a block:
$this->append('breadcrumb');
echo ' World';
$this->end();
// And later on you retrieve it:
echo $this->fetch('breadcrumb');
// Outputs "Hello World"

Where do you place this? In a view file. For example, when a user goes to mysite.com/listings/add, it loads a view in Listings/add.ctp. Inside this file, at the top, you do can do:

PHP
1
2
3
4
5
6
// Listings/add.ctp
$this->start('breadcrumb');
echo "Home > Add Listing";
$this->end();
// Continue your view file

This says that when this view (Listings/add.ctp) is loaded, then the breadcrumb should be “Home > Add Listing”. Of course this is simplified (I removed any HTML, etc, just to demonstrate).

Now that we have one view block, we need to pull this into the main layout. Since the breadcrumb shows up before any content, we will structure it using an element, which is pulled into the default layout file. I have an element, in Elements/breadcrumbs/base.ctp, which houses the basic structure of my breadcrumb. This element is called from my Layouts/default.ctp (also, super simplified):

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Elements/breadcrumbs/base.ctp
<ul class="breadcrumb">
    < ?php
    // There's nothing in this block, so output a default or base-level crumb
    if(!$this->fetch('breadcrumb')) {
        echo "Home";
    } else {
        echo $this->fetch('breadcrumb');
    } ?>
</ul>
// Layouts/default.ctp
...
<body>
<div id="nav">
< ?php echo $this->element('breadcrumbs/base'); ?>
</div>
<div id="body">
< ?php echo $content_for_layout; ?>
</div>
...
</body>

The $this->fetch(‘breadcrumb’) is getting a block by the name of breadcrumb. I check to see if that block exists; if it doesn’t, then I output a default item of “Home”. Otherwise, I output the contents of the “breadcrumb” block.

Then when you load the page, it will show Home, and if you go to Listings/add, it will show Home > Add. Pretty simple! In my views, instead of calling the start()/end(), I have an element, under Elements/breadcrumbs/single.ctp, that builds a single level breadcrumb:

PHP
1
2
3
4
5
6
7
8
9
// Elements/breadcrumbs/single.ctp:
$this->start('breadcrumb');
echo '<a href="/">Home</a> | <a href="'.$url.'">'.$title.'</a>';
$this->end();
// First line in a view, let's say Listings/add.ctp
echo $this->element('breadcrumbs/single', array(
'url' => 'listings/add', 'title' => 'Add a Listing'
));

You can clean this up even more by automating it from the $this->request, and using $title_for_layout. I also have another view, which takes an array as a parameter, to build multi-level breadcrumbs:

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Elements/breadcrumbs/multi.ctp:
$this->start('breadcrumb');
echo "<li><a href='/'>Home</a></li>";
foreach($items as $i) {
echo "<li><a href='{$i[url]}'>{$i[title]}</a></li>";
}
$this->end();
// Use it in a view:
echo $this->element('breadcrumbs/multi', array('items' =>
array(
array('url' => '/level1', 'title' => 'Level 1'),
array('url' => '/level2', 'title' => 'Level 2'),
// ...
)
));

Hope this helps! The $scripts_for_layout has also been deprecated in favor of of the view-blocks feature, which create, since now Javascript file can be included on a page-by-page basis, using $this->append

Written by Nabeel

January 31st, 2012 at 2:24 pm

Posted in CakePHP,php

Node.js and nginx

without comments

This took me some time to figure out, and I didn’t see any detailed posts or bug reports on how to fix this. Nginx doesn’t support HTTP 1.1 on proxy pass, meaning, when you place Node.JS behind a proxy (for load balancing purposes, or you just have multiple endpoints on port 80), websockets will not work properly, since HTTP 1.1 is a core requirement. You’ll know, when you get errors similar to this:

Java
1
2
Error during WebSocket handshake: 'Connection' header value is not 'Upgrade'
XMLHttpRequest cannot load ***. Origin *** is not allowed by Access-Control-Allow-Origin.

I’m running nginx 0.6.8, with nginx 1.0.11. To fix this, you need to upgrade to a later version of nginx (a development version), which supports HTTP 1.1 (albeit, experimentally), and then enable the proxy_http_version 1.1 parameter in your vhost configuration.

I’m doing this on Ubuntu.

First, let’s compile nginx:

Shell
1
2
3
4
5
6
7
8
9
10
11
12
13
cd /usr/src
wget http://nginx.org/download/nginx-1.1.13.tar.gz
sudo tar xzvf nginx-1.1.13.tar.gz
cd nginx-1.1.13
sudo ./configure --prefix=/etc/nginx --sbin-path=/usr/sbin --with-http_ssl_module
sudo make; sudo make install
/usr/sbin/nginx -V
# Something like this should show:
nginx version: nginx/1.1.13
built by gcc 4.6.1 (Ubuntu/Linaro 4.6.1-9ubuntu3)
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin --with-http_ssl_module

Next, we setup our vhost:

Shell
1
2
3
4
5
6
7
8
9
10
11
12
13
server {
listen 80;
server_name node.domain.com;
location / {
proxy_pass http://localhost:8000;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_redirect off;
proxy_http_version 1.1;
}
}

And now no more errors, and nodejs is working properly. Do note that this is a “bleeding edge” version of nginx, and could come with its own share of issues – so keep an eye out and test thoroughly!

Edit: If you’re still running into some problems, you can enable only xhr-polling/jsonp-polling in your Node.JS/socket.io configuration:

JavaScript
1
2
3
4
io.set('transports', [
'xhr-polling',
'jsonp-polling'
]);

Written by Nabeel

January 21st, 2012 at 7:48 pm

Posted in General,nginx

Domain updated!

without comments

I’m now using “nabeelio.com” – since it’s been my long-time nickname, and nsslive just doesn’t mean anything anymore. All links have been updated, the old site will just redirect here. Cheers!

Written by Nabeel

January 17th, 2012 at 10:30 am

Posted in General

Sphinx and CakePHP

with 2 comments

For a project, I’ve decided to use the Sphinx search engine, and was looking for behaviors for CakePHP, to just make it much easier to implement. Since I’m using Cake 2.0, I could only find something that was for < Cake 1.3. So I decided to update it for use with Cake2.0, and it’s working beautifully with pagination.

It’s located in my github site:

https://github.com/nshahzad/Sphinx-CakePHP

The usage is exactly the same as the original (the link to it is above). The only thing is that it’s assuming you have the sphinxapi.php (which comes with the Sphinx source) extracted into Vendor/sphinxapi/sphinxapi.php (that’s where App::import() will look for it).

Written by Nabeel

January 3rd, 2012 at 10:01 am

Posted in CakePHP,phpVMS

Installing Redmine on Ubuntu 11.04 w/nginx and mongrel

without comments

This one took me a few hours, but I’ve got my handy-dandy notes. I’m going to assume you’re got nginx installed, whether there are vhosts or not…

I’m also installing to /var/www/redmine

Java
1
2
3
4
5
6
7
sudo apt-get install mongrel ruby gems
cd /var/www
wget http://rubyforge.org/frs/download.php/75097/redmine-1.2.1.tar.gz
tar xzvf redmine-1.2.1.tar.gz
mv redmine-1.2.1 redmine
sudo chown www-data: redmine -R
sudo chmod 775 redmine -R

Next, we are going to patch Redmine, to work with Mongrel

Java
1
2
3
4
5
cd /var/www/redmine/config/initializers/
wget http://www.redmine.org/attachments/6146/rails_6440_patch.rb
wget https://gist.github.com/raw/826692/cb0dcf784c30e6a6d00c631f350de99ab99e389d/mongrel.rb
sudo chmod 775 . -R
sudo chown www-data: -R

Next, setup the right versions of Rails, etc

Java
1
2
3
gem install -v=2.3.14 rails
gem install rack -v=1.1.1
gem install rake -v0.8.7

Now setup MySQL:

Java
1
2
3
4
mysql -uroot -p
create user 'redmine'@'localhost' identified by 'password';
grant all privileges on `redmine%` . * to 'redmine'@'localhost';
create database redmine character set utf8;

And next, we configure and run the installer for Redmine. We are going to edit the database.yml, set it to match your above settings

Java
1
2
3
4
5
6
7
cd /var/www/redmine/config
mv database.yml.production database.yml
nano database.yml
cd /var/www/redmine
rake generate_session_store
RAILS_ENV=production rake db:migrate
RAILS_ENV=production rake redmine:load_default_data

Next, we start the server

Java
1
mongrel_rails start -e production -p 9001 -d

Next, create the nginx vhost, I created it as /etc/nginx/sites-enabled/redmine

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
server {
listen 80;
server_name YOUR_HOSTNAME_HERE;
root /var/www/redmine/public;
#error_log /var/log/nginx/redmine.log debug;
expires epoch;
location / {
expires epoch;
alias /var/www/redmine/public/;
try_files $uri/index.html $uri.html $uri @mongrel;
}
location @mongrel {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_pass_header Set-Cookie;
proxy_pass http://127.0.0.1:9001;
}
}

Written by Nabeel

October 3rd, 2011 at 6:11 pm

Posted in General,nginx

Tagged with ,

MySQL Diff Tool

with 6 comments

After searching for a while, I haven’t been able to find a tool which will show the diffs between two MySQL Databases. There are plenty to handle migrations, but migrations are tough when you’re writing an app which is install by an end-user. So I wrote a tool/class which will take the XML of a proper database (that file can be distributed in your package), and then will compare the XML schema against the schema in the current database.

Generate a MySQL Dump file:

Shell
1
mysqldump --xml --no-data testuser -utestuser -ptest1 > structure.xml

Then call the command line script (diffgen):

Shell
1
2
3
4
5
6
7
8
diffgen -utestuser -ptest1 -dtestuser -hlocalhost -fstructure.xml -tshow
-u Database User
-p Database Password
-d Database Name
-h Database Host
-f Dump File Path
-t "show" or "run" - show will output the SQL, "run" will run the SQL

There’s also a class file (which it is all from), which you can use to integrate into your own custom scripts (as-is the case with phpVMS, which is distributed with the structure.xml that is generated by my Phing build process, and it “shapes” the database on the remote server properly in an update script).

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
include 'MySQLDiff.class.php';
$params = ;
try {
$diff = new MySQLDiff(array(
        'dbuser' => 'testuser',
        'dbpass' => 'test1',
        'dbname' => 'testuser',
        'dbhost' => 'localhost',
        'dumpxml' => 'structure.xml',
    ));
} catch(Exception $e) {
echo $e->getMessage(); exit;
}
# This returns an array of what's missing in the database
try {
$diff_lines = $diff->getDiffs();
var_dump($diff_lines);
catch(Exception $e) {
echo $e->getMessage(); exit;
}
# This returns SQL queries which can be run to fix the database
try {
$diff_lines = $diff->getSQLDiffs();
var_dump($diff_lines);
} catch(Exception $e) {
echo $e->getMessage(); exit;
}
# This generates the SQL and actually runs all of them
try {
$diff_lines = $diff->runSQLDiff();
var_dump($diff_lines);
} catch(Exception $e) {
echo $e->getMessage(); exit;
}

The script can be downloaded from https://github.com/nshahzad/MySQLDiff

Written by Nabeel

April 12th, 2011 at 7:52 pm

Posted in General

Amazon PHP API

without comments

I couldn’t find a working PHP class for the Amazon API, which had Exception handling and some versatility. So I wrote one up. It’s a work-in-progress at the moment, but it’s available on GitHub:

http://github.com/nshahzad/AmazonAPI

The included README has detailed instructions. The class uses the __call() functionality, and you just pass the required parameters as a dictionary array. Requires some reading of the Amazon docs, but much more flexible.

PHP
1
2
include 'amazon.php';
$amz = new AmazonProductLookup('YOUR AWS KEY', 'YOUR SECRET KEY');

Written by Nabeel

September 29th, 2010 at 9:20 am

Posted in General

PHP class for Google Geocoder API

without comments

For a project I’ve been working on, I needed to access Google’s Geocoder API. I search for names (schools in this case), and return as much info as I can that Google has about it.

I’ve posted the class up on Github, it’s straightforward, and might help some people out:

http://github.com/nshahzad/Google-Geocoder

The usage is in the readme/displayed right on the github page. It uses cURL and JSON to keep the traffic transfered low. That also means you need the json_decode() function, which is in PHP 5.2 and up.

Happy 4th!

Written by Nabeel

July 4th, 2010 at 1:44 pm

Posted in General

Building php-fpm against Ubuntu PHP Packages

without comments

This is how I’ve been building php-fpm against the Debian PHP packages. It’ll be useful for when Ubuntu 10.04 (Lucid Lynx) Comes out with PHP 5.3. I do this from my home directory. It will download the package souce from Ubuntu, then compile php-fpm standalone against that.

Shell
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
sudo apt-get install php5-cli php5-cgi php5-common \
php5-curl php5-dev php5-gd php5-mcrypt \
php5-memcache php5-mysql php5-suhosin
# Get from the Debian repo
sudo apt-get build-dep php5-common
sudo apt-get -b source php5-common
# Change this to the PHP version being used!
# Look on http://launchpad.net/php-fpm/master to match it
export PHP_VER=5.2.10
wget "http://launchpad.net/php-fpm/master/0.6/+download/php-fpm-0.6-$PHP_VER.tar.gz"
tar -zxvf "php-fpm-0.6-$PHP_VER.tar.gz"
cd "php-fpm-0.6-$PHP_VER"
mkdir fpm-build && cd fpm-build
sudo ../configure --srcdir=../ \
--with-php-src="../../php5-5.2.10.dfsg.1" \
--with-php-build="../../php5-5.2.10.dfsg.1/cgi-build" \
--with-fpm-conf="/etc/php5/fpm/php-fpm.conf" \
--with-libevent="/usr/lib"
sudo make
sudo make install
sudo update-rc.d php-fpm defaults
# Resulting in:
Installing PHP FPM binary: /usr/local/bin/php-fpm
Installing PHP FPM config: /etc/php5/fpm/php-fpm.conf
Installing PHP FPM man page: /usr/local/man/man1/php-fpm.1
Installing PHP FPM init script: /etc/init.d/php-fpm
*** FPM Installation complete. ***
run:
`update-rc.d php-fpm defaults; invoke-rc.d php-fpm start`

Then, configure the php-fpm file. That should be it :)

Written by Nabeel

April 4th, 2010 at 10:54 am

Posted in General

A better way for nginx PHP config

with one comment

Doing some reconfiguration on my webserver (nginx) to make it easier to administer. My first goal was to get rid of this nastiness:

Java
1
2
3
4
5
6
7
8
9
10
server {
...
location ~ \.php$ {
include /etc/nginx/conf/fastcgi_params;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /var/path/to/$fastcgi_script_name;
}
}

It’s too verbose to copy/paste into each virtual host file. Instead, you can just combine the file into the /etc/nginx/conf/fastcgi_params file. I renamed it to php_params, and this is what it’s got:

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
location ~ \.php(.*)$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param DOCUMENT_URI $document_uri;
fastcgi_param DOCUMENT_ROOT $document_root;
fastcgi_param SERVER_PROTOCOL $server_protocol;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param GATEWAY_INTERFACE CGI/1.1;
fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;
fastcgi_param REMOTE_ADDR $remote_addr;
fastcgi_param REMOTE_PORT $remote_port;
fastcgi_param SERVER_ADDR $server_addr;
fastcgi_param SERVER_PORT $server_port;
fastcgi_param SERVER_NAME $server_name;
# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param REDIRECT_STATUS 200;
}

Now I don’t have to change it everywhere. So, instead, now I do:

Java
1
2
3
4
5
server {
...
# Include the PHP Fast-CGI Params
include /etc/nginx/conf/php_params;
}

Bam! 6 lines down to one, and much easier to administer. I like, I like.

Written by Nabeel

October 6th, 2009 at 5:23 pm

Posted in General,nginx