90891653 by Chris Boden

Added Cookie as external; updated FB a LOT, committing while working, lots of junk code with it

1 parent 1a53179d
......@@ -4,19 +4,29 @@ namespace Tz\WordPress\Tools\Analytics;
use Tz;
use Tz\WordPress\Tools;
const OPTION_NAME = 'tz_analytics';
const VERSION = 1;
const OPTION_NAME = 'tz_analytics';
const OPTION_GROUP = 'reading';
const OPTION_SECTION = 'tz_analytics_main';
call_user_func(function() {
Vars::$options = new Tools\WP_Option(OPTION_NAME);
Tools\add_actions(__NAMESPACE__ . '\Actions');
if (is_admin()) {
require_once(__DIR__ . DIRECTORY_SEPARATOR . 'Settings.php');
}
});
function validate($data) {
return $data;
}
class Actions {
public static function admin_init() {
register_setting(OPTION_GROUP, OPTION_NAME, __NAMESPACE__ . '\validate');
add_settings_section(OPTION_SECTION, 'Google Analytics', function() {}, OPTION_GROUP);
Tools\add_settings_fields(__NAMESPACE__ . '\Fields', OPTION_GROUP, OPTION_SECTION);
}
public static function wp_print_scripts() {
if (Tz\LIVE !== 1 || empty(Vars::$options['api_key'])) {
return;
......@@ -27,6 +37,8 @@ class Actions {
_gaq.push(['_setAccount', '<?php echo Vars::$options['api_key']; ?>']);
_gaq.push(['_trackPageview']);
// _gaq.push(['_trackEvent', 'download', 'Membership', 'sub category?']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript';
ga.async = true;
......@@ -38,6 +50,12 @@ class Actions {
}
}
class Fields {
public static function api_key() {
echo '<input type="text" name="' . OPTION_NAME . '[' . __FUNCTION__ . ']" id="' . __FUNCTION__ . '" value="' . Vars::$options[__FUNCTION__] . '" />';
}
}
class Vars {
public static $options;
}
......
<?php
namespace Tz\WordPress\Tools\Analytics\Settings;
use Tz\WordPress\Tools;
use Tz\WordPress\Tools\Analytics;
const OPTION_GROUP = 'tz_analytics_group';
const OPTION_SECTION = 'tz_analytics_main';
const ADMIN_PAGE = 'tz-tool-analytics';
const CAPABILITY = 'configure_analytics';
call_user_func(function() {
$role = get_role('administrator');
$role->add_cap(CAPABILITY);
Tools\add_actions(__NAMESPACE__ . '\Actions');
});
function displayPage() {
require_once(__DIR__ . DIRECTORY_SEPARATOR . 'settings_view.php');
}
function validate($data) {
return $data;
}
class Actions {
public static function admin_menu() {
add_options_page('Analytics', 'Analytics', CAPABILITY, ADMIN_PAGE, __NAMESPACE__ . '\displayPage');
}
public static function admin_init() {
register_setting(OPTION_GROUP, Analytics\OPTION_NAME, __NAMESPACE__ . '\validate');
add_settings_section(OPTION_SECTION, '', function() {}, ADMIN_PAGE);
Tools\add_settings_fields(__NAMESPACE__ . '\Fields', ADMIN_PAGE, OPTION_SECTION);
}
}
class Fields {
public static function api_key() {
echo '<input type="text" name="' . Analytics\OPTION_NAME . '[' . __FUNCTION__ . ']" id="' . __FUNCTION__ . '" value="' . Analytics\Vars::$options[__FUNCTION__] . '" />';
}
}
?>
\ No newline at end of file
<?php
namespace Tz\WordPress\Tools\Analytics\Settings;
?>
<div class="wrap">
<?php screen_icon(); ?>
<h2>Analytics Settings</h2>
<form method="post" action="options.php">
<?php
settings_fields(OPTION_GROUP);
do_settings_sections(ADMIN_PAGE);
?>
<p class="submit"><input type="submit" class="button-primary" value="Save Changes" /></p>
</form>
</div>
\ No newline at end of file
<?php
/*
* TODO:
* Test registration/activations system
* Test injection - none was done
* Possibly create hook for login page
*/
namespace Tz\WordPress\Tools\Auth;
use Tz\WordPress\Tools;
use Tz\Common;
use Exception, LogicException, InvalidArgumentException, BadMethodCallException;
const REG_METH_AUTO_REG = 1;
const REG_METH_VALID_EMAIL = 2;
const ACTION_CHECK_AUTH = 'check_auth';
const FORGOT_METH_VALID_EMAIL = 1;
const FORGOT_METH_RAND_PASS = 2;
// These are all WordPress hooks, I put them here for easy reference
const ACTION_LOGIN = 'wp_login';
const ACTION_LOGOUT = 'wp_logout';
const ACTION_ACTIVATE = 'user_register';
// The things with these is they're dynamic but static functions aren't...
const ACTION_ACTIVATE = 'auth_activate';
//const ACTION_REGISTER
const OPTION_NAME = 'tz_auth'; // Database lookup key (`wp_options`.`option_name`)
call_user_func(function() {
Vars::$options = new Tools\WP_Option(OPTION_NAME);
Tools\add_actions(__NAMESPACE__ . '\Actions');
if (is_admin()) {
require_once(__DIR__ . DIRECTORY_SEPARATOR . 'Settings.php');
}
......@@ -64,6 +73,29 @@ function login($username, $password, $remember = true) {
}
/**
* NOTE: Exerciese EXTREME caution!!! This automatically logs a user user without password verification!!!
* Intended use is for third party authentication
* @param {String} $username Username of the person to login as
* @param {Boolean} $remember Longer session
* @throws
* @returns {WP_User} of the newly authenticated user
*/
function signin($username, $remember = true) {
// What happens if someone is already signed on? Throw exception?
$user = get_user_by('login', $username);
if (false === $user) {
throw new Exception('Invalid username');
}
_set_auth_cookie($user->ID, $remember);
_set_current_user($user->ID);
do_action('wp_login', $username);
return $user;
}
/**
* Attempts to log the user out
* @returns Boolean
* @throws LogicException If HTTP headers have already been sent
......@@ -80,56 +112,116 @@ function logout() {
/**
* @param {Array} $user_data User data array, requires minimum (username, password, email)
* @param {Integer} $registration_method Method of registeration, see constants beginning with REG_METH
* @throws {InvalidArgumentException} If an invalid $registration_method is passed
* @throw {BadMethodCallException} If any of the $user_data parameters are invalid
* @returns {Integer} New user $id if successful
* @returns {String} Unique key to activate the account
* @uses wp-includes/registration.php
* @global $wpdb
* @see wpmu_signup_user
*/
function register($user_data = Array(), $registration_method = 1) {
if (!in_array($registration_method, Array(REG_METH_AUTO_REG, REG_METH_VALID_EMAIL))) {
throw new InvalidArgumentException("Invalid registration method selected");
}
function register($username, $email, $password, $meta = Array()) {
require_once(ABSPATH . WPINC . DIRECTORY_SEPARATOR . 'registration.php');
$user_data = Array(
'username' => $username
, 'password' => $password
, 'email' => $email
);
$meta['password'] = $password;
// array_filter($user_data, 'esc_sql');
$valid = new Validation($user_data);
if (count($valid->errors) > 0) {
throw new BadMethodCallException(implode("\n", $valid->errors));
}
array_filter($user_data, 'esc_sql');
// $key = substr( md5( time() . rand() . $user_email ), 0, 16 );
global $wpdb;
// possibly call wpmu_signup_user() if REG_METH_VALID_EMAIL; _insert_user if REG_METH_AUTO_REG
// Can't do that without making a database call; the unique registration key is created and destroyed in the function
// I'll have to make a database call to retreive it, at the very lest
// I can't do that at all; the function sends an email to the user with a auto-generated password
// I'll have to do database manipulation manually
$id = (int)_insert_user($user_data);
$username = preg_replace( '/\s+/', '', sanitize_user($username, true));
$email = sanitize_email($email);
$key = substr(md5(time() . rand() . $email ), 0, 16);
$meta = serialize($meta);
$wpdb->insert($wpdb->signups, Array(
'domain' => '',
'path' => '',
'title' => '',
'user_login' => $username,
'user_email' => $email,
'registered' => current_time('mysql', true),
'activation_key' => $key,
'meta' => $meta
));
// should I call ACTION_ACTIVATE if REG_METHOD_AUTO_REG?
return $key;
}
// this is so wrong
/**
* @param {String} $key Unique key to activate account
* @global $wpdb
* @see wpmu_activate_signup
*/
function activate($key) {
global $wpdb;
$wpdb->query("UPDATE `{$wpdb->users}` SET `user_status` = 1 WHERE `ID` = {$id}");
$signup = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->signups} WHERE activation_key = %s", $key));
return $id;
}
if (empty($signup)) {
throw new Exception("{$key} is not a valid registration key");
}
if ($signup->active) {
throw new Exception('Account has already been activated');
}
// Do I need to do another username_exists() call?
// Can 2 users put the same username in the signup table at the same time?
// Do I need to re-sanatize this?
$meta = unserialize($signup->meta);
/*
$user_data = Array(
'user_login' => $signup->user_login
, 'user_email' => $signup->user_email
, 'user_pass' => $meta['password']
);
$id = (int)_insert_user($user_data);
*/
$id = _create_user($signup->user_login, $meta['password'], $signup->user_email);
unset($meta['password']);
// Don't think I need $username
function activate($username, $activation_key) {
// wpmu_activate_signup
// I can't do that either; that function sends a WordPress email
if (!$id) {
throw new Exception('Unable to create user');
}
/* Add the user to the appropriate blog
$now = current_time('mysql', true);
$wpdb->update($wpdb->signups, array('active' => 1, 'activated' => $now), array('activation_key' => $key));
global $current_site;
$user_site = get_site_option( 'dashboard_blog', $current_site->blog_id );
if ( $user_site == false )
add_user_to_blog( '1', $user_id, get_site_option( 'default_user_role', 'subscriber' ) );
else
add_user_to_blog( $user_site, $user_id, get_site_option( 'default_user_role', 'subscriber' ) );
do_action(ACTION_ACTIVATE, $user_id);
add_new_user_to_blog( $user_id, $user_email, $meta );
do_action('wpmu_activate_user', $user_id, $password, $meta);
*/
return (int)$id;
}
// Not sure I need this function
// Application can just set rand password
// Or perhapds I do need it, move it to registered again or something???
function forgot_password($username, $forgot_method) {
class Actions {
/*
// I forget why I chose wp() instead of set_current_user()...
public static function wp() {
global $post; // I want a better way to do this
if ($post->ID == Vars::$options['login_page'] && !is_user_logged_in()) {
do_action(ACTION_CHECK_AUTH);
}
}
*/
}
class Validation extends Common\Validation {
......
......@@ -30,10 +30,14 @@ use Tz\WordPress\Tools\Auth;
use FB;
use Exception;
use InvalidArgumentException;
const OPTION_NAME = 'tz_auth_fb';
//setcookie('wpfb_logout', '', time() - 3600, '/');
call_user_func(function() {
Vars::$options = new Tools\WP_Option(OPTION_NAME, Array('button_title' => 'Login'));
......@@ -53,6 +57,7 @@ const OPTION_NAME = 'tz_auth_fb';
function drawLoginButton($echo = true) {
$title = Vars::$options['button_title'] ?: 'Login';
$btn = '<a id="TzFB" class="fb_button fb_button_medium"><span class="fb_button_text">' . $title . '</span></a>';
$btn = '<fb:login-button></fb:login-button>';
if (!$echo) {
return $btn;
......@@ -70,12 +75,51 @@ function getSDK() {
'appId' => Vars::$options['application_id']
, 'secret' => Vars::$options['application_secret']
, 'cookie' => true
, 'domain' => Vars::$options['domain_name']
));
}
return $instance;
}
function load() {
?>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: '<?php echo Vars::$options['application_id']; ?>', status: true, cookie: true, xfbml: true});
FB.getLoginStatus(function(response) {
console.log(response.status);
});
FB.Event.subscribe('auth.login', function(response) { window.location.reload(); });
<?php if (isset($_COOKIE['wpfb_logout'])): ?>
FB.getLoginStatus(function(response) {
if (response.session) {
FB.logout(function() {
var date = new Date();
date.setTime(date.getTime() - 1);
document.cookie = 'wpfb_logout=;expires=' + date.toGMTString() + ';path=/';
// window.location.reload();
});
}
});
<?php endif; ?>
};
(function() {
var e = document.createElement('script');
e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
<?php
}
/*
* Logic for all these methods needs to be re-thought out
* Should only load FB stuff when something happens (decide)
......@@ -88,38 +132,69 @@ class Actions {
* Logs the user in to WP if they logged into FB
* @global $post
*/
public static function wp() {
global $post; // I want a better way to do this
public static function set_current_user() {
$sdk = getSDK();
if (null === ($sess = $sdk->getSession())) {
return;
}
if (isset($_COOKIE['wpfb_logout'])) {
$sdk->setSession();
return;
}
if ($post->ID == Auth\Vars::$options['login_page'] && !is_user_logged_in()) {
$sdk = getSDK();
// if user is not logged in do the following
// if user is logged in merge account? do checks?
if ($sdk->getSession()) {
$info = $sdk->api('/me');
// get email, verify vs database
// register and/or login
// User is not logged into WP and has just logged in via FB
// need try/catch here - I think I got an OAuthException at one point
try {
$info = $sdk->api('/me');
$username = 'fbc' . $sess['uid'];
} catch (FB\FacebookApiException $e) {
return;
}
require_once(ABSPATH . WPINC . DIRECTORY_SEPARATOR . 'registration.php');
if (username_exists($username)) {
$user = Auth\signin($username);
} else {
if (false !== get_user_by('email', $info['email'])) {
// Not sure if I can throw exception, this is outside the theme stuff...
throw new Exception('email conflict');
}
try {
$key = Auth\register($username, $info['email'], _generate_password());
$id = Auth\activate($key);
$user = Auth\signin($username);
} catch (Exception $e) {
// many types of exceptions
}
}
foreach (Vars::$options['ext_perms'] as $key => $on) {
// I need to map some keys to WordPress presets
// update_user_meta($user->ID, $key, $info[$key]);
}
}
/**
* Load the Facebook scripts for login
*/
public static function wp_enqueue_scripts() {
if (is_admin() || is_user_logged_in()) {
return;
}
public static function OFF_wp_enqueue_scripts() {
_enqueue_script('facebook-all', 'http://connect.facebook.net/en_US/all.js');
_enqueue_script('tz-facebook', Tools\url('tz-facebook.js', __FILE__), Array('addEvent'));
_enqueue_script('tz-facebook', Tools\url('tz-facebook.js', __FILE__), Array('addEvent', 'Cookie'));
_localize_script('tz-facebook', 'TzFBData', Array('AppID' => Vars::$options['application_id'], 'ext_perms' => implode(',', array_keys(Vars::$options['ext_perms']))));
_localize_script('tz-facebook', 'TzFBData', Array('AppID' => Vars::$options['application_id'], 'ext_perms' => implode(',', array_keys(Vars::$options['ext_perms'])), 'loginPage' => get_permalink(Auth\Vars::$options['login_page'])));
}
/**
* Creates the anchor needed for Facebook scripts
*/
public static function get_footer() {
public static function OFF_get_footer() {
echo '<div id="fb-root"></div>';
}
......@@ -127,21 +202,28 @@ class Actions {
* Destroy Facebook session data on site if the log out of WordPress
*/
public static function wp_logout() {
$sdk = getSDK();
$sdk->setSession(); // I think this is how you log them out of Facebook
setcookie('wpfb_logout', 1, 0, '/', Vars::$options['domain_name']);
}
}
class ShortCodes {
public static function fb_login_button() {
/*
if (is_user_logged_in()) {
return '';
}
*/
$sdk = getSDK();
if ($sdk->getSession()) {
ob_start();
print_r($sdk->getSession());
print_r($_COOKIE);
try {
print_r($sdk->api('/me'));
} catch (Exception $e) {
die('fuck');
}
$data = '<pre>' . ob_get_contents() . '</pre>';
ob_end_clean();
......
......@@ -51,6 +51,10 @@ class Cred_Fields {
public static function button_title() {
echo '<input type="text" id="' . __FUNCTION__ . '" name="' . Facebook\OPTION_NAME . '[' . __FUNCTION__ . ']" value="' . Facebook\Vars::$options[__FUNCTION__] . '" />';
}
public static function domain() {
echo '<input type="text" id="' . __FUNCTION__ . '" name="' . Facebook\OPTION_NAME . '[' . __FUNCTION__ . ']" value="' . Facebook\Vars::$options[__FUNCTION__] . '" />';
}
}
class Opt_Fields {
......
<?php
namespace FB;
use Exception;
use Exception, OAuthException;
if (!function_exists('curl_init')) {
throw new Exception('Facebook needs the CURL PHP extension.');
......@@ -447,11 +447,14 @@ class Facebook
// results are returned, errors are thrown
if (is_array($result) && isset($result['error'])) {
$e = new FacebookApiException($result);
if ($e->getType() === 'OAuthException') {
$this->setSession(null);
}
throw $e;
try {
throw new FacebookApiException($result);
} catch (FacebookApiException $e) {
if ($e->getType() === 'OAuthException') {
$this->setSession(null);
}
throw $e;
}
}
return $result;
}
......@@ -505,15 +508,17 @@ class Facebook
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
if ($result === false) {
$e = new FacebookApiException(array(
'error_code' => curl_errno($ch),
'error' => array(
try {
throw new FacebookApiException(array(
'error_code' => curl_errno($ch),
'error' => array(
'message' => curl_error($ch),
'type' => 'CurlException',
),
));
curl_close($ch);
throw $e;
)));
} catch (Exception $e) {
curl_close($ch);
throw $e;
}
}
curl_close($ch);
return $result;
......
window.fbAsyncInit = function() {
FB.init({appId: TzFBData.AppID, status: true, cookie: true, xfbml: true});
FB.Event.subscribe('auth.login', function(response) { window.location.reload(); });
};
var TzFB = function() {
var init = function() {
var oBtn = document.getElementById('TzFB');
if (oBtn) {
addEvent(oBtn, 'click', api.login);
}
}
FB.Event.subscribe('auth.login', function(response) { console.log('login called'); window.location.href = TzFBData.loginPage; });
var api = {
login: function() {
FB.login(function() {}, {perms: TzFBData.ext_perms});
}
};
var oBtn = document.getElementById('TzFB');
if (oBtn) {
addEvent(oBtn, 'click', FB.login);
}
if (Cookie.read('wpfb_logout')) {
Cookie.erase('wpfb_logout');
addEvent(window, 'load', init);
return api;
}();
\ No newline at end of file
FB.getLoginStatus(function(response) {
if (response.session) {
FB.logout(function() {
Cookie.erase('wpfb_logout');
window.location.reload();
});
}
});
}
};
\ No newline at end of file
......
......@@ -20,6 +20,7 @@ use Exception;
_register_script('addEvent', url('scripts/addEvent.js', __FILE__));
_register_script('xmlhttpHandler', url('scripts/xmlhttpHandler.js', __FILE__));
_register_script('fireEvent', url('scripts/fireEvent.js', __FILE__));
_register_script('Cookie', url('scripts/Cookie/Cookie.js', __FILE__));
import('ShortCodes');
if (defined('Tz\DEBUG') && Tz\DEBUG === true) {
......
......@@ -165,4 +165,14 @@ function _logout_url() {
$params = func_get_args();
return call_user_func_array('wp' . __FUNCTION__, $params);
}
?>
function _set_auth_cookie() {
$params = func_get_args();
return call_user_func_array('wp' . __FUNCTION__, $params);
}
function _create_user() {
$params = func_get_args();
return call_user_func_array('wpmu' . __FUNCTION__, $params);
}
?>
\ No newline at end of file
......