Introduction

This guide will show you how to setup a new project using Ember and Laravel, JSON-API and token based authentication.  The deployed version of your application will be a Laravel backend which serves up the Ember frontend using a Laravel route.

Software

At the time of writing the tools used are:

Prerequisites

  1. Ember CLI 2.4.1
  2. Laravel Requirements
  3. Composer
  4. Git or any other VCS that you prefer

Continue reading

The Code

// Inline Style Images
$content    =   preg_replace_callback('/!\[(.*)\]\s?\((.*)(.png|.gif|.jpg|.jpeg)(.*)\)/',function($match){
    return str_replace('your_search_term','your_replacement',$match[0]);
},$content);

// Reference Style Images
$content    =   preg_replace_callback('/\[(.*)\]:\s?(.*)(.png|.gif|.jpg|.jpeg)/',function($match){
    return str_replace('your_search_term','your_replacement',$match[0]);
},$content);

Why Would You Need This?

I had to use the above code in a Laravel project where the content is entered into a frontend form in Markdown format. When saving the data in my Laravel backend app I wanted to replace the image URL with a placeholder so that the sites URL itself isn’t hardcoded into the database. When displaying the data, the placeholder is replaced with the URL of the site again. This means that if the URL ever changes (different dev environment, staging, production etc) then the images would still load providing that the files still existed in the same location on the server.

Your use case might be different but the above regex should provide you with a decent starting point to actually find the image tags (both inline and reference style) and then manipulate them however you wish.

Telegram messenger recently released an API that lets you easily create bots for their platform.  After deciding to have a bit of a play with it, I found that I had an issue where the webhooks would not send any updates to my server with no apparent error.

The Problem

I made all the following checks:

  1. Valid SSL certificate
  2. Webhook successfully registered using the Telegram setWebhook method
  3. The method responded properly when I sent a test request using a REST service tester
  4. Server access logs – look like Telegram had never even hit the server

The Solution

After a full day of searching, testing and bashing my head against the keyboard, I found this thread on Reddit, where the user described a problem where a full chained certificate was required on the server, not just the server certificate.

To create chained certificate you’ll need to have a look at what instructions your certificate issuer provides.

In my case the certificate being used was a Comodo PositiveSSL, for which I downloaded all the certificates that they sent, which contained:

  • Root CA Certificate – AddTrustExternalCARoot.crt
  • Intermediate CA Certificate – COMODORSAAddTrustCA.crt
  • Intermediate CA Certificate – COMODORSADomainValidationSecureServerCA.crt
  • Your PositiveSSL Certificate – my_domain.crt

I had to combine them all into a file in the following order:

  • my_domain.crt
  • COMODORSADomainValidationSecureServerCA.crt
  • COMODORSAAddTrustCA.crt
  • AddTrustExternalCARoot.crt

For the example above the command would have been:

cat my_domain.crt COMODORSADomainValidationSecureServerCA.crt AddTrustExternalCARoot.crt COMODORSAAddTrustCA.crt > bundle.crt

After that it was just a case of uploading the new bundle.crt to my server, updating the nginx config, and hey presto, within minutes I was receiving all the responses for my webhooks

Hi folks, I’m back with another freebie for you.  This time it’s a Concrete5 package that lets you create, manage and display testimonials on your website.

The following fields are available to you:

  • Title
  • Author
  • Department
  • Quote
  • URL
  • Display Order

When adding a block you can choose specific testimonials to display, or display all. Additionally, you can sort by display order, or in a random order.

Requirements

All you need is a Concrete5 website running on 5.5.0 or greater.

Usage

You can find full documentation on the Github page

License

It’s totally free and open-source so you can do whatever you like with it!  It’s quite easy to adapt into a management system for any other kind of object like people, books or even managing your own movie database.

Screenshots

Download

I’ve submitted the package to the Marketplace and will update this post will a link once it’s live.  In the meantime you can download from Github.

Download here

Support

If you have any issues or feature requests please get in touch via the comments, Twitter, or email

Introduction

When working with databases, you may want a table structure which allows your record to have a parent record (heirachical recordset).  In simple scenarios it’s easy enough to simply have a parent_id column. However, for displaying the entire tree you’ll need a lot of recursion to go through all the top level nodes, test for children, and then test the children for children etc.  It soon proves to be very long-winded and inefficient.

Instead of using the standard parent_id approach, there’s a database structure known as the Nested Set Model.  The nested set model uses an algorithm which basically uses tree traversal to number each node, and once the numbering is complete it becomes very easy to query the tree and search, whether its for root nodes (base node), leaf nodes (nodes with no children) or branches (the path from the root node to a particular node).

Performance

As the tree traversal for numbering the nodes is required, the Nested Set Model requires slightly more overhead when updating the table (each node needs to be renumbered when a change is made), but as mentioned earlier, is very efficient when it comes to actually querying the table.

Example Usage Scenario

A simple use for Nested Set Model would be a category table for a website, where categories can have subcategories.  And even subcategories can have subcategories.  Categories are generally setup in the admin on most sites, and even then are rarely updated so the fact that updating a Nested Set can be a bit slow isn’t actually a issue.  On the frontend the visitors and customers will simply be viewing categories, so they’ll be reaping the benefits of the efficiency and great performance of the Nested Set Model.

Introducing Baobab

Baobab is a free PHP/MySQL implementation of the Nested Set Model.  It can be modified to work with other database systems too.  Baobab uses the Nested Set Model, but also the offers the advantage of supporting multiple trees in the same table, or alternatively you can setup different trees in individual tables, depending on your requirements.

It takes an Object-Oriented approach (OOP) and provides you with an entire API of useful methods including:

  • getRoot()
  • appendChild()
  • getTreeHeight()
  • deleteNode()

Just take a look at the documentation page to see how much Baobab has to offer.

Download and Install

Getting started with Baobab is dead simple.  It’s an open-source project hosted on GitHub which you can download here.  Once you’ve got the code it’s a simple case of placing the classes wherever you need them, include them in your PHP and use the Simple Tree Example to get started.  If you’re more confident then you can have a look at the Multiple Tree Example.

Baobab on GitHub

Conclusion

I’ve found Baobab particularly useful in my projects and have extended it to tie in with my own PHP library.  It offers you the power of using nested sets, without requiring you to code your own implementation of nested.  There’s a lot of useful functions in there, plus the default SQL structure can easily be extended to contain your own table fields too.

It’s great, it’s free and if you need to hold data in a tree structure then it’s certainly worth checking out.

Here’s a quick tip on how to disable notices like this one appearing on your site:

Deprecated: Function eregi() is deprecated in…

At the top of your application (bootstrap or index file) just add the following line of PHP:

error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);

This tells your application to show all errors EXCEPT for Notices and Deprecation errors.  Obviously you can show Notices if you prefer by removing & ~E_NOTICE from that function

Hope this helps!

This morning I was faced with an issue with SwiftMailer where the PHP code was throwing an error message as it failed to connect with the mail server.

To solve it I first thought of using a try/catch, but obviously that wouldn’t work due to the fact that the function only throws a Warning, not an Exception.

The solution was quite straight forward…

  1. Create a custom error handler, to gracefully capture the warning and display a custom message
  2. Set the custom error handler before attempting to call the function causing the warning (in this case it was fsockopen)
  3. Reset the error handler to the default PHP one after calling the function.

Here’s an example of an error handler function you can use. I’m using Smarty for my output, but you can send your output to the users browser in any way you wish.

function errorHandler($errno,$errmsg,$errfile) {		
	   	//email yourself the error message and code
	   	$email	=	"An error {$erro} occured on page ".$_SERVER['REQUEST_URI'].", in the file {$errfile}.\r\n\r\nThe error is shown below:\r\n{$errmsg}";
	   	mail("email@domain.com","PHP Error Notification",$email);
	   	
	   	//output a friendly message for the user	
	   	$wrapper	=	new SmartyTemplate(); 
	   	$msg		=	"Thank  you for your message.  Unfortunately we have been unable to send your email, please go back and resubmit the form or call us on 0800 123 456 directly.  Sorry for any inconvenience caused";   	
	   	$wrapper->assign("content", $msg);   		
	   	$wrapper->display("display_wrapper.tpl");
		exit();		
	}

The next step is to set our new error handler before the call to the function that causes the warning. As mentioned, my issue was with fsockopen in in SwiftMailer, but the fix is the same for anything. Here’s how I did it in Swift.
find the offending function (in Swift/Transport/StreamBuffer.php)

if(!$this->_stream = fsockopen($host, $this->_params['port'], $errno, $errstr, $timeout)) {

and add set the error handler before it.

set_error_handler("errorHandler");
    if(!$this->_stream = fsockopen($host, $this->_params['port'], $errno, $errstr, $timeout)) { 

As I only want my error handler to run for that particular function, and not for every function in the entire site, I just have to make sure I remove my custom error handler after the function.
Just add this after your function:

restore_error_handler();

Which will cause PHP to revert to it’s normal error handling method once it’s gotten back your function.

Extras
My usage of error handling was very specific to a single function. Of course you can have a site wide error handler instead which gracefully handles every PHP error/warning/notice within a single function. You could just declare the function a common file and then handle each kind of error independently. The PHP website has a great example of this:

function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    if (!(error_reporting() & $errno)) {
        // This error code is not included in error_reporting
        return;
    }

    switch ($errno) {
    case E_USER_ERROR:
        echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
        echo "  Fatal error on line $errline in file $errfile";
        echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
        echo "Aborting...<br />\n";
        exit(1);
        break;

    case E_USER_WARNING:
        echo "<b>My WARNING</b> [$errno] $errstr<br />\n";
        break;

    case E_USER_NOTICE:
        echo "<b>My NOTICE</b> [$errno] $errstr<br />\n";
        break;

    default:
        echo "Unknown error type: [$errno] $errstr<br />\n";
        break;
    }

    /* Don't execute PHP internal error handler */
    return true;
}

It would be quite easy to tweak that function so that it emailed you a log of the error (and/or stored it in the DB) and then redirected the user to a nice looking page notifying them that there’s an error, but you’re aware of it.