/**
  * Build signature
  *
  * @param String $baseString - base string
  * @param OAuthConsumer $consumer - consumer
  * @param OAuthToken $token - token
  * @return String
  */
 public function build($baseString, $consumer, $token)
 {
     $keyParts = array($consumer->getSecret(), $token ? $token->getSecret() : '');
     $keyParts = OAuthUtils::urlEncodeRfc3986($keyParts);
     $key = implode('&', $keyParts);
     return base64_encode(hash_hmac('sha1', $baseString, $key, true));
 }
Example #2
0
 public static function create($name, $app_url)
 {
     $app = new OAuthConsumer();
     $app->set('name', $name);
     $app->set('app_url', $app_url);
     $app->set('user_id', User::$me->id);
     $app->set('consumer_key', MyOAuthProvider::generateToken());
     $app->set('consumer_secret', MyOAuthProvider::generateToken());
     $app->set('active', 1);
     $app->save();
     return $app;
 }
Example #3
0
 /**
  * This function checks if the consumer exist in the DB and that it is active
  * You can modify it at your will but you __HAVE TO__ set $provider->consumer_secret to the right value or the signature will fail
  * It's called by OAuthCheckRequest()
  * @param $provider mixed
  * @return int
  */
 public function checkConsumer($provider)
 {
     $c = OAuthConsumer::findByKey($provider->consumer_key);
     if ($c->isHydrated()) {
         if (!$c->isActive()) {
             return OAUTH_CONSUMER_KEY_REFUSED;
         } else {
             $this->consumer = $c;
             $provider->consumer_secret = $this->consumer->get('consumer_secret');
             return OAUTH_OK;
         }
     }
     return OAUTH_CONSUMER_KEY_UNKNOWN;
 }
Example #4
0
     // begin OAuth authentication method(s)
 } elseif ($_CONF['user_login_method']['oauth'] && isset($_GET['oauth_login'])) {
     $modules = SEC_collectRemoteOAuthModules();
     $active_service = count($modules) == 0 ? false : in_array($_GET['oauth_login'], $modules);
     if (!$active_service) {
         $status = -1;
         COM_errorLog("OAuth login failed - there was no consumer available for the service:" . $_GET['oauth_login']);
     } else {
         $query = array_merge($_GET, $_POST);
         $service = $query['oauth_login'];
         COM_clearSpeedlimit($_CONF['login_speedlimit'], $service);
         if (COM_checkSpeedlimit($service, $_CONF['login_attempts']) > 0) {
             displayLoginErrorAndAbort(82, $LANG12[26], $LANG04[112]);
         }
         require_once $_CONF['path_system'] . 'classes/oauthhelper.class.php';
         $consumer = new OAuthConsumer($service);
         $callback_url = $_CONF['site_url'] . '/users.php?oauth_login='******'login');
             COM_errorLog("OAuth Error: " . $consumer->error);
             echo COM_refresh($_CONF['site_url'] . '/users.php?msg=111');
             // OAuth authentication error
         }
         $consumer->doAction($oauth_userinfo);
     }
     //  end OAuth authentication method(s)
 } else {
     $status = -2;
 }
 public function build_signature(&$request, OAuthConsumer $consumer, $token)
 {
     $base_string = $request->get_signature_base_string();
     // Fetch the private key cert based on the request
     $cert = $consumer->getProperty(OAuthSignatureMethod_RSA_SHA1::$PRIVATE_KEY);
     // Pull the private key ID from the certificate
     //FIXME this function seems to be called both for a oauth.json action where
     // there is no phrase required, but for signed requests too, which do require it
     // this is a dirty hack to make it work .. kinda
     if (!($privatekeyid = @openssl_pkey_get_private($cert))) {
         if (!($privatekeyid = @openssl_pkey_get_private($cert, Config::get('private_key_phrase') != '' ? Config::get('private_key_phrase') : null))) {
             throw new Exception("Could not load private key");
         }
     }
     // Sign using the key
     $signature = '';
     if (($ok = openssl_sign($base_string, $signature, $privatekeyid)) === false) {
         throw new OAuthException("Could not create signature");
     }
     // Release the key resource
     @openssl_free_key($privatekeyid);
     return base64_encode($signature);
 }
Example #6
0
 /**
  * Constructor.
  *
  * @param 	object 	An optional KConfig object with configuration options
  */
 public function __construct(KConfig $config)
 {
     parent::__construct($config->key, $config->secret, $config->callback_url);
 }
Example #7
0
/**
* Saves the user's information back to the database
*
* @param    array   $A  User's data
* @return   string      HTML error message or meta redirect
*
*/
function saveuser($A)
{
    global $_CONF, $_TABLES, $_USER, $LANG04, $LANG24, $_US_VERBOSE;
    if ($_US_VERBOSE) {
        COM_errorLog('**** Inside saveuser in usersettings.php ****', 1);
    }
    $reqid = DB_getItem($_TABLES['users'], 'pwrequestid', "uid = {$_USER['uid']}");
    if ($reqid != $A['uid']) {
        DB_change($_TABLES['users'], 'pwrequestid', "NULL", 'uid', $_USER['uid']);
        COM_accessLog("An attempt was made to illegally change the account information of user {$_USER['uid']}.");
        return COM_refresh($_CONF['site_url'] . '/index.php');
    }
    if (!isset($A['cooktime'])) {
        // If not set or possibly removed from template - set to default
        $A['cooktime'] = $_CONF['default_perm_cookie_timeout'];
    } else {
        $A['cooktime'] = COM_applyFilter($A['cooktime'], true);
    }
    // If empty or invalid - set to user default
    // So code after this does not fail the user password required test
    if ($A['cooktime'] < 0) {
        // note that == 0 is allowed!
        $A['cooktime'] = $_USER['cookietimeout'];
    }
    // to change the password, email address, or cookie timeout,
    // we need the user's current password
    $service = DB_getItem($_TABLES['users'], 'remoteservice', "uid = {$_USER['uid']}");
    if ($service == '') {
        if (!empty($A['passwd']) || $A['email'] != $_USER['email'] || $A['cooktime'] != $_USER['cookietimeout']) {
            // verify password
            if (empty($A['old_passwd']) || SEC_encryptUserPassword($A['old_passwd'], $_USER['uid']) < 0) {
                return COM_refresh($_CONF['site_url'] . '/usersettings.php?msg=83');
            } elseif ($_CONF['custom_registration'] && function_exists('CUSTOM_userCheck')) {
                $ret = CUSTOM_userCheck($A['username'], $A['email']);
                if (!empty($ret)) {
                    // Need a numeric return for the default message handler
                    // - if not numeric use default message
                    if (!is_numeric($ret['number'])) {
                        $ret['number'] = 400;
                    }
                    return COM_refresh("{$_CONF['site_url']}/usersettings.php?msg={$ret['number']}");
                }
            }
        } elseif ($_CONF['custom_registration'] && function_exists('CUSTOM_userCheck')) {
            $ret = CUSTOM_userCheck($A['username'], $A['email']);
            if (!empty($ret)) {
                // Need a numeric return for the default message handler
                // - if not numeric use default message
                if (!is_numeric($ret['number'])) {
                    $ret['number'] = 400;
                }
                return COM_refresh("{$_CONF['site_url']}/usersettings.php?msg={$ret['number']}");
            }
        }
    } else {
        if ($A['email'] != $_USER['email'] || $A['cooktime'] != $_USER['cookietimeout']) {
            // re athenticate remote user again for these changes to take place
            // Can't just be done here since user may have to relogin to his service which then sends us back here and we lose his changes
        }
    }
    // no need to filter the password as it's encoded anyway
    if ($_CONF['allow_username_change'] == 1) {
        $A['new_username'] = COM_applyFilter($A['new_username']);
        if (!empty($A['new_username']) && $A['new_username'] != $_USER['username']) {
            $A['new_username'] = DB_escapeString($A['new_username']);
            if (DB_count($_TABLES['users'], 'username', $A['new_username']) == 0) {
                if ($_CONF['allow_user_photo'] == 1) {
                    $photo = DB_getItem($_TABLES['users'], 'photo', "uid = {$_USER['uid']}");
                    if (!empty($photo)) {
                        $newphoto = preg_replace('/' . $_USER['username'] . '/', $A['new_username'], $photo, 1);
                        $imgpath = $_CONF['path_images'] . 'userphotos/';
                        if (rename($imgpath . $photo, $imgpath . $newphoto) === false) {
                            $display = COM_errorLog('Could not rename userphoto "' . $photo . '" to "' . $newphoto . '".');
                            $display = COM_createHTMLDocument($display, array('pagetitle' => $LANG04[21]));
                            return $display;
                        }
                        DB_change($_TABLES['users'], 'photo', DB_escapeString($newphoto), "uid", $_USER['uid']);
                    }
                }
                DB_change($_TABLES['users'], 'username', $A['new_username'], "uid", $_USER['uid']);
            } else {
                return COM_refresh($_CONF['site_url'] . '/usersettings.php?msg=51');
            }
        }
    }
    // a quick spam check with the unfiltered field contents
    $profile = '<h1>' . $LANG04[1] . ' ' . $_USER['username'] . '</h1><p>';
    // this is a hack, for some reason remoteservice links made SPAMX SLV check barf
    if (empty($service)) {
        $profile .= COM_createLink($A['homepage'], $A['homepage']) . '<br' . XHTML . '>';
    }
    $profile .= $A['location'] . '<br' . XHTML . '>' . $A['sig'] . '<br' . XHTML . '>' . $A['about'] . '<br' . XHTML . '>' . $A['pgpkey'] . '</p>';
    $result = PLG_checkforSpam($profile, $_CONF['spamx']);
    if ($result > 0) {
        COM_displayMessageAndAbort($result, 'spamx', 403, 'Forbidden');
    }
    $A['email'] = COM_applyFilter($A['email']);
    $A['email_conf'] = COM_applyFilter($A['email_conf']);
    $A['homepage'] = COM_applyFilter($A['homepage']);
    // basic filtering only
    $A['fullname'] = strip_tags(COM_stripslashes($A['fullname']));
    $A['location'] = strip_tags(COM_stripslashes($A['location']));
    $A['sig'] = strip_tags(COM_stripslashes($A['sig']));
    $A['about'] = strip_tags(COM_stripslashes($A['about']));
    $A['pgpkey'] = strip_tags(COM_stripslashes($A['pgpkey']));
    if (!COM_isEmail($A['email'])) {
        return COM_refresh($_CONF['site_url'] . '/usersettings.php?msg=52');
    } else {
        if ($A['email'] !== $A['email_conf']) {
            return COM_refresh($_CONF['site_url'] . '/usersettings.php?msg=78');
        } else {
            if (emailAddressExists($A['email'], $_USER['uid'])) {
                return COM_refresh($_CONF['site_url'] . '/usersettings.php?msg=56');
            } else {
                $passwd = '';
                if ($service == '') {
                    if (!empty($A['passwd'])) {
                        if ($A['passwd'] == $A['passwd_conf'] && SEC_encryptUserPassword($A['old_passwd'], $_USER['uid']) == 0) {
                            SEC_updateUserPassword($A['passwd'], $_USER['uid']);
                            if ($A['cooktime'] > 0) {
                                $cooktime = $A['cooktime'];
                            } else {
                                $cooktime = -1000;
                            }
                            SEC_setCookie($_CONF['cookie_password'], $passwd, time() + $cooktime);
                        } elseif (SEC_encryptUserPassword($A['old_passwd'], $_USER['uid']) < 0) {
                            return COM_refresh($_CONF['site_url'] . '/usersettings.php?msg=68');
                        } elseif ($A['passwd'] != $A['passwd_conf']) {
                            return COM_refresh($_CONF['site_url'] . '/usersettings.php?msg=67');
                        }
                    }
                } else {
                    // Cookie
                    if ($A['cooktime'] > 0) {
                        $cooktime = $A['cooktime'];
                    } else {
                        $cooktime = -1000;
                    }
                    SEC_setCookie($_CONF['cookie_password'], $passwd, time() + $cooktime);
                }
                if ($_US_VERBOSE) {
                    COM_errorLog('cooktime = ' . $A['cooktime'], 1);
                }
                if ($A['cooktime'] <= 0) {
                    $cooktime = 1000;
                    SEC_setCookie($_CONF['cookie_name'], $_USER['uid'], time() - $cooktime);
                } else {
                    SEC_setCookie($_CONF['cookie_name'], $_USER['uid'], time() + $A['cooktime']);
                }
                if ($_CONF['allow_user_photo'] == 1) {
                    $delete_photo = '';
                    if (isset($A['delete_photo'])) {
                        $delete_photo = $A['delete_photo'];
                    }
                    $filename = handlePhotoUpload($delete_photo);
                }
                if (!empty($A['homepage'])) {
                    $pos = MBYTE_strpos($A['homepage'], ':');
                    if ($pos === false) {
                        $A['homepage'] = 'http://' . $A['homepage'];
                    } else {
                        $prot = substr($A['homepage'], 0, $pos + 1);
                        if ($prot != 'http:' && $prot != 'https:') {
                            $A['homepage'] = 'http:' . substr($A['homepage'], $pos + 1);
                        }
                    }
                    $A['homepage'] = DB_escapeString($A['homepage']);
                }
                $A['fullname'] = DB_escapeString($A['fullname']);
                $A['email'] = DB_escapeString($A['email']);
                $A['location'] = DB_escapeString($A['location']);
                $A['sig'] = DB_escapeString($A['sig']);
                $A['about'] = DB_escapeString($A['about']);
                $A['pgpkey'] = DB_escapeString($A['pgpkey']);
                if (!empty($filename)) {
                    if (!file_exists($_CONF['path_images'] . 'userphotos/' . $filename)) {
                        $filename = '';
                    }
                }
                DB_query("UPDATE {$_TABLES['users']} SET fullname='{$A['fullname']}',email='{$A['email']}',homepage='{$A['homepage']}',sig='{$A['sig']}',cookietimeout={$A['cooktime']},photo='{$filename}' WHERE uid={$_USER['uid']}");
                DB_query("UPDATE {$_TABLES['userinfo']} SET pgpkey='{$A['pgpkey']}',about='{$A['about']}',location='{$A['location']}' WHERE uid={$_USER['uid']}");
                // Call custom registration save function if enabled and exists
                if ($_CONF['custom_registration'] and function_exists('CUSTOM_userSave')) {
                    CUSTOM_userSave($_USER['uid']);
                }
                PLG_userInfoChanged($_USER['uid']);
                // at this point, the user information has been saved, but now we're going to check to see if
                // the user has requested resynchronization with their remoteservice account
                $msg = 5;
                // default msg = Your account information has been successfully saved
                if (isset($A['resynch'])) {
                    if ($_CONF['user_login_method']['oauth'] && strpos($_USER['remoteservice'], 'oauth.') === 0) {
                        $modules = SEC_collectRemoteOAuthModules();
                        $active_service = count($modules) == 0 ? false : in_array(substr($_USER['remoteservice'], 6), $modules);
                        if (!$active_service) {
                            $status = -1;
                            $msg = 115;
                            // Remote service has been disabled.
                        } else {
                            require_once $_CONF['path_system'] . 'classes/oauthhelper.class.php';
                            $service = substr($_USER['remoteservice'], 6);
                            $consumer = new OAuthConsumer($service);
                            $callback_url = $_CONF['site_url'];
                            $consumer->setRedirectURL($callback_url);
                            $user = $consumer->authenticate_user();
                            $consumer->doSynch($user);
                        }
                    }
                    if ($msg != 5) {
                        $msg = 114;
                        // Account saved but re-synch failed.
                        COM_errorLog($MESSAGE[$msg]);
                    }
                }
                if ($_US_VERBOSE) {
                    COM_errorLog('**** Leaving saveuser in usersettings.php ****', 1);
                }
                return COM_refresh($_CONF['site_url'] . '/users.php?mode=profile&amp;uid=' . $_USER['uid'] . '&amp;msg=' . $msg);
            }
        }
    }
}
Example #8
0
 public function signRequest($url, $method)
 {
     try {
         // Parse the request into parameters for OAuth signing, stripping out
         // any OAuth or OpenSocial parameters injected by the client
         $parsedUri = parse_url($url);
         $resource = $url;
         $queryParams = $this->sanitize($_GET);
         $postParams = $this->sanitize($_POST);
         // The data that is supposed to be posted to the target page is contained in the postData field
         // in the $_POST to the Shindig proxy server
         // Here we parse it and put it into the $postDataParams array which then is merged into the postParams
         // to be used for the GET/POST request and the building of the signature
         $postDataParams = array();
         if (isset($_POST['postData']) && count($postDataParts = split('&', urldecode($_POST['postData']))) > 0) {
             foreach ($postDataParts as $postDataPart) {
                 $position = strpos($postDataPart, '=');
                 $key = substr($postDataPart, 0, $position);
                 $value = substr($postDataPart, $position + 1);
                 $postDataParams[$key] = $value;
             }
         }
         $postParams = array_merge($postParams, $this->sanitize($postDataParams));
         $msgParams = array();
         $msgParams = array_merge($msgParams, $queryParams);
         $msgParams = array_merge($msgParams, $postParams);
         $this->addOpenSocialParams($msgParams);
         $this->addOAuthParams($msgParams);
         $consumer = new OAuthConsumer(NULL, NULL, NULL);
         $consumer->setProperty(OAuthSignatureMethod_RSA_SHA1::$PRIVATE_KEY, $this->privateKeyObject);
         $signatureMethod = new OAuthSignatureMethod_RSA_SHA1();
         $req_req = OAuthRequest::from_consumer_and_token($consumer, NULL, $method, $resource, $msgParams);
         $req_req->sign_request($signatureMethod, $consumer, NULL);
         // Rebuild the query string, including all of the parameters we added.
         // We have to be careful not to copy POST parameters into the query.
         // If post and query parameters share a name, they end up being removed
         // from the query.
         $forPost = array();
         $postData = false;
         if ($method == 'POST') {
             foreach ($postParams as $key => $param) {
                 $forPost[$key] = $param;
                 if ($postData === false) {
                     $postData = array();
                 }
                 $postData[] = OAuthUtil::urlencodeRFC3986($key) . "=" . OAuthUtil::urlencodeRFC3986($param);
             }
             if ($postData !== false) {
                 $postData = implode("&", $postData);
             }
         }
         $newQuery = '';
         foreach ($req_req->get_parameters() as $key => $param) {
             if (!isset($forPost[$key])) {
                 $newQuery .= urlencode($key) . '=' . urlencode($param) . '&';
             }
         }
         // and stick on the original query params too
         if (isset($parsedUri['query']) && !empty($parsedUri['query'])) {
             $oldQuery = array();
             parse_str($parsedUri['query'], $oldQuery);
             foreach ($oldQuery as $key => $val) {
                 $newQuery .= urlencode($key) . '=' . urlencode($val) . '&';
             }
         }
         // Careful here; the OAuth form encoding scheme is slightly different than
         // the normal form encoding scheme, so we have to use the OAuth library
         // formEncode method.
         $url = $parsedUri['scheme'] . '://' . $parsedUri['host'] . (isset($parsedUri['port']) ? ':' . $parsedUri['port'] : '') . $parsedUri['path'] . '?' . $newQuery;
         // The headers are transmitted in the POST-data array in the field 'headers'
         // if no post should be made, the value should be false for this parameter
         $postHeaders = isset($_POST['headers']) && $method == 'POST' ? $_POST['headers'] : false;
         return new RemoteContentRequest($url, $postHeaders, $postData);
     } catch (Exception $e) {
         throw new GadgetException($e);
     }
 }
Example #9
0
 public function view_app()
 {
     $this->assertLoggedIn();
     $this->set('area', 'app');
     try {
         $app = new OAuthConsumer($this->args('app_id'));
         if (!$app->isHydrated()) {
             throw new Exception("This app does not exist.");
         }
         $this->setTitle("View App - " . $app->getName());
         $this->set('app', $app);
     } catch (Exception $e) {
         $this->setTitle('View App - Error');
         $this->set('megaerror', $e->getMessage());
     }
 }
Example #10
0
 public function view_app()
 {
     $this->assertLoggedIn();
     try {
         $app = new OAuthConsumer($this->args('app_id'));
         if (!$app->isHydrated()) {
             throw new Exception("This app does not exist.");
         }
         if (!User::$me->isAdmin() && $app->get('user_id') != User::$me->id) {
             throw new Exception("You are not authorized to view this app.");
         }
         $this->setTitle("View App - " . $app->getName());
         $this->set('app', $app);
     } catch (Exception $e) {
         $this->setTitle('View App - Error');
         $this->set('megaerror', $e->getMessage());
     }
 }
Example #11
0
/**
* Saves the user's information back to the database
*
* @A        array       User's data
*
*/
function saveuser($A)
{
    global $_CONF, $_TABLES, $_USER, $LANG04, $LANG24, $_US_VERBOSE;
    if ($_US_VERBOSE) {
        COM_errorLog('**** Inside saveuser in usersettings.php ****', 1);
    }
    $reqid = DB_getItem($_TABLES['users'], 'pwrequestid', "uid = " . (int) $_USER['uid']);
    if ($reqid != $A['uid']) {
        DB_change($_TABLES['users'], 'pwrequestid', "NULL", 'uid', (int) $_USER['uid']);
        COM_accessLog("An attempt was made to illegally change the account information of user {$_USER['uid']}.");
        return COM_refresh($_CONF['site_url'] . '/index.php');
    }
    if (isset($_POST['merge'])) {
        if (COM_applyFilter($_POST['remoteuid'], true) != $_USER['uid']) {
            echo COM_refresh($_CONF['site_url'] . '/usersettings.php?mode=edit');
        }
        USER_mergeAccounts();
    }
    // If not set or possibly removed from template - initialize variable
    if (!isset($A['cooktime'])) {
        $A['cooktime'] = 0;
    } else {
        $A['cooktime'] = COM_applyFilter($A['cooktime'], true);
    }
    // If empty or invalid - set to user default
    // So code after this does not fail the user password required test
    if ($A['cooktime'] < 0) {
        // note that == 0 is allowed!
        $A['cooktime'] = $_USER['cookietimeout'];
    }
    // to change the password, email address, or cookie timeout,
    // we need the user's current password
    $account_type = DB_getItem($_TABLES['users'], 'account_type', "uid = {$_USER['uid']}");
    $service = DB_getItem($_TABLES['users'], 'remoteservice', "uid = {$_USER['uid']}");
    if ($service == '') {
        $current_password = DB_getItem($_TABLES['users'], 'passwd', "uid = {$_USER['uid']}");
        if (!empty($A['newp']) || $A['email'] != $_USER['email'] || $A['cooktime'] != $_USER['cookietimeout']) {
            if (empty($A['passwd']) || !SEC_check_hash($A['passwd'], $current_password)) {
                return COM_refresh($_CONF['site_url'] . '/usersettings.php?msg=83');
            } elseif ($_CONF['custom_registration'] && function_exists('CUSTOM_userCheck')) {
                $ret = CUSTOM_userCheck($A['username'], $A['email']);
                if (!empty($ret)) {
                    // Need a numeric return for the default message handler
                    // - if not numeric use default message
                    if (!is_numeric($ret)) {
                        $ret['number'] = 97;
                    }
                    return COM_refresh("{$_CONF['site_url']}/usersettings.php?msg={$ret}");
                }
            }
        } elseif ($_CONF['custom_registration'] && function_exists('CUSTOM_userCheck')) {
            $ret = CUSTOM_userCheck($A['username'], $A['email']);
            if (!empty($ret)) {
                // Need a numeric return for the default message hander - if not numeric use default message
                // - if not numeric use default message
                if (!is_numeric($ret)) {
                    $ret = 97;
                }
                return COM_refresh("{$_CONF['site_url']}/usersettings.php?msg={$ret}");
            }
        }
    }
    // Let plugins have a chance to decide what to do before saving the user, return errors.
    $msg = PLG_itemPreSave('useredit', $A['username']);
    if (!empty($msg)) {
        // need a numeric return value - otherwise use default message
        if (!is_numeric($msg)) {
            $msg = 97;
        }
        return COM_refresh("{$_CONF['site_url']}/usersettings.php?msg={$msg}");
    }
    // no need to filter the password as it's encoded anyway
    if ($_CONF['allow_username_change'] == 1) {
        $A['new_username'] = $A['new_username'];
        if (!empty($A['new_username']) && USER_validateUsername($A['new_username']) && $A['new_username'] != $_USER['username']) {
            $A['new_username'] = DB_escapeString($A['new_username']);
            if (DB_count($_TABLES['users'], 'username', $A['new_username']) == 0) {
                if ($_CONF['allow_user_photo'] == 1) {
                    $photo = DB_getItem($_TABLES['users'], 'photo', "uid = " . (int) $_USER['uid']);
                    if (!empty($photo) && strstr($photo, $_USER['username']) !== false) {
                        $newphoto = preg_replace('/' . $_USER['username'] . '/', $_USER['uid'], $photo, 1);
                        $imgpath = $_CONF['path_images'] . 'userphotos/';
                        @rename($imgpath . $photo, $imgpath . $newphoto);
                        DB_change($_TABLES['users'], 'photo', DB_escapeString($newphoto), "uid", (int) $_USER['uid']);
                    }
                }
                DB_change($_TABLES['users'], 'username', $A['new_username'], "uid", (int) $_USER['uid']);
            } else {
                return COM_refresh($_CONF['site_url'] . '/usersettings.php?msg=51');
            }
        }
    }
    // a quick spam check with the unfiltered field contents
    $profile = '<h1>' . $LANG04[1] . ' ' . $_USER['username'] . '</h1><p>';
    // this is a hack, for some reason remoteservice links made SPAMX SLV check barf
    if (empty($service)) {
        $profile .= COM_createLink($A['homepage'], $A['homepage']) . '<br />';
    }
    $profile .= $A['location'] . '<br />' . $A['sig'] . '<br />' . $A['about'] . '<br />' . $A['pgpkey'] . '</p>';
    $result = PLG_checkforSpam($profile, $_CONF['spamx']);
    if ($result > 0) {
        COM_displayMessageAndAbort($result, 'spamx', 403, 'Forbidden');
    }
    $A['email'] = COM_applyFilter($A['email']);
    $A['email_conf'] = COM_applyFilter($A['email_conf']);
    $A['homepage'] = COM_applyFilter($A['homepage']);
    // basic filtering only
    $A['fullname'] = COM_truncate(trim(USER_sanitizeName($A['fullname'])), 80);
    $A['location'] = strip_tags($A['location']);
    $A['sig'] = strip_tags($A['sig']);
    $A['about'] = strip_tags($A['about']);
    $A['pgpkey'] = strip_tags($A['pgpkey']);
    if (!COM_isEmail($A['email'])) {
        return COM_refresh($_CONF['site_url'] . '/usersettings.php?msg=52');
    } else {
        if ($A['email'] !== $A['email_conf']) {
            return COM_refresh($_CONF['site_url'] . '/usersettings.php?msg=78');
        } else {
            if (emailAddressExists($A['email'], $_USER['uid'])) {
                return COM_refresh($_CONF['site_url'] . '/usersettings.php?msg=56');
            } else {
                if ($service == '') {
                    if (!empty($A['newp'])) {
                        $A['newp'] = trim($A['newp']);
                        $A['newp_conf'] = trim($A['newp_conf']);
                        if ($A['newp'] == $A['newp_conf'] && SEC_check_hash($A['passwd'], $current_password)) {
                            $passwd = SEC_encryptPassword($A['newp']);
                            DB_change($_TABLES['users'], 'passwd', DB_escapeString($passwd), "uid", (int) $_USER['uid']);
                            if ($A['cooktime'] > 0) {
                                $cooktime = $A['cooktime'];
                                $token_ttl = $A['cooktime'];
                            } else {
                                $cooktime = 0;
                                $token_ttl = 14400;
                            }
                            $ltToken = SEC_createTokenGeneral('ltc', $token_ttl);
                            SEC_setCookie($_CONF['cookie_password'], $ltToken, time() + $cooktime);
                        } elseif (!SEC_check_hash($A['passwd'], $current_password)) {
                            return COM_refresh($_CONF['site_url'] . '/usersettings.php?msg=68');
                        } elseif ($A['newp'] != $A['newp_conf']) {
                            return COM_refresh($_CONF['site_url'] . '/usersettings.php?msg=67');
                        }
                    }
                } else {
                    // Cookie
                    if ($A['cooktime'] > 0) {
                        $cooktime = $A['cooktime'];
                    } else {
                        $cooktime = 0;
                    }
                    $ltToken = SEC_createTokenGeneral('ltc', $cooktime);
                    SEC_setCookie($_CONF['cookie_password'], $ltToken, time() + $cooktime);
                }
                if ($_US_VERBOSE) {
                    COM_errorLog('cooktime = ' . $A['cooktime'], 1);
                }
                if ($A['cooktime'] <= 0) {
                    $cookie_timeout = 0;
                    $token_ttl = 14400;
                } else {
                    $cookie_timeout = time() + $A['cooktime'];
                    $token_ttl = $A['cooktime'];
                }
                SEC_setCookie($_CONF['cookie_name'], $_USER['uid'], $cookie_timeout, $_CONF['cookie_path'], $_CONF['cookiedomain'], $_CONF['cookiesecure'], true);
                DB_query("DELETE FROM {$_TABLES['tokens']} WHERE owner_id=" . (int) $_USER['uid'] . " AND urlfor='ltc'");
                if ($cookie_timeout > 0) {
                    $ltToken = SEC_createTokenGeneral('ltc', $token_ttl);
                    SEC_setCookie($_CONF['cookie_password'], $ltToken, $cookie_timeout, $_CONF['cookie_path'], $_CONF['cookiedomain'], $_CONF['cookiesecure'], true);
                } else {
                    SEC_setCookie($_CONF['cookie_password'], '', -10000, $_CONF['cookie_path'], $_CONF['cookiedomain'], $_CONF['cookiesecure'], true);
                }
                if ($_CONF['allow_user_photo'] == 1) {
                    $delete_photo = '';
                    if (isset($A['delete_photo'])) {
                        $delete_photo = $A['delete_photo'];
                    }
                    $filename = handlePhotoUpload($delete_photo);
                }
                if (!empty($A['homepage'])) {
                    $pos = MBYTE_strpos($A['homepage'], ':');
                    if ($pos === false) {
                        $A['homepage'] = 'http://' . $A['homepage'];
                    } else {
                        $prot = substr($A['homepage'], 0, $pos + 1);
                        if ($prot != 'http:' && $prot != 'https:') {
                            $A['homepage'] = 'http:' . substr($A['homepage'], $pos + 1);
                        }
                    }
                    $A['homepage'] = DB_escapeString($A['homepage']);
                }
                $A['fullname'] = DB_escapeString($A['fullname']);
                $A['email'] = DB_escapeString($A['email']);
                $A['location'] = DB_escapeString($A['location']);
                $A['sig'] = DB_escapeString($A['sig']);
                $A['about'] = DB_escapeString($A['about']);
                $A['pgpkey'] = DB_escapeString($A['pgpkey']);
                if (!empty($filename)) {
                    if (!file_exists($_CONF['path_images'] . 'userphotos/' . $filename)) {
                        $filename = '';
                    }
                }
                DB_query("UPDATE {$_TABLES['users']} SET fullname='{$A['fullname']}',email='{$A['email']}',homepage='{$A['homepage']}',sig='{$A['sig']}',cookietimeout=" . (int) $A['cooktime'] . ",photo='" . DB_escapeString($filename) . "' WHERE uid=" . (int) $_USER['uid']);
                DB_query("UPDATE {$_TABLES['userinfo']} SET pgpkey='{$A['pgpkey']}',about='{$A['about']}',location='{$A['location']}' WHERE uid=" . (int) $_USER['uid']);
                // Call custom registration save function if enabled and exists
                if ($_CONF['custom_registration'] and function_exists('CUSTOM_userSave')) {
                    CUSTOM_userSave($_USER['uid']);
                }
                PLG_userInfoChanged((int) $_USER['uid']);
                // at this point, the user information has been saved, but now we're going to check to see if
                // the user has requested resynchronization with their remoteservice account
                $msg = 5;
                // default msg = Your account information has been successfully saved
                if (isset($A['resynch'])) {
                    if ($_CONF['user_login_method']['oauth'] && strpos($_USER['remoteservice'], 'oauth.') === 0) {
                        $modules = SEC_collectRemoteOAuthModules();
                        $active_service = count($modules) == 0 ? false : in_array(substr($_USER['remoteservice'], 6), $modules);
                        if (!$active_service) {
                            $status = -1;
                            $msg = 115;
                            // Remote service has been disabled.
                        } else {
                            require_once $_CONF['path_system'] . 'classes/oauthhelper.class.php';
                            $service = substr($_USER['remoteservice'], 6);
                            $consumer = new OAuthConsumer($service);
                            $callback_url = $_CONF['site_url'];
                            $consumer->setRedirectURL($callback_url);
                            $user = $consumer->authenticate_user();
                            $consumer->doSynch($user);
                        }
                    }
                    if ($msg != 5) {
                        $msg = 114;
                        // Account saved but re-synch failed.
                        COM_errorLog($MESSAGE[$msg]);
                    }
                }
                PLG_profileExtrasSave();
                PLG_profileSave();
                if ($_US_VERBOSE) {
                    COM_errorLog('**** Leaving saveuser in usersettings.php ****', 1);
                }
                return COM_refresh($_CONF['site_url'] . '/users.php?mode=profile&amp;uid=' . $_USER['uid'] . '&amp;msg=' . $msg);
            }
        }
    }
}
 /**
  * Create OAuthRequest from Consumer and Token
  *
  * @param OAuthConsumer $consumer - OAuthConsumer
  * @param OAuthToken $token - OAuthToken
  * @param String $httpMethod - http method
  * @param String $httpURL - http URL
  * @param array|null $parameters - parameters
  * @return OAuthRequest
  */
 public static function createFromConsumerAndToken($consumer, $token, $httpMethod, $httpURL, $parameters = null)
 {
     @$parameters or $parameters = array();
     $nonce = OAuthRequest::generateNonce();
     $timestamp = OAuthRequest::generateTimestamp();
     $default = array('oauth_version' => OAuthRequest::VERSION, 'oauth_nonce' => $nonce, 'oauth_timestamp' => $timestamp, 'oauth_consumer_key' => $consumer->getKey());
     if ($token) {
         $default['oauth_token'] = $token->getKey();
     }
     $parameters = array_merge($default, $parameters);
     $urlParts = parse_url($httpURL);
     if (isset($urlParts['query']) && $urlParts['query']) {
         $params = OAuthUtils::parseParameterFromString($urlParts['query']);
         $parameters = array_merge($params, $parameters);
     }
     return new OAuthRequest($httpMethod, $httpURL, $parameters, $nonce, $timestamp);
 }
 function __construct($key, $secret, $callback_url = NULL, $id = NULL)
 {
     $this->id = $id;
     parent::__construct($key, $secret, $callback_url);
 }
Example #14
0
 private function signRequest(RemoteContentRequest $request)
 {
     $url = $request->getUrl();
     $method = $request->getMethod();
     try {
         // Parse the request into parameters for OAuth signing, stripping out
         // any OAuth or OpenSocial parameters injected by the client
         $parsedUri = parse_url($url);
         $resource = $url;
         $queryParams = array();
         if (isset($parsedUri['query'])) {
             parse_str($parsedUri['query'], $queryParams);
             // strip out all opensocial_* and oauth_* params so they can't be spoofed by the client
             foreach ($queryParams as $key => $val) {
                 if (strtolower(substr($key, 0, strlen('opensocial_'))) == 'opensocial_' || strtolower(substr($key, 0, strlen('oauth_'))) == 'oauth_') {
                     unset($queryParams[$key]);
                 }
             }
             $queryParams = $this->sanitize($queryParams);
         }
         $contentType = $request->getHeader('Content-Type');
         $signBody = stripos($contentType, 'application/x-www-form-urlencoded') !== false || $contentType == null;
         if ($request->getPostBody()) {
             if ($signBody) {
                 $postParams = array();
                 // on normal application/x-www-form-urlencoded type post's encode and parse the post vars
                 parse_str($request->getPostBody(), $postParams);
                 $postParams = $this->sanitize($postParams);
             } else {
                 // on any other content-type of post (application/{json,xml,xml+atom}) use the body signing hash
                 // see http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/drafts/4/spec.html for details
                 $queryParams['oauth_body_hash'] = base64_encode(sha1($request->getPostBody(), true));
             }
         }
         $msgParams = array();
         $msgParams = array_merge($msgParams, $queryParams);
         if ($signBody && isset($postParams)) {
             $msgParams = array_merge($msgParams, $postParams);
         }
         $this->addOpenSocialParams($msgParams, $request->getToken(), $request->getOptions()->ownerSigned, $request->getOptions()->viewerSigned);
         $this->addOAuthParams($msgParams, $request->getToken());
         $consumer = new OAuthConsumer(NULL, NULL, NULL);
         $consumer->setProperty(OAuthSignatureMethod_RSA_SHA1::$PRIVATE_KEY, $this->privateKeyObject);
         $signatureMethod = new OAuthSignatureMethod_RSA_SHA1();
         $req_req = OAuthRequest::from_consumer_and_token($consumer, NULL, $method, $resource, $msgParams);
         $req_req->sign_request($signatureMethod, $consumer, NULL);
         // Rebuild the query string, including all of the parameters we added.
         // We have to be careful not to copy POST parameters into the query.
         // If post and query parameters share a name, they end up being removed
         // from the query.
         $forPost = array();
         $postData = false;
         if ($method == 'POST' && $signBody) {
             foreach ($postParams as $key => $param) {
                 $forPost[$key] = $param;
                 if ($postData === false) {
                     $postData = array();
                 }
                 $postData[] = OAuthUtil::urlencodeRFC3986($key) . "=" . OAuthUtil::urlencodeRFC3986($param);
             }
             if ($postData !== false) {
                 $postData = implode("&", $postData);
             }
         }
         $newQuery = '';
         foreach ($req_req->get_parameters() as $key => $param) {
             if (!isset($forPost[$key])) {
                 $newQuery .= urlencode($key) . '=' . urlencode($param) . '&';
             }
         }
         // and stick on the original query params too
         if (isset($parsedUri['query']) && !empty($parsedUri['query'])) {
             $oldQuery = array();
             parse_str($parsedUri['query'], $oldQuery);
             foreach ($oldQuery as $key => $val) {
                 $newQuery .= urlencode($key) . '=' . urlencode($val) . '&';
             }
         }
         // Careful here; the OAuth form encoding scheme is slightly different than
         // the normal form encoding scheme, so we have to use the OAuth library
         // formEncode method.
         $url = $parsedUri['scheme'] . '://' . $parsedUri['host'] . (isset($parsedUri['port']) ? ':' . $parsedUri['port'] : '') . (isset($parsedUri['path']) ? $parsedUri['path'] : '') . '?' . $newQuery;
         $request->setUri($url);
         if ($signBody) {
             $request->setPostBody($postData);
         }
     } catch (Exception $e) {
         throw new GadgetException($e);
     }
 }
Example #15
0
 // Here we go with the handling of OAuth authentification.
 $active_service = false;
 $modules = SEC_collectRemoteOAuthModules();
 $active_service = count($modules) == 0 ? false : in_array($_GET['oauth_login'], $modules);
 if (!$active_service) {
     $status = -1;
 } else {
     $query = array_merge($_GET, $_POST);
     $service = $query['oauth_login'];
     $callback_url = $_CONF['site_url'] . '/users.php?oauth_login='******'login_speedlimit'], $service);
     if (COM_checkSpeedlimit($service, $_CONF['login_attempts']) > 0) {
         displayLoginErrorAndAbort(82, $LANG12[26], $LANG04[112]);
     }
     require_once $_CONF['path_system'] . 'classes/oauthhelper.class.php';
     $consumer = new OAuthConsumer($service);
     $callback_query_string = $consumer->getCallback_query_string();
     $cancel_query_string = $consumer->getCancel_query_string();
     if (!isset($query[$callback_query_string]) && (empty($cancel_query_string) || !isset($query[$cancel_query_string]))) {
         $url = $consumer->find_identity_info($callback_url, $query);
         if (empty($url)) {
             COM_updateSpeedlimit('login');
             COM_updateSpeedlimit($service);
             echo COM_refresh($_CONF['site_url'] . '/users.php?msg=110');
             exit;
         } else {
             header('Location: ' . $url);
             exit;
         }
     } elseif (isset($query[$callback_query_string])) {
         $oauth_userinfo = $consumer->sreq_userinfo_response($query);