Protected: boat

Posted by & filed under Odds.

This content is password protected. To view it please enter your password below:

Apache SSL – Multiple Certificates on a Single IP

Posted by & filed under Linux, Server.

Setting up multiple SSL Certificates on a single IP address is possible, and acceptable on nearly all browsers, thanks to Server Name Identification (SNI).

https for markflint.net

SNI sends a site visitor the certificate that matches the requested server name – great! No more need to buy extra IP addresses.

I set this up on a Ubuntu 12.04 server and it was quite straightforward. The process I followed was:
1) set up the server and virtual hosts (see first link below)
2) generate a certificate request (CSR) (see second link below) – make sure you include www. before the domain name
3) go over to https://cheapsslsecurity.com and buy a RapidSSL for about £5.
— there is a process whereby they email you a link to generate your certificate
— to generate your cert you need the CSR you created earlier
— NB: for ‘verification’ you won’t be able to use the email address you get the certificate mailed to, so I chose to use ‘file verification’ where I uploaded a file to the server to verify
— Also note, if you included www. in the domain name while creating the CSR your cert with cover both with or without www.

https://www.digitalocean.com/community/articles/how-to-set-up-multiple-ssl-certificates-on-one-ip-with-apache-on-ubuntu-12-04

This first reference is great for understanding SNI and how to set up your virtual hosts for multiple SSL. Note, this link is for a self-signed cert, so you need to generate a request (CSR) instead… see next link:

http://viralsolani.wordpress.com/2013/02/07/how-to-install-ssl-certificates-with-apache-2-on-ubuntu-12-04/

Also for further cross-references:
http://www.seleads.com/webmastering/how-to-ssl-ubuntu-12-04-apache-2-22/
https://library.linode.com/web-servers/apache/ssl-guides/ubuntu-12.04-precise-pangolin#sph_install-a-commercial-ssl-certificate

Heartbleed bug – Upgrade OpenSSL on Ubuntu 12.04

Posted by & filed under Linux, Server.

The Heartbleed bug found in OpenSSL needs addressing if you are using OpenSSL to generate TLS keys for HTTPS or FTPS in particular. Upgrading OpenSSL on Ubuntu is not just a matter of running ‘apt-get upgrade’ – this does not get the latest patched version. I found the answer was to install the openssl libssl-dev package. For more info see:

http://askubuntu.com/a/434245/172772

Once installed I checked openssl and got the following info:

user@myserver:~# openssl version -a
OpenSSL 1.0.1 14 Mar 2012
built on: Mon Apr  7 20:33:29 UTC 2014
platform: debian-amd64

The important bit is ‘built on:’ – it should be April 7th or later.

It’s probably wise to make new TLS keys to replace any that may already be compromised.

Related info:
http://stackoverflow.com/questions/10175812/how-to-build-a-self-signed-certificate-with-openssl

http://www.howtoforge.com/setting-up-proftpd-tls-on-ubuntu-12.10

Example PDO Singleton Class

Posted by & filed under mySQL, PHP.

<?php
/**
 * Example PDO class with basic function example.
 * Instead of using different credentials for local and remote db,
 * you could add the same users creds to both local and remote.
 */
class Database {
    
    // local connection
    public $local = array(
	'host' => 'localhost',
	'user' => 'root',
	'pass' => '',
	'db' => 'dbname'
    );
    
    // remote connection
    public $remote = array(
	'host' => 'localhost',
	'user' => 'user',
	'pass' => 'pw',
	'db' => 'dbname'
    );
    
    private static $_singleton;
    private $dbh;

    private function __construct() {
	$creds = ($_SERVER['SERVER_ADDR'] == '127.0.0.1') ? $this->local : $this->remote;
	$this->_connect(
	    $creds['host'],
	    $creds['user'],
	    $creds['pass'],
	    $creds['db']
	);
	// set error level to warnings
	$this->dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
    }

    public static function getInstance() {
        if(!self::$_singleton) {
            self::$_singleton = new Database();
        }
        return self::$_singleton;
    }

    private function _connect($host, $user, $pass, $db) {
	try {
	    $this->dbh = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
	    return true;
	} catch (PDOException $e) {
	    return $e->getMessage();
	}
    }

    public function getUser($un, $pw){
	try {
	    $sql = "SELECT username FROM user WHERE username = :username AND password = :password";

	    $stmt = $this->dbh->prepare($sql);
	    $stmt->bindParam(':username', $un);
	    $stmt->bindParam(':password', $pw);
	    $stmt->execute();

	    $usrObj = $stmt->fetch(PDO::FETCH_OBJ);

	} catch (PDOException $e) {
	    return $e->getMessage();
	}
    }

    public function addNews($date){
	try {
	    $sql = "INSERT INTO news (`date`,`content`,`created`) VALUES (:date,:content,:created)";
	    $stmt = $this->dbh->prepare($sql);
	    $stmt->bindParam(':date', $date);
	    $created =  date('Y-m-d H:i:s');
	    $stmt->bindParam(':created',$created);

	    if ($stmt->execute()) {
		return '1';
	    } else {
		return var_export($stmt->errorInfo());
	    }
	} catch (PDOException $e) {
	    return $e->getMessage();
	}
    }
    
    public function disconnect() {
        $this->dbh = null;
    }
}
?>

Magento translate renderTotals()

Posted by & filed under Magento, PHP.

I had an issue where Magento was not picking up translation of “Free Shipping – Free” on my Checkout page. I got round this by adding a function inside /app/code/core/Mage/Sales/Model/Quote/Address/Total/Shipping.php inside the collect() function:

        if ($method) {
	    
	    function mof($txt){
		$expr = new Mage_Core_Model_Translate_Expr($txt, 'Mage_Page');
		$args = array($txt, $expr);
		return Mage::app()->getTranslator()->translate($args);
	    }
	    
            foreach ($address->getAllShippingRates() as $rate) {
                if ($rate->getCode()==$method) {
                    $amountPrice = $address->getQuote()->getStore()->convertPrice($rate->getPrice(), false);
                    $this->_setAmount($amountPrice);
                    $this->_setBaseAmount($rate->getPrice());
		    
                    $shippingDescription = mof($rate->getCarrierTitle()) . ' - ' . mof($rate->getMethodTitle());
		    
                    $address->setShippingDescription(trim($shippingDescription, ' -'));
                    break;
                }
            }
        }

Enable CodeIgniter for xDebug

Posted by & filed under CodeIgniter, Frameworks/CMS, PHP.

In app/config/config.php change the following vars:

$config['uri_protocol'] = "PATH_INFO";
$config['enable_query_strings'] = TRUE;
$config['permitted_uri_chars'] = '';

And in add a file in app/libraries called MY_Input.php with the following content:

class MY_Input extends CI_Input {
    function _sanitize_globals()
    {
        $this->allow_get_array = TRUE;
        parent::_sanitize_globals();
    }    
}

Foreign key restraints

Posted by & filed under Magento, mySQL.

Trying to import a Magento table into a database (drop table if exists) I got an error:

#1217 - Cannot delete or update a parent row: a foreign key constraint fails 

The way to get round this is to remove the foreign key constraint CHECK, delete the table, then add the check again:

SET FOREIGN_KEY_CHECKS=0
DROP TABLE cms_page
SET FOREIGN_KEY_CHECKS=1 

Testing PayPal IPN results

Posted by & filed under PHP.

If you are getting 400 errors back from paypal make sure you add a Host header. It won’t do any harm to add the Connection close header too. Notice the host depends on whether you’re aiming at sandbox or live paypal.

// post back to PayPal system to validate
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
/******** this line from http://stackoverflow.com/questions/11810344/paypal-ipn-bad-request-400-error ************/
$header .= "Host: www.sandbox.paypal.com\r\n";
/*****************************************************************************************************************/
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$header .= "Connection: close\r\n";

Change all table cols to a different collate

Posted by & filed under mySQL.

$dbname = 'my_databaseName';
mysql_connect('127.0.0.1', 'root', '');
mysql_query("ALTER DATABASE `$dbname` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci");
$res = mysql_query("SHOW TABLES FROM `$dbname`");
while($row = mysql_fetch_row($res)) {
   $query = "ALTER TABLE {$dbname}.`{$row[0]}` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci";
   mysql_query($query);
   $query = "ALTER TABLE {$dbname}.`{$row[0]}` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci";
   mysql_query($query);
}
echo 'all tables converted';

Taken from here

Pros and Cons of using latest jQuery CDN

Posted by & filed under Javascript.

It is not a good idea to use the following CDN jQuery in your live (deployed) sites.

http://code.jquery.com/jquery-latest.min.js

This always serves the latest version. If you are using jQuery plugins written by yourself or 3rd party you can find that these plugins break when a new release of jQuery is pushed.

This happened to me recently when jQuery went to 1.9.0 and the jquery cycle plugin broke. It is safer to use an explicit version like this:

http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js

The advantage of using the latest version is that any new methods are available when you go back to your deployed site to add functionality.

The downside is that your site could break and unless you are regularly a visitor you might find it has been broken for sometime!

Validate a file at a given Path or URL

Posted by & filed under PHP.

This class is useful for verifying an uploaded file to tell you the file type and whether or not the file can be opened.

Usage would be:

$f = new validateURI('[path or URL]');
print_r($f->uriInfo);

Here is the class…

<?php
class validateURI {

    public $uriInfo;

    function __construct($uri = null) {

	if (is_null($uri)){
	    return false;
	}
	
	$this->uriInfo = array(
	    'errors' => array(),
	    'validURI' => 0,
	    'uri' => $uri
	);

	// get an array of loaded PHP extensions
	$exts = get_loaded_extensions();

	// find the filetype - try SPL first.
	if (in_array('SPL', $exts)) {
	    $info = new SplFileInfo($uri);
	    $this->uriInfo['fileType'] = $info->getExtension();
	    $this->uriInfo['fileType_method'] = 'SplFileInfo';
	} else {
	    $this->uriInfo['filetype'] = substr($uri, strrpos($uri, '.') + 1);
	    $this->uriInfo['fileType_method'] = 'substring';
	}

	// Use cURL or fopen (if ini allow_url_fopen) to test absolute URLs
	if (parse_url($uri, PHP_URL_SCHEME) != '') {
	    $this->uriInfo['uri_type'] = 'URL';
	    if (in_array('curl', $exts)) {
		$this->uriInfo['method'] = 'cURL';
		// urlencode breaks the path on my local windows machine!
		if ($_SERVER['SERVER_ADDR']!='127.0.0.1'){
		    $uri = urlencode($uri);
		}
		$ch = curl_init($uri);
		if ($ch === false) {
		    $this->uriInfo['errors'][] = 'curl_init failed';
		} else {
		    curl_setopt($ch, CURLOPT_NOBODY, true);
		    curl_exec($ch);
		    $retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		    $this->uriInfo['contentType'] = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
		    // $retcode > 400 -> not found, $retcode = 200, found.
		    //echo curl_error($ch);exit;
		    curl_close($ch);
		    $this->uriInfo['cURL_retcode'] = $retcode;
		    if ($retcode > 199 && $retcode < 400) {
			$this->uriInfo['validURI'] = 1;
		    }
		}
	    } elseif (ini_get('allow_url_fopen')) {
		$this->uriInfo['method'] = 'url_fopen';
		if (fopen($uri, "r") !== false) {
		    $this->uriInfo['validURI'] = 1;
		} else {
		    $this->uriInfo['errors'][] = 'url_fopen failed';
		}
	    }
	} else {
	    $this->uriInfo['uri_type'] = 'unknown';
	    $this->uriInfo['method'] = 'local fopen';
	    // test paths/relative URLs
	    if (fopen($uri, "r") !== false) {
		$this->uriInfo['uri_type'] = 'valid path';
		$this->uriInfo['validURI'] = 1;
	    }
	}
    }
}
?>

Detect Flash from Javascript

Posted by & filed under Javascript.

var hasFlash = false;
try {
    var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
    if(fo) hasFlash = true;
}catch(e){
    if(navigator.mimeTypes ["application/x-shockwave-flash"] != undefined) hasFlash = true;
}

Credit to someone on Stackoverflow.com! Can’t find the reference anymore.

Handle mysql_query() error without a variable

Posted by & filed under mySQL, PHP.

Thought this was a neat way of testing/handling query errors without assigning the result to a variable because you don’t need a variable unless you are using SELECT.

mysql_query($query);
if (mysql_error()) {
    throw new Exception(...);
}

mysql_error() returns empty string if there was no error, which evaluates to false, as pointed out by jakub-arnold in this post

Bitnami