<?php

/**
 * @file
 * Simple Facebook Login Module for Drupal Sites.
 */
define("SIMPLE_FB_CONNECT_DEFAULT_DIMENSIONS_STRING", "1024x1024");
define("SIMPLE_FB_CONNECT_DEFAULT_WIDTH", 1024);
define("SIMPLE_FB_CONNECT_DEFAULT_HEIGHT", 1024);
define("SIMPLE_FB_CONNECT_PERMISSION_DENIED_PARAMETER", 'access_denied');

/**
 * Implements hook_menu().
 */
function simple_fb_connect_menu() {
  $items['user/simple-fb-connect'] = array(
    'title' => (variable_get('simple_fb_connect_login_only', 0) == 0 ? 'Register/' : '') . 'Login with FB',
    'page callback' => 'simple_fb_connect_login',
    'access callback' => 'user_is_anonymous',
    'type' => MENU_LOCAL_TASK,
  );

  $items['admin/config/people/simple-fb-connect'] = array(
    'title' => 'Simple FB Connect Settings',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('simple_fb_connect_api_keys_settings'),
    'access arguments' => array('administer simple fb'),
    'file' => 'simple_fb_connect.admin.inc',
  );
  return $items;
}

/**
 * Implements hook_permission().
 */
function simple_fb_connect_permission() {
  $items = array();
  $items['administer simple fb'] = array(
    'title' => "Administer Simple Facebook Connect Module settings"
  );
  return $items;
}

/**
 * Page callback for the FB Connect URL.
 */
function simple_fb_connect_login() {
    $facebook = facebook_client();
    $acc = $facebook->getAccessToken();
    $fb_user = $facebook->getUser();

    if ($fb_user) {
      $fb_user_profile = $facebook->api('/me');

      $query = db_select('users', 'u');
      $query->condition('u.mail', check_plain($fb_user_profile['email']));
      $query->fields('u', array('uid'));
      $query->range(0, 1);

      $drupal_user_id = 0;
      $result = $query->execute();
      foreach ($result as $record) {
        $drupal_user_id = $record->uid;
      }

      if ($drupal_user_id) {
        $user_obj = user_load($drupal_user_id);
        if ($user_obj->status) {
          $form_state = array();
          $form_state['uid'] = $user_obj->uid;
          user_login_submit(array(), $form_state);
          drupal_set_message(t('You have been logged in with the username !username', array('!username' => $user_obj->name)));
        }
        else {
          drupal_set_message(t('You could not be logged in as your account is blocked. Contact site administrator.'), 'error');
        }
        drupal_goto('user');
      }
      else {
        if (!variable_get('simple_fb_connect_login_only', 0)) {
          //create the drupal user
          //This will generate a random password, you could set your own here
          $drupal_username_generated = simple_fb_connect_unique_user_name(check_plain($fb_user_profile['username']));

          $password = user_password(8);
          //set up the user fields
          $fields = array(
            'name' => $drupal_username_generated,
            'mail' => check_plain($fb_user_profile['email']),
            'pass' => $password,
            'status' => 1,
            'init' => 'email address',
            'roles' => array(
              DRUPAL_AUTHENTICATED_RID => 'authenticated user',
            ),
          );
          if (variable_get('user_pictures', 0)) {
            $dimensions_in_text = variable_get('user_picture_dimensions', SIMPLE_FB_CONNECT_DEFAULT_DIMENSIONS_STRING);
            $dimensions = explode('x', $dimensions_in_text);
            if (count($dimensions) == 2) {
              $width = $dimensions[0];
              $height = $dimensions[1];
            }
            else {
              $width = SIMPLE_FB_CONNECT_DEFAULT_WIDTH;
              $height = SIMPLE_FB_CONNECT_DEFAULT_HEIGHT;
            }
            $pic_url = "https://graph.facebook.com/" . check_plain($fb_user_profile['username']) . "/picture?width=$width&height=$height";
            $response = drupal_http_request($pic_url);
            $file = 0;
            if ($response->code == 200) {
              $file = file_save_data($response->data);
            }
            if (is_object($file)) {
              $fields['picture'] = $file->fid;
            }
          }


          //the first parameter is left blank so a new user is created
          $account = user_save('', $fields);
          // If you want to send the welcome email, use the following code
          // Manually set the password so it appears in the e-mail.
          $account->password = $fields['pass'];
          // Send the e-mail through the user module.
          drupal_mail('user', 'register_no_approval_required', $account->mail, NULL, array('account' => $account), variable_get('site_mail', 'admin@drupalsite.com'));
          drupal_set_message(t('You have been registered with the username !username', array('!username' => $account->name)));
          drupal_goto("user/simple-fb-connect");
        }
        else {
          drupal_set_message(t('There was no account with the email addresse !email found. Please register before trying to login.', array('!email' => check_plain($fb_user_profile['email']))), 'error');
          drupal_goto("user");
        }
      }
    }
    else {
      if (!isset($_REQUEST['error'])) {
        if (variable_get('simple_fb_connect_appid', 0)) {
          $login_url_params = array(
            'scope' => 'email',
            'fbconnect' => 1,
            'redirect_uri' => 'http://' . $_SERVER['HTTP_HOST'] . request_uri(),
          );
          $login_url = $facebook->getLoginUrl($login_url_params);
          drupal_goto($login_url);
        }
        else {
          drupal_set_message(t('Facebook App ID Missing. Can not perform Login now. Contact Site administrator.'), 'error');
          drupal_goto("user");
        }
      }
      else {
        if ($_REQUEST['error'] == SIMPLE_FB_CONNECT_PERMISSION_DENIED_PARAMETER) {
          drupal_set_message(t('Could not login with facebook. You did not grant permission for this app on facebook to access your email address.'), 'error');
        }
        else {
          drupal_set_message(t('There was a problem in logging in with facebook. Contact site administrator.'), 'error');
        }
        drupal_goto('user');
      }
    }
}

/**
 * Implements hook_libraries_info().
 */
function simple_fb_connect_libraries_info() {
  // Returns an associative array, with information about external library
  $libraries['facebook-php-sdk'] = array(
    'name' => 'Facebook PHP SDK',
    'vendor url' => 'https://github.com/facebook/facebook-php-sdk',
    'download url' => 'https://github.com/facebook/facebook-php-sdk/archive/v3.2.3.tar.gz',
    'version arguments' => array(
      'file' => 'readme.md',
      // Best practice: Document the actual version strings for later reference.
      // Facebook PHP SDK (v.3.2.2)
      'pattern' => '/Facebook PHP SDK \(v\.(3\.\d\.\d)\)/',
      'lines' => 3,
    ),
    // supported library version, including relevant files
    'versions' => array(
      '3.2.2' => array(
        'files' => array(
          'php' => array(
            'src/base_facebook.php',
            'src/facebook.php',
          ),
        ),
      ),
    ),
  );
  return $libraries;
}

/**
 * Locates and loads the Facebook PHP SDK library.
 */
function simple_fb_connect_facebook_client_load_include() {
  if (!class_exists('Facebook')) {
    if (function_exists('libraries_load')) {
      $library = libraries_load('facebook-php-sdk');
    }
    else {
      $sdk_path = DRUPAL_ROOT . '/sites/all/libraries/facebook-php-sdk/src/facebook.php';
      $library = array('loaded' => file_exists($sdk_path));
      if ($library['loaded']) {
        require_once $sdk_path;
      }
    }
    if (!$library['loaded']) {
      watchdog('simple_fb_connect', 'Unable to load the required Facebook library');
      drupal_set_message(t('Facebook Library not found'), 'error');
      drupal_goto('user');
    }
  }
  return class_exists('Facebook') && defined('Facebook::VERSION');
}

/**
 * Get the facebook client object for easy access.
 * @return Facebook
 *   Facebook Api object
 */
function facebook_client() {
  static $fb = NULL;

  if (is_null($fb)) {

    if (simple_fb_connect_facebook_client_load_include()) {
      $init_params = array(
        'appId' => variable_get('simple_fb_connect_appid', ''),
        'secret' => variable_get('simple_fb_connect_skey', ''),
      );
      $fb = new Facebook($init_params);
    }
  }

  return $fb;
}

/**
 * Generates a unique username for drupal site based on fb username.
 */
function simple_fb_connect_unique_user_name($fb_name, $i = 0) {
  $trimmed_name = '';
  $user_to_load = '';
  if ($i == 0) {
    $trimmed_name = strtolower(trim(str_replace(' ', '_', $fb_name)));
    $user_to_load = $trimmed_name;
  }
  else {
    $trimmed_name = $fb_name;
    $user_to_load = $trimmed_name . "_" . $i;
  }

  //Check if user exists by loading userbyname
  if (is_object(user_load_by_name($user_to_load))) {
    $i++;
    return (simple_fb_connect_unique_user_name($trimmed_name, $i));
  }
  else {
    return $user_to_load;
  }
}
