/** * Adds information to the definition list that causes the app to "phone * home" and see if there are upgrades available. Currently added to the * dashboard only. * Nothing renders with this method. It is public so it can be added by * plugins. */ public function AddUpdateCheck() { if (C('Garden.NoUpdateCheck')) { return; } // Check to see if the application needs to phone-home for updates. Doing // this here because this method is always called when admin pages are // loaded regardless of the application loading them. $UpdateCheckDate = Gdn::Config('Garden.UpdateCheckDate', ''); if ($UpdateCheckDate == '' || !IsTimestamp($UpdateCheckDate) || $UpdateCheckDate < strtotime("-1 day")) { $UpdateData = array(); // Grab all of the plugins & versions $Plugins = Gdn::PluginManager()->AvailablePlugins(); foreach ($Plugins as $Plugin => $Info) { $Name = ArrayValue('Name', $Info, $Plugin); $Version = ArrayValue('Version', $Info, ''); if ($Version != '') { $UpdateData[] = array('Name' => $Name, 'Version' => $Version, 'Type' => 'Plugin'); } } // Grab all of the applications & versions $ApplicationManager = Gdn::Factory('ApplicationManager'); $Applications = $ApplicationManager->AvailableApplications(); foreach ($Applications as $Application => $Info) { $Name = ArrayValue('Name', $Info, $Application); $Version = ArrayValue('Version', $Info, ''); if ($Version != '') { $UpdateData[] = array('Name' => $Name, 'Version' => $Version, 'Type' => 'Application'); } } // Grab all of the themes & versions $ThemeManager = new Gdn_ThemeManager(); $Themes = $ThemeManager->AvailableThemes(); foreach ($Themes as $Theme => $Info) { $Name = ArrayValue('Name', $Info, $Theme); $Version = ArrayValue('Version', $Info, ''); if ($Version != '') { $UpdateData[] = array('Name' => $Name, 'Version' => $Version, 'Type' => 'Theme'); } } // Dump the entire set of information into the definition list (jQuery // will pick it up and ping the VanillaForums.org server with this info). $this->AddDefinition('UpdateChecks', Gdn_Format::Serialize($UpdateData)); } }
/** * Synchronizes the user based on a given UserKey. * * @param string $UserKey A string that uniquely identifies this user. * @param array $Data Information to put in the user table. * @return int The ID of the user. */ public function Synchronize($UserKey, $Data) { $UserID = 0; $Attributes = ArrayValue('Attributes', $Data); if (!is_array($Attributes)) { $Attributes = array(); } // If the user didnt log in, they won't have a UserID yet. That means they want a new // account. So create one for them. if (!isset($Data['UserID']) || $Data['UserID'] <= 0) { // Prepare the user data. $UserData['Name'] = $Data['Name']; $UserData['Password'] = RandomString(16); $UserData['Email'] = ArrayValue('Email', $Data, '*****@*****.**'); $UserData['Gender'] = strtolower(substr(ArrayValue('Gender', $Attributes, 'm'), 0, 1)); $UserData['HourOffset'] = ArrayValue('HourOffset', $Attributes, 0); $UserData['DateOfBirth'] = ArrayValue('DateOfBirth', $Attributes, ''); $UserData['CountNotifications'] = 0; $UserData['Attributes'] = Gdn_Format::Serialize($Attributes); if ($UserData['DateOfBirth'] == '') { $UserData['DateOfBirth'] = '1975-09-16'; } // Make sure there isn't another user with this username. if ($this->ValidateUniqueFields($UserData['Name'], $UserData['Email'])) { // Insert the new user. $this->AddInsertFields($UserData); $UserID = $this->_Insert($UserData); } if ($UserID) { // Save the roles. $Roles = ArrayValue('Roles', $Data, Gdn::Config('Garden.Registration.DefaultRoles')); $this->SaveRoles($UserID, $Roles, FALSE); } } else { $UserID = $Data['UserID']; } // Synchronize the transientkey from the external user data source if it is present (eg. WordPress' wpnonce). if (array_key_exists('TransientKey', $Attributes) && $Attributes['TransientKey'] != '' && $UserID > 0) { $this->SetTransientKey($UserID, $Attributes['TransientKey']); } return $UserID; }
/** * Add another user to the conversation. * * @since 2.0.0 * @access public * * @param int $ConversationID Unique ID of conversation effected. * @param int $UserID Unique ID of current user. */ public function AddUserToConversation($ConversationID, $UserID) { if (!is_array($UserID)) { $UserID = array($UserID); } // First define the current users in the conversation $OldContributorData = $this->GetRecipients($ConversationID); $OldContributorData = Gdn_DataSet::Index($OldContributorData, 'UserID'); $AddedUserIDs = array(); // Get some information about this conversation $ConversationData = $this->SQL->Select('LastMessageID')->Select('CountMessages')->From('Conversation')->Where('ConversationID', $ConversationID)->Get()->FirstRow(); // Add the user(s) if they are not already in the conversation foreach ($UserID as $NewUserID) { if (!array_key_exists($NewUserID, $OldContributorData)) { $AddedUserIDs[] = $NewUserID; $this->SQL->Insert('UserConversation', array('UserID' => $NewUserID, 'ConversationID' => $ConversationID, 'LastMessageID' => $ConversationData->LastMessageID, 'CountReadMessages' => 0, 'DateConversationUpdated' => $ConversationData['DateUpdated'])); } elseif ($OldContributorData[$NewUserID]->Deleted) { $AddedUserIDs[] = $NewUserID; $this->SQL->Put('UserConversation', array('Deleted' => 0), array('ConversationID' => $ConversationID, 'UserID' => $NewUserID)); } } if (count($AddedUserIDs) > 0) { $Session = Gdn::Session(); // Update the Contributors field on the conversation $Contributors = array_unique(array_merge($AddedUserIDs, array_keys($OldContributorData))); sort($Contributors); $this->SQL->Update('Conversation')->Set('Contributors', Gdn_Format::Serialize($Contributors))->Where('ConversationID', $ConversationID)->Put(); $ActivityModel = new ActivityModel(); foreach ($AddedUserIDs as $AddedUserID) { $ActivityModel->Queue(array('ActivityType' => 'AddedToConversation', 'NotifyUserID' => $AddedUserID, 'HeadlineFormat' => T('You were added to a conversation.', '{InsertUserID,user} added {NotifyUserID,you} to a <a href="{Url,htmlencode}">conversation</a>.')), 'ConversationMessage'); } $ActivityModel->SaveQueue(); $this->UpdateUserUnreadCount($AddedUserIDs); } }
/** * * * * * */ public function ProcessAuthorizedRequest($ProviderKey, $UserKey, $UserName = NULL, $ForeignNonce = NULL, $OptionalPayload = NULL) { // Try to load the association for this Provider + UserKey $Association = Gdn::Authenticator()->GetAssociation($UserKey, $ProviderKey, Gdn_Authenticator::KEY_TYPE_PROVIDER); // We havent created a UserAuthentication entry yet. Create one. This will be an un-associated entry. if (!$Association) { $Association = Gdn::Authenticator()->AssociateUser($ProviderKey, $UserKey, 0); // Couldn't even create a half-association. if (!$Association) return Gdn_Authenticator::AUTH_DENIED; } // Retrieved an association which has been fully linked to a local user if ($Association['UserID'] > 0) { // We'll be tracked by Vanilla cookies now, so delete the Proxy cookie if it exists... $this->DeleteCookie(); // Log the user in. $this->SetIdentity($Association['UserID'], FALSE); // Check for a request token that needs to be converted to an access token $Token = $this->LookupToken($ProviderKey, $UserKey, 'request'); if ($Token) { // Check for a stored Nonce $ExistingNonce = $this->LookupNonce($Token['Token']); // Found one. Copy it as if it was passed in to this method, and then delete it. if ($ExistingNonce !== FALSE) { $ForeignNonce = $ExistingNonce; $this->ClearNonces($Token['Token']); } unset($Token); } // Sync the user's email and roles. if (is_array($OptionalPayload) && count($OptionalPayload) > 0) { if (isset($OptionalPayload['Email'])) { Gdn::SQL()->Put('User', array('Email' => $OptionalPayload['Email']), array('UserID' => $Association['UserID'])); } $Roles = GetValue('Roles', $OptionalPayload, FALSE); if ($Roles) { Gdn::UserModel()->SaveRoles($Association['UserID'], $Roles, FALSE); Gdn::Session()->Start($Association['UserID'], TRUE); } } $TokenType = 'access'; $AuthReturn = Gdn_Authenticator::AUTH_SUCCESS; } else { // This association is not yet associated with a local forum account. // Set the memory cookie to trigger the handshake page $CookiePayload = array( 'UserKey' => $UserKey, 'ProviderKey' => $ProviderKey, 'UserName' => $UserName, 'UserOptional' => Gdn_Format::Serialize($OptionalPayload) ); $SerializedCookiePayload = Gdn_Format::Serialize($CookiePayload); $this->Remember($ProviderKey, $SerializedCookiePayload); $TokenType = 'request'; $AuthReturn = Gdn_Authenticator::AUTH_PARTIAL; } $Token = $this->LookupToken($ProviderKey, $UserKey, $TokenType); if (!$Token) $Token = $this->CreateToken($TokenType, $ProviderKey, $UserKey, TRUE); if ($Token && !is_null($ForeignNonce)) { $TokenKey = $Token['Token']; try { $this->SetNonce($TokenKey, $ForeignNonce); } catch (Exception $e) {} } return $AuthReturn; }
function K($Name, $Value = Null) { static $SQL, $Cache, $DataTableCreated; if (is_null($DataTableCreated)) { $DataTableCreated = C('Plugins.UsefulFunctions.DataTableCreated'); if ($DataTableCreated === False) { Gdn::Structure()->Table('Data')->Column('Name', 'varchar(200)', False, 'unique')->Column('Value', 'text')->Set(False, False); $DataTableCreated = True; SaveToConfig('Plugins.UsefulFunctions.DataTableCreated', $DataTableCreated); } } // Select if ($SQL === Null) { $SQL = Gdn::SQL(); } if (is_string($Name) && $Value === Null) { $Modificator = $Name[0]; if (in_array($Modificator, array('#', '%', '@'))) { $Name = substr($Name, 1); } if (!isset($Cache[$Name])) { switch ($Modificator) { case '#': $SQL->Where('Name', $Name); break; case '%': case '@': default: $SQL->Like('Name', $Name, 'right'); } $Result = Null; $ResultSet = $SQL->Select('Name, Value')->From('Data')->Get(); if ($ResultSet->NumRows() == 0) { return False; } elseif ($Modificator == '%') { foreach ($ResultSet as $Data) { $S = "['" . str_replace('.', "']['", $Data->Name) . "']"; eval("\$Value =& \$Result{$S};"); // eval is evil if (is_null($Value) || $Value === '' || is_array($Value)) { $Value = $Cache[$Data->Name] = Gdn_Format::Unserialize($Data->Value); } else { // TODO: FIX ME // Lost value. What should we do? Delete? Throw Exception? } } } elseif ($Modificator == '@' || $ResultSet->NumRows() > 1) { foreach ($ResultSet as $Data) { $K = array_pop(explode('.', $Data->Name)); $Result[$K] = $Cache[$Data->Name] = Gdn_Format::Unserialize($Data->Value); } // reduce result array //if ($Modificator == '@') while(count($Result) == 1) $Result = array_shift($Result); } else { $Result = $ResultSet->FirstRow()->Value; $Result = Gdn_Format::Unserialize($Result); } $Cache[$Name] = $Result; } return $Cache[$Name]; } // Delete if ($Value === False) { if (is_array($Name)) { return $SQL->WhereIn('Name', $Name)->Delete('Data'); } if (is_string($Name)) { return $SQL->Like('Name', $Name, 'right')->Delete('Data'); } trigger_error(sprintf('Incorrect type of Key (%s)', gettype($Name))); } // Insert/Update if (!is_array($Name)) { $Name = array($Name => $Value); } foreach ($Name as $Key => $Value) { $Value = Gdn_Format::Serialize($Value); $SQL->Replace('Data', array('Value' => $Value), array('Name' => $Key)); } }
<?php if (!defined('APPLICATION')) { exit; } /** * Conversations stub content for a new site. * * Called by ConversationsHooks::Setup() to insert stub content upon enabling app. * @package Conversations */ // Only do this once, ever. if (!$Drop) { return; } $SQL = Gdn::Database()->SQL(); // Prep default content $ConversationBody = "Pssst. Hey. A conversation is a private chat between two or more members. No one can see it except the members added. You can delete this one since I’m just a bot and know better than to talk back."; $SystemUserID = Gdn::UserModel()->GetSystemUserID(); $TargetUserID = Gdn::Session()->UserID; $Now = Gdn_Format::ToDateTime(); $Contributors = Gdn_Format::Serialize(array($SystemUserID, $TargetUserID)); // Insert stub conversation $ConversationID = $SQL->Insert('Conversation', array('InsertUserID' => $SystemUserID, 'DateInserted' => $Now, 'Contributors' => $Contributors, 'CountMessages' => 1)); $MessageID = $SQL->Insert('ConversationMessage', array('ConversationID' => $ConversationID, 'Body' => T('StubConversationBody', $ConversationBody), 'Format' => 'Html', 'InsertUserID' => $SystemUserID, 'DateInserted' => $Now)); $SQL->Update('Conversation')->Set('LastMessageID', $MessageID)->Where('ConversationID', $ConversationID)->Put(); $SQL->Insert('UserConversation', array('ConversationID' => $ConversationID, 'UserID' => $TargetUserID, 'CountReadMessages' => 0, 'LastMessageID' => $MessageID, 'DateConversationUpdated' => $Now));
public function UserController_Warning_Create($Sender, $Args) { $Sender->Permission('Garden.Moderation.Manage'); $UserID = (int) GetValue('0', $Args); $User = Gdn::UserModel()->GetID($UserID); if (!$User) { throw NotFoundException($User); } if ($Sender->Form->AuthenticatedPostBack()) { $Type = $Sender->Form->GetValue('Warning'); $Reason = $Sender->Form->GetValue('Reason'); if (empty($Type) || !in_array($Type, $this->WarnLevel)) { $Sender->Form->AddError('ValidateRequired', 'Warn Level'); } if (empty($Reason)) { $Sender->Form->AddError('ValidateRequired', 'Reason'); } if ($Sender->Form->ErrorCount() == 0) { Gdn::UserModel()->SetMeta($UserID, array('Warnings.' . time() => Gdn_Format::Serialize(array('Type' => $Type, 'Reason' => $Reason)))); Gdn::UserModel()->SaveAttribute($UserID, 'WarnLevel', $Type); // get those notification sent $this->SaveActivity($User, $Type, $Reason); // Redirect after a successful save. if ($Sender->Request->Get('Target')) { $Sender->RedirectUrl = $Sender->Request->Get('Target'); } else { $Sender->RedirectUrl = Url(UserUrl($User)); } } } $Sender->SetData('User', $User); $Sender->SetData('WarnLevel', array_combine($this->WarnLevel, array_map(array($this, 'WarnLevelFormat'), $this->WarnLevel))); $Sender->AddSideMenu(); $Sender->Title(T('Warning.Warn', 'Warn')); $Sender->View = $this->ThemeView('warning'); $Sender->Render(); }
/** * Assigns a setting to the configuration array. * * @param string $Name The name of the configuration setting to assign. If the setting is * contained within an associative array, use dot denomination to get the * setting. ie. <code>$this->Set('Database.Host', $Value)</code> would set * <code>$Configuration[$Group]['Database']['Host'] = $Value</code>. * @param mixed $Value The value of the configuration setting. * @param boolean $Overwrite If the setting already exists, should it's value be overwritten? Defaults to true. */ public function Set($Name, $Value, $Overwrite = TRUE) { if (!is_array($this->_Data)) { $this->_Data = array(); } if (!is_array($this->_SaveData)) { $this->_SaveData = array(); } $Keys = explode('.', $Name); $KeyCount = count($Keys); $Array =& $this->_Data; $SaveArray =& $this->_SaveData; for ($i = 0; $i < $KeyCount; ++$i) { $Key = $Keys[$i]; if (!is_array($Array)) { $Array = array(); } $KeyExists = array_key_exists($Key, $Array); if ($i == $KeyCount - 1) { // If we are on the last iteration of the key, then set the value. if ($KeyExists === FALSE || $Overwrite === TRUE) { $Array[$Key] = Gdn_Format::Serialize($Value); $SaveArray[$Key] = Gdn_Format::Serialize($Value); } } else { // Otherwise, traverse the array if ($KeyExists === FALSE) { $Array[$Key] = array(); $SaveArray[$Key] = array(); } $Array =& $Array[$Key]; $SaveArray =& $SaveArray[$Key]; } } }
/** * Saves a name/value to the user's specified $Column. * * This method throws exceptions when errors are encountered. Use try ... * catch blocks to capture these exceptions. * * @param string The name of the serialized column to save to. At the time of this writing there are three serialized columns on the user table: Permissions, Preferences, and Attributes. * @param int The UserID to save. * @param mixed The name of the value being saved, or an associative array of name => value pairs to be saved. If this is an associative array, the $Value argument will be ignored. * @param mixed The value being saved. */ public function SaveToSerializedColumn($Column, $UserID, $Name, $Value = '') { // Load the existing values $UserData = $this->GetID($UserID, DATASET_TYPE_OBJECT); if (!$UserData) { throw new Exception(sprintf('User %s not found.', $UserID)); } $Values = GetValue($Column, $UserData); if (!is_array($Values) && !is_object($Values)) { $Values = @unserialize($UserData->{$Column}); } // Throw an exception if the field was not empty but is also not an object or array if (is_string($Values) && $Values != '') { throw new Exception(sprintf(T('Serialized column "%s" failed to be unserialized.'), $Column)); } if (!is_array($Values)) { $Values = array(); } // Hook for plugins $this->EventArguments['CurrentValues'] =& $Values; $this->EventArguments['Column'] =& $Column; $this->EventArguments['UserID'] =& $UserID; $this->EventArguments['Name'] =& $Name; $this->EventArguments['Value'] =& $Value; $this->FireEvent('BeforeSaveSerialized'); // Assign the new value(s) if (!is_array($Name)) { $Name = array($Name => $Value); } $RawValues = array_merge($Values, $Name); $Values = array(); foreach ($RawValues as $Key => $RawValue) { if (!is_null($RawValue)) { $Values[$Key] = $RawValue; } } $Values = Gdn_Format::Serialize($Values); // Save the values back to the db $SaveResult = $this->SQL->Put('User', array($Column => $Values), array('UserID' => $UserID)); $this->ClearCache($UserID, array('user')); return $SaveResult; }
/** * Save tags when saving a discussion. */ public function DiscussionModel_AfterSaveDiscussion_Handler($Sender) { $FormPostValues = GetValue('FormPostValues', $Sender->EventArguments, array()); $DiscussionID = GetValue('DiscussionID', $Sender->EventArguments, 0); $IsInsert = GetValue('Insert', $Sender->EventArguments); $RawFormTags = GetValue('Tags', $FormPostValues, ''); $FormTags = trim(strtolower($RawFormTags)); $FormTags = TagModel::SplitTags($FormTags); // Resave the Discussion's Tags field as serialized $SerializedTags = Gdn_Format::Serialize(explode(',', $RawFormTags)); $Sender->SQL->Update('Discussion')->Set('Tags', $SerializedTags)->Where('DiscussionID', $DiscussionID)->Put(); // Find out which of these tags is not yet in the tag table $ExistingTagData = $Sender->SQL->Select('TagID, Name')->From('Tag')->WhereIn('Name', $FormTags)->Get(); $NewTags = $FormTags; $Tags = array(); // <-- Build a complete associative array of $Tags[TagID] => TagName values for this discussion. foreach ($ExistingTagData as $ExistingTag) { if (in_array($ExistingTag->Name, $NewTags)) { unset($NewTags[array_search($ExistingTag->Name, $NewTags)]); } $Tags[$ExistingTag->TagID] = $ExistingTag->Name; } // Insert the missing ones foreach ($NewTags as $NewTag) { $TagID = $Sender->SQL->Insert('Tag', array('Name' => strtolower($NewTag), 'InsertUserID' => Gdn::Session()->UserID, 'DateInserted' => Gdn_Format::ToDateTime(), 'CountDiscussions' => 0)); $Tags[$TagID] = $NewTag; } // Find out which tags are not yet associated with this discussion, and which tags are no longer on this discussion $TagIDs = array_keys($Tags); $NonAssociatedTagIDs = $TagIDs; $AssociatedTagIDs = array(); $RemovedTagIDs = array(); $ExistingTagData = $Sender->SQL->Select('t.*')->From('TagDiscussion td')->Join('Tag t', 'td.TagID = t.TagID')->Where('DiscussionID', $DiscussionID)->Get(); foreach ($ExistingTagData as $ExistingTag) { if (in_array($ExistingTag->TagID, $TagIDs)) { unset($NonAssociatedTagIDs[array_search($ExistingTag->TagID, $NonAssociatedTagIDs)]); } else { if (!GetValue('Type', $ExistingTag) && !in_array($ExistingTag->TagID, $TagIDs)) { $RemovedTagIDs[] = $ExistingTag->TagID; } else { $AssociatedTagIDs[] = $ExistingTag->TagID; } } } // Associate the ones that weren't already associated foreach ($NonAssociatedTagIDs as $TagID) { $Sender->SQL->Insert('TagDiscussion', array('DiscussionID' => $DiscussionID, 'TagID' => $TagID)); } // Remove tags that were removed, and reduce their counts if (count($RemovedTagIDs) > 0) { // Reduce count $Sender->SQL->Update('Tag')->Set('CountDiscussions', 'CountDiscussions - 1', FALSE)->WhereIn('TagID', $RemovedTagIDs)->Put(); // Remove association $Sender->SQL->WhereIn('TagID', $RemovedTagIDs)->Delete('TagDiscussion', array('DiscussionID' => $DiscussionID)); } // Update the count on all previously unassociated tags $Sender->SQL->Update('Tag')->Set('CountDiscussions', 'CountDiscussions + 1', FALSE)->WhereIn('TagID', $NonAssociatedTagIDs)->Put(); }
/** * Add another user to the conversation. * * @since 2.0.0 * @access public * * @param int $ConversationID Unique ID of conversation effected. * @param int $UserID Unique ID of current user. */ public function AddUserToConversation($ConversationID, $UserID) { if (!is_array($UserID)) $UserID = array($UserID); // First define the current users in the conversation $OldContributorData = $this->GetRecipients($ConversationID); $OldContributorUserIDs = ConsolidateArrayValuesByKey($OldContributorData->ResultArray(), 'UserID'); $AddedUserIDs = array(); // Get some information about this conversation $ConversationData = $this->SQL ->Select('LastMessageID') ->Select('CountMessages') ->From('Conversation') ->Where('ConversationID', $ConversationID) ->Get() ->FirstRow(); // Add the user(s) if they are not already in the conversation foreach ($UserID as $NewUserID) { if (!in_array($NewUserID, $OldContributorUserIDs)) { $AddedUserIDs[] = $NewUserID; $this->SQL->Insert('UserConversation', array( 'UserID' => $NewUserID, 'ConversationID' => $ConversationID, 'LastMessageID' => $ConversationData->LastMessageID, 'CountReadMessages' => 0 )); } } if (count($AddedUserIDs) > 0) { $Session = Gdn::Session(); // Update the Contributors field on the conversation $Contributors = array_unique(array_merge($AddedUserIDs, $OldContributorUserIDs)); sort($Contributors); $this->SQL ->Update('Conversation') ->Set('Contributors', Gdn_Format::Serialize($Contributors)) ->Where('ConversationID', $ConversationID) ->Put(); // NOTIFY ALL NEWLY ADDED USERS THAT THEY WERE ADDED TO THE CONVERSATION foreach ($AddedUserIDs as $AddedUserID) { AddActivity( $Session->UserID, 'AddedToConversation', '', $AddedUserID, '/messages/'.$ConversationID ); } // Update the unread conversation count for each affected user $this->SQL ->Update('User') ->Set('CountUnreadConversations', 'coalesce(CountUnreadConversations, 0) + 1', FALSE) ->WhereIn('UserID', $AddedUserIDs) ->Put(); } }
/** * Add another user to the conversation. * * @since 2.0.0 * @access public * * @param int $ConversationID Unique ID of conversation effected. * @param int $UserID Unique ID of current user. */ public function AddUserToConversation($ConversationID, $UserID) { if (!is_array($UserID)) { $UserID = array($UserID); } // First define the current users in the conversation $OldContributorData = $this->GetRecipients($ConversationID); $OldContributorData = Gdn_DataSet::Index($OldContributorData, 'UserID'); $AddedUserIDs = array(); // Get some information about this conversation $ConversationData = $this->SQL->Select('LastMessageID')->Select('CountMessages')->From('Conversation')->Where('ConversationID', $ConversationID)->Get()->FirstRow(); // Add the user(s) if they are not already in the conversation foreach ($UserID as $NewUserID) { if (!array_key_exists($NewUserID, $OldContributorData)) { $AddedUserIDs[] = $NewUserID; $this->SQL->Insert('UserConversation', array('UserID' => $NewUserID, 'ConversationID' => $ConversationID, 'LastMessageID' => $ConversationData->LastMessageID, 'CountReadMessages' => 0)); } elseif ($OldContributorData[$NewUserID]->Deleted) { $AddedUserIDs[] = $NewUserID; $this->SQL->Put('UserConversation', array('Deleted' => 0), array('ConversationID' => $ConversationID, 'UserID' => $NewUserID)); } } if (count($AddedUserIDs) > 0) { $Session = Gdn::Session(); // Update the Contributors field on the conversation $Contributors = array_unique(array_merge($AddedUserIDs, array_keys($OldContributorData))); sort($Contributors); $this->SQL->Update('Conversation')->Set('Contributors', Gdn_Format::Serialize($Contributors))->Where('ConversationID', $ConversationID)->Put(); foreach ($AddedUserIDs as $AddedUserID) { // And notify them that they were added to the conversation AddActivity($Session->UserID, 'AddedToConversation', '', $AddedUserID, '/messages/' . $ConversationID); } $this->UpdateUserUnreadCount($AddedUserIDs); } }
/** * Saves a name/value to the user's specified $Column. * * This method throws exceptions when errors are encountered. Use try ... * catch blocks to capture these exceptions. * * @param string The name of the serialized column to save to. At the time of this writing there are three serialized columns on the user table: Permissions, Preferences, and Attributes. * @param int The UserID to save. * @param mixed The name of the value being saved, or an associative array of name => value pairs to be saved. If this is an associative array, the $Value argument will be ignored. * @param mixed The value being saved. */ public function SaveToSerializedColumn($Column, $UserID, $Name, $Value = '') { // Load the existing values $UserData = $this->SQL->Select($Column) ->From('User') ->Where('UserID', $UserID) ->Get() ->FirstRow(); if (!$UserData) throw new Exception(T('ErrorRecordNotFound')); $Values = unserialize($UserData->$Column); // Throw an exception if the field was not empty but is also not an object or array if (is_string($Values) && $Values != '') throw new Exception(sprintf(T('Serialized column "%s" failed to be unserialized.'),$Column)); if (!is_array($Values)) $Values = array(); // Hook for plugins $this->EventArguments['CurrentValues'] = &$Values; $this->EventArguments['Column'] = &$Column; $this->EventArguments['UserID'] = &$UserID; $this->EventArguments['Name'] = &$Name; $this->EventArguments['Value'] = &$Value; $this->FireEvent('BeforeSaveSerialized'); // Assign the new value(s) if (!is_array($Name)) $Name = array($Name => $Value); $RawValues = array_merge($Values, $Name); $Values = array(); foreach ($RawValues as $Key => $RawValue) if (!is_null($RawValue)) $Values[$Key] = $RawValue; $Values = Gdn_Format::Serialize($Values); // Save the values back to the db return $this->SQL->Put('User', array($Column => $Values), array('UserID' => $UserID)); }
/** * Synchronizes the user based on a given UniqueID. * * @param string $UniqueID A string that uniquely identifies this user. * @param array $Data Information to put in the user table. * @return int The ID of the user. */ public function Synchronize($UniqueID, $Data) { $UserID = 0; $Attributes = ArrayValue('Attributes', $Data); if (!is_array($Attributes)) { $Attributes = array(); } // Try and get the user based on the uniqueID. $this->SQL->Select('ua.UniqueID, ua.UserID as AuthUserID')->Select('u.*'); if (array_key_exists('UserID', $Data)) { $UniqueIDParam = $this->SQL->NamedParameter('UniqueID', TRUE, $UniqueID); $User = $this->SQL->From('User u')->Join('UserAuthentication ua', 'u.UserID = ua.UserID and ua.UniqueID = ' . $UniqueIDParam, 'left')->Where('u.UserID', $Data['UserID']); } else { $this->SQL->From('UserAuthentication ua')->Join('User u', 'u.UserID = ua.UserID')->Where('ua.UniqueID', $UniqueID); } $User = $this->SQL->Get()->FirstRow(); if ($User === FALSE) { // Clean the user data. $UserData['Name'] = $Data['Name']; $UserData['Password'] = RandomString(7); $UserData['Email'] = ArrayValue('Email', $Attributes, '*****@*****.**'); $UserData['Gender'] = strtolower(substr(ArrayValue('Gender', $Attributes, 'm'), 0, 1)); $UserData['HourOffset'] = ArrayValue('HourOffset', $Attributes, 0); $UserData['DateOfBirth'] = ArrayValue('DateOfBirth', $Attributes, ''); $UserData['CountNotifications'] = 0; $UserData['Attributes'] = Gdn_Format::Serialize($Attributes); if ($UserData['DateOfBirth'] == '') { $UserData['DateOfBirth'] = '1975-09-16'; } // Make sure there isn't another user with this username. if ($this->ValidateUniqueFields($UserData['Name'], $UserData['Email'])) { // Insert the new user. $this->AddInsertFields($UserData); $UserID = $this->_Insert($UserData); } if ($UserID) { // Save the roles. $Roles = ArrayValue('Roles', $Data, Gdn::Config('Garden.Registration.DefaultRoles')); $this->SaveRoles($UserID, $Roles, FALSE); // Save the authentication. $this->SQL->Insert('UserAuthentication', array('UniqueID' => $UniqueID, 'UserID' => $UserID)); } } else { // Check to see if we have to insert an authentication. if (is_null($User->UniqueID)) { $this->SQL->Insert('UserAuthentication', array('UniqueID' => $UniqueID, 'UserID' => $User->UserID)); } // Clean the user data. $UserData = array_intersect_key($Data, array('Name' => 0, 'Email' => 0, 'Gender' => 0, 'DateOfBirth' => 0, 'HourOffset' => 0)); if (array_key_exists('Gender', $UserData)) { $UserData['Gender'] = strtolower(substr($UserData['Gender'], 0, 1)); } // Make sure there isn't another user with this username. if ($User->Name != $UserData['Name'] || $User->Email != $UserData['Email']) { $UniqueData = $this->SQL->Select('u.Name, u.Email')->From('User u')->Where('u.UserID <>', $User->UserID)->BeginWhereGroup(); if ($User->Name != $UserData['Name']) { $this->SQL->Where('u.Name', $UserData['Name']); } if ($User->Email != $UserData['Email']) { if ($User->Name != $UserData['Name']) { $this->SQL->OrWhere('u.Email', $UserData['Email']); } else { $this->SQL->Where('u.Email', $UserData['Email']); } } $this->SQL->EndWhereGroup(); $OtherUsers = $this->SQL->Get(); foreach ($OtherUsers as $OtherUser) { // If there is another user with the same username/email then don't update. if ($OtherUser->Name == $UserData['Name']) { $UserData['Name'] = $User->Name; } if ($OtherUser->Email == $UserData['Email']) { $UserData['Email'] = $User->Email; } } } // Update the user. $UserID = $User->UserID; $UserData['UserID'] = $UserID; $this->Save($UserData); // Update the roles. if (array_key_exists('Roles', $Data)) { $this->SaveRoles($UserID, $Data['Roles'], FALSE); } } // Synchronize the transientkey from the external user data source if it is present (eg. WordPress' wpnonce). if (array_key_exists('TransientKey', $Attributes) && $Attributes['TransientKey'] != '' && $UserID > 0) { $this->SetTransientKey($UserID, $Attributes['TransientKey']); } return $UserID; }
public function SaveToSerializedColumn($Column, $RowID, $Name, $Value = '') { if (!isset($this->Schema)) { $this->DefineSchema(); } // TODO: need to be sure that $this->PrimaryKey is only one primary key $FieldName = $this->PrimaryKey; // Load the existing values $Row = $this->SQL->Select($Column)->From($this->Name)->Where($FieldName, $RowID)->Get()->FirstRow(); if (!$Row) { throw new Exception(T('ErrorRecordNotFound')); } $Values = Gdn_Format::Unserialize($Row->{$Column}); if (is_string($Values) && $Values != '') { throw new Exception(T('Serialized column failed to be unserialized.')); } if (!is_array($Values)) { $Values = array(); } if (!is_array($Name)) { $Name = array($Name => $Value); } // Assign the new value(s) $Values = Gdn_Format::Serialize(array_merge($Values, $Name)); // Save the values back to the db return $this->SQL->From($this->Name)->Where($FieldName, $RowID)->Set($Column, $Values)->Put(); }
protected function _StringsScriptSeperate($Strings) { $Token = 'inline_' . md5(Gdn_Format::Serialize($Strings)); $CacheFile = PATH_CACHE . "/Consolidate/{$Token}"; //check cache if (file_exists($CacheFile)) { $Inline = Gdn_Format::Unserialize(file_get_contents($CacheFile)); if (GetValue('Before', $Inline)) { $Strings = GetValue('Before', $Inline); } if (GetValue('After', $Inline)) { $this->InlineJsStrings = GetValue('After', $Inline); } if (!in_array($Token, $this->ChunkedFiles)) { $this->ChunkedFiles[] = $Token; } return $Strings; } foreach ($Strings as &$String) { //detect script if (stripos($String, '<script') !== FALSE) { //remove HTML comments $String = preg_replace_callback("`<!--(.*?)-->`imsU", array($this, '_StripHTMLComments'), $String); //escape quoted scripts $String = preg_replace_callback("`(?<!\\\\)'((.*?)<script[^>]*>(.*?)</script>(.*?))*?(?<!\\\\)'`imsU", array($this, '_EscapeCommentedScript'), $String); $String = preg_replace_callback("`(?<!\\\\)\"((.*?)<script[^>]*>(.*?)</script>(.*?))*?(?<!\\\\)\"`imsU", array($this, '_EscapeCommentedScript'), $String); //remove and save inline scripts (including conditional tags) $String = preg_replace_callback("`(<!--[\\s]*\\[if[^\\]]*\\]>[\\s]*(-->)?)?<script[^>]*>(.*?)</script>((<!--)?[\\s]*<!\\[endif\\][\\s]*-->)?`imsU", array($this, '_ScriptSeperate'), $String); } } $Inline = array(); if (!empty($Strings)) { $Inline['Before'] = $Strings; } if (!empty($this->InlineJsStrings)) { $Inline['After'] = $this->InlineJsStrings; } //cache if (!empty($Inline)) { $Inline = Gdn_Format::Serialize($Inline); if (!file_exists(dirname($CacheFile))) { mkdir(dirname($CacheFile), 0777, TRUE); } file_put_contents($CacheFile, $Inline); if (!in_array($Token, $this->ChunkedFiles)) { $this->ChunkedFiles[] = $Token; } } return $Strings; }
public function Handshake($AuthenticationSchemeAlias = 'default') { try { // Don't show anything if handshaking not turned on by an authenticator if (!Gdn::Authenticator()->CanHandshake()) { throw new Exception(); } // Try to load the authenticator $Authenticator = Gdn::Authenticator()->AuthenticateWith($AuthenticationSchemeAlias); // Try to grab the authenticator data $Payload = $Authenticator->GetHandshake(); if ($Payload === FALSE) { Gdn::Request()->WithURI('dashboard/entry/auth/password'); return Gdn::Dispatcher()->Dispatch(); } } catch (Exception $e) { Gdn::Request()->WithURI('/entry/signin'); return Gdn::Dispatcher()->Dispatch(); } $UserInfo = array('UserKey' => $Authenticator->GetUserKeyFromHandshake($Payload), 'ConsumerKey' => $Authenticator->GetProviderKeyFromHandshake($Payload), 'TokenKey' => $Authenticator->GetTokenKeyFromHandshake($Payload), 'UserName' => $Authenticator->GetUserNameFromHandshake($Payload), 'UserEmail' => $Authenticator->GetUserEmailFromHandshake($Payload)); // Manual user sync is disabled. No hand holding will occur for users. $SyncScreen = C('Garden.Authenticator.SyncScreen', 'on'); switch ($SyncScreen) { case 'on': $this->SyncScreen($Authenticator, $UserInfo, $Payload); break; case 'off': case 'smart': $UserID = $this->UserModel->Synchronize($UserInfo['UserKey'], array('Name' => $UserInfo['UserName'], 'Email' => $UserInfo['UserEmail'])); if ($UserID > 0) { // Account created successfully. // Finalize the link between the forum user and the foreign userkey $Authenticator->Finalize($UserInfo['UserKey'], $UserID, $UserInfo['ConsumerKey'], $UserInfo['TokenKey'], $Payload); /// ... and redirect them appropriately $Route = $this->RedirectTo(); if ($Route !== FALSE) { Redirect($Route); } else { Redirect('/'); } } else { // Account not created. if ($SyncScreen == 'smart') { $this->StatusMessage = T('There is already an account in this forum using your email address. Please create a new account, or enter the credentials for the existing account.'); $this->SyncScreen($Authenticator, $UserInfo, $Payload); } else { // Set the memory cookie to allow signinloopback to shortcircuit remote query. $CookiePayload = array('Sync' => 'Failed'); $SerializedCookiePayload = Gdn_Format::Serialize($CookiePayload); $Authenticator->Remember($UserInfo['ConsumerKey'], $SerializedCookiePayload); // This resets vanilla's internal "where am I" to the homepage. Needed. Gdn::Request()->WithRoute('DefaultController'); $this->SelfUrl = Url(''); //Gdn::Request()->Path(); $this->View = 'syncfailed'; $this->ProviderSite = $Authenticator->GetProviderUrl(); $this->Render(); } } break; } }
public function ProcessAuthorizedRequest($ProviderKey, $UserKey, $UserName = NULL) { $Association = Gdn::Authenticator()->GetAssociation($UserKey, $ProviderKey, Gdn_Authenticator::KEY_TYPE_PROVIDER); // We havent created a user entry yet. Lets! if (!$Association) { $Association = Gdn::Authenticator()->AssociateUser($ProviderKey, $UserKey, 0); if (!$Association) { return Gdn_Authenticator::AUTH_DENIED; } } if ($Association['UserID'] > 0) { // Tracked by Vanilla cookies now... $this->DeleteCookie(); $this->SetIdentity($Association['UserID'], FALSE); return Gdn_Authenticator::AUTH_SUCCESS; } else { // Set the memory cookie $CookiePayload = array('UserKey' => $UserKey, 'ProviderKey' => $ProviderKey, 'UserName' => $UserName); $SerializedCookiePayload = Gdn_Format::Serialize($CookiePayload); $this->_Remember($ProviderKey, $SerializedCookiePayload); return Gdn_Authenticator::AUTH_PARTIAL; } }