function Streams_0_8_6_Streams_mysql() { $app = Q_Config::expect('Q', 'app'); // access for managing communities $access = new Streams_Access(); $access->publisherId = $app; $access->streamName = 'Streams/community*'; $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 categories $access = new Streams_Access(); $access->publisherId = $app; $access->streamName = 'Streams/category/'; $access->ofUserId = ''; $access->ofContactLabel = "{$app}/admins"; $access->readLevel = Streams::$READ_LEVEL['messages']; $access->writeLevel = Streams::$WRITE_LEVEL['close']; $access->adminLevel = Streams::$ADMIN_LEVEL['manage']; $access->save(); // template to help users relate things to Streams/category streams Streams_Stream::insert(array('publisherId' => '', 'name' => 'Streams/category/', 'type' => 'Streams/template', 'title' => 'Untitled Category', 'icon' => 'Streams/category', 'content' => '', 'attributes' => null, 'readLevel' => Streams::$READ_LEVEL['messages'], 'writeLevel' => Streams::$WRITE_LEVEL['relate'], 'adminLevel' => Streams::$ADMIN_LEVEL['invite']))->execute(); // template to help users create subcategories for things Streams_RelatedTo::insert(array('toPublisherId' => '', 'toStreamName' => 'Streams/category/', 'type' => 'subcategories', 'fromPublisherId' => '', 'fromStreamName' => 'Streams/category/'))->execute(); }
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(); }
function Websites_0_8_3_Streams_mysql() { $app = Q_Config::expect('Q', 'app'); // access for managing communities $access = new Streams_Access(); $access->publisherId = $app; $access->streamName = 'Streams/community*'; $access->ofUserId = ''; $access->ofContactLabel = "Websites/admins"; $access->readLevel = Streams::$READ_LEVEL['messages']; $access->writeLevel = Streams::$WRITE_LEVEL['edit']; $access->adminLevel = Streams::$ADMIN_LEVEL['manage']; $access->save(); }
function Streams_access_put($params) { $user = Users::loggedInUser(true); Q_Valid::nonce(true); $publisherId = Streams::requestedPublisherId(true); $streamName = Streams::requestedName(true); $stream = Streams::fetchOne($user->id, $publisherId, $streamName); if (!$stream) { throw new Q_Exception_MissingRow(array('table' => 'stream', 'criteria' => 'with that name')); } if (!$stream->testAdminLevel('own')) { throw new Users_Exception_NotAuthorized(); } $p = array_merge($_REQUEST, $params); $access = new Streams_Access(); $access->publisherId = $stream->publisherId; $access->streamName = $stream->name; $access->ofUserId = Q::ifset($_REQUEST, 'ofUserId', ''); $access->ofContactLabel = Q::ifset($_REQUEST, 'ofContactLabel', ''); if (empty($access->ofUserId) and empty($access->ofContactLabel)) { $fields = array('grantedByUserId', 'filter', 'readLevel', 'writeLevel', 'adminLevel', 'permissions'); foreach ($fields as $field) { if (isset($p[$field])) { $stream->{$field} = $p[$field]; } } $stream->save(); return; } $access->retrieve(); $fields = array('grantedByUserId', 'filter', 'readLevel', 'writeLevel', 'adminLevel', 'permissions'); foreach ($fields as $field) { if (isset($p[$field])) { $access->{$field} = $p[$field]; } } $defaults = array('grantedByUserId' => $user->id, 'readLevel' => -1, 'writeLevel' => -1, 'adminLevel' => -1); foreach ($defaults as $k => $v) { if (!isset($access->{$k})) { $access->{$k} = $v; } } $access->save(); Streams::$cache['access'] = $access; }
function Streams_after_Users_User_saveExecute($params) { // If the username or icon was somehow modified, // update all the avatars for this publisher $modifiedFields = $params['modifiedFields']; $user = $params['row']; $updates = array(); if (isset($modifiedFields['username'])) { $updates['username'] = $modifiedFields['username']; } if (isset($modifiedFields['icon'])) { $updates['icon'] = $modifiedFields['icon']; } if ($user->id === Users::communityId()) { $firstName = Users::communityName(); $lastName = Users::communitySuffix(); $firstName = $firstName ? $firstName : ""; $lastName = $lastName ? $lastName : ""; } else { $firstName = Q::ifset(Streams::$cache, 'register', 'first', ''); $lastName = Q::ifset(Streams::$cache, 'register', 'last', ''); } if ($params['inserted']) { // create some standard streams for them $onInsert = Q_Config::get('Streams', 'onInsert', 'Users_User', array()); if (!$onInsert) { return; } $p = new Q_Tree(); $p->load(STREAMS_PLUGIN_CONFIG_DIR . DS . 'streams.json'); $p->load(APP_CONFIG_DIR . DS . 'streams.json'); $values = array('Streams/user/firstName' => $firstName, 'Streams/user/lastName' => $lastName); // Check for user data from facebook if (!empty(Users::$cache['facebookUserData'])) { $userData = Users::$cache['facebookUserData']; foreach ($userData as $name_fb => $value) { foreach ($p->getAll() as $name => $info) { if (isset($info['name_fb']) and $info['name_fb'] === $name_fb) { $onInsert[] = $name; $values[$name] = $value; } } } } foreach ($onInsert as $name) { $stream = Streams::fetchOne($user->id, $user->id, $name); if (!$stream) { // it shouldn't really be in the db yet $stream = new Streams_Stream(); $stream->publisherId = $user->id; $stream->name = $name; } $stream->type = $p->expect($name, "type"); $stream->title = $p->expect($name, "title"); $stream->content = $p->get($name, "content", ''); // usually empty $stream->readLevel = $p->get($name, 'readLevel', Streams_Stream::$DEFAULTS['readLevel']); $stream->writeLevel = $p->get($name, 'writeLevel', Streams_Stream::$DEFAULTS['writeLevel']); $stream->adminLevel = $p->get($name, 'adminLevel', Streams_Stream::$DEFAULTS['adminLevel']); if ($name === "Streams/user/icon") { $sizes = Q_Config::expect('Users', 'icon', 'sizes'); sort($sizes); $stream->setAttribute('sizes', $sizes); $stream->icon = $user->iconUrl(); } if (isset($values[$name])) { $stream->content = $values[$name]; } $stream->save(); // this also inserts avatars $o = array('userId' => $user->id, 'skipAccess' => true); $so = $p->get($name, "subscribe", array()); if ($so === false) { $stream->join($o); } else { $stream->subscribe(array_merge($o, $so)); } } // Save a greeting stream, to be edited $communityId = Users::communityId(); Streams::create($user->id, $user->id, "Streams/greeting", array('name' => "Streams/greeting/{$communityId}")); // Create some standard labels $label = new Users_Label(); $label->userId = $user->id; $label->label = 'Streams/invited'; $label->icon = 'labels/Streams/invited'; $label->title = 'People I invited'; $label->save(true); $label2 = new Users_Label(); $label2->userId = $user->id; $label2->label = 'Streams/invitedMe'; $label2->icon = 'labels/Streams/invitedMe'; $label2->title = 'Who invited me'; $label2->save(true); // By default, users they invite should see their full name $access = new Streams_Access(); $access->publisherId = $user->id; $access->streamName = 'Streams/user/firstName'; $access->ofUserId = ''; $access->ofContactLabel = 'Streams/invited'; $access->grantedByUserId = $user->id; $access->readLevel = Streams::$READ_LEVEL['content']; $access->writeLevel = -1; $access->adminLevel = -1; $access->save(); $access = new Streams_Access(); $access->publisherId = $user->id; $access->streamName = 'Streams/user/lastName'; $access->ofUserId = ''; $access->ofContactLabel = 'Streams/invited'; $access->grantedByUserId = $user->id; $access->readLevel = Streams::$READ_LEVEL['content']; $access->writeLevel = -1; $access->adminLevel = -1; $access->save(); // NOTE: the above saving of access caused Streams::updateAvatar to run, // insert a Streams_Avatar row for the new user, and properly configure it. } else { if ($modifiedFields) { if ($updates) { Streams_Avatar::update()->set($updates)->where(array('publisherId' => $user->id))->execute(); } foreach ($modifiedFields as $field => $value) { $name = Q_Config::get('Streams', 'onUpdate', 'Users_User', $field, null); if (!$name) { continue; } $stream = isset(Streams::$beingSaved[$field]) ? Streams::$beingSaved[$field] : Streams::fetchOne($user->id, $user->id, $name); if (!$stream) { // it should probably already be in the db continue; } $stream->content = $value; if ($name === "Streams/user/icon") { $sizes = Q_Config::expect('Users', 'icon', 'sizes'); sort($sizes); $attributes = $stream->attributes; $stream->setAttribute('sizes', $sizes); $stream->icon = $changes['icon'] = $user->iconUrl(); } Streams::$beingSavedQuery = $stream->changed($user->id); } } } }
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; }
/** * Starts a recurring subscription * @param {Streams_Stream} $plan The subscription plan stream * @param {string} [$payments=null] The type of payments processor, could be "authnet" or "stripe". If omitted, the subscription proceeds without any payments. * @param {array} [$options=array()] Options for the subscription * @param {date} [$options.startDate=today] The start date of the subscription * @param {date} [$options.endDate=today+year] The end date of the subscription * @param {Users_User} [$options.user=Users::loggedInUser()] Allows us to set the user to subscribe * @param {Users_User} [$options.publisherId=Users::communityId()] Allows us to override the publisher to subscribe to * @param {string} [$options.description=null] description of the charge, to be sent to customer * @param {string} [$options.metadata=null] any additional metadata to store with the charge * @param {string} [$options.subscription=null] if this charge is related to a subscription stream * @param {string} [$options.subscription.publisherId] * @param {string} [$options.subscription.streamName] * @throws Assets_Exception_DuplicateTransaction * @throws Assets_Exception_HeldForReview * @throws Assets_Exception_ChargeFailed * @return {Streams_Stream} A stream of type 'Assets/subscription' representing this subscription */ static function startSubscription($plan, $payments = null, $options = array()) { if (!isset($options['user'])) { $options['user'] = Users::loggedInUser(true); } $app = Q_Config::expect('Q', 'app'); $user = Q::ifset($options, 'user', Users::loggedInUser(true)); $currency = 'USD'; // TODO: may want to implement support for currency conversion $startDate = Q::ifset($options, 'startDate', date("Y-m-d")); $startDate = date('Y-m-d', strtotime($startDate)); $months = $plan->getAttribute('months', 12); $amount = $plan->getAttribute('amount'); $endDate = date("Y-m-d", strtotime("-1 day", strtotime("+{$months} month", strtotime($startDate)))); $endDate = date('Y-m-d', strtotime($endDate)); $publisherId = Q::ifset($options, 'publisherId', Users::communityId()); $publisher = Users_User::fetch($publisherId); $streamName = "Assets/subscription/{$user->id}/{$plan->name}"; if ($subscription = Streams::fetchOne($publisherId, $publisherId, $streamName)) { return $subscription; // it already started } $attributes = Q::json_encode(array('payments' => $payments, 'planPublisherId' => $plan->publisherId, 'planStreamName' => $plan->name, 'startDate' => $startDate, 'endDate' => $endDate, 'months' => $months, 'amount' => $amount, 'currency' => $currency)); $stream = Streams::create($publisherId, $publisherId, "Assets/subscription", array('name' => $streamName, 'title' => $plan->title, 'readLevel' => Streams::$READ_LEVEL['none'], 'writeLevel' => Streams::$WRITE_LEVEL['none'], 'adminLevel' => Streams::$ADMIN_LEVEL['none'], 'attributes' => $attributes)); $access = new Streams_Access(array('publisherId' => $publisherId, 'streamName' => $streamName, 'ofUserId' => $user->id, 'grantedByUserId' => $app, 'readLevel' => Streams::$READ_LEVEL['max'], 'writeLevel' => -1, 'adminLevel' => -1)); $access->save(); $amount = $plan->getAttribute('amount', null); if (!is_numeric($amount)) { throw new Q_Exception_WrongValue(array('field' => 'amount', 'range' => 'an integer')); } $options['stream'] = $stream; if ($payments) { Assets::charge($payments, $amount, $currency, $options); } /** * @event Assets/startSubscription {before} * @param {Streams_Stream} plan * @param {Streams_Stream} subscription * @param {string} startDate * @param {string} endDate * @return {Users_User} */ Q::event('Assets/startSubscription', compact('plan', 'user', 'publisher', 'stream', 'startDate', 'endDate', 'months', 'currency'), 'after'); return $stream; }
/** * Does necessary preparations for saving a stream in the database. * @method beforeSave * @param {array} $modifiedFields * The array of fields * @return {array} * @throws {Exception} * If mandatory field is not set */ function beforeSave($modifiedFields) { if (empty($this->attributes)) { $this->attributes = '{}'; } if (!$this->retrieved) { // Generate a unique name for the stream if (!isset($modifiedFields['name'])) { $this->name = $modifiedFields['name'] = Streams::db()->uniqueId(Streams_Stream::table(), 'name', array('publisherId' => $this->publisherId), array('prefix' => $this->type . '/Q')); } // we don't want user to update private fields but will set initial values to them $privateFieldNames = self::getConfigField($this->type, 'private', array()); // magic fields are handled by parent method $magicFieldNames = array('insertedTime', 'updatedTime'); $privateFieldNames = array_diff($privateFieldNames, $magicFieldNames); $streamTemplate = $this->getStreamTemplate('Streams_Stream'); $fieldNames = Streams_Stream::fieldNames(); if ($streamTemplate) { // if template exists copy all non-PK and non-magic fields from template foreach (array_diff($fieldNames, $this->getPrimaryKey(), $magicFieldNames) as $field) { if (in_array($field, $privateFieldNames) || !array_key_exists($field, $modifiedFields)) { $this->{$field} = $modifiedFields[$field] = $streamTemplate->{$field}; } } } else { // otherwise (no template) set all private fields to defaults foreach ($privateFieldNames as $field) { $defaults = self::getConfigField($this->type, 'defaults', Streams_Stream::$DEFAULTS); $this->{$field} = $modifiedFields[$field] = Q::ifset($defaults, $field, null); } } // Assign default values to fields that haven't been set yet foreach (array_diff($fieldNames, $magicFieldNames) as $field) { if (!array_key_exists($field, $this->fields) and !array_key_exists($field, $modifiedFields)) { $defaults = self::getConfigField($this->type, 'defaults', Streams_Stream::$DEFAULTS); $this->{$field} = $modifiedFields[$field] = Q::ifset($defaults, $field, null); } } // Get all access templates and save corresponding access $type = true; $accessTemplates = $this->getStreamTemplate('Streams_Access', $type); for ($i = 1; $i <= 3; ++$i) { foreach ($accessTemplates[$i] as $template) { $access = new Streams_Access(); $access->copyFrom($template->toArray()); $access->publisherId = $this->publisherId; $access->streamName = $this->name; if (!$access->save(true)) { return false; // JUNK: this leaves junk in the database, but preserves consistency } } } } /** * @event Streams/Stream/save/$streamType {before} * @param {Streams_Stream} stream * @return {false} To cancel further processing */ $params = array('stream' => $this, 'modifiedFields' => $modifiedFields); if (false === Q::event("Streams/Stream/save/{$this->type}", $params, 'before')) { return false; } foreach ($this->fields as $name => $value) { if (!empty($this->fieldsModified[$name])) { $modifiedFields[$name] = $value; } } $this->beforeSaveExtended($modifiedFields); $result = parent::beforeSave($modifiedFields); // Assume that the stream's name is not being changed $fields = array('Streams/user/firstName' => false, 'Streams/user/lastName' => false, 'Streams/user/username' => 'username', 'Streams/user/icon' => 'icon'); if (!isset($fields[$this->name])) { return $result; } $field = $this->name === 'Streams/user/icon' ? 'icon' : 'content'; $wasModified = !empty($this->fieldsModified[$field]) or !empty($this->fieldsModified['readLevel']); if (!$wasModified) { return $result; } if ($publicField = $fields[$this->name] and !Q::eventStack('Db/Row/Users_User/saveExecute')) { Streams::$beingSaved[$publicField] = $this; try { $user = Users_User::fetch($this->publisherId, true); $user->{$publicField} = $modifiedFields[$field]; $user->save(); } catch (Exception $e) { Streams::$beingSaved[$publicField] = array(); throw $e; } Streams::$beingSaved[$publicField] = array(); return Streams::$beingSavedQuery; } if ($this->retrieved and !$publicField) { // Update all avatars corresponding to access rows for this stream $taintedAccess = Streams_Access::select('*')->where(array('publisherId' => $this->publisherId, 'streamName' => $this->name))->fetchDbRows(); Streams::updateAvatars($this->publisherId, $taintedAccess, $this, true); } return $result; }