Get MySQL version in CakePHP 3

by on Mar.27, 2015, under CakePHP, PHP

You need to import ConnectionManager:

use Cake\Datasource\ConnectionManager;
$stmt = ConnectionManager::get('default')->query('SELECT version() as v');
$stmt->execute();
echo $stmt->fetch('assoc')['v'];

More on executing CakePHP custom queries, here.

Comments Off more...

Get browser plugins with javascript

by on Mar.27, 2015, under Javascript & Ajax

for (i = 0; i < navigator.plugins.length; i++) 
{
   plugin = navigator.plugins[i];
   document.write(plugin.name);
   document.writeln(" - ");
   document.write(plugin.filename);
   document.write("<br><br>");
}
Comments Off more...

Generating POT Files in CakePHP 3

by on Mar.20, 2015, under CakePHP, PHP

cakePHP 3 book – i18n

The i18n features of CakePHP use po files as their translation source. This makes them easily to integrate with tools like poedit and other common translation tools.

The i18n shell provides a quick and easy way to generate po template files. These templates files can then be given to translators so they can translate the strings in your application. Once you have translations done, pot files can be merged with existing translations to help update your translations.

1. Open cmd
2. change directory to cakephp application for ex.

cd C:\xampp\htdocs\myapps\cakephp\

3. Execute:

bin\cake i18n extract

To extract POT files from Plugins:

bin\cake i18n extract --plugin myPluginName

To translate .pot files, open them with poedit, translate your texts and save the .pot file as .po file in \src\Locale\en_US\default.po (or whatever is your locale).

Comments Off more...

Sanitize data coming out of the database in cakephp 3

by on Mar.20, 2015, under CakePHP, PHP

A security measure that most programmers forget to take when building database oriented applications is to sanitize-validate data coming out of the database. Let’s see how can we sanitize our data in cakePHP 3.

cakePHP 3 book – Entities

Create your Entity for ex. Country:

namespace App\Model\Entity;
 
use Cake\ORM\Entity;
 
class Country extends Entity
{
 
    protected $_accessible = [
        'name' => true,
        'code' => true,
        '*' => false,
    ];
 
    protected function _getCode($code)
    {
        return substr(preg_replace('/[^A-Z]/', '', strtoupper($code)), 0, 2);
    }
 
    protected function _getName($name)
    {
        return ucwords(substr(preg_replace('/[^a-zA-Z\(\);\' ]/', '', $name), 0, 50));
    }
}
Comments Off more...

Validating and Sanitizing data in CakePHP 3

by on Mar.20, 2015, under CakePHP, PHP

CakePHP 3 book – Validators

CakePHP 3 book – Table Objects

CakePHP 3 book – Saving data

Countries Table SQL schema:

CREATE TABLE IF NOT EXISTS `countries` (
  `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(50) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'Uknown', 
  `code` VARCHAR(2) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'UN', 
  `modified` DATETIME NULL,
  `created` DATETIME NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`),
  UNIQUE KEY `code` (`code`),
  KEY `created` (`created`),
  KEY `modified`	(`modified`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

In your Table Model for ex. CountriesTable append necessary use references:

use Cake\Validation\Validator;
use Cake\ORM\RulesChecker;
use Cake\ORM\Rule\IsUnique;
use Cake\Event\Event, ArrayObject;

Add validationDefault function to CountriesTable class:

public function validationDefault(Validator $validator)
{
    $validator->provider('custom', 'App\Model\Validation\MyValidation');
 
    $validator 
        ->requirePresence('name', 'create')
        ->notEmpty('name')
        ->add('name', 'minlength',  ['rule'  =>  ['minLength', 1]])
        ->add('name', 'maxlength',  ['rule'  =>  ['maxLength', 50]])
        ->add('name', 'regex',      ['rule'  =>  'countryname', 
            'provider' =>  'custom'])
 
        ->requirePresence('code', 'create')
        ->notEmpty('code')
        ->add('code', 'minlength',  ['rule'  =>  ['minLength', 2]])
        ->add('code', 'maxlength',  ['rule'  =>  ['maxLength', 2]])
        ->add('code', 'regex',      ['rule'  =>  'countrycode', 
            'provider' =>  'custom'])
	;
 
	return $validator;
}

Create class src/Model/Validation/MyValidation:

namespace App\Model\Validation;
use Cake\Validation\Validation;
 
class MyValidation extends Validation
{
 
    public static function countryname($check)
    {
        if (is_array($check)) {
            extract(static::_defaults($check));
        }
 
        if (empty($check) && $check != '0') {
            return false;
        }
 
        return self::_check($check, '/^[a-zA-Z\(\)\;\' ]+$/');
    }
 
    public static function countrycode($check)
    {
        if (is_array($check)) {
            extract(static::_defaults($check));
        }
 
        if (empty($check) && $check != '0') {
            return false;
        }
 
        return self::_check($check, '/^[A-Z]+$/');
    }
 
}

Add function buildRules for the last validation rules:

public function buildRules(RulesChecker $rules)
{
    $rules->add($rules->isUnique(['name']));
    $rules->add($rules->isUnique(['code']));
 
    return $rules;
}

Sanitize data before validation:

public function beforeMarshal(Event $event, ArrayObject $data, ArrayObject $options)
{
	$data['code'] = substr(preg_replace('/[^A-Z]/', '', strtoupper($data['code'])), 0, 2);
	$data['name'] = ucwords(substr(preg_replace('/[^a-zA-Z\(\);\' ]/', '', $data['name']), 0, 50));
}
Comments Off more...

How to configure session in CakePHP 3

by on Mar.17, 2015, under CakePHP, PHP

Let’s see how can we configure session in cakePHP to something safer.

1. Open config/app.php file
2. Scroll down to the end of file and locate:

'Session' => [
    'defaults' => 'php',
],

and change it to this:

'Session' => [
    'defaults'  =>  'database',
	'cookie'    =>  'webapptest',
	'timeout'   =>  24,     //minutes
	'ini'       =>  [
		'session.gc_divisor'        =>  1000,
		'session.cookie_secure'     =>  true,
		'session.cookie_path'       =>  '/',
		'session.cookie_domain'     =>  'your_domain_name_or_subdomain',
		'session.cookie_httponly'   =>  true,
		'session.cookie_lifetime'   =>  1440,   //seconds
	],
],
Comments Off more...

CakePHP 3 – Force all actions to require SSL

by on Mar.16, 2015, under CakePHP, PHP

Let’s see how we can force all actions to require SSL and how to tell cakePHP to redirect to the ssl version of our application.

We are going to edit src/Controller/AppController class.

Add use directive:

use Cake\Event\Event;

Create function beforeFilter:

public function beforeFilter(Event $event) 
{
    parent::beforeFilter($event); 
    $this->Security->requireSecure();
}

Edit initialize function:

public function initialize()
{
    parent::initialize();
    $this->loadComponent('Security', ['blackHoleCallback' => 'forceSSL']);
}

Create function forceSSL:

public function forceSSL()
{
    return $this->redirect('https://' . env('SERVER_NAME') . $this->request->here);
}

All controllers that extend AppController class will be forced to use SSL. CakePHP will take care to redirect the user to the SSL-secured version of the request.

You can find more information here.

Comments Off more...

Create custom configuration files in CakePHP 3

by on Mar.16, 2015, under CakePHP, PHP

1. Create new file into folder config/
2. Name it whatever you like: myconf.php
3. Add your code:

<?php 
return [
    /*
     * my configuration
     */
    'myconf' => [
        'setting_1'   =>  'value_1',
        'setting_2'   =>  'value_2',
        'setting_3'   =>  'value_3',
    ],
];

4. Now you have to load it. Open file config/bootstrap.php, locate line:

Configure::load('app', 'default', false);

and append this line underneath:

Configure::load('myconf', 'default');

More about configuration here.

Comments Off more...

How do I install svn in Ubuntu 14

by on Mar.12, 2015, under SVN, Ubuntu

1. Add rabbitcvs repository

sudo add-apt-repository ppa:rabbitvcs/ppa

2. Update system repos

sudo apt-get update

3. Install rabbitcvs components

sudo apt-get install rabbitvcs-cli rabbitvcs-core rabbitvcs-gedit rabbitvcs-nautilus3

4. Permissions

sudo chown -R myusername:mygroup ~/.config/rabbitvcs
Comments Off more...

How to use jQuery datepicker

by on Mar.08, 2015, under HTML & CSS, JQuery

Include these files into your application:
jquery
jquery ui

<link type="text/css" href="/css/jquery-ui.css" rel="stylesheet"/>
<script type="text/javascript" src="/js/jquery-git2.js"></script>
<script type="text/javascript" src="/js/jquery-ui.js"></script>

Javascript Code

$(document).ready(function()
{
    $(function() {
        $( "#datepicker" ).datepicker({
            dateFormat: "dd/mm/yy"
        });
    });
});

Html Code

<label for="datepicker">datepicker</label>
<input type="text" id="datepicker" name="datepicker" value="" />
Comments Off more...