Sunday, April 20, 2008

JavaScript to Detect Unsupported Browsers

Hi,

I have made made a script to detect if our website is compatible with the user browser.

I have pasted the script below..

So it checks if the user browser is ie7+,firefox2+,safari3+ or opera8+, is not it redirects to another page.

This script is included in two places:

http://discern.uits.iu.edu:8490/UI/index.php
http://discern.uits.iu.edu:8490/adminLogin.php

This is cuz I believe that all our pages use the session check to redirect the user who has not logged in to the login page.



//JavaScript Document
//Author: Saurabh Ajmera

//test for MSIE x.x;
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
{
var ieversion=new Number(RegExp.$1)
if (!(ieversion>=7))
window.location = "/UI/incompatible.html"

}
//test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
else if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent))
{
var ffversion=new Number(RegExp.$1)
if (!(ffversion>=2))
window.location = "/UI/incompatible.html"

}
//test for Opera/x.x or Opera x.x (ignoring remaining decimal places);
else if (/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent))
{

var oprversion=new Number(RegExp.$1)
if (!(oprversion>=8))
window.location = "/UI/incompatible.html"
}
//this took me the longest..only cuz apple uses altogether different naming convention..BAD APPLE!!
else if(/Mozilla[\/\s](\d+\.\d+)/.test(navigator.userAgent))
{
var badapple=new Number(RegExp.$1)
if (!(badapple>=5))
window.location = "/UI/incompatible.html"


}
else
window.location = "/UI/incompatible.html"

Wednesday, April 16, 2008

Help popup in JavaScript

I have made the help function in javascript.

This function will, popup a help message whenever the user clicks on the help link.

You need to include the file help.js which is present in the modules folder.
Example:
<script type="text/javascript" language="javascript" src="/modules/help.js"></script>

Usage:
<a href ="#" id=elementid onClick="helppopup('<elementid>,'the helptesting')">help</a>

Example:
<a href = "#" id="helpLink1" onclick="helppopup('helpLink1','the helptesting')">help</a>

Source Code:
//Javascript Document.
//Author:Saurabh Ajmera
function findPosition( oElement ) {
if( typeof( oElement.offsetParent ) != 'undefined' ) {
for( var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent ) {
posX += oElement.offsetLeft;
posY += oElement.offsetTop;
}
return [ posX, posY ];
} else {
return [ oElement.x, oElement.y ];
}
}
function helppopup(id,text)
{
helpwindow = window.open (" ",
"helpwindow","location=1,scrollbars=1,resizable=1,
width=350,height=250");
Element = document.getElementById(id);
pos = findPosition(Element);
helpwindow.moveTo(pos[0],pos[1]);
helpwindow.document.write(text)
}

Tuesday, April 1, 2008

JavaScript Code to protect against injection attacks

Description:

This code uses a simple regular expression to check if the user input contains any characters which might enable SQL injection attacks or Cross Site scripting attacks.

The code checks all the textarea and the input tags in the form tag and checks if the value entered by the user contains on of the special character matching the regular expression:
[\^\$\(\)\<\>\|\\\}\{\]\[\*\?%&\+\'@]

Usage:
  • Add the following line as the first line after beginning your form tag - <INPUT TYPE="hidden" NAME="regex" id="regex" VALUE="[\^\$\(\)\<\>\|\\\}\{\]\[\*\?%&\+\'@]" SIZE=50>. I could have declared this regular expression in the javascript itself, but for some reason, javascript could'nt find the any match if the match occurred at index 0, N This way seems to work for me.

  • Create an div element with id error -
  • <div id="error" align="center" style="background-color:#FF0000; color:#FFFFFF; display:block; width:inherit "> </div> <br />
    . You need this cas my script does getElementById('error').innerHTML to display the error message.

  • Call this script onSubmit. For example: <form method="post" name="frmEditAccount" action="../modules/processEditProfile.php" id="frmEditAccount" onSubmit="return inputValidation(frmEditAccount)">
    Here the onSubmit event calls the function inputValidation(frmEditAccount), cas I have doing some more validation besides just the security check. Thus my defination of inputValidation will look like.
  • function inputValidation(frm)
    {
    if(!securityCheck())
    {
    return false;
    }
    else
    {
    return validateEditProfile(frm);
    }
    }
    • Include the javascript file -
    • <script language="javascript" type="text/javascript" src="/modules/securityCheck.js">
      </script>


    • The only way this code can fail is, if someone has javascript disabled, I didn't had much time to figure out, how to detect if javascript is enabled on a browser, but If I find something I will be adding it to this script.
    • This code is working for the following forms:
    userRegistration, editProfile, projectCreate, and for the userHomePage, i.e. for the Search.

    I have pasted the code below. Please email me if you have any problems using the code.

    One more thing, debugging a JavaScript code is a developer's night mare, cas you have to completely depend on the browser. So if you are thinking of debugging a javascript code try using Firefox with a web developer extension, this will install a nice toolbar on firefox, n you can check various kind of errors, like JavaScript error, CSS error, etc...

    Please do not attempt to modify this code on the UITS server. If you think it is an important modification let me know about it.

    //JavaScript Document
    /*#########################################
    Author:Saurabh Ajmera
    Date:02/16/2008
    Description:This function does some security check, no special characters allowed!!
    ###########################################*/

    function isInputSecure(value)
    {
    //lets trim the extra space
    //alert('I am in..');
    var re;
    re = new RegExp(document.getElementById('regex').value);
    //alert(value.match(re))?0:1);
    return (value.match(re))?0:1

    }

    function securityCheck()
    {
    //alert("checkin..");
    //alert(document.getElementById(id).value);
    //if(!isInputSecure(document.getElementById(id).value))
    //{
    //var inputCount = document.evaluate("count(//input)", document, null, XPathResult.ANY_TYPE, null).numberValue;
    //alert("This document contains " + inputCount + " input tags");

    var j = 0;

    while(document.getElementsByTagName('textarea')[j++])
    {
    //alert(document.getElementsByTagName('textarea')[j-1].value);
    if(!isInputSecure(document.getElementsByTagName('textarea')[j-1].value))
    {
    //document.getElementsByTagName('input')[i]
    //alert(document.getElementsByTagName('textarea')[0].value);
    document.getElementById('error').innerHTML = 'For security reasons, you cannot enter the following characters as input:\n ^ $ ( ) < > | \ } { ] [ * ? % & + \' @ ] ';
    //alert("For security seasons, you cannot the following characters as input:\n ^ $ ( ) < > | \ } { ] [ * ? % & + ' @ ] ");
    return false;
    }
    //j++;
    }
    var i = 0;
    while(document.getElementsByTagName('input')[i])
    {
    //for(var i=0;i<=inputCount;i++) //{ //alert(document.getElementsByTagName('input')[i].value); if((!isInputSecure(document.getElementsByTagName('input')[i].value)) && (document.getElementsByTagName('input')[i].type != 'hidden')) { //document.getElementsByTagName('input')[i] document.getElementById('error').innerHTML = 'For security reasons, you cannot enter the following characters as input:\n ^ $ ( ) < > | \ } { ] [ * ? % & + \' @ ] ';
    //alert("For security seasons, you cannot the following characters as input:\n ^ $ ( ) < > | \ } { ] [ * ? % & + ' @ ] ");
    return false;
    }
    i++;


    }
    return true;



    }

Wednesday, March 12, 2008

Notifications

Finally, the notification module is ready.

But to make it work completely you have to call the addNotification function everytime you want to send a notification.

Description about addNotification is as follows:

addNotification($userID,$projectID,$fileID,$type);

This function takes four arguments viz:$userID, $projectID, $fileID, $type

There are four cases when a notification will be send:

  1. upload :(When a new file is uploaded a notification will be send to all the members of that project) So, Once a file is uploaded, you need to call addNotification. Useage: addNotification($userID,$projectID,$fileID,"upload");

  2. join: (When a new user has joined a project a notification will be send to all the members of that project) So, Once the user is approved by the system administrator, you need to call addNotification. Useage:addNotification($userID,$projectID,0,"join");

  3. request: (When a user requests to join a project a notification will be send to the owner of the project) So, once a user submits the request to join the project, call addNotification. Useage:addNotification($userID,$projectID,0,"request");

  4. invite: (When a user is invited to join a project) So, once a user is invited by the owner of the project to join the project call addNotification($userID,$projectID,0,"invite");

Sunday, March 2, 2008

Exception Handling

Here is how you need to make exception handling on your pages.
Displaying error message
displayError("sorry there is an error in data");
result: sorry there is an error in data
Query errors
errorHandler("sorry error in query");

Eg: $conn->query($query) or errorHandler("error message");
result: error message
Display success message
displayMessage("success in uploading file");

result : success in uploading file

Wednesday, February 20, 2008

Handling Sessions

Everytime a genuine user logs into the website we create a session object, which stores his userID.

Every page a user visits logging in to the wesite, should have a session check at the begining of each page. This is done by a function sessionExists().

This function checks if the session object is created for the particular user. If the session is created it will return true, else it will just redirect the user to the home page of this website.

Function: sessionExists()
Defination:
function sessionExists(){
//start the session session_start();
if(!session_is_registered('userID'))
{
//the session variable isn't registered, send them back to the login page
header( "Location: http://discern.uits.iu.edu:8490/UI/index.php" );
}
else {return true;}
}

Usage:
include("../modules/login_func.php");
if (sessionExists())
{
//your page
}

Saturday, February 9, 2008

Including a Java Script File

<html>
<head>
<script type="text/javascript" src="file.js"></script>

</head>
</html>

Please don't use the shortcut <script type="text/javascript" src="file.js" />
This causes problems with Internet Explorer 6, which doesn't load the JavaScript page.

Once you include the javascript file, it executes automatically when you load the HTML file. You can also group the code in JavaScript functions, which only executes when called explicitly(This is what we will be doing most of the time).