function Websites_before_Streams_Stream_save_Websites_article($params) { $stream = $params['stream']; $modifiedFields = $params['modifiedFields']; if ($stream->wasRetrieved()) { return; } $user = new Users_User(); if (empty($stream->userId) and empty($modifiedFields['userId'])) { if ($liu = Users::loggedInUser()) { $stream->userId = $liu->id; } else { throw new Q_Exception_RequiredField(array('field' => 'userId')); } } $user->id = $stream->userId; if (!$user->retrieve()) { throw new Users_Exception_NoSuchUser(); } $title = Streams::displayName($user, array('fullAccess' => true)); if (isset($title)) { $stream->title = $title; } $stream->icon = $user->iconUrl(); $s = Streams::fetchOne($user->id, $user->id, "Streams/user/icon"); if (!$s or !($sizes = $s->getAttribute('sizes', null))) { $sizes = Q_Config::expect('Users', 'icon', 'sizes'); sort($sizes); } $stream->setAttribute('sizes', $sizes); }
function users_register_post() { $u = new Users_User(); $u->email_address = $_REQUEST['email_address']; if ($u->retrieve()) { $key = 'this email'; throw new Users_Exception_AlreadyVerified(compact('key')); } // Insert a new user into the database $user = new Users_User(); $user->username = $_REQUEST['username']; if ($user->retrieve()) { throw new Users_Exception_UsernameExists(array(), array('username')); } $user->icon = 'default'; $user->password_hash = ''; $user->save(); // sets the user's id // Import the user's icon if (isset($_REQUEST['icon'])) { $folder = 'user_id_' . $user->id; users_register_post_download($_REQUEST['icon'], $folder, 80); users_register_post_download($_REQUEST['icon'], $folder, 40); $user->icon = $folder; $user->save(); } // Add an email to the user, that they'll have to verify $user->addEmail($_REQUEST['email_address']); Users::setLoggedInUser($user); Users::$cache['user'] = $user; }
function Users_0_8_3_Users_mysql() { $app = Q_Config::expect('Q', 'app'); $appRootUrl = Q_Config::expect('Q', 'web', 'appRootUrl'); $user = new Users_User(); $user->id = $app; $user->username = $app; $user->url = $appRootUrl; $user->icon = "{$appRootUrl}/img/icon"; $user->signedUpWith = 'none'; $user->save(); }
function Users_0_8_3_Users_mysql() { $app = Q_Config::expect('Q', 'app'); $communityId = Users::communityId(); $communityName = Q_Config::get('Users', 'community', 'name', $app); $appRootUrl = Q_Config::expect('Q', 'web', 'appRootUrl'); $user = new Users_User(); $user->id = $communityId; $user->username = $communityName; $user->url = $appRootUrl; $user->icon = "{$appRootUrl}/img/icon"; $user->signedUpWith = 'none'; $user->save(); }
function users_activate_post() { $email_address = Pie_Dispatcher::uri()->email_address; $mobile_number = Pie_Dispatcher::uri()->mobile_number; $email = null; $mobile = null; if ($email_address) { $email = new Users_Email(); $email->address = $email_address; // NOTE: not sharded by user_id if (!$email->retrieve()) { throw new Pie_Exception_MissingRow(array('table' => 'email', 'criteria' => "address = {$email_address}")); } $user = new Users_User(); $user->id = $email->user_id; if (!$user->retrieve()) { throw new Pie_Exception_MissingRow(array('table' => 'user', 'criteria' => 'id = ' . $user->id)); } if ($email->activation_code != $_REQUEST['code']) { throw new Pie_Exception("The activation code does not match.", 'code'); } $user->setEmailAddress($email->address); // may throw exception $type = "email address"; } if ($mobile_number) { $mobile = new Users_Mobile(); $mobile->number = $mobile_number; // NOTE: not sharded by user_id if (!$mobile->retrieve()) { throw new Pie_Exception_MissingRow(array('table' => 'mobile phone', 'criteria' => "number = {$mobile_number}")); } $user = new Users_User(); $user->id = $mobile->user_id; if (!$user->retrieve()) { throw new Pie_Exception_MissingRow(array('table' => 'user', 'criteria' => 'id = ' . $user->id)); } if ($mobile->activation_code != $_REQUEST['code']) { throw new Pie_Exception("The activation code does not match.", 'code'); } $user->setMobileNumber($mobile->number); // may throw exception $type = "mobile number"; } if ($type) { Pie_Response::addNotice("users/activate", "Your {$type} has been activated."); } Users::$cache['user'] = $user; }
function Users_resend_post() { $identifier = Users::requestedIdentifier($type); if ($type !== 'email' and $type !== 'mobile') { throw new Q_Exception("Expecting a valid email or mobile number", array('identifier', 'emailAddress', 'mobileNumber')); } if ($type === 'email') { $thing = 'email address'; $field = 'emailAddress'; $row = new Users_Email(); $row->address = $identifier; } else { if ($type === 'mobile') { $thing = 'mobile number'; $field = 'mobileNumber'; $row = new Users_Mobile(); $row->number = $identifier; } else { throw new Q_Exception("Expecting a valid email or mobile number", array('identifier', 'emailAddress', 'mobileNumber')); } } if ($row->retrieve()) { $userId = $row->userId; } else { if ($ui = Users::identify($type, $identifier, 'future')) { $userId = $ui->userId; } else { throw new Q_Exception("That {$thing} was not found in the system", array('identifier', $field)); } } $user = new Users_User(); $user->id = $userId; if (!$user->retrieve()) { throw new Q_Exception("No user corresponds to that {$thing}", array('identifier', $field)); } if ($logged_in_user = Users::loggedInUser() and $logged_in_user->id != $user->id) { throw new Q_Exception("That {$thing} belongs to someone else", array('identifier', $field)); } if ($type === 'email') { $existing = $user->addEmail($identifier); } else { $existing = $user->addMobile($identifier); } if ($existing) { $existing->resendActivationMessage(); } Users::$cache['user'] = $user; }
function Streams_0_8_8_Streams_mysql() { $communityId = Users::communityId(); $user = Users_User::fetch($communityId, true); Streams::create($communityId, $communityId, 'Streams/resource', array('name' => 'Streams/invitations', 'readLevel' => 0, 'writeLevel' => 0, 'adminLevel' => 0)); Streams_Access::insert(array('publisherId' => $communityId, 'streamName' => "Streams/invitations", 'ofUserId' => '', 'grantedByUserId' => null, 'ofContactLabel' => "{$app}/admins", 'readLevel' => Streams::$READ_LEVEL['messages'], 'writeLevel' => Streams::$WRITE_LEVEL['close'], 'adminLevel' => Streams::$ADMIN_LEVEL['invite']))->execute(); }
function Streams_after_Q_objects() { $user = Users::loggedInUser(); if (!$user) { return; } $invite = Streams::$followedInvite; if (!$invite) { return; } $displayName = $user->displayName(); if ($displayName) { return; } $stream = new Streams_Stream(); $stream->publisherId = $invite->publisherId; $stream->name = $invite->streamName; if (!$stream->retrieve()) { throw new Q_Exception_MissingRow(array('table' => 'stream', 'criteria' => 'with that name'), 'streamName'); } // Prepare the complete invite dialog $invitingUser = Users_User::fetch($invite->invitingUserId); list($relations, $related) = Streams::related($user->id, $stream->publisherId, $stream->name, false); $params = array('displayName' => null, 'action' => 'Streams/basic', 'icon' => $user->iconUrl(), 'token' => $invite->token, 'user' => array('icon' => $invitingUser->iconUrl(), 'displayName' => $invitingUser->displayName(array('fullAccess' => true))), 'stream' => $stream->exportArray(), 'relations' => Db::exportArray($relations), 'related' => Db::exportArray($related)); $config = Streams_Stream::getConfigField($stream->type, 'invite', array()); $defaults = Q::ifset($config, 'dialog', array()); $tree = new Q_Tree($defaults); if ($tree->merge($params)) { $dialogData = $tree->getAll(); if ($dialogData) { Q_Response::setScriptData('Q.plugins.Streams.invite.dialog', $dialogData); Q_Response::addTemplate('Streams/invite/complete'); } } }
/** * This tool renders a user avatar * * @param {array} $options An associative array of parameters, containing: * @param {boolean} [$options.userId] * "userId" => The user's id. Defaults to id of the logged-in user, if any. * @param {boolean} [$options.icon] * "icon" => Optional. Render icon before the username. * @param {boolean} [$options.iconAttributes] * "iconAttributes" => Optional. Array of attributes to render for the icon. * @param {boolean} [$options.editable] * "editable" => Optional. Whether to provide an interface for editing the user's info. Can be array containing "icon", "name". * @param {array} [$options.inplaces] Additional fields to pass to the child Streams/inplace tools, if any * @param {boolean} [$options.renderOnClient] * If true, only the html container is rendered, so the client will do the rest. */ function Users_avatar_tool($options) { $defaults = array('icon' => false, 'editable' => false); $options = array_merge($defaults, $options); if (empty($options['userId'])) { $user = Users::loggedInUser(); $options['userId'] = $user->id; } else { $user = Users_User::fetch($options['userId']); } Q_Response::addStylesheet('plugins/Q/css/Q.css'); Q_Response::setToolOptions($options); if (!empty($options['renderOnClient'])) { return ''; } if (!$user) { return ''; } $user->addPreloaded(); $p = $options; $p['userId'] = $user->id; Q_Response::setToolOptions($p); $result = ''; $icon = $options['icon']; if ($icon) { if ($icon === true) { $icon = Q_Config::get('Users', 'icon', 'defaultSize', 40); } $attributes = isset($options['iconAttributes']) ? $options['iconAttributes'] : array(); $attributes['class'] = isset($attributes['class']) ? $attributes['class'] . ' Users_avatar_icon' : 'Users_avatar_icon'; $result .= Q_Html::img($user->iconUrl($icon), 'user icon', $attributes); } $result .= '<span class="Users_avatar_name">' . $user->username . '</span>'; return $result; }
function Users_identifier_post() { $userId = Q::ifset($_REQUEST, 'userId', null); if (isset($userId)) { $user = Users_User::fetch($userId, true); if ($user->emailAddress or $user->mobileNumber) { throw new Q_Exception("This user is already able to log in and set their own email and mobile number."); } } else { $user = Users::loggedInUser(true); } $app = Q_Config::expect('Q', 'app'); $fields = array(); $identifier = Users::requestedIdentifier($type); if (!$type) { throw new Q_Exception("a valid email address or mobile number is required", array('identifier', 'mobileNumber', 'emailAddress')); } if ($type === 'email') { $subject = Q_Config::get('Users', 'transactional', 'identifier', 'subject', "Welcome! Verify your email address."); $view = Q_Config::get('Users', 'transactional', 'identifier', 'body', 'Users/email/addEmail.php'); $user->addEmail($identifier, $subject, $view, array(), array('html' => true)); } else { if ($type === 'mobile') { $view = Q_Config::get('Users', 'transactional', 'identifier', 'sms', 'Users/sms/addMobile.php'); $user->addMobile($identifier, $view); } } }
/** * Add contact with one or more labels * @method addContact * @static * @param {string} $userId * The id of the user whose contact will be added * @param {string|array} $label * The label of the contact. This can be a string or an array of strings, in which case * multiple contact rows are saved. * @param {string} $contactUserId * The id of the user who is the contact * @param {string} [$nickname=''] * Optional nickname to assign to the contact * @param {string} [$asUserId=null] The user to do this operation as. * Defaults to the logged-in user. Pass false to skip access checks. * @throws {Q_Exception_RequiredField} * if $label is missing * @return {array} Array of contacts that are saved */ static function addContact($userId, $label, $contactUserId, $nickname = '', $asUserId = null) { foreach (array('userId', 'label', 'contactUserId') as $field) { if (empty(${$field})) { throw new Q_Exception_RequiredField($field); } } Users::canManageContacts($asUserId, $userId, $label, true); Users_User::fetch($userId, true); Users_User::fetch($contactUserId, true); $labels = is_array($label) ? $label : array($label); // Insert the contacts one by one $contacts = array(); foreach ($labels as $l) { $contact = new Users_Contact(); $contact->userId = $userId; $contact->label = $l; $contact->contactUserId = $contactUserId; if (isset($nickname)) { $contact->nickname = $nickname; } $contact->save(true); $contacts[] = $contact; } /** * @event Users/Contact/addContact {after} * @param {string} contactUserId * @param {string} label * @param {array} contacts */ Q::event('Users/Contact/addContact', compact('contactUserId', 'label', 'contacts'), 'after'); return $contacts; }
function users_user_response_json() { $email_address = $_REQUEST['email_address']; // check our db $user = new Users_User(); $user->email_address = $email_address; if ($user->retrieve()) { return array('username' => $user->username, 'icon' => $user->icon); } $email_hash = md5(strtolower(trim($email_address))); $json = file_get_contents("http://www.gravatar.com/{$email_hash}.json"); $result = json_decode($json); if ($result) { return $result; } // otherwise, return default $email_parts = explode('@', $email_address, 2); return array("entry" => array(array("id" => "571", "hash" => "357a20e8c56e69d6f9734d23ef9517e8", "requestHash" => "357a20e8c56e69d6f9734d23ef9517e8", "profileUrl" => "http:\\/\\/gravatar.com\\/test", "preferredUsername" => $email_parts[0], "thumbnailUrl" => "http://gravatar.com/avatar/{$email_hash}?r=g&d=wavatar&s=80", "photos" => array(), "displayName" => "", "urls" => array()))); }
function Streams_invite_response_accountStatus() { if (empty($_REQUEST['token'])) { throw new Q_Exception("Missing token!"); } $invite = new Streams_Invite(); $invite->token = $_REQUEST['token']; if (!$invite->retrieve()) { throw new Q_Exception("Wrong token '" . $invite->token . "'!"); } $user = new Users_User(); $user->id = $invite->userId; if (!$user->retrieve()) { throw new Users_Exception_NoSuchUser(); } if (!empty($user->passphraseHash) || !empty($user->fb_uid)) { return "complete"; } }
function Streams_0_8_4_Streams_mysql() { $app = Q_Config::expect('Q', 'app'); $communityId = Users::communityId(); $user = Users_User::fetch($communityId); // avatar for the App user $avatar = new Streams_Avatar(); $avatar->toUserId = $communityId; $avatar->publisherId = $communityId; $avatar->username = $user->username; $avatar->firstName = Users::communityName(); $avatar->lastName = Users::communitySuffix(); $avatar->icon = $user->icon; $avatar->save(); $avatar2 = new Streams_Avatar(); $avatar2->copyFrom($avatar, null, false, true); $avatar->toUserId = ''; $avatar->save(); // access stream for managing app roles $stream = new Streams_Stream(); $stream->publisherId = Users::communityId(); $stream->name = 'Streams/contacts'; $stream->type = 'Streams/resource'; $stream->title = "Contacts"; $stream->setAttribute('prefixes', array("Users/", "{$app}/")); $stream->save(); // access stream for managing app roles $stream = new Streams_Stream(); $stream->publisherId = $app; $stream->name = 'Streams/labels'; $stream->type = 'Streams/resource'; $stream->title = "Labels"; $stream->setAttribute('prefixes', array("Users/", "{$app}/")); $stream->save(); // access for managing app contacts $access = new Streams_Access(); $access->publisherId = $communityId; $access->streamName = 'Streams/contacts'; $access->ofUserId = ''; $access->ofContactLabel = "{$app}/admins"; $access->readLevel = Streams::$READ_LEVEL['messages']; $access->writeLevel = Streams::$WRITE_LEVEL['edit']; $access->adminLevel = Streams::$ADMIN_LEVEL['manage']; $access->save(); // access for managing app roles $access = new Streams_Access(); $access->publisherId = $communityId; $access->streamName = 'Streams/labels'; $access->ofUserId = ''; $access->ofContactLabel = "{$app}/admins"; $access->readLevel = Streams::$READ_LEVEL['messages']; $access->writeLevel = Streams::$WRITE_LEVEL['edit']; $access->adminLevel = Streams::$ADMIN_LEVEL['manage']; $access->save(); }
/** * We are going to implement a subset of the OAuth 1.0a functionality for now, * and later we can expand it to match the full OAuth specification. */ function Users_authorize_response() { if (Q_Response::getErrors()) { Q_Dispatcher::showErrors(); } $response_type = 'token'; $token_type = 'bearer'; $client_id = $_REQUEST['client_id']; $state = $_REQUEST['state']; $skip = Q::ifset($_REQUEST, 'skip', false); $scope = Users_OAuth::requestedScope(true, $scopes); $client = Users_User::fetch($client_id, true); if (!$client) { throw new Q_Exception_MissingRow(array('table' => 'client user', 'criteria' => "id = '{$client_id}'"), 'client_id'); } if (empty($client->url)) { throw new Q_Exception("Client app needs to register url", 'client_id'); } $redirect_uri = Q::ifset($_REQUEST, 'redirect_uri', $client->url); $user = Users::loggedInUser(); $oa = null; if (isset(Users::$cache['oAuth'])) { $oa = Users::$cache['oAuth']; } else { if ($user) { $oa = new Users_OAuth(); $oa->client_id = $client_id; $oa->userId = $user->id; $oa->state = $state; $oa = $oa->retrieve(); } } $remaining = $scope; if ($oa and $oa->wasRetrieved()) { // User is logged in and already has a token for this client_id and state $paths = Q_Config::get('Users', 'authorize', 'clients', Q::app(), 'redirectPaths', false); $path = substr($redirect_uri, strlen($client->url) + 1); $p = array('response_type' => $response_type, 'token_type' => $token_type, 'access_token' => $oa->access_token, 'expires_in' => $oa->token_expires_seconds, 'scope' => implode(' ', $scope), 'state' => $oa->state); $p = Q_Utils::sign($p, 'Q.Users.oAuth'); // the redirect uri could be a native app url scheme $s = strpos($redirect_uri, '#') === false ? '#' : '&'; $redirect_uri = Q_Uri::from($redirect_uri . $s . http_build_query($p), false)->toUrl(); if (!Q::startsWith($redirect_uri, $client->url) or is_array($paths) and !in_array($path, $paths)) { throw new Users_Exception_Redirect(array('uri' => $redirect_uri)); } Q_Response::redirect($redirect_uri); return false; } $terms_label = Users::termsLabel('authorize'); Q_Response::setScriptData('Q.Users.authorize', compact('client_id', 'redirect_uri', 'scope', 'scopes', 'remaining', 'state', 'response_type', 'skip')); $content = Q::view('Users/content/authorize.php', compact('client', 'user', 'redirect_uri', 'scope', 'scopes', 'remaining', 'state', 'terms_label', 'response_type', 'skip')); Q_Response::setSlot('content', $content); Q_Response::setSlot('column0', $content); return true; }
function Streams_invited_response() { if (!($token = Q_Dispatcher::uri()->token)) { throw new Q_Exception_RequiredField(array('field' => 'token'), 'token'); } if (!($invite = Streams_Invite::fromToken($token))) { throw new Q_Exception_MissingRow(array('table' => 'invite', 'criteria' => "token: {$token}"), 'token'); } Users_User::fetch($invite->userId, true)->setVerified(); Q_Response::redirect($invite->appUrl . "?" . http_build_query(array('Q.Streams.token' => $token), null, '&')); }
function Q_response_dialogs() { // Here is where you would pre-generate various dialog elements // that you might show with Q.Dialogs.push if (!Users::roles(null, array('Websites/admins'))) { return ''; } $app = Q_Config::expect('Q', 'app'); $userIds = Users_Contact::select('contactUserId')->where(array('userId' => $app, 'label' => 'Websites/admins'))->fetchAll(PDO::FETCH_COLUMN, 'contactUserId'); $admins = Users_User::select('*')->where(array('id' => $userIds))->fetchDbRows(); return Q::view('Trump/dialogs/common.php', compact('admins')); }
function Users_user_response_users($params = array()) { $req = array_merge($_REQUEST, $params); Q_Valid::requireFields(array('userIds'), $req, true); $userIds = $req['userIds']; if (is_string($userIds)) { $userIds = explode(",", $userIds); } $fields = Q_Config::expect('Users', 'avatarFields'); $users = Users_User::select($fields)->where(array('id' => $userIds))->fetchDbRows(null, null, 'id'); return Q_Response::setSlot('users', Db::exportArray($users, array('asAvatar' => true))); }
function Users_activate_objects_mobile($mobileNumber, &$mobile) { Q_Response::removeNotice('Users/activate/objects'); $mobile = new Users_Mobile(); if (!Q_Valid::phone($mobileNumber, $normalized)) { return; } $mobile->number = $normalized; if (!$mobile->retrieve()) { throw new Q_Exception_MissingRow(array('table' => 'mobile phone', 'criteria' => "number {$normalized}")); } $user = Users::loggedInUser(); if ($user) { if ($user->id != $mobile->userId) { throw new Q_Exception("You are logged in as a different user. Please log out and click the link again."); } } else { $user = new Users_User(); $user->id = $mobile->userId; if (!$user->retrieve()) { throw new Q_Exception_MissingRow(array('table' => 'user', 'criteria' => 'id = ' . $user->id)); } } if ($mobile->activationCode != $_REQUEST['code']) { throw new Q_Exception("The activation code does not match. Did you get a newer message?", 'code'); } $timestamp = Users_Mobile::db()->getCurrentTimestamp(); if ($timestamp > Users_Mobile::db()->fromDateTime($mobile->activationCodeExpires)) { throw new Q_Exception("Activation code expired"); } if (Q_Request::method() !== 'POST' and empty($_REQUEST['p']) and isset($user->mobileNumber) and $user->mobileNumber == $mobile->number) { $displayName = Streams::displayName($user); Q_Response::setNotice('Users/activate/objects', "{$normalized} has already been activated for {$displayName}", true); return $user; } return $user; }
/** * Get a summary of streams related to the specified user's * "Streams/user/interests" stream * * @param {array} $_REQUEST * @param {string} [$_REQUEST.userId=loggedInUserId] userId * @return {void} */ function Streams_interest_response_interests() { $user = Users::loggedInUser(); $userId = Q::ifset($_REQUEST, 'userId', null); if ($user and $userId and $userId != $user->id and Q_Config::get('Streams', 'interests', 'allowClientQueries', false)) { throw new Q_Exception("Client queries are restricted, as per Streams/interests/allowClientQueries"); } if ($userId) { $user = Users_User::fetch($userId); } if (!$user) { throw new Users_Exception_NotLoggedIn(); } return Streams_Category::getRelatedTo($user->id, 'Streams/user/interests', 'Streams/interests'); }
function Broadcast_stream_response_content() { $publisherId = Streams::requestedPublisherId(true); $name = Streams::requestedName(true); $fields = Streams::requestedFields(); $user = Users::loggedInUser(); $userId = $user ? $user->id : 0; if (isset(Streams::$cache['stream'])) { $stream = Streams::$cache['stream']; } else { $streams = Streams::fetch($userId, $publisherId, $name, $fields, array('limit' => 30)); if (empty($streams)) { throw new Q_Exception("No such stream", 'name'); } $stream = reset($streams); } if ($publisherId != $userId and !$stream->testReadLevel('content')) { return "This belongs to someone else."; } if ($publisherId != $userId and !$stream->testReadLevel('content')) { throw new Users_Exception_NotAuthorized(); } $userIds = array(); $agreements = Broadcast_Agreement::select('userId')->where(array('publisherId' => $publisherId, 'streamName' => $name, 'platform' => 'facebook'))->fetchDbRows(); foreach ($agreements as $a) { $userIds[] = $a->userId; } if ($userIds) { $agreed_users = Users_User::select('*')->where(array('id' => $userIds))->fetchDbRows(); } else { $agreed_users = array(); } $src = 'Broadcast/widget?'; $q = array('publisherId' => $publisherId, 'streamName' => $name); foreach (array('css', 'button', 'checkmark', 'explanation') as $field) { if (isset($_REQUEST[$field])) { $q[$field] = $_REQUEST[$field]; } } $src .= http_build_query($q, null, '&'); $style = 'border: 0px;'; $code = Q_Html::tag('iframe', compact('src', 'style'), ''); Q_Response::addScript('plugins/Broadcast/js/Broadcast.js'); return Q::view('Broadcast/content/stream.php', compact('publisherId', 'name', 'fields', 'user', 'stream', 'agreed_users', 'code')); }
/** * We are going to implement a subset of the OAuth 1.0a functionality for now, * and later we can expand it to match the full OAuth specification. */ function Users_authorize_response() { if (Q_Response::getErrors()) { Q_Dispatcher::showErrors(); } $client_id = $_REQUEST['client_id']; $redirect_url = $_REQUEST['redirect_uri']; $state = $_REQUEST['state']; $client = Users_User::fetch($client_id); if (!$client) { throw new Q_Exception_MissingRow(array('table' => 'user', 'criteria' => "id = '{$client_id}'"), 'client_id'); } if (empty($client->url)) { throw new Q_Exception("Client app needs to register url", 'client_id'); } if (substr($redirect_url, 0, strlen($client->url)) !== $client->url) { throw new Q_Exception_WrongValue(array('field' => 'redirect_uri', 'range' => "a url prefixed by client user's url")); } $user = Users::loggedInUser(); $oa = null; if (isset(Users::$cache['oAuth'])) { $oa = Users::$cache['oAuth']; } else { if ($user) { $oa = new Users_OAuth(); $oa->client_id = $client_id; $oa->userId = $user->id; $oa->state = $state; $oa->retrieve(); } } if ($oa and $oa->wasRetrieved()) { // User is logged in and already has a token for this client_id and state $separator = strpos($redirect_url, '?') === false ? '?' : '&'; $url = $redirect_url . $separator . http_build_query(array('access_token' => $oa->access_token, 'token_type' => 'bearer', 'expires_in' => $oa->token_expires_seconds, 'scope' => 'user', 'state' => $oa->state)); Q_Response::redirect(Q_Uri::from($url, false)); return false; } $terms_label = Users::termsLabel('authorize'); $content = Q::view('Users/content/authorize.php', compact('client', 'redirect_url', 'user', 'state', 'terms_label')); Q_Response::setSlot('content', $content); Q_Response::setSlot('column0', $content); return true; }
/** * This tool renders ways to get in touch * * @param array [$options] An associative array of options, containing: * @param {string|Users_User} [$options.user] Required. The user object or id of the user exposing their primary identifiers for getting in touch. * @param {boolean|string} [$options.email] Pass true here to use the primary verified email address, if any. Or pass the string label for this button. * @param {string} [$options.emailSubject] Fill this if you want the email subject to be automatically filled in * @param {string} [$options.emailBody] Fill this if you want the email body to be automatically filled in * @param {boolean|string} [$options.sms] Pass true here to allow texting the primary verified mobile number, if any. Or pass the string label for this button. * @param {boolean|string} [$options.call] Pass true here to allow calling the primary verified mobile number, if any. Or pass the string label for this button. * @param {string} [$options.tag] The type of tag to use, defaults to "button" * @param {string} [$options.class] Any classes to add to the tags * @param {string} [$options.between] Any HTML to put between the elements */ function Users_getintouch_tool($options) { $tag = 'button'; $class = null; $between = ''; $user = null; $emailSubject = ''; $emailBody = ''; extract($options, EXTR_IF_EXISTS); if (!$user) { throw new Q_Exception_RequiredField(array('field' => 'user')); } if (is_string($user)) { $userId = $user; $user = Users_User::fetch($userId); if (!$user) { throw new Q_Exception_MissingRow(array('table' => 'user', 'criteria' => "id={$userId}")); } } $ways = array(); $email = $sms = $call = false; if (!empty($options['email']) and $user->emailAddress) { $email = is_string($options['email']) ? $options['email'] : "Email me"; $email = Q_Html::img("plugins/Users/img/email.png") . $email; $ways['email'] = Q_Html::tag($tag, array('id' => 'email', 'class' => $class), $email); Q_Response::setToolOptions(array('emailAddress' => Q_Utils::obfuscate($user->emailAddress), 'emailSubject' => Q_Utils::obfuscate($emailSubject), 'emailBody' => Q_Utils::obfuscate($emailBody))); } if (Q_Request::isMobile()) { $obfuscated_mobileNumber = Q_Utils::obfuscate($user->mobileNumber); if (!empty($options['sms']) and $user->mobileNumber) { $sms = is_string($options['sms']) ? $options['sms'] : "Text me"; $sms = Q_Html::img("plugins/Users/img/sms.png") . $sms; $ways['sms'] = Q_Html::tag($tag, array('id' => 'sms', 'class' => $class), $sms); Q_Response::setToolOptions(array('mobileNumber' => $obfuscated_mobileNumber)); } if (!empty($options['call']) and $user->mobileNumber) { $call = is_string($options['call']) ? $options['call'] : "Call me"; $call = Q_Html::img("plugins/Users/img/call.png") . $call; $ways['call'] = Q_Html::tag($tag, array('id' => 'call', 'class' => $class), $call); Q_Response::setToolOptions(array('mobileNumber' => $obfuscated_mobileNumber)); } } return implode($between, $ways); }
/** * Get the logged-in user's credits stream * @method userStream * @param {string} [$userId=null] * The id of the user for which the stream is obtained. Defaults to logged-in user. * @param {string} [$asUserId=null] * The id of the user who is trying to obtain it. Defaults to logged-in user. * @param {boolean} [$throwIfNotLoggedIn=false] * Whether to throw a Users_Exception_NotLoggedIn if no user is logged in. * @return {Streams_Stream|null} * @throws {Users_Exception_NotLoggedIn} If user is not logged in and * $throwIfNotLoggedIn is true */ static function userStream($userId = null, $asUserId = null, $throwIfNotLoggedIn = false) { if (!isset($userId)) { $user = Users::loggedInUser($throwIfNotLoggedIn); if (!$user) { return null; } } else { $user = Users_User::fetch($userId, true); } $userId = $user->id; $streamName = 'Awards/user/credits'; $stream = Streams::fetchOne($asUserId, $userId, $streamName); if (!$stream) { $amount = Q_Config::get('Awards', 'credits', 'amounts', 'Users/insertUser', self::DEFAULT_AMOUNT); $stream = Streams::create($userId, $userId, 'Awards/credits', array('name' => 'Awards/user/credits', 'title' => "Credits", 'icon' => 'plugins/Awards/img/credits.png', 'content' => '', 'attributes' => Q::json_encode(compact('amount')))); } return $stream; }
function Streams_0_8_7_Streams_mysql() { $app = Q_Config::expect('Q', 'app'); $user = Users_User::fetch($app, true); $simulated = array('row' => $user, 'inserted' => true, 'modifiedFields' => $user->fields); Q::event('Db/Row/Users_User/saveExecute', $simulated, 'after'); $stream = array('publisherId' => '', 'name' => "Streams/images/", 'type' => 'Streams/template', 'title' => 'Image Gallery', 'icon' => 'default', 'content' => '', 'attributes' => null, 'readLevel' => Streams::$READ_LEVEL['messages'], 'writeLevel' => Streams::$WRITE_LEVEL['close'], 'adminLevel' => Streams::$ADMIN_LEVEL['invite']); $access = array('publisherId' => '', 'streamName' => "Streams/images/", 'ofUserId' => '', 'grantedByUserId' => null, 'ofContactLabel' => "{$app}/admins", 'readLevel' => Streams::$READ_LEVEL['messages'], 'writeLevel' => Streams::$WRITE_LEVEL['close'], 'adminLevel' => Streams::$ADMIN_LEVEL['invite']); Streams_Stream::insert($stream)->execute(); Streams_Access::insert($access)->execute(); $stream['name'] = $access['streamName'] = 'Streams/image/'; $stream['icon'] = 'Streams/image'; $stream['title'] = 'Untitled Image'; Streams_Stream::insert($stream)->execute(); Streams_Access::insert($access)->execute(); $stream['name'] = $access['streamName'] = 'Streams/file/'; $stream['icon'] = 'files/_blank'; $stream['title'] = 'Untitled File'; Streams_Stream::insert($stream)->execute(); Streams_Access::insert($access)->execute(); }
/** * Check if user "owns" a stream template for a publisher * @method isOwner * @static * @param {string} $publisherId * @param {string} $type * @param {string|Users_User} [$user=null] * @return {boolean} */ static function isOwner($publisherId, $type, $user = null) { if (!isset($user)) { $user = Users::loggedInUser(); } else { if (is_string($user)) { $user = Users_User::fetch($user); } } if (!isset($user)) { return false; } // check if user is owner of stream template $stream = new Streams_Stream(); $stream->publisherId = $publisherId; $stream->name = $type . '/'; if (!$stream->retrieve()) { return false; } $stream->calculateAccess($user->id); return $stream->testAdminLevel('own'); }
/** * Adds contacts to the system. Fills the "contacts" slot. * @param {array} $_REQUEST * @param {string} $_REQUEST.label The label of the contact * @param {string} $_REQUEST.contactUserId The contactUserId of the contact * @param {string} [$_REQUEST.nickname] The nickname of the contact * @param {string} [$_REQUEST.userId=Users::loggedInUser(true)->id] You can override the user id, if another plugin adds a hook that allows you to do this */ function Users_contact_post($params = array()) { $req = array_merge($_REQUEST, $params); Q_Request::requireFields(array('label', 'contactUserId'), $req, true); $loggedInUserId = Users::loggedInUser(true)->id; $userId = Q::ifset($req, 'userId', $loggedInUserId); $contactUserId = $req['contactUserId']; $nickname = Q::ifset($req, 'nickname', null); $l = $req['label']; if ($userId !== $loggedInUserId) { Users_User::fetch($userId, true); } Users_User::fetch($contactUserId, true); Users::canManageContacts($loggedInUserId, $userId, $l, true); $label = new Users_Label(); $label->userId = $userId; $label->label = $l; if (!$label->retrieve()) { throw new Q_Exception_MissingRow(array('table' => 'Users_Label', 'criteria' => json_encode($label->fields))); } $contacts = Users_Contact::addContact($userId, $l, $contactUserId, $nickname); Q_Response::setSlot('contacts', Db::exportArray($contacts)); }
function Users_avatar_response($params) { $userIds = $batch = null; extract($_REQUEST, EXTR_IF_EXISTS); if ($batch) { $batch = json_decode($batch, true); if (!isset($batch)) { throw new Q_Exception_WrongValue(array('field' => 'batch', 'range' => '{userIds: [userId1, userId2, ...]}')); } if (!isset($batch['userIds'])) { throw new Q_Exception_RequiredField(array('field' => 'userIds')); } $userIds = $batch['userIds']; } else { if (!isset($userIds)) { throw new Q_Exception_RequiredField(array('field' => 'userIds'), 'userIds'); } } if (is_string($userIds)) { $userIds = explode(",", $userIds); } $fields = Q_Config::expect('Users', 'avatarFields'); $users = Users_User::select($fields)->where(array('id' => $userIds))->fetchDbRows(null, null, 'id'); $avatars = Db::exportArray($users); if (!isset($batch)) { Q_Response::setSlot('avatars', $avatars); return $avatars; } if ($batch) { $result = array(); foreach ($userIds as $userId) { $result[] = array('slots' => array('avatar' => isset($avatars[$userId]) ? $avatars[$userId] : null)); } Q_Response::setSlot('batch', $result); } return $avatars; }
function resendActivationMessage($subject = null, $view = null, $fields = array(), $options = array()) { if (!isset($subject)) { $subject = Q_Config::get('Users', 'transactional', 'resend', 'subject', Q_Config::get('Users', 'transactional', 'activation', 'subject', 'Did you forget your passphrase?')); } if (!isset($view)) { $view = Q_Config::get('Users', 'transactional', 'resend', 'body', Q_Config::get('Users', 'transactional', 'activation', 'body', 'Users/email/activation.php')); } if (!isset($options['html'])) { $options['html'] = true; } $user = $this->get('user', null); if (!$user) { $user = new Users_User(); $user->id = $this->userId; if (!$user->retrieve()) { throw new Q_Exception_NotVerified(array('type' => 'email address'), 'emailAddress'); } } $minutes = Q_Config::get('Users', 'activation', 'expires', 60 * 24 * 7); $this->activationCode = strtolower(Q_Utils::unique(7)); $this->activationCodeExpires = new Db_Expression("CURRENT_TIMESTAMP + INTERVAL {$minutes} MINUTE"); $this->authCode = md5(microtime() + mt_rand()); $link = 'Users/activate?p=1&code=' . urlencode($this->activationCode) . ' emailAddress=' . urlencode($this->address); /** * @event Users/resend {before} * @param {string} user * @param {string} email */ Q::event('Users/resend', compact('user', 'email', 'link'), 'before'); $this->save(); $email = $this; $fields2 = array_merge($fields, array('user' => $user, 'email' => $this, 'app' => Q_Config::expect('Q', 'app'), 'baseUrl' => Q_Request::baseUrl(), 'link' => $link)); $this->sendMessage($subject, $view, $fields2, $options); // may throw exception if badly configured /** * @event Users/resend {after} * @param {string} user * @param {string} email */ Q::event('Users/resend', compact('user', 'email'), 'after'); }
function Streams_before_Q_objects() { $token = Q_Request::special('Streams.token', null); if ($token === null) { return; } $invite = Streams_Invite::fromToken($token); if (!$invite) { throw new Q_Exception_MissingRow(array('table' => 'invite', 'criteria' => "token = '{$token}"), 'token'); } // did invite expire? $ts = Streams_Invite::db()->select("CURRENT_TIMESTAMP")->fetchAll(PDO::FETCH_NUM); if (isset($invite->expireTime) and $invite->expireTime < $ts[0][0]) { $invite->state = 'expired'; $invite->save(); } // is invite still pending? if ($invite->state !== 'pending') { switch ($invite->state) { case 'expired': $exception = new Streams_Exception_AlreadyExpired(null, 'token'); break; case 'accepted': $exception = new Streams_Exception_AlreadyAccepted(null, 'token'); break; case 'declined': $exception = new Streams_Exception_AlreadyDeclined(null, 'token'); break; case 'forwarded': $exception = new Streams_Exception_AlreadyForwarded(null, 'token'); break; default: $exception = new Q_Exception("This invite has already been " . $invite->state, 'token'); break; } $shouldThrow = Q::event('Streams/objects/inviteException', compact('invite', 'exception'), 'before'); if ($shouldThrow === null) { Q_Response::setNotice('Streams/objects', $exception->getMessage(), true); } else { if ($shouldThrow === true) { throw $exception; } } } // now process the invite $invitedUser = Users_User::fetch($invite->userId, true); $stream = Streams::fetchOne($invitedUser->id, $invite->publisherId, $invite->streamName); if (!$stream) { throw new Q_Exception_MissingRow(array('table' => 'stream', 'criteria' => "publisherId = '{$invite->publisherId}', name = '{$invite->streamName}'")); } $byUser = Users_User::fetch($invite->invitingUserId, true); $byStream = Streams::fetchOne($byUser->id, $invite->publisherId, $invite->streamName); if (!$byStream) { throw new Q_Exception_MissingRow(array('table' => 'stream', 'criteria' => "publisherId = '{$invite->publisherId}', name = '{$invite->streamName}'")); } $access = new Streams_Access(); $access->publisherId = $byStream->publisherId; $access->streamName = $byStream->name; $access->ofUserId = $invite->userId; $specified_access = false; foreach (array('readLevel', 'writeLevel', 'adminLevel') as $level_type) { $access->{$level_type} = -1; if (empty($invite->{$level_type})) { continue; } // Give access level from the invite. // However, if inviting user has a lower access level now, // then give that level instead, unless it is lower than // what the invited user would have had otherwise. $min = min($invite->{$level_type}, $byStream->get($level_type, 0)); if ($min > $stream->get($level_type, 0)) { $access->{$level_type} = $min; $specified_access = true; } } if ($specified_access) { $access->save(true); } // now log invited user in $user = Users::loggedInUser(); if (empty($user) or $user->id !== $invite->userId) { $user = new Users_User(); $user->id = $invite->userId; if (!$user->retrieve()) { // The user who was invited doesn't exist // This shouldn't happen. We just silently log it and return. Q::log("Sanity check failed: invite with {$invite->token} pointed to nonexistent user"); return; } Users::setLoggedInUser($user); } // accept invite and autosubscribe if first time if ($invite->accept() and !$stream->subscription($user->id)) { $stream->subscribe(); } // retain the invite object for further processing Streams::$followedInvite = $invite; }