Tuesday, 2 October 2012

mail are delivered in the spam folder instead of inbox


How to Avoid Spam Filters with PHP mail() Emails

Just about everyone who uses PHP has encountered the popular PHP mail() function which enables email to be sent from a server. This function is preferred to other methods of sending email, such as sending mail with SMTP Authentication, because its implementation is quick and easy. Unfortunately, when using the mail() function, your emails are more likely to be marked as spam. So how can we fix this?
A Simple Implementation Example

Many users of the mail() function often have simple implementations as shown in the code sample below:

<?
mail("recipient@recipient.com", "Message", "A simple message.", "From: The Sender <sender@sender.com>");
?>

While this implementation will successfully send an email, the email will probably get caught in the recipient’s spam filter. Fortunately, there are some simple fixes that can help you avoid spam filters.
4 Ways To Make Your PHP mail() Emails Less Spammy
1. Use Headers

In the simple example above, the from name and email address was added as the fourth parameter. Instead, consider using headers to set your From and Reply-To email addresses.

<?
  $headers .= "Reply-To: The Sender <sender@sender.com>\r\n";
  $headers .= "Return-Path: The Sender <sender@sender.com>\r\n";
  $headers .= "From: The Sender <senter@sender.com>\r\n";
?>

But headers  are good for more than just setting details about the sender. They are also important for setting the content type, the email priority, and more. Here are how some additional headers look.

<?
  $headers .= "Organization: Sender Organization\r\n";
  $headers .= "MIME-Version: 1.0\r\n";
  $headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
  $headers .= "X-Priority: 3\r\n";
  $headers .= "X-Mailer: PHP". phpversion() ."\r\n"
?>

Be sure to replace the fourth parameter with the $headers variable as shown below.

<?
mail("recipient@recipient.com", "Message", "A simple message.", $headers);
?>
2. The Message Sender Domain and Server Domain Should Match

Spammers are notorious for sending emails from one server and trying to make the recipient believe that it came from somewhere else. So if you are sending an email from example@example.com, it is a good idea the the script reside on example.com.
3. Be Sure to Properly Use the Content-type Attribute

The Content-type attribute enables a message sender to say whether or not an email is plain text  or html, or whether it has attachments. Obviously, the easiest to use content type is text/plain. You just add your text as shown in the simple example, and you are done. But when you use the other content types, additional pieces might be expected. For example, with the text/html content type, an html body tag is expected. Not having this tag could result in your email being marked as spam.
4. Verify That Your Server Is Not Blacklisted

When a server is blacklisted, it means that that server has identified as one that has been sending a lot of spam. This results in recipient mail servers rejecting or filtering any mail that is received from that server.

So if your mail is not being received it is a good idea to verify that your server has not been blacklisted. This goes for both shared and dedicated servers. In a shared environment, it is common for other users on the server to be sending out spam. And in a dedicated environment, spammers may have found a way to exploit a vulnerability in a server or contact form to send out spam. So it is easy for either type of server to be blacklisted.



Alright, now that you have the basics on avoiding spam filters, reconstruct your scripts and happy emailing!

Tuesday, 4 September 2012

What is .htaccess? Its used


In order to specify your own customized error documents, you simply need to add the following command, on one line, within your htaccess file:
ErrorDocument code /directory/filename.ext
or
ErrorDocument 404 /errors/notfound.html
This would cause any error code resulting in 404 to be forward to yoursite.com/errors/notfound.html

Likewise with:
ErrorDocument 500 /errors/internalerror.html
You can name the pages anything you want (I'd recommend something that would prevent you from forgetting what the page is being used for), and you can place the error pages anywhere you want within your site, so long as they are web-accessible (through a URL). The initial slash in the directory location represents the root directory of your site, that being where your default page for your first-level domain is located. I typically prefer to keep them in a separate directory for maintenance purposes and in order to better control spiders indexing them through a ROBOTS.TXT file, but it is entirely up to you.
If you were to use an error document handler for each of the error codes I mentioned, the htaccess file would look like the following (note each command is on its own line):
ErrorDocument 400 /errors/badrequest.html
ErrorDocument 401 /errors/authreqd.html
ErrorDocument 403 /errors/forbid.html
ErrorDocument 404 /errors/notfound.html
ErrorDocument 500 /errors/serverr.html
You can specify a full URL rather than a virtual URL in the ErrorDocument string (http://yoursite.com/errors/notfound.html vs. /errors/notfound.html). But this is not the preferred method by the server's happiness standards.
You can also specify HTML, believe it or not!
ErrorDocument 401 "<body bgcolor=#ffffff><h1>You have
 to actually <b>BE</b> a <a href="#">member</A> to view 
this page, Colonel!
The only time I use that HTML option is if I am feeling particularly saucy, since you can have so much more control over the error pages when used in conjunction with xSSI or CGI or both. Also note that the ErrorDocument starts with a " just before the HTML starts, but does not end with one...it shouldn't end with one and if you do use that option, keep it that way. And again, that should all be on one line, no naughty word wrapping!


For to password protect a directory and all the directories below.
Put a file named .htaccess in the directory you want to password protect with the follow text.


AuthUserFile /opt/guide/www.widexl.com/.htpasswd
AuthType Basic
AuthName "Member Page"
require valid-user

For to password protect the admin.pl script.
You can use wildcards for this, like: "*.html"   "*.zip"

<files "admin.pl">
AuthUserFile /opt/guide/www.widexl.com/.htpasswd
AuthType Basic
AuthName "Administrator script"
require valid-user
</files>

AuthUserFile: This is the full path to your password file
AuthType: This need to be Basic.
AuthName: This is the name (Realm) you want to give to your password protected site.


top
Auth Digest

MD5 Digest authentication provides a more secure password system than Basic authentication, but only works with supporting browsers. The only major browsers which support digest authentication are Internet Explorer 5.0, Amaya and Konqueror from KDE2. I don't think its save for Big Brother, but it's always more save than Auth Basic. And most users are using Internet Explorer 5.0 or higher.
Module: mod_digest (old version)
Module: mod_auth_digest (new version)
OS: Unix, Linux, WinNT.

Don't use both modules on the same time.

Setting up MD5 Digest authentication is easy.
Put a file named .htaccess in the directory you want to password protect with the follow text.

Example: mod_digest

AuthDigestFile /opt/guide/www.widexl.com/.htpasswd
AuthType Digest
AuthName "Member Page"
require valid-user

Example: mod_auth_digest

AuthDigestFile /opt/guide/www.widexl.com/.htpasswd
AuthType Digest
AuthName "Member Page"
AuthDigestDomain /member/ http://www.widexl.com/members/
AuthDigestNonceLifetime 300
require valid-user


Enabling SSI Via htaccess

Many people want to use SSI, but don't seem to have the ability to do so with their current web host. You can change that with htaccess. A note of caution first...definitely ask permission from your host before you do this, it can be considered 'hacking' or violation of your host's TOS, so be safe rather than sorry:
AddType text/html .shtml
AddHandler server-parsed .shtml
Options Indexes FollowSymLinks Includes
The first line tells the server that pages with a .shtml extension (for Server parsed HTML) are valid. The second line adds a handler, the actual SSI bit, in all files named .shtml. This tells the server that any file named .shtml should be parsed for server side commands. The last line is just techno-junk that you should throw in there.
And that's it, you should have SSI enabled. But wait...don't feel like renaming all of your pages to .shtml in order to take advantage of this neat little toy? Me either! Just add this line to the fragment above, between the first and second lines:
AddHandler server-parsed .html
A note of caution on that one too, however. This will force the server to parse every page named .html for SSI commands, even if they have no SSI commands within them. If you are using SSI sparingly on your site, this is going to give you more server drain than you can justify. SSI does slow down a server because it does extra stuff before serving up a page, although in human terms of speed, it is virtually transparent. Some people also prefer to allow SSI in html pages so as to avoid letting anyone who looks at the page extension to know that they are using SSI in order to prevent the server being compromised through SSI hacks, which is possible. Either way, you now have the knowledge to use it either way.
If, however, you are going to keep SSI pages with the extension of .shtml, and you want to use SSI on your Index pages, you need to add the following line to your htaccess:
DirectoryIndex index.shtml index.html

jQuery - Selectors


The jQuery library harnesses the power of Cascading Style Sheets (CSS) selectors to let us quickly and easily access elements or groups of elements in the Document Object Model (DOM).
A jQuery Selector is a function which makes use of expressions to find out matching elements from a DOM based on the given criteria.

The $() factory function:

All type of selectors available in jQuery, always start with the dollar sign and parentheses: $().
The factory function $() makes use of following three building blocks while selecting elements in a given document:
jQueryDescription
Tag Name:Represents a tag name available in the DOM. For example $('p') selects all paragraphs in the document.
Tag ID:Represents a tag available with the given ID in the DOM. For example $('#some-id') selects the single element in the document that has an ID of some-id.
Tag Class:Represents a tag available with the given class in the DOM. For example $('.some-class') selects all elements in the document that have a class of some-class.
All the above items can be used either on their own or in combination with other selectors. All the jQuery selectors are based on the same principle except some tweaking.
NOTE: The factory function $() is a synonym of jQuery() function. So in case you are using any other JavaScript library where $ sign is conflicting with some thing else then you can replace $ sign by jQuery name and you can use function jQuery() instead of $().

Example:

Following is a simple example which makes use of Tag Selector. This would select all the elements with a tag name p.
<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   
   <script type="text/javascript" language="javascript">
   $(document).ready(function() {
      var pars = $("p");
      for( i=0; i<pars.length; i++ ){
         alert("Found paragraph: " + pars[i].innerHTML);
      }
   });
   </script>
</head>
<body>
   <div>
      <p class="myclass">This is a paragraph.</p>
      <p id="myid">This is second paragraph.</p>
      <p>This is third paragraph.</p>
   </div>
</body>
</html>

How to use Selectors?

The selectors are very useful and would be required at every step while using jQuery. They get the exact element that you want from your HTML document.
Following table lists down few basic selectors and explains them with examples.
SelectorDescription
NameSelects all elements which match with the given element Name.
#IDSelects a single element which matches with the given ID
.ClassSelects all elements which match with the given Class.
Universal (*)Selects all elements available in a DOM.
Multiple Elements E, F, GSelects the combined results of all the specified selectors E, F or G.
Similar to above syntax and examples, following examples would give you understanding on using different type of other useful selectors:
  • $('*'): This selector selects all elements in the document.
  • $("p > *"): This selector selects all elements that are children of a paragraph element.
  • $("#specialID"): This selector function gets the element with id="specialID".
  • $(".specialClass"): This selector gets all the elements that have the class of specialClass.
  • $("li:not(.myclass)"): Selects all elements matched by <li> that do not have class="myclass".
  • $("a#specialID.specialClass"): This selector matches links with an id of specialID and a class of specialClass.
  • $("p a.specialClass"): This selector matches links with a class of specialClass declared within <p> elements.
  • $("ul li:first"): This selector gets only the first <li> element of the <ul>.
  • $("#container p"): Selects all elements matched by <p> that are descendants of an element that has an id of container.
  • $("li > ul"): Selects all elements matched by <ul> that are children of an element matched by <li>
  • $("strong + em"): Selects all elements matched by <em> that immediately follow a sibling element matched by <strong>.
  • $("p ~ ul"): Selects all elements matched by <ul> that follow a sibling element matched by <p>.
  • $("code, em, strong"): Selects all elements matched by <code> or <em> or <strong>.
  • $("p strong, .myclass"): Selects all elements matched by <strong> that are descendants of an element matched by <p> as well as all elements that have a class of myclass.
  • $(":empty"): Selects all elements that have no children.
  • $("p:empty"): Selects all elements matched by <p> that have no children.
  • $("div[p]"): Selects all elements matched by <div> that contain an element matched by <p>.
  • $("p[.myclass]"): Selects all elements matched by <p> that contain an element with a class of myclass.
  • $("a[@rel]"): Selects all elements matched by <a> that have a rel attribute.
  • $("input[@name=myname]"): Selects all elements matched by <input> that have a name value exactly equal to myname.
  • $("input[@name^=myname]"): Selects all elements matched by <input> that have a name value beginning with myname.
  • $("a[@rel$=self]"): Selects all elements matched by <p> that have a class value ending with bar
  • $("a[@href*=domain.com]"): Selects all elements matched by <a> that have an href value containing domain.com.
  • $("li:even"): Selects all elements matched by <li> that have an even index value.
  • $("tr:odd"): Selects all elements matched by <tr> that have an odd index value.
  • $("li:first"): Selects the first <li> element.
  • $("li:last"): Selects the last <li> element.
  • $("li:visible"): Selects all elements matched by <li> that are visible.
  • $("li:hidden"): Selects all elements matched by <li> that are hidden.
  • $(":radio"): Selects all radio buttons in the form.
  • $(":checked"): Selects all checked boxex in the form.
  • $(":input"): Selects only form elements (input, select, textarea, button).
  • $(":text"): Selects only text elements (input[type=text]).
  • $("li:eq(2)"): Selects the third <li> element
  • $("li:eq(4)"): Selects the fifth <li> element
  • $("li:lt(2)"): Selects all elements matched by <li> element before the third one; in other words, the first two <li> elements.
  • $("p:lt(3)"): selects all elements matched by <p> elements before the fourth one; in other words the first three <p> elements.
  • $("li:gt(1)"): Selects all elements matched by <li> after the second one.
  • $("p:gt(2)"): Selects all elements matched by <p> after the third one.
  • $("div/p"): Selects all elements matched by <p> that are children of an element matched by <div>.
  • $("div//code"): Selects all elements matched by <code>that are descendants of an element matched by <div>.
  • $("//p//a"): Selects all elements matched by <a> that are descendants of an element matched by <p>
  • $("li:first-child"): Selects all elements matched by <li> that are the first child of their parent.
  • $("li:last-child"): Selects all elements matched by <li> that are the last child of their parent.
  • $(":parent"): Selects all elements that are the parent of another element, including text.
  • $("li:contains(second)"): Selects all elements matched by <li> that contain the text second.
You can use all the above selectors with any HTML/XML element in generic way. For example if selector $("li:first") works for <li> element then $("p:first") would also work for <p> element.

Thursday, 16 August 2012

integrate icici payment gateway php without JavaBridge/JDK



The Installation process for SFAClient.zip

 

1.     Unzip SFAClient.zip. This will create a folder called SFAClient
2.    SFAClient contains the following files and directory.
1.     Sfa – SFA Client library (contains the PHP Sfa library)
2.     Test Pages – Sample pages for transactions and a test page (test.php) for testing php.
3.     sfa.properties

PHP Web Application Directory Structure – Sample Example

·         Create the following  PHP Web application directory structure as given below
o   E.g. the Merchant website directory name is “Merchant_Site_Dir”.
·         Copy all the directory and files from unzipped SFAClient to Merchant_Site_Dir .



§  Place the directory Merchant_Site_Dir in C:/wamp/www/ as shown below.
·         Sfa, Test Pages and sfa.properties



Note:
§  Sfa folder should be copied to the folder where TestPages/Merchant pages are present.
§  The directory names are case sensitive. Create them as mention above.











Changes in Test Pages

  • Open the SFAResponse.php and made some changes

<?php
include("Sfa/EncryptionUtil.php");


                        $strMerchantId="00000001";
                        $astrFileName="c://key//sbi//00000001.key";
                        $astrClearData;
                        $ResponseCode = "";
                        $Message = "";
                        $TxnID = "";
                        $ePGTxnID = "";
                        $AuthIdCode = "";
                        $RRN = "";
                        $CVRespCode = "";
                        $Reserve1 = "";
                        $Reserve2 = "";
                        $Reserve3 = "";
                        $Reserve4 = "";
                        $Reserve5 = "";
                        $Reserve6 = "";
                        $Reserve7 = "";
                        $Reserve8 = "";
                        $Reserve9 = "";
                        $Reserve10 = "";


Note : Mercant ID must be same as the .key file name. e.g. if file is 00000001.key then Merchant ID must be 00000001.

  • According to merchant type i.e. SSL or MOTO change select the file and make the changes
    • e.g. if Merchant is SSL Merchant then change the TestSsl.php
<?php


include("Sfa/BillToAddress.php");
include("Sfa/CardInfo.php");
include("Sfa/Merchant.php");
include("Sfa/MPIData.php");
include("Sfa/ShipToAddress.php");
include("Sfa/PGResponse.php");
include("Sfa/PostLibPHP.php");
include("Sfa/PGReserveData.php");

 $oMPI                        =          new     MPIData();

 $oCI               =          new     CardInfo();

 $oPostLibphp =          new     PostLibPHP();

 $oMerchant    =          new     Merchant();

 $oBTA                       =          new     BillToAddress();

 $oSTA                        =          new     ShipToAddress();

 $oPGResp      =          new     PGResponse();

 $oPGReserveData = new PGReserveData();




 $oMerchant->setMerchantDetails("00000001","00001203","00001203","193.545.34.33",rand()."","Ord123","http://10.10.10.167/SFAResponse.php","POST","INR","INV123","req.Sale","100","","Ext1","true","Ext3","Ext4","Ext5");
?>
Put marchant id.


  • e.g. if Merchant is Moto Merchant then change the TestMoto.php



Set the key directory path


·         'Key.Directory' should contain the name of the folder, which contains the merchant key. A trailing slash has to be included at the end of this value. The name of the file (.key file) need not be set. Save the file after making other relevant changes.
§  Key.Directory=D://WAMP//WWW//key//
Note: Don’t include key in key directory path.
·         Enable the verbose parameter to “true” only when required to generate logs. These logs are to be used for debugging (while integration) and should not be set to “true” in production as it might lead to considerable amount of logs depending on the number of transactions.
·         To verify the success of the above operations open the jar file again and check if the properties file has the values set.

 

 

Enabling Curl extensions

 


The curl extension files are

  • libeay32.dll
  • ssleay32.dll

These files should be present in to C:\WINDOWS\system32 and Php installation directory.

Open the php.ini file from PHP installation directory remove the semicolon of extension=php_curl.dll.

 


Disabling mcrypt extensions (for PHP version <= 4.4.4)

 


  • Open the php.ini file from PHP installation directory add the semicolon on start of line  ;extension=php_mcrypt.dll (if semicolon not present).

 Checklist

 

·           Merchant should have access to ePG over https
·           Check connectivity between php
1.     Restart the IIS Server
2.     Browse the testjava.php page either from browser of from IIS as shown below
                                       i.    Url : http://localhost/Merchant_Site_Name/test.php



Transaction Testing

 

·         Restart the Apache
·         Open the PHP page either from browser or from Apache
·         If Merchant is SSL then open TestSsl.php else if Merchant is Moto then TestMoto.php
1.         From IIS

               2.  From Browser
·         Type the URL : http://localhost/Merchant_Site_name/TestSsl.php


Troubleshooting

 


Problem : In log file if you got SSL certificate problem….



Solution : Add the certificate CSR in \Sfa\cacerts.pem file. (Refer Adding Certificates in  Cacerts section).

Tuesday, 7 August 2012

Basic Linux Commands

mkdir - make directories
Usage
mkdir [OPTION] DIRECTORY
Options
Create the DIRECTORY(ies), if they do not already exist.
 Mandatory arguments to long options are mandatory for short options too.
 -m, mode=MODE  set permission mode (as in chmod), not rwxrwxrwx - umask
 -p, parents  no error if existing, make parent directories as needed
 -v, verbose  print a message for each created directory
 -help display this help and exit
 -version output version information and exit
cd - change directories
Use cd to change directories. Type cd followed by the name of a directory to access that directory.Keep in mind that you are always in a directory and can navigate to directories hierarchically above or below.
mv- change the name of a directory
Type mv followed by the current name of a directory and the new name of the directory.
 Ex: mv testdir newnamedir
pwd - print working directory
will show you the full path to the directory you are currently in. This is very handy to use, especially when performing some of the other commands on this page
 rmdir - Remove an existing directory
 rm -r
Removes directories and files within the directories recursively.
chown - change file owner and group
Usage
chown [OPTION] OWNER[:[GROUP]] FILE
chown [OPTION] :GROUP FILE
chown [OPTION] --reference=RFILE FILE
Options
Change the owner and/or group of each FILE to OWNER and/or GROUP. With --reference, change the owner and group of each FILE to those of RFILE.
 -c, changes like verbose but report only when a change is made
 -dereference affect the referent of each symbolic link, rather than the symbolic link itself
 -h, no-dereference affect each symbolic link instead of any referenced file (useful only on systems that can         change the ownership of a symlink)
 -from=CURRENT_OWNER:CURRENT_GROUP
  change the owner and/or group of each file only if its current owner and/or group match those specified here.  Either  may  be  omitted,  in which case a match is not required for the omitted attribute.
-no-preserve-root do not treat `/' specially (the default)
-preserve-root fail to operate recursively on `/'
-f, -silent, -quiet  suppress most error messages
-reference=RFILE use RFILE's owner and group rather than the specifying OWNER:GROUP values
-R, -recursive operate on files and directories recursively
-v, -verbose output a diagnostic for every file processed
The  following options modify how a hierarchy is traversed when the -R option is also specified. If more than one is specified, only the final one  takes effect.
-H     if a command line argument is a symbolic link to a directory, traverse it
-L     traverse every symbolic link to a directory encountered
-P     do not traverse any symbolic links (default)
chmod - change file access permissions
Usage
chmod [-r] permissions filenames
 r  Change the permission on files that are in the subdirectories of the directory that you are currently in.        permission  Specifies the rights that are being granted. Below is the different rights that you can grant in an alpha  numeric format.filenames  File or directory that you are associating the rights with Permissions
u - User who owns the file.
g - Group that owns the file.
o - Other.
a - All.
r - Read the file.
w - Write or edit the file.
x - Execute or run the file as a program.
Numeric Permissions:
CHMOD can also to attributed by using Numeric Permissions:
400 read by owner
040 read by group
004 read by anybody (other)
200 write by owner
020 write by group
002 write by anybody
100 execute by owner
010 execute by group
001 execute by anybody
ls - Short listing of directory contents
-a        list hidden files
-d        list the name of the current directory
-F        show directories with a trailing '/'
            executable files with a trailing '*'
-g        show group ownership of file in long listing
-i        print the inode number of each file
-l        long listing giving details about files  and directories
-R        list all subdirectories encountered
-t        sort by time modified instead of name
cp - Copy files
cp  myfile yourfile
Copy the files "myfile" to the file "yourfile" in the current working directory. This command will create the file "yourfile" if it doesn't exist. It will normally overwrite it without warning if it exists.
cp -i myfile yourfile
With the "-i" option, if the file "yourfile" exists, you will be prompted before it is overwritten.
cp -i /data/myfile
Copy the file "/data/myfile" to the current working directory and name it "myfile". Prompt before overwriting the  file.
cp -dpr srcdir destdir
Copy all files from the directory "srcdir" to the directory "destdir" preserving links (-poption), file attributes (-p option), and copy recursively (-r option). With these options, a directory and all it contents can be copied to another dir
ln - Creates a symbolic link to a file.
ln -s test symlink
Creates a symbolic link named symlink that points to the file test Typing "ls -i test symlink" will show the two files are different with different inodes. Typing "ls -l test symlink" will show that symlink points to the file test.
locate - A fast database driven file locator.
slocate -u
This command builds the slocate database. It will take several minutes to complete this command.This command must be used before searching for files, however cron runs this command periodically  on most systems.locate whereis Lists all files whose names contain the string "whereis". directory.
more - Allows file contents or piped output to be sent to the screen one page at a time
less - Opposite of the more command
cat - Sends file contents to standard output. This is a way to list the contents of short files to the screen. It works well with piping.
whereis - Report all known instances of a command
wc - Print byte, word, and line counts
bg
bg jobs Places the current job (or, by using the alternative form, the specified jobs) in the background, suspending its execution so that a new user prompt appears immediately. Use the jobs command to discover the identities of background jobs.
cal month year - Prints a calendar for the specified month of the specified year.
cat files - Prints the contents of the specified files.
clear - Clears the terminal screen.
cmp file1 file2 - Compares two files, reporting all discrepancies. Similar to the diff command, though the output format differs.
diff file1 file2 - Compares two files, reporting all discrepancies. Similar to the cmp command, though the output format differs.
dmesg - Prints the messages resulting from the most recent system boot.
fg
fg jobs - Brings the current job (or the specified jobs) to the foreground.
file files - Determines and prints a description of the type of each specified file.
find path -name pattern -print
Searches the specified path for files with names matching the specified pattern (usually enclosed in single quotes) and prints their names. The find command has many other arguments and functions; see the online documentation.
finger users - Prints descriptions of the specified users.
free  - Displays the amount of used and free system memory.
ftp hostname
Opens an FTP connection to the specified host, allowing files to be transferred. The FTP program provides subcommands for accomplishing file transfers; see the online documentation.
head files - Prints the first several lines of each specified file.
ispell files - Checks the spelling of the contents of the specified files.
kill process_ids
kill - signal process_ids
kill -l
Kills the specified processes, sends the specified processes the specified signal (given as a number or name), or prints a list of available signals.
killall program
killall - signal program
Kills all processes that are instances of the specified program or sends the specified signal to all processes that are instances of the specified program.
mail - Launches a simple mail client that permits sending and receiving email messages.
man title
man section title - Prints the specified man page.
ping host - Sends an echo request via TCP/IP to the specified host. A response confirms that the host is operational.
reboot - Reboots the system (requires root privileges).
shutdown minutes
shutdown -r minutes
Shuts down the system after the specified number of minutes elapses (requires root privileges). The -r option causes the system to be rebooted once it has shut down.
sleep time - Causes the command interpreter to pause for the specified number of seconds.
sort files - Sorts the specified files. The command has many useful arguments; see the online documentation.
split file - Splits a file into several smaller files. The command has many arguments; see the online documentation
sync - Completes all pending input/output operations (requires root privileges).
telnet host - Opens a login session on the specified host.
top - Prints a display of system processes that's continually updated until the user presses the q key.
traceroute host - Uses echo requests to determine and print a network path to the host.
uptime - Prints the system uptime.
w - Prints the current system users.
wall - Prints a message to each user except those who've disabled message reception. Type Ctrl-D to end the message.


Saturday, 4 August 2012

Demo/About/Documentation geolocation API , IP address based Geolocation


Demo/About/Documentation geolocation API

The geolocation-feature implements the navigator.geolocation API. The following methods are available:

    navigator.getCurrentPosition: successCallback, errorCallback and options ({timeout: number}) are supported
    navigator.watchPosition: in shim identical to getCurrentPosition, except it returns an useless ID
    navigator.clearWatch: is noop in shim

The shim uses the geolocation information provided by http://freegeoip.net and/or googles API-Loader
Options for geolocation

    confirmText (string): confirm text for requesting access to geo data.

$.webshims.setOptions('geolocation', { confirmText: '{location} wants to know your position. It is Ok to press Ok.' }); navigator.geolocation.getCurrentPosition(function(pos){ alert("Thx, you are @ latitude: "+ pos.coords.latitude +"/longitude: " + pos.coords.longitude); });

The following code extracts illustrate how to obtain basic location information:

Example of a "one-shot" position request.

    function showMap(position) {
      // Show a map centered at (position.coords.latitude, position.coords.longitude).
    }

    // One-shot position request.
    navigator.geolocation.getCurrentPosition(showMap);
   

Example of requesting repeated position updates.

    function scrollMap(position) {
      // Scrolls the map so that it is centered at (position.coords.latitude, position.coords.longitude).
    }

    // Request repeated updates.
    var watchId = navigator.geolocation.watchPosition(scrollMap);

    function buttonClickHandler() {
      // Cancel the updates when the user clicks a button.
      navigator.geolocation.clearWatch(watchId);
    }
   

Example of requesting repeated position updates and handling errors.

    function scrollMap(position) {
      // Scrolls the map so that it is centered at (position.coords.latitude, position.coords.longitude).
    }

    function handleError(error) {
      // Update a div element with error.message.
    }

    // Request repeated updates.
    var watchId = navigator.geolocation.watchPosition(scrollMap, handleError);

    function buttonClickHandler() {
      // Cancel the updates when the user clicks a button.
      navigator.geolocation.clearWatch(watchId);
    }
   

Example of requesting a potentially cached position.

    // Request a position. We accept positions whose age is not
    // greater than 10 minutes. If the user agent does not have a
    // fresh enough cached position object, it will automatically
    // acquire a new one.
    navigator.geolocation.getCurrentPosition(successCallback,
                                             errorCallback,
                                             {maximumAge:600000});

    function successCallback(position) {
      // By using the 'maximumAge' option above, the position
      // object is guaranteed to be at most 10 minutes old.
    }

    function errorCallback(error) {
      // Update a div element with error.message.
    }

   

Forcing the user agent to return a fresh cached position.

    // Request a position. We only accept cached positions whose age is not
    // greater than 10 minutes. If the user agent does not have a fresh
    // enough cached position object, it will immediately invoke the error
    // callback.
    navigator.geolocation.getCurrentPosition(successCallback,
                                             errorCallback,
                                             {maximumAge:600000, timeout:0});

    function successCallback(position) {
      // By using the 'maximumAge' option above, the position
      // object is guaranteed to be at most 10 minutes old.
      // By using a 'timeout' of 0 milliseconds, if there is
      // no suitable cached position available, the user agent
      // will asynchronously invoke the error callback with code
      // TIMEOUT and will not initiate a new position
      // acquisition process.
    }

    function errorCallback(error) {
      switch(error.code) {
        case error.TIMEOUT:
          // Quick fallback when no suitable cached position exists.
          doFallback();
          // Acquire a new position object.
          navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
          break;
        case ... // treat the other error cases.
      };
    }

    function doFallback() {
      // No fresh enough cached position available.
      // Fallback to a default position.
    }
   

Forcing the user agent to return any available cached position.

    // Request a position. We only accept cached positions, no matter what
    // their age is. If the user agent does not have a cached position at
    // all, it will immediately invoke the error callback.
    navigator.geolocation.getCurrentPosition(successCallback,
                                             errorCallback,
                                             {maximumAge:Infinity, timeout:0});

    function successCallback(position) {
      // By setting the 'maximumAge' to Infinity, the position
      // object is guaranteed to be a cached one.
      // By using a 'timeout' of 0 milliseconds, if there is
      // no cached position available at all, the user agent
      // will immediately invoke the error callback with code
      // TIMEOUT and will not initiate a new position
      // acquisition process.
      if (position.timestamp < freshness_threshold &&
          position.coords.accuracy < accuracy_threshold) {
        // The position is relatively fresh and accurate.
      } else {
        // The position is quite old and/or inaccurate.
      }
    }

    function errorCallback(error) {
      switch(error.code) {
        case error.TIMEOUT:
          // Quick fallback when no cached position exists at all.
          doFallback();
          // Acquire a new position object.
          navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
          break;
        case ... // treat the other error cases.
      };
    }

    function doFallback() {
      // No cached position available at all.
      // Fallback to a default position.
    }
   
IP address based Geolocation

So now the obvious question is what about those browsers that don’t support geolocation at all? The answer is that we must use an external geolocation service. These services do their best to map the IP address of a device to geographic locations using large geolocation databases. Usually they do a good job, but at times they may suffer from the following issues:

    IP addresses may be associated with the wrong location (e.g., the wrong postal code, city or suburb within a metropolitan area).
    Addresses may be associated only with a very broad geographic area (e.g., a large city, or a state). Many addresses are associated only with a city, not with a street address or latitude/longitude location.
    Some addresses will not appear in the database and therefore cannot be mapped (often true for IP numbers not commonly used on the Internet).

The important thing to remember is that when an external geolocation service is used, the accuracy is not as good as geolocation native to the device, and in some scenarios it may be completely off. Additionally, such services do not provide any information regarding the altitude, speed or heading of the device. Regardless, when GPS or triangulation are not available, they are a good fallback.

YQL Geo Library is a dedicated and lightweight library that lets you perform geolocation using good old Yahoo services. This library can do other things which I’ll leave to you to discover, but for now let’s look at how we should modify our code to successfully detect the location on both supporting and non-supporting browsers:
view plaincopy to clipboardprint?

    <!DOCTYPE html>
    <html>
     
      <head>
      <script src="js/jquery-1.4.2.min.js"></script>
      <script src="js/yqlgeo.js"></script>
      <script>
        jQuery(window).ready(function(){
            jQuery("#btnInit").click(initiate_geolocation);
        })
     
        function initiate_geolocation() {
            if (navigator.geolocation)
            {
                navigator.geolocation.getCurrentPosition(handle_geolocation_query, handle_errors);
            }
            else
            {
                yqlgeo.get('visitor', normalize_yql_response);
            }
        }
     
        function handle_errors(error)
        {
            switch(error.code)
            {
                case error.PERMISSION_DENIED: alert("user did not share geolocation data");
                break;
     
                case error.POSITION_UNAVAILABLE: alert("could not detect current position");
                break;
     
                case error.TIMEOUT: alert("retrieving position timedout");
                break;
     
                default: alert("unknown error");
                break;
            }
        }
     
        function normalize_yql_response(response)
        {
            if (response.error)
            {
                var error = { code : 0 };
                handle_error(error);
                return;
            }
     
            var position = {
                coords :
                {
                    latitude: response.place.centroid.latitude,
                    longitude: response.place.centroid.longitude
                },
                address :
                {
                    city: response.place.locality2.content,
                    region: response.place.admin1.content,
                    country: response.place.country.content
                }
            };
     
            handle_geolocation_query(position);
        }
     
        function handle_geolocation_query(position){
            alert('Lat: ' + position.coords.latitude + ' ' +
                  'Lon: ' + position.coords.longitude);
            }
        </script>
     
      </head>
      <body>
        <div>
          <button id="btnInit" >Find my location</button>
        </div>
     
      </body>
    </html>