Adding SyntaxHighlighter JS to blogspot

by Noman Muhammad

SyntaxHighlighter is a bunch of Javascript files to help a developer/coder to post code snippets to website/blog and have it look pretty. It supports multiple language and its very easy to use and deploy it. Download SyntaxHighlighter.
Now extract the contents of the package and upload the Scripts and Styles folder to any host or website which can be linked from the blogspot site.
To make it work, now we need to edit our blog's template and add the following code after the <!-- end outer-wrapper --> tag:


<link href='http://[HOST URL]/SyntaxHighlighter.css' rel='stylesheet' type='text/css'/>
<script language='javascript' src='http://[HOST URL]/shCore.js'/>

<script language='javascript'>
dp.SyntaxHighlighter.BloggerMode();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

Now we need to add support for the languages we want. For example to add support for the language php and ruby we need to link to two files. shBrushPhp.js and shBrushRuby.js.
Another Interesting thing that Its not really needed to upload the code/files as those files are already hosted by google.code.
We can easily lined up to those files. So, the above code snippet with support for PHP and RUBY will be as below.

<link href='http://syntaxhighlighter.googlecode.com/svn-history/r57/trunk/Styles/SyntaxHighlighter.css' rel='stylesheet' type='text/css'/>
<script language='javascript' src='http://syntaxhighlighter.googlecode.com/svn-history/r57/trunk/Scripts/shCore.js'/>

<script language='javascript'>
dp.SyntaxHighlighter.BloggerMode();
dp.SyntaxHighlighter.HighlightAll('code');
</script<

<!--Support for php and ruby : -->
<script language='javascript' src='http://syntaxhighlighter.googlecode.com/svn-history/r57/trunk/Scripts/shBrushPhp.js'/>
<script language='javascript' src='http://syntaxhighlighter.googlecode.com/svn-history/r57/trunk/Scripts/shBrushRuby.js'/>

Syntaxhighlighter supports pre and textarea tags, but it will not work automagically, we need to put our code into the <pre> or <textarea>.

To add some php code to our blog we to put our code as follows:
<pre name="code" class="php">
---- PHP code goes here ----
</pre>

Similarly for Ruby Code:
<pre name="code" class="ror">
---- RUBY code goes here ----
</pre>

See details on that page

One important notice from Overview of SyntaxHighlighter Trying to highlight 10kb worth of text will result in JavaScript being aborted because of long execution time.

Command line PHP in Windows

by Noman Muhammad

In Linux (Ubuntu, Fedora) OS we have the PHP executable available in shell, so we can run command line php script. But in windows to do so, we have to set PHP executable as Windows path variable.
We can do that in two ways ...

1. Open the command prompt (start -> run -> cmd)
and type: set PATH=%PATH%;C:\path_to_php
here, "C:\path_to_php" is the physical folder where php.exe is located. In my case its on C:\xampp\php.

Now we can run PHP script from anywhere we want like this:
D:\>php -v
PHP 5.2.5 (cli) (built: Nov 8 2007 23:18:51)
Copyright (c) 1997-2007 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2007 Zend Technologies
with Zend Extension Manager v1.2.0, Copyright (c) 2003-2007, by Zend Technologies
with Xdebug v2.0.2, Copyright (c) 2002-2007, by Derick Rethans

Main problem of this method is this will affect only a single command prompt.

2. The second method will affect all command prompts. First, right click on "My Computer", then click on "Properties" - a dialog box with some tabs will appear.
Now from the tab named "Advanced" click on the button "Environment Variables". This will open the Environment Variables box. Now choose the Path variable from the system variables box and click Edit.
Append the variable value with:

;C:\path_to_php

here, "C:\path_to_php" is the physical folder where php.exe is located. In my case its on C:\xampp\php.
';' character is used to separate directories in the var, so be sure it’s present.

Thats all.

Copy to Clipboard !!! using Javascript

by Noman Muhammad

Copy to clipboard functionality is very useful when we want to copy any particular content of a web page automatically. I search over the net to know how to implement it. I found that almost every tutorial use the javascript function "execCommand()". Here is an example how I use it:


<body>
<script type="text/javascript">
function ClipBoard()
{
holdtext.innerText = copytext.innerText;
Copied = holdtext.createTextRange();
Copied.execCommand("RemoveFormat");
Copied.execCommand("Copy");
}
</script>


<SPAN ID="copytext" STYLE="background-color:pink">
COPY This Line!
</SPAN>

<TEXTAREA ID="holdtext" STYLE="display:none;"></TEXTAREA>
<BUTTON onClick="ClipBoard();">Copy to Clipboard</BUTTON>
</body>


When I click on the button the line "COPY This Line!" will be copied to the clipboard and then I can paste it anywhere.
But its not a solution of my problem when i open my page on Mozilla Firefox browser.
As per I know Firefox doesn't support the javascript function "execCommand()".

After some googling I find this link which solve my problem both for IE and FireFox. Here is my implementation of this:

<html>
<head>Copy to Clipboard</head>
<body>
<script type="text/javascript">
function copy_to_clipboard(text)
{
if(window.clipboardData)
{
window.clipboardData.setData('text',text);
}
else
{
var clipboarddiv=document.getElementById('divclipboardswf');
if(clipboarddiv==null)
{
clipboarddiv=document.createElement('div');
clipboarddiv.setAttribute("name", "divclipboardswf");
clipboarddiv.setAttribute("id", "divclipboardswf");
document.body.appendChild(clipboarddiv);
}
clipboarddiv.innerHTML='<embed src="clipboard.swf" FlashVars="clipboard='+
encodeURIComponent(text)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
}
}
</script>

<input type="text" id="rt" value="" />
<input type="button" value="Copy" onclick="copy_to_clipboard(document.getElementById('rt').value);" />

</body>
</html>


To use it for firefox I have to download the flash (.swf) file from here and placed at path where this function is placed or else source parameter for embed tag to be changed to correct path where the flash file is been placed.
I also need firefox plugins for flash player as it depends on flash.
Now if I write something on the text box and then press the button the written text on the input box will be copied to the clipborad.

It works very fine. :)

Fckeditor: Image resize on Upload

by Noman Muhammad

Fckeditor (Html text editor) v-2.6.4 does not have automatic image resizing feature on upload or at least i don't know :( whether this editor has this feature. So to be able to resize picture on upload via fckeditor i bring some changes on "commands.php" file of fckeditor files. This file located on '\editor\filemanager\connectors\php' of the fckeditor folder. Open this file and

1. go to line # 219. It looks like


move_uploaded_file( $oFile['tmp_name'], $sFilePath ) ;

This line is under the function 'FileUpload'

2. Now change the line to

if($sExtension == 'jpg' || $sExtension == 'jpeg' || $sExtension == 'gif' )
{
$uploadedfile = $_FILES['NewFile']['tmp_name'];

// Create an Image from it so we can do the resize
$src = imagecreatefromjpeg($uploadedfile);

// Capture the original size of the uploaded image
list($width,$height)=getimagesize($uploadedfile);

// For my purposes, I have resized the image to be
// 300 pixels wide, and maintain the original aspect
// ratio. This prevents the image from being "stretched"
// or "squashed". If you prefer some max width other than
// 300, simply change the $newwidth variable
$newwidth=300;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);

// this line actually does the image resizing, copying from the original
// image into the $tmp image
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

// now write the resized image to disk. I have assumed that you want the
// resized, uploaded image file to reside in the ./images subdirectory.
$filename = $_FILES['NewFile']['tmp_name'];
imagejpeg($tmp,$filename,100);
move_uploaded_file( $filename, $sFilePath ) ;
imagedestroy($src);
imagedestroy($tmp);
}
else
{
move_uploaded_file( $oFile['tmp_name'], $sFilePath ) ;
}

3. thats all.

It works for me and hope will for U :)

Scrolling PHP News Ticker

by Noman Muhammad

We often show latest news from various News Site RSS feed in our site. We can show this news as like as scrolling news in the TV channels. We called it news ticker. Here i show the steps that i do to show those news like TV channel scrolling news. I use this javascript file to do this. Here is my steps

1. create a index.php file and add these lines between body tag:

<DIV ID="TICKER" STYLE="width:520px; overflow:hidden"  onmouseover="TICKER_PAUSED=true" onMouseOut="TICKER_PAUSED=false">
<?php
include("xmlparser.php");
?>
</DIV>
<script type="text/javascript" src="webticker_lib.js" language="javascript"></script>


2. Download the webticker_lib.js javascript file from here

3. create a .php file name xmlparser.php and put those line:

<?php

$insideitem = false;
$tag = "";
$title = "";
$description = "";
$link = "";

function startElement($parser, $name, $attrs) {
global $insideitem, $tag, $title, $description, $link;
if ($insideitem) {
$tag = $name;
} elseif ($name == "ITEM") {
$insideitem = true;
}
}

function endElement($parser, $name) {
global $insideitem, $tag, $title, $description, $link;
if ($name == "ITEM") {
printf("<a href='%s' target='_blank'>%s</a> ",
trim($link),htmlspecialchars(trim($title)));
$title = "";
$description = "";
$link = "";
$insideitem = false;
}
}

function characterData($parser, $data) {
global $insideitem, $tag, $title, $description, $link;
if ($insideitem) {
switch ($tag) {
case "TITLE":
$title .= $data;
break;
case "DESCRIPTION":
$description .= $data;
break;
case "LINK":
$link .= $data;
break;
}
}
}


$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
$fp = fopen("http://bangla.irib.ir/index.php?option=com_rss&feed=RSS2.0&no_html=1","r")
or die("Error reading RSS data.");
while ($data = fread($fp, 4096))
xml_parse($xml_parser, $data, feof($fp))
or die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
fclose($fp);
xml_parser_free($xml_parser);

?>


Here "http://bangla.irib.ir/index.php?option=com_rss&feed=RSS2.0&no_html=1" is the rss feed address, from that i retrieve news. So we to change this address when we want to retrieve news from other RSS feeder.
Thats all. Now Run the index.php file and get news ticker in action.

Simple Javascript menu :OpenCube

by Noman Muhammad

Often we to create Javascript menu to use in website. Opencube provides a tremendous software to produce various type(horizontal/vertical) of menu and use it our site. This software can be downloaded from this link. For Linux/mac download from here. Use it and enjoy it :).

Simple Ajax Tab Menu

by Noman Muhammad

Ajax tab menu is very useful to show contents without reloading the full page. Last week i create a Ajax based tab menu. Basically i modified my menu by getting help from this link. Here i'll show the steps that i do to create this menu functional.

1. create a simple html file (index.html). Between body tag put these


<ul id="tabmenu">
<li onclick="makeactive(1)"><a class="" id="tab1">First Tab</a></li>
<li onclick="makeactive(2)"><a class="" id="tab2">Second Tab</a></li>
<li onclick="makeactive(3)"><a class="" id="tab3">Third Tab</a></li>
</ul>
<div id="content"></div>

Between head tag put these lines

<script language="JavaScript" type="text/javascript" src="ajax.js"></script>
<script language="JavaScript" type="text/javascript">
function makeactive(tab)
{
document.getElementById("tab1").className = "";
document.getElementById("tab2").className = "";
document.getElementById("tab3").className = "";
document.getElementById("tab"+tab).className = "active";
callAjax('content.php?content= '+tab, 'content', 'getting content for tab '+tab+'. Wait...', 'Error');
}
</script>


2. Now create the ajax.js that we add in our head section. These are the content of ajax.js

function callAjax(url, pageElement, callMessage, errorMessage) {
document.getElementById(pageElement).innerHTML = callMessage;
try {
req = new XMLHttpRequest(); /* e.g. Firefox */
} catch(e) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP"); /* some versions IE */
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP"); /* some versions IE */
} catch (E) {
req = false;
}
}
}
req.onreadystatechange = function() {responseAjax(pageElement, errorMessage);};
req.open("GET",url,true);
req.send(null);
}

function responseAjax(pageElement, errorMessage) {
var output = '';
if(req.readyState == 4) {
if(req.status == 200) {
output = req.responseText;
document.getElementById(pageElement).innerHTML = output;
} else {
document.getElementById(pageElement).innerHTML = errorMessage+"\n"+output;
}
}
}


3. Now we need another php file where output will be processed. Nmae it "content.php" and put these lines in it

<?php
if ($_GET['content'] == 1)
{
echo 'Content for Page 1';
}
if ($_GET['content'] == 2)
{
echo 'Content for Page 2';
}
if ($_GET['content'] == 3)
{
echo 'Content For Page 3';
}
?>


Thats all. Now run the index file and see the tab menu in action.
To get First Tab selected when the page loaded just add this( onload="makeactive(1)") to body tag. So in index.html body tag will look as like as that : <body onload="makeactive(1)">