<?php
/**
 * Display help and module information
 * @param section which section of the site we’re displaying help
 * @return help text for section
 */
function registration_help($section=’’) {
   $output='';	
   switch ($section) {
      case 'admin/help#registration':
      $output .= t("
      <p>Users with the correct <a href=\"%permissions\">permissions</a> can send registration
       to the site admin via email from a form on the site.</p>
      <p>To enable its use, a user needs the \"access registration\" permission.</p>
      <p>The site admin specifies the email address that the users send to, as well as other
       parameters, such as what fields to show the user to fill (name, address, email), whether
       the user address is to be validated, and whether to log all attempts to use this form.</p>
      <p>The email address is never visible to the users, and therefore cannot be used by SPAM
       harvesters.</p>");
      break;
     case 'admin/modules#description':
       $output = t("Form For Registeration");
       break;
   }
   return $output;
}

function registration_menu($may_cache) {
global $user;
  $access = user_access('can register users');
  
  if ($may_cache) {
    $items[] = array(
    'path'     => 'registration',
    'callback' => 'registration_page',
    'title'    => 'Registration',
    'access'   => $access,
    'weight'   => 0);
 
    $items[] = array('path' => 'admin/registration',
      'title' => t('registration'),
      'callback' => 'registration_admin_categories',
      'access' => user_access('administer site configuration'),
      'weight' => 1);
    
    $items[] = array('path' => 'admin/registration/category',
      'title' => t('categories'),
      'callback' => 'registration_admin_categories',
      'access' => user_access('administer site configuration'),
      'type' => MENU_DEFAULT_LOCAL_TASK
    );
 }
 
  return $items;
}


//For Fields that have to be populated through the database
function registration_admin_categories(){
  
}


//Fields that will be included in the settings page that will be included in the registration page
function registration_settings() {
  $form['registration_fields'] = array (
    '#type' => 'fieldset',
    '#title' => t('Fields to include on the form:'),
    '#tree' => FALSE,
  );
  
  $form['registration_fields']['registration_field_fname'] = array (
    '#type' => 'checkbox',
    '#title' => t(' First Name'),
    '#default_value' => variable_get('registration_field_fname', '1'),
  );

  $form['registration_fields']['registration_field_mname'] = array (
    '#type' => 'checkbox',
    '#title' => t('Middle Name'),
    '#default_value' => variable_get('registration_field_mname', '1'),
  );

  $form['registration_fields']['registration_field_lname'] = array (
    '#type' => 'checkbox',
    '#title' => t('Last Name'),
    '#default_value' => variable_get('registration_field_lname', '1'),
  );

  $form['registration_fields']['registration_field_sex'] = array (
    '#type' => 'checkbox',
    '#title' => t('Sex'),
    '#default_value' => variable_get('registration_field_sex', '0'),
  );

  $form['registration_fields']['registration_field_postal'] = array (
    '#type' => 'checkbox',
    '#title' => t('Postal Address'),
    '#default_value' => variable_get('registration_field_postal', '0'),
  );
 
  $form['registration_fields']['registration_field_collname']=array(
    '#type' => 'checkbox',
    '#title' => t('College Name'),
    '#default_value' => variable_get('registration_field_type',1),
  );	
  
  $form['registration_fields']['registration_field_email'] = array (
    '#type' => 'checkbox',
    '#title' => t('Users Email Address'),
    '#default_value' => variable_get('registration_field_email', '1'),
  );

  $form['registration_fields']['registration_field_phone'] = array (
    '#type' => 'checkbox',
    '#title' => t('Phone Number'),
    '#default_value' => variable_get('registration_field_phone', '0'),
  );

  $form['registration_fields']['registration_field_username'] = array (
    '#type' => 'checkbox',
    '#title' => t('User Name'),
    '#default_value' => variable_get('registration_field_username', '1'),
  );

  $form['registration_fields']['registration_field_password'] = array (
    '#type' => 'checkbox',
    '#title' => t('Password'),
    '#default_value' => variable_get('registration_field_password', '1'),
  );
  
  $form['registration_fields']['registration_field_state']=array(
    '#type' => 'checkbox',
    '#title'=> t('State of Residence'),
    '#default_value' => variable_get('registration_field_state','0'),
  );

  $form['registration_fields']['registration_field_regtype'] = array (
    '#type' => 'checkbox',
    '#title' => t('Registration Type'),
    '#default_value' => variable_get('registration_field_regtype', '1'),
  );

  $form['miscellaneous_settings'] = array (
    '#type' => 'fieldset',
    '#title' => t('Miscellaneous Settings:'),
    '#tree' => FALSE,
  );

  $form['miscellaneous_settings']['registration_validate_sender_address'] = array (
    '#type' => 'checkbox',
    '#title' => t('Validate Sender\'s Email Address'),
    '#default_value' => variable_get('registration_validate_sender_address', '0'),
  );

  $form['miscellaneous_settings']['registration_logging'] = array (
    '#type' => 'checkbox',
    '#title' => t('Log all registration attempts to watchdog'),
    '#default_value' => variable_get('registration_logging', '1'),
  );
  return $form;
}


//Fields that will be there in the registration form
function registration_display_form () {
  global $user;

  $edit = $_POST["edit"];

  if ( variable_get("registration_field_fname", t('First Name')) )
    $form['form_field_fname'] = array (
      '#type' => 'textfield',
      '#title' => t('Your First Name'),
      '#default_value' => $edit['form_field_fname'],
      '#size' => '20',
      '#maxlength' => '64',
    );
  
  if ( variable_get("registration_field_mname", t('Middle Name')) )
    $form['form_field_mname'] = array (
      '#type' => 'textfield',
      '#title' => t('Your Middle Name'),
      '#default_value' => $edit['form_field_mname'],
      '#size' => '20',
      '#maxlength' => '64',
    );
  
  if ( variable_get("registration_field_lname", t('Last Name')) )
    $form['form_field_lname'] = array (
      '#type' => 'textfield',
      '#title' => t('Your Last Name'),
      '#default_value' => $edit['form_field_lname'],
      '#size' => '20',
      '#maxlength' => '64',
    );

//  $sex = array ('Male', 'Female');
  if ( variable_get("registration_field_sex",t('Sex')) )
    $form['form_field_sex'] = array('#type' => 'select',
    '#title' => t('Sex'),
    '#options' => array('0' => 'Male', '1' => 'Female'),
    '#default_value' => $edit['form_field_sex'],
    '#description' => t('Enter Your Sex'),
  );
 
  if ( variable_get("registration_field_collname", t('College Name')) )
    $form['form_field_collname'] = array (
      '#type' => 'textfield',
      '#title' => t('College Name'),
      '#default_value' => $edit['form_field_collname'],
      '#size' => '30',
      '#maxlength' => '64',
    ); 

  if ( variable_get("registration_field_email", t('Email Address')) )
    $form['form_field_email'] = array (
      '#type' => 'textfield',
      '#title' => t('Your E-Mail Address'),
      '#default_value' => $edit['form_field_email'],
      '#size' => '30',
      '#maxlength' => '64',
    );

  if ( variable_get("registration_field_phone", t('Phone Number')) )
    $form['form_field_phone'] = array (
      '#type' => 'textfield',
      '#title' => t('Phone Number'),
      '#default_value' => $edit['form_field_phone'],
      '#size' => '20',
      '#maxlength' => '64',
    );

  if ( variable_get("registration_field_postal", t('Postal Address')) ) 
    $form['form_field_postal'] = array (
      '#type' => 'textfield',
      '#title' => t('Your Postal Address'),
      '#default_value' => $edit['form_field_postal'],
      '#size' => '50',
      '#maxlength' => '64',
    );

  $categories = array ('Andaman and Nicobar','Andhra Pradesh','Arunachal Pradesh','Assam','Bihar','Chhattisgarh','Dadra and Nagar Haveli','Daman and Diu','Delhi','Goa','Gujarat','Haryana','Himachal Pradesh','Jammu and Kashmir','Jharkhand','Karnataka','Kerala','Lakshadweep','Madhya Pradesh','Maharashtra','Manipur','Meghalaya','Mizoram','Nagaland','Orissa','Pondicherry','Punjab','Rajasthan','Sikkim','Tamil Nadu','Tripura','Uttaranchal','Uttar Pradesh','West Bengal');
  if (variable_get("registration_field_state",t("State Of Residence")))
  $form['form_field_state'] = array('#type' => 'select',
          '#title' => t('State Of Residence'),
          '#default_value' => '',
          '#options' => $categories,
          '#required' => TRUE,
        );

  if ( variable_get("registration_field_username", t('Username')) ) 
    $form['form_field_username'] = array (
      '#type' => 'textfield',
      '#title' => t('User Name'),
      '#default_value' => $edit['form_field_username'],
      '#size' => '20',
      '#maxlength' => '64',
    );

  if ( variable_get("registration_field_password", t('Password')) ) 
    $form['form_field_password'] = array (
      '#type' => 'password',
      '#title' => t('Password'),
      '#default_value' => $edit['form_field_password'],
      '#size' => '20',
      '#maxlength' => '64',
    );
/*   
  if (variable_get("registration_field_states",t('State of Residence')))
    $form['form_field_state']=array(
      '#type' => 'dropdown'
      '#default_value' => $edit['form_field_state']
    ); 
*/
  if ( variable_get("registration_field_regtype", t('Registration type')) ) 
    $form['form_field_regtype'] = array (
      '#type' => 'textfield',
      '#title' => t('Registration type'),
      '#default_value' => $edit['form_field_regtype'],
      '#size' => '30',
      '#maxlength' => '64',
    ); 

    $form['form_field_referer'] = array (
      '#type' => 'hidden',
      '#value' => $_SERVER[HTTP_REFERER],
    );

    $form['submit'] = array (
      '#type' => 'submit',
      '#value' => t('Register Now'),
    );

//  $output .= $message . form($form, "post");
//  if ($title) {
//    $output = theme("box", $title, $output);
//  }

  return drupal_get_form('registration_display_form', $form);
}

function registration_display_form_validate($form_id, $form_values) {
  
  if ( variable_get("registration_field_fname", t('First Name')) ){
  if (empty($form_values['form_field_fname'])) {
    form_set_error('First Name', t('You must enter a First Name.'));
  }
  if (!ctype_alpha($form_values['form_field_fname']) ){
    form_set_error('First Name', t('You must enter the first Name in alphabets only'));
  }
  /*$name = $form_values['form_field_name'];
  if (!strlen($name)) return t('You must enter a username.');
  if (substr($name, 0, 1) == ' ') return t('The username cannot begin with a space.');
  if (substr($name, -1) == ' ') return t('The username cannot end with a space.');
  if (ereg('  ', $name)) return t('The username cannot contain multiple spaces in a row.');
  if (ereg("[^\x80-\xF7 [:alnum:]@_.-]", $name)) return t('The username contains an illegal character.');
  if (preg_match('/[\x{80}-\x{A0}'.          // Non-printable ISO-8859-1 + NBSP
                   '\x{AD}'.                 // Soft-hyphen
                   '\x{2000}-\x{200F}'.      // Various space characters
                   '\x{2028}-\x{202F}'.      // Bidirectional text overrides
                   '\x{205F}-\x{206F}'.      // Various text hinting characters
                   '\x{FEFF}'.               // Byte order mark
                   '\x{FF01}-\x{FF60}'.      // Full-width latin
                   '\x{FFF9}-\x{FFFD}]/u',   // Replacement characters
                   $name)) {
    return t('The username contains an illegal character.');
  }*/

}

  if ( variable_get("registration_field_mname", t('Middle Name')) ){
  if (empty($form_values['form_field_mname'])) {
    form_set_error('Middle Name', t('You must enter a Middle Name.'));
  }
  if (!ctype_alpha($form_values['form_field_mname']) ){
    form_set_error('Middle Name', t('You must enter the Middle Name in alphabets only'));
  }}

  if ( variable_get("registration_field_lname", t('Last Name')) ){
  if (empty($form_values['form_field_lname'])) {
    form_set_error('Last Name', t('You must enter a Last Name.'));
  }
  if (!ctype_alpha($form_values['form_field_lname']) ){
    form_set_error('Last Name', t('You must enter the Last Name in alphabets only'));
  }}
  
  if ( variable_get("registration_field_collname", t('College Name')) ){
  if (empty($form_values['form_field_collname'])) {
    form_set_error('College Name', t('You must enter your college name.'));
  }}
  
  if ( variable_get("registration_field_email", t('Email Address')) ){
  if (empty($form_values['form_field_email'])) {
    form_set_error('College Name', t('You must enter your E-Mail ID.'));
  }}
  
  if ( variable_get("registration_field_phone", t('Phone Number')) ){
  if (empty($form_values['form_field_phone'])) {
    form_set_error('Name', t('You must enter a Phone Number.'));
  }
  if (!ctype_digit($form_values['form_field_phone'])){
    form_set_error('Name',t('Please Enter the phone number in digits only'));
  }
  }

  if ( variable_get("registration_field_postal", t('Postal Address')) ) {
  if (empty($form_values['form_field_postal'])) {
    form_set_error('Name', t('You must enter an Address .'));
  }}
  
  if ( variable_get("registration_field_username", t('Username')) ){ 
  if (empty($form_values['form_field_username'])) {
    form_set_error('Name', t('You must enter a User-Name.'));
  }}

  if ( variable_get("registration_field_password", t('Password')) ){ 
  if (empty($form_values['form_field_password'])) {
    form_set_error('Name', t('You must enter a Password.'));
  }
  else {
    $recipients = explode(',', $form_values['form_field_email']);
    foreach($recipients as $recipient) {
      if (!valid_email_address(trim($recipient))) {
        form_set_error('recipients', t('%recipient is an invalid e-mail address.', array('%recipient' => theme('placeholder', $recipient))));
      }}
    }
  }
}


//The Registration page as will appear to the user
function registration_page() {
  $edit = $_POST["edit"];
  $op = arg(1);
  
  // Set breadcrumbs
  $breadcrumb = array(array('path' => 'registration'));
  menu_set_location($breadcrumb);

/*  if ($edit) {
    if ( variable_get("registration_logging", "1") ) {
      registration_watchdog_log();
    }

    registration_validate_data();
    if (form_get_errors()) {
      $form = registration_display_form() ;
      print theme("page", $form);
    }
    else {
      registration_send_email();
      drupal_set_message(variable_get("registration_rmsg_success", "Thank you for your message"));
      drupal_goto(); // Go to home page
    }
  }
  else {*/
    $form = registration_display_form () ;
    print theme("page", $form);
  //}
}

function registration_display_form_submit ($form_id, $form_values)
{
   $sec = array('Male', 'Female');
   $stat=array ('Andaman and Nicobar','Andhra Pradesh','Arunachal Pradesh','Assam','Bihar','Chhattisgarh','Dadra and Nagar Haveli','Daman and Diu','Delhi','Goa','Gujarat','Haryana','Himachal Pradesh','Jammu and Kashmir','Jharkhand','Karnataka','Kerala','Lakshadweep','Madhya Pradesh','Maharashtra','Manipur','Meghalaya','Mizoram','Nagaland','Orissa','Pondicherry','Punjab','Rajasthan','Sikkim','Tamil Nadu','Tripura','Uttaranchal','Uttar Pradesh','West Bengal');


   $password = md5($form_values['form_field_password']); 
   db_query("INSERT INTO {registration} (fname, mname, lname, sex, collname, email, postal, phone, username, password, regtype,state) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')", $form_values['form_field_fname'],$form_values['form_field_mname'],$form_values['form_field_lname'], $sec[$form_values['form_field_sex']], $form_values['form_field_collname'], $form_values['form_field_email'], $form_values['form_field_postal'], $form_values['form_field_phone'], $form_values['form_field_username'],$password , $form_values['form_field_regtype'], $stat[$form_values['form_field_state']]);

  /*
  function user_fields() {
  static $fields; 
  $fields = array('uid', 'name', 'pass', 'mail', 'picture', 'mode', 'sort', 'threshold', 'theme', 'signature', 'created', 'access', 'login', 'status', 'timezone', 'language', 'init', 'data');
  }
 
 function user_save($account, $array = array(), $category = 'account') {
 $user_fields = user_fields(); 
  
    $array['created'] = time();
    $array['uid'] = db_next_id('{users}_uid');

   
    // Note, we wait with saving the data column to prevent module-handled
    // fields from being saved there. We cannot invoke hook_user('insert') here
    // because we don't have a fully initialized user object yet.
   
    foreach ($array as $key => $value) {
      switch($key) {
        case 'pass':
          $fields[] = $key;
          $values[] = md5($value);
          $s[] = "'%s'";
          break;
        case 'uid':        case 'mode':     case 'sort':
        case 'threshold':  case 'created':  case 'access':
        case 'login':      case 'status':
          $fields[] = $key;
          $values[] = $value;
          $s[] = "%d";
          break;
        default:
          if (substr($key, 0, 4) !== 'auth' && in_array($key, $user_fields)) {
            $fields[] = $key;
            $values[] = $value;
            $s[] = "'%s'";
          }
          break;
      }
    }
    db_query('INSERT INTO {users} ('. implode(', ', $fields) .') VALUES ('. implode(', ', $s) .')', $values);

    // Reload user roles (delete just to be safe).
    db_query('DELETE FROM {users_roles} WHERE uid = %d', $array['uid']);
    foreach ((array)$array['roles'] as $rid) {
      db_query('INSERT INTO {users_roles} (uid, rid) VALUES (%d, %d)', $array['uid'], $rid);
    }

    // Build the initial user object.
    $user = user_load(array('uid' => $array['uid']));

    user_module_invoke('insert', $array, $user, $category);

    // Build and save the serialized data field now
    $data = array();
    foreach ($array as $key => $value) {
      if ((substr($key, 0, 4) !== 'auth') && ($key != 'roles') && (!in_array($key, $user_fields)) && ($value !== null)) {
        $data[$key] = $value;
      }
    }
    db_query("UPDATE {users} SET data = '%s' WHERE uid = %d", serialize($data), $user->uid);

    // Build the finished user object.
    $user = user_load(array('uid' => $array['uid']));
  }

  // Save distributed authentication mappings
  $authmaps = array();
  foreach ($array as $key => $value) {
    if (substr($key, 0, 4) == 'auth') {
      $authmaps[$key] = $value;
    }
  }
  if (sizeof($authmaps) > 0) {
    user_set_authmaps($user, $authmaps);
  }

  return $user;
}
 
  $fields['created']=time();
  $fields['uid']=db_next_id('{users}_uid');
  $fields['name']=$form_values['form_field_username'];
  $fields['pass']=$password;
  $fields['mail']=$form_values['form_field_email'];
  
//  db_query("INSERT INTO {users} (uid,name, pass, mail) VALUES ('%s','%s','%s','%s')", $id ,$form_values['form_field_username'], $password, $form_values['form_field_email'];
*/

   drupal_set_message(t('Name %form_field_username has been added .', array('%form_field_username' => theme('placeholder', $form_values['form_field_username']))));
}
?>
