1
0
mirror of https://github.com/e107inc/e107.git synced 2025-08-25 23:36:29 +02:00

Merge pull request #4099 from Deltik/fix-3492

New 3rd-party PHP dependency manager for e107 core and HybridAuth upgrade.
This commit is contained in:
Cameron
2020-02-26 13:58:03 -08:00
committed by GitHub
297 changed files with 14089 additions and 27806 deletions

View File

@@ -0,0 +1,279 @@
<?php
/**
* e107 website system
*
* Copyright (C) 2008-2020 e107 Inc (e107.org)
* Released under the terms and conditions of the
* GNU General Public License (http://www.gnu.org/licenses/gpl.txt)
*
*/
require_once(e_HANDLER . "user_handler.php");
class SocialLoginConfigManager
{
const SOCIAL_LOGIN_PREF = "social_login";
const SOCIAL_LOGIN_FLAGS = "social_login_active";
const ENABLE_BIT_GLOBAL = 0;
const ENABLE_BIT_TEST_PAGE = 1;
/**
* @var e_pref
*/
private $config;
private $supportedProvidersCache = null;
/**
* SocialLoginHandler constructor.
* @param $config e_pref
*/
public function __construct($config)
{
$this->config = $config;
}
/**
* Check a social login boolean (toggle) setting
*
* For backwards compatibility, if the global bit (0) is off, no other bits can be on.
*
* @param int $bit Which setting to check
* @return boolean TRUE if the setting is enabled, FALSE otherwise
*/
public function isFlagActive($bit = self::ENABLE_BIT_GLOBAL)
{
$flags = $this->config->get(self::SOCIAL_LOGIN_FLAGS);
if (!($flags & 1 << self::ENABLE_BIT_GLOBAL)) return false;
return (bool)($flags & 1 << $bit);
}
/**
* Set a social login boolean (toggle) setting
*
* For backwards compatibility, if the global bit (0) is off, no other bits can be on.
*
* @param int $bit Which setting to change
* @param boolean $active TRUE to enable the setting, FALSE to disable the setting
*/
public function setFlag($bit, $active)
{
$flags = $this->config->get(self::SOCIAL_LOGIN_FLAGS);
if (!is_numeric($flags)) $flags = 0x0;
$flags = $flags & ~(1 << $bit) | ($active << $bit);
if (!($flags & 1 << self::ENABLE_BIT_GLOBAL)) $this->config->set(self::SOCIAL_LOGIN_FLAGS, 0x0);
else $this->config->set(self::SOCIAL_LOGIN_FLAGS, $flags);
$this->saveConfig();
}
/**
* Checks whether the specified social login provider is enabled
* @param $providerName string The un-normalized name of the provider to check
* @return bool Whether the specified provider is enabled
*/
public function isProviderEnabled($providerName)
{
$result = $this->getProviderConfig($providerName, "/enabled");
return (bool)$result;
}
/**
* Disable and remove the specified social login provider
* @param $providerName string The un-normalized name of the provider to forget
*/
public function forgetProvider($providerName)
{
$this->config->removePref(self::SOCIAL_LOGIN_PREF . '/' . $this->normalizeProviderName($providerName));
}
/**
* Overwrite the entire social login provider configuration with the specified options
*
* Does not commit to database.
*
* @param $providerName string The un-normalized name of the social login provider
* @param $options array Associative array of options
* $options['enabled'] bool Whether the social login provider is enabled
* $options['keys'] array Authentication app keys
* $options['keys']['id'] string The OAuth1 client key or OAuth2 client ID
* $options['keys']['secret'] string The OAuth1 or OAuth2 client secret
* $options['scope'] string OAuth2 scopes, space-delimited
* @see SocialLoginConfigManager::saveConfig() to commit to database.
*
*/
public function setProviderConfig($providerName, $options)
{
$config = $this->config->get(self::SOCIAL_LOGIN_PREF);
if (!is_array($config)) $this->config->set(self::SOCIAL_LOGIN_PREF, []);
self::array_unset_empty_recursive($options);
if (empty($options)) $this->forgetProvider($providerName);
else $this->config->setPref(
self::SOCIAL_LOGIN_PREF . '/' . $this->normalizeProviderName($providerName),
$options
);
}
private static function array_unset_empty_recursive(&$array)
{
foreach ($array as $key => &$value)
{
if (is_array($value))
{
$arraySize = self::array_unset_empty_recursive($value);
if (!$arraySize)
{
unset($array[$key]);
}
}
else if (empty($array[$key]))
{
unset($array[$key]);
}
}
return count($array);
}
public function saveConfig()
{
$this->config->save(true, false, false);
}
/**
* Get the social login provider configuration currently stored in the database
* @param $providerName string The un-normalized name of the social login provider
* @param $path string Nested array keys, slash-delimited ("/")
* @return array|mixed The configuration of the specified provider, or the value of the $path
*/
public function getProviderConfig($providerName, $path = "")
{
if (empty($path)) $path = "";
elseif (substr($path, 0, 1) !== "/") $path = "/$path";
$pref = $this->config->getPref(
self::SOCIAL_LOGIN_PREF . '/' . $this->normalizeProviderName($providerName) . $path
);
return $pref;
}
/**
* Get configs of providers that are supported and configured
* @return array Associative array where the key is the denormalized provider name and the value is its config
*/
public function getValidConfiguredProviderConfigs()
{
$supported_providers = $this->getSupportedProviders();
$configured_providers = $this->getConfiguredProviders();
$unsupported_providers = array_diff($configured_providers, $supported_providers);
$configured_providers = array_diff($configured_providers, $unsupported_providers);
$provider_configs = [];
foreach ($configured_providers as $configured_provider)
{
$provider_configs[$configured_provider] =
$this->getProviderConfig($configured_provider);
}
return $provider_configs;
}
/**
* Get the social login providers for which we have adapters
* @return array String list of supported providers. Empty if Hybridauth is broken.
*/
public function getSupportedProviders()
{
if ($this->supportedProvidersCache === null)
$this->supportedProvidersCache = e_user_provider::getSupportedProviders();
return $this->supportedProvidersCache;
}
/**
* Get the type of provider from a provider name
* @param $providerName string Name of the supported social login provider
* @return string|bool "OAuth1", "OAuth2", or "OpenID". If false, the provider name is invalid.
* Other values are technically possible but not supported.
*/
public function getTypeOfProvider($providerName)
{
return e_user_provider::getTypeOf($providerName);
}
/**
* Get standard and supplementary fields of the specified provider
* @param $providerName string Name of the supported social login provider
* @return array Multidimensional associative array where the keys are the known field names and the values are a
* description of what their key is for. Keys can be nested in parent keys. Parent keys will not
* have a description of the key. All fields take a string value. Return will be empty if the
* specified provider does not have any known fields.
*/
public function getFieldsOf($providerName)
{
return e_user_provider::getFieldsOf($providerName);
}
/**
* Get the providers that are currently configured in the core preferences
* @return array String list of configured provider names
*/
public function getConfiguredProviders()
{
$output = [];
$social_login_config = $this->getSocialLoginConfig();
$configured_providers = array_keys($social_login_config);
foreach ($configured_providers as $configured_provider)
{
$output[] = $this->denormalizeProviderName($configured_provider);
}
sort($output);
return $output;
}
protected function getSocialLoginConfig()
{
$config = $this->config->get(self::SOCIAL_LOGIN_PREF);
if (!is_array($config)) $config = [];
return $config;
}
/**
* Turn a provider name into one fit for storage in the database (core preferences)
* @return string Normalized social login provider name
*/
public function normalizeProviderName($providerName)
{
$normalizedProviderName = $providerName;
foreach ($this->getSupportedProviders() as $providerProperCaps)
{
if (mb_strtolower($providerName) == mb_strtolower($providerProperCaps))
{
$normalizedProviderName = $providerProperCaps;
break;
}
}
$providerType = $this->getTypeOfProvider($normalizedProviderName);
$normalizedProviderName = preg_replace('/(OpenID|OAuth1|OAuth2)$/i', '', $normalizedProviderName);
if (empty($normalizedProviderName) && !empty($providerType) || $providerName == $providerType)
return $providerType;
elseif ($providerType)
return "{$normalizedProviderName}-{$providerType}";
return $providerName;
}
/**
* Turn a normalized provider name into a Hybridauth-compatible adapter name
* @param $normalizedProviderName string Provider name stored in the database
* @return string Hybridauth-compatible adapter name. May not necessarily exist in Hybridauth.
*/
public function denormalizeProviderName($normalizedProviderName)
{
list($provider_name, $provider_type) = array_pad(explode("-", $normalizedProviderName), 2, "");
if ($provider_type != $this->getTypeOfProvider($provider_name)) $provider_name .= $provider_type;
return $provider_name;
}
}

View File

@@ -3,7 +3,7 @@
// Generated e107 Plugin Admin Area
require_once('../../class2.php');
if (!getperms('P'))
if (!getperms('P'))
{
e107::redirect('admin');
exit;
@@ -15,63 +15,63 @@ e107::lan('social',false, true);
class social_adminarea extends e_admin_dispatcher
{
protected $modes = array(
protected $modes = array(
'main' => array(
'controller' => 'social_ui',
'path' => null,
'ui' => 'social_form_ui',
'uipath' => null
),
);
);
protected $adminMenu = array(
// 'main/list' => array('caption'=> LAN_MANAGE, 'perm' => 'P'),
// 'main/create' => array('caption'=> LAN_CREATE, 'perm' => 'P'),
'main/configure' => array('caption'=> LAN_CONFIGURE, 'perm' => 'P'),
'main/prefs' => array('caption'=> LAN_PREFS, 'perm' => 'P'),
'main/prefs' => array('caption'=> LAN_PREFS, 'perm' => 'P'),
);
protected $adminMenuAliases = array(
'main/edit' => 'main/list'
);
'main/edit' => 'main/list'
);
protected $menuTitle = LAN_PLUGIN_SOCIAL_NAME;
}
require_once("SocialLoginConfigManager.php");
class social_ui extends e_admin_ui
{
protected $pluginTitle = LAN_PLUGIN_SOCIAL_NAME;
protected $pluginName = 'social';
// protected $eventName = 'social-social'; // remove comment to enable event triggers in admin.
// protected $table = 'social';
// protected $pid = 'interview_id';
protected $perPage = 10;
protected $perPage = 10;
protected $batchDelete = true;
// protected $batchCopy = true;
// protected $sortField = 'somefield_order';
// protected $orderStep = 10;
// protected $tabs = array('Tabl 1','Tab 2'); // Use 'tab'=>0 OR 'tab'=>1 in the $fields below to enable.
// protected $listQry = "SELECT * FROM `#tableName` WHERE field != '' "; // Example Custom Query. LEFT JOINS allowed. Should be without any Order or Limit.
protected $listOrder = '';
protected $fields = array();
protected $fieldpref = array();
protected $preftabs = array(LAN_LOGIN, LAN_SOCIAL_ADMIN_14, LAN_SOCIAL_ADMIN_15, LAN_SOCIAL_ADMIN_16, LAN_SOCIAL_ADMIN_17, LAN_SOCIAL_ADMIN_37);
@@ -107,17 +107,31 @@ class social_ui extends e_admin_ui
);
protected $social_logins = array();
/**
* @var SocialLoginConfigManager
*/
protected $social_login_config_manager;
protected $social_external = array();
public function init()
const TEST_URL = SITEURL."?route=system/xup/test";
public function init()
{
$this->social_login_config_manager = new SocialLoginConfigManager(e107::getConfig());
if(!empty($_POST['save_social']) )
{
$cfg = e107::getConfig();
$cfg->setPref('social_login', $_POST['social_login']);
$cfg->setPref('social_login_active', $_POST['social_login_active']);
foreach ($_POST['social_login'] as $provider_name => $raw_updated_social_login)
{
$this->social_login_config_manager->setProviderConfig($provider_name, $raw_updated_social_login);
}
$social_login_flags =
!!$_POST['social_login_active'] << SocialLoginConfigManager::ENABLE_BIT_GLOBAL |
!!$_POST['social_login_test_page'] << SocialLoginConfigManager::ENABLE_BIT_TEST_PAGE;
$cfg->setPref(SocialLoginConfigManager::SOCIAL_LOGIN_FLAGS, $social_login_flags);
$cfg->setPref('xurl', $_POST['xurl']);
$cfg->save(true, true, true);
@@ -132,120 +146,16 @@ class social_ui extends e_admin_ui
{
$this->prefs['sharing_providers']['writeParms']['optArray'][$k] = $k;
}
// print_a($bla);
// Single/ Social Login / / copied from hybridAuth config.php so it's easy to add more.
// Used Below.
$this->social_logins = array (
// openid providers
"AOL" => array (
"enabled" => true
),
"Facebook" => array (
"enabled" => true,
"keys" => array ( "id" => "", "secret" => "" ),
"trustForwarded" => false,
// A comma-separated list of permissions you want to request from the user. See the Facebook docs for a full list of available permissions: http://developers.facebook.com/docs/reference/api/permissions.
"scope" => "email",
// The display context to show the authentication page. Options are: page, popup, iframe, touch and wap. Read the Facebook docs for more details: http://developers.facebook.com/docs/reference/dialogs#display. Default: page
"display" => ""
),
"Foursquare" => array (
"enabled" => true,
"keys" => array ( "id" => "", "secret" => "" )
),
"Github" => array (
"enabled" => true,
"keys" => array ( "id" => "", "secret" => "" ),
"scope" => "user:email",
),
"Google" => array (
"enabled" => true,
"keys" => array ( "id" => "", "secret" => "" ),
"scope" => "email"
),
/*
"Instagram" => array (
"enabled" => true,
"keys" => array ( "id" => "", "secret" => "" )
),*/
"LinkedIn" => array (
"enabled" => true,
"keys" => array ( "id" => "", "secret" => "" )
),
// windows live
"Live" => array (
"enabled" => true,
"keys" => array ( "id" => "", "secret" => "" )
),
/*
"MySpace" => array (
"enabled" => true,
"keys" => array ( "key" => "", "secret" => "" )
),
*/
"OpenID" => array (
"enabled" => true
),
"Steam" => array (
"enabled" => true,
"keys" => array ( "key" => "" )
),
"Twitter" => array (
"enabled" => true,
"keys" => array ( "key" => "", "secret" => "" ),
"includeEmail" => true,
),
"Yahoo" => array (
"enabled" => true,
"keys" => array ( "id" => "", "secret" => "" ),
),
);
$this->social_external = array(
"Facebook" => "https://developers.facebook.com/apps",
"Twitter" => "https://dev.twitter.com/apps/new",
"Google" => "https://code.google.com/apis/console/",
"Live" => "https://manage.dev.live.com/ApplicationOverview.aspx",
"LinkedIn" => "https://www.linkedin.com/secure/developer",
"Foursquare" => "https://www.foursquare.com/oauth/",
"Github" => "https://github.com/settings/applications/new",
"Steam" => "http://steamcommunity.com/dev/apikey",
"Instagram" => "http://instagram.com/developer"
);
}
// ------- Customize Create --------
public function beforeCreate($new_data)
public function beforeCreate($new_data, $old_data)
{
return $new_data;
}
public function afterCreate($new_data, $old_data, $id)
{
// do something
@@ -253,12 +163,12 @@ class social_ui extends e_admin_ui
public function onCreateError($new_data, $old_data)
{
// do something
}
// do something
}
// ------- Customize Update --------
public function beforeUpdate($new_data, $old_data, $id)
{
return $new_data;
@@ -266,21 +176,19 @@ class social_ui extends e_admin_ui
public function afterUpdate($new_data, $old_data, $id)
{
// do something
// do something
}
public function onUpdateError($new_data, $old_data, $id)
{
// do something
}
// do something
}
function renderHelp()
{
$this->testUrl = SITEURL."?route=system/xup/test";
$notice = "".LAN_SOCIAL_ADMIN_08." <br /><a href='".self::TEST_URL."' rel='external'>".self::TEST_URL."</a>";
$notice = "".LAN_SOCIAL_ADMIN_08." <br /><a href='".$this->testUrl."' rel='external'>".$this->testUrl."</a>";
$callBack = SITEURL."index.php";
$callBack = SITEURL;
$notice .= "<br /><br />".LAN_SOCIAL_ADMIN_09."</br ><a href='".$callBack."'>".$callBack."</a>";
@@ -288,152 +196,75 @@ class social_ui extends e_admin_ui
}
// optional - a custom page.
// optional - a custom page.
public function configurePage()
{
$ns = e107::getRender();
$frm = e107::getForm();
$pref = e107::pref('core');
$slcm = $this->social_login_config_manager;
require_once("social_setup.php");
$social_setup = new social_setup();
if ($social_setup->upgrade_required())
{
return "<p>" . LAN_SOCIAL_UPDATE_REQUIRED . "</p>";
}
$text = $this->generateAdminFormJs();
// e107::getMessage()->addInfo($notice);
$text = "<table class='table adminform'>
$text .= "<table class='table adminform'>
<colgroup>
<col class='col-label' />
<col class='col-control' />
</colgroup>
<tbody>
<tr>
<td><label for='social-login-active'>".LAN_SOCIAL_ADMIN_02."</label>
<td><label for='social-login-active-1'>".LAN_SOCIAL_ADMIN_02."</label>
</td>
<td>
".$frm->radio_switch('social_login_active', $pref['social_login_active'])."
".$frm->radio_switch('social_login_active', $slcm->isFlagActive($slcm::ENABLE_BIT_GLOBAL))."
<div class='smalltext field-help'>".LAN_SOCIAL_ADMIN_07." </div>
</td>
</tr>
<tr><td colspan='2'>
<table class='table table-bordered table-striped'>
<colgroup>
<col style='width:10%' />
<col class='col-control' />
<col class='col-control' />
<col class='col-control' />
<col style='width:20%' />
</colgroup>
<thead>
<tr>
<th>".LAN_SOCIAL_ADMIN_04."</th>
<th>".LAN_SOCIAL_ADMIN_05."</th>
<th>".LAN_SOCIAL_ADMIN_06."</th>
<th>".LAN_SOCIAL_ADMIN_38."</th>
<th class='center'>".LAN_SOCIAL_ADMIN_03."</th>
</tr>
</thead>
";
if(!is_array($pref['social_login']))
{
$pref['social_login'] = array();
}
foreach($this->social_logins as $prov=>$val)
{
$textKeys = '';
$textScope = '';
$keyCount= array();
$label = varset($this->social_external[$prov]) ? "<a class='e-tip' rel='external' title=' ".LAN_SOCIAL_ADMIN_10."' href='".$this->social_external[$prov]."'>".$prov."</a>" : $prov;
$radio_label = strtolower($prov);
$text .= "
<tr>
<td><label for='social-login-".$radio_label."-enabled'>".$label."</label></td>
<td>
<label for='social-login-test-mode-1'>
<a href='".self::TEST_URL."' target='_blank'>".LAN_SOCIAL_ADMIN_TEST_PAGE_TOGGLE."</a>
</label>
</td>
<td>
".$frm->radio_switch('social_login_test_page', $slcm->isFlagActive($slcm::ENABLE_BIT_TEST_PAGE))."
<div class='smalltext field-help'>".LAN_SOCIAL_ADMIN_TEST_PAGE_INFO." </div>
</td>
</tr>";
";
foreach($val as $k=>$v)
{
switch ($k) {
case 'enabled':
$eopt = array('class'=>'e-expandit');
$textEnabled = $frm->radio_switch('social_login['.$prov.'][enabled]', vartrue($pref['social_login'][$prov]['enabled']),'','',$eopt);
break;
case 'keys':
// $cls = vartrue($pref['single_login'][$prov]['keys'][$tk]) ? "class='e-hideme'" : '';
$sty = vartrue($pref['social_login'][$prov]['keys'][vartrue($tk)]) ? "" : "e-hideme";
// $text .= "<div class='e-expandit-container {$sty}' id='option-{$prov}' >";
foreach($v as $tk=>$idk)
{
$eopt = array( 'size'=>'block-level');
$keyCount[] = 1;
$textKeys .= "<td>".$frm->text('social_login['.$prov.'][keys]['.$tk.']', vartrue($pref['social_login'][$prov]['keys'][$tk]), 100, $eopt)."</td>";
}
// $text .= "</div>";
break;
case 'scope':
$eopt = array( 'size'=>'block-level');
$keyCount[] = 1;
$textScope .= "<td>".$frm->text('social_login['.$prov.'][scope]', vartrue($pref['social_login'][$prov]['scope']), 100, $eopt)."</td>";
break;
default:
break;
}
}
if(empty($keyCount))
{
$textKeys = "<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>";
}
elseif(count($keyCount) == 1)
{
$textKeys .= "<td>&nbsp;</td><td>&nbsp;</td>";
}
elseif(count($keyCount) == 2)
{
$textKeys .= "<td>&nbsp;</td>";
}
$text .= $textKeys.$textScope."<td class='center'>".$textEnabled."</td>";
$text .= "
</tr>
";
}
$text .= "</table>
</td></tr>
$supported_providers = $slcm->getSupportedProviders();
$configured_providers = $slcm->getConfiguredProviders();
$unconfigured_providers = array_diff($supported_providers, $configured_providers);
$unsupported_providers = array_diff($configured_providers, $supported_providers);
$configured_providers = array_diff($configured_providers, $unsupported_providers);
$text .= $this->generateSocialLoginSection(
LAN_SOCIAL_LOGIN_SECTION_UNSUPPORTED,
LAN_SOCIAL_LOGIN_SECTION_UNSUPPORTED_DESCRIPTION,
$unsupported_providers
);
$text .= $this->generateSocialLoginSection(
LAN_SOCIAL_LOGIN_SECTION_CONFIGURED,
LAN_SOCIAL_LOGIN_SECTION_CONFIGURED_DESCRIPTION,
$configured_providers
);
$text .= $this->generateSocialLoginSection(
LAN_SOCIAL_LOGIN_SECTION_UNCONFIGURED,
LAN_SOCIAL_LOGIN_SECTION_UNCONFIGURED_DESCRIPTION,
$unconfigured_providers
);
$text .= "
</tbody></table>
";
// -------------------------------
//
//
@@ -454,7 +285,7 @@ class social_ui extends e_admin_ui
'twitter' => array('label'=>"Twitter", "placeholder"=>"eg. https://twitter.com/e107"),
'youtube' => array('label'=>"Youtube", "placeholder"=>"eg.https://youtube.com/e107Inc"),
'linkedin' => array('label'=>"LinkedIn", "placeholder"=>"eg. http://www.linkedin.com/groups?home=&gid=1782682"),
'github' => array('label'=>"Github", "placeholder"=>"eg. https://github.com/e107inc"),
'github' => array('label'=>"GitHub", "placeholder"=>"eg. https://github.com/e107inc"),
'flickr' => array('label'=>"Flickr", "placeholder"=>""),
'instagram' => array('label'=>"Instagram", "placeholder"=>""),
'pinterest' => array('label'=>"Pinterest", "placeholder"=>""),
@@ -506,17 +337,231 @@ class social_ui extends e_admin_ui
return $ret;
}
/**
* @param $text
* @param array $provider_names
* @return string
*/
private function generateSocialLoginSection($section_name, $section_explanation, $provider_names)
{
if (empty($provider_names)) return "";
$text = "
<tr>
<td colspan='2'>
<h4>$section_name</h4>
<p>$section_explanation</p>
<table class='table table-bordered table-striped'>
<colgroup>
<col style='width:10%' />
<col style='width:5%' />
<col class='col-control' />
<col style='width:5%' />
</colgroup>
<thead>
<tr>
<th>" . LAN_SOCIAL_ADMIN_04 . "</th>
<th>" . LAN_SOCIAL_ADMIN_AUTH_TYPE . "</th>
<th>" . LAN_SOCIAL_ADMIN_COLUMN_CONFIGURATION . "</th>
<th class='center'>" . LAN_SOCIAL_ADMIN_03 . "</th>
</tr>
</thead>
";
foreach ($provider_names as $provider_name)
{
$text .= $this->generateSocialLoginRow($provider_name);
}
$text .= "</table>
</td>
</tr>";
return $text;
}
/**
* @param $provider_name
* @return string Text to append
*/
private function generateSocialLoginRow($provider_name)
{
$slcm = $this->social_login_config_manager;
$provider_type = $slcm->getTypeOfProvider($provider_name);
if (empty($provider_type)) $provider_type = "<em>" . LAN_SOCIAL_ADMIN_AUTH_TYPE_UNKNOWN . "</em>";
$normalized_provider_name = $slcm->normalizeProviderName($provider_name);
list($pretty_provider_name,) = array_pad(explode("-", $normalized_provider_name), 2, "");
$frm = e107::getForm();
$textKeys = '';
$textScope = '';
$label = varset(self::getApiDocumentationUrlFor($provider_name)) ? "<a class='e-tip' rel='external' title=' " . LAN_SOCIAL_ADMIN_10 . "' href='" . self::getApiDocumentationUrlFor($provider_name) . "'>" . $pretty_provider_name . "</a>" : $pretty_provider_name;
$radio_label = strtolower($provider_name);
$text = "
<tr>
<td><label for='social-login-" . $radio_label . "-enabled'>" . $label . "</label></td>
<td>$provider_type</td>
";
$text .= "<td>";
$fieldInfo = self::array_slash($slcm->getFieldsOf($provider_name));
foreach ($fieldInfo as $fieldSlash => $description)
{
$field = str_replace("/", "][", $fieldSlash);
$frm_options = [
'size' => 'block-level',
'placeholder' => self::getPlaceholderFor($provider_name, $fieldSlash),
];
$text .= "<div><label>$fieldSlash</label>";
$text .= $frm->text(
"social_login[$provider_name][$field]",
$slcm->getProviderConfig($provider_name, $fieldSlash),
256,
$frm_options
);
$text .= "<div class='smalltext field-help'>$description</div>";
$text .= "</div>";
}
$text .= "</td>";
$textEnabled = $frm->radio_switch("social_login[$provider_name][enabled]", $slcm->isProviderEnabled($provider_name), '', '', ['class' => 'e-expandit']);
$text .= $textKeys . $textScope . "<td class='center'>" . $textEnabled . "</td>";
$text .= "
</tr>
";
return $text;
}
/**
* Based on Illuminate\Support\Arr::dot()
* @copyright Copyright (c) Taylor Otwell
* @license https://github.com/illuminate/support/blob/master/LICENSE.md MIT License
* @param $array
* @param string $prepend
* @return array
*/
private static function array_slash($array, $prepend = '')
{
$results = [];
foreach ($array as $key => $value)
{
if (is_array($value) && !empty($value))
{
$results = array_merge($results, static::array_slash($value, $prepend . $key . '/'));
}
else
{
$results[$prepend . $key] = $value;
}
}
return $results;
}
private static function getPlaceholderFor($providerName, $fieldSlash)
{
switch ($fieldSlash)
{
case "scope":
$propertyName = "scope";
break;
case "openid_identifier":
$propertyName = "openidIdentifier";
break;
default:
$propertyName = "";
}
try
{
$class = "\Hybridauth\Provider\\$providerName";
$reflection = new ReflectionClass($class);
$properties = $reflection->getDefaultProperties();
return isset($properties[$propertyName]) ? $properties[$propertyName] : null;
}
catch (ReflectionException $e)
{
return null;
}
}
private static function getApiDocumentationUrlFor($providerName)
{
try
{
$class = "\Hybridauth\Provider\\$providerName";
$reflection = new ReflectionClass($class);
$properties = $reflection->getDefaultProperties();
return isset($properties['apiDocumentation']) ? $properties['apiDocumentation'] : null;
}
catch (ReflectionException $e)
{
return null;
}
}
private function generateAdminFormJs()
{
return <<<EOD
<script type='text/javascript'>
var e107 = e107 || {'settings': {}, 'behaviors': {}};
let socialLoginSwitches = {
'social-login-test-page__switch': null,
};
function socialLoginSwitchesHighstate(element) {
if (element === undefined) return;
let isActive = element.checked;
if (isActive) {
for (let key in socialLoginSwitches) {
let toggle = $('[name='+key+']');
toggle.bootstrapSwitch('disabled', false);
if (socialLoginSwitches[key] !== null) toggle.bootstrapSwitch('state', socialLoginSwitches[key]);
}
} else {
for (let key in socialLoginSwitches) {
let toggle = $('[name='+key+']');
socialLoginSwitches[key] = toggle.bootstrapSwitch('state');
toggle.bootstrapSwitch('state', false);
toggle.bootstrapSwitch('disabled', true);
}
}
}
(function ($)
{
e107.behaviors.manageSocialLoginSwitches = {
attach: function (context, settings) {
let globalSwitch = $('[name=social-login-active__switch]');
socialLoginSwitchesHighstate(globalSwitch.get(0));
globalSwitch.on('switchChange.bootstrapSwitch', function(event) {
socialLoginSwitchesHighstate(event.target);
});
},
};
})(jQuery);
</script>
EOD;
}
}
class social_form_ui extends e_admin_form_ui
{
}
}
new social_adminarea();
require_once(e_ADMIN."auth.php");

View File

@@ -164,7 +164,7 @@ class social_shortcodes extends e_shortcode
function sc_social_login($parm=null)
{
$pref = e107::pref('core', 'social_login_active');
$pref = e107::getUserProvider()->isSocialLoginEnabled();

View File

@@ -15,8 +15,6 @@ define("LAN_SOCIAL_ADMIN_04", "Provider");
define("LAN_SOCIAL_ADMIN_05", "Key/ID");
define("LAN_SOCIAL_ADMIN_06", "Secret");
define("LAN_SOCIAL_ADMIN_07", "Allows users to signup/login with their social media accounts. When enabled, this option will still allow users to signup/login even if the core user registration system above is disabled.");
define("LAN_SOCIAL_ADMIN_08", "Note: In most cases you will need to obtain an id and secret key from one of the providers.\nClick the blue links to the right to configure.\n\nYou may test your configuration with the following URL:");
define("LAN_SOCIAL_ADMIN_09", "Your callback URL is: ");
define("LAN_SOCIAL_ADMIN_10", "Get a key from the provider");
define("LAN_SOCIAL_ADMIN_11", "Your");
define("LAN_SOCIAL_ADMIN_12", "page");
@@ -50,3 +48,35 @@ define("LAN_SOCIAL_ADMIN_39", "Providers");
define("LAN_SOCIAL_ADMIN_40", "Update User Display Name");
define("LAN_SOCIAL_ADMIN_41", "Update User Avatar");
define("LAN_SOCIAL_ADMIN_42", "Custom Image");
define("LAN_SOCIAL_ADMIN_AUTH_TYPE", "Type");
define("LAN_SOCIAL_ADMIN_AUTH_TYPE_UNKNOWN", "Unknown");
define("LAN_SOCIAL_UPDATE_REQUIRED",
"A <a href=\"" . e_ADMIN_ABS . "e107_update.php\">database update</a> is required to continue using this plugin."
);
define("LAN_SOCIAL_ADMIN_COLUMN_CONFIGURATION", "Configuration");
define("LAN_SOCIAL_ADMIN_TEST_PAGE_TOGGLE", "Test Page");
define("LAN_SOCIAL_ADMIN_TEST_PAGE_INFO", "Enable or disable the social login test page");
define("LAN_SOCIAL_ADMIN_08", "Note: In most cases, you will need to obtain an application ID and secret key from social login providers.\nIf a provider's name is a link, that link should take you to the login application configuration documentation.\n\nYou may test your configuration with the following URL after enabling the \"".LAN_SOCIAL_ADMIN_TEST_PAGE_TOGGLE."\" option:");
define("LAN_SOCIAL_ADMIN_09", "Your callback URL is: ");
define("LAN_SOCIAL_LOGIN_SECTION_UNSUPPORTED", "Broken Configured Providers");
define("LAN_SOCIAL_LOGIN_SECTION_CONFIGURED", "Manage Existing Providers");
define("LAN_SOCIAL_LOGIN_SECTION_UNCONFIGURED", "Add New Providers");
define("LAN_SOCIAL_LOGIN_SECTION_UNSUPPORTED_DESCRIPTION",
"These social login providers were configured in the past but no longer have an adapter that can support them. " .
"This may be due to them no longer existing or being replaced by a different provider."
);
define("LAN_SOCIAL_LOGIN_SECTION_CONFIGURED_DESCRIPTION",
"These social login providers are currently configured. " .
"If the master switch \"" . LAN_SOCIAL_ADMIN_02 . "\" is toggled on, each provider in this table that is " .
"also toggled on may be used for user registration and login. If you empty the fields of a provider here and save, " .
"it will move to the \"" . LAN_SOCIAL_LOGIN_SECTION_UNCONFIGURED . "\" section."
);
define("LAN_SOCIAL_LOGIN_SECTION_UNCONFIGURED_DESCRIPTION",
"These are the available social login providers, which have not been configured. " .
"Once you configure and save a provider here, it will move to the \"" . LAN_SOCIAL_LOGIN_SECTION_CONFIGURED . "\" section."
);

View File

@@ -0,0 +1,193 @@
<?php
/**
* e107 website system
*
* Copyright (C) 2008-2020 e107 Inc (e107.org)
* Released under the terms and conditions of the
* GNU General Public License (http://www.gnu.org/licenses/gpl.txt)
*
*/
require_once("SocialLoginConfigManager.php");
class social_setup
{
const RENAMED_PROVIDERS = [
'AOL' => 'AOLOpenID',
'Github' => 'GitHub',
'Live' => 'WindowsLive',
];
public function upgrade_required()
{
return (
$this->upgrade_required_provider_name_normalization() ||
$this->upgrade_required_rename_xup() ||
$this->upgrade_required_steam_xup_bug()
);
}
private function upgrade_required_provider_name_normalization()
{
$coreConfig = e107::getConfig();
$manager = new SocialLoginConfigManager($coreConfig);
$providerConfig = $coreConfig->getPref(SocialLoginConfigManager::SOCIAL_LOGIN_PREF);
if (!is_array($providerConfig)) $providerConfig = [];
$normalizedProviderNames = array_keys($providerConfig);
foreach ($normalizedProviderNames as $normalizedProviderName)
{
$actualNormalizedProviderName =
$manager->normalizeProviderName($manager->denormalizeProviderName($normalizedProviderName));
if ($actualNormalizedProviderName !== $normalizedProviderName) return true;
}
return false;
}
private function upgrade_required_rename_xup()
{
$db = e107::getDb();
$whereSegment = array_map(function ($oldProviderName)
{
return "user_xup LIKE BINARY '{$oldProviderName}\_%'";
}, array_keys(self::RENAMED_PROVIDERS));
$count = $db->count('user', '(*)', implode(' OR ', $whereSegment));
return $count >= 1;
}
/**
* @see https://github.com/e107inc/e107/pull/4099#issuecomment-590579521
*/
private function upgrade_required_steam_xup_bug()
{
$db = e107::getDb();
$count = $db->count('user', '(*)', "user_xup LIKE 'Steam\_https://steamcommunity.com/openid/id/%'");
return $count >= 1;
}
public function upgrade_pre()
{
$this->upgrade_pre_provider_name_normalization();
$this->upgrade_pre_rename_xup();
$this->upgrade_pre_steam_xup_bug();
}
private function upgrade_pre_provider_name_normalization()
{
$coreConfig = e107::getConfig();
$logger = e107::getMessage();
$manager = new SocialLoginConfigManager($coreConfig);
$providerConfig = $coreConfig->getPref(SocialLoginConfigManager::SOCIAL_LOGIN_PREF);
if (!is_array($providerConfig)) $providerConfig = [];
foreach ($providerConfig as $oldNormalizedProviderName => $oldOptions)
{
$denormalizedProviderName = $manager->denormalizeProviderName($oldNormalizedProviderName);
$denormalizedProviderName = $this->upgradeDenormalizedProviderQuirks($denormalizedProviderName);
$actualNormalizedProviderName = $manager->normalizeProviderName($denormalizedProviderName);
$newOptions = $oldOptions;
/* Commented out because there are no known options to migrate from HybridAuth 2 to Hybridauth 3
if (isset($newOptions['keys']['key']))
{
$newOptions['keys']['id'] = $newOptions['keys']['key'];
unset($newOptions['keys']['key']);
}
if ($newOptions != $oldOptions)
{
$manager->setProviderConfig($denormalizedProviderName, $newOptions);
$logger->addSuccess(
"Updated configuration format of social login provider $denormalizedProviderName"
);
}
*/
if ($actualNormalizedProviderName !== $oldNormalizedProviderName)
{
$manager->setProviderConfig($denormalizedProviderName, $newOptions);
$coreConfig->removePref(
SocialLoginConfigManager::SOCIAL_LOGIN_PREF . '/' . $oldNormalizedProviderName
);
$logger->addSuccess(
"Updated name of social login provider $oldNormalizedProviderName$actualNormalizedProviderName"
);
}
}
$manager->saveConfig();
}
private function upgradeDenormalizedProviderQuirks($denormalizedProviderName)
{
$renamedProviders = self::RENAMED_PROVIDERS;
if (isset($renamedProviders[$denormalizedProviderName])) return $renamedProviders[$denormalizedProviderName];
return $denormalizedProviderName;
}
private function upgrade_pre_rename_xup()
{
$db = e107::getDb();
foreach (self::RENAMED_PROVIDERS as $oldProviderName => $newProviderName)
{
$db->select('user', '*', "user_xup LIKE '{$oldProviderName}\_%'");
$rows = $db->rows();
foreach ($rows as $row)
{
$old_user_xup = $row['user_xup'];
$new_user_xup = preg_replace(
'/^' . preg_quote($oldProviderName) . '_/',
$newProviderName . '_',
$old_user_xup
);
$this->fixUserXup($db, $row['user_id'], $old_user_xup, $new_user_xup);
}
}
}
/**
* @see https://github.com/e107inc/e107/pull/4099#issuecomment-590579521
*/
private function upgrade_pre_steam_xup_bug()
{
$db = e107::getDb();
$db->select('user', '*', "user_xup LIKE 'Steam\_https://steamcommunity.com/openid/id/%'");
$rows = $db->rows();
foreach ($rows as $row)
{
$old_user_xup = $row['user_xup'];
$new_user_xup = str_ireplace(
['http://steamcommunity.com/openid/id/', 'https://steamcommunity.com/openid/id/'],
'',
$old_user_xup
);
$this->fixUserXup($db, $row['user_id'], $old_user_xup, $new_user_xup);
}
}
/**
* @param e_db_mysql $db
* @param string $user_id
* @param string $old_user_xup
* @param string $new_user_xup
*/
private function fixUserXup($db, $user_id, $old_user_xup, $new_user_xup)
{
$logger = e107::getMessage();
$status = $db->update(
'user',
"user_xup = '" . $db->escape($new_user_xup) . "' WHERE user_id = " . $db->escape($user_id)
);
if ($status !== 1)
{
$logger->addError(
"Unexpected error while correcting user_xup of user_id = " . $user_id . " from \"" . $old_user_xup . "\" to \"" . $new_user_xup . "\": " .
$db->getLastErrorText()
);
}
else
{
$logger->addSuccess("Corrected user_xup of user_id = " . $user_id . " from \"" . $old_user_xup . "\" to \"" . $new_user_xup . "\"");
}
}
}