Sunday, 21 September 2014

Automate your Android with NFC tags

This blog is going to be different to anythingI've done before. I try and do a blog about what I have learnt each week. This normally comes from work (hence all the Joomla related blogs). However work has been pretty slow. My other option was to write about what I've been learning in Java as I am currently creating a new Android app. The issue with this is that I am still getting used to Java so I'm not yet at a stage where I am comfortable writing about it.

So instead this week I am going to show you what I have been doing with my phone since discovering NFC tags.
Ill start with NFC tags. NFC stands for near field communication and it is a form of wireless technology that allows the exchange of small amounts of data from a tag to a NFC compatible phone. The tags them selves don't need any batteries as they draw power from the receiving device.

The tag can be anything, they're commonly put in key rings and stickers but they can be put into anything really. The good thing about the technology is that it has been around for quite some time. Contactless bank cards, Oyster cards and key fobs for secure buildings all use this (or very similar) technology.

I'm going to go through a few apps you can download which make some tasks a lot easier. The first app is NFC Actions, this provides you with a list of common tasks you might want to automate. I used this app to connect to my WiFi network. You just pick your WiFi network and enter the password, write to the tag by placing it on the back of the phone. 

Once the tag was written I simply put the sticker on my router with the idea that if any of my guests come over and want to connect to the WiFi then they can just put there phone on the tag and viola! The only draw back to using these types of apps is that the receiving device needs to have the app as well.

Another notable app is AnyTag NFC Launcher. This reads any NFC tag and allows you to open an app. So I have it set to open the Natwest app when it detects my bank card and the Oyster Balance.  For more ideas regarding NFCs have a look at this blog.

Sunday, 14 September 2014

Creating a Custom 404 Page in Joomla

One thing I have noticed about Joomla that sort of snook in under the radar for me is that it doesn't have a built in facility to create your own 404 error page. After a bit of research I've found out how to get it done. It's not that complicated but it does involve popping into the back end and adding some PHP code.

Joomla does have it's own built in 404 page but as you can see here it's not very user friendly in the slightest:
It doesn't follow the style of the site and it's doesn't include the default navigation which means any users will more than likely just give up and leave the site. 
In order to create your own custom page you first need to a new 'uncategorised' article. This will serve as your 404 page, include some text like Sorry, we couldn't find what you're looking for... Well really you can put what you want on it really (I won't tell!) but the fact it's going to be an article means that once we are done you can treat it and manage it like any other Joomla page.
Once you have saved your new article make note of the alias as we'll need this for the next step. Before we get stuck into the PHP code we need to create a hidden menu item so that we can navigate to the article. I won't go into detail on how to do this as if you don't know then this task might be a bit to advanced for you. The next step is to go to your ftp client and navigate to templates>system>error.php
Copy this error.php file and replace the one located in your sites template folder. For example, if I was using a template named 'Puriity' I would copy the error.php file to the templates/cleancloud directory.
 if (($this->error->getCode()) == '404') {
header('Location: /404');
exit;
}
Above is the code you need to add to your error.php. This needs to be added just after the line which defines _JEXEC. You then just need to change the location URL to your error pages alias (don't forget the /). If you are using Joomla 1.5 or below the you will also need change getCode() to code in order to use this snippet.
Now when you try and go to a URL that doesn't exist you will be redirected to your nice and shiny new 404 page.
Didn't I tell you it was simple :).

Friday, 5 September 2014

Making Use of Scoped CSS

This week folks I'm going to talk about Scoped CSS. Yeah I've never heard of it before either, well until very recently at least. 
Scope is a new attribute in HTML5 that allows you to override styles for a particular child element by declaring some inline styles. So basically this mean the style block with the scoped attribute will overwrite the global styles generally found in the head (whether in a style block or linked stylesheet), but only on the sibling/descendent elements inside the same parent.
If you're still not sure look at the example code below with the outcome to see it in action.

CSS Scoped Code

and this is what it should look like...
CSS Scoped View
So what is the point or benefit  hear you moan. Well;
  • It may be desirable to keep the CSS of a particular interactive element together with the HTML. If the element in question is unique on the site (like a complex slider for example), there is no advantage to caching it with global styles.
  • Keeping the CSS with the HTML for organization may have value however.
  • When working with a team it can be a great way to allow for simultaneous development of various areas of the site without worrying about the state of the global CSS - I can see this as a short term solution.
  • If your article is getting aggregated by another site it's possible to customize styles on another website that would otherwise be beyond the reach of your global stylesheet.
  • If you enable tags in the comment section of your site you can give your readers the ability to style their... nevermind this is probably a terrible idea.
  • For use in widgets on third-party sites where the CSS is unknown and the in-widget styles shouldn't affect anywhere else. Although being able to reset the styles within the widget is the other half of that battle.
  • Finally (and most exciting to me), Scoped CSS is ideal for working within Content Management Systems where you have much less flexibility for adding unique markup to common templated areas, or no access to the existing stylesheets.

Sunday, 31 August 2014

Managing Multiple Projects in Chrome

If like me you work on multiple project at the same time. Switching between all the tabs can be quite an effort as well as very confusing at times. What I'm going to do today is show you how i manage multiple projects in chrome. This has so far proved really useful for me as it allows me to easily have a new browser window for each project i have and I am able to flick between them at the click of a button.
If you've ever played around in the settings section of Chrome then you have most likely noticed the facility to add multiple users. we're basically going to use this but with the added extra (hack) of signing in with individual Google+ accounts. 
To use this facility you need to navigate the settings menu and scroll down to the users section. Currently you'll see an icon for the current user (that's you!). You could go ahead and add a new user from here but we're going to take an extra step so you can choose you/your projects Google+ profile photo.
To enable this feature for all versions of Chrome enter the following into the address bar:
chrome://flags/#enable-google-profile-info 
You'll then see the screen below which allows you to Enable Google profile name and icon. Enable that now and restart your browser.
Once this is done you should now see you Google+ profile name in the corner of your browser. When you click on your username it will show you a drop down menu and list any other users you have already assigned. As i have my set up already complete you can see my list oh projects I have as well as my personal account too.
To add a new user simply click on the bottom link which says, in my case, Not Jamie Pezone? On a separate note you can click on the padlock and set a password for the current user which has its obvious benefits.
This will launch a new dialog window displaying all your accounts. From here you can edit, add and remove accounts. I'll quickly go through the process of adding a new user now.
First of all you need to click new user (surprise surprise). This will open a new browser session under the user Person 1 and present you with a Google sign in screen. Here you simply sign in with a gmail account for the project.
An issue I had however was that my projects are both associated to my personal Google+ profile. Signing in with just my personal account would be pointless for the likes of Google plus as I would have to still navigate my way through G+ to my pages section a choose my page. 
However after some searching I found that we can get around this by using the email address that is created for each G+ page. If you go to your G+ page > setting and the scroll down to third party tools.
Here you'll see your pages email address. Simply click set up password and sign in with these details. This will allow you to have a Chrome profile specifically for this page. It will mean that when you go to G+ with this Chrome user it will load up just that account so there is no need to navigate through the personal account to get to the right page.

Friday, 22 August 2014

Joomla 3 Search Engine Friendly URLs

Ok so I've been using Joomla in my new job for a while now. It was a bit of a learning curve as I had no previous experience with a CMS but now I'm getting used to it I can see me using it quite a lot with future websites. 
Although it has some limitations it is very good for small to medium size sites which could range from static website to a simple e-commerce site. There's a ton of extensions that can just be added on with little trouble.

You don't really need any coding experience to use it however it helps as some default features are not very SEO or user friendly. Today I'm going to go through process I do with each of my new Joomla sites to take care of things like SEO friendly URLs and removing the article number from URLs.
By default a link to an article in Joomla will look something like this,  www.example.com/index.php?option=com_content?&view=article=3...etc These perform very poorly in search engines as they mean nothing to nobody.

SEO Friendly URLs

Ok so the first step of this is quite simple. 
Within administrator > Global Configuration make the following changes:
Joomla SEO Settings
Switch Search Engine Friendly URLs and Use URL rewriting to Yes. Make sure Adds Suffix to URL and Unicode Aliases are set to No. This will change the URLs to something like: www.example.com/index.php/10-my-tenth-article. This Is already a lot better isn't it :). This however still won't work and the reason for that is the index.php in the URL. Next we will remove it.
Now that the first (and the easiest) step is over with lets get onto the trickier stuff. It's probably only 'tricky' for someone who has no experience editing a .htaccess file or no coding experience at all. I think anyone with even a small amount of experience won't be pushed too far out of their comfort zone if at all.
So in the next and final step of this part we need to update our .htaccess file. This can sometimes be tricky to find as it can be hidden by your computer or server (if using an in browser file manager). You will need to show hidden files in order to find this file. If you still can't find the file then it's possible you wont have one (typical of a new Joomla installation). If this is the case then open up a file called htaccess.txt in your root directory. This is your .htaccess file that if waiting to be used.
once you've opened it you need to search for the custom redirects section and add the following code:
RewriteCond %{THE_REQUEST} !^POST
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^/]+/)*index\.php/([^\ ]*)\ HTTP/
RewriteCond %{SERVER_PORT}>s ^(443>(s)|[0-9]+>s)$
RewriteRule ^(([^/]+/)*)index\.php/(.*)$ http%2://www.example.com/$1$2 [R=301,L] 
Two more things you need to do is: 1, make sure that you remove all #'s at the start of any line we are editing otherwise it will be ignored. 2, replace www.example.com with your own domain name.
This will now turn your URLs into much nicer SEO friendly and human readable URLs....almost. Your URLs will now look something like this www.example.com/10-my-tenth-article. This should work fine now (if not try going back to step one). However we still have the article number in the URL, which is pointless and potentially detrimental SEO-wise as well as being not very user friendly.
So now we're going to jump into a PHP file and sort that out.  

Step 1 Joomla 3.0.2:

Naviagate to and open  “components/com_content/router.php“, then continue on step 2. Remember, you’ll probably have to re-do this step every time you update Joomla.

Step 2 (There are two places need to do this change, one near the top, one in the middle) Replace this:

$advanced = $params->get('sef_advanced_link', 0);
With this:
$advanced = $params->get('sef_advanced_link', 1);

Step 3 You want to edit your router.php file:

- From: ->where($db->quoteName(‘alias’) . ‘ = ‘ . $db->quote($db->quote($segment)));
- To: ->where($db->quoteName(‘alias’) . ‘ = ‘ . $db->quote($segment));

You URLs should now look bloody gorgeous! If you do struggle with this for any reason (other versions of Joomla may differ in this process slightly) please contact me and I'll do my best to help you get sorted.

Friday, 15 August 2014

Responsive Mobile Dialer with CSS3

These days web design is all about responsiveness. It's basically a fancy word for a site which 'reacts' dynamically to be optimised for different screen sizes. This means that it will display content which has been specifically designed with a device in mind. 
One thing traditional responsive techniques don't do natively is deal with phone numbers properly. What do I mean by this? Lets say your'e looking at website on your phone and you see a phone number, currently you'd have to copy and paste the number into the dialer. 

What I'm going to do today is show a responsive way to deal with phone numbers. Using the tel prefix with a little CSS and HTML we'll get the dialer showing up for mobile only. For the sake of this blog i'll just keep it very simple and start with a basic HTML page.
First we'll build our code:


01234 567 890
01234 567 890

and our CSS:
#phone-number{
 color: #FFF;
 float: right;
 text-align: center;
 font-size: 18pt;
 margin: 5px;
 font-family: arial;
 text-shadow: 2px 2px 2px #000;
}
#telnum{
 display:none;
}
What we have here is some basic styling to the container and the tel anchor element hidden away as default as we are going to optimise for desktop as a default. Your number should look like this one:
The next step is to make this responsive for mobile devices. As these tend to have much smaller screen sizes we shall use CSS media queries to detect the change in browser size. The code below listens for the browsers width and while it is below 767 pixels it implements the CSS contained within it's parenthesis.
@media (max-width: 767px) {
 #normnum{
  display:none;
 }
 #telnum{
  text-decoration: none;
  color: inherit;
  cursor: text;
  display:block;
 }
 
}
This very simply hide the normnum div and shows the telnum anchor text. As you can see from the image below:
You can see that while my mouse was hovered over the anchor text it showed the href destination. In Chrome this isn't an issue as you can click on it and nothing happens. However some other browsers treat the link as normal and attempt to navigate to the page. This creates errors which is why we use the media query to hide the link so it is not clicked by accident.
Lets view this on a mobile device and see what the results are, first Android:
 

Friday, 8 August 2014

IP Canonicalization and Sitelink Demotion

IP Canonicalization

This week I've been doing quite a bit of SEO. This is not something I'm familiar with so it's been a good week for learning a couple of tricks beyond keywords and meta descriptions. The first trick I learnt was IP Canonicalization.
 The idea of IP canonicalization is to redirect any pages that could be labeled as duplicate content to there original URL. This makes sure that the IP address does not get indexed by Google. The solution to this problem is a 301 redirect, this is a permanent redirect from one URL to another. The main benefit of a 301 redirect as apposed to other methods is that there are no search engine penalties. 
The best way to set up a 301 redirect is to edit the .htaccess file found in your root directory. The code you need to insert is below:
RewriteEngine On 
RewriteCond %{HTTP_HOST} ^xxx\.xxx\.xxx\.xxx [nc,or] 
RewriteCond %{HTTP_HOST} ^example\.com [nc] 
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
You just need to change the XXX's with your servers IP address and the example domain for your own. This is the simplest and most effective solution of IP Canonicalization. As an extra precaution you could edit your robots.txt file on your server to stop Google from indexing certain parts of your site.
The best way to check if you have applied this properly is to go to SEO site checkup and enter your web address. It is important to note that if you are on a shared server you may need to speaking to your hosting provider to activate IP Canonicalization.

Sitelink Demotion

Another trick i discovered this week is sitelink demotions. What's that you say!? basically it is a set of links which appear below a particular page  when it is shown in search results. The image below give a better idea of what I'm talking about:
Google Sitelink Demotion Picture
1)The main search result
2)Sitelinks
Google's algorithms determine sitelinks by analysing a site's link structure to determine of there are other links that can be provide in the search results that could save the users time. Google doesn't always get this right though and this can lead to incorrect or no links being displayed with the search results.
When this happens you can use the sitelinks section on Google Webmasters. Once you navigate to this section within your site area you will see the following form:
Google Sitelinks Demotion Search Result
The highlighted text field is not the sitelink URL that you wish to demote. It is for the page that the sitelinks will show up for. It's the URL that's displayed at the top of the search listing. If you want your home page to have sitelinks then you leave this field blank and put the sitelink URL in the field below.
You can demote up to 100 sitelinks per site and Google does state that it can take some time to make the changes to sitelinks and they are effective for 90 days from your most recent visit to the Sitelinks page in Webmaster Tools.

Tuesday, 5 August 2014

Geocaching API with PHP 5

After dealing with the over complicated Geocaching API I decided that I would write a little blog for anyone else who is struggling. The connection is made using OAuth. To get access to the API you had to go through their process of filling in a form manually. However they're not currently accepting any new requests. 
For my demonstration I am using Composer PHP Dependency Manager. You can choose to download and install it yourself (easier to do so on Mac) or you can grab my full code of at the end of this blog.

Ill go through the code now though so we have a better understanding how it works and the requests are made:
First of all we turn on error reporting and start a session:
spl_autoload_register(function ($classname) {
    $classname = ltrim($classname, "\\");
    preg_match('/^(.+)?([^\\\\]+)$/U', $classname, $match);
    $classname = str_replace("\\", "/", $match[1]). str_replace(array("\\", "_"), "/", $match[2]) . ".php";
    include_once __DIR__ . '/src/' . $classname;
});
We then autoload the OAuth class so we can use it. Once this has been loaded in we then declare to the server that we are using these classes
use Geocaching\OAuth\OAuth as OAuth,
    Geocaching\Api\Json as Json;
The next two sections provide some basic logic. The first section simply removes the cookie and destroys the session to reset the form when the reset button is pressed
if(isset($_POST['reset'])) {
    $_SESSION = array();
    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', 0);
    }
    session_destroy();
    header('Location: index.php');
    exit(0);
}

if(!array_key_exists('production', $_SESSION) && array_key_exists('url', $_POST)) {
    switch ($_POST['url']) {
        case 'live_mobile':
        case 'live':
            $_SESSION['production'] = true;
            $_SESSION['url'] = $_POST['url'];
            break;
        case 'staging':
        default:
            $_SESSION['production'] = false;
            $_SESSION['url'] = $_POST['url'];
    }
}

The next section control what redirect URL is used to allow the user to sign into GC.com. The options are staging which is for testing purposes only, live and live mobile which obviously link to the live site but have different styles.
if (!isset($_SESSION['ACCESS_TOKEN'])) {

    $callback_url = 'http://' . $_SERVER['HTTP_HOST'] . OAuth::getRequestUri();

    //First step : Ask a token, go to the Geocaching OAuth URL
    if(isset($_POST['oauth']) && isset($_POST['oauth_key']) && isset($_POST['oauth_secret'])) {
        $consumer = new OAuth($_POST['oauth_key'], $_POST['oauth_secret'], $callback_url, $_SESSION['url']);
        $consumer->setLogging('/tmp/');

        $token = $consumer->getRequestToken();
        $_SESSION['OAUTH_KEY'] = $_POST['oauth_key'];
        $_SESSION['OAUTH_SECRET'] = $_POST['oauth_secret'];
        $_SESSION['REQUEST_TOKEN'] = serialize($token);
        $consumer->redirect();
    }

    //Second step : Go back from Geocaching OAuth URL, retrieve the token
    if(!empty($_GET) && isset($_SESSION['REQUEST_TOKEN'])) {
        $consumer = new OAuth($_SESSION['OAUTH_KEY'], $_SESSION['OAUTH_SECRET'], $callback_url, $_SESSION['url']);
        $consumer->setLogging('/tmp/');
        $token = $consumer->getAccessToken($_GET, unserialize($_SESSION['REQUEST_TOKEN']));
        $_SESSION['ACCESS_TOKEN'] = serialize($token);
        header('Location: index.php');
        exit(0);
    }
}

The last section here is the interaction with GC.com. In the first step with ask for the request token and go to the Geocaching OAuth URL declared by the switch statement. GC.com then sends us back to our page and we go to the second step which goes back to GC.com to retrieve the access token. Once we have our access token we are redirected back to our page for a final time we the ability to make requests
if (isset($_SESSION['ACCESS_TOKEN']))
        {
            $token = unserialize($_SESSION['ACCESS_TOKEN']);
            echo "Token: " . $token['oauth_token'].""; $api = new Json($token['oauth_token'], $_SESSION['production']); $api->setLogging('/tmp/'); $params = array('PublicProfileData' => true); try { $user = $api->getYourUserProfile($params); } catch(Exception $e) { echo '' . $e->getMessage() . ''; } echo "Connected as: " . $user->Profile->User->UserName . " (Id = " . $user->Profile->User->Id . ")"; preg_match('/([0-9]+)/', $user->Profile->PublicProfile->MemberSince, $matches); $memberSince = date('Y-m-d H:i:s', floor($matches[0]/1000)); echo "Member since: " . $memberSince . "";

echo "<hr>";
The access token is stored into the session data so we can revisit our page without having to go through the request process again. When we come to making requests for data we first have to check that the token is in the session array. If it is then we proceed and after unserializing the token we call in the Json class with the token and production type (live, mobile or staging) so we can make the request.
In this example we are just going to make a simple request for the current users profile data.
This is done by running the getYourUserProfile function from the Json class. Each function has a set of parameters needed, in our case just the one is needed which is declared in $params as an array.
We have a try catch to display any errors should the request fail for any reason. When a request is carried out successfully you should be presented with your Geocaching username and ID along with some basic profile information.
This is my first ever blog and the code is basically taken from Surfoo's Github. The reason I have decided to elaborate and do my own blog is because his example doesn't work out of the box. I created my own little demo and put it on on my own Github. All you will have to do is drop this on a server that supports PHP5+, enters your Geocaching API keys and it should work.