Category Archives: Uncategorized

NOIP daemon autostart after system restart on Raspberry Pi (Raspbian)

This short tutorial shows how to setup noip daemon to run automatically after system restart. OS used is Raspbian 3.18.7+ on Raspberry Pi 1 B+ device. Already installed and configured noip is assumed.

1. Create file /etc/init.d/noip2. Should be owned by root with 755 permissions. Put the code from https://gist.github.com/rtrzebinski/863458ed5a176fa94a6b into this file.

$ sudo su
# cd /etc/init.d
# touch noip2
# chmod 755 noip
# vim noip

# ls -l noip2 
-rwxr-xr-x 1 root root 1038 Apr 19 10:48 noip2

2. Add script to run commands:

# update-rc.d /etc/init.d/noip2 defaults 90

3. Restart device

# sudo reboot

4. Check if noip is up after reboot

$ ps aux | grep noip
nobody    2071  0.0  0.3   2484  1700 ?        Ss   10:54   0:00 /usr/local/bin/noip2

Noip will now start after every system reboot.

Allow SQLite to use foreign keys in Laravel 4

Because of backwards compatibility foreign key checking is by default disabled in SQLite databases. As current Laravel 4 version does not provide any elegant way of enabling that, a little hack is required to force foreign keys for SQLite connections.

Add the following code to the end of file app/start/global.php

if (DB::connection() instanceof Illuminate\Database\SQLiteConnection) {
  DB::statement(DB::raw('PRAGMA foreign_keys=1'));
}

Laravel 4 database seeding example

Database seeding is a convenient way to fill Laravel 4 application with test data, this can be useful while application developing, or testing. In provided example ‘users’ table will be seeded with test user data. Example table was previously created with Laravel Migrations which is described in this post.

First create seeding class for the table under app/database/seeds directory, in this case UserTableSeeder.php

class UserTableSeeder extends Seeder {

	public function run() {
		// delete existing db rows
		DB::table('users')->delete();
		// create new user
		User::create(array(
			'name' => 'test user 1',
			'email' => 'foo@bar.com',
			'password' => Hash::make('password')
		));
	}

}

Method run() deletes all existing users, then creates new user row with provided name, email and password (hashed with Hash::make() function). Please note that ‘User::create’ requires User model to be set up. By default User model is created in app/models, so there is no need of doing that in this particular case.

Next we need to add new seeder class to app/database/seeds/DatabaseSeeder.php

class DatabaseSeeder extends Seeder {

	/**
	 * Run the database seeds.
	 * @return void
	 */
	public function run() {
		Eloquent::unguard();
		$this->call('UserTableSeeder');
	}

}

And this is it, now simply call the following artisan command

$ php artisan db:seed

And check if users table contains test data

mysql> select * from users;
+----+-------------+-------------+--------------------------------------------------------------+----------------+---------------------+---------------------+
| id | name        | email       | password                                                     | remember_token | created_at          | updated_at          |
+----+-------------+-------------+--------------------------------------------------------------+----------------+---------------------+---------------------+
|  1 | test user 1 | foo@bar.com | $2y$10$e2hVN4Yf7.aEOHiVRmN5XORQcuIaHUDege5V9i9792Wfx8DFe03W2 | NULL           | 2014-08-10 14:11:02 | 2014-08-10 14:11:02 |
+----+-------------+-------------+--------------------------------------------------------------+----------------+---------------------+---------------------+

Laravel 4 database migrations example

Laravel 4 migrations provides a convenient way of versioning changes in application database structure. It uses Laravel Schema Builder to store database structure in php classes, this structure is then utilised to create/alter/delete database tables in database that is currently used by application. Schema Builder is database type independent, so any database supported by Laravel can be used. This makes extremely easy to change database type, and keep the same tables structure (for instance from MySQL to SQLite).

Database schema should be altered if any change in database structure has to be done. This way all developers can use the same schema version, as php files can be easily stored in version control system. One important thing to notice about migrations: always create new migration file when you want to alter existing table. Migration class that was used should not be changed.

Let’s create simple ‘users’ table with migrations. Table should contain: id, name, email, password, remember_token, created_at and updated_at fields. First thing to do is set up database connection, this should be done by altering app/config/database.php file. The most commonly MySQL will be used, this requires to set username, password, host, and database name in ‘mysql’ array. When database connection is set up go to project’s root directory, and run:

$ php artisan migrate:make create_users --create --table=users

This command will create a new migration file for users table in app/database/migrations directory (by default). File name contains current date, time, and underscored class name provided after ‘migrate:make’ (create_users). Full path to the file is in my case app/database/migrations/2014_08_10_131305_create_users.php. Edit this file to provide users table fields and details. Remember to always use artisan commands to create migration files, don’t create them manually.

CreateUsers class has 2 methods: up() and down(). Up is being called when ‘php artisan migrate’ command is run (this creates/alters table), down() is being called when ‘php artisan migrate:rollback’ is run (this rollbacks last migration, so deletes users table in this particular case).

Complete CreateUsers code:

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsers extends Migration {

	/**
	 * Run the migrations.
	 * @return void
	 */
	public function up() {
		Schema::create('users', function(Blueprint $table) {
			$table->engine = 'InnoDB';
			$table->increments('id');
			$table->string('name', 128)->nullable();
			$table->string('email', 256);
			$table->string('password', 256);
			// remember token is nullable by default
			$table->rememberToken();
			$table->timestamps();
		});
	}

	/**
	 * Reverse the migrations.
	 * @return void
	 */
	public function down() {
		Schema::table('users', function() {
			Schema::drop('users');
		});
	}

}

Now this class can be used to create table with structure defined in up() method, for this purpose simply run:

$ php artisan migrate

Than log in to mysql and check what tables was created (I assume that database was empty before).

mysql> show tables;
+------------------+
| Tables_in_sm2dev |
+------------------+
| migrations       |
| users            |
+------------------+

mysql> describe migrations;
+-----------+--------------+------+-----+---------+-------+
| Field     | Type         | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| migration | varchar(255) | NO   |     | NULL    |       |
| batch     | int(11)      | NO   |     | NULL    |       |
+-----------+--------------+------+-----+---------+-------+

mysql> describe users;
+----------------+------------------+------+-----+---------------------+----------------+
| Field          | Type             | Null | Key | Default             | Extra          |
+----------------+------------------+------+-----+---------------------+----------------+
| id             | int(10) unsigned | NO   | PRI | NULL                | auto_increment |
| name           | varchar(128)     | YES  |     | NULL                |                |
| email          | varchar(256)     | NO   |     | NULL                |                |
| password       | varchar(256)     | NO   |     | NULL                |                |
| remember_token | varchar(100)     | YES  |     | NULL                |                |
| created_at     | timestamp        | NO   |     | 0000-00-00 00:00:00 |                |
| updated_at     | timestamp        | NO   |     | 0000-00-00 00:00:00 |                |
+----------------+------------------+------+-----+---------------------+----------------+

Migrations table contains data internally used by Laravel to manage migrations, users table contains fields previously defined in CreateUsers class.

Universal PHP error and exception handler class for Codeigniter

One of the php disadvantages is that internal PHP functions uses built-in error reporting system, while object oriented extensions use exceptions. In this article I’ve presented custom Codeigniter class that handles all uncaught exceptions thrown during a runtime. That solution works sufficiently with modern code, but standard php errors are not under its control. My aim was to handle all system wide errors and exceptions within just one class and in the same way.

A simple solution to achieve this is to use set_error_handler() function. It’s similar to set_exception_handler(), but expects error details instead of exception object. When handler function is called, it throws new ErrorException with error details passed to the construct. This simple modification translates every ocurred error into uncaught exception, so php errors and exceptions are treated exactly the same way. Functions like printException() and logException() can be reused, so there is no need to write new functions just for regular errors purpose.

Another issue is controlling which errors should be handled. I’ve decided to check the occured error level against current error_reporting value, if bitwise ‘and’ result is 0, then error is just ignored. This allows you to set error_reporting(E_ALL ^ NOTICE) to ignore all notices, just like in default php error handling mechanism.

One signifficant thing to notice while using this solution is that every error handled by provided class will stop the script. So if you have error_reporting(E_ALL) set, every notice/warning will terminate the script. This happens because execution will always stop after the exception_handler is called.

class ErrorHandler extends BaseLibrary {

    protected $oException;

    public function __construct() {
        parent::__construct();
        set_exception_handler(array($this, 'handleException'));
        set_error_handler(array($this, 'handleError'));
    }

    /**
     * Handles errors regarding error_reporting value
     * @param int $errno
     * @param string $errstr
     * @param string $errfile
     * @param string $errline
     * @throws ErrorException
     */
    public function handleError($errno, $errstr, $errfile, $errline) {
        if (error_reporting() & $errno) {
            throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
        }
    }

    /**
     * Handles exception regarding ENVIRONMENT constant
     * Execution will stop after this function is called.
     * @param Exception $oException
     */
    public function handleException(Exception $oException) {
        $this->oException = $oException;

        switch (ENVIRONMENT) {
            case 'development':
            case 'testing':
                $this->printException();
                $this->logException();
                break;
            case 'production':
                $this->logException();
                break;
        }
    }

    /**
     * Prints readable exception content to the client
     */
    private function printException() {
        print("<pre>");
        print("Code: " . $this->oException->getCode() . "<br/>");
        print("Message: " . $this->oException->getMessage() . "<br/>");
        print("File: " . $this->oException->getFile() . "<br/>");
        print("Line: " . $this->oException->getLine() . "<br/>");
        print("Trace: " . $this->oException->getTraceAsString() . "<br/>");
        print("</pre>");
    }

    /**
     * Logs exception in application/logs
     * Requires $config['log_threshold'] to be >= 1 (application/config/config.php)
     */
    private function logException() {
        $this->CI->logger->logException($this->oException);
    }

}

Logger library for Codeigniter

Codeigniter framework provides number of useful functions for Error Handling (described on http://ellislab.com/codeigniter/user-guide/general/errors.html). One of them – log_message(‘level’, ‘message’) writes a new log line to /application/logs/[log file name]. Great adventage of using this solution is that developer doesn’t have to create (open, close etc.) log files on filesystem. Just one function does the job.

Below you’ll find a code of Logger class that provides additional improvements to events logging. This class provides additional layer for logging proccess. It uses log_message(‘level’, ‘message’) for logging user – system interactions, and exceptions.

class Logger extends BaseLibrary {

    private $oUser;

    public function __construct() {
        parent::__construct();
        $this->oUser = $this->CI->sessionmanager->getUser();
    }

    /**
     * Logs action to log file as 'info'
     * Requires $config['log_threshold'] to be >= 3 (application/config/config.php)
     * @param string $strAction name of the action user takes
     * @param array $arrData optional details of taken action
     */
    public function logAction($strAction, array $arrData = null) {
        $strMessage = '';
        $strMessage .= 'action: ' . $strAction . ' ';
        $strMessage .= 'ip: ' . $this->CI->input->ip_address() . ' ';

        // add user id if any logged in
        if ($this->oUser->getId()) {
            $strMessage .= 'user: ' . $this->oUser->getId() . ' ';
        }

        // add data if provided
        if ($arrData) {
            $strMessage .= 'data: ' . str_replace(array("\n", "\r", "    "), '', print_r($arrData, true));
        }

        log_message('info', $strMessage);
    }

    /**
     * Logs exception to log file as 'error'
     * Requires $config['log_threshold'] to be >= 1 (application/config/config.php)
     * @param Exception $oException
     */
    public function logException(Exception $oException) {
        $strMessage = '';
        $strMessage .= $oException->getMessage() . ' ';
        $strMessage .= $oException->getCode() . ' ';
        $strMessage .= $oException->getFile() . ' ';
        $strMessage .= $oException->getLine();
        $strMessage .= "\n" .  $oException->getTraceAsString();
        
        log_message('error', $strMessage);
    }

}

BaseLibrary simply provides a refrence to the original CodeIgniter object:

class BaseLibrary {

    protected $CI;

    public function __construct() {
        $this->CI = & get_instance();
    }

}

Classes should be stored in /application/libraries. I recommend to auto load both of them.

Logger class provides logAction() method for logging user actions, and logException() for logging exceptions. Usage of logAction() is convinient for instance in CRUD models:

// within create() method
$this->logger->logAction('question created', (array) $this);

// within update() method
$this->logger->logAction('question updated', (array) $this);

// within delete() method
$this->logger->logAction('question deleted', (array) $this);

Just one line of code writes a fully detailed log, including: date/time, client ip address, id of logged user (if any), details array (i.e. model object dump). Example log line for object create() method:

INFO  - 2014-01-20 18:46:12 --> action: course created ip: 89.65.208.66 user: 2 data: Array([0] => Array([CoursecourseId] => 0[CoursecourseName] => Some name[CoursecourseName_dirty] => 1[CoursecourseQuestionsAmount] => [CoursecourseAveragePoints] => [CourseuserId] => 2))

Any array with details to be logged can be provided in the second parameter:

// custom example

$this->logger->logAction('wall painted', array('color' => 'green', 'foo' => $bar));

Simple way to use custom PHP interfaces within Codeigniter application

Codeigniter itself doesn’t provide any built-in method to use custom PHP interfaces. So if you want to implement some in your class, this requires a little hacky solution.

First create an extension class for Codeigniter loader. This will let you load interfaces using $this->load->iface() method (‘interface’ is a reserved PHP word, so it can’t be used as a function name). File path should be: /application/core/MY_Loader.php

class MY_Loader extends CI_Loader {

  public function __construct() {
    parent::__construct();
  }

  public function iface($strInterfaceName) {
    require_once APPPATH . '/interfaces/' . $strInterfaceName . '.php';
  }

}

Now create a new folder for interface files: /application/interfaces. This is an example interface /application/interfaces/CrudModelInterface.php code:

interface CrudModelInterface {
    public function create();
    public function load();
    public function update();
    public function delete();
}

To implement a particular interface in your class just load it right before the class beginning. In this case it’s loaded in model file, so get_instance() finction must be used instead of $this variable.

get_instance()->load->iface('CrudModelInterface'); // interface file name

class User extends CI_Model implements CrudModelInterface {

(...)

Codeigniter Sparks oAuth 2 plugin example controller

This post shows an example controller class which allows you to log in to Codeigniter application via external oAuth 2 system like facebook or google. It uses multi-provider oAuth 2 client package from Sparks repository. Sparks is a package management system for Codeigniter that allows you to install external libraries. I recommend to do it with ssh, but there is also a possibility of manual installation for those who can’t use shell.

You can install oAuth 2 package from http://getsparks.org/packages/oauth2/versions/HEAD/show

Things to notice about oAuth 2 package:

1. It uses url helper, so you should load it (I recommend auto loading – http://ellislab.com/codeigniter%20/user-guide/general/autoloader.html, url helper is one of the most commonly used Codeigniter helper), otherwise the following error will be shown:

Fatal error: Call to undefined function site_url() in /sparks/oauth2/0.4.0/libraries/Provider.php on line 76

2. I’ve found a bug in /sparks/oauth2/0.4.0/libraries/Provider/Blooie.php, function url_access_token() is not closed (just add } afterwords to fix it).
Not many use blooie, thats why this is not fixed yet I guess 🙂

3. Codeigniter session must be initialized, see http://ellislab.com/codeigniter%20/user-guide/libraries/sessions.html

Every oAuth service must provide you with an id, and secret string to make you use it. That usually requires to register an app in oAuth provider system. Presented class reads provider data from config file (db is also a good or even better idea). The following is an empty example for facebook and google credentails stored in /application/config/config.php:

$config['oauthProvidersData'] = array(
    'facebook' => array(
        'id' => '',
        'secret' => ''
    ),
    'google' => array(
        'id' => '',
        'secret' => ''
    )
);

You should obviously fill it with a proper data taken from oAuth provider. Nice thing about this solution is when you want to add new oAuth service, there is no need to modify anything more than config file, (much better than hardcoding it within class file).

My goal is to let user just click on facebook or google icon, and be logged. During the first visit user must always accept permissions of our app, and that’s it. If user is visiting controller and agrees for permissions for the first time, than a new user (db row) will be created. During next login the user will be loaded from db, basing on oAuth user id (taken from a provider), and the name of a service. These two variables are always unique together, so it is safe to base on that set of credentials.

Path to run controler is /login/oauth/{providerName} considering mod_rewite being activated. I use my own User model, and SessionManager library, but because of the comments it should be easy to understand what they do.

class Login extends CI_Controller {

    public function __construct() {
        parent::__construct();
    }

    /**
     * Gets user data array from oauth service
     * than runs loginOauthUser
     * @param string $strProviderName
     */
    public function oauth($strOauthProviderName) {
        $this->load->spark('oauth2/0.4.0');

        // create oauth provider object
        $arrOauthProvidersData = $this->config->item('oauthProvidersData');
        $oProvider = $this->oauth2->provider($strOauthProviderName, $arrOauthProvidersData[$strOauthProviderName]);

        // get user data array
        if ($this->input->get('code')) {
            $strToken = $oProvider->access($this->input->get('code'));
            $arrOauthUserData = $oProvider->get_user_info($strToken);
            $this->loginOauthUser($strOauthProviderName, $arrOauthUserData);
        } else {
            $strAuthUrl = $oProvider->authorize();
            // redirects this page which is needed to exchange data between servers
            redirect($strAuthUrl);
        }

        // user canceled permissions request - go to home page
        if ($this->input->get('error')) {
            redirect(base_url());
        }
    }

    /**
     * Logs user in, if it exists in database
     * Creates new one if doesn't
     * Restores session and redirects to home page after that
     * @param string $strOauthProvider
     * @param array $arrUserData
     */
    private function loginOauthUser($strOauthProviderName, $arrOauthUserData) {
        $this->load->model('User');
        $oUser = new User();
        $oUser->setOauthId($arrOauthUserData['uid']);
        $oUser->setOauthProvider($strOauthProviderName);

        try {
            // try to authorize
            $oUser->authorize(); // throws an exception on faliture, loads object on success
        } catch (Exception $exc) {
            // if log in incorrect -> user doesn't exist -> create new one
            $oUser->setName($arrOauthUserData['name']);
            $oUser->setEmail($arrOauthUserData['email']);
            $oUser->create();
        }

        // write user data to session and go to main page
        $this->sessionmanager->restoreUserData($oUser);
        redirect(base_url());
    }

}

Exceptions handler for Codeigniter

While developing web applications I use php exceptions model for handling errors, which is similar to ones used in java and other objective languages. When an error occurs you can throw an exception, then an Exception object is created. Exception can then be caught somewhere else in the code, where you can decide what to do in case of a particular error, here an exception object can be used to read details about the error. You can also create your own Exception class, or use one of the existing e.g. in SPL (see http://www.php.net/manual/en/spl.exceptions.php). This helps you recognize which kind of error occured, not just if (you can throw many exceptions in one function), and write many variants of application behaviour for different kinds of errors (exceptions thrown). Everything is explained in php manual (http://php.net/exceptions), read for details.

My problem was that very often my exception was caught just to be passed to the error class (then write to log file, print on screen etc.). I didn’t like repeating try/catch section of the code looking like this:

try {
  // code throwing exception(s)
} catch (Exception $exc) {
  new Error($exc);
}

In the above example Error class construct should be considered as an exception handler.

Built-in php (obviously 5, I believe nobody uses php 4 nowadays) set_exception_handler function comes of help. It lets you define a handler function used if an exception is not caught within a try/catch block. Presented ExceptionHandler class is a Codeigniter library, it should be auto loaded so handle function is always set as default handler (in constructor). Handle must be public, otherwise set_exception_handler won’t work. Class also contains functions for printing and logging exceptions details (you can add whatever you want to happen when your system is in trouble). You can obviously use it for handling exceptions in try/catch blocks, but it’s not necessary. Once library’s loaded, it’s object is already created under $this->librarynamenocapitals, so ‘manual’ run looks like this:

try {
  // code throwing exception(s)
} catch (Exception $exc) {
  $this->exceptionhandler->handle($exc);
}

You can also add other behaviours to this class such as: send email to admin, or return just particular answer code (nice in REST web services). You can change this depending on ENVIRONMENT constant mode (set in index.php, you should know this before writing anything in Codeigniter).

class ExceptionHandler {

    protected $oException;

    public function __construct() {
        // set default uncaught exceptions handler
        set_exception_handler(array($this, 'handle'));
    }

    /**
     * Handles exception regarding ENVIRONMENT constant
     * @param Exception $oException
     */
    public function handle(Exception $oException) {
        $this->oException = $oException;

        switch (ENVIRONMENT) {
            case 'development':
            case 'testing':
                $this->printException();
                $this->logException();
                break;
            case 'production':
                $this->logException();
                break;
        }
    }

    /**
     * Prints readable exception content to the browser
     */
    private function printException() {
        print("
");
        print("Code: " . $this->oException->getCode() . "
");
        print("Message: " . $this->oException->getMessage() . "
");
        print("File: " . $this->oException->getFile() . "
");
        print("Line: " . $this->oException->getLine() . "
");
        print("Trace: " . $this->oException->getTraceAsString() . "
");
        print("
");
 }

 /**
 * Logs exception in application/logs
 * Requires $config['log_threshold'] to be >= 1 (application/config/config.php)
 */
 private function logException() {
 log_message('error', $this->oException->getMessage()
 . ' ' . $this->oException->getCode()
 . ' ' . $this->oException->getFile()
 . ' ' . $this->oException->getLine()
 . "\n" . $this->oException->getTraceAsString());
 }

}

Please read this article if you want to extend provided class by handling also regular PHP errors.

Przyczyny błędu ERROR 1005 (HY000) Can’t create table (errno: 150) w MySQL

Pojawiający się podczas próby dodania do bazy danych tabeli błąd “Can’t create table (errno: 150)” związany jest ze zdefiniowanymi w niej kluczami obcymi. MySQL sprawdza poprawność klucza obcego, porównując go z kluczem obcym w tabeli z którą tworzy relację. Ważne jest żeby tabela do której odnosi się klucz obcy istniała, a pole na które  wskazuje, było dokładnie identyczne z polem wskazującym. Poniżej znajduje się lista potencjalnych przyczyn wystąpienia błędu wraz z rozwiązaniami.

Continue reading