gpeopl.es

Numerous ramblings on current affairs, philosophy, technology and religion

March 2, 2013
by Gareth Peoples
0 comments

QUnit, Javascript and Mock Objects

Following on from the previous post where I was testing some logical functionality in JavaScript it is possible to see that QUnit can provide simple assertions for logical statements like in other unit testing frameworks. However, there are times when you need to test functions and classes which take in complex objects as parameters as opposed to simple types.

JavaScript perhaps comes in quite strongly because it is not a strongly typed language, which of course has some disadvantages in general, but in terms of unit testing this is a very good thing. Unlike languages like C# where it is very difficult to mock an object without using interfaces or other levels of abstraction, this is not an issue as you can construct any object that conforms to what is being tested irrespective of type. The only major consideration that will come into whether or not something is testable is not manipulating the document in a direct manner (pass in an element triggered on an event rather than directly manipulating the DOM using JQuery). Another consideration will be if you are using AJAX requests you might want to check the functionality around the AJAX request rather than testing the ordinary transmission of data, that is if we are considering unit testing rather than end-to-end testing which QUnit is built for thanks to asynchronous testing (a functionality in QUnit which is also nicely geared towards setTimeout).

Example: let’s consider UI interaction
This again is very simple, it’s just to get across the basic idea of mock objects and QUnit. All we’re going to work towards is to have a div with a blue background, and when you click on it, it will turn red. For the purposes of this let’s look to our unit test class and write our additional tests to the js/tests.js file that we created last time. We’re assuming that all ui functionality will be contained in logic.ui, and we want to see the class change from blue, to red (the element object literal is serving as our mock object).

test('recolour test from blue', function () {
    var element = {
        className: 'blue'
    };
    logic.ui.change_color(element);
    ok(element.className == 'red')
});

Run the tests watch them fail and let’s make them pass.

Setting up the CSS with our two classes blue and red respectively:

.blue {
    background-color: #0094ff;
    width: 300px;
    height:  400px;
}

.red {
    background-color: #ff0000;
    width: 900px;
    height: 1200px;
}

Setting up the HTML page:

< !DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
        <link rel="stylesheet" href="css/main.css" type="text/css" />
        <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
        <script type="text/javascript" src="js/logic.js"></script>
        <script type="text/javascript" src="js/bindings.js"></script>
    </head>
    <body>
        <div id="box" class="blue"></div>
    </body>
</html>

Let’s look to implementing the logic in our logic.js class. Notice we’re creating a new object literal (or a sub object literal) for implementing the new methods.

logic.ui = {
    change_color: function (element) {
                    element.className = 'red';
                  }
};

Let’s set up our bindings for JQuery (using bindings.js)

$(function () {
    $('#box').bind('click', function () { logic.ui.change_color(this); });
});

Then we’re done. We should see our tests pass. But let’s say that we’re not happy with that and we also want to see it toggle back in the other direction.

Let’s go to js/tests.js again and write another test that will check the opposite direction:

test('recolour test from blue', function () {
    var element = {
        className: 'red'
    };
    logic.ui.change_color(element);
    ok(element.className == 'blue')
});

Like last time let’s watch it fail. After that’s established let’s move to refactor our old code inside the change_color method on the logic.ui sub-literal:

logic.ui = {
    change_color: function (element) {
        if (element.className == 'blue') element.className = 'red';
        else if (element.className == 'red') element.className = 'blue';
    }
};

As you watch the tests pass you’ll see that you’ve been using QUnit tests to test your user interface logic in Javascript, you’ll also have seen how easy it is to mock these element objects to do your tasks.

Please comment if you have any questions or if something needs correcting.

March 1, 2013
by Gareth Peoples
0 comments

QUnit, Javascript and TDD

At work we’ve been cleaning up JavaScript in our ASP.NET projects. After stumbling along a small but reasonably powerful unit testing framework I must say I’m convinced that JavaScript is one of the easiest languages to create useful unit tests in, one of the easiest languages to use for Test Driven Development and one of the easiest languages to use for mocking.

Example: let’s consider pure logic without any user interaction.
Simple stuff, addition, subtraction, multiplication and division. Before you start, you’ll need to download the QUnit JavaScript and CSS files, and copy the text for the sample test runner. Create a test javascript file, and create a test logic file (I created a js folder and this test.js, and logic.js accordingly).

Let’s create our tests and watch them fail. In QUnit the test syntax is rather straight forward. Let’s assume that all our logic will be in logic.calculate until we implement it:

test("addition test", function() {
    var x = 2;
    var y = 3;
    var result = logic.calculate.addition(x, y);
    ok(result == 5);
});

test("multiplication test", function() {
    var x = 7;
    var y = 4;
    var result = logic.calculate.multiplication(x, y);
    ok(result == 28);
});

test("division test", function () {
    var x = 32;
    var y = 4;
    var result = logic.calculate.division(x, y);
    ok(result == 8);
});

test("subtraction test", function () {
    var x = 10;
    var y = 2;
    var result = logic.calculate.subtraction(x, y);
    ok(result == 8);
});

Create the test runner by copying and pasting the below HTML (as per the QUnit website) for the test runner:

< !DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>QUnit Example</title>
  <link rel="stylesheet" href="/css/qunit-1.11.0.css">
</link></meta></head>
<body>
  <div id="qunit"></div>
  <div id="qunit-fixture"></div>
  <script src="/js/qunit-1.11.0.js"></script>
  <script src="/js/tests.js"></script>
<script src="/js/logic.js"></script>
</body>
</html>

When you load the tests.html you should see all the tests fail using the QUnit runner. This is good, this is what we expect considering we’ve not actually done any of the code yet. We expect whatever we write to do the number crunching necessary for addition, subtraction, multiplication, and division.

Using the JavaScript object literal notation, let’s write an object to do this for us, and write only so much code that it passes. So in our logic.js file we can make it look as follows:

var logic = {};

logic.calculate = {
    addition: function (x, y) {
        return (x + y);
    },
    subtraction: function (x, y) {
        return (x - y);
    },
    multiplication: function (x, y) {
        return (x * y);
    },
    division: function (x, y) {
        return (x / y);
    }
};

That’s it, click on the test.html page for the test runner and you should see them all pass.

November 5, 2011
by Gareth Peoples
0 comments

Thoughts on Blasphemy against the Holy Spirit

This week we were studying Mark chapter 3 at our small group at church. As we came to the section where Jesus claims that all sins and blasphemies can be forgiven but whoever blasphemes against the Holy Spirit cannot be forgiven (Mark 3:29).

And the scribes who came down from Jerusalem were saying, “He is possessed by Beelzebul,” and “by the prince of demons he casts out the demons.” And he called them to him and said to them in parables, “How can Satan cast out Satan? If a kingdom is divided against itself, that kingdom cannot stand. And if a house is divided against itself, that house will not be able to stand. And if Satan has risen up against himself and is divided, he cannot stand, but is coming to an end. But no one can enter a strong man’s house and plunder his goods, unless he first binds the strong man. Then indeed he may plunder his house. “Truly, I say to you, all sins will be forgiven the children of man, and whatever blasphemies they utter, but whoever blasphemes against the Holy Spirit never has forgiveness, but is guilty of an eternal sin”—for they were saying, “He has an unclean spirit.” (Mark 3:22-30 ESV)

This reminded me of a campaign on Youtube a few years ago by the Rational Response Squad called the Blasphemy Challenge.  This campaign brought hundreds of people to their cameras to reject the existence of the Holy Spirit under the presumption that they would be damned to hell in a Christian understanding for doing so:

But is this what the passage is saying? – Is it saying that if you deny the Holy Spirit that you are barred from salvation for life? I don’t think so. The clue for me is in the text. If we look more closely to verse 29 we get a better idea of what Jesus is trying to say, putting particular emphasis on the tense used.

“Truly, I say to you, all sins will be forgiven the children of man, and whatever blasphemies they utter, but whoever blasphemes against the Holy Spirit never has forgiveness, but is guilty of an eternal sin”—for they were saying, “He has an unclean spirit.”

Blasphemes in this passage is written in the present tense  rather than in the past tense. The passage as such isn’t saying whoever has ever blasphemed the Holy Spirit at any one point in their lives will be forgiven, but rather for as long as someone blasphemes they will not be able to come to forgiveness through Jesus Christ.

How can you be brought from the domain of darkness into the Kingdom of God’s Son Jesus where there is the forgiveness of sins (Colossians 1:13-14)  if that isn’t what you desire? – If one doesn’t desire to come to Christ one isn’t forced to, that is the nature of ones free will.

The broader question seems to be how can you be forgiven if you don’t want to be forgiven? The context of either side of this passage also gives us a little more perspective as to why this should be the case.  In the previous section we have both Jesus’ family claim that He is mad (Mark 3:21), and the Pharisees claiming that Jesus was casting out demons in the name of Satan rather than in the name of God and Jesus’ response to that objection, essentially how could one plunder Satan’s house with his blessing, the simple paradox of Satan casting out Satan (Mark 3:21-27). In the following section of this passage we have Jesus at his house with His disciples and with His family, where He says “For whoever does the will of God, he is my mother, my brother, and my sister and my mother” (Mark 3:35). This is the radical conclusion that as important as family was in Jewish society that faith is more important in terms of the Kingdom of God that Jesus had come to proclaim (Mark 1:14-15).

Simply put, I do believe that all blasphemy can be forgiven including blasphemy against the Holy Spirit if one is willing to stop, think, and ask God for mercy thus no longer blaspheming against the Spirit.

If you disagree with me I’d love to hear, feel free to leave a comment under this post.

August 6, 2011
by Gareth Peoples
12 Comments

Flowplayer secure plugin with PHP

A few months ago I was saying that I was working on a team project at university. We mainly used the flowplayer API to create a video site where videos could be uploaded and commented on (You can still see it here for now).

One of the interesting issues that arose when we were doing this was that we wanted to allow for some security so that users couldn’t directly download videos unless they had the sufficient privileges to do so. I looked to the flowplayer secure plugin for information, but the tutorials were mainly geared towards web server solutions such as using plugins for lighttpd or wowza webserver. However, if you were using Apache or simply didn’t want to have to go to the headache of configuring plugins there wasn’t much other option at least as the website suggested. I thought that sharing this piece of code which has no doubt given other people plenty of headaches would be useful to someone in some way.

Eventually through tweaking both on the flowplayer JS code and tweaking with the apache mod_rewrite tool and a PHP script to interpret the parameters that were passed in such as name timestamp and an md5 hash in the URL. On the md5 hash being validated correctly the PHP script would provide the correct video. The videos would be blocked from direct access with the mod_rewrite tool.

PHP:

<?php
/* Time limitation using secure plugin flowplayer
@author Gareth Peoples
*/

session_start();
$hash = $_GET['h'];
$streamname = $_GET['v'];
$originaltimestamp = $_GET['t'];
$timestamp = ceil($originaltimestamp / 1000);
$current = time();
$token = get_secret();
$checkhash = md5($token . "/" . $streamname . $originaltimestamp);
if (($current - $timestamp) <= 6 && ($checkhash == $hash)) {
    mysql_connect("localhost", "username", "password");
    mysql_select_db("yourdb");
    $query = mysql_query("select videopath from videos where id = '$streamname'");
    $streamname = mysql_result($query, 0, 'videopath');
    get_file();
}
else {
header('Location: YOURURL');
}
// Get the file from the server
function get_file() {
    global $streamname;
    header('Content-Description: File Transfer');
        header('Content-type: video/mp4');
        header("Content-length: " . filesize($streamname));
        header("Expires: 0");
        header("Content-Transfer-Encoding: binary");
    $file = fopen($streamname, 'r');
    echo stream_get_contents($file);   
    fclose($file);
    exit;
}
// Return secret to flowplayer for use
function get_secret() {
    $token = '69964920064c0a7626e6c97997070fcd';
    return $token;
}
?>

Flowplayer JS:

/* Javascript for secure plugin
   @author Gareth Peoples
   @team Team Northwestern
   @email mail@gpeopl.es / gareth.peoples.2009@nuim.ie
*/

var timestamp = +new Date();

flowplayer("player", "YOURURL/player/flowplayer-3.2.7.swf", {
plugins: {
    secure: {
        url: 'player/flowplayer.securestreaming-3.2.3.swf',
        timestamp: timestamp,
       // N.B For extra security you could generate the token randomly using AJAX rather than picking a random MD5 string
        token: '69964920064c0a7626e6c97997070fcd'
    }  
},

clip: {
    autoPlay: false,
    autoBuffering: true,
    duration: 30,
    urlResolvers: 'secure',
    baseUrl: 'YOURURL'
}
});

.htaccess:

RewriteEngine on
RewriteRule ^(.*)/(.*)/(.*)$ YOURURL/videos/index.php?h=$1&t=$2&v=$3
RewriteRule ^$ YOURURL

So to explain it briefly:
Flowplayer JS sets up the link in the format baseUrl/hash/timestamp/streamName. As a result you need a .htaccess file in Apache to parse the URL in this format and to pass it into your PHP script, which in my case makes the hash $_GET['h'] the timestamp $_GET['t'] and the video name or in my case the video name is the video id in the database. If this isn’t that case for you you can alter the script accordingly.
The PHP script parses the variables that are received, converts the timestamp from milliseconds (JS) into seconds (PHP) and then checks if less than 6 seconds has passed since the URL was generated and if the hash is correct. If either of these conditions don’t satisfy then the video won’t be accessible by that URL any longer and a new URL will be required.

Make sure to change the YOURURL’s and the database info accordingly. If you have any questions please feel free to contact me on Twitter or leave a comment on the blog. If you have found this useful or are using it on your website I’d be very interested to hear. Or indeed if you have and will be making improvements to this code I’d also be really interested to hear this.

May 9, 2011
by Gareth Peoples
0 comments

Stepping out into the unknown

In continuing my look into the Torah or the books of the Jewish law I just have to mention one of the most striking passages in it as far as I’m concerned. The passage deals with courage and fear during the time that the Israelites are in the desert on their way from Egypt to the Promised Land and two people, namely Joshua son of Nun and Caleb son of Jephunneh amongst others spy out the land of Caanan before the Israelites enter. The point of the blogs on the Hebrew Scriptures namely the Torah or the first 5 books of the Bible (Genesis, Exodus, Leviticus, Numbers and Deuteronomy) is to show that there is actually a wealth of significance in these texts, and there is much that these texts can teach us in the 21st century despite the fact that they were written in antiquity. I have to emphasise that I am not a theologian or a Biblical scholar and I do of course welcome criticism and new perspectives into what I’m looking into.

The text I’m looking at is from Numbers 14:6-24 (the text is viewable by clicking on the link, click the box to close it). Fear is something that we can encounter a lot particularly when we are stepping into the unknown. Things that we are far from acquainted with. Humans have a tendency to desire to be in control, yet at the same time we cannot be in control of fate, or indeed in circumstance. From a Christian perspective it is believed that ultimately God is in control, but sometimes believing it is difficult when we can’t seem to understand what direction things are going in. Habakkuk (a book that we studied at our Christian Union this semester) over the next while is a key voice in the Bible that expresses sheer confusion and unbelief in the face of God’s plan. Very often we don’t understand what it is or how it can make sense. Habakkuk speaks out of frustration of being unable to hear God in the society he is in. One that has largely rejected God in practice. When God does answer, Habakkuk is hugely confused, asking if the Lord is really from everlasting? Why would he choose sinners like the Babylonians to punish the people of Israel? (Habakkuk 1:12)

In the text we’re looking at in Numbers when Joshua and Caleb are returning back from the land there is much confusion amongst the congregation of Israel as to what God’s plan really is for them. Joshua and Caleb tell the congregation of Israel what they had seen when they were spying in the land of Caanan. Joshua tells them about the land and how great it is. One can tell that both he and Caleb are clearly enthusiastic about what God has given to them (Numbers 13:30-31). The others who went up with them have no faith in their abilities, they are discouraged. But Joshua and Caleb are confident that they have God on their side, and that He is surely with them:

If the LORD is pleased with us, he will lead us into that land, a land flowing with milk and honey, and will give it to us. Only do not rebel against the LORD. And do not be afraid of the people of the land, because we will swallow them up. Their protection is gone, but the LORD is with us. Do not be afraid of them.”
Numbers 14:8-9 (NIV)

The Israelites have forgotten. They forgot what God did for them in the Exodus. They forgot that it was only by God’s strength that they are where they are right now. We can sit here and criticise the Israelites for this attitude but ultimately with how much are we willing to trust God? How much do we fear others in making our decisions, and in how much are we willing to truly appreciate that God is there even when things look scary ahead? Sometimes we find that it is very little, but we just have to take that moment to sit and reflect over what God has done in our lives and what a gracious God He is. Things can often look bleak but we have to remind ourselves that God has put us here for a reason, even if sometimes that reason seems indiscernible to us. Life decisions will lead us to a number of places, some times it seems that there are numerous possibilities before us and we aren’t quite so sure where we will be in the future.

When the Israelites did decide to attempt to enter the land of Canaan their attack failed, largely because it was too late. They put their trust in themselves rather than in what was revealed to them by God (Numbers 14:39-45). It is funny how it almost seems easier to live and focus on life if we can rely on secular endeavour. If we have our own abilities what is there to really need from anything else including God for that matter? The difference is that Caleb and Joshua were willing to step forward in faith and were willing to put their very lives and destiny into God’s hand. The reason I guess why I like this passage is that I aspire in my faith to live as Caleb and Joshua did giving each and every day into God’s hand, particularly when ultimately I can’t really know what is coming next.

May 7, 2011
by Gareth Peoples
0 comments

Osama bin Laden: a philosophical take

Osama bin Laden

A lot has happened within the last week from the UK royal wedding, Northern Ireland, Scotland and Wales assembly elections, AV referendum. But nothing has been talked about to the extent of Osama bin Laden’s death in a US military operation last weekend. Was it right that people celebrated his death in the streets of New York? In an interview with Sean Hannity last week Rudy Giuliani suggested that it wasn’t the time to celebrate this:

And the information isn’t all accurate but a lot of it is and we can’t give that up. And the other thing that we can’t have happen — you know, I had a mixed feeling about the elation last night, you know, the celebrations in Washington and celebrations in New York. I can understand the emotion and I sort of appreciated the fact that people haven’t forgotten. But I thought this is not the time yet to celebrate. We’re still in the middle of this. We have it one — this is not like winning the second World War.

I have much the same feeling as Rudy Giuliani on this, but for very different reasons. His reasoning is just that well, the war on terror isn’t over. Indeed one could wonder if it would ever be over because people will rise up in bin Laden’s place and indeed people have risen up in events all over the world since 9/11. It only takes a reminder to last years (thankfully largely unsuccessful) suicide bombing in Stockholm, or even last week a look into the terror plot in respect to Sellafield nuclear power plant which followed from bin Laden’s death (although police are reluctant to draw any substantive connection between both events) to see this.

Is this the only reason why we could oppose the type of celebration that we have seen in America over bin Laden’s death. Even if bin Laden is the worst person in the world, and even if he is the orchestrator of countless murders, we need to consider something about what makes the human being a human being. Is a person on birth doomed to commit what is evil, or is it because of a multitude of variables that a person becomes what they are. Culture, family, surroundings, political environment, and so on. One could find countless factors that ultimately make people who they are.

As a result, can we not see bin Laden as a being who is a result of many variables, or that bin Laden could have been an entirely different person were different variables presented before him. Now, don’t get me wrong in writing this I’m not saying that bin Laden should be regarded as being off the hook. Rather I am saying that it should be regarded as a profound tragedy that Osama bin Laden chose to live the life he did rather than live another life that wouldn’t have brought about the same destruction, suffering and hurt that he did. Indeed, if we are to take a look at this from an empirical point of view, that knowledge is gained by experience and that personality is developed by it we start to see this from a different perspective.

The 17th century philosopher John Locke presented that each person in the beginning is merely a tabular rasa or a blank slate. Experiences are if you will what make this blank slate into a substantive I, or you, or anyone else. This of course brings in to other questions such as whether or not people who have become brain dead are in earnest the people who they actually say they are, but I will leave such questions aside for clarity. As we continue to live these experiences are continually chipped into our very being, we become shaped by them. Are we saying that it is really so easy to stay away from systems of thought that breed hostility? We know that this can’t be the case given clear history.

As a Christian the perspective differs even more. Christopher Morgan professor of theology at California Baptist University wrote an article on The Gospel Coalition website the day after the event took place. He brings in the concept of eternal punishment. He notes that it is a tragedy that Osama bin Laden lived a life which rejected the living God, but at the same time he notes that it is justice (not just in the mere fact that He died) that these events have happened. There is a diachotomy between the inherent tragedy that lies in the fact that people have refused to live by God’s standards in His world and indeed respecting the lives of all those whom He created, but also the inherent justice that results from this having taken place after the evil that Osama bin Laden via Al Queda has perpetrated.

What do these events mean as far as the world is concerned however? That seems a lot more uncertain. The BBC has covered the statement that Al Queda have given acknowledging the death of Osama bin Laden vowing to continue terrorist attacks as usual. It seems that things are more rather than less volatile for the near future, and it seems that even as Obama praises those who took part in this operation that (as Rudy Giuliani mentioned earlier) there will be more threats into the future, probably so much that one wonders if they can ever be truly subdued. I don’t feel this is something to celebrate, it is ultimately a great tragedy. Yes, we can feel some relief that justice has been done, but ultimately bin Laden is liable to a punishment that cannot even be contemplated by man.

May 7, 2011
by Gareth Peoples
0 comments

PHP / AJAX search suggestion

Following on from the previous code that I provided for the AJAX comment system, I thought that I might share with you some code that I have written for a suggest search function like what is seen in our team project. Obviously for legal reasons I won’t be showing you anything other than what I personally have contributed. As with the last case, this includes four major components, XHTML 1.0, PHP and Javascript, and CSS.

The idea is that this code will on each key press into the search box send a request to PHP to run a search query using the string that is currently in the searchbox. On doing this PHP will return at maximum the top 3 results ordered according to whatever you put in the query (I will be leaving the query blank in the PHP so you can use your own as far as I know most search queries use the LIKE syntax in MYSQL). On receiving the PHP javascript turns the results DIV in the XHTML and CSS to unhidden so that it can display the results as an overlay over the page.

As mentioned if you have any questions about the code please leave a comment on the blog or send me a tweet. I hope that this will be useful.
XHTML –

        < ?xml version='1.0' encoding='utf-8' ?>
        < !DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'
        'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
        <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en'>
        <head>
            <!-- Title on webpage -->
            <title>suggest search - gpeopl.es </title>
            <!-- CSS style sheet references -->
            <link rel='stylesheet' href='main.css' type='text/css' title='main'/>
       
            <!-- Javascript references -->
            <script type='text/javascript' src='suggest.js'></script>
        </head>
        <body>
       
            <!-- Search box -->
            <div id='search'>
                <form action='search.php' method='get'>
                <input type='text' id='searchbox' name='search' onkeyup='suggest();'/>
                <input type='submit' value='search' />
                </form>
                <div id='suggest'></div>
                </div>
        </body>
        </html>

CSS –

#suggest {
    visibility: hidden;
    position: absolute;
    padding-top: 5px;
}

#suggestion {
    width: 700px;
    font-family: Segoe UI;
    font-size: 10pt;
    background: #FFFFFF;
    word-wrap: break-word;
    border-left: 1px #444444 solid;
    border-right: 1px #444444 solid;
}

Javascript -

/* AJAX suggest code
@author Gareth Peoples
@e-mail mail[at]gpeopl.es
*/


function suggest() {
var string = document.getElementById('searchbox').value;
var suggestarea = document.getElementById('suggest');
suggestarea.style.visibility = 'visible';
if (string == "") suggestarea.style.visibility = 'hidden';
var url = 'suggest.php';
var params = 'suggest=' + string;
http.open("POST", url, true);
// Header information here
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
    http.onreadystatechange = function() {
        if (http.readyState == 4) {
        suggestarea.innerHTML = http.responseText;
        }
    }
    http.send(params);
}

PHP -

<?php
/* Search suggest class in PHP
   @author Gareth Peoples
   @email mail[at]gpeopl.es
*/

$connection = mysql_connect('localhost', 'youruser', 'yourpassword');
$database = mysql_select_db('yourdb');
class suggest {
    // Suggest function for AJAX search box script
    function suggest($string) {
        $query = mysql_query("YOUR QUERY HERE");
        if(!$query) die('Invalid query: '.mysql_error());
        $numrows = mysql_num_rows($query);
       
            if ($numrows > 0) {
            $numresults = 3;
            if ($numresults > $numrows) $numresults = $numrows;
            for ($i = 1; $i < = $numresults; $i++) {
                 $title = stripslashes(mysql_result($query, ($i-1), 'title'));
              $description = stripslashes(mysql_result($query, ($i-1), 'description'));
              $videoid = stripslashes(mysql_result($query, ($i-1), 'id'));
              if ($i == 1 && $numresults != 1) echo "<div id='suggestion' style='border-top: 1px #444444 solid; border-bottom: 1px #444444 dashed;'>";
              else if ($numresults == 1) echo "<div id='suggestion' style='border-bottom: 1px #444444 solid; border-top: 1px #444444 solid;'>";
              else if ($i == $numresults) echo "<div id='suggestion' style='border-bottom: 1px #444444 solid;'>";
              else echo "<div id='suggestion' style='border-bottom:  1px #444444 dashed;'>";
              echo "YOUR QUERY RESULT CONTENT IN HERE</div>";
            }
        }
    }
}

// If POST suggest != do an AJAX query on database
if ($_POST['suggest'] != null) {
    $string = $_POST['suggest'];
    $suggest = new suggest($string);
}
?>
</div></div>

May 6, 2011
by Gareth Peoples
8 Comments

PHP / AJAX comment system

It’s been a while since I posted, but as I said a few months ago I have been working on a team project in Computer Science amongst finishing off my studies in philosophy. For my team project I got back into developing in Javascript / PHP / CSS and XHTML 1.0. A lot of the stuff is familiar to me since I have developed in PHP for roughly 5 years now. What was new is using AJAX more and more, and indeed it is the first large project I have worked on in a long time which allowed me to use Object Oriented PHP code structure. As a part of this project we had to work on an individual page.

Our individual page had to include a comment section, which is what I’m looking to share with you on this blog. The page uses an AJAX auto-refresh  feature, and is a very basic system where people can post comments, the form is validated to 175 characters in Javascript and to make sure it isn’t empty. There is no user management or deletion mechanism as it’s meant to be a raw system.

The code works very simply. The XHTML requests a Javascript function get_comments(1) where 1 is page 1 of the comments. AJAX requests this from the PHP which grabs this from MYSQL and Javascript places the HTML that is returned by PHP into the box. Javascript also refreshes the page that one is on in the comments every 5 seconds giving it a live feel. So if one is on page 5 page 5 will load every five seconds. In terms of posting, the script checks if the form is empty, if so it returns this error to the user, it checks and limits characters to 175 characters which is slightly more than a tweet. If these conditions are satisfied AJAX sends a post request to the PHP which is handled. In the event that there is an error PHP returns false which Javascript interprets as 0, and if it succeeds it returns a 1. The PHP is written in an object oriented manner with some external PHP code to handle POST requests. Apart from this there isn’t very much PHP on the actual link to the individual page.

I hope you find this useful, if you have any questions leave them in the comment area below this blog post or on my twitter page and I will see what I can do! I will be putting up some code on PHP / AJAX search suggest on this page very shortly also.

XHTML 1.0 -

&lt; ?xml version='1.0' encoding='utf-8' ?&gt;
&lt; !DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'&gt;

&nbsp;

<!-- Javascript references -->&nbsp;

<script type="text/javascript" src="js/comment.js"></script>
<div class="sidebar">
<h1><a name="comments"></a>Comments</h1>
<em>Post a comment:</em>
<textarea id="commentbox" onkeypress="limit_text();" name="comment" rows="5" cols="35"></textarea>
<p align="right">
</p>

<input id="commentbutton" onclick="post_comment()" type="button" value="Post comment" /></div>

PHP -

&lt; ?php
/* Comment class for individual project
@author Gareth Peoples
@email mail@gpeopl.es
*/


$connection = mysql_connect('localhost', 'dbusername', 'dbpassword');
$database = mysql_select_db('database');

class comment {
function insert_comment($comment) {
$comment = mysql_real_escape_string(strip_tags($comment));
if ($comment == null) {
return "empty";
}
else {
$date = date('jS \of F h:i:s A');
$query = mysql_query("insert into comments (comment, date) values ('$comment', '$date')");
if ($query) {
return true;
}
else {
return false;
}
}
}
function get_comments($page) {
$perpage = 5;
$query = mysql_query('select * from comments order by id desc');
$numrows = mysql_num_rows($query);
$last = ceil($numrows / $perpage);
if ($numrows &gt; 0) {
$result = "";
$i = ($page - 1) * $perpage;
$j = ($page * $perpage);
if ($j &gt; $numrows) $j = $numrows;
while ($i &lt; $j) {
$comment = stripslashes(mysql_result($query, $i, 'comment'));
$date = mysql_result($query, $i, 'date');
$result .= "
<div class="
comment">$comment</div>
<p class="
date" align="right">$date</p>
"
;
$i++;
}
if ($last &gt; 1) {
for ($i = 1; $i &lt; = $last; $i++) {
if ($i != $last &amp;&amp; $i != $page) $result .= "<strong><a onclick="get_comments($i);" href="#comments">$i</a>,";
else if ($i == $page &amp;&amp; $i != $last) $result .= "</strong><strong>$i</strong>,";
else if ($i == $page &amp;&amp; $i == $last) $result .= "<strong>$i</strong>";
else $result .= "<strong><a onclick="get_comments($i);" href="#comments">$i</a>";
}
}
return $result;
}
return 'There are no comments yet, be the first!';
}
}</strong>

// Post function for dealing with Javascript AJAX comments
if ($_POST['function'] == 'post' &amp;&amp; $_POST['comment'] != null) {
$comment = new comment();
$thecomment = $_POST['comment'];
echo $comment-&gt;insert_comment($thecomment);
}
// Function to grab all the comments from the database (pagination later)
else if ($_POST['function'] == 'get' &amp;&amp; $_POST['page'] != null) {
$comment = new comment();
$page = $_POST['page'];
echo $comment-&gt;get_comments($page);
}
?&gt;

Javascript -

/* AJAX functionality for comments
@author Gareth Peoples
@e-mail mail[at]gpeopl.es
*/

var currentpage = 1;
var http = false;
http = new XMLHttpRequest();
// Update AJAX comments every 5 seconds
setInterval('get_comments(currentpage)', 5000);

function post_comment() {
var errorbox = document.getElementById('errorbox');
var commentbox = document.getElementById('commentbox');
var url ='backend/comment.php';
var params ='function=post&amp;comment=' + commentbox.value;
http.open("POST", url, true);
if (commentbox.value != "") {
// Header information here
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if (http.readyState == 4) {
if (http.responseText == 1) {
get_comments(1);
commentbox.value = '';
errorbox.style.visibility = 'visible';
errorbox.style.color = '#008811';
errorbox.innerHTML = 'Comment successfully posted';
}
else {
errorbox.style.visibility = 'visible';
errorbox.style.color = '#FF0000';
errorbox.innerHTML = 'Error: database error!';
}
}
}
http.send(params);
}
else {
errorbox.style.visibility = 'visible';
errorbox.style.color = '#FF0000';
errorbox.innerHTML = 'Error: comment box is empty';
}
}

function get_comments(page) {
currentpage = page;
var commentarea = document.getElementById('commentcontainer');
var url = 'backend/comment.php';
var params = 'function=get&amp;page=' + page;
http.open("POST", url, true);
// Header information here
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if (http.readyState == 4) {
commentarea.innerHTML = http.responseText;
}
}
http.send(params);
}

function limit_text() {
var maxlength = 175;
var currentcharacters = document.getElementById('commentbox').value.length;
var commentbox = document.getElementById('commentbox');
var errorbox = document.getElementById('errorbox');
if (currentcharacters &gt; maxlength) {
errorbox.style.visibility = 'visible';
errorbox.style.color = '#FF0000';
errorbox.innerHTML = 'There is a 175 character limit';
commentbox.value = commentbox.value.substring(0, maxlength);
}
}

March 21, 2011
by Gareth Peoples
0 comments

Most who claim to be Christians in UK don’t believe Jesus existed…

Census form

image from BBC

There was a very interesting story covered by both the BBC and the Guardian this morning about a survey that the British Humanist Association has commissioned in order to encourage people in Britain to put “No Religion” on the census for their Census campaign.

The striking quote in the article was:

It also showed that 48% of the people interviewed who said they were Christian believed that Jesus was a person.

The Guardian

Among respondents who identified themselves as Christian, fewer than half said they believed Jesus Christ was a real person who died, came back to life and was the son of God.

BBC

This issue is one of the few issues I agree with the British Humanist Association and indeed the Humanist Association of Ireland and Atheist Ireland who have also been campaigning for similar measures in the Irish census. Naturally it is best to tell the Government the truth about your convictions and in general so that they can be aware of the current state in respect to it. However, it is evident that this issue tackles far more than honesty, but that nature of Christianity itself.

This raises the question of what Christianity is? If Christianity doesn’t have anything distinctive to believe concerning the life of Jesus, and if it doesn’t have anything distinctive to say about our relationship with God, what is it that distinguishes Christians in creed from non-Christians?

Indeed, why is the Resurrection so essential to the Christian faith? Why did the first Apostles go from seeing Jesus die, to going out into the world proclaiming that He had risen to new life and that we could receive new life through his death and Resurrection. When Paul the Apostle was writing a letter to the community of Christians in Rome in the New Testament he wrote the following about the Resurrection as being central for the Christian experience:

Or don’t you know that all of us who were baptised into Christ Jesus were baptised into His death? We were therefore buried with Him through baptism into death in order that just as Christ was raised from the dead through the glory of the Father, we too may live a new life. If we have been united with Him like this in His death, we will certainly be also reunited with Him in this resurrection. (Romans 6:3-5 NIV)

Paul in Romans places the crucifixion of Jesus and the new life of Jesus in the Resurrection as both being central to the Christian message. It is through Jesus standing in our place and taking the weight of our sin through His crucifixion that in His Resurrection that we stand justified before God able to begin a relationship with Him. The clear message that now that we have been justified by faith in Jesus’ crucifixion and Resurrection we can also live new lives different from the life governed by our sinful nature and that we can enjoy a new relationship with God free from the strain and guilt of sin.

It is this importance that leads him to write to the Corinthians that:

And if Christ has not been raised our preaching is useless and so is your faith [...] And if Christ has not been raised, your faith is futile and you are still in your sins. (1 Corinthians 15:14-17 – NIV)

Simply put the centrality of the crucfixion and Resurrection in the Christian faith simply cannot be denied. It is the centre of Christian experience. Indeed it is by knowing the love that Christ has shown for us through both the crucifixion and the Resurrection that we are told in 1 John 4 that we can authentically begin to love others. It is the centrality of Jesus’ existence in a snap shot of time on this earth that is so crucially important in what we believe. It is by Jesus humbling Himself in human flesh that we can begin to know the beginning of a relationship with God (Philippians 2). Indeed it is in Peter recalling the incredible encounter he had with Jesus in his existence amongst us that he begins his second letter writing:

We did not follow cleverly invented stories when we told you about the power and coming of our Lord Jesus Christ, but we were eye-witnesses of this majesty. (2 Peter 1:16 – NIV)

I hope to look into some of the key arguments defending the Christian belief in the Resurrection and real existence of Christ. I wholeheartedly agree with the British Humanist Association that denying that Jesus exists is a good reason to question the authenticity of claiming that one is a Christian when one can deny something so utterly central to the Christian faith as the existence of Jesus. If you’re reading this and are seriously thinking about what you would put down on the census next month, I’d really challenge you to read through the Gospels and see what Christians actually believe about the life and Resurrection of Christ and see a truth that changed the world forever.

March 21, 2011
by Gareth Peoples
0 comments

Is there ever such a thing as just war?

Coalition airstrike in Libya

Coalition airstrike in Libya - photo by Reuters

The recent conflict in Libya and indeed in other nations right across the Arab world has been in my attention for some time now. The current situation in Libya is tragic, tragic in that it has come to this. It has been quite a while since my belief in pacifist means of engagement has been so shaken. That said I do have a number of concerns about the current state of events in Libya.

1. If Gaddafi is a tyrant and I truly believe he is, why aren’t we taking necessary action against other rogue states in that region and beyond? - Just recently in the midst of the Bahrain protests, Saudi Arabia and its other neighbours in the UAE and in Qatar sent troops into Bahrain to suppress the unrest. Why is military action acceptable in this case and not in the case of Bahrain? Indeed, I would suspect that it has much more to do with favourable trading partners rather than the actual genuine need to liberate countries under tyranny. Indeed in the case of Saudi Arabia itself run under absolute monarchy, limiting the freedom of religion of non-Muslims and inhibiting the freedom of women to live as equals in that society. One could also invoke other examples such as North Korea. The question lies in why is this happening now and here rather than anywhere else.

2. When did Gaddafi lose his legitimacy? - A few weeks ago Obama claimed that Gaddafi had lost all legitimacy to lead Libya. Indeed under both Brown and Blair there was amicable relations between the UK and Libya. Gaddafi has never been anything else but a dictator, so what legitimacy or democratic mandate did he have to rule in Libya to begin with?

3. Is this going to be a long term conflict? - Although the United Nations resolution has explicitly stated that no ground action can be mandated, Gaddafi himself has said that he will fight this as a war, along with absurd comments that this action is a Crusade against Islam despite the fact that the Arab League approved of the action and indeed Saudi Arabia and Qatar (the same nations that are currently suppressing the protest in Bahrain) approved it in the United Nations. Is it possible that Western powers could be caught in the conflict already? Which leads me onto my next question.

4. If public support outside the Western world and indeed in the Western world begins to wane would this leave us in a similar situation as in Iraq or Afghanistan? The Guardian yesterday reported that support amongst Arab nations, China and Russia had diminished after the first day of airstrikes which both deemed to be disproportionate. If the mandate of the people in the nations that originally supported these airstrikes deteriorates how will such nations manage to pull away from the conflict graciously?

5. If we do secure the result of bring in Libya into the control of rebels, what steps will be taken to transition into democracy - In numerous other scenarios such as the Islamic Revolution in Iran in 1979 against the Shah there have been transitions in power only from one tyrant to another. This action if it is to continue must also secure that there will actually be free elections in Libya and a fair representative democracy.

I’m still on the fence for now. If any of you have any thoughts they would be much much much appreciated. Ultimately it comes down to the simple question of whether or not there can be really a just war.