/** * Display a debugging area. * * This function is highly inspired by the Query Monitor. * https://wordpress.org/plugins/query-monitor/ * * Note: in order for this function to display the sql queries, 'SAVEQUERIES' should be defined as true in 'wp-config.php' */ function wsl_display_dev_mode_debugging_area($keyword = 'wsl_') { global $wpdb, $wp_actions, $wp_filter; ?> <style> .wsl-dev-nonselectsql { color: #a0a !important; } .wsl-dev-expensivesql { color: #f44 !important; } .wsl-dev-optionfunc { color: #4a4 !important; } .wsl-dev-wslfunc { color: #1468fa !important; } .wsl-dev-nonwslfunc { color: #a0a !important; } .wsl-dev-usedhook, .wsl-dev-usedhook a { color: #1468fa; } .wsl-dev-usedwslhook { color: #a0a !important; } .wsl-dev-unusedhook, .wsl-dev-unusedhook a{ color: #a3a3a3 !important; } .wsl-dev-hookcallback, .wsl-dev-hookcallback a { color: #4a4 !important; } .wsl-dev-table { width:100%; border: 1px solid #e5e5e5; box-shadow: 0 1px 1px rgba(0, 0, 0, 0.04); border-spacing: 0; clear: both; margin: 0; width: 100%; } .wsl-dev-table td, .wsl-dev-table th { border: 1px solid #dddddd; padding: 8px 10px; background-color: #fff; text-align: left; } </style> <?php if (class_exists('Hybrid_Error', false) && Hybrid_Error::getApiError()) { ?> <h4>Provider API Error</h4> <table class="wsl-dev-table"> <tr> <td> <?php echo Hybrid_Error::getApiError(); ?> </td> </tr> </table> <?php } ?> <h4>SQL Queries</h4> <table class="wsl-dev-table"> <tr> <td colspan="3"> 1. SAVEQUERIES should be defined and set to TRUE in order for the queries to show up (http://codex.wordpress.org/Editing_wp-config.php#Save_queries_for_analysis) <br /> 2. Calls for get_option() don't necessarily result on a query to the database. WP use both cache and wp_load_alloptions() to load all options at once. Hence, it won't be shown here. </td> </tr> <?php $queries = $wpdb->queries; $total_wsl_queries = 0; $total_wsl_queries_time = 0; if ($queries) { foreach ($queries as $item) { $sql = trim($item[0]); $time = $item[1]; $stack = $item[2]; $sql = str_ireplace(array(' FROM ', ' WHERE ', ' LIMIT ', ' GROUP BY ', ' ORDER BY ', ' SET '), array("\n" . 'FROM ', "\n" . 'WHERE ', "\n" . 'LIMIT ', "\n" . 'GROUP BY ', "\n" . 'ORDER BY ', "\n" . 'SET '), $sql); # https://wordpress.org/plugins/query-monitor/ $callers = explode(',', $stack); $caller = trim(end($callers)); if (false !== strpos($caller, '(')) { $caller_name = substr($caller, 0, strpos($caller, '(')) . '()'; } else { $caller_name = $caller; } if (stristr($caller_name, $keyword) || stristr($sql, $keyword) || stristr($stack, $keyword)) { ?> <tr> <td valign="top" width="450"> <?php if (stristr($caller_name, $keyword)) { ?> <a href="https://github.com/hybridauth/WordPress-Social-Login/search?q=<?php echo $caller_name; ?> " target="_blank" class="wsl-dev-wslfunc"><?php echo $caller_name; ?> </a> <?php } else { ?> <a href="https://developer.wordpress.org/?s=<?php echo $caller_name; ?> " target="_blank" class="wsl-dev-nonwslfunc<?php if (stristr($caller_name, '_option')) { echo "- wsl-dev-optionfunc"; } ?> "><?php echo $caller_name; ?> </a> <?php } ?> <p style="font-size:11px; margin-left:10px"> <?php if (count($callers)) { # God damn it for ($i = count($callers) - 1; $i > 0; $i--) { if (!stristr($callers[$i], '.php') && !stristr($callers[$i], 'call_user_func_')) { echo "#{$i} " . $callers[$i] . '<br />'; } } } ?> </p> </td> <td valign="top" class="<?php if (!stristr('#' . $sql, '#select ')) { echo 'wsl-dev-nonselectsql'; } ?> "><?php echo nl2br($sql); ?> </td> <td valign="top" width="50" nowrap class="<?php if ($time > 0.05) { echo 'wsl-dev-expensivesql'; } ?> "><?php echo number_format($time, 4, '.', ''); ?> </td> </tr> <?php $total_wsl_queries++; $total_wsl_queries_time += $time; } } } ?> <tr> <td colspan="2">Total SQL Queries by WSL : <?php echo $total_wsl_queries; ?> </td> <td width="50" nowrap><?php echo number_format($total_wsl_queries_time, 4, '.', ''); ?> </td> </tr> </table> <h4>Hooks</h4> <table class="wsl-dev-table"> <?php if ($wp_actions) { foreach ($wp_actions as $name => $count) { if (isset($wp_filter[$name])) { $action = $wp_filter[$name]; if ($action) { foreach ($action as $priority => $callbacks) { foreach ($callbacks as $callback) { if (isset($callback['function']) && is_string($callback['function'])) { if (stristr($callback['function'], $keyword) || stristr($name, $keyword)) { ?> <tr> <td valign="top" width="270" nowrap class="wsl-dev-usedhook"> <?php if (stristr($name, $keyword)) { ?> <a class="wsl-dev-usedwslhook" href="https://github.com/hybridauth/WordPress-Social-Login/search?q=<?php echo $name; ?> " target="_blank"><?php echo $name; ?> </a> <?php } else { echo $name; } ?> </td> <td valign="top" class="wsl-dev-hookcallback"> <?php if (stristr($callback['function'], $keyword)) { ?> <a href="https://github.com/hybridauth/WordPress-Social-Login/search?q=<?php echo $callback['function']; ?> " target="_blank"><?php echo $callback['function']; ?> </a> <?php } else { echo $callback['function']; } // I hit a record ?> </td> <td valign="top" width="50"> <?php echo $priority; ?> </td> <td valign="top" width="50"> <?php echo $callback['accepted_args']; ?> </td> </tr> <?php } } } } } } elseif (stristr($name, $keyword)) { ?> <tr> <td valign="top" width="270" nowrap class="wsl-dev-unusedhook"> <a href="https://github.com/hybridauth/WordPress-Social-Login/search?q=<?php echo $name; ?> " target="_blank"><?php echo $name; ?> </a> </td> <td></td> <td></td> <td></td> </tr> <?php } } } ?> </table> <h4>PHP Session</h4> <table class="wsl-dev-table"> <?php foreach ($_SESSION as $k => $v) { ?> <tr><th width="270"><label><?php echo $k; ?> </label></th><td><?php print_r($v); ?> </td></tr> <?php } ?> </tbody> </table> <h4>Wordpress</h4> <table class="wsl-dev-table"> <tbody> <tr><th width="270"><label>Version</label></th><td><?php echo get_bloginfo('version'); ?> </td></tr> <tr><th><label>Multi-site</label></th><td><?php echo is_multisite() ? 'Yes' . "\n" : 'No'; ?> </td></tr> <tr><th><label>Site url</label></th><td><?php echo site_url(); ?> </td></tr> <tr><th><label>Home url</label></th><td><?php echo home_url(); ?> </td></tr> <tr><th><label>Plugins url</label></th><td><?php echo plugins_url(); ?> </td></tr> </tbody> </table> <h4>WSL</h4> <table class="wsl-dev-table"> <tbody> <tr><th width="270"><label>Version</label></th><td><?php echo wsl_get_version(); ?> </td></tr> <tr><th><label>Plugin path</label></th><td><?php echo WORDPRESS_SOCIAL_LOGIN_ABS_PATH; ?> </td></tr> <tr><th><label>Plugin url</label></th><td><?php echo WORDPRESS_SOCIAL_LOGIN_PLUGIN_URL; ?> </td></tr> <tr><th><label>HA endpoint</label></th><td><?php echo WORDPRESS_SOCIAL_LOGIN_HYBRIDAUTH_ENDPOINT_URL; ?> </td></tr> </tbody> </table> <h4>Website</h4> <table class="wsl-dev-table"> <tbody> <tr><th width="270"><label>IP</label></th><td><?php echo $_SERVER['SERVER_ADDR']; ?> </td></tr> <tr><th><label>Domain</label></th><td><?php echo $_SERVER['HTTP_HOST']; ?> </td></tr> <tr><th><label>Port</label></th><td><?php echo isset($_SERVER['SERVER_PORT']) ? 'On (' . $_SERVER['SERVER_PORT'] . ')' : 'N/A'; ?> </td></tr> <tr><th><label>X Forward</label></th><td><?php echo isset($_SERVER['HTTP_X_FORWARDED_PROTO']) ? 'On (' . $_SERVER['HTTP_X_FORWARDED_PROTO'] . ')' : 'N/A'; ?> </td></tr> </tbody> </table> <h4>Software</h4> <table class="wsl-dev-table"> <tbody> <tr><th width="270"><label>Server</label></th><td><?php echo $_SERVER['SERVER_SOFTWARE']; ?> </td></tr> <tr><th><label>PHP</label></th><td><?php echo PHP_VERSION; ?> </td></tr> <tr><th><label>MySQL</label></th><td><?php echo $wpdb->db_version(); ?> </td></tr> <tr><th><label>Time</label></th><td><?php echo date(DATE_ATOM, time()); ?> / <?php echo time(); ?> </td></tr> </tbody> </table> <h4>MySQL</h4> <table class="wsl-dev-table"> <tbody> <tr><th width="270"><label>Host</label></th><td><?php echo $wpdb->dbhost; ?> </td></tr> <tr><th><label>User</label></th><td><?php echo $wpdb->dbuser; ?> </td></tr> <tr><th><label>Database</label></th><td><?php echo $wpdb->dbname; ?> </td></tr> <tr><th><label>Prefix</label></th><td><?php echo $wpdb->prefix; ?> </td></tr> <tr><th><label>Base_prefix</label></th><td><?php echo $wpdb->prefix; ?> </td></tr> <tr><th><label>Num_queries</label></th><td><?php echo $wpdb->num_queries; ?> </td></tr> </tbody> </table> <?php }
/** * Make http request */ function request($url, $method, $postfields = NULL, $auth_header = NULL, $content_type = NULL, $multipart = false) { $this->http_info = array(); $ci = curl_init(); /* Curl settings */ curl_setopt($ci, CURLOPT_USERAGENT, $this->curl_useragent); curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->curl_connect_time_out); curl_setopt($ci, CURLOPT_TIMEOUT, $this->curl_time_out); curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:')); curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->curl_ssl_verifypeer); curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader')); curl_setopt($ci, CURLOPT_HEADER, FALSE); curl_setopt($ci, CURLINFO_HEADER_OUT, TRUE); curl_setopt($ci, CURLINFO_HEADER_OUT, TRUE); if ($multipart) { curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:', $auth_header)); } elseif ($content_type) { curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:', "Content-Type: {$content_type}")); } if ($this->curl_proxy) { curl_setopt($ci, CURLOPT_PROXY, $this->curl_proxy); } switch ($method) { case 'POST': curl_setopt($ci, CURLOPT_POST, TRUE); if (!empty($postfields)) { curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields); } if (!empty($auth_header) && $this->curl_auth_header && !$multipart) { curl_setopt($ci, CURLOPT_HTTPHEADER, array('Content-Type: application/atom+xml', $auth_header)); } break; case 'DELETE': curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE'); if (!empty($postfields)) { $url = "{$url}?{$postfields}"; } } curl_setopt($ci, CURLOPT_URL, $url); $response = curl_exec($ci); $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE); $this->http_info = array_merge($this->http_info, curl_getinfo($ci)); curl_close($ci); //- Hybrid_Error::deleteApiError(); if ($this->http_code != 200) { Hybrid_Error::setApiError($this->http_code . '. ' . preg_replace('/\\s+/', ' ', $response)); } if (defined('WORDPRESS_SOCIAL_LOGIN_DEBUG_API_CALLS')) { do_action('wsl_log_provider_api_call', 'OAuth1', $url, $method, $postfields, $this->http_code, $this->http_info, $response); } //- return $response; }
/** * General data send/request method. * * @param str $method * The data communication method. * @param str $url * The Linkedin API endpoint to connect with. * @param str $data * [OPTIONAL] The data to send to LinkedIn. * @param arr $parameters * [OPTIONAL] Addition OAuth parameters to send to LinkedIn. * * @return arr * Array containing: * * array( * 'info' => Connection information, * 'linkedin' => LinkedIn response, * 'oauth' => The OAuth request string that was sent to LinkedIn * ) */ function fetch($method, $url, $data = NULL, $parameters = array()) { // check for cURL if (!extension_loaded('curl')) { // cURL not present throw new LinkedInException('LinkedIn->fetch(): PHP cURL extension does not appear to be loaded/present.'); } try { // generate OAuth values $oauth_consumer = new OAuthConsumer($this->getApplicationKey(), $this->getApplicationSecret(), $this->getCallbackUrl()); $oauth_token = $this->getToken(); $oauth_token = !is_null($oauth_token) ? new OAuthToken($oauth_token['oauth_token'], $oauth_token['oauth_token_secret']) : NULL; $defaults = array('oauth_version' => self::_API_OAUTH_VERSION); $parameters = array_merge($defaults, $parameters); // generate OAuth request $oauth_req = OAuthRequest::from_consumer_and_token($oauth_consumer, $oauth_token, $method, $url, $parameters); $oauth_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $oauth_consumer, $oauth_token); // start cURL, checking for a successful initiation if (!($handle = curl_init())) { // cURL failed to start throw new LinkedInException('LinkedIn->fetch(): cURL did not initialize properly.'); } // set cURL options, based on parameters passed curl_setopt($handle, CURLOPT_CUSTOMREQUEST, $method); curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($handle, CURLOPT_URL, $url); curl_setopt($handle, CURLOPT_VERBOSE, FALSE); if (isset(Hybrid_Auth::$config["proxy"])) { curl_setopt($handle, CURLOPT_PROXY, Hybrid_Auth::$config["proxy"]); } // configure the header we are sending to LinkedIn - http://developer.linkedin.com/docs/DOC-1203 $header = array($oauth_req->to_header(self::_API_OAUTH_REALM)); if (is_null($data)) { // not sending data, identify the content type $header[] = 'Content-Type: text/plain; charset=UTF-8'; switch ($this->getResponseFormat()) { case self::_RESPONSE_JSON: $header[] = 'x-li-format: json'; break; case self::_RESPONSE_JSONP: $header[] = 'x-li-format: jsonp'; break; } } else { $header[] = 'Content-Type: text/xml; charset=UTF-8'; curl_setopt($handle, CURLOPT_POSTFIELDS, $data); } curl_setopt($handle, CURLOPT_HTTPHEADER, $header); // set the last url, headers $this->last_request_url = $url; $this->last_request_headers = $header; // gather the response $return_data['linkedin'] = curl_exec($handle); $return_data['info'] = curl_getinfo($handle); $return_data['oauth']['header'] = $oauth_req->to_header(self::_API_OAUTH_REALM); $return_data['oauth']['string'] = $oauth_req->base_string; //- $http_code = curl_getinfo($handle, CURLINFO_HTTP_CODE); Hybrid_Error::deleteApiError(); if ($http_code != 200) { Hybrid_Error::setApiError($http_code . '. ' . preg_replace('/\\s+/', ' ', $return_data['linkedin'])); } if (defined('WORDPRESS_SOCIAL_LOGIN_DEBUG_API_CALLS')) { do_action('wsl_log_provider_api_call', 'OAuth1.LinkedIn', $url, $method, $data, $http_code, $this->http_info, $return_data['linkedin']); } //- // check for throttling if (self::isThrottled($return_data['linkedin'])) { throw new LinkedInException('LinkedIn->fetch(): throttling limit for this user/application has been reached for LinkedIn resource - ' . $url); } //TODO - add check for NO response (http_code = 0) from cURL // close cURL connection curl_close($handle); // no exceptions thrown, return the data return $return_data; } catch (OAuthException $e) { // oauth exception raised throw new LinkedInException('OAuth exception caught: ' . $e->getMessage()); } }
/** * define:endpoint step 3.1 and 3.2 */ public static function processAuthDone() { Hybrid_Endpoint::authInit(); // Fix a strange behavior when some provider call back ha endpoint // with /index.php?hauth.done={provider}?{args}... if (strrpos($_SERVER["QUERY_STRING"], '?')) { $_SERVER["QUERY_STRING"] = str_replace("?", "&", $_SERVER["QUERY_STRING"]); parse_str($_SERVER["QUERY_STRING"], Hybrid_Endpoint::$request); } $provider_id = trim(strip_tags(Hybrid_Endpoint::$request["hauth_done"])); $hauth = Hybrid_Auth::setup($provider_id); if (!$hauth) { Hybrid_Logger::error("Endpoint: Invalide parameter on hauth_done!"); $hauth->adapter->setUserUnconnected(); header("HTTP/1.0 404 Not Found"); die("Invalide parameter! Please return to the login page and try again."); } try { Hybrid_Logger::info("Endpoint: call adapter [{$provider_id}] loginFinish() "); $hauth->adapter->loginFinish(); } catch (Exception $e) { Hybrid_Logger::error("Exception:" . $e->getMessage(), $e); Hybrid_Error::setError($e->getMessage(), $e->getCode(), $e->getTraceAsString(), $e); $hauth->adapter->setUserUnconnected(); } Hybrid_Logger::info("Endpoint: job done. retrun to callback url."); $hauth->returnToCallbackUrl(); die; }
/** * Makes an HTTP request. This method can be overridden by subclasses if * developers want to do fancier things or use something other than curl to * make the request. * * @param string $url The URL to make the request to * @param array $params The parameters to use for the POST body * @param CurlHandler $ch Initialized curl handle * * @return string The response text */ protected function makeRequest($url, $params, $ch = null) { if (!$ch) { $ch = curl_init(); } $opts = self::$CURL_OPTS; if ($this->getFileUploadSupport()) { $opts[CURLOPT_POSTFIELDS] = $params; } else { $opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&'); } $opts[CURLOPT_URL] = $url; // disable the 'Expect: 100-continue' behaviour. This causes CURL to wait // for 2 seconds if the server does not support this header. if (isset($opts[CURLOPT_HTTPHEADER])) { $existing_headers = $opts[CURLOPT_HTTPHEADER]; $existing_headers[] = 'Expect:'; $opts[CURLOPT_HTTPHEADER] = $existing_headers; } else { $opts[CURLOPT_HTTPHEADER] = array('Expect:'); } curl_setopt_array($ch, $opts); $result = curl_exec($ch); $errno = curl_errno($ch); // CURLE_SSL_CACERT || CURLE_SSL_CACERT_BADFILE if ($errno == 60 || $errno == 77) { self::errorLog('Invalid or no certificate authority found, ' . 'using bundled information'); curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . DIRECTORY_SEPARATOR . 'fb_ca_chain_bundle.crt'); $result = curl_exec($ch); } // With dual stacked DNS responses, it's possible for a server to // have IPv6 enabled but not have IPv6 connectivity. If this is // the case, curl will try IPv4 first and if that fails, then it will // fall back to IPv6 and the error EHOSTUNREACH is returned by the // operating system. if ($result === false && empty($opts[CURLOPT_IPRESOLVE])) { $matches = array(); $regex = '/Failed to connect to ([^:].*): Network is unreachable/'; if (preg_match($regex, curl_error($ch), $matches)) { if (strlen(@inet_pton($matches[1])) === 16) { self::errorLog('Invalid IPv6 configuration on server, ' . 'Please disable or get native IPv6 on your server.'); self::$CURL_OPTS[CURLOPT_IPRESOLVE] = CURL_IPRESOLVE_V4; curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); $result = curl_exec($ch); } } } //- $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); Hybrid_Error::deleteApiError(); if ($http_code != 200) { Hybrid_Error::setApiError($http_code . '. ' . preg_replace('/\\s+/', ' ', $result)); } if (defined('WORDPRESS_SOCIAL_LOGIN_DEBUG_API_CALLS')) { do_action('wsl_log_provider_api_call', 'OAuth2.Facebook', $opts[CURLOPT_URL], null, $opts[CURLOPT_POSTFIELDS], $http_code, curl_getinfo($ch), $result); } //- if ($result === false) { $e = new FacebookApiException(array('error_code' => curl_errno($ch), 'error' => array('message' => curl_error($ch), 'type' => 'CurlException'))); curl_close($ch); throw $e; } curl_close($ch); return $result; }
function wsl_component_authtest() { // HOOKABLE: do_action("wsl_component_authtest_start"); $adapter = null; $provider_id = isset($_REQUEST["provider"]) ? $_REQUEST["provider"] : null; $user_profile = null; $assets_base_url = WORDPRESS_SOCIAL_LOGIN_PLUGIN_URL . 'assets/img/'; if (!class_exists('Hybrid_Auth', false)) { require_once WORDPRESS_SOCIAL_LOGIN_ABS_PATH . "hybridauth/Hybrid/Auth.php"; } try { $provider = Hybrid_Auth::getAdapter($provider_id); // make as few call as possible if (!(isset($_SESSION['wsl::userprofile']) && $_SESSION['wsl::userprofile'] && ($user_profile = json_decode($_SESSION['wsl::userprofile'])))) { $user_profile = $provider->getUserProfile(); $_SESSION['wsl::userprofile'] = json_encode($user_profile); } $adapter = $provider->adapter; } catch (Exception $e) { } $ha_profile_fields = array(array('field' => 'identifier', 'label' => _wsl__("Provider user ID", 'wordpress-social-login')), array('field' => 'profileURL', 'label' => _wsl__("Profile URL", 'wordpress-social-login')), array('field' => 'webSiteURL', 'label' => _wsl__("Website URL", 'wordpress-social-login')), array('field' => 'photoURL', 'label' => _wsl__("Photo URL", 'wordpress-social-login')), array('field' => 'displayName', 'label' => _wsl__("Display name", 'wordpress-social-login')), array('field' => 'description', 'label' => _wsl__("Description", 'wordpress-social-login')), array('field' => 'firstName', 'label' => _wsl__("First name", 'wordpress-social-login')), array('field' => 'lastName', 'label' => _wsl__("Last name", 'wordpress-social-login')), array('field' => 'gender', 'label' => _wsl__("Gender", 'wordpress-social-login')), array('field' => 'language', 'label' => _wsl__("Language", 'wordpress-social-login')), array('field' => 'age', 'label' => _wsl__("Age", 'wordpress-social-login')), array('field' => 'birthDay', 'label' => _wsl__("Birth day", 'wordpress-social-login')), array('field' => 'birthMonth', 'label' => _wsl__("Birth month", 'wordpress-social-login')), array('field' => 'birthYear', 'label' => _wsl__("Birth year", 'wordpress-social-login')), array('field' => 'email', 'label' => _wsl__("Email", 'wordpress-social-login')), array('field' => 'phone', 'label' => _wsl__("Phone", 'wordpress-social-login')), array('field' => 'address', 'label' => _wsl__("Address", 'wordpress-social-login')), array('field' => 'country', 'label' => _wsl__("Country", 'wordpress-social-login')), array('field' => 'region', 'label' => _wsl__("Region", 'wordpress-social-login')), array('field' => 'city', 'label' => _wsl__("City", 'wordpress-social-login')), array('field' => 'zip', 'label' => _wsl__("Zip", 'wordpress-social-login'))); ?> <style> .widefat td, .widefat th { border: 1px solid #DDDDDD; } .widefat th label { font-weight: bold; } .wp-social-login-provider-list { padding: 10px; } .wp-social-login-provider-list a {text-decoration: none; } .wp-social-login-provider-list img{ border: 0 none; } </style> <div class="metabox-holder columns-2" id="post-body"> <table width="100%"> <tr valign="top"> <td> <?php if (!$adapter) { ?> <div style="padding: 15px; margin-bottom: 8px; border: 1px solid #ddd; background-color: #fff;box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);"> <p><?php _wsl_e("Connect with a provider to get started", 'wordpress-social-login'); ?> .</p> </div> <?php } else { ?> <div class="stuffbox"> <h3> <label><?php _wsl_e("Connected adapter specs", 'wordpress-social-login'); ?> </label> </h3> <div class="inside"> <table class="wp-list-table widefat"> <tr> <th width="200"><label><?php _wsl_e("Provider", 'wordpress-social-login'); ?> </label></th> <td><?php echo $adapter->providerId; ?> </td> </tr> <?php if (isset($adapter->openidIdentifier)) { ?> <tr> <th width="200"><label><?php _wsl_e("OpenID Identifier", 'wordpress-social-login'); ?> </label></th> <td><?php echo $adapter->openidIdentifier; ?> </td> </tr> <?php } ?> <?php if (isset($adapter->scope)) { ?> <tr> <th width="200"><label><?php _wsl_e("Scope", 'wordpress-social-login'); ?> </label></th> <td><?php echo $adapter->scope; ?> </td> </tr> <?php } ?> <?php if (isset($adapter->config['keys'])) { ?> <tr> <th width="200"><label><?php _wsl_e("Application keys", 'wordpress-social-login'); ?> </label></th> <td><div style="max-width:650px"><?php echo json_encode($adapter->config['keys']); ?> </div></td> </tr> <?php } ?> <?php if ($adapter->token("access_token")) { ?> <tr> <th width="200"><label><?php _wsl_e("Access token", 'wordpress-social-login'); ?> </label></th> <td><div style="max-width:650px"><?php echo $adapter->token("access_token"); ?> </div></td> </tr> <?php } ?> <?php if ($adapter->token("access_token_secret")) { ?> <tr> <th width="200"><label><?php _wsl_e("Access token secret", 'wordpress-social-login'); ?> </label></th> <td><?php echo $adapter->token("access_token_secret"); ?> </td> </tr> <?php } ?> <?php if ($adapter->token("expires_in")) { ?> <tr> <th width="200"><label><?php _wsl_e("Access token expires in", 'wordpress-social-login'); ?> </label></th> <td><?php echo (int) $adapter->token("expires_at") - time(); ?> <?php _wsl_e("second(s)", 'wordpress-social-login'); ?> </td> </tr> <?php } ?> <?php if ($adapter->token("expires_at")) { ?> <tr> <th width="200"><label><?php _wsl_e("Access token expires at", 'wordpress-social-login'); ?> </label></th> <td><?php echo date(DATE_W3C, $adapter->token("expires_at")); ?> </td> </tr> <?php } ?> </table> </div> </div> <?php $console = false; if (!isset($adapter->openidIdentifier)) { ?> <div class="stuffbox"> <h3> <label><?php _wsl_e("Connected adapter console", 'wordpress-social-login'); ?> </label> </h3> <div class="inside"> <?php $path = isset($adapter->api->api_base_url) ? $adapter->api->api_base_url : ''; $path = isset($_REQUEST['console-path']) ? $_REQUEST['console-path'] : $path; $method = isset($_REQUEST['console-method']) ? $_REQUEST['console-method'] : ''; $query = isset($_REQUEST['console-query']) ? $_REQUEST['console-query'] : ''; $response = ''; if ($path && in_array($method, array('GET', 'POST'))) { $console = true; try { if ($method == 'GET') { $response = $adapter->api->get($path . ($query ? '?' . $query : '')); } else { $response = $adapter->api->get($path, $query); } $response = $response ? $response : Hybrid_Error::getApiError(); } catch (Exception $e) { $response = "ERROR: " . $e->getMessage(); } } ?> <form action="" method="post"/> <table class="wp-list-table widefat"> <tr> <th width="200"><label><?php _wsl_e("Path", 'wordpress-social-login'); ?> </label></th> <td><input type="text" style="width:96%" name="console-path" value="<?php echo htmlentities($path); ?> "><a href="https://apigee.com/providers" target="_blank"><img src="<?php echo $assets_base_url . 'question.png'; ?> " style="vertical-align: text-top;" /></a></td> </tr> <tr> <th width="200"><label><?php _wsl_e("Method", 'wordpress-social-login'); ?> </label></th> <td><select style="width:100px" name="console-method"><option value="GET" <?php if ($method == 'GET') { echo 'selected'; } ?> >GET</option><!-- <option value="POST" <?php if ($method == 'POST') { echo 'selected'; } ?> >POST</option>--></select></td> </tr> <tr> <th width="200"><label><?php _wsl_e("Query", 'wordpress-social-login'); ?> </label></th> <td><textarea style="width:100%;height:60px;margin-top:6px;" name="console-query"><?php echo htmlentities($query); ?> </textarea></td> </tr> </table> <br /> <input type="submit" value="<?php _wsl_e("Submit", 'wordpress-social-login'); ?> " class="button"> </form> </div> </div> <?php if ($console) { ?> <div class="stuffbox"> <h3> <label><?php _wsl_e("API Response", 'wordpress-social-login'); ?> </label> </h3> <div class="inside"> <textarea rows="25" cols="70" wrap="off" style="width:100%;height:400px;margin-bottom:15px;font-family: monospace;font-size: 12px;"><?php echo htmlentities(print_r($response, true)); ?> </textarea> </div> </div> <?php if (0) { ?> <div class="stuffbox"> <h3> <label><?php _wsl_e("Code PHP", 'wordpress-social-login'); ?> </label> </h3> <div class="inside"> <textarea rows="25" cols="70" wrap="off" style="width:100%;height:210px;margin-bottom:15px;font-family: monospace;font-size: 12px;" >include_once WORDPRESS_SOCIAL_LOGIN_ABS_PATH . 'hybridauth/Hybrid/Auth.php'; /*! Important Direct access to providers apis is newly introduced into WSL and we are still experimenting, so they may change in future releases. */ try { $<?php echo strtolower($adapter->providerId); ?> = Hybrid_Auth::getAdapter( '<?php echo htmlentities($provider_id); ?> ' ); <?php if ($method == 'GET') { ?> $response = $<?php echo strtolower($adapter->providerId); ?> ->api()->get( '<?php echo htmlentities($path . ($query ? '?' . $query : '')); ?> ' ); <?php } else { ?> $response = $<?php echo strtolower($adapter->providerId); ?> ->api()->post( '<?php echo htmlentities($path); ?> ', (array) $query ); <?php } ?> } catch( Exception $e ) { echo "Ooophs, we got an error: " . $e->getMessage(); }</textarea> </div> </div> <div class="stuffbox"> <h3> <label><?php _wsl_e("Connected adapter debug", 'wordpress-social-login'); ?> </label> </h3> <div class="inside"> <textarea rows="25" cols="70" wrap="off" style="width:100%;height:400px;margin-bottom:15px;font-family: monospace;font-size: 12px;"><?php echo htmlentities(print_r($adapter, true)); ?> </textarea> </div> </div> <div class="stuffbox"> <h3> <label><?php _wsl_e("PHP Session", 'wordpress-social-login'); ?> </label> </h3> <div class="inside"> <textarea rows="25" cols="70" wrap="off" style="width:100%;height:350px;margin-bottom:15px;font-family: monospace;font-size: 12px;"><?php echo htmlentities(print_r($_SESSION, true)); ?> </textarea> </div> </div> <?php } ?> <?php } ?> <?php } ?> <?php if (!$console) { ?> <div class="stuffbox"> <h3> <label><?php _wsl_e("Connected user social profile", 'wordpress-social-login'); ?> </label> </h3> <div class="inside"> <table class="wp-list-table widefat"> <?php $user_profile = (array) $user_profile; foreach ($ha_profile_fields as $item) { $item['field'] = $item['field']; ?> <tr> <th width="200"> <label><?php echo $item['label']; ?> </label> </th> <td> <?php if (isset($user_profile[$item['field']]) && $user_profile[$item['field']]) { $field_value = $user_profile[$item['field']]; if (in_array(strtolower($item['field']), array('profileurl', 'websiteurl', 'email'))) { ?> <a href="<?php if ($item['field'] == 'email') { echo 'mailto:'; } echo $field_value; ?> " target="_blank"><?php echo $field_value; ?> </a> <?php } elseif (strtolower($item['field']) == 'photourl') { ?> <a href="<?php echo $field_value; ?> " target="_blank"><img width="36" height="36" align="left" src="<?php echo $field_value; ?> " style="margin-right: 5px;" > <?php echo $field_value; ?> </a> <?php } else { echo $field_value; } } ?> </td> </tr> <?php } ?> </table> </div> </div> <?php } ?> <?php } ?> </td> <td width="10"></td> <td width="400"> <div class="postbox"> <div class="inside"> <h3><?php _wsl_e("Authentication Playground", 'wordpress-social-login'); ?> </h3> <div style="padding:0 20px;"> <p> <?php _wsl_e('Authentication Playground will let you authenticate with the enabled social networks without creating any new user account', 'wordpress-social-login'); ?> . </p> <p> <?php _wsl_e('This tool will also give you a direct access to social networks apis via a lightweight console', 'wordpress-social-login'); ?> . </p> </div> </div> </div> </style> <div class="postbox"> <div class="inside"> <div style="padding:0 20px;"> <p> <?php _wsl_e("Connect with", 'wordpress-social-login'); ?> : </p> <div style="width: 380px; padding: 10px; border: 1px solid #ddd; background-color: #fff;"> <?php do_action('wordpress_social_login', array('mode' => 'test', 'caption' => '')); ?> </div> </div> </div> </div> </td> </tr> </table> </div> <?php // HOOKABLE: do_action("wsl_component_authtest_end"); }
/** * Try to initialize Hybrid_Auth with given $config hash or file */ public static function initialize($config) { if (!session_id()) { throw new Exception("Hybriauth require the use of 'session_start()' at the start of your script.", 1); } if (!is_array($config) && !file_exists($config)) { throw new Exception("Hybriauth config does not exist on the given path.", 1); } if (!is_array($config)) { $config = (include $config); } // build some need'd paths $config["path_base"] = realpath(dirname(__FILE__)) . "/"; $config["path_libraries"] = $config["path_base"] . "thirdparty/"; $config["path_resources"] = $config["path_base"] . "resources/"; $config["path_providers"] = $config["path_base"] . "Providers/"; // reset debug mode if (!isset($config["debug_mode"])) { $config["debug_mode"] = false; $config["debug_file"] = null; } # load hybridauth required files, a autoload is on the way... require_once $config["path_base"] . "Error.php"; require_once $config["path_base"] . "Logger.php"; require_once $config["path_base"] . "Storage.php"; require_once $config["path_base"] . "Provider_Adapter.php"; require_once $config["path_base"] . "Provider_Model.php"; require_once $config["path_base"] . "Provider_Model_OpenID.php"; require_once $config["path_base"] . "Provider_Model_OAuth1.php"; require_once $config["path_base"] . "Provider_Model_OAuth2.php"; require_once $config["path_base"] . "User.php"; require_once $config["path_base"] . "User_Profile.php"; require_once $config["path_base"] . "User_Contact.php"; require_once $config["path_base"] . "User_Activity.php"; // hash given config Hybrid_Auth::$config = $config; // start session storage mng Hybrid_Auth::$store = new Hybrid_Storage(); // instace of errors mng Hybrid_Auth::$error = new Hybrid_Error(); // instace of log mng Hybrid_Auth::$logger = new Hybrid_Logger(); // store php session and version.. $_SESSION["HA::PHP_SESSION_ID"] = session_id(); $_SESSION["HA::VERSION"] = Hybrid_Auth::$version; // almost done, check for errors then move on Hybrid_Logger::info("Enter Hybrid_Auth::initialize()"); Hybrid_Logger::info("Hybrid_Auth::initialize(). Hybrid_Auth used version: " . Hybrid_Auth::$version); Hybrid_Logger::info("Hybrid_Auth::initialize(). Hybrid_Auth called from: " . Hybrid_Auth::getCurrentUrl()); Hybrid_Logger::debug("Hybrid_Auth initialize. dump used config: ", serialize($config)); Hybrid_Logger::debug("Hybrid_Auth initialize. dump current session: ", serialize($_SESSION)); Hybrid_Logger::info("Hybrid_Auth initialize: check if any error is stored on the endpoint..."); if (Hybrid_Error::hasError()) { $m = Hybrid_Error::getErrorMessage(); $c = Hybrid_Error::getErrorCode(); $p = Hybrid_Error::getErrorPrevious(); Hybrid_Logger::error("Hybrid_Auth initialize: A stored Error found, Throw an new Exception and delete it from the store: Error#{$c}, '{$m}'"); Hybrid_Error::clearError(); if (!$p instanceof Exception) { $p = null; } //TODO: Is this check realy needed? throw new Exception($m, $c, $p); } Hybrid_Logger::info("Hybrid_Auth initialize: no error found. initialization succeed."); // Endof initialize }
/** * define:endpoint step 3.1 and 3.2 */ public static function processAuthDone() { Hybrid_Endpoint::authInit(); $provider_id = trim(strip_tags(Hybrid_Endpoint::$request["hauth_done"])); $hauth = Hybrid_Auth::setup($provider_id); if (!$hauth) { Hybrid_Logger::error("Endpoint: Invalide parameter on hauth_done!"); $hauth->adapter->setUserUnconnected(); header("HTTP/1.0 404 Not Found"); die("Invalide parameter! Please return to the login page and try again."); } try { Hybrid_Logger::info("Endpoint: call adapter [{$provider_id}] loginFinish() "); $hauth->adapter->loginFinish(); } catch (Exception $e) { Hybrid_Logger::error("Exception:" . $e->getMessage(), $e); Hybrid_Error::setError($e->getMessage(), $e->getCode(), $e->getTraceAsString(), $e); $hauth->adapter->setUserUnconnected(); } Hybrid_Logger::info("Endpoint: job done. retrun to callback url."); $hauth->returnToCallbackUrl(); die; }
/** * define:endpoint step 3.1 and 3.2 */ public static function processAuthDone() { Hybrid_Endpoint::authInit(); $provider_id = trim(strip_tags(Hybrid_Endpoint::$request["hauth_done"])); # check if page accessed directly if (!Hybrid_Auth::storage()->get("hauth_session.{$provider_id}.hauth_endpoint")) { throw new Hybrid_Exception("You cannot access this page directly."); } $hauth = Hybrid_Auth::setup($provider_id); if (!$hauth) { $hauth->adapter->setUserUnconnected(); throw new Hybrid_Exception("Invalid parameter! Please return to the login page and try again."); } try { $hauth->adapter->loginFinish(); } catch (Exception $e) { Hybrid_Error::setError($e->getMessage(), $e->getCode()); $hauth->adapter->setUserUnconnected(); } $hauth->returnToCallbackUrl(); die; }
/** * Return the latest api error */ public static function getLatestApiError() { return Hybrid_Error::getErrorMessage(); }
function request($url, $params = false, $type = "GET") { if ($type == "GET") { $url = $url . (strpos($url, '?') ? '&' : '?') . http_build_query($params, '', '&'); } $this->http_info = array(); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, $this->curl_time_out); curl_setopt($ch, CURLOPT_USERAGENT, $this->curl_useragent); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->curl_connect_time_out); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->curl_ssl_verifypeer); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $this->curl_ssl_verifyhost); curl_setopt($ch, CURLOPT_HTTPHEADER, $this->curl_header); if ($this->curl_proxy) { curl_setopt($ch, CURLOPT_PROXY, $this->curl_proxy); } if ($type == "POST") { curl_setopt($ch, CURLOPT_POST, 1); if ($params) { curl_setopt($ch, CURLOPT_POSTFIELDS, $params); } } $response = curl_exec($ch); $this->http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $this->http_info = array_merge($this->http_info, curl_getinfo($ch)); curl_close($ch); //- Hybrid_Error::deleteApiError(); if ($this->http_code != 200) { Hybrid_Error::setApiError($this->http_code . '. ' . preg_replace('/\\s+/', ' ', $response)); } if (defined('WORDPRESS_SOCIAL_LOGIN_DEBUG_API_CALLS')) { do_action('wsl_log_provider_api_call', 'OAuth2', $url, $type, $params, $this->http_code, $this->http_info, $response); } //- return $response; }
protected function request_curl($url, $method = 'GET', $params = array(), $update_claimed_id) { $params = http_build_query($params, '', '&'); $curl = curl_init($url . ($method == 'GET' && $params ? '?' . $params : '')); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/xrds+xml, */*')); if (!empty($this->proxy)) { curl_setopt($curl, CURLOPT_PROXY, $this->proxy['host']); if (!empty($this->proxy['port'])) { curl_setopt($curl, CURLOPT_PROXYPORT, $this->proxy['port']); } if (!empty($this->proxy['user'])) { curl_setopt($curl, CURLOPT_PROXYUSERPWD, $this->proxy['user'] . ':' . $this->proxy['pass']); } } if ($this->verify_peer !== null) { curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verify_peer); if ($this->capath) { curl_setopt($curl, CURLOPT_CAPATH, $this->capath); } if ($this->cainfo) { curl_setopt($curl, CURLOPT_CAINFO, $this->cainfo); } } if ($method == 'POST') { curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $params); } elseif ($method == 'HEAD') { curl_setopt($curl, CURLOPT_HEADER, true); curl_setopt($curl, CURLOPT_NOBODY, true); } else { curl_setopt($curl, CURLOPT_HEADER, true); curl_setopt($curl, CURLOPT_HTTPGET, true); } $response = curl_exec($curl); if ($method == 'HEAD' && curl_getinfo($curl, CURLINFO_HTTP_CODE) == 405) { curl_setopt($curl, CURLOPT_HTTPGET, true); $response = curl_exec($curl); $response = substr($response, 0, strpos($response, "\r\n\r\n")); } //- $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE); Hybrid_Error::deleteApiError(); if ($http_code != 200) { Hybrid_Error::setApiError($http_code . '. ' . preg_replace('/\\s+/', ' ', $response)); } if (defined('WORDPRESS_SOCIAL_LOGIN_DEBUG_API_CALLS')) { do_action('wsl_log_provider_api_call', 'OpenID', $url . ($method == 'GET' && $params ? '?' . $params : ''), $method, $params, curl_getinfo($curl), curl_getinfo($curl), $response); } //- if ($method == 'HEAD' || $method == 'GET') { $header_response = $response; # If it's a GET request, we want to only parse the header part. if ($method == 'GET') { $header_response = substr($response, 0, strpos($response, "\r\n\r\n")); } $headers = array(); foreach (explode("\n", $header_response) as $header) { $pos = strpos($header, ':'); if ($pos !== false) { $name = strtolower(trim(substr($header, 0, $pos))); $headers[$name] = trim(substr($header, $pos + 1)); } } if ($update_claimed_id) { # Updating claimed_id in case of redirections. $effective_url = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL); if ($effective_url != $url) { $this->identity = $this->claimed_id = $effective_url; } } if ($method == 'HEAD') { return $headers; } else { $this->headers = $headers; } } if (curl_errno($curl)) { throw new ErrorException(curl_error($curl), curl_errno($curl)); } return $response; }
/** * define:endpoint step 3.1 and 3.2 */ protected function processAuthDone() { $provider_id = trim($this->getProperty('hauth_done')); $hauth = Hybrid_Auth::setup($provider_id); if (!$hauth) { Hybrid_Logger::error("Endpoint: Invalid parameter on hauth_done!"); $hauth->adapter->setUserUnconnected(); header("HTTP/1.0 404 Not Found"); return "Invalid parameter! Please return to the login page and try again."; } try { Hybrid_Logger::info("Endpoint: call adapter [{$provider_id}] loginFinish() "); $hauth->adapter->loginFinish(); } catch (Exception $e) { Hybrid_Logger::error("Exception:" . $e->getMessage(), $e); Hybrid_Error::setError($e->getMessage(), $e->getCode(), $e->getTraceAsString(), $e); $hauth->adapter->setUserUnconnected(); } Hybrid_Logger::info("Endpoint: job done. retrun to callback url."); // Save profile data in session $profile = $hauth->adapter->getUserProfile(); // else $_SESSION['social_profile'] = array('provider' => $provider_id, 'profile' => $this->modx->error->toArray($profile)); //$q->prepare(); //$this->modx->log(1, $q->toSQL()); // else $hauth->returnToCallbackUrl(); return ''; }
/** * Display an error message in case user authentication fails */ function wsl_process_login_render_error_page($e, $config = null, $provider = null, $adapter = null) { // HOOKABLE: do_action("wsl_process_login_render_error_page", $e, $config, $provider, $adapter); $assets_base_url = WORDPRESS_SOCIAL_LOGIN_PLUGIN_URL . 'assets/img/'; $message = _wsl__("Unspecified error!", 'wordpress-social-login'); $notes = ""; $apierror = substr($e->getMessage(), 0, 145); switch ($e->getCode()) { case 0: $message = _wsl__("Unspecified error.", 'wordpress-social-login'); break; case 1: $message = _wsl__("WordPress Social Login is not properly configured.", 'wordpress-social-login'); break; case 2: $message = sprintf(__wsl__("WordPress Social Login is not properly configured.<br /> <b>%s</b> need to be properly configured.", 'wordpress-social-login'), $provider); break; case 3: $message = _wsl__("Unknown or disabled provider.", 'wordpress-social-login'); break; case 4: $message = sprintf(_wsl__("WordPress Social Login is not properly configured.<br /> <b>%s</b> requires your application credentials.", 'wordpress-social-login'), $provider); $notes = sprintf(_wsl__("<b>What does this error mean ?</b><br />Most likely, you didn't setup the correct application credentials for this provider. These credentials are required in order for <b>%s</b> users to access your website and for WordPress Social Login to work.", 'wordpress-social-login'), $provider) . _wsl__('<br />Instructions for use can be found in the <a href="http://miled.github.io/wordpress-social-login/networks.html" target="_blank">User Manual</a>.', 'wordpress-social-login'); break; case 5: $message = sprintf(_wsl__("Authentication failed. Either you have cancelled the authentication or <b>%s</b> refused the connection.", 'wordpress-social-login'), $provider); break; case 6: $message = sprintf(_wsl__("Request failed. Either you have cancelled the authentication or <b>%s</b> refused the connection.", 'wordpress-social-login'), $provider); break; case 7: $message = _wsl__("You're not connected to the provider.", 'wordpress-social-login'); break; case 8: $message = _wsl__("Provider does not support this feature.", 'wordpress-social-login'); break; } if (is_object($adapter)) { $adapter->logout(); } // provider api response if (class_exists('Hybrid_Error', false) && Hybrid_Error::getApiError()) { $tmp = Hybrid_Error::getApiError(); $apierror = $apierror . "\n" . '<br />' . $tmp; // network issue if (trim($tmp) == '0.') { $apierror = "Could not establish connection to provider API"; } } return wsl_render_error_page($message, $notes, $provider, $apierror, $e); }
/** * define:endpoint step 3.1 and 3.2 */ protected function processAuthDone() { $provider_id = trim($this->getProperty('hauth_done')); $hauth = Hybrid_Auth::setup($provider_id); if (!$hauth) { Hybrid_Logger::error("Endpoint: Invalid parameter on hauth_done!"); $hauth->adapter->setUserUnconnected(); header("HTTP/1.0 404 Not Found"); return "Invalid parameter! Please return to the login page and try again."; } try { Hybrid_Logger::info("Endpoint: call adapter [{$provider_id}] loginFinish() "); $hauth->adapter->loginFinish(); } catch (Exception $e) { Hybrid_Logger::error("Exception:" . $e->getMessage(), $e); Hybrid_Error::setError($e->getMessage(), $e->getCode(), $e->getTraceAsString(), $e); $hauth->adapter->setUserUnconnected(); } Hybrid_Logger::info("Endpoint: job done. retrun to callback url."); // Save profile data in session $profile = $hauth->adapter->getUserProfile(); // Try to get user by social profile /*$q = $this->modx->newQuery('modUser'); $q->innerJoin('modUserProfile', 'Profile'); $q->innerJoin('modHybridAuthUserProfile', 'SocialProfile'); $q->innerJoin('modHybridAuthProvider', 'Provider', "Provider.id=SocialProfile.provider"); $q->where(array( "SocialProfile.identifier" => $profile->identifier, "Provider.name" => $provider, "modUser.active" => 1, "Profile.blocked" => 0, )); $q->limit(1); if($user = $this->modx->getObject('modUser', $q)){ $user->addSessionContext($this->modx->context->key); $redirectTo = $this->modx->getOption('site_url'); $this->modx->sendRedirect($redirectTo); return; }*/ // else $_SESSION['social_profile'] = array('provider' => $provider_id, 'profile' => $this->modx->error->toArray($profile)); //$q->prepare(); //$this->modx->log(1, $q->toSQL()); // else $hauth->returnToCallbackUrl(); return ''; }
// with /index.php?hauth.done={provider}?{args}... if (strrpos($_SERVER["QUERY_STRING"], '?')) { $_SERVER["QUERY_STRING"] = str_replace("?", "&", $_SERVER["QUERY_STRING"]); parse_str($_SERVER["QUERY_STRING"], $_REQUEST); } $provider_id = trim(strip_tags($_REQUEST["hauth_done"])); $hauth = Hybrid_Auth::setup($provider_id); if (!$hauth) { Hybrid_Logger::error("Endpoint: Invalide parameter on hauth_done!"); $hauth->adapter->setUserUnconnected(); header("HTTP/1.0 404 Not Found"); die("Invalide parameter! Please return to the login page and try again."); } try { Hybrid_Logger::info("Endpoint: call adapter [{$provider_id}] loginFinish() "); $hauth->adapter->loginFinish(); } catch (Exception $e) { Hybrid_Logger::error("Exception:" . $e->getMessage(), $e); Hybrid_Error::setError($e->getMessage(), $e->getCode(), $e->getTraceAsString(), $e); $hauth->adapter->setUserUnconnected(); } Hybrid_Logger::info("Endpoint: job done. retrun to callback url."); $hauth->returnToCallbackUrl(); die; } } else { # Else, # We advertise our XRDS document, something supposed to be done from the Realm URL page echo str_replace("{X_XRDS_LOCATION}", Hybrid_Auth::getCurrentUrl(false) . "?get=openid_xrds&v=" . Hybrid_Auth::$version, file_get_contents(dirname(__FILE__) . "/Hybrid/resources/openid_realm.html")); die; }
/** * Define: endpoint step 3.1 and 3.2 * @return void * @throws Hybrid_Exception */ protected function processAuthDone() { $this->authInit(); $provider_id = trim(strip_tags($this->request["hauth_done"])); $hauth = Hybrid_Auth::setup($provider_id); if (!$hauth) { Hybrid_Logger::error("Endpoint: Invalid parameter on hauth_done!"); $hauth->adapter->setUserUnconnected(); throw new Hybrid_Exception("Invalid parameter! Please return to the login page and try again."); } try { Hybrid_Logger::info("Endpoint: call adapter [{$provider_id}] loginFinish() "); $hauth->adapter->loginFinish(); } catch (Exception $e) { Hybrid_Logger::error("Exception:" . $e->getMessage(), $e); Hybrid_Error::setError($e->getMessage(), $e->getCode(), $e->getTraceAsString(), $e->getPrevious()); $hauth->adapter->setUserUnconnected(); } Hybrid_Logger::info("Endpoint: job done. return to callback url."); $hauth->returnToCallbackUrl(); die; }
/** * Try to initialize Hybrid_Auth with given $config hash or file */ public static function initialize($config) { if (!is_array($config) && !file_exists($config)) { throw new Exception("Hybriauth config does not exist on the given path.", 1); } if (!is_array($config)) { $config = (include $config); } // build some need'd paths $config["path_base"] = realpath(dirname(__FILE__)) . "/"; $config["path_libraries"] = $config["path_base"] . "thirdparty/"; $config["path_resources"] = $config["path_base"] . "resources/"; $config["path_providers"] = $config["path_base"] . "Providers/"; // reset debug mode if (!isset($config["debug_mode"])) { $config["debug_mode"] = false; $config["debug_file"] = null; } # load hybridauth required files, a autoload is on the way... require_once $config["path_base"] . "Error.php"; require_once $config["path_base"] . "Logger.php"; require_once $config["path_base"] . "Storage.php"; require_once $config["path_base"] . "Provider_Adapter.php"; require_once $config["path_base"] . "Provider_Model.php"; require_once $config["path_base"] . "Provider_Model_OpenID.php"; require_once $config["path_base"] . "Provider_Model_OAuth1.php"; require_once $config["path_base"] . "Provider_Model_OAuth2.php"; require_once $config["path_base"] . "User.php"; require_once $config["path_base"] . "User_Profile.php"; require_once $config["path_base"] . "User_Contact.php"; require_once $config["path_base"] . "User_Activity.php"; // hash given config Hybrid_Auth::$config = $config; // instace of log mng Hybrid_Auth::$logger = new Hybrid_Logger(); // instace of errors mng Hybrid_Auth::$error = new Hybrid_Error(); // start session storage mng Hybrid_Auth::$store = new Hybrid_Storage(); Hybrid_Logger::info("Enter Hybrid_Auth::initialize()"); Hybrid_Logger::info("Hybrid_Auth::initialize(). PHP version: " . PHP_VERSION); Hybrid_Logger::info("Hybrid_Auth::initialize(). Hybrid_Auth version: " . Hybrid_Auth::$version); Hybrid_Logger::info("Hybrid_Auth::initialize(). Hybrid_Auth called from: " . Hybrid_Auth::getCurrentUrl()); // PHP Curl extension [http://www.php.net/manual/en/intro.curl.php] if (!function_exists('curl_init')) { Hybrid_Logger::error('Hybridauth Library needs the CURL PHP extension.'); throw new Exception('Hybridauth Library needs the CURL PHP extension.'); } // PHP JSON extension [http://php.net/manual/en/book.json.php] if (!function_exists('json_decode')) { Hybrid_Logger::error('Hybridauth Library needs the JSON PHP extension.'); throw new Exception('Hybridauth Library needs the JSON PHP extension.'); } // session.name if (session_name() != "PHPSESSID") { Hybrid_Logger::info('PHP session.name diff from default PHPSESSID. http://php.net/manual/en/session.configuration.php#ini.session.name.'); } // safe_mode is on if (ini_get('safe_mode')) { Hybrid_Logger::info('PHP safe_mode is on. http://php.net/safe-mode.'); } // open basedir is on if (ini_get('open_basedir')) { Hybrid_Logger::info('PHP open_basedir is on. http://php.net/open-basedir.'); } Hybrid_Logger::debug("Hybrid_Auth initialize. dump used config: ", serialize($config)); Hybrid_Logger::debug("Hybrid_Auth initialize. dump current session: ", Hybrid_Auth::storage()->getSessionData()); Hybrid_Logger::info("Hybrid_Auth initialize: check if any error is stored on the endpoint..."); if (Hybrid_Error::hasError()) { $m = Hybrid_Error::getErrorMessage(); $c = Hybrid_Error::getErrorCode(); $p = Hybrid_Error::getErrorPrevious(); Hybrid_Logger::error("Hybrid_Auth initialize: A stored Error found, Throw an new Exception and delete it from the store: Error#{$c}, '{$m}'"); Hybrid_Error::clearError(); // try to provide the previous if any // Exception::getPrevious (PHP 5 >= 5.3.0) http://php.net/manual/en/exception.getprevious.php if (version_compare(PHP_VERSION, '5.3.0', '>=') && $p instanceof Exception) { throw new Exception($m, $c, $p); } else { throw new Exception($m, $c); } } Hybrid_Logger::info("Hybrid_Auth initialize: no error found. initialization succeed."); // Endof initialize }
/** * Аутентификация HybridAuth * @param string $provider * @return bool */ protected function hybridauth_authenticate($provider) { global $hybridauth; try { $params = array(); if ($provider == 'OpenID') { $openid_identifier = get('openid_identifier', '', 'g'); if ($openid_identifier) { $params['openid_identifier'] = $openid_identifier; } } $adapter = $hybridauth->authenticate($provider, $params); $user_profile = $adapter->getUserProfile(); if (!$user_profile) { Hybrid_Error::setError("Error getUserProfile, provider=" . $provider . ". Line=" . __LINE__); $this->setError("error_get_profile"); return false; } if ($this->_user) { // Есть текущий залогиненный пользователь, надо привязать к нему // Если не привязано уже к другому пользователю $link_user_id = (int) sql_getValue("SELECT user_id FROM {$this->_table_socials} WHERE provider='{$provider}' AND identifier='{$user_profile->identifier}'"); if ($link_user_id && $link_user_id != $this->_user->getId()) { $adapter->logout(); Hybrid_Error::setError("Provider={$provider}, identifier={$user_profile->identifier}: already linked to another user={$link_user_id}" . ". Line=" . __LINE__); $this->setError("link_provider_error"); return false; } $name = ''; if ($user_profile->firstName) { $name = $user_profile->firstName; if ($user_profile->lastName) { $name .= ' ' . $user_profile->lastName; } } else { if ($user_profile->displayName) { $name = $user_profile->displayName; } } if (!$name) { $name = $user_profile->identifier; } if ($name) { $win1251 = iconv('utf-8', 'windows-1251', $name); if ($win1251) { $name = $win1251; } } $this->_user->createSocialLink(array('provider' => $provider, 'identifier' => $user_profile->identifier, 'profileURL' => $user_profile->profileURL, 'photoURL' => $user_profile->photoURL, 'name' => $name)); } else { // Никто не залогинен $user_id = sql_getValue("SELECT user_id FROM {$this->_table_socials} WHERE provider='{$provider}' AND identifier='{$user_profile->identifier}'"); if (!$user_id) { $user_id = $this->createUserByProvider($provider, $user_profile); if ($user_id === false) { Hybrid_Error::setError("Error create user in table {$this->_table}" . ". Line=" . __LINE__); return false; } } // авторизовать на сайте $this->login($user_id); } return true; } catch (Exception $e) { Hybrid_Error::setError($e->getMessage() . ". Line=" . __LINE__); $this->setError($e->getMessage()); return false; } }