/** * create dependent objects before running each test **/ public final function setUp() { // run the default setUp() method first parent::setUp(); // create and insert a Profile to own the test Tweet $this->profile = new Profile(null, "@phpunit", "*****@*****.**", "+12125551212"); $this->profile->insert($this->getPDO()); // create the test Tweet $this->tweet = new Tweet(null, $this->profile->getProfileId(), "PHPUnit favorite test passing"); $this->tweet->insert($this->getPDO()); // calculate the date (just use the time the unit test was setup...) $this->VALID_FAVORITEDATE = new DateTime(); }
public static function fromUrl($url, $depth = 0) { common_debug('MentionURL: trying to find a profile for ' . $url); $url = preg_replace('#https?://#', 'https://', $url); try { $profile = Profile::fromUri($url); } catch (UnknownUriException $ex) { } if (!$profile instanceof Profile) { $profile = self::findProfileByProfileURL($url); } $url = str_replace('https://', 'http://', $url); if (!$profile instanceof Profile) { try { $profile = Profile::fromUri($url); } catch (UnknownUriException $ex) { } } if (!$profile instanceof Profile) { $profile = self::findProfileByProfileURL($url); } if (!$profile instanceof Profile) { $hcard = mention_url_representative_hcard($url); if (!$hcard) { return null; } $mention_profile = new Mention_url_profile(); $mention_profile->query('BEGIN'); $profile = new Profile(); $profile->profileurl = $hcard['url'][0]; $profile->fullname = $hcard['name'][0]; preg_match('/\\/([^\\/]+)\\/*$/', $profile->profileurl, $matches); if (!$hcard['nickname']) { $hcard['nickname'] = array($matches[1]); } $profile->nickname = $hcard['nickname'][0]; $profile->created = common_sql_now(); $mention_profile->profile_id = $profile->insert(); if (!$mention_profile->profile_id) { $mention_profile->query('ROLLBACK'); return null; } $mention_profile->profileurl = $profile->profileurl; if (!$mention_profile->insert()) { $mention_profile->query('ROLLBACK'); if ($depth > 0) { return null; } else { return self::fromUrl($url, $depth + 1); } } else { $mention_profile->query('COMMIT'); } } return $profile; }
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_good_rand(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; }
/** * Register a new user account and profile and set up default subscriptions. * If a new-user welcome message is configured, this will be sent. * * @param array $fields associative array of optional properties * string 'bio' * string 'email' * bool 'email_confirmed' pass true to mark email as pre-confirmed * string 'fullname' * string 'homepage' * string 'location' informal string description of geolocation * float 'lat' decimal latitude for geolocation * float 'lon' decimal longitude for geolocation * int 'location_id' geoname identifier * int 'location_ns' geoname namespace to interpret location_id * string 'nickname' REQUIRED * string 'password' (may be missing for eg OpenID registrations) * string 'code' invite code * ?string 'uri' permalink to notice; defaults to local notice URL * @return mixed User object or false on failure */ static function register($fields) { // MAGICALLY put fields into current scope extract($fields); $profile = new Profile(); if (!empty($email)) { $email = common_canonical_email($email); } $nickname = common_canonical_nickname($nickname); $profile->nickname = $nickname; if (!User::allowed_nickname($nickname)) { common_log(LOG_WARNING, sprintf("Attempted to register a nickname that is not allowed: %s", $profile->nickname), __FILE__); return false; } $profile->profileurl = common_profile_url($nickname); if (!empty($fullname)) { $profile->fullname = $fullname; } if (!empty($homepage)) { $profile->homepage = $homepage; } if (!empty($bio)) { $profile->bio = $bio; } if (!empty($location)) { $profile->location = $location; $loc = Location::fromName($location); if (!empty($loc)) { $profile->lat = $loc->lat; $profile->lon = $loc->lon; $profile->location_id = $loc->location_id; $profile->location_ns = $loc->location_ns; } } $profile->created = common_sql_now(); $user = new User(); $user->nickname = $nickname; // Users who respond to invite email have proven their ownership of that address if (!empty($code)) { $invite = Invitation::staticGet($code); if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) { $user->email = $invite->address; } } if (isset($email_confirmed) && $email_confirmed) { $user->email = $email; } // This flag is ignored but still set to 1 $user->inboxed = 1; // Set default-on options here, otherwise they'll be disabled // initially for sites using caching, since the initial encache // doesn't know about the defaults in the database. $user->emailnotifysub = 1; $user->emailnotifyfav = 1; $user->emailnotifynudge = 1; $user->emailnotifymsg = 1; $user->emailnotifyattn = 1; $user->emailmicroid = 1; $user->emailpost = 1; $user->jabbermicroid = 1; $user->viewdesigns = 1; $user->created = common_sql_now(); if (Event::handle('StartUserRegister', array(&$user, &$profile))) { $profile->query('BEGIN'); $id = $profile->insert(); if (empty($id)) { common_log_db_error($profile, 'INSERT', __FILE__); return false; } $user->id = $id; if (!empty($uri)) { $user->uri = $uri; } else { $user->uri = common_user_uri($user); } if (!empty($password)) { // may not have a password for OpenID users $user->password = common_munge_password($password, $id); } $result = $user->insert(); if (!$result) { common_log_db_error($user, 'INSERT', __FILE__); return false; } // Everyone gets an inbox $inbox = new Inbox(); $inbox->user_id = $user->id; $inbox->notice_ids = ''; $result = $inbox->insert(); if (!$result) { common_log_db_error($inbox, 'INSERT', __FILE__); return false; } // Everyone is subscribed to themself $subscription = new Subscription(); $subscription->subscriber = $user->id; $subscription->subscribed = $user->id; $subscription->created = $user->created; $result = $subscription->insert(); if (!$result) { common_log_db_error($subscription, 'INSERT', __FILE__); return false; } if (!empty($email) && !$user->email) { $confirm = new Confirm_address(); $confirm->code = common_confirmation_code(128); $confirm->user_id = $user->id; $confirm->address = $email; $confirm->address_type = 'email'; $result = $confirm->insert(); if (!$result) { common_log_db_error($confirm, 'INSERT', __FILE__); return false; } } if (!empty($code) && $user->email) { $user->emailChanged(); } // Default system subscription $defnick = common_config('newuser', 'default'); if (!empty($defnick)) { $defuser = User::staticGet('nickname', $defnick); if (empty($defuser)) { common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick), __FILE__); } else { Subscription::start($user, $defuser); } } $profile->query('COMMIT'); if (!empty($email) && !$user->email) { mail_confirm_address($user, $confirm->code, $profile->nickname, $email); } // Welcome message $welcome = common_config('newuser', 'welcome'); if (!empty($welcome)) { $welcomeuser = User::staticGet('nickname', $welcome); if (empty($welcomeuser)) { common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick), __FILE__); } else { $notice = Notice::saveNew($welcomeuser->id, sprintf(_('Welcome to %1$s, @%2$s!'), common_config('site', 'name'), $user->nickname), 'system'); } } Event::handle('EndUserRegister', array(&$profile, &$user)); } return $user; }
protected function ensureProfile($twuser) { // check to see if there's already a profile for this user $profileurl = 'https://twitter.com/' . $twuser->screen_name; try { $profile = $this->getProfileByUrl($twuser->screen_name, $profileurl); $this->updateAvatar($twuser, $profile); return $profile; } catch (NoResultException $e) { common_debug(__METHOD__ . ' - Adding profile and remote profile ' . "for Twitter user: {$profileurl}."); } $profile = new Profile(); $profile->query("BEGIN"); $profile->nickname = $twuser->screen_name; $profile->fullname = $twuser->name; $profile->homepage = $twuser->url; $profile->bio = $twuser->description; $profile->location = $twuser->location; $profile->profileurl = $profileurl; $profile->created = common_sql_now(); try { $id = $profile->insert(); // insert _should_ throw exception on failure if (empty($id)) { throw new Exception('Failed insert'); } } catch (Exception $e) { common_log(LOG_WARNING, __METHOD__ . " Couldn't insert profile: " . $e->getMessage()); common_log_db_error($profile, 'INSERT', __FILE__); $profile->query("ROLLBACK"); return false; } $profile->query("COMMIT"); $this->updateAvatar($twuser, $profile); return $profile; }
static function register($fields) { # MAGICALLY put fields into current scope extract($fields); $profile = new Profile(); $profile->query('BEGIN'); $profile->nickname = $nickname; $profile->profileurl = common_profile_url($nickname); if (!empty($fullname)) { $profile->fullname = $fullname; } if (!empty($homepage)) { $profile->homepage = $homepage; } if (!empty($bio)) { $profile->bio = $bio; } if (!empty($location)) { $profile->location = $location; } $profile->created = common_sql_now(); $id = $profile->insert(); if (empty($id)) { common_log_db_error($profile, 'INSERT', __FILE__); return false; } $user = new User(); $user->id = $id; $user->nickname = $nickname; if (!empty($password)) { # may not have a password for OpenID users $user->password = common_munge_password($password, $id); } # Users who respond to invite email have proven their ownership of that address if (!empty($code)) { $invite = Invitation::staticGet($code); if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) { $user->email = $invite->address; } } $inboxes = common_config('inboxes', 'enabled'); if ($inboxes === true || $inboxes == 'transitional') { $user->inboxed = 1; } $user->created = common_sql_now(); $user->uri = common_user_uri($user); $result = $user->insert(); if (!$result) { common_log_db_error($user, 'INSERT', __FILE__); return false; } # Everyone is subscribed to themself $subscription = new Subscription(); $subscription->subscriber = $user->id; $subscription->subscribed = $user->id; $subscription->created = $user->created; $result = $subscription->insert(); if (!$result) { common_log_db_error($subscription, 'INSERT', __FILE__); return false; } if (!empty($email) && !$user->email) { $confirm = new Confirm_address(); $confirm->code = common_confirmation_code(128); $confirm->user_id = $user->id; $confirm->address = $email; $confirm->address_type = 'email'; $result = $confirm->insert(); if (!$result) { common_log_db_error($confirm, 'INSERT', __FILE__); return false; } } if (!empty($code) && $user->email) { $user->emailChanged(); } $profile->query('COMMIT'); if ($email && !$user->email) { mail_confirm_address($user, $confirm->code, $profile->nickname, $email); } return $user; }
/** * Save passed profile * * Stores the OMB profile $profile. Overwrites an existing entry. * Throws exceptions in case of error. * * @param OMB_Profile $profile The OMB profile which should be saved * * @access public **/ public function saveProfile($omb_profile) { if (common_profile_url($omb_profile->getNickname()) == $omb_profile->getProfileURL()) { throw new Exception('Not implemented'); } else { $remote = Remote_profile::staticGet('uri', $omb_profile->getIdentifierURI()); if ($remote) { $exists = true; $profile = Profile::staticGet($remote->id); $orig_remote = clone $remote; $orig_profile = clone $profile; // XXX: compare current postNotice and updateProfile URLs to the ones // stored in the DB to avoid (possibly...) above attack } else { $exists = false; $remote = new Remote_profile(); $remote->uri = $omb_profile->getIdentifierURI(); $profile = new Profile(); } $profile->nickname = $omb_profile->getNickname(); $profile->profileurl = $omb_profile->getProfileURL(); $fullname = $omb_profile->getFullname(); $profile->fullname = is_null($fullname) ? '' : $fullname; $homepage = $omb_profile->getHomepage(); $profile->homepage = is_null($homepage) ? '' : $homepage; $bio = $omb_profile->getBio(); $profile->bio = is_null($bio) ? '' : $bio; $location = $omb_profile->getLocation(); $profile->location = is_null($location) ? '' : $location; if ($exists) { $profile->update($orig_profile); } else { $profile->created = DB_DataObject_Cast::dateTime(); # current time $id = $profile->insert(); if (!$id) { // TRANS: Exception thrown when creating a new profile fails in OAuth store. throw new Exception(_('Error inserting new profile.')); } $remote->id = $id; } $avatar_url = $omb_profile->getAvatarURL(); if ($avatar_url) { if (!$this->add_avatar($profile, $avatar_url)) { // TRANS: Exception thrown when creating a new avatar fails in OAuth store. throw new Exception(_('Error inserting avatar.')); } } else { $avatar = $profile->getOriginalAvatar(); if ($avatar) { $avatar->delete(); } $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE); if ($avatar) { $avatar->delete(); } $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE); if ($avatar) { $avatar->delete(); } $avatar = $profile->getAvatar(AVATAR_MINI_SIZE); if ($avatar) { $avatar->delete(); } } if ($exists) { if (!$remote->update($orig_remote)) { // TRANS: Exception thrown when updating a remote profile fails in OAuth store. throw new Exception(_('Error updating remote profile.')); } } else { $remote->created = DB_DataObject_Cast::dateTime(); # current time if (!$remote->insert()) { // TRANS: Exception thrown when creating a remote profile fails in OAuth store. throw new Exception(_('Error inserting remote profile.')); } } } }
/** * test grabbing a Profile by email **/ public function testGetValidProfileByEmail() { // count the number of rows and save it for later $numRows = $this->getConnection()->getRowCount("profile"); // create a new Profile and insert to into mySQL $profile = new Profile(null, $this->VALID_ATHANDLE, $this->VALID_EMAIL, $this->VALID_PHONE); $profile->insert($this->getPDO()); // grab the data from mySQL and enforce the fields match our expectations $pdoProfile = Profile::getProfileByEmail($this->getPDO(), $profile->getEmail()); $this->assertSame($numRows + 1, $this->getConnection()->getRowCount("profile")); $this->assertSame($pdoProfile->getAtHandle(), $this->VALID_ATHANDLE); $this->assertSame($pdoProfile->getEmail(), $this->VALID_EMAIL); $this->assertSame($pdoProfile->getPhone(), $this->VALID_PHONE); }
static function register($fields) { if (!empty($fields['userid'])) { $profile = Profile::getKV('id', $fields['userid']); if ($profile && !$profile->hasRight(Right::CREATEGROUP)) { common_log(LOG_WARNING, "Attempted group creation from banned user: " . $profile->nickname); // TRANS: Client exception thrown when a user tries to create a group while banned. throw new ClientException(_('You are not allowed to create groups on this site.'), 403); } } $fields['nickname'] = Nickname::normalize($fields['nickname']); // MAGICALLY put fields into current scope // @fixme kill extract(); it makes debugging absurdly hard $defaults = array('nickname' => null, 'fullname' => null, 'homepage' => null, 'description' => null, 'location' => null, 'uri' => null, 'mainpage' => null, 'aliases' => array(), 'userid' => null); $fields = array_merge($defaults, $fields); extract($fields); $group = new User_group(); if (empty($uri)) { // fill in later... $uri = null; } if (empty($mainpage)) { $mainpage = common_local_url('showgroup', array('nickname' => $nickname)); } // We must create a new, incrementally assigned profile_id $profile = new Profile(); $profile->nickname = $nickname; $profile->fullname = $fullname; $profile->profileurl = $mainpage; $profile->homepage = $homepage; $profile->bio = $description; $profile->location = $location; $profile->created = common_sql_now(); $group->nickname = $profile->nickname; $group->fullname = $profile->fullname; $group->homepage = $profile->homepage; $group->description = $profile->bio; $group->location = $profile->location; $group->mainpage = $profile->profileurl; $group->created = $profile->created; $profile->query('BEGIN'); $id = $profile->insert(); if ($id === false) { $profile->query('ROLLBACK'); throw new ServerException(_('Profile insertion failed')); } $group->profile_id = $id; $group->uri = $uri; if (isset($fields['join_policy'])) { $group->join_policy = intval($fields['join_policy']); } else { $group->join_policy = 0; } if (isset($fields['force_scope'])) { $group->force_scope = intval($fields['force_scope']); } else { $group->force_scope = 0; } if (Event::handle('StartGroupSave', array(&$group))) { $result = $group->insert(); if ($result === false) { common_log_db_error($group, 'INSERT', __FILE__); // TRANS: Server exception thrown when creating a group failed. throw new ServerException(_('Could not create group.')); } if (!isset($uri) || empty($uri)) { $orig = clone $group; $group->uri = common_local_url('groupbyid', array('id' => $group->id)); $result = $group->update($orig); if (!$result) { common_log_db_error($group, 'UPDATE', __FILE__); // TRANS: Server exception thrown when updating a group URI failed. throw new ServerException(_('Could not set group URI.')); } } $result = $group->setAliases($aliases); if (!$result) { // TRANS: Server exception thrown when creating group aliases failed. throw new ServerException(_('Could not create aliases.')); } $member = new Group_member(); $member->group_id = $group->id; $member->profile_id = $userid; $member->is_admin = 1; $member->created = $group->created; $result = $member->insert(); if (!$result) { common_log_db_error($member, 'INSERT', __FILE__); // TRANS: Server exception thrown when setting group membership failed. throw new ServerException(_('Could not set group membership.')); } self::blow('profile:groups:%d', $userid); if ($local) { $local_group = new Local_group(); $local_group->group_id = $group->id; $local_group->nickname = $nickname; $local_group->created = common_sql_now(); $result = $local_group->insert(); if (!$result) { common_log_db_error($local_group, 'INSERT', __FILE__); // TRANS: Server exception thrown when saving local group information failed. throw new ServerException(_('Could not save local group info.')); } } Event::handle('EndGroupSave', array($group)); } $profile->query('COMMIT'); return $group; }
function ensureProfile($user) { // check to see if there's already a profile for this user $profileurl = 'http://twitter.com/' . $user->screen_name; $profile = Profile::staticGet('profileurl', $profileurl); if ($profile) { if (defined('SCRIPT_DEBUG')) { common_debug("Profile for {$profile->nickname} found."); } // Check to see if the user's Avatar has changed $this->checkAvatar($user, $profile); return $profile->id; } else { if (defined('SCRIPT_DEBUG')) { common_debug('Adding profile and remote profile ' . "for Twitter user: {$profileurl}"); } $profile = new Profile(); $profile->query("BEGIN"); $profile->nickname = $user->screen_name; $profile->fullname = $user->name; $profile->homepage = $user->url; $profile->bio = $user->description; $profile->location = $user->location; $profile->profileurl = $profileurl; $profile->created = common_sql_now(); $id = $profile->insert(); if (empty($id)) { common_log_db_error($profile, 'INSERT', __FILE__); $profile->query("ROLLBACK"); return false; } // check for remote profile $remote_pro = Remote_profile::staticGet('uri', $profileurl); if (!$remote_pro) { $remote_pro = new Remote_profile(); $remote_pro->id = $id; $remote_pro->uri = $profileurl; $remote_pro->created = common_sql_now(); $rid = $remote_pro->insert(); if (empty($rid)) { common_log_db_error($profile, 'INSERT', __FILE__); $profile->query("ROLLBACK"); return false; } } $profile->query("COMMIT"); $this->saveAvatars($user, $id); return $id; } }
if (empty($fullname)) { echo 'username required'; exit; } if (empty($email)) { echo 'email required'; exit; } if (empty($password)) { echo 'password required'; exit; } $profile = new Profile(); $profile->fullname = $fullname; $profile->email = $email; $profile->created = common_sql_now(); $profile_id = $profile->insert(); if (!$profile_id) { common_log_db_error($profile, 'INSERT', __FILE__); exit; } $profile_role = new Profile_role(); $profile_role->profile_id = $profile_id; $profile_role->role = Profile_role::SUPERADMIN; $profile_role->created = common_sql_now(); $profile_role->insert(); $pnew = Profile::staticGet($profile_id); $orig = clone $pnew; $pnew->password = common_munge_password($password, $profile_id); $pnew->update($orig); echo "Done!";
$requestObject = json_decode($requestContent); // make sure form is filled out fully, to prevent db issues if (empty($requestObject->profileName) === true) { throw new InvalidArgumentException("Must chose a user name", 405); } if (empty($requestObject->profileEmail) === true) { throw new InvalidArgumentException("Must use a valid email", 405); } if (empty($requestObject->profilePassword) === true) { throw new InvalidArgumentException("password cannot be empty", 405); } // sanitize the email $profileSalt = bin2hex(openssl_random_pseudo_bytes(32)); $profileEmailActivation = bin2hex(openssl_random_pseudo_bytes(8)); // create the hash $profileHash = hash_pbkdf2("sha512", $requestObject->profilePassword, $profileSalt, 262144, 128); // create a new Profile, and insert into db $profile = new Profile(null, $requestObject->profileEmail, $profileEmailActivation, $profile->insert($pdo)); $reply->message = "A new Profile has been created"; } else { throw new InvalidArgumentException("Invalid HTTP method"); } } catch (\Exception $exception) { $reply->status = $exception->getCode(); $reply->message = $exception->getMessage(); } catch (\TypeError $typeError) { $reply->status = $typeError->getCode(); $reply->message = $typeError->getMessage(); } header("Content-type: application/json"); echo json_encode($reply);
function linkback_profile($entry, $mf2, $response, $target) { if (isset($entry['properties']['author']) && isset($entry['properties']['author'][0]['properties'])) { $author = $entry['properties']['author'][0]['properties']; } else { $author = linkback_hcard($mf2, $response->getEffectiveUrl()); } if (!$author) { $author = array('name' => array($entry['name'])); } if (!$author['url']) { $author['url'] = array($response->getEffectiveUrl()); } $user = User::getKV('uri', $author['url'][0]); if ($user instanceof User) { common_log(LOG_INFO, "Linkback: ignoring linkback from local user: {$url}"); return true; } try { $profile = Profile::fromUri($author['url'][0]); } catch (UnknownUriException $ex) { } if (!$profile instanceof Profile) { $profile = Profile::getKV('profileurl', $author['url'][0]); } if (!$profile instanceof Profile) { $profile = new Profile(); $profile->profileurl = $author['url'][0]; $profile->fullname = $author['name'][0]; $profile->nickname = $author['nickname'] ? $author['nickname'][0] : str_replace(' ', '', $author['name'][0]); $profile->created = common_sql_now(); $profile->insert(); } return array($profile, $author); }
function saveRemoteProfile(&$req) { # FIXME: we should really do this when the consumer comes # back for an access token. If they never do, we've got stuff in a # weird state. $nickname = $req->get_parameter('omb_listenee_nickname'); $fullname = $req->get_parameter('omb_listenee_fullname'); $profile_url = $req->get_parameter('omb_listenee_profile'); $homepage = $req->get_parameter('omb_listenee_homepage'); $bio = $req->get_parameter('omb_listenee_bio'); $location = $req->get_parameter('omb_listenee_location'); $avatar_url = $req->get_parameter('omb_listenee_avatar'); $listenee = $req->get_parameter('omb_listenee'); $remote = Remote_profile::staticGet('uri', $listenee); if ($remote) { $exists = true; $profile = Profile::staticGet($remote->id); $orig_remote = clone $remote; $orig_profile = clone $profile; } else { $exists = false; $remote = new Remote_profile(); $remote->uri = $listenee; $profile = new Profile(); } $profile->nickname = $nickname; $profile->profileurl = $profile_url; if (!is_null($fullname)) { $profile->fullname = $fullname; } if (!is_null($homepage)) { $profile->homepage = $homepage; } if (!is_null($bio)) { $profile->bio = $bio; } if (!is_null($location)) { $profile->location = $location; } if ($exists) { $profile->update($orig_profile); } else { $profile->created = DB_DataObject_Cast::dateTime(); # current time $id = $profile->insert(); if (!$id) { return false; } $remote->id = $id; } if ($exists) { if (!$remote->update($orig_remote)) { return false; } } else { $remote->created = DB_DataObject_Cast::dateTime(); # current time if (!$remote->insert()) { return false; } } if ($avatar_url) { if (!$this->addAvatar($profile, $avatar_url)) { return false; } } $user = common_current_user(); $datastore = omb_oauth_datastore(); $consumer = $this->getConsumer($datastore, $req); $token = $this->getToken($datastore, $req, $consumer); $sub = new Subscription(); $sub->subscriber = $user->id; $sub->subscribed = $remote->id; $sub->token = $token->key; # NOTE: request token, not valid for use! $sub->created = DB_DataObject_Cast::dateTime(); # current time if (!$sub->insert()) { return false; } return true; }
<?php require_once "/etc/apache2/capstone-mysql/encrypted-config.php"; require_once "profile.php"; $pdo = connectToEncryptedMySQL("/etc/apache2/data-design/vhooker.ini"); $profile = new Profile(null, 1, "this is from PHP"); $profile->insert($pdo); $profile->setProfile("now I changed the message"); $profile->update($pdo); $profile->delete($pdo);
function ensureProfile($user) { // check to see if there's already a profile for this user $profileurl = 'http://twitter.com/' . $user->screen_name; $profile = $this->getProfileByUrl($user->screen_name, $profileurl); if (!empty($profile)) { common_debug($this->name() . " - Profile for {$profile->nickname} found."); // Check to see if the user's Avatar has changed $this->checkAvatar($user, $profile); return $profile; } else { common_debug($this->name() . ' - Adding profile and remote profile ' . "for Twitter user: {$profileurl}."); $profile = new Profile(); $profile->query("BEGIN"); $profile->nickname = $user->screen_name; $profile->fullname = $user->name; $profile->homepage = $user->url; $profile->bio = $user->description; $profile->location = $user->location; $profile->profileurl = $profileurl; $profile->created = common_sql_now(); try { $id = $profile->insert(); } catch (Exception $e) { common_log(LOG_WARNING, $this->name() . ' Couldn\'t insert profile - ' . $e->getMessage()); } if (empty($id)) { common_log_db_error($profile, 'INSERT', __FILE__); $profile->query("ROLLBACK"); return false; } // check for remote profile $remote_pro = Remote_profile::staticGet('uri', $profileurl); if (empty($remote_pro)) { $remote_pro = new Remote_profile(); $remote_pro->id = $id; $remote_pro->uri = $profileurl; $remote_pro->created = common_sql_now(); try { $rid = $remote_pro->insert(); } catch (Exception $e) { common_log(LOG_WARNING, $this->name() . ' Couldn\'t save remote profile - ' . $e->getMessage()); } if (empty($rid)) { common_log_db_error($profile, 'INSERT', __FILE__); $profile->query("ROLLBACK"); return false; } } $profile->query("COMMIT"); $this->saveAvatars($user, $id); return $profile; } }
function handle($args) { parent::handle($args); if (common_logged_in()) { $this->clientError(_('You can use the local subscription!')); return; } $omb = $_SESSION['oauth_authorization_request']; if (!$omb) { $this->clientError(_('Not expecting this response!')); return; } common_debug('stored request: ' . print_r($omb, true), __FILE__); common_remove_magic_from_request(); $req = OAuthRequest::from_request(); $token = $req->get_parameter('oauth_token'); # I think this is the success metric if ($token != $omb['token']) { $this->clientError(_('Not authorized.')); return; } $version = $req->get_parameter('omb_version'); if ($version != OMB_VERSION_01) { $this->clientError(_('Unknown version of OMB protocol.')); return; } $nickname = $req->get_parameter('omb_listener_nickname'); if (!$nickname) { $this->clientError(_('No nickname provided by remote server.')); return; } $profile_url = $req->get_parameter('omb_listener_profile'); if (!$profile_url) { $this->clientError(_('No profile URL returned by server.')); return; } if (!Validate::uri($profile_url, array('allowed_schemes' => array('http', 'https')))) { $this->clientError(_('Invalid profile URL returned by server.')); return; } if ($profile_url == common_local_url('showstream', array('nickname' => $nickname))) { $this->clientError(_('You can use the local subscription!')); return; } common_debug('listenee: "' . $omb['listenee'] . '"', __FILE__); $user = User::staticGet('nickname', $omb['listenee']); if (!$user) { $this->clientError(_('User being listened to doesn\'t exist.')); return; } $other = User::staticGet('uri', $omb['listener']); if ($other) { $this->clientError(_('You can use the local subscription!')); return; } $fullname = $req->get_parameter('omb_listener_fullname'); $homepage = $req->get_parameter('omb_listener_homepage'); $bio = $req->get_parameter('omb_listener_bio'); $location = $req->get_parameter('omb_listener_location'); $avatar_url = $req->get_parameter('omb_listener_avatar'); list($newtok, $newsecret) = $this->access_token($omb); if (!$newtok || !$newsecret) { $this->clientError(_('Couldn\'t convert request tokens to access tokens.')); return; } # XXX: possible attack point; subscribe and return someone else's profile URI $remote = Remote_profile::staticGet('uri', $omb['listener']); if ($remote) { $exists = true; $profile = Profile::staticGet($remote->id); $orig_remote = clone $remote; $orig_profile = clone $profile; # XXX: compare current postNotice and updateProfile URLs to the ones # stored in the DB to avoid (possibly...) above attack } else { $exists = false; $remote = new Remote_profile(); $remote->uri = $omb['listener']; $profile = new Profile(); } $profile->nickname = $nickname; $profile->profileurl = $profile_url; if (!is_null($fullname)) { $profile->fullname = $fullname; } if (!is_null($homepage)) { $profile->homepage = $homepage; } if (!is_null($bio)) { $profile->bio = $bio; } if (!is_null($location)) { $profile->location = $location; } if ($exists) { $profile->update($orig_profile); } else { $profile->created = DB_DataObject_Cast::dateTime(); # current time $id = $profile->insert(); if (!$id) { $this->serverError(_('Error inserting new profile')); return; } $remote->id = $id; } if ($avatar_url) { if (!$this->add_avatar($profile, $avatar_url)) { $this->serverError(_('Error inserting avatar')); return; } } $remote->postnoticeurl = $omb['post_notice_url']; $remote->updateprofileurl = $omb['update_profile_url']; if ($exists) { if (!$remote->update($orig_remote)) { $this->serverError(_('Error updating remote profile')); return; } } else { $remote->created = DB_DataObject_Cast::dateTime(); # current time if (!$remote->insert()) { $this->serverError(_('Error inserting remote profile')); return; } } if ($user->hasBlocked($profile)) { $this->clientError(_('That user has blocked you from subscribing.')); return; } $sub = new Subscription(); $sub->subscriber = $remote->id; $sub->subscribed = $user->id; $sub_exists = false; if ($sub->find(true)) { $sub_exists = true; $orig_sub = clone $sub; } else { $sub_exists = false; $sub->created = DB_DataObject_Cast::dateTime(); # current time } $sub->token = $newtok; $sub->secret = $newsecret; if ($sub_exists) { $result = $sub->update($orig_sub); } else { $result = $sub->insert(); } if (!$result) { common_log_db_error($sub, $sub_exists ? 'UPDATE' : 'INSERT', __FILE__); $this->clientError(_('Couldn\'t insert new subscription.')); return; } # Notify user, if necessary mail_subscribe_notify_profile($user, $profile); # Clear the data unset($_SESSION['oauth_authorization_request']); # If we show subscriptions in reverse chron order, this should # show up close to the top of the page common_redirect(common_local_url('subscribers', array('nickname' => $user->nickname))); }
<?php /** * Created by PhpStorm. * User: OldManVin * Date: 1/22/2016 * Time: 12:01 PM */ require_once "/etc/apache2/capstone-mysql/encrypted -config.php"; $pdo = connectToEncryptedMySQL("/ect/apache2/data-design/dfontaine1/ini"); require_once "/etc/apache2/capstone-mysql/encrypted-config.php"; require_once "your-class-file.php"; //now use the PDO object normally $tweet = new Profile(null, 1, "this is from php"); $tweet->insert($pdo); $tweet->setProfile("now i change the message"); $tweet->update($pdo); $tweet->delete($pdo);
function initGroupProfileId() { printfnq("Ensuring all User_group entries have a Profile and profile_id..."); $group = new User_group(); $group->whereAdd('NOT EXISTS (SELECT id FROM profile WHERE id = user_group.profile_id)'); $group->find(); while ($group->fetch()) { try { // We must create a new, incrementally assigned profile_id $profile = new Profile(); $profile->nickname = $group->nickname; $profile->fullname = $group->fullname; $profile->profileurl = $group->mainpage; $profile->homepage = $group->homepage; $profile->bio = $group->description; $profile->location = $group->location; $profile->created = $group->created; $profile->modified = $group->modified; $profile->query('BEGIN'); $id = $profile->insert(); if (empty($id)) { $profile->query('ROLLBACK'); throw new Exception('Profile insertion failed, profileurl: ' . $profile->profileurl); } $group->query("UPDATE user_group SET profile_id={$id} WHERE id={$group->id}"); $profile->query('COMMIT'); $profile->free(); } catch (Exception $e) { printfv("Error initializing Profile for group {$group->nickname}:" . $e->getMessage()); } } printfnq("DONE.\n"); }
/** * Look up, and if necessary create, an Ostatus_profile for the remote * entity with the given webfinger address. * This should never return null -- you will either get an object or * an exception will be thrown. * * @param string $addr webfinger address * @return Ostatus_profile * @throws Exception on error conditions * @throws OStatusShadowException if this reference would obscure a local user/group */ public static function ensureWebfinger($addr) { // First, try the cache $uri = self::cacheGet(sprintf('ostatus_profile:webfinger:%s', $addr)); if ($uri !== false) { if (is_null($uri)) { // Negative cache entry // TRANS: Exception. throw new Exception(_m('Not a valid webfinger address.')); } $oprofile = Ostatus_profile::getKV('uri', $uri); if ($oprofile instanceof Ostatus_profile) { return $oprofile; } } // Try looking it up $oprofile = Ostatus_profile::getKV('uri', Discovery::normalize($addr)); if ($oprofile instanceof Ostatus_profile) { self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri()); return $oprofile; } // Now, try some discovery $disco = new Discovery(); try { $xrd = $disco->lookup($addr); } catch (Exception $e) { // Save negative cache entry so we don't waste time looking it up again. // @todo FIXME: Distinguish temporary failures? self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null); // TRANS: Exception. throw new Exception(_m('Not a valid webfinger address.')); } $hints = array_merge(array('webfinger' => $addr), DiscoveryHints::fromXRD($xrd)); // If there's an Hcard, let's grab its info if (array_key_exists('hcard', $hints)) { if (!array_key_exists('profileurl', $hints) || $hints['hcard'] != $hints['profileurl']) { $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']); $hints = array_merge($hcardHints, $hints); } } // If we got a feed URL, try that $feedUrl = null; if (array_key_exists('feedurl', $hints)) { $feedUrl = $hints['feedurl']; try { common_log(LOG_INFO, "Discovery on acct:{$addr} with feed URL " . $hints['feedurl']); $oprofile = self::ensureFeedURL($hints['feedurl'], $hints); self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri()); return $oprofile; } catch (Exception $e) { common_log(LOG_WARNING, "Failed creating profile from feed URL '{$feedUrl}': " . $e->getMessage()); // keep looking } } // If we got a profile page, try that! $profileUrl = null; if (array_key_exists('profileurl', $hints)) { $profileUrl = $hints['profileurl']; try { common_log(LOG_INFO, "Discovery on acct:{$addr} with profile URL {$profileUrl}"); $oprofile = self::ensureProfileURL($hints['profileurl'], $hints); self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri()); return $oprofile; } catch (OStatusShadowException $e) { // We've ended up with a remote reference to a local user or group. // @todo FIXME: Ideally we should be able to say who it was so we can // go back and refer to it the regular way throw $e; } catch (Exception $e) { common_log(LOG_WARNING, "Failed creating profile from profile URL '{$profileUrl}': " . $e->getMessage()); // keep looking // // @todo FIXME: This means an error discovering from profile page // may give us a corrupt entry using the webfinger URI, which // will obscure the correct page-keyed profile later on. } } // XXX: try hcard // XXX: try FOAF if (array_key_exists('salmon', $hints)) { $salmonEndpoint = $hints['salmon']; // An account URL, a salmon endpoint, and a dream? Not much to go // on, but let's give it a try $uri = 'acct:' . $addr; $profile = new Profile(); $profile->nickname = self::nicknameFromUri($uri); $profile->created = common_sql_now(); if (!is_null($profileUrl)) { $profile->profileurl = $profileUrl; } $profile_id = $profile->insert(); if ($profile_id === false) { common_log_db_error($profile, 'INSERT', __FILE__); // TRANS: Exception. %s is a webfinger address. throw new Exception(sprintf(_m('Could not save profile for "%s".'), $addr)); } $oprofile = new Ostatus_profile(); $oprofile->uri = $uri; $oprofile->salmonuri = $salmonEndpoint; $oprofile->profile_id = $profile_id; $oprofile->created = common_sql_now(); if (!is_null($feedUrl)) { $oprofile->feeduri = $feedUrl; } $result = $oprofile->insert(); if ($result === false) { $profile->delete(); common_log_db_error($oprofile, 'INSERT', __FILE__); // TRANS: Exception. %s is a webfinger address. throw new Exception(sprintf(_m('Could not save OStatus profile for "%s".'), $addr)); } self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri()); return $oprofile; } // TRANS: Exception. %s is a webfinger address. throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'), $addr)); }
/** * Register a new user account and profile and set up default subscriptions. * If a new-user welcome message is configured, this will be sent. * * @param array $fields associative array of optional properties * string 'bio' * string 'email' * bool 'email_confirmed' pass true to mark email as pre-confirmed * string 'fullname' * string 'homepage' * string 'location' informal string description of geolocation * float 'lat' decimal latitude for geolocation * float 'lon' decimal longitude for geolocation * int 'location_id' geoname identifier * int 'location_ns' geoname namespace to interpret location_id * string 'nickname' REQUIRED * string 'password' (may be missing for eg OpenID registrations) * string 'code' invite code * ?string 'uri' permalink to notice; defaults to local notice URL * @return User object * @throws Exception on failure */ static function register(array $fields) { // MAGICALLY put fields into current scope extract($fields); $profile = new Profile(); if (!empty($email)) { $email = common_canonical_email($email); } // Normalize _and_ check whether it is in use. Throw NicknameException on failure. $profile->nickname = Nickname::normalize($nickname, true); $profile->profileurl = common_profile_url($profile->nickname); if (!empty($fullname)) { $profile->fullname = $fullname; } if (!empty($homepage)) { $profile->homepage = $homepage; } if (!empty($bio)) { $profile->bio = $bio; } if (!empty($location)) { $profile->location = $location; $loc = Location::fromName($location); if (!empty($loc)) { $profile->lat = $loc->lat; $profile->lon = $loc->lon; $profile->location_id = $loc->location_id; $profile->location_ns = $loc->location_ns; } } $profile->created = common_sql_now(); $user = new User(); $user->nickname = $profile->nickname; $invite = null; // Users who respond to invite email have proven their ownership of that address if (!empty($code)) { $invite = Invitation::getKV($code); if ($invite instanceof Invitation && $invite->address && $invite->address_type == 'email' && $invite->address == $email) { $user->email = $invite->address; } } if (isset($email_confirmed) && $email_confirmed) { $user->email = $email; } // Set default-on options here, otherwise they'll be disabled // initially for sites using caching, since the initial encache // doesn't know about the defaults in the database. $user->emailnotifysub = 1; $user->emailnotifynudge = 1; $user->emailnotifymsg = 1; $user->emailnotifyattn = 1; $user->emailmicroid = 1; $user->emailpost = 1; $user->jabbermicroid = 1; $user->created = common_sql_now(); if (Event::handle('StartUserRegister', array($profile))) { $profile->query('BEGIN'); $id = $profile->insert(); if ($id === false) { common_log_db_error($profile, 'INSERT', __FILE__); $profile->query('ROLLBACK'); // TRANS: Profile data could not be inserted for some reason. throw new ServerException(_m('Could not insert profile data for new user.')); } $user->id = $id; if (!empty($uri)) { $user->uri = $uri; } else { $user->uri = common_user_uri($user); } if (!empty($password)) { // may not have a password for OpenID users $user->password = common_munge_password($password, $id); } $result = $user->insert(); if ($result === false) { common_log_db_error($user, 'INSERT', __FILE__); $profile->query('ROLLBACK'); // TRANS: User data could not be inserted for some reason. throw new ServerException(_m('Could not insert user data for new user.')); } // Everyone is subscribed to themself $subscription = new Subscription(); $subscription->subscriber = $user->id; $subscription->subscribed = $user->id; $subscription->created = $user->created; $result = $subscription->insert(); if (!$result) { common_log_db_error($subscription, 'INSERT', __FILE__); $profile->query('ROLLBACK'); // TRANS: Subscription data could not be inserted for some reason. throw new ServerException(_m('Could not insert subscription data for new user.')); } // Mark that this invite was converted if (!empty($invite)) { $invite->convert($user); } if (!empty($email) && !$user->email) { $confirm = new Confirm_address(); $confirm->code = common_confirmation_code(128); $confirm->user_id = $user->id; $confirm->address = $email; $confirm->address_type = 'email'; $result = $confirm->insert(); if (!$result) { common_log_db_error($confirm, 'INSERT', __FILE__); $profile->query('ROLLBACK'); // TRANS: Email confirmation data could not be inserted for some reason. throw new ServerException(_m('Could not insert email confirmation data for new user.')); } } if (!empty($code) && $user->email) { $user->emailChanged(); } // Default system subscription $defnick = common_config('newuser', 'default'); if (!empty($defnick)) { $defuser = User::getKV('nickname', $defnick); if (empty($defuser)) { common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick), __FILE__); } else { Subscription::ensureStart($profile, $defuser->getProfile()); } } $profile->query('COMMIT'); if (!empty($email) && !$user->email) { mail_confirm_address($user, $confirm->code, $profile->nickname, $email); } // Welcome message $welcome = common_config('newuser', 'welcome'); if (!empty($welcome)) { $welcomeuser = User::getKV('nickname', $welcome); if (empty($welcomeuser)) { common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick), __FILE__); } else { $notice = Notice::saveNew($welcomeuser->id, sprintf(_('Welcome to %1$s, @%2$s!'), common_config('site', 'name'), $user->nickname), 'system'); } } Event::handle('EndUserRegister', array($profile)); } if (!$user instanceof User) { throw new ServerException('User could not be registered. Probably an event hook that failed.'); } return $user; }