Saturday, February 11, 2012

Shell Script for auto-start and shutdown for a service in linux

Some services are having different starting points in linux. for example webmin: To start webmin we need to execute the command /etc/webmin/start where as all service can be started as /etc/init.d/service-name start. this is comman practice now. so we will write a shell script which will allow us to make it auto-start and shutdown for a service with comman practice & will start when we boot up the computer. lets take an example of webmin.


To make webmin automatically start when we boot up the computer,Create a file in "/etc/init.d/" directory as



sudo vi /etc/init.d/webmin

And put the following code in that file:
# Webmin auto-start
#
# description: Auto-starts webmin
# processname: webmin
# pidfile: /var/run/webmin.pid
case $1 in
start)
sh /etc/webmin start
;;
stop)
sh /etc/webmin stop
;;
restart)
sh /etc/webmin start
sh /etc/webmin stop
;;
esac
exit 0

now we need to change the file permission of this file so that it become executable.



sudo chmod 755 /etc/init.d/webmin

The now the final step is to linking this script to the startup folders with a symbolic link as.



sudo ln -s /etc/init.d/webmin /etc/rc1.d/K99webmin
sudo ln -s /etc/init.d/webmin /etc/rc2.d/S99webmin

Now we are ready with our new set of commands to start, stop & restart the service as



sudo /etc/init.d/webmin start
sudo /etc/init.d/webmin stop
sudo /etc/init.d/webmin restart

How to Authenticate Users With Facebook Connect

How to Authenticate Users With Facebook ConnectTutorial Details


  • Topic: Facebook Connect, PHP

  • Difficulty: Moderate

  • Estimated Completion Time: 45 Minutes


 

 

 

Lately, there’s been quite a fuzz about lazy registration. It turns out that the less the user has to think, the higher the conversion rates are! What a thought! If everybody seems to have a Facebook profile, why not add a one-click user registration? I’ll show you how to do that today.

 




Step 1. The Setup


MySQL Table


Let’s begin by creating a database table.



  1. CREATE TABLE `users` (

  2.     `id` int(10) unsigned NOT NULL AUTO_INCREMENT,

  3.     `oauth_provider` varchar(10),

  4.     `oauth_uid` text,

  5.     `username` text,

  6.     PRIMARY KEY (`id`)

  7. ) ENGINE=MyISAM  DEFAULT CHARSET=latin1;



Quite simple: we will be setting up a table for user information with id, username, first and last name, the URL to the user’s picture, and registered date. Also, we’re adding both an oauth_provider andoauth_uid fields, to distinguish between different third party open authentication protocols and their identifiers. For example, let’s say that, next week, you decide that it’s a good idea to also let Twitter users in. Easy; you just set another value to the oauthprovider, and avoid duplicating oauthuid values.

The Facebook App


Let’s begin by creating a new application. Give it a name and agree to the terms and conditions. Next, grab both the API Key and Secret in the basic tab as shown below.

On the canvas tab, set both the Canvas URL and Post-Authorize Redirect URL to your localhost and path that the script will process — something like http://localhost.com/login_facebook.php?. Note the question mark at the end and the domain; both are required by Facebook. Simply set your hosts file to a valid domain name.

On the connect tab, set the Connect URL to the same value and set localhost.com (or the one you are using) as the Base Domain.

Now save, download the client library, and unzip facebook.php in the srcdir to a new directory created in the root.




Step 2. The Callback


The authentication flow has three steps:

  1. The local script generates a URL asking the user for permission

  2. Facebook returns to the Canvas URL specified with a GET parameter

  3. The GET parameter authenticates the session


Let’s make a quick test before registering and login.



  1. # We require the library

  2. require("facebook.php");


  3. # Creating the facebook object

  4. $facebook = new Facebook(array(

  5.     'appId'  => 'YOUR_APP_ID',

  6.     'secret' => 'YOUR_APP_SECRET',

  7.     'cookie' => true

  8. ));


  9. # Let's see if we have an active session

  10. $session = $facebook->getSession();


  11. if(!empty($session)) {

  12.     # Active session, let's try getting the user id (getUser()) and user info (api->('/me'))

  13.     try{

  14.         $uid = $facebook->getUser();

  15.         $user = $facebook->api('/me');

  16.     } catch (Exception $e){}


  17.     if(!empty($user)){

  18.         # User info ok? Let's print it (Here we will be adding the login and registering routines)

  19.         print_r($user);

  20.     } else {

  21.         # For testing purposes, if there was an error, let's kill the script

  22.         die("There was an error.");

  23.     }

  24. } else {

  25.     # There's no active session, let's generate one

  26.     $login_url = $facebook->getLoginUrl();

  27.     header("Location: ".$login_url);

  28. }



Now, go to http://localhost.com/login_facebook.php, and let’s see what happens. If you are redirected to Facebook and requested for permission, we are on the right track.

However, there might be two issues. The first one: if you’re redirected to Facebook, but it shows an error, there might be a missing value in the configuration. Go back to your application settings and check both the Connect and Canvas tabs and make sure the fields are ok as described above.

There might be another issue, where you see an error, like “Uncaught CurlException: 60: SSL certificate problem, verify that the CA cert is OK.” This happens because of the CURL settings. You’ll have to openfacebook.php, find the makeRequest() method, and, inside the function, find this line:



  1. $opts = self::$CURL_OPTS;



Immediately following it, add:



  1. $opts[CURLOPT_SSL_VERIFYPEER] = false;



I hate hacking libraries, but I haven’t found another way. Well, let’s continue with user registration. I’ve also added a try/catch statement, because, if there’s an old session keys in the GET params in the URL, the script will die with a horrible error.




Step 3. Registration and Authentication


We’ll next be working with MySQL. Please note that I will not implement a data sanitizer, since I want to keep the code as short and on task as possible. Please keep this in mind: always sanitize your data.

First, let’s connect to the database.



  1. mysql_connect('localhost', 'YOUR_USERNAME', 'YOUR_PASSWORD');

  2. mysql_select_db('YOUR_DATABASE');



Now, let’s work on the $session conditional, in case we have a session.



  1. # We have an active session; let's check if we've already registered the user

  2. $query = mysql_query("SELECT * FROM users WHERE oauth_provider = 'facebook' AND oauth_uid = ". $user['id']);

  3. $result = mysql_fetch_array($query);


  4. # If not, let's add it to the database

  5. if(empty($result)){

  6.     $query = mysql_query("INSERT INTO users (oauth_provider, oauth_uid, username) VALUES ('facebook', {$user['id']}, '{$user['name']}')");

  7.     $query = msyql_query("SELECT * FROM users WHERE id = " . mysql_insert_id());

  8.     $result = mysql_fetch_array($query);

  9. }



Note that I’m querying the database, looking for facebook as a oauth_provider; it’s generally a good idea, if you want to accept other OAuth providers (as twitter, Google Accounts, Open ID, etc.) and aoauth_uid, since it’s the identifier the provider gives to its user accounts.

The oauth_provider field could potentially lead to bad performance if we leave it as a text field type. As such, the best option is setting it to an ENUM type.

We have now a $result var with the values queried from the database. Let’s next add some sessions. Add this line at the beginning of your script.


  1. session_start();



After the empty($result) conditional, append the following:



  1. if(!empty($user)){

  2.     # ...


  3.     if(empty($result)){

  4.         # ...

  5.     }


  6.     # let's set session values

  7.     $_SESSION['id'] = $result['id'];

  8.     $_SESSION['oauth_uid'] = $result['oauth_uid'];

  9.     $_SESSION['oauth_provider'] = $result['oauth_provider'];

  10.     $_SESSION['username'] = $result['username'];

  11. }



As it makes little sense to authenticate a user who is already logged in, just below the session_start()line, add:




  1. if(!empty($_SESSION)){

  2.     header("Location: home.php");

  3. }



And in the scripts which require authentication, just add:



  1. session_start();

  2. if(!empty($_SESSION)){

  3.     header("Location: login_facebook.php");

  4. }



And if you want to display the username, access it as an array.



  1. echo 'Welcome ' . $_SESSION['username'];

  2. # or..

  3. echo 'Welcome ' . !empty($_SESSION) ? $_SESSION['username'] : 'guest';







Step 4. Additional Methods


Facebook has a ton of connect features, but here are four that I’ve found to be the most useful.

Legacy Methods


I might be missing something, but the FQL seems more flexible and easy than the Graph API. Fortunately, Facebook still lets developers use it, altough with the new library, it has changed a bit.

If you want the user id, first name, last name, squared thumbnail for the user picture, the biggest user picture available, and his or her gender, you can use the users.getInfo method.



  1. $uid = $facebook->getUser();

  2. $api_call = array(

  3.     'method' => 'users.getinfo',

  4.     'uids' => $uid,

  5.     'fields' => 'uid, first_name, last_name, pic_square, pic_big, sex'

  6. );

  7. $users_getinfo = $facebook->api($api_call);



You can check the full list of fields available for Users.getInfo.


It is possible to achieve the same result, using FQL.



  1. $uid = $facebook->getUser();

  2. $fql_query  =   array(

  3.     'method' => 'fql.query',

  4.     'query' => 'SELECT uid, first_name, last_name, pic_square, pic_big, sex FROM user WHERE uid = ' . $uid

  5. );

  6. $fql_info = $facebook->api($fql_query);



Here’s the list of tables which can be accessed with FQL, as well as the fields available for the table users.

Extended Permissions


Facebook provides applications with some interaction with the user’s data – just as long as it’s authorized. With the old API, the authorization for additional permissions was exclusively available for the Javascript SDK (altough I’m not quite sure). With the new API, we can easily redirect the user to an authorization dialog in Facebook, and return to our site after the access is either granted or denied.

In the following example, we will be redirecting a user to authorize posts status updates, photos, videos and notes, the user’s real email address, birthday and access to photos and videos.


  1. $uid = $facebook->getUser();

  2. # req_perms is a comma separated list of the permissions needed

  3. $url = $facebook->getLoginUrl(array(

  4. 'req_perms' => 'email,user_birthday,status_update,publish_stream,user_photos,user_videos'

  5. ));

  6. header("Location: {$url} ");



Here’s a full list of permissions. Note that you can specify both the url to direct to if the user accepts and the url to be redirected to if the user denies. The key for these array elements are next and cancel_url, respectively. Here’s a quick example:



  1. $url = $facebook->getLoginUrl(array(

  2.     'req_perms' => 'email',

  3.     'next' => 'http://localhost.com/thanks.php',

  4.     'cancel_url' => 'http://localhost.com/sorry.php'

  5. ));



If not specified, the default is the requesting script’s location.

Checking for Extended Permissions


Since the user can easily revoke permissions, the application should always check if a given permission is granted before using it, specially if it’s about publishing something. We will have to use the legacy API, as it seems it’s not fully implemented with the new one yet.



  1. $uid = $facebook->getUser();


  2. # users.hasAppPermission

  3. $api_call = array(

  4.     'method' => 'users.hasAppPermission',

  5.     'uid' => $uid,

  6.     'ext_perm' => 'publish_stream'

  7. );

  8. $users_hasapppermission = $facebook->api($api_call);

  9. print_r($users_hasapppermission);



The ext_perm will only support the old list of available permissions.

Publishing to the Wall


Let’s post something to the wall after verifying the user has the publish_stream permission.



  1. # let's check if the user has granted access to posting in the wall

  2. $api_call = array(

  3.     'method' => 'users.hasAppPermission',

  4.     'uid' => $uid,

  5.     'ext_perm' => 'publish_stream'

  6. );

  7. $can_post = $facebook->api($api_call);

  8. if($can_post){

  9.     # post it!

  10.     $facebook->api('/'.$uid.'/feed', 'post', array('message' => 'Saying hello from my Facebook app!'));

  11.     echo 'Posted!';

  12. } else {

  13.     die('Permissions required!');

  14. }



Essentially, we are making an API call to /<user_id>/feed, using the POST method (second argument) and an array as a third argument for the data to be sent. In this case, this third argument supports message,linkpicturecaptionname and description. Here’s the code:



  1. $facebook->api('/'.$uid.'/feed', 'post', array(

  2.     'message' => 'The message',

  3.     'name' => 'The name',

  4.     'description' => 'The description',

  5.     'caption' => 'The caption',

  6.     'picture' => 'http://i.imgur.com/yx3q2.png',

  7.     'link' => 'http://net.tutsplus.com/'

  8. ));



Here’s how it is posted.

 

Some Additional Information you Should Know:


The user can easily revoke permissions with two clicks in his or her wall. You should heavily test what might happen if a user revoked one or more permissions that are vital for the proper functioning of your website, or even if the application is fully removed. This is important.





5. Conclusion


While Facebook’s authentication capabilities are indeed useful, since so many people are on Facebook these days, using it as the only method of authentication in a site is not recommended. What about those who don’t have Facebook accounts? Are they not allowed to access your application? Thanks for reading!

Saturday, January 28, 2012

Evolution of MS-DOS "Deal of the Century"

IBM & Microsoft History


In 1980, IBM first approached Bill Gates of Microsoft, to discuss the state of home computers and what Microsoft products could do for IBM. Gates gave IBM a few ideas on what would make a great home computer, among them to have Basic written into the ROM chip. Microsoft had already produced several versions of Basic for different computer system beginning with the Altair, so Gates was more than happy to write a version for IBM.

Gary Kildall


As for an operating system (OS) for an IBM computer, since Microsoft had never written an operating system before, Gates had suggested that IBM investigate an OS called CP/M (Control Program for Microcomputers), written by Gary Kildall of Digital Research. Kindall had his Ph.D. in computers and had written the most successful operating system of the time, selling over 600,000 copies of CP/M, his operating system set the standard at that time.

The Secret Birth of MS-DOS


IBM tried to contact Gary Kildall for a meeting, executives met with Mrs Kildall who refused to sign a non-disclosure agreement. IBM soon returned to Bill Gates and gave Microsoft the contract to write a new operating system, one that would eventually wipe Gary Kildall's CP/M out of common use.

The "Microsoft Disk Operating System" or MS-DOS was based on Microsoft's purchase of QDOS, the "Quick and Dirty Operating System" written by Tim Paterson of Seattle Computer Products, for their prototype Intel 8086 based computer.

However, ironically QDOS was based (or copied from as some historians feel) on Gary Kildall's CP/M. Tim Paterson had bought a CP/M manual and used it as the basis to write his operating system in six weeks. QDOS was different enough from CP/M to be considered legally a different product. IBM had deep enough pockets in any case to probably have won an infringement case, if they had needed to protect their product. Microsoft bought the rights to QDOS for $50,000, keeping the IBM & Microsoft deal a secret from Tim Paterson and his company, Seattle Computer Products.

Deal of the Century


Bill Gates then talked IBM into letting Microsoft retain the rights, to market MS-DOS separate from the IBM PC project, Gates and Microsoft proceeded to make a fortune from the licensing of MS-DOS. In 1981, Tim Paterson quit Seattle Computer Products and found employment at Microsoft.

Sources:www.about.com

Saturday, January 7, 2012

How to Set Up an Amazon EC2 Instance

To start with Amazon Cloud we are going use the AWS Management Console. Login to the Management Console (If registered Else create an account with your credit card details and then login). On the home screen, make sure the tab EC2 is selected. then follow these steps as in images...


Now We need to select an ami so here i am going with ubuntu AMI. Here we can choose ami from amazon also in Quick start tab. But we are going with ubuntu so we will get it in community AMIs and search for your Amazon ami using AMI-ID. we can choose with or without EBS.



 Now select Instance Type, here i am going with micro instance


Now if we need to go for specific settings then we can customize but here we are going with default settings as first time.


Now Keep a name for your server as


Now We need to create a key pair & download .pem file which can be use to connect to server usingh ssh.


Now select security group which will allow us to connect/Access cloud AMI based on rules.


Now the summary of instance we have configure & chosen for Click launch to start the AMI.


Now After this step in few minute our AMI will start. Now we need to enable SSH in security group. then only we can connect to our AWS AMI as


ssh -i keypairfilename.pem ubuntu@public_address of AMI

if it ask for password provide as ubuntu further we can change it.