Index: drupalgapps.admin.inc
===================================================================
--- drupalgapps.admin.inc	(revision 0)
+++ drupalgapps.admin.inc	(revision 0)
@@ -0,0 +1,181 @@
+<?php
+// $Id$
+
+/**
+ * @file
+ * Admin UI functions.
+ */
+
+/*
+ * Admin page setting  Form has following fields
+ *
+ *  1. Domain information
+ *      a. Domain name (validate for domain name type) (required)
+ *      b. Domain name owner / Organisation using it (optional)
+ *  2. Admin credentils
+ *      a. Administrator email (validate for email type) (required)
+ *      b. Admin password (required)
+ *  3.Token renewal policy
+ *      a. Renewal rate of token (default = 23)
+ *      b. on event of failure
+ *          i. Email (default =checked )
+ *          ii. Enter the Email id (validate for email type) (optional)
+ */
+
+
+/**
+ * Main settings form for drupalgapps.
+ */
+function drupalgapps_settings_form() {
+  $form = array();
+
+  $form['domain_info'] = array(
+    '#type' =>'fieldset',
+    '#title'=> t('Domain information'),
+    '#collapsible'=> TRUE,
+    '#collapsed' => FALSE,
+  );
+
+  $form['domain_info']['domain_name'] = array(
+    '#type' => t('textfield'),
+    '#title'=> t('Domain name'),
+    '#description' => t('Your Google Apps domain name, e.g. www.example.com'),
+    '#size' => 30,
+    '#required' => TRUE,
+    '#default_value' => variable_get('drupalgapps_domain_name', ''),
+  );
+
+  $form['domain_info']['organisation'] = array(
+    '#type' => t('textfield'),
+    '#title'=> t('Organisation Name'),
+    '#description' => t('Used for display purposes only.'),
+    '#size' => 30,
+    '#default_value' => variable_get('drupalgapps_organisation_name', ''),
+  );
+
+  $form['admin_credentials'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Administrator credentials'),
+    '#description' => t('Administrator account details to use for fetching Authentication token.'),
+    '#collapsible' => TRUE,
+    '#collapsed' => FALSE,
+  );
+
+  $form['admin_credentials']['admin_email'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Email'),
+    '#description' => t('Preferably you should create a seperate email id with admin privileges which is not in use elsewhere. To prevent problems, the password for this administration account should not be changed without updating here too.'),
+    '#size' => 30,
+    '#required' => TRUE,
+    '#default_value' => trim(aes_decrypt(variable_get('drupalgapps_admin_email', ''))),
+  );
+
+  $form['admin_credentials']['admin_password'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Password for the admin email'),
+    '#required' => TRUE,
+    '#size' => 30,
+    '#default_value' => trim(aes_decrypt(variable_get('drupalgapps_admin_password', ''))),
+  );
+
+
+  $form['token_policy'] = array(
+    '#type' => 'fieldset' ,
+    '#title' => t('Token Renewal Policy'),
+    '#collapsible'=>TRUE,
+    '#collapsed' => FALSE,
+  );
+
+  $form['token_policy']['renewal_rate'] = array(
+    '#type' => 'select',
+    '#title' => t('Renewal rate of authentication token (in hours)'),
+    '#options' => drupal_map_assoc(range(1, 23)),
+    '#default_value' => variable_get('drupalgapps_token_renewal_rate', 23),
+    '#description' => t("ONLY FOR ADVANCED USERS.<br/>Do not change without knowledge about provisioning API authentication.<br/><br/> The authenication token used for Google's Provisioning API expires every 24 hours, but to prevent problems, the module renews the token in every 23 hrs by default."),
+  );
+
+  $form['token_policy']['on_failure'] = array(
+    '#type' => 'fieldset' ,
+    '#title'=> t('Error handling'),
+    '#description' => t('Action to be taken when the module is unable to fetch the Authentication token for Google Apps'),
+    '#collapsible' => TRUE,
+    '#collapsed' => FALSE,
+  );
+
+  $form['token_policy']['on_failure']['send_email'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Send Email to Administrator'),
+    '#default_value' => variable_get('drupalgapps_email_send_option', 1),
+    '#description' => t('Drupal will email administrator if token expires, gets revoked or for any other problems which prevents use of the provisioning API.'),
+  );
+
+  $form['token_policy']['on_failure']['failure_email'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Warning email address'),
+    '#description' => t('If blank, the email will be sent to the administrator account used to fetch the authentication token.'),
+    '#size' => 30,
+    '#required' => FALSE,
+    '#default_value' => variable_get('drupalgapps_failure_email', ''),
+  );
+
+  $form['proxy_config'] = array(
+    '#type' => 'fieldset',
+    '#title'=> t('Proxy configuration'),
+    '#collapsible' => TRUE,
+    '#collapsed' => FALSE,
+  );
+
+  $form['proxy_config']['proxy'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Proxy Server Details'),
+    '#description' => t('If your webserver is behind a proxy server, enter proxy details in the format <b>[ip address]:[port]</b> , eg : 172.16.68.6:3128'),
+    '#size' => 30,
+    '#required' => FALSE,
+    '#default_value' => variable_get('drupalgapps_proxy', ''),
+  );
+
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Save'),
+  );
+
+  return $form;
+}
+
+/**
+ * Validation function for drupalgapps_settings_form().
+ */
+function drupalgapps_settings_form_validate($form, &$form_state) {
+  $admin_email = valid_email_address($form_state['values']['admin_email']);
+  $failure_email = valid_email_address($form_state['values']['failure_email']);
+
+  if (!$admin_email) {
+    form_set_error('admin_email', 'Email address entered is invalid.');
+  }
+  elseif ($form_state['values']['failure_email'] && !$failure_email) {
+    form_set_error('failure_email', 'Email address entered is invalid.');
+  }
+}
+
+
+/**
+ * Submit handler for drupalgapps_settings_form().
+ */
+function drupalgapps_settings_form_submit($form, &$form_state) {
+  variable_set('drupalgapps_domain_name', trim($form_state['values']['domain_name']));
+  variable_set('drupalgapps_organisation_name', trim($form_state['values']['organisation']));
+  variable_set('drupalgapps_token_renewal_rate', $form_state['values']['renewal_rate']);
+  variable_set('drupalgapps_email_send_option', $form_state['values']['send_email']);
+  variable_set('drupalgapps_failure_email', trim($form_state['values']['failure_email']));
+  variable_set('drupalgapps_proxy', trim($form_state['values']['proxy']));
+
+  $encrypted_admin_email = aes_encrypt(trim($form_state['values']['admin_email']));
+  variable_set('drupalgapps_admin_email', $encrypted_admin_email);
+
+  $encrypted_admin_password = aes_encrypt(trim($form_state['values']['admin_password']));
+  variable_set('drupalgapps_admin_password', $encrypted_admin_password);
+
+  // Fetch the authentication token.
+  drupalgapps_get_authtoken();
+}
+
Index: drupalgapps.module
===================================================================
--- drupalgapps.module	(revision 524)
+++ drupalgapps.module	(working copy)
@@ -4,313 +4,22 @@
 
 /*
  * @file
+ * Implements Wrapper of Google provisoning API.
  *
- * Impliments Wrapper of Google provisoning API
  * Provide clientlogin authenentication for Provisoning api
- * Provides a Core  to assist developers  build wrapper/application of/using other Google Apps API
+ * Provides a Core to assist developers build wrapper/application of/using other Google Apps API
  */
 
-/*
- * Implimentation of Hook_help : Function to provide help text on setting page of module
+/**
+ * @ingroup core_hooks
+ * @{
  */
-function drupalgapps_help($path, $arg) {
 
-  $output = '';  //declare your output variable
-
-  switch ($path) {
-    case "admin/help#drupalgapps":
-      $output = '<p>'. t('Google Apps framework for Drupal') .'</p>';
-      $output .= '<p>'. t('This Module is the core of Google Apps framework. It has following tasks to handle : ') .'</p>';
-      $output .= '<ol><li>'. t('Impliment Wrapper of  <a href = "@provision">Google Apps provisioning api</a> ( CRUD and more of Google apps user account )', array('@provision' => 'http://code.google.com/apis/apps/gdata_provisioning_api_v2.0_reference.htm')) .'</li>';
-      $output .= '<li>'. t('<a href="@clientlogin">Client Login</a> Authentication for Provisioning API', array('@clientlogin' => 'http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html#ClientLogin')) .'</li>';
-      $output .= '<li>'. t('The Core : developed to assist develop wrapper/application of/using other Google Apps  APIs , which are not yet covered.') .'</li></ol>';
-      break;
-  }
-  return $output;
-
-
-}
-
-
-function drupalgapps_page() {
-  return drupal_get_form('drupalgapps_form');
-}
-
-/*
- * Admin page setting  Form has following fields
- *
- *
- *  1. Domain information
- *      a. Domain name ( validate for domain name type ) (required )
- *      b. Domain name owner / Organisation using it (optional )
- *  2. Admin credentils
- *      a. Administrator email (validate for email type ) (required )
- *      b. Admin password ( required )
- *  3.Token renewal policy
- *      a. Renewal rate of token (defaut = 23 )
- *      b. on event of failure
- *          i. Email (default =checked )
- *          ii. Enter the Email id ( validate for email type ) (optional)
- */
-
-
-/*
- * Implementation of hook_form().
- */
-function drupalgapps_form($formstate) {
-  $form = array();
-
-  $form['domain_info'] = array(
-    '#type' =>'fieldset',
-    '#title'=> t('Domain information'),
-    '#description' => t('Detail about the Domain , on which Google apps is impliemented which you intend use this module for.'),
-    '#collapsible'=> TRUE,
-    '#collapsed' => FALSE,
-  );
-
-  $form['domain_info']['domain_name'] = array(
-    '#type' => t('textfield'),
-    '#title'=> t('Enter the Domain name '),
-    '#description' => t('domain name for which you/your organisation has/have registered Google Apps. Example : www.example.com'),
-    '#size' => 30,
-    '#required' => TRUE,
-    '#default_value' => variable_get('drupalgapps_domain_name', ''),
-  );
-
-  $form['domain_info']['organisation'] = array(
-    '#type' => t('textfield'),
-    '#title'=> t('Organisation Name (Optional)'),
-    '#description' => t('Organisation to which this domain belong or The organisation which is going to use  Google apps on this Domain. Which ever more specific.'),
-    '#size' => 30,
-    '#default_value' => variable_get('drupalgapps_organisation_name', ''),
-  );
-
-  $form['admin_credentials'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Administrator credentials'),
-    '#description' => t('Administrator account details used for fetching Authentication token'),
-    '#collapsible' => TRUE,
-    '#collapsed' => FALSE,
-  );
-
-  $form['admin_credentials']['admin_email'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Email'),
-    '#required' => TRUE,
-    '#default_value' => 'admin@example.com',
-    '#description' => t('Enter the ADMIN EMAIL (ful ) . Preferably you should create a seperate email id with admin rights (privilages), and donot use anywhere esle, i.e Specially/only used by this module. The reason being, the password for that email/account should not be changed, else you will also have to update in this modules setting immediately, else this module and all the modules using this module will be disabled'),
-    '#size' => 30,
-    '#default_value' => trim(aes_decrypt(variable_get('drupalgapps_admin_email', ''))),
-  );
-
-  $form['admin_credentials']['admin_password'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Password for the admin email'),
-    '#required' => TRUE,
-    '#size' => 30,
-    '#default_value' => trim(aes_decrypt(variable_get('drupalgapps_admin_password', ''))),
-  );
-
-
-  $form['token_policy'] = array(
-    '#type' => 'fieldset' ,
-    '#title' => t('Token Renewal Policy'),
-    '#collapsible'=>TRUE,
-    '#collapsed' => FALSE,
-    '#description' => t('This section deals with all the setting related to token storage, renewal and logging'),
-  );
-
-  $form['token_policy']['renewal_rate'] = array(
-    '#type' => 'select',
-    '#title' => t('Revewal rate of auth. token (in Hours)'),
-    '#options' => drupal_map_assoc(range(1, 23)),
-    '#default_value' => variable_get('drupalgapps_token_renewal_rate', 23),
-    '#description' => t('ONLY FOR ADVANCED USERS.<br/> DO NOT change it untill you have knowledge about the Authentication token involved in provisioning API authentication.<br/><br/> Though, the authenication token used for provisioning API expires every 24 hours, but to eliminate any last minute glichtes, by DEFAULT the module runs the cron job and renew the token in every 23 hrs.  '),
-  );
-
-  $form['token_policy']['on_failure'] = array(
-    '#type' => 'fieldset' ,
-    '#title'=> t('On Event when failure occurs while fetching Token'),
-    '#description' => t('Action to be taken when the module is unable to fetch the Authentication token for Google Apps'),
-    '#collapsible' => TRUE,
-    '#collapsed' => FALSE,
-  );
-
-  $form['token_policy']['on_failure']['send_email'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Send Email to Administrator'),
-    '#default_value' => variable_get('drupalgapps_email_send_option', 1),
-    '#description' => t('Enabled by default. On enabling this , Drupal will mail admin if token expires or get revoked or anyother reason due to which Provisioning API doesnot function.'),
-  );
-
-  $form['token_policy']['on_failure']['failure_email'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Email address to send the warning email (optional )'),
-    '#description' => t('If left Empty, the email will be sent to the administrator account used to fetch the authentication token, i.e. Enter above.'),
-    '#size' => 30,
-    '#required' => FALSE,
-    '#default_value' => variable_get('drupalgapps_failure_email', ''),
-  );
-
-  $form['proxy_config'] = array(
-    '#type' => 'fieldset',
-    '#title'=> t('Proxy configuration of the Web-Server'),
-    '#collapsible' => TRUE,
-    '#collapsed' => FALSE,
-  );
-
-  $form['proxy_config']['proxy'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Proxy Server Details'),
-    '#description' => t('If your webserver is under any procy server, through which it is accessing Internet, Please enter Proxy server IP address and port Details in form <b>[ip address]:[port]</b> , eg : 172.16.68.6:3128'),
-    '#size' => 30,
-    '#required' => FALSE,
-    '#default_value' => variable_get('drupalgapps_proxy', ''),
-  );
-
-  $form['submit'] = array(
-    '#type' => 'submit',
-    '#value' => t('Save'),
-  );
-
-  return $form;
- //  return system_settings_form($form);
-}
-
-
-function drupalgapps_form_submit($form_id, &$form_state) {
-  $admin_email = valid_email_address($form_state['values']['admin_email']);
-  $failure_email = valid_email_address($form_state['values']['failure_email']);
-
-  if (!$admin_email) {
-    form_set_error('admin_email', 'Email address entered is not Valid');
-  }
-  elseif ($form_state['values']['failure_email'] != NULL && !$failure_email) {
-    form_set_error('failure_email', 'Email address entered is not Valid');
-  }
-  else {
-    $domain_name = $form_state['values']['domain_name'];
-    variable_set('drupalgapps_domain_name', $domain_name);
-
-    $organisation_name = $form_state['values']['organisation'];
-    variable_set('drupalgapps_organisation_name', $organisation_name);
-
-    $admin_email_address = $form_state['values']['admin_email'];
-    $encrypted_admin_email = aes_encrypt($admin_email_address);
-    variable_set('drupalgapps_admin_email', $encrypted_admin_email);
-
-    $admin_email_password = $form_state['values']['admin_password'];
-    $encrypted_admin_password = aes_encrypt($admin_email_password);
-    variable_set('drupalgapps_admin_password', $encrypted_admin_password);
-
-    $renewal_rate = $form_state['values']['renewal_rate'];
-    variable_set('drupalgapps_token_renewal_rate', $renewal_rate);
-
-    $email_send_option = $form_state['values']['send_email'];
-    variable_set('drupalgapps_email_send_option', $email_send_option);
-
-    $failure_email_address = $form_state['values']['failure_email'];
-    variable_set('drupalgapps_failure_email', $failure_email_address);
-
-    $proxy_address = $form_state['values']['proxy'];
-    if ($proxy_address) {
-      variable_set('drupalgapps_proxy', $proxy_address);
-    }
-    else {
-      variable_set('drupalgapps_proxy', NULL);
-    }
-
-    drupalgapps_get_authtoken();
-  }
-}
-
 /**
- * The function to fetch the Authentication token
+ * Implementation of hook_perm().
  */
-function drupalgapps_get_authtoken() {
-
-  /*
-  $form['drupalgapps_settings'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Maximum number of links'),
-    '#default_value' => '2',
-    '#size' => 2,
-    '#maxlength' => 2,
-    '#description' => t("The maximum number of links to display in the block."),
-    '#required' => TRUE,
-  );
-  */
-
-
-  $admin_api_email = trim(aes_decrypt(variable_get('drupalgapps_admin_email', '')));
-  $admin_api_password = trim(aes_decrypt(variable_get('drupalgapps_admin_password', '')));
-  $proxy_add = variable_get('drupalgapps_proxy', NULL);
-  if ($proxy_add) {
-    $proxy_exist = 1;
-  }
-  else {
-    $proxy_exist = 0;
-  }
-
-
-  $http_proxy_status = '0';
-  $proxy_address = '';
-  $headerdata = "&Email=".urlencode($admin_api_email)."&Passwd=".$admin_api_password."&accountType=HOSTED&service=apps";
-
-  $headerfields = array(
-    'Content-type' => 'application/x-www-form-urlencoded',
-    'Content-Length' => strlen($headerdata)
-  );
-  //$headerfields = $headerfields."\nContent-Length :".strlen($headerdata);
-
-
-  $curl_post_request = curl_init();
-  curl_setopt($curl_post_request, CURLOPT_URL, 'https://www.google.com/accounts/ClientLogin');
-  curl_setopt($curl_post_request, CURLOPT_RETURNTRANSFER, 1);
-  curl_setopt($curl_post_request, CURLOPT_HTTPHEADER, array($headerfields));
-  curl_setopt($curl_post_request, CURLOPT_POSTFIELDS, $headerdata);
-  curl_setopt($curl_post_request, CURLOPT_HTTPPROXYTUNNEL, $proxy_exist);
-  curl_setopt($curl_post_request, CURLOPT_PROXY, $proxy_add );
-  curl_setopt($curl_post_request, CURLOPT_SSL_VERIFYPEER, FALSE);
-  curl_setopt($curl_post_request, CURLOPT_SSL_VERIFYHOST,  2);
-  $response = curl_exec($curl_post_request);
-
-
-  /*
-   * Get the respose code
-   *
-   * HTTP 200 : Success --> Token fetched
-   * HTTP 403 : Access forbidden --> Token not Fetched
-   */
-
-  $response_code = curl_getinfo($curl_post_request, CURLINFO_HTTP_CODE);
-  curl_close($curl_post_request);
-  $response = substr($response, strpos($response, "Auth") + 5, strlen($response));
-  drupal_set_message($response);
-  if ($response_code == '200') {
-    drupal_set_message(t('Authentication Token fetched'), 'status');
-    watchdog('Google Apps', 'Authentication token fetched properly.', array(), WATCHDOG_NOTICE);
-    variable_set ("gapps_prov_api_auth_token", $response);  //Store authentication token in drupal variable
-  }
-  elseif ($response_code == '403') {
-    drupal_set_message('Unable to fetch Token . Please Re-check the credentials', 'error');
-    drupalgapp_failure_warning($admin_api_email);
-  }
-
-  /*
-   * CURL options and thier purpose :
-   *
-   * CURLOPT_SSL_VERIFYPEER  : FALSE to stop cURL from verifying the peer's certificate.
-   * CURLOPT_SSL_VERIFYHOST  : 2 to check the existence of a common name and also verify that it matches the hostname provided. 1 to check the existence of a common name in the SSL peer certificate.
-   * CURLOPT_HTTPPROXYTUNNEL : TRUE to tunnel through a given HTTP proxy.
-   * CURLOPT_PROXY           : The HTTP proxy to tunnel requests through.
-   */
-
-  $gaccount = 'betatest';
-  $firstname = 'beta';
-  $lastname = 'test';
-  $password = 'moonshine';
-  $username = 'ankur.saxena';
+function drupalgapps_perm() {
+  return array('administer drupalgapps');
 }
 
 /**
@@ -320,29 +29,40 @@
   $items = array();
 
   $items['admin/settings/drupalgapps'] = array(
-    'title' => t('DrupalGapps module settings'),
+    'title' => t('DrupalGapps'),
     'description' => t('Description of your DrupalGapps settings page'),
-    'page callback' => 'drupalgapps_page',
-    //'page arguments' => array('drupalgapps_admin'),
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('drupalgapps_settings_form'),
     'access arguments' => array('administer drupalgapps'),
     'type' => MENU_NORMAL_ITEM,
+    'file' => 'drupalgapps.admin.inc',
   );
 
   return $items;
 }
 
 /**
- * Implementation of hook_perm().
+ * Implementation of hook_help()
  */
-function drupalgapps_perm() {
-  return array('administer drupalgapps');
+function drupalgapps_help($path, $arg) {
+  $output = '';
+
+  switch ($path) {
+    case 'admin/help#drupalgapps':
+      $output = '<p>'. t('Google Apps framework for Drupal') .'</p>';
+      $output .= '<p>'. t('This Module is the core of Google Apps framework. It has following tasks to handle :') .'</p>';
+      $output .= '<ol><li>'. t('Implement Wrapper of  <a href = "@provision">Google Apps provisioning api</a> (CRUD and more of Google apps user account)', array('@provision' => 'http://code.google.com/apis/apps/gdata_provisioning_api_v2.0_reference.htm')) .'</li>';
+      $output .= '<li>'. t('<a href="@clientlogin">Client Login</a> Authentication for Provisioning API', array('@clientlogin' => 'http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html#ClientLogin')) .'</li>';
+      $output .= '<li>'. t('The Core : developed to assist develop wrapper/application of/using other Google Apps  APIs , which are not yet covered.') .'</li></ol>';
+      break;
+  }
+  return $output;
 }
 
-
-/*
+/**
  * Implementation of hook_cron()
  *
- * After the time interval set by default ( 23 hrs) or administrator, it fetches
+ * After the time interval set by default (23 hrs) or administrator, it fetches
  * the authentication token for provisioning API
  */
 function drupalgapps_cron() {
@@ -366,67 +86,83 @@
   }
 }
 
+/**
+ * @} End of "ingroup core_hooks".
+ */
 
-function drupalgapp_failure_warning($admin_api_email) {
-  global $user;
+/**
+ * @ingroup client_login
+ * @{
+ */
 
-  if (!variable_get('clean_url', '0')) {
-    $gapps_admin_path = '/?q=admin/settings/drupalgapps';
-  }
-  else {
-    $gapps_admin_path = '/admin/settings/drupalgapps';
-  }
+/**
+ * The function to fetch the authentication token.
+ */
+function drupalgapps_get_authtoken() {
 
+  $admin_api_email = trim(aes_decrypt(variable_get('drupalgapps_admin_email', '')));
+  $admin_api_password = trim(aes_decrypt(variable_get('drupalgapps_admin_password', '')));
+  $proxy_add = variable_get('drupalgapps_proxy', NULL);
+  $proxy_exist = $proxy_add ? 1 : 0;
 
-  // Function to send results over email.
-  $params['subject'] = t('[@site_name] @severity_desc: Alert from your web site', array(
-    '@site_name' => variable_get('site_name', 'Drupal'),
-    '@severity_desc' => t('Critical'),
-  ));
+  $http_proxy_status = '0';
+  $proxy_address = '';
+  $headerdata = '&Email=' . urlencode($admin_api_email) . '&Passwd=' . urlencode($admin_api_password) . '&accountType=HOSTED&service=apps';
 
-  $params['message']  = "\nSite:         @base_url";
-  $params['message'] .= "\nSeverity:     @severity_desc";
-  $params['message'] .= "\nType:         @type";
-  $params['message'] .= "\nUser:         @name";
-  $params['message'] .= "\nLink:         @link";
-  $params['message'] .= "\nMessage:      \n\n@message\n@reason1\n@reason2";
+  $headerfields = array(
+    'Content-type' => 'application/x-www-form-urlencoded',
+    'Content-Length' => strlen($headerdata)
+  );
+  //$headerfields = $headerfields."\nContent-Length :".strlen($headerdata);
 
-  $params['message'] = t($params['message'], array(
-    '@base_url'      => $GLOBALS['base_url'],
-    '@severity_desc' => t('Critical'),
-    '@type'          => 'Google Apps',
-    '@name'          => 'Administrator',
-    '@link'          => $GLOBALS['base_url'].$gapps_admin_path,
-    '@message'       => 'DrupalGapps module is unable to fetch authentication token for provisioning API. Hence all CRUD action on Google apps user accounts ( Google apps user management) has been halted. Probable reason could be : ',
-    '@reason1'       => '1. The admin account credentials being used to fetch Auth. token havent changed .',
-    '@reason2'       => '2. There is a problem in Internet connection on your webserver.',
-  ));
 
+  $ch = curl_init();
+  curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/accounts/ClientLogin');
+  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+  curl_setopt($ch, CURLOPT_HTTPHEADER, array($headerfields));
+  curl_setopt($ch, CURLOPT_POSTFIELDS, $headerdata);
+  curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, $proxy_exist); // TRUE of tunnel through a given HTTP proxy
+  curl_setopt($ch, CURLOPT_PROXY, $proxy_add);
+  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // FALSE to stop cURL from verifying the peer's certificate.
+  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2); // 2 to check the existence of a common name and also verify that it matches the hostname provided.
+  // Could set CURLOPT_SSL_VERIFYHOST to 1 to check the existence of a common name in the SSL peer certificate.
+  $response = curl_exec($ch);
 
-  if (variable_get('drupalgapps_failure_email', NULL) != NULL) {
-    drupal_mail('drupalgapps', 'warning', variable_get('drupalgapps_failure_email', variable_get('site_mail', NULL)), user_preferred_language($account), $params, NULL, TRUE);
-  }
-  else {
-    drupal_mail('drupalgapps', 'warning', $admin_api_email, user_preferred_language($account), $params, NULL, TRUE);
-  }
 
-  watchdog('Google Apps', 'Critical : unable to fetch Authentication token from Google . Google Apps User account managament is halted . Most probably Problem arised because of the Admin creditential. Check them. ', array(), WATCHDOG_CRITICAL, l(t('DrupalGapps Settings'), 'admin/settings/drupalgapps'));
+  // Get the response code.
+  // HTTP 200 : Success --> Token fetched
+  // HTTP 403 : Access forbidden --> Token not Fetched
+  $response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+  curl_close($ch);
 
-}
+  // Parse out the authentication token.
+  $auth_token = NULL;
+  $response_lines = split("\n", $response);
+  foreach ($response_lines as $line) {
+    if (preg_match('/^Auth=(.+)$/', $line, $matches)) {
+      $auth_token = $matches[1];
+      break;
+    }
+  }
 
+  drupal_set_message($auth_token);
 
-/**
- * Implementation of hook_mail().
- */
-function drupalgapps_mail($key, &$message, $params) {
-  global $user;
-
-  switch ($key) {
-    case 'warning':
-      $message['subject'] = $params['subject'];
-      $message['body'] = $params['message'];
-      break;
+  if ($response_code == '200') {
+    drupal_set_message(t('Authentication Token fetched'), 'status');
+    watchdog('Google Apps', 'Authentication token fetched properly.', array(), WATCHDOG_NOTICE);
+    variable_set ('gapps_prov_api_auth_token', $auth_token);  //Store authentication token in drupal variable
   }
+  elseif ($response_code == '403') {
+    drupal_set_message('Unable to fetch authentication token . Please re-check your settings.', 'error');
+    drupalgapp_failure_warning($admin_api_email);
+  }
+
+  // @TODO: remove this.
+  $gaccount = 'betatest';
+  $firstname = 'beta';
+  $lastname = 'test';
+  $password = 'moonshine';
+  $username = 'ankur.saxena';
 }
 
 /**
@@ -467,10 +203,11 @@
   curl_setopt($ch, CURLOPT_URL, $url);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($ch, CURLOPT_HTTPHEADER, array($header));
-  curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, $proxy_exist);
+  curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, $proxy_exist); // TRUE of tunnel through a given HTTP proxy
   curl_setopt($ch, CURLOPT_PROXY, $proxy_add);
-  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
-  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2);
+  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // FALSE to stop cURL from verifying the peer's certificate.
+  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2); // 2 to check the existence of a common name and also verify that it matches the hostname provided.
+  // Could set CURLOPT_SSL_VERIFYHOST to 1 to check the existence of a common name in the SSL peer certificate.
 
   // Get the response.
   $result = curl_exec($ch);
@@ -507,10 +244,84 @@
   return FALSE;
 }
 
+/**
+ * @} End of "ingroup client_login".
+ */
 
 /**
- * Google Apps API : wrapper of provisioning API.
+ * @ingroup mail
+ * @{
  */
+
+/**
+ * Handle authentication failures.
+ */
+function drupalgapp_failure_warning($admin_api_email) {
+  global $user;
+
+  // Function to send results over email.
+  $params['subject'] = t('[@site_name] @severity_desc: Alert from your web site', array(
+    '@site_name' => variable_get('site_name', 'Drupal'),
+    '@severity_desc' => t('Critical'),
+  ));
+
+  $params['message']  = "\nSite:         @base_url";
+  $params['message'] .= "\nSeverity:     @severity_desc";
+  $params['message'] .= "\nType:         @type";
+  $params['message'] .= "\nUser:         @name";
+  $params['message'] .= "\nLink:         @link";
+  $params['message'] .= "\nMessage:      \n\n@message\n@reason1\n@reason2";
+
+  $params['message'] = t($params['message'], array(
+    '@base_url'      => url('<front>', array('absolute' => TRUE)),
+    '@severity_desc' => t('Critical'),
+    '@type'          => 'Google Apps',
+    '@name'          => 'Administrator',
+    '@link'          => url('admin/settings/drupalgapps', array('absolute' => TRUE)),
+    '@message'       => 'DrupalGapps module is unable to fetch authentication token for provisioning API. Hence all CRUD action on Google apps user accounts (Google apps user management) has been halted. Probable reason could be : ',
+    '@reason1'       => '1. The admin account credentials being used to fetch Auth. token havent changed .',
+    '@reason2'       => '2. There is a problem in Internet connection on your webserver.',
+  ));
+
+
+  if (variable_get('drupalgapps_failure_email', NULL) != NULL) {
+    drupal_mail('drupalgapps', 'warning', variable_get('drupalgapps_failure_email', variable_get('site_mail', NULL)), user_preferred_language($account), $params, NULL, TRUE);
+  }
+  else {
+    drupal_mail('drupalgapps', 'warning', $admin_api_email, user_preferred_language($account), $params, NULL, TRUE);
+  }
+
+  watchdog('Google Apps', 'Critical : unable to fetch Authentication token from Google . Google Apps User account managament is halted . Most probably Problem arised because of the Admin creditential. Check them. ', array(), WATCHDOG_CRITICAL, l(t('DrupalGapps Settings'), 'admin/settings/drupalgapps'));
+
+}
+
+
+/**
+ * Implementation of hook_mail().
+ */
+function drupalgapps_mail($key, &$message, $params) {
+  global $user;
+
+  switch ($key) {
+    case 'warning':
+      $message['subject'] = $params['subject'];
+      $message['body'] = $params['message'];
+      break;
+  }
+}
+
+/**
+ * @} End of "ingroup mail".
+ */
+
+/**
+ * @ingroup provisioning_api
+ * @{
+ */
+
+/**
+ * Create user account.
+ */
 function drupalgapps_make_gaccount($gaccount, $firstname, $lastname, $password, $quota = '', $changePassword = TRUE, $suspended = FALSE, $admin = FALSE) {
 
   $data = <<<XML
@@ -563,8 +374,8 @@
   //Some more XML
 
    $httpresult = drupal_http_request('https://apps-apis.google.com/a/feeds/jiitu.org/user/2.0',
-                                array(  'Authorization' => "GoogleLogin auth=".$auth,
-                                        'Content-Type' => "application/atom+xml"),
+                                array('Authorization' => "GoogleLogin auth=".$auth,
+                                      'Content-Type' => "application/atom+xml"),
    add                             'POST',
                                 $post_data);
 
@@ -1021,3 +832,6 @@
   }
 }
 
+/**
+ * @} End of "ingroup provisioning_api".
+ */
Index: drupalgapps.install
===================================================================
--- drupalgapps.install	(revision 524)
+++ drupalgapps.install	(working copy)
@@ -1,4 +1,5 @@
 <?php
+// $Id$
 
 /**
  * @file
