Example #1
0
 static function generateNew()
 {
     $cons = new Consumer();
     $rand = common_random_hexstr(16);
     $cons->seed = $rand;
     $cons->consumer_key = md5(time() + $rand);
     $cons->consumer_secret = md5(md5(time() + time() + $rand));
     $cons->created = common_sql_now();
     return $cons;
 }
 static function saveNew($user_id, $action, $arg1, $arg2)
 {
     $channel = new Realtime_channel();
     $channel->user_id = $user_id;
     $channel->action = $action;
     $channel->arg1 = $arg1;
     $channel->arg2 = $arg2;
     $channel->audience = 1;
     $channel->channel_key = common_random_hexstr(16);
     // 128-bit key, 32 hex chars
     $channel->created = common_sql_now();
     $channel->modified = $channel->created;
     $channel->insert();
     return $channel;
 }
Example #3
0
 function handle($args)
 {
     parent::handle($args);
     if (common_is_real_login()) {
         // TRANS: Client error displayed when trying to log in while already logged on.
         $this->clientError(_m('Already logged in.'));
     } else {
         global $casSettings;
         phpCAS::client(CAS_VERSION_2_0, $casSettings['server'], $casSettings['port'], $casSettings['path'], false);
         phpCAS::setNoCasServerValidation();
         phpCAS::handleLogoutRequests();
         phpCAS::forceAuthentication();
         global $casTempPassword;
         $casTempPassword = common_random_hexstr(16);
         $user = common_check_user(phpCAS::getUser(), $casTempPassword);
         if (!$user) {
             // TRANS: Server error displayed when trying to log in with incorrect username or password.
             $this->serverError(_m('Incorrect username or password.'));
         }
         // success!
         if (!common_set_user($user)) {
             // TRANS: Server error displayed when login fails in CAS authentication plugin.
             $this->serverError(_m('Error setting user. You are probably not authorized.'));
         }
         common_real_login(true);
         $url = common_get_returnto();
         if ($url) {
             // We don't have to return to it again
             common_set_returnto(null);
         } else {
             if (common_config('site', 'private') && $casSettings['takeOverLogin']) {
                 //SSO users expect to just go to the URL they entered
                 //if we don't have a returnto set, the user entered the
                 //main StatusNet url, so send them there.
                 $url = common_local_url('public');
             } else {
                 //With normal logins (regular form-based username/password),
                 //the user would expect to go to their home after logging in.
                 $url = common_local_url('public', array('nickname' => $user->nickname));
             }
         }
         common_redirect($url, 303);
     }
 }
Example #4
0
 function makeNew($user)
 {
     $login_token = Login_token::getKV('user_id', $user->id);
     if (!empty($login_token)) {
         $login_token->delete();
     }
     $login_token = new Login_token();
     $login_token->user_id = $user->id;
     $login_token->token = common_random_hexstr(16);
     $login_token->created = common_sql_now();
     $result = $login_token->insert();
     if (!$result) {
         common_log_db_error($login_token, 'INSERT', __FILE__);
         // TRANS: Exception thrown when trying creating a login token failed.
         // TRANS: %s is the user nickname for which token creation failed.
         throw new Exception(sprintf(_('Could not create login token for %s'), $user->nickname));
     }
     return $login_token;
 }
Example #5
0
 /**
  * Factory method for creating a new conversation.
  *
  * Use this for locally initiated conversations. Remote notices should
  * preferrably supply their own conversation URIs in the OStatus feed.
  *
  * @return Conversation the new conversation DO
  */
 static function create($uri = null, $created = null)
 {
     // Be aware that the Notice does not have an id yet since it's not inserted!
     $conv = new Conversation();
     $conv->created = $created ?: common_sql_now();
     $conv->uri = $uri ?: sprintf('%s%s=%s:%s=%s', TagURI::mint(), 'objectType', 'thread', 'nonce', common_random_hexstr(8));
     // This insert throws exceptions on failure
     $conv->insert();
     return $conv;
 }
 function new_request_token($consumer, $callback)
 {
     $t = new Token();
     $t->consumer_key = $consumer->key;
     $t->tok = common_random_hexstr(16);
     $t->secret = common_random_hexstr(16);
     $t->type = 0;
     // request
     $t->state = 0;
     // unauthorized
     $t->verified_callback = $callback;
     if ($callback === 'oob') {
         // six digit pin
         $t->verifier = mt_rand(0, 9999999);
     } else {
         $t->verifier = common_random_hexstr(8);
     }
     $t->created = common_sql_now();
     if (!$t->insert()) {
         return null;
     } else {
         return new OAuthToken($t->tok, $t->secret);
     }
 }
Example #7
0
function common_session_token()
{
    common_ensure_session();
    if (!array_key_exists('token', $_SESSION)) {
        $_SESSION['token'] = common_random_hexstr(64);
    }
    return $_SESSION['token'];
}
Example #8
0
 /**
  * Include a session token for CSRF protection
  *
  * @return void
  */
 function sessionToken()
 {
     if (strtolower($this->method()) == 'post') {
         $this->out->hidden('token-' . $this->id() ?: common_random_hexstr(3), common_session_token(), 'token');
     }
 }
 function setAvatar($user)
 {
     try {
         $picUrl = sprintf('http://graph.facebook.com/%d/picture?type=large', $this->fbuser->id);
         // fetch the picture from Facebook
         $client = new HTTPClient();
         // fetch the actual picture
         $response = $client->get($picUrl);
         if ($response->isOk()) {
             // seems to always be jpeg, but not sure
             $tmpname = "facebook-avatar-tmp-" . common_random_hexstr(4);
             $ok = file_put_contents(Avatar::path($tmpname), $response->getBody());
             if (!$ok) {
                 common_log(LOG_WARNING, 'Couldn\'t save tmp Facebook avatar: ' . $tmpname, __FILE__);
             } else {
                 // save it as an avatar
                 $imagefile = new ImageFile(null, Avatar::path($tmpname));
                 $filename = Avatar::filename($user->id, image_type_to_extension($imagefile->preferredType()), 180, common_timestamp());
                 // Previous docs said 180 is the "biggest img we get from Facebook"
                 $imagefile->resizeTo(Avatar::path($filename, array('width' => 180, 'height' => 180)));
                 // No need to keep the temporary file around...
                 @unlink(Avatar::path($tmpname));
                 $profile = $user->getProfile();
                 if ($profile->setOriginal($filename)) {
                     common_log(LOG_INFO, sprintf('Saved avatar for %s (%d) from Facebook picture for ' . '%s (fbuid %d), filename = %s', $user->nickname, $user->id, $this->fbuser->name, $this->fbuid, $filename), __FILE__);
                     // clean up tmp file
                 }
             }
         }
     } catch (Exception $e) {
         common_log(LOG_WARNING, 'Couldn\'t save Facebook avatar: ' . $e->getMessage(), __FILE__);
         // error isn't fatal, continue
     }
 }
Example #10
0
 /**
  * Setting to subscribe means it is _waiting_ to become active. This
  * cannot be done in a transaction because there is a chance that the
  * remote script we're calling (as in the case of PuSHpress) performs
  * the lookup _while_ we're POSTing data, which means the transaction
  * never completes (PushcallbackAction gets an 'inactive' state).
  *
  * @return boolean true when everything is ok (throws Exception on fail)
  * @throws Exception on failure, can be HTTPClient's or our own.
  */
 protected function doSubscribe($mode)
 {
     $orig = clone $this;
     if ($mode == 'subscribe') {
         $this->secret = common_random_hexstr(32);
     }
     $this->sub_state = $mode;
     $this->update($orig);
     unset($orig);
     try {
         $callback = common_local_url('pushcallback', array('feed' => $this->id));
         $headers = array('Content-Type: application/x-www-form-urlencoded');
         $post = array('hub.mode' => $mode, 'hub.callback' => $callback, 'hub.verify' => 'async', 'hub.verify_token' => 'Deprecated-since-PuSH-0.4', 'hub.secret' => $this->secret, 'hub.topic' => $this->getUri());
         $client = new HTTPClient();
         if ($this->huburi) {
             $hub = $this->huburi;
         } else {
             if (common_config('feedsub', 'fallback_hub')) {
                 $hub = common_config('feedsub', 'fallback_hub');
                 if (common_config('feedsub', 'hub_user')) {
                     $u = common_config('feedsub', 'hub_user');
                     $p = common_config('feedsub', 'hub_pass');
                     $client->setAuth($u, $p);
                 }
             } else {
                 throw new FeedSubException('Server could not find a usable PuSH hub.');
             }
         }
         $response = $client->post($hub, $headers, $post);
         $status = $response->getStatus();
         // PuSH specificed response status code
         if ($status == 202) {
             common_log(LOG_INFO, __METHOD__ . ': sub req ok, awaiting verification callback');
             return;
         } else {
             if ($status >= 200 && $status < 300) {
                 common_log(LOG_ERR, __METHOD__ . ": sub req returned unexpected HTTP {$status}: " . $response->getBody());
             } else {
                 common_log(LOG_ERR, __METHOD__ . ": sub req failed with HTTP {$status}: " . $response->getBody());
             }
         }
     } catch (Exception $e) {
         common_log(LOG_ERR, __METHOD__ . ": error \"{$e->getMessage()}\" hitting hub {$this->huburi} subscribing to {$this->getUri()}");
         // Reset the subscription state.
         $orig = clone $this;
         $this->sub_state = 'inactive';
         $this->update($orig);
         // Throw the Exception again.
         throw $e;
     }
     throw new ServerException("{$mode} request failed.");
 }
 private function _fakeNotice($user = null, $text = null)
 {
     if (empty($user)) {
         $user = $this->author1;
     }
     if (empty($text)) {
         $text = "fake-o text-o " . common_random_hexstr(32);
     }
     return Notice::saveNew($user->id, $text, 'test', array('uri' => null));
 }
 static function createAnonProfile()
 {
     // Get the anon user's IP, and turn it into a nickname
     list($proxy, $ip) = common_client_ip();
     // IP + time + random number should help to avoid collisions
     $baseNickname = $ip . '-' . time() . '-' . common_random_hexstr(5);
     $profile = new Profile();
     $profile->nickname = $baseNickname;
     $id = $profile->insert();
     if (!$id) {
         // TRANS: Server exception.
         throw new ServerException(_m("Could not create anonymous user session."));
     }
     // Stick the Profile ID into the nickname
     $orig = clone $profile;
     $profile->nickname = 'anon-' . $id . '-' . $baseNickname;
     $result = $profile->update($orig);
     if (!$result) {
         // TRANS: Server exception.
         throw new ServerException(_m("Could not create anonymous user session."));
     }
     common_log(LOG_INFO, "AnonymousFavePlugin - created profile for anonymous user from IP: " . $ip . ', nickname = ' . $profile->nickname);
     return $profile;
 }
Example #13
0
 /**
  * Send a verification ping to subscriber, and if confirmed apply the changes.
  * This may create, update, or delete the database record.
  *
  * @param string $mode 'subscribe' or 'unsubscribe'
  * @param string $token hub.verify_token value, if provided by client
  * @throws ClientException on failure
  */
 function verify($mode, $token = null)
 {
     assert($mode == 'subscribe' || $mode == 'unsubscribe');
     $challenge = common_random_hexstr(32);
     $params = array('hub.mode' => $mode, 'hub.topic' => $this->topic, 'hub.challenge' => $challenge);
     if ($mode == 'subscribe') {
         $params['hub.lease_seconds'] = $this->lease;
     }
     if ($token !== null) {
         // TODO: deprecated in PuSH 0.4
         $params['hub.verify_token'] = $token;
         // let's put it in there if remote uses PuSH <0.4
     }
     // Any existing query string parameters must be preserved
     $url = $this->callback;
     if (strpos($url, '?') !== false) {
         $url .= '&';
     } else {
         $url .= '?';
     }
     $url .= http_build_query($params, '', '&');
     $request = new HTTPClient();
     $response = $request->get($url);
     $status = $response->getStatus();
     if ($status >= 200 && $status < 300) {
         common_log(LOG_INFO, "Verified {$mode} of {$this->callback}:{$this->topic}");
     } else {
         // TRANS: Client exception. %s is a HTTP status code.
         throw new ClientException(sprintf(_m('Hub subscriber verification returned HTTP %s.'), $status));
     }
     $old = HubSub::getByHashkey($this->topic, $this->callback);
     if ($mode == 'subscribe') {
         if ($old instanceof HubSub) {
             $this->update($old);
         } else {
             $ok = $this->insert();
         }
     } else {
         if ($mode == 'unsubscribe') {
             if ($old instanceof HubSub) {
                 $old->delete();
             } else {
                 // That's ok, we're already unsubscribed.
             }
         }
     }
 }
Example #14
0
 /**
  * Generate a new UUID
  *
  * @return 36-char v4 (random-ish) UUID
  */
 static function gen()
 {
     return sprintf('%s-%s-%04x-%04x-%s', common_random_hexstr(4), common_random_hexstr(2), hexdec(common_random_hexstr(2)) & 0xfff | 0x4000, hexdec(common_random_hexstr(2)) & 0x3fff | 0x8000, common_random_hexstr(6));
 }
 function autoRegister($username, $nickname)
 {
     if (is_null($nickname)) {
         $nickname = $username;
     }
     $entry = $this->ldapCommon->get_user($username, $this->attributes);
     if ($entry) {
         $registration_data = array();
         foreach ($this->attributes as $sn_attribute => $ldap_attribute) {
             //ldap won't let us read a user's password,
             //and we're going to set the password to a random string later anyways,
             //so don't bother trying to read it.
             if ($sn_attribute != 'password') {
                 $registration_data[$sn_attribute] = $entry->getValue($ldap_attribute, 'single');
             }
         }
         if (isset($registration_data['email']) && !empty($registration_data['email'])) {
             $registration_data['email_confirmed'] = true;
         }
         $registration_data['nickname'] = $nickname;
         //set the database saved password to a random string.
         $registration_data['password'] = common_random_hexstr(16);
         return User::register($registration_data);
     } else {
         //user isn't in ldap, so we cannot register him
         return false;
     }
 }