Location: PHPKode > scripts > Facebook 2011 For PhpBB > Facebook_2011/root/includes/ucp/ucp_fbregister.php
<?php
/**
 * @package		Facebook 2011
 * @author      Damien Keitel <hide@address.com>
 * @license 	http://opensource.org/licenses/gpl-license.php GNU Public License
 * @link        http://forums.damienkeitel.com
 * @copyright (c) 2011 Damien Keitel
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
 * NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 *
 */

/**
* @ignore
*/
if (!defined('IN_PHPBB'))
{
	exit;
}

  /**
  * ucp_fbregister
  * Facebook Board registration
   * @package		Facebook 2011
  */
class ucp_fbregister
{
  var $u_action;
          
    function get_facebook_cookie($app_id, $app_secret) {
      $args = array();
      parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
      ksort($args);
      $payload = '';
      foreach ($args as $key => $value) {
        if ($key != 'sig') {
          $payload .= $key . '=' . $value;
        }
      }
      if (md5($payload . $app_secret) != $args['sig']) {
        return null;
      }
      return $args;
    }

  function parse_signed_request($signed_request, $secret) {
    list($encoded_sig, $payload) = explode('.', $signed_request, 2); 

    // decode the data
    $sig = self::base64_url_decode($encoded_sig);
    $data = json_decode(self::base64_url_decode($payload), true);

    if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
      error_log('Unknown algorithm. Expected HMAC-SHA256');
      return null;
    }

    // check sig
    $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
    if ($sig !== $expected_sig) {
      error_log('Bad Signed JSON signature!');
      return null;
    }

    return $data;
  }

  function base64_url_decode($input) {
      return base64_decode(strtr($input, '-_', '+/'));
  }

  function main($id, $mode)
  {
    global $config, $db, $user, $auth, $template, $phpbb_root_path, $phpEx;
      
    define('FACEBOOK_APP_ID', $config['fb2011_appid']);
    define('FACEBOOK_SECRET', $config['fb2011_secret']);
    //
    if ($config['require_activation'] == USER_ACTIVATION_DISABLE)
    {
      trigger_error('UCP_REGISTER_DISABLE');
    }

    include($phpbb_root_path . 'includes/functions_profile_fields.' . $phpEx);
    include($phpbb_root_path . 'includes/functions_fb2011.' . $phpEx);
    
    $user->add_lang('mods/fb2011');	// Global Alternate Login language file.
    $user->add_lang('mods/info_ucp_fb2011');
    
    $coppa			= (isset($_REQUEST['coppa'])) ? ((!empty($_REQUEST['coppa'])) ? 1 : 0) : false;
    $agreed			= (!empty($_POST['agreed'])) ? 1 : 0;
    $submit			= true;
    $change_lang	= request_var('change_lang', 0);
    $user_lang		= request_var('lang', $user->lang_name);
    $fb2011_login			= (request_var('fb2011_login', 0) == 1) ? true : false;
    $fb2011_login_type		= request_var('fb2011_login_type', 0);
    $fb_user 			= (request_var('fb2011_fb_user', 0) > 1) ? true : false;
    $fb2011_login_fb  = (request_var('fb2011_fb_user', 0) == 1) ? true : false;

    if ($change_lang || $user_lang != $config['default_lang'])
    {
      $use_lang = ($change_lang) ? basename($change_lang) : basename($user_lang);

      if (file_exists($user->lang_path . $use_lang . '/'))
      {
        if ($change_lang)
        {
          $submit = false;

          // Setting back agreed to let the user view the agreement in his/her language
          $agreed = (empty($_GET['change_lang'])) ? 0 : $agreed;
        }

        $user->lang_name = $user_lang = $use_lang;
        $user->lang = array();
        $user->data['user_lang'] = $user->lang_name;
        $user->add_lang(array('common', 'ucp'));
      }
      else
      {
        $change_lang = '';
        $user_lang = $user->lang_name;
      }
    }


    $cp = new custom_profile();

    $error = $cp_data = $cp_error = array();

    if ( ($coppa === false && $config['coppa_enable']) || ($coppa && !$config['coppa_enable']))
    {
      $add_lang = ($change_lang) ? '&amp;change_lang=' . urlencode($change_lang) : '';
      $add_coppa = ($coppa !== false) ? '&amp;coppa=' . $coppa : '';

      $s_hidden_fields = array(
        'change_lang'	=> $change_lang,
      );

      // If we change the language, we want to pass on some more possible parameter.
      if ($change_lang)
      {
        // We do not include the password
        $s_hidden_fields = array_merge($s_hidden_fields, array(
          'username'			=> utf8_normalize_nfc(request_var('username', '', true)),
          'email'				=> strtolower(request_var('email', '')),
          'email_confirm'		=> strtolower(request_var('email_confirm', '')),
          'lang'				=> $user->lang_name,
          'tz'				=> request_var('tz', (float) $config['board_timezone']),
        ));

      }

      // Checking amount of available languages
      $sql = 'SELECT lang_id
        FROM ' . LANG_TABLE;
      $result = $db->sql_query($sql);

      $lang_row = array();
      while ($row = $db->sql_fetchrow($result))
      {
        $lang_row[] = $row;
      }
      $db->sql_freeresult($result);

      if ($coppa === false && $config['coppa_enable'])
      {
        $now = getdate();
        $coppa_birthday = $user->format_date(mktime($now['hours'] + $user->data['user_dst'], $now['minutes'], $now['seconds'], $now['mon'], $now['mday'] - 1, $now['year'] - 13), $user->lang['DATE_FORMAT']);
        unset($now);

        $template->assign_vars(array(
          'S_LANG_OPTIONS'	=> (sizeof($lang_row) > 1) ? language_select($user_lang) : '',
          'L_COPPA_NO'		=> sprintf($user->lang['UCP_COPPA_BEFORE'], $coppa_birthday),
          'L_COPPA_YES'		=> sprintf($user->lang['UCP_COPPA_ON_AFTER'], $coppa_birthday),

          'U_COPPA_NO'		=> append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=fbregister&amp;coppa=0' . $add_lang),
          'U_COPPA_YES'		=> append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=fbregister&amp;coppa=1' . $add_lang),

          'S_SHOW_COPPA'		=> true,
          'S_HIDDEN_FIELDS'	=> build_hidden_fields($s_hidden_fields),
          'S_UCP_FBACTION'		=> append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=fbregister' . $add_lang),
        ));
      }
      else
      {
        $template->assign_vars(array(
          'S_LANG_OPTIONS'	=> (sizeof($lang_row) > 1) ? language_select($user_lang) : '',
          'L_TERMS_OF_USE'	=> sprintf($user->lang['TERMS_OF_USE_CONTENT'], $config['sitename'], generate_board_url()),

          'S_SHOW_COPPA'		=> false,
          'S_REGISTRATION'	=> true,
          'S_HIDDEN_FIELDS'	=> build_hidden_fields($s_hidden_fields),
          'S_UCP_FBACTION'		=> append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=fbregister' . $add_lang . $add_coppa),
          )
        );
      }
      unset($lang_row);

      $this->tpl_name = 'ucp_agreement';
      return;
    }
    
    
    // The CAPTCHA kicks in here. We can't help that the information gets lost on language change. 
    if ($config['enable_confirm'])
    {
      include($phpbb_root_path . 'includes/captcha/captcha_factory.' . $phpEx);
      $captcha =& phpbb_captcha_factory::get_instance($config['captcha_plugin']);
      $captcha->init(CONFIRM_REG);
    }

    // Try to manually determine the timezone and adjust the dst if the server date/time complies with the default setting +/- 1
    $timezone = date('Z') / 3600;
    $is_dst = date('I');

    if ($config['board_timezone'] == $timezone || $config['board_timezone'] == ($timezone - 1))
    {
      $timezone = ($is_dst) ? $timezone - 1 : $timezone;

      if (!isset($user->lang['tz_zones'][(string) $timezone]))
      {
        $timezone = $config['board_timezone'];
      }
    }
    else
    {
      $is_dst = $config['board_dst'];
      $timezone = $config['board_timezone'];
    }

if(isset($_REQUEST['signed_request'])) 
{
  $server_url = generate_board_url();  
  $key_len = 54 - strlen($server_url);
  $key_len = max(6, $key_len); // we want at least 6
  $key_len = ($config['max_pass_chars']) ? min($key_len, $config['max_pass_chars']) : $key_len; // we want at most $config['max_pass_chars']
  $user_actkey = substr(gen_rand_string(10), 0, $key_len);
  $new_user_password = gen_rand_string(8);
    $cookie = $this->get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);
    $response = self::parse_signed_request($_REQUEST['signed_request'], FACEBOOK_SECRET);
    $fb_user = $response['user_id'];
    $fb_data = @json_decode(file_get_contents('https://graph.facebook.com/me?access_token=' . $cookie['access_token']));
    $data = array(
          'username' => $response['registration']['username'],
          'email' => $response['registration']['email'],
          'email_confirm' => $response['registration']['email'],
          'new_password' => $new_user_password,
          'password_confirm' => $new_user_password,
          'tz' => (!$fb_data ? $timezone : (float) $fb_data->timezone),
          'lang' => (isset($_GET['change_lang'])) ? $_GET['change_lang'] : $config['default_lang'],
    );
      
    //Check and initialize some variables if needed
      $error = validate_data($data, array(
        'username'			=> array(
          array('string', false, $config['min_name_chars'], $config['max_name_chars']),
          array('username', '')),
        'new_password'		=> array(
          array('string', false, $config['min_pass_chars'], $config['max_pass_chars']),
          array('password')),
        'password_confirm'	=> array('string', false, $config['min_pass_chars'], $config['max_pass_chars']),
        'email'				=> array(
          array('string', false, 6, 60),
          array('email')),
        'email_confirm'		=> array('string', false, 6, 60),
        'tz'				=> array('num', false, -14, 14),
        'lang'				=> array('match', false, '#^[a-z_\-]{2,}$#i'),
      ));

      //if (!check_form_key('ucp_register'))
      //{
      //	$error[] = $user->lang['FORM_INVALID'];
      //}

      // Replace "error" strings with their real, localised form
      $error = preg_replace('#^([A-Z_]+)$#e', "(!empty(\$user->lang['\\1'])) ? \$user->lang['\\1'] : '\\1'", $error);

      // DNSBL check
      if ($config['check_dnsbl'])
      {
        if (($dnsbl = $user->check_dnsbl('register')) !== false)
        {
          $error[] = sprintf($user->lang['IP_BLACKLISTED'], $user->ip, $dnsbl[1]);
        }
      }

      // validate custom profile fields
      $cp->submit_cp_field('register', $user->get_iso_lang_id(), $cp_data, $error);

      if (!sizeof($error))
      {
        $server_url = generate_board_url();

        // Which group by default?
        $group_name = ($coppa) ? 'REGISTERED_COPPA' : 'REGISTERED';

        $sql = 'SELECT group_id
          FROM ' . GROUPS_TABLE . "
          WHERE group_name = '" . $db->sql_escape($group_name) . "'
            AND group_type = " . GROUP_SPECIAL;
        $result = $db->sql_query($sql);
        $row = $db->sql_fetchrow($result);
        $db->sql_freeresult($result);

        if (!$row)
        {
          trigger_error('NO_GROUP');
        }

        $group_id = $row['group_id'];

        if (($coppa ||
          $config['require_activation'] == USER_ACTIVATION_SELF ||
          $config['require_activation'] == USER_ACTIVATION_ADMIN) && $config['email_enable'])
        {
          $user_actkey = gen_rand_string(mt_rand(6, 10));
          $user_type = USER_INACTIVE;
          $user_inactive_reason = INACTIVE_REGISTER;
          $user_inactive_time = time();
        }
        else
        {
          $user_type = USER_NORMAL;
          $user_actkey = '';
          $user_inactive_reason = 0;
          $user_inactive_time = 0;
        }

        $user_row = array(
          'username'				=> $data['username'],
          'user_password'			=> phpbb_hash($data['new_password']),
          'user_email'			=> $data['email'],
          'group_id'				=> (int) $group_id,
          'user_timezone'			=> (float) $data['tz'],
          'user_dst'				=> $is_dst,
          'user_lang'				=> $data['lang'],
          'user_type'				=> $user_type,
          'user_actkey'			=> $user_actkey,
          'user_ip'				=> $user->ip,
          'user_regdate'			=> time(),
          'user_inactive_reason'	=> $user_inactive_reason,
          'user_inactive_time'	=> $user_inactive_time,
          
        );
        if (($config['allow_avatar_remote_fb']) && ($response['registration']['pic'] == 'true'))
        {
          // this only works with jpg fb images. if test account or blank will null
          $avatar = array('remotelinkfb'=> 'https://graph.facebook.com/' . $response['user_id'] . '/picture?.jpg', 'width'=>50, 'height'=>50);
          $error = array();
          list($user_row['user_avatar_type'], $user_row['user_avatar'], $user_row['user_avatar_width'], $user_row['user_avatar_height']) = avatar_remote_fb($avatar, $error);
        }
        if ($config['new_member_post_limit'])
        {
          $user_row['user_new'] = 1;
        }

        // Register user...
        $user_id = user_add($user_row);

        // This should not happen, because the required variables are listed above...
        if ($user_id === false)
        {
          trigger_error('NO_USER', E_USER_ERROR);
        }
        
        $fb2011_user_login_settings[FB2011_FACEBOOK_LOGIN] = 1;
        
        $fb2011_user_settings = set_fb2011_settings($fb2011_user_login_settings);
      
        $sql = 'INSERT INTO ' . FB2011_USER_DATA . '(user_id, fb2011_user_settings, fb2011_fb_id)'
            . "  VALUES('$user_id', '$fb2011_user_settings', '$fb_user')";
                
        $result = $db->sql_query($sql);
                
        // DB Error
        if(!$result)
        {
          trigger_error('Unable to connect with phpBB database.');
        }

        $fb2011_email_lang = $user->lang['FACEBOOK'];       
        
        // Okay, captcha, your job is done.
        if ($config['enable_confirm'] && isset($captcha))
        {
          $captcha->reset();
        }

        if ($coppa && $config['email_enable'])
        {
          $message = $user->lang['ACCOUNT_COPPA'];
          $email_template = 'coppa_welcome_inactive_fb2011';
        }
        else if ($config['require_activation'] == USER_ACTIVATION_SELF && $config['email_enable'])
        {
          $message = $user->lang['ACCOUNT_INACTIVE'];
          $email_template = 'user_welcome_inactive_fb2011';
        }
        else if ($config['require_activation'] == USER_ACTIVATION_ADMIN && $config['email_enable'])
        {
          $message = $user->lang['ACCOUNT_INACTIVE_ADMIN'];
          $email_template = 'admin_welcome_inactive_fb2011';
        }
        else
        {
          $message = $user->lang['ACCOUNT_ADDED'];
          $email_template = 'user_welcome_fb2011';
        }

        if ($config['email_enable'])
        {
          include_once($phpbb_root_path . 'includes/functions_messenger.' . $phpEx);

          $messenger = new messenger(false);

          $messenger->template($email_template, $data['lang']);

          $messenger->to($data['email'], $data['username']);

          $messenger->headers('X-AntiAbuse: Board servername - ' . $config['server_name']);
          $messenger->headers('X-AntiAbuse: User_id - ' . $user->data['user_id']);
          $messenger->headers('X-AntiAbuse: Username - ' . $user->data['username']);
          $messenger->headers('X-AntiAbuse: User IP - ' . $user->ip);

          $messenger->assign_vars(array(
            'WELCOME_MSG'	=> htmlspecialchars_decode(sprintf($user->lang['WELCOME_SUBJECT'], $config['sitename'])),
            'USERNAME'		=> htmlspecialchars_decode($data['username']),
            'U_ACTIVATE'	=> "$server_url/ucp.$phpEx?mode=activate&u=$user_id&k=$user_actkey")
          );

          if ($coppa)
          {
            $messenger->assign_vars(array(
              'FAX_INFO'		=> $config['coppa_fax'],
              'MAIL_INFO'		=> $config['coppa_mail'],
              'EMAIL_ADDRESS'	=> $data['email'])
            );
          }

          $messenger->send(NOTIFY_EMAIL);

          if ($config['require_activation'] == USER_ACTIVATION_ADMIN)
          {
            // Grab an array of user_id's with a_user permissions ... these users can activate a user
            $admin_ary = $auth->acl_get_list(false, 'a_user', false);
            $admin_ary = (!empty($admin_ary[0]['a_user'])) ? $admin_ary[0]['a_user'] : array();

            // Also include founders
            $where_sql = ' WHERE user_type = ' . USER_FOUNDER;

            if (sizeof($admin_ary))
            {
              $where_sql .= ' OR ' . $db->sql_in_set('user_id', $admin_ary);
            }

            $sql = 'SELECT user_id, username, user_email, user_lang, user_jabber, user_notify_type
              FROM ' . USERS_TABLE . ' ' .
              $where_sql;
            $result = $db->sql_query($sql);

            while ($row = $db->sql_fetchrow($result))
            {
              $messenger->template('admin_activate', $row['user_lang']);
              $messenger->to($row['user_email'], $row['username']);
              $messenger->im($row['user_jabber'], $row['username']);

              $messenger->assign_vars(array(
                'USERNAME'			=> htmlspecialchars_decode($data['username']),
                'U_USER_DETAILS'	=> "$server_url/memberlist.$phpEx?mode=viewprofile&u=$user_id",
                'U_ACTIVATE'		=> "$server_url/ucp.$phpEx?mode=activate&u=$user_id&k=$user_actkey")
              );

              $messenger->send($row['user_notify_type']);
            }
            $db->sql_freeresult($result);
          }
        }

        $message = $message . '<br /><br />' . sprintf($user->lang['RETURN_INDEX'], '<a href="' . append_sid("{$phpbb_root_path}index.$phpEx") . '">', '</a>');
        trigger_error($message);
      }

    $s_hidden_fields = array(
      'agreed'		=> 'true',
      'change_lang'	=> 0,
    );

    if ($config['coppa_enable'])
    {
      $s_hidden_fields['coppa'] = $coppa;
    }

    if ($config['enable_confirm'])
    {
      $s_hidden_fields = array_merge($s_hidden_fields, $captcha->get_hidden_fields());
    }
    $s_hidden_fields = build_hidden_fields($s_hidden_fields);
    $confirm_image = '';

    // Visual Confirmation - Show images
    if ($config['enable_confirm'])
    {
      $template->assign_vars(array(
        'CAPTCHA_TEMPLATE'		=> $captcha->get_template(),
      ));
    }

    //
    $l_reg_cond = '';
    switch ($config['require_activation'])
    {
      case USER_ACTIVATION_SELF:
        $l_reg_cond = $user->lang['UCP_EMAIL_ACTIVATE'];
      break;

      case USER_ACTIVATION_ADMIN:
        $l_reg_cond = $user->lang['UCP_ADMIN_ACTIVATE'];
      break;
    }
}
//BEGIN fb2011 mod
$fbreg =    '<fb:registration redirect-uri="' . generate_board_url() . '/ucp.php?mode=fbregister' . '"' . "\n" .
            ' fields=\'[' . "\n" .
            '   {"name":"name"},' . "\n" .
            '   {"name":"email"},' . "\n" .
            '   {"name":"username", "description":"' . $user->lang['USERNAME'] . '","type":"text"},' . "\n";
if($config['fb2011_fb_show_bday'] == 'yes') 
{
  $fbreg .= '   {"name":"birthday"},' . "\n";
}       
if($config['fb2011_fb_show_gender'] == 'yes') 
{
  $fbreg .= '   {"name":"gender"},' . "\n";
}
if($config['fb2011_fb_show_location'] == 'yes') 
{
  $fbreg .= '   {"name":"location"},' . "\n";
} 
  $fbreg .= '   {"name":"pic", "description":"' . $user->lang['LINK_REMOTE_AVATAR_EXPLAIN_FB'] . '", "type":"checkbox",  "default":"checked"},' . "\n" .
            '   ]\'' . "\n" .
            ' onvalidate="validate"></fb:registration> ' . "\n" .
            '' . "\n" .
            '<script> ' . "\n" .
            'function validate(form) {' . "\n" .
            ' var illegalChars = /[\W_]/;' . "\n" .
            '  errors = {};' . "\n" .
            'if (form.username == "") {' . "\n" .
            '        errors.username = "' . $user->lang['NO_USER_SPECIFIED'] . '\n";' . "\n" .
            '    } else if ((form.username.length < 3) || (form.username.length > 35)) {' . "\n" .
            '        errors.username = "' . $user->lang['TOO_SHORT_USERNAME'] . '\n";' . "\n" .
            '    } else if (illegalChars.test(form.username)) {' . "\n" .
            '        errors.username = "' . $user->lang['INVALID_CHARS_USERNAME'] . '\n";' . "\n" .
            '    }' . "\n" . 
            '  return errors;' . "\n" .
            '}' . "\n" .
            '</script>' . "\n";
//END fb2011 mod
    
    
$template->assign_vars(array(
      'ERROR'				=> (sizeof($error)) ? implode('<br />', $error) : '',
      'FB2011_FB_REGO'     => $fbreg,
      'S_FB2011' => (isset($fb_user) ? true : false),
      //'FACEBOOK'      => 'testing',
//			'S_TZ_OPTIONS'		=> tz_select($data['tz']),
      'S_CONFIRM_REFRESH'	=> ($config['enable_confirm'] && $config['confirm_refresh']) ? true : false,
      'S_REGISTRATION'	=> true,
      'S_COPPA'			=> $coppa,
//			'S_HIDDEN_FIELDS'	=> $s_hidden_fields,
      'S_UCP_FBACTION'		=> append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=fbregister'),
    ));

    //
    $user->profile_fields = array();

    // Generate profile fields -> Template Block Variable profile_fields
    $cp->generate_profile_fields('register', $user->get_iso_lang_id());

    //
    $this->tpl_name = 'ucp_register';
    $this->page_title = 'UCP_REGISTRATION';
  }
}

?>
Return current item: Facebook 2011 For PhpBB