Web Development

Replacing Line Breaks With <br /> Tags Using JavaScript

Posted in Javascript / jQuery, Web Development on February 22nd, 2012 by Steve Marks – Be the first to comment

A scenario arose today where I needed to take the content within a textarea and then output it the screen as HTML. In doing this I knew I would have to take the line breaks in the textarea content (\n) and swap them out for <br /> HTML tags. Languages like PHP come with inbuilt functions to handle this kind of replacement. JavaScript however does not.

I started out by trying the following:

var output = document.form1.myTextarea.value.replace("\n", "<br />");

This kind of worked but only replaced the first line break. I then remembered from previous posts that the JavaScript replace() function will only swap out the first occurrence of a string.

A quick change was required to the code as follows:

var output = document.form1.myTextarea.value.replace(/\n/g, "<br />");

By turning the first parameter into a regular expression and enabling ‘global’ matching (\g), all line breaks were now being converted as expected.

Share

PHP Function to Connect via FTP with Retry Capability

Posted in PHP, Web Development on February 21st, 2012 by Steve Marks – Be the first to comment

Let’s face it… If something can go wrong, it will go wrong. This is no exception for FTP connections either. Maybe the remote server is not accessible, the network is down, or the connection times out.

PHP comes with a set of useful functions to deal with common FTP operations. What I want to show you in this post however is, in conjuntion with these functions, how to improve the connection aspect and add a failsafe should a connection not be available. I find this especially effective for scripts left running as a background process.

Let’s take a look at the function:

function connect_to_ftp($ftp_host, $ftp_user, $ftp_pass, $retries)
{
	$connected = false;
	$retry = 0;

	// Keep looping until connected or met no. of retries if $retries is not zero
	while (!$connected && ($retries==0 || ($retries>0 && $retry<$retries)))
	{
		// try connecting to host
		$ftp_conn = ftp_connect($ftp_host);

		if ($ftp_conn)
		{
			// connection was successful. now try to login
			$ftp_login = ftp_login($ftp_conn, $ftp_user, $ftp_pass);

			if ($ftp_login)
			{
				// login was successful. let's get outta here...
				return $ftp_conn;
			}
			else
			{
				echo "Unable to login to ".$ftp_host." using ".$ftp_user.":".$ftp_pass."\n";
			}
		}
		else
		{
			echo "Unable to establish FTP connection to ".$ftp_host."\n";
		}

		sleep(5); // sleep for 5 seconds before trying again

		$retry++;
	}

	return $ftp_conn;
}

And an example of using the function:

// initialise FTP connection details
$ftp_host = 'ftp.mysite.com';
$ftp_user = 'username';
$ftp_pass = 'password';
$retries = 0; // Number of maximum retries. Set to 0 for unlimited

// returned is an FTP connection as a resource for use in other functions
$ftp_conn = connect_to_ftp($ftp_host, $ftp_user, $ftp_pass, $retries);

echo 'FTP Connection: '.$ftp_conn;

Share

Bring Google Map Markers to Front on Hover

Posted in Javascript / jQuery, Web Development on February 21st, 2012 by Steve Marks – Be the first to comment

When placing markers onto a map using the Google Maps V3 API they will be placed from front-to-back based on their lat/lng. This is normally fine but can cause a problem when there are lots of overlapping markers congregated together, or when the user is viewing the map at a lower zoom level, at which point it can be tricky to select certain markers that have been pushed back.

As a result of the above I needed a way to bring markers to the front when the user hovered their mouse over them. I’ve included the code below but first let’s start with a demonstration of the problem faced and how the code helps:

Try rolling over the markers and you’ll see that the one to the rear will come to the front. This isn’t just limited to two markers either. It will work regardless of the number of markers shown on the map.

Ok, so onto the code:

var map;
// array of markers added to the map
// used at a later date
var markers = new Array();
// a global variable used to store the highest zIndex
// saves calculating it repeatedly
var highestZIndex = 0;

function initialize() {

	/* SETUP MAP */
	var myLatlng = new google.maps.LatLng(52.06768, -1.33758);
	var mapOptions = {
		center: myLatlng,
		zoom: 10,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	}
	map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

	/* ADD 1st MARKER */
	var markerOptions = {
		position: new google.maps.LatLng(52.06768, -1.32058),
		map: map,
		zIndex:1 // important!
	};
	var marker = new google.maps.Marker(markerOptions);
	markers.push(marker);
	// assign a custom variable to this marker containing the zIndex
	marker.set("myZIndex", marker.getZIndex());

	// add mouseover and mouseout events to first marker
	google.maps.event.addListener(marker, "mouseover", function() {
		getHighestZIndex();
		this.setOptions({zIndex:highestZIndex});
	});
	google.maps.event.addListener(marker, "mouseout", function() {
		this.setOptions({zIndex:this.get("myZIndex")});
	});

	/* ADD 2nd MARKER */
	var markerOptions = {
		position: new google.maps.LatLng(52.06768, -1.33758),
		map: map,
		zIndex:2 // important!
	};
	var marker = new google.maps.Marker(markerOptions);
	markers.push(marker);
	// assign a custom variable to this marker containing the zIndex
	marker.set("myZIndex", marker.getZIndex());

	// add mouseover and mouseout events to second marker
	google.maps.event.addListener(marker, "mouseover", function() {
		getHighestZIndex();
		this.setOptions({zIndex:highestZIndex+1});
	});
	google.maps.event.addListener(marker, "mouseout", function() {
		this.setOptions({zIndex:this.get("myZIndex")});
	});

}

function getHighestZIndex() {

	// if we haven't previously got the highest zIndex
	// save it as no need to do it multiple times
	if (highestZIndex==0) {
		if (markers.length>0) {
			// loop through markers
			for (var i=0; i<markers.length; i++) {
				tempZIndex = markers[i].getZIndex();
				// if this zIndex is the highest so far
				if (tempZIndex>highestZIndex) {
					highestZIndex = tempZIndex;
				}
			}
		}
	}
	return highestZIndex;

}

One important thing to note regarding the above is that markers must have a zIndex option set, either by specifying it when adding the marker initially or by using the setOption() function. Without a zIndex, the function getZindex() will return ‘undefined’.

Share

IIS Able To Connect Via FTP But Can’t Upload Files

Posted in Server Management, Web Development on February 20th, 2012 by Steve Marks – Be the first to comment

Over the past couple of days I’ve been setting up a new box running Windows Server 2008 r2. One of the main requirements for it was that it should be able to accept file uploads via FTP. This wasn’t too much of a problem and seemed to be relatively easy… Install the IIS role, install the FTP service and setup an FTP site along with any associated users.

All was going well and I was able to connect to the server remotely as a standard user with no problem at all. When I came to upload a file however I started to get the following error:

550 Access is denied

The Solution

After a bit of investigation I managed to solve the problem by following the steps below:

1. Open the ‘Internet Information Services (IIS) Manager’. You should be able to find this in your Start menu under ‘Administrative Tools’.

2. Once opened, right-click your FTP site and select ‘Edit Permissions…’ from the menu:

IIS FTP Upload Access Denied 1

3. Select the ‘Security’ tab.

4. Click the ‘Users’ group. You can see from the permissions shown underneath that by default this group doesn’t have ‘Write’ permissions:

IIS FTP Upload Access Denied 2

5. Click ‘Edit…’ and select to allow the ‘Write’ permission:

IIS FTP Upload Access Denied 3

6. Click ‘OK’ to save the changes.

Once the above change has been performed you should now be able to successfully upload files without problem.

Share

EPC (Energy Performance Certificates) Graph Individual Parts

Posted in Web Development on February 17th, 2012 by Steve Marks – Be the first to comment

You’ll probably be familiar with EPC (Energy Performance Certificates) graphs if you work in the property or energy industry. In essence they provide valuable information as to the current and potential energy efficiency of a home. In the UK all properties bought, sold or rented require an EPC.

Whilst recently playing with EPC graphs from a programmatic point of view I couldn’t find an EPC graph split into all it’s individual parts. As a result I created my own set of images and include it for download from the link below:

Download Here

Here’s a preview of whats included:

EPC Graph Parts

Share

Stop WordPress Closing Code Blocks When it Encounters a Blank Line

Posted in Web Development on February 9th, 2012 by Steve Marks – Be the first to comment

WordPress allows you to highlight blocks of code for readability when writing a post or typing a comment. This can easily be acheived by adding text between <code></code> tags at which point it will put it in a pretty little box and differentiate it from the rest of the content. If you’re reading this however you probably already knew that.

The problem I faced however was, if I added one or more blank lines within these <code></code> tags it would completely split up what was before the new line and what was after. Allow me to show you an example of what I mean:

This is a line of text with a blank line after it.

This is the second line of text with a blank line before it.

See how it looks like two separate code snippets?

The Solution

The solution turned out to relatively simple. All that was needed was to add a &nbsp; (non-breaking space) character or <br /> tag on the blank line and it would keep the code block complete around all lines.

I’ve include below an example where I place a <br /> tag on the blank line in the middle:

This is a line of text with a blank line after it.

This is the second line of text with a blank line before it.

Share

How to Fix IE8 Error “Unable to download X.php from yoursite.com”

Posted in PHP, Web Development on February 9th, 2012 by Steve Marks – Be the first to comment

Rarely do I hear the words “Internet Explorer” and “Error” mentioned in the same sentence. Alright… maybe that’s a bit of a lie. Unfortunately however, few us can control what browsers our users are using so we have to try and cater for all instances. The one I’m going to talk about today is specific to IE8 and occured when trying to force the download of a PDF to the browser in a PHP script.

The error reads as follows:

Unable to download somefile.php from yoursite.com.

Internet Explorer was unable to open this site. The requested site is
either unavailable or cannot be found. Please try again later.

After looking into the problem it turned out that the problem was down to the PHP headers being sent when outputting the file, inparticular the ‘Cache-Control’ header. If this header is not being set, or is not being set correctly you can start to experience problems.

The Solution

Previously I wasn’t using the aforementioned ‘Cache-Control’ header but apparently setting it to ‘no-cache’ or ‘no-store’ will have the same negative effect. For me the answer was to set it to ‘private’ or to set it with a blank value. Like so:

header("Cache-Control: private");

Or:

header("Cache-Control: ");

The site in question was also being used over SSL but I’m not sure if this also played a role. Regardless, the above worked and it kept our IE8 users happy.

Share

Resolve “X is not a verified user” When Adding Developer to Facebook App Roles

Posted in Web Development on February 8th, 2012 by Steve Marks – Be the first to comment

Is not a verified user

Whilst recently building my first Facebook app, one of the things I wanted to do was share ownership with another developer so we could both work on it and share other apps in the future. When trying to add this other user I kept getting an error returned claiming that they were not a verified user.

When looking into how to resolve this I saw a number of possible causes mentioned across the web, from the app being in ‘Sandbox’ mode, to groups not being setup correctly.

None of these proposed solutions worked and after digging a little further I found this page on Facebook help:

How do I verify my developer account?

It turns out that to be added to a role for a Facebook app you need to verify your account via phone or by adding a credit card. After trying the steps explained on the page above I was then able to add the second developer successfully.

Share

MySQL DELETE Query Statement With JOIN

Posted in MySQL, Web Development on December 3rd, 2011 by Steve Marks – 1 Comment

Executing a MySQL DELETE query that contains a JOIN… This is something that I always forget how to do so I wanted to write about it as a personal reference, and to help others looking to do the same. First lets take a look at a standard DELETE query containing a single table:

DELETE FROM
	`my_table`
WHERE
	`my_value`='FooBar';

Easy right? Now, the next part is where I was going wrong and I’m guessing is the same in your case. The next statement shows how you might first try to perform the DELETE with a JOIN based on other MySQL syntax:

DELETE FROM
	`my_table`
INNER JOIN `second_table` ON `second_table`.`id_column`=`my_table`.`id_column`
WHERE
	`my_value`='FooBar';

By running the above you’ll get the following error:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INNER JOIN `second_table` ON `second_table`.`id_column`=`my_table`.`id_column` WHERE `my_va' ne 1

The Solution

Sticking with the query above we can get it to work with a simple amendment. All we need to do is put the name of the table we’re deleting from between the words ‘DELETE’ and ‘FROM’ like so:

DELETE `my_table` FROM
	`my_table`
INNER JOIN `second_table` ON `second_table`.`id_column`=`my_table`.`id_column`
WHERE
	`my_value`='FooBar';

Share

Resolve SugarCRM “You have been logged out because your session has expired”

Posted in Server Management, Software, Web Development on October 24th, 2011 by Steve Marks – 1 Comment

Upon trying to login to SugarCRM ealier today I kept getting an error stating “You have been logged out because your session has expired”. I knew the details were correct but no matter how many times I tried the same message kept coming up and I could not login. Upon fumbling around for a while I came across a couple of solutions, one of which resolved the problem. I explain these in more detail below:

Solution One – Session Directory Not Writable

This first solution wasn’t relevant in my case but I did see it mentioned a few times on my travels as a very likely resolution to the problem mentioned above and thought it worth a mention it here.

When you’re logged into SugarCRM it uses PHP sessions to store information about your current visit. This solution suggests that the directory where this session information is stored is not writable and therefore SugarCRM is unable to continue past the login screen.

So where is this directory? The first place to look is in your SugarCRM configuration file. This can found in the root of your SugarCRM installation and is in a file called config.php. Within this PHP file is a reference to where sessions will be stored. If this contains a valid path then ensure SugarCRM has permission to write to it.

If the above path in config.php is blank then SugarCRM will use the path set in the php.ini file. You can view what this is set to by creating a PHP file and entering the following:

echo ini_get("session.save_path");

Solution Two – Disk Out Of Space

The other possible cause of the error was that the disk where SugarCRM is located was out of space which was the case in my scenario. By simply deleting a few old backups and cleaning down unused files I was then able to login again immediately.

Share