Category Archives: Uncategorized

Use Composer with Kohana 3.3

Kohana 3.3 has a file named “composer.json” in the root of the project, however it is not configured for Kohana and Composer is not installed.

This example is tested on a Mac. Windows users will need to install Composer from the instructions on the Composer project site, at http://getcomposer.org/doc/00-intro.md.

Install Composer

First, modify composer.json to tell composer where to install libraries.

to:

{
	"config": {
		"vendor-dir": "application/vendor"
	},
	"require": {
		"phpunit/phpunit": "3.7.24",
		"phing/phing": "dev-master"
	}
}

Open a terminal and navigate to the root of your Kohana project.

curl -sS https://getcomposer.org/installer | php
php composer.phar install

Modify Kohana’s bootstrap.php File

Add this to bootstrap. Right above the router configuration is a good spot.

/**
 * Autoload composer libraries
 * 
 */
require APPPATH . 'vendor/autoload.php';

Adding a Library

You can either edit composer.json with your required library (and then re-run the install command above), or use the composer require verb from the command line to add the library, which also modifies composer.json.

php composer.phar require "monolog/monolog" "1.6.0"

The monolog package page is https://packagist.org/packages/monolog/monolog. Note that you need the package name for the first parameter and the version for the second parameter.

Delete Old Files on Amazon AWS S3

If you have a script to automatically back up to Amazon S3 from your server, it is good to limit the age of stored backups.

This bash script allows you to use s3cmd to do just that. You specify the bucket to process and the age os files to retain.

Important: You must first install and configure s3cmd.

#!/bin/bash
 
usage (){
  echo " "
  echo Usage: s3-del-old "bucketname" "time"
  echo Example: s3-del-old \"mybucket\" \"30 days\"
  echo " "
  echo "Do not include a leading slash in bucketname."
  echo " "
}
 
# if incorrect # parameters, show usage
if [ $# -lt 2 ]; then
  usage
  exit 2
elif [ $# -gt 2 ]; then
  usage
  exit 2
fi
 
# don't allow leading slash in bucketname
firstchar=${1:0:1}
if [ $firstchar = "/" ]; then
  echo "ERROR: Do not start bucketname with a slash."
  usage
exit 2
fi
 
# don't allow "s3:" in beginning of filename
teststring=${1:0:3}
teststring=${teststring,,}
if [ $teststring = "s3:" ]; then
  echo "ERROR: Do not start bucketname with \"s3:\""
  usage
exit 2
fi
 
# transform first parameter into fully formed s3 bucket parameter with trailing slash star
target='s3://'${1%/}'/*'
 
s3cmd ls $target | while read -r line;
do
  create_date=`echo $line | awk '{print $1,$2}'`
  create_date_unixtime=`date -d"$create_date" +%s`
  older_than_unixtime=`date -d"-$2" +%s`
  if [[ $create_date_unixtime -lt $older_than_unixtime ]]
  then
    filename=`echo $line|awk '{print $4}'`
    if [[ $filename != "" ]]
    then
      echo deleting $filename $create_date
      s3cmd del $filename
    fi
  fi
done;

Use Chrome securely from Starbucks via SSH SOCKS

Do you have a server that you can access with OpenSSH? Do you want to be able to browse the web, even non-SSL, unencrypted pages, without others on the network being able to see what you’re looking at or even hijacking your sessions? Given the existence of Firesheep, it is really easy for even unsophisticated users to hijack a web browsing session.

The method I’m presenting is easy and effective. OpenSSH makes this a snap. Your web browsing packets will be routed via an encrypted connection to your server.

Create a SOCKS Proxy Connection on localhost

First, in a terminal, open a SOCKS connection to your server with OpenSSH. Just add “-D 9999″ to your normal SSH command. This will create a SOCKS proxy on localhost at port 9999.

ssh -D 9999 username@myserver.com

Depending on your configuration, you may need to enter your server account password. Whatever your normal authentication is for SSH. This will even open a normal SSH session, you will get a shell prompt on the server like normal. If you do not want a shell prompt, use “-ND” instead of “-D” and the

You now have a proxy on your local computer using SOCKS on port 9999. Now we just need to use it.

Install Switchy! in your Chrome browser

This can be easily found in the Chrome Web Store.

Use your Shiny New SOCKS Proxy

Open the Switchy! Options dialog. Type the a name for this proxy in Profile Name. On the SOCKS Host line, enter “localhost” in the first blank and “9999” for the Port. Click the Save button. You are using a SOCKS proxy running on your localhost.

Then, select the proxy by clicking the Switchy! icon in Chrome and selecting the proxy name you just entered.

You are now using a secure connection to browse the web. Note that someone on the network where your server is hosted can still snoop your traffic, but not in the Starbucks where your are sitting.

View/download a file not in the public directory with PHP

When you need to give users access to files that are not in the public directory, where you cannot simply use an anchor tag with an “href”, you need to do a bit of work. For example, if you’ve created an authentication system where only authenticated users can download or view a file, this can be necessary.

$filename = 'something';
$file_path = '/somepath/to/the/file/';
$file_fullpath = $file_path . $filename;
//
//
if (!file_exists($file_fullpath)) {
    header("HTTP/1.0 404 Not Found");
    return;
}
//
// get the mime type
$finfo = finfo_open(FILEINFO_MIME_TYPE); 
$mimeType = finfo_file($finfo, $file_fullpath);
//
// calc values for header
$size = filesize($file_fullpath);
$time = date('r', filemtime($file_fullpath));
$fm = @fopen($file_fullpath, 'rb');
if (!$fm) {
    header('HTTP/1.0 505 Internal server error');
    return;
}
$begin = 0;
$end = $size;
if (isset($_SERVER['HTTP_RANGE'])) {
    if (preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches)) {
        $begin = intval($matches[0]);
        if (!empty($matches[1])) $end = intval($matches[1]);
    }
}
//
// create http header
if ($begin > 0 || $end < $size) {
    header('HTTP/1.0 206 Partial Content');
}else {
    header('HTTP/1.0 200 OK');
}
header('HTTP/1.0 200 OK');
header("Content-Type: $mimeType");
header('Cache-Control: public, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Accept-Ranges: bytes');
header('Content-Length:' . ($end - $begin));
header("Content-Range: bytes $begin-$end/$size");
header("Content-Disposition: inline; filename=$filename");
header("Content-Transfer-Encoding: binary\n");
header("Last-Modified: $time");
header('Connection: close');
// output the file
$cur = $begin;
fseek($fm, $begin, 0);
while (!feof($fm) && $cur < $end && (connection_status() == 0)) {
    print fread($fm, min(1024 * 16, $end - $cur));
    $cur+= 1024 * 16;
}

There you have it. Your user can click the link for the file, which then runs this code. In my case, this is in a Kohana controller.

The files are not stored in a public directory, so unauthenticated users cannot access them.

If a file is created on the fly, like a PDF of an invoice, this will also work.

Create a Drupal site on an Ubuntu Server

This will help you quickly install a Drupal site on an Ubuntu server.

This is my script for this purpose. Use it as you will. This procedure assumes that you have already installed Apache, MySQL, phpMyAdmin and PHP. It also assumes that you are familiar with everything. This is probably not a beginner’s guide, but an aid to someone more experienced that wants to install Drupal quickly.

Create and run a shell script to create your site

Use this template to create a shell script that will create your site. Create a text file from the following template called “make_dru.sh” (in your home directory is fine). Modify lines 7 to 17 for your installation. Then use “chmod +x make_dru.sh” and execute the script with “sudo ./make_dru.sh”.

#!/bin/bash
#
# make drupal project
#

# 
OWNER="andrew" 			# change to your username
GROUP="staff"			# change to your username or the group that will work on the site
DRUPAL_URL="http://ftp.drupal.org/files/projects/drupal-6.17.tar.gz" # update to the current version, if there is one
SITESROOT="/usr/local/var/www"  # change to the directory where you put website directories
URL="www.sitename.com"		# change to your site's address

# database.php parameters
DBUSER="sitename"		# change to something meaningful
DBPWD="passwordgoeshere"		# change to a long password
DBHOST="localhost"		# leave alone
DBDATABASE=$DBUSER		# leave alone
 
#
# make sure this is run as root
#
if [[ $UID -ne 0 ]]; then
    echo "Not running as root"
    exit
fi
 
if [ ! -d $SITESROOT ]; then
	echo "$SITESROOT directory does not exist"
	exit
fi
 
#
# check for existence of the specified user owner
#
/bin/egrep  -i "^$OWNER" /etc/passwd > /dev/null
if [ ! $? -eq 0 ]; then
   echo "User $OWNER, which is specified as the owner, does not exist in /etc/passwd"
   exit
fi
 
#
# check for existence of the specified group
#
/bin/egrep -i "^$GROUP" /etc/group > /dev/null
if [ ! $? -eq 0 ]; then
   echo "$GROUP, which is specified as the group to use, does not exist in /etc/group"
   exit
fi
 
#
# change to the siteroot directory
#
cd $SITESROOT
 
if [ -d $URL ]; then
	echo "$SITESROOT/$URL directory already exists"
	exit
fi 
 
mkdir $URL
chown $OWNER:$GROUP $URL
cd $URL
 
#
# get Drupal
#
echo 'get Drupal'
wget -O drupal.tgz $DRUPAL_URL
tar -xzvf drupal.tgz
find . -maxdepth 1 -type d -name 'drupal*' -exec mv {} public \;
sudo chown -R $OWNER:$GROUP public
find . -type d -exec chmod g+ws {} \;
 
#
# temporarily allow write to settings
#
cp public/sites/default/default.settings.php public/sites/default/settings.php
chmod a+w public/sites/default/settings.php
chmod a+w public/sites/default
 
#
# logs
#
echo "set up logs"
mkdir logs
sudo chown $OWNER:www-data logs
chmod g+ws logs
touch logs/error.log
touch logs/combined.log
 
#
# create Apache virtual site
#
echo creating Apache virtual site file in /etc/apache2/sites-available
echo "
	ServerName $URL
	DocumentRoot $SITESROOT/$URL/public
	DirectoryIndex index.php
	LogLevel warn
	ErrorLog $SITESROOT/$URL/logs/error.log
	CustomLog $SITESROOT/$URL/logs/combined.log combined

" > /etc/apache2/sites-available/$URL
 
#
# finish up
#
echo -e "Drupal website was created in: $SITESROOT/$URL\n"
echo -e "To finish, do the following:\n"
echo "1. Enable site with: sudo a2ensite $URL"
echo "2. Restart Apache with: sudo /etc/init.d/apache2 restart"
echo "3. Make a crontab entry ('sudo crontab -e') like: 0 * * * * wget -O - -q -t 1 http://$URL/cron.php"
echo -e "4. Create a MySQL database with:\n"
echo -e "\t     user: $DBUSER"
echo -e "\t      pwd: $DBPWD"
echo -e "\t     host: $DBHOST"
echo -e "\t database: $DBDATABASE"
echo "5. Open the site in your browser and finish the set-up."
echo "6. Remove write privileges with: sudo chmod og-w public/sites/default/settings.php"
echo "   ..and: sudo chmod og-w public/sites/default"

Create the database and user with phpMyAdmin

  • click the “Privileges” tab and add a new user
  • in the “User name” field, enter the sitename that you entered for DBUSER in the script
  • in the Host field, select “Local”
  • enter or generate a password – make it a long one, like 20 characters
  • in the Database for User list, select “Create database with same name and grant all privileges”
  • click Go

Enable the new Drupal website

This will tell Apache to enable the virtual site that was made in the script and then restart Apache.

sudo a2ensite www.sitename.com
sudo /etc/init.d/apache2 restart

Configure the site

Open site in browser and configure it

Remove temporary write privileges

During site creation, write privileges were needed, after site set-up, remove them. In a shell, while in the sites directory (where the public directory is run these commands:

sudo chmod og-w public/sites/default/settings.php
sudo chmod og-w public/sites/default

Ubuntu command line: see PDF of a man page

So, you use the command line. And, you’d like to look at a command’s manual page.

Wouldn’t it be handy to open the page into another window, nicely formatted, all typeset and neat? That is exactly what this little script will do.

I keep my personal scripts and executables in ~/bin (the bin directory inside my home directory). My ~.profile file in Ubuntu already had that in the path, if ~/bin exists.

If needed, create ~/bin:

mkdir ~/bin

Create a shell script called ~/bin/gman with these lines:

#!/bin/sh -e
man -t $1 | ps2pdf - > "/tmp/$1.man.pdf"
gnome-open "/tmp/$1.man.pdf"

Make the shell script executable with:

chmod +x ~/bin/gman

If needed, exit your shell and open it back up again. This would be to ensure that ~/bin is detected and added to your PATH.

Then, to use it, just type gman and the command you are interested in, ie. grep.

gman grep

This will show you a beautiful, formatted document: