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.

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

This year I’ve decided that I want to learn at least one new language and have decided that I’ll be learning Ruby.  I’ve read great things about Ruby and Rails, all about how it’s made development fun again for devs, lets you actually get on with creating responsive web applications and is generally just so awesome.  I’ll be writing up everything I discover, whether it’s finding things which are much easier than their PHP alternative, or getting frustrated by the fact that I can’t figure out how to do something I’d normally consider trivial in PHP.

Part I is based on me setting up Rails on my local Windows machine and then spending a couple of hours working my way through the Getting Started tutorial.

Ruby VS Ruby On Rails

One of the first things I asked myself was, “am I learning Ruby or Ruby on Rails?” and went off in search for an answer, which was “both”.

Ruby is the language.  Rails is a framework written in Ruby which makes creating web applications really easy.
So me learning Rails is actually me learning how create Rails applications in Ruby.  Got it?

Setup

The setup of Rails itself wasn’t too bad.  I just downloaded the Windows installer from Ruby Installer and the DevKit from the same site, which allows me to compile and use gems natively.  That was it for Rails installation, simple enough.

MySQL Setup

To create my first application I simply fired up Netbeans, which is my IDE of choice, and created a new Ruby on Rails Application.  This was pretty cool, except for the fact that I couldn’t get MySQL working.  I have MySQL running locally as part of WAMP, but installing the mysql gem for Ruby wasn’t enough.  Whenever I tried running the app it’d complain and quit.

I started looking up solutions, and spent a lot of time searching for people with similar issues, but no matter what I tried I couldn’t get it working.  I spent at least an hour looking for a fix and got really frustrated, it was quite a dark time, however I kept looking and finally found this solution on how to install MySQL on Windows 7 64-bit with Ruby.  The tutorial was simple to follow, and as soon as I’d finished my app started working, good times.

Hello Ruby

Now that I had Rails setup and installed on my machine, it was time to start learning how to build things.  I went to the getting started tutorial and worked my way through it.  As I worked through it I spotted a LOT of things which seemed to make me love Ruby, and lot of things which went well and truly over my head.

Things I Loved

  1. Sprockets – In your application directory, Rails has assets directories for JavaScript, Stylesheets and Images.  Whenever you use the CLI to create a new controller, it creates new .scss and .coffee files with the name of your controller.  This means that you can separate out all the style and scripts for each component of your site really easily.  Rails then compiles your Sass and CoffeeScript files when your run your application into a single CSS and a single JavaScript file.
  2. Response types – it was so stupidly easy to return content in a specific format based on the URL extension.  For example:
    myurl.com/posts – would be the expected HTML output all my blog posts
    myurl.com/posts.json – would route to the same controller and action, but return all the blog posts as a JSON string
    myurl.com/posts.xml – all the posts but now as valid XML
  3. Rails IS an MVC framework – Rails is built to be an MVC framework.  The moment you generate your first app (easy as: `rails new myappname`!) it creates a base application which follows the MVC pattern and easily allows you to extend it into your own.
  4. Syntax that “just makes sense”– here’s a sample of a Model in Ruby:
    class Post < ActiveRecord::Base
      validates :name,  :presence => true
      validates :title, :presence => true,
                        :length => { :minimum => 5 }
    
      has_many :comments
    end
    It amazes at me at how much you can understand just from looking at the class declaration.
  5. It’s So Simple – whilst you could argue that I now have the benefit of a few years PHP experience, I still remember that when I first started with PHP, which was my first web language (I’d done Java and C++ before), I spent a whole summer just going over the basics and working my way up to creating a blog as part of working through a book.  In fact, the blog was pretty poor an lacked a lot of key features like security and it was done in procedural programming.  It wasn’t until about a year into PHP that I started working with frameworks and OOP properly.  In comparison, it took me just a few hours to go from “I want to learn Ruby”, to having a working blog application using MVC conventions.

It’s Over My Head

When I said there were a few things that went well over my head, well…I lied, it was basically just the syntax.  Whilst in some cases the syntax made a lot of sense, in other cases I was getting really confused e.g. when they were generating forms in the views and I had no idea what the hell was going on.  At the time I decided the best thing to do was to carry on the guide and then go through everything and look up the bits I didn’t get.
This is actually as far as I’ve got to date, but see the next section on how I intend to learn the syntax.

Where To Next?

Whilst I’ve completed the basic blog tutorial, the next step is to learn how to make a full web application.  I’ve looked around and found that the book Agile Web Development With Rails is THE book to learn Rails with according to a lot of people.  I managed to find an early edition at work today and have brought it home to start looking through for the rest of this evening.
The book has an appendix which contains a quick-start guide to the Ruby language and syntax so I’m going to start with that to understand the things from the blog tutorial which I didn’t quite get, and then make my way through the book which should also clarify some of the things for me.

Verdict.

Simply put, I think Rails is ACE.  So far it’s been great.  Whilst there’s some bits I don’t quite get yet, well what can you expect, it’s been about 3 hours so far!  Overall it seems to be a very powerful framework which not only enforces but also simplifies the best web programming conventions.  Lovin’ it.

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.