Quick tips for setting up Eclipse and Monkey

  • Optional – add whatever plugins that you think is useful for your development work.

Monkey Script

  • To create a monkey script, add a new file under the “monkey” folder (need to create in eclipse). Name the file “author.js” for example (we are going to create a macro to insert developer’s comments). Copy and paste the following code in author.js
/*
 * Menu: Editors > Developer's Comment
 * Key: M3+M2+a
 * DOM: http://download.eclipse.org/technology/dash/update/org.eclipse.eclipsemonkey.lang.javascript
 */
var newDate = new Date();
var comment = "@author Bernard Peh "+newDate;

var commentLength = comment.length;

function main() {

	var editor = editors.activeEditor;

	// get range of lines in the selection (or at the cursor position)
	var range = editor.selectionRange;
	var startLine = editor.getLineAtOffset(range.startingOffset);
	var endLine = editor.getLineAtOffset(range.endingOffset);

	// determine if we're adding or removing comments
	var source = editor.source;
	var offset = editor.getOffsetAtLine(startLine);
	var addComment = (source.substring(offset, offset + commentLength) != comment);
	var adjust = 0;

	editor.beginCompoundChange();

	if (addComment) {
		for (var i = startLine; i <= endLine; i++) {
			var offset = range.startingOffset;
                        // var offset = editor.getOffsetAtLine(i);
			editor.applyEdit(offset, 0, comment);
		}
	} else {
		for (var i = startLine; i <= endLine; i++) {
			var offset = range.startingOffset;
                        // var offset = editor.getOffsetAtLine(i);

			if (source.substring(offset + adjust, offset + adjust + commentLength) == comment) {
				editor.applyEdit(offset, commentLength, "");
				adjust += commentLength;
			}
		}
	}

	editor.endCompoundChange();
}

Everything in author.js is javascript. Modify as you see fit. More examples can be seen in the plugins dir (org.eclipse.eclipsemonkey_x.x.x.xxxxxx). Now in any document, just press alt+shift+a to insert the author’s comment. Imagine what you can do with this technique!!

 // eg. to add phpdoc using the shortcut, modify the variables
/*
 * Menu: Editors > php class header
 * Key: M1+M2+c
 * DOM: http://download.eclipse.org/technology/dash/update/org.eclipse.eclipsemonkey.lang.javascript
 */
var newDate = new Date();
var comment = "\t/*\n\t * shor desc\n\t * \n\t * long comments\n\t * @author Bernard Peh "+
newDate+"\n\t */";

/*
 * Menu: Editors > php function header
 * Key: M1+M2+f
 * DOM: http://download.eclipse.org/technology/dash/update/org.eclipse.eclipsemonkey.lang.javascript
 */
var newDate = new Date();
var comment = "\t/*\n\t * shor desc\n\t * \n\t * long comments\n\t * @author Bernard Peh "+
newDate+"\n\t * @param string $var desc\n\t * @return integer\n\t */";

Note

  • If the monkey shortcut key doesn’t work, check for keys conflict. Try out new key combination.
  • M1 is the COMMAND key on MacOS X, and the CTRL key on most other platforms. M2 is the SHIFT key. M3 is the Option key on MacOS X, and the ALT key on most other platforms. M4 is the CTRL key on MacOS X, and is undefined on other platforms.

Other Tips

  • CTRL + SHIFT + L : Shows you a list of your currently defined shortcut keys.
  • mouse over a function or class to see quick description.
  • CTRL + mouse over a function or class to see snippets of the class or function. While hovering the text, press F2 to see full code snippets.
M1 is the COMMAND key on MacOS X, and the CTRL key on most other platforms. M2 is the SHIFT key. M3 is the Option key on MacOS X, and the ALT key on most other platforms. M4 is the CTRL key on MacOS X, and is undefined on other platforms.

How to create a simple CMS without DB access

A Content Management System (CMS) allows you to update your website easily without touching anything in the backend. If you are a non-IT person, you will almost always want a CMS for your website because it makes you less dependent on your web designers or developers to add, edit or delete contents in your website.

There are many good CMS out there but most of them require some sort of database access in the backend. Many PHP CMS uses mysql or postgres database which resides in the server. Installation and troubleshooting of CMS might require some technical knowledge and server configuration could be daunting for some.

I was creating a website for a client recently when he requested a CMS for him to update the web pages during his free time. I was tempted to install a popular ready made CMS such as joomla but on futher thoughts, joomla on a small business website could be an overkill. The website would most likely not utilise many features of joomla and furthermore, his hosting package does not include a database (amazing). Given a short time frame to come up with a solution, I created a simple PHP script for him to do the job, ie to edit the content of a few web pages only.

In this example, we are going to create a simple CMS in PHP without the use of MYSQL, POSGRESQL or any other databases.

Simple Login Form

In a form, I added 2 fields, the username and password. The form is to post its data back to the same page so that we can verify whether the username and password fits with a preset value. The html code for the form is shown below:

<form method=”post” action=””>
<table width=”400″ border=”0″ align=”center” cellpadding=”2″ cellspacing=”2″>
<tr>
<td>Username: </td>
<td><input type=”text” name=”username”></td>
</tr>
<tr>
<td>Passwd: </td>
<td><input type=”password” name=”passwd”></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type=”submit” name=”Submit” value=”Submit”>&nbsp;&nbsp; <input type=”reset” name=”reset” value=”Reset”>
</td>
</tr>
</table>
</form>

Once the username and password are verified, a username session will be triggered to remember that the administrator has logged into the system. We will prompt the user if they enter the wrong details.

if (isset($_POST[‘Submit’])) {
if (($_POST[‘username’] == ‘admin’) && ($_POST[‘passwd’] == ‘yourpassword’)) {
$_SESSION[‘username’] = ‘login’;
}
else {
echo “<b>You login details is not correct. Pls login again</b>”;
}
}

If everything goes well as expected, a quick menu will be displayed. The menu consists of a few links to the files that are editable. In this case, the links are pointing to the home and contact us page. There is also a link to logout from the system.

if ($_SESSION[‘username’]==’login’) {
echo “<p align=’center’>
<a href=”?file=../index.html”>Home Page</a><br/>
<a href=”?file=../contact_us.html”>Contact Us</a><br/>
<br/>
<em>Click on the links above to edit the files.</em><br/>
<a href=”?logout”>logout</a></p>”;
}

Creating Start and End Points in the HTML Files

Before we can start editing the content, we have to tell the CMS which part of the content is editable. In order to do that, we need to create a unique marking in the HTML file. The HTML code for my home page may look like this:

<html>
<body>
<div class=’header’>
This is my header
</div>
<div class=’main’>
Contents written here can be edited
</div>
</body>
</html>

If I want all the contents within the <div class=’main’> to be editable, I need to add my own unique code just for the sake of marking the editable region. So the new HTML code might look like this:

<html>
<body>
<div class=’header’>
This is my header
</div>
<div class=’main’>
<!– EDITABLE –>
Contents written here can be edited
<!– EDITABLE –>
</div>
</body>
</html>

The Decoding Engine

What we have done in the previous step is really to encode the HTML file with the <!– EDITABLE –> tag. We now need to decode it. Thanks to the PHP explode function, we can now strip out the <– EDITABLE –> tag and get the contents.

if (isset($_REQUEST[‘file’])) {
$fc = file_get_contents($_REQUEST[‘file’]);
$text = explode(“<!– EDITABLE –>”,$fc);
echo “<form method=’post’ action=”><textarea name=’content’>$text[1]</textarea>”;
echo “<p><input type=’hidden’ name=’file’ value='”.$_REQUEST[‘file’].”‘ />
<input name=’submitUpdate’ type=’submit’ value=’Update Page’></form>”;
}

The variable $text is an array. $text[0] and $text[2] corresponds to the content before and after the tag <!– EDITABLE –>. Therefore $text[1] is the editable text we want and we display it in the textarea.

Capturing the Edited Content

The edited content is passed again back to the same page via the $_POST variable. If the submit button has been clicked, we will update the home page content. The way we do it is similar to how we strip the <!– EDITABLE –> tag using the explode function. Because we are actually writing to a file, not to a database, we need not add escape characters to the content. PHP version 4.x has magic_quotes turned on by default which happens to escape all our $_POST variables. So if magic_quotes is turned on, we need to unescape the $_POST variables.

if (isset($_POST[‘submitUpdate’])) {
if (get_magic_quotes_gpc()) {
$_POST = array_map(‘stripslashes’,$_POST);
}

$fc = file_get_contents($_POST[‘file’]);
// truncate file
$fw = fopen($_POST[‘file’], ‘w+’);
$text = explode(“<!– EDITABLE –>”,$fc);

$newText = $text[0].”<!– EDITABLE –>”.htmlentities($_POST[‘content’]).”<!–EDITABLE ->”.$text[2];
if (fwrite($fw, $newText)===FALSE) {
die(“Cannot write to file.”);
}
fclose($fw);
exit(“<div><span class=’redText’>The file has been updated. Click <a href=\”index.php\”>here</a> to go back to admin page.</div>”);
}

In the function “file_get_contents”, we get the contents of the file to be edited and strip them into 3 parts again. Noticed that I need to clear my original file with a fopen($_POST[‘file’], ‘w+’).

Now, we rejoin the 3 parts back again. Our edited content is actually in $_POST[‘content’] but it might consists of some illegal characters which has certain meaning in PHP. So we need to convert them into the HTML equivalent using the htmlentities function. We then close the file.

The codes may seem complicated but the logic should be simple enough. One thing to note though is that the content is displayed in a textarea. This means that the user has to put in their own html tag such as <b>, <p> …etc if they want any text formating. You can also add in a HTML editor to make the text formatting easier. I actually used fckeditor with this content management system in my client’s website.

The full source code at my website – PHP CMS.

Online Calendar Using PHP and AJAX Update 1

A bit of history if you are interested

I can vaguely recalled that a designer friend wanted to add a calendar to a custom made CMS. We searched high and low found a few good ones – some commercial and some open source. He found the installation and configuration daunting though.

As a programmer, I knew that playing with dates is always complicated. That is why, creating a calendar from scratch is not a simple task. At about the same time, I was researching in how to create a calendar in a quick and efficient way. After a few days of hard work, I managed to come up with a quick solution. To make his life easier, I combined the source code and the cofiguration variables into one file so he can just include one php line in his current CMS and get it to work. The quick calendar turned out to be functional and good enough to meet the deadline.

I then decided to share the code in evolt.org and received alot of request to add more features. Well, that was good and bad news for me. Good news because many people like it – felt good; Bad news because my daytime work became hectic and I don’t have the time!

Thanks for the support

I would like to thank everyone at evolt.org for giving ideas and commenting on the quick calendar. I hope many people find it useful. It has been a year++ since I last updated it…  as mentioned, I didn’t have the time to improve on it. The christmas break provided me some time to re-look at the calendar again. I took on the comments that you guys left on the evolt article or emailed me and made some changes. It turned out that the changes I’ve made was quite major. I’ve updated the code. check it out:

quick calendar demo 1 | quick calendar source

The installation instructions is in the source code.

As you can see, my css skills aren’t that great. Well, I am not a designer.

One big change was the addition of more comments in the source code. I hope that will make things easier if you decide to hack it (you might need to if you want drastic change in the layout for now). The structure of the class has been changed as well. Instead of using 2 separate classes and aggregation, I decided to use one base calendar class and inheritance. There were also some tweaks in the logic and bug fixes.

I still think there are room for improvements:

1. I like to separate the presentation from logic. At the moment, the QCalendarStandard class is working like a ‘view’, creating all the html code. Not ideal. Ultimately, the user should be able to design the layout without touching the source code.

2. As the calendar becomes more flexible, there is a need to separate the application into a few files. Perhaps a config file, a css file, a base class file, a few more extension classes, a template file. This also means that the installation becomes slightly complex (something against my wish!!). I was struggling with this for a long time. It was the first time I chunked all the code into one file. The reason was simple – I wanted to make the installation idiot proof, minimise installation procedures and reduce the complication with other running apps.

3. Use PHP 5 Coding standards. Eg using “__construct” and proper variable declaration. I purposely made it in PHP 4 two years ago because I knew alot of apps are still using PHP 4. Its probably time to upgrade.

4. I think the way the ajax function – qCalendarDetails() is being used to display the long description is kinda doggy. I probably need to rethink that part or create a user friendly admin panel to administer the calendar.

5. Yes, I think adding a  calendar admin panel is a good idea.

6. Possible to use css to create the calendar instead of using tables.

I will post the more information on how to use the calendar  in the demo soon.

Search Engine Rankings With PEAR SOAP

Google implemented a search API in 2002 for web developers to do Google search within their own website. By using SOAP (Simple Object Access Protocol) procedures, the API allows the search and results retrieval to run in the background.

I have implemented a google search function in this website using PEAR SOAP. The script loops through google searched results to find how well you rank for certain keywords in google.

/google_api_search.php

download the source code – google api search with pear soap

Online Calendar Using PHP and AJAX

This calendar plugs in seamless with any content management system you are using. With Ajax, your screen need not be refreshed. The functionality can be easily extended using inheritance.

The full demo can be seen here – PHP Ajax Calendar and source code is here – Simple PHP Calendar Source.