Ejemplo n.º 1
0
 public function ProfileController_AfterUserInfo_Handler($Sender)
 {
     if (Gdn::Session()->CheckPermission('Garden.Moderation.Manage') || $Sender->User->UserID == Gdn::Session()->User->UserID) {
         $Warnings = Gdn::UserModel()->GetMeta($Sender->User->UserID, 'Warnings.%', 'Warnings.', array());
         krsort($Warnings);
         $History = False;
         echo '<div class="Warnings">';
         echo Wrap(T('Warning.Warnings', 'Warnings'), 'h2', array('class' => 'H'));
         foreach ($Warnings as $Date => $Warning) {
             $Warning = Gdn_Format::Unserialize($Warning);
             $Reason = '';
             if (is_array($Warning)) {
                 $Reason = $Warning['Reason'];
                 $Warning = $Warning['Type'];
             }
             if ($History && $Warning != 'None') {
                 $WarningClass = "{$Warning} Historical";
             } else {
                 $WarningClass = $Warning;
             }
             if (!$History && $Warning == 'None') {
                 echo '<div class="NoWarning">' . T('Warning.NoWarnings', 'There are no current warnings for this user. ') . '</div>';
             }
             echo '<div class="Warn ' . $WarningClass . '">' . T('Warning.Level.' . $Warning, $Warning) . '<span class="WarningDate">' . Gdn_Format::Date($Date) . '</span></div>';
             if ($Reason) {
                 echo '<div class="WarningReason ' . $WarningClass . '">' . Gdn_Format::Text($Reason) . '</div>';
             }
             $History = True;
         }
         if (count($Warnings) == 0) {
             echo '<div class="NoWarning">' . T('Warning.NoWarnings', 'There are no current warnings for this user. ') . '</div>';
         }
         if (count($Warnings) > 1) {
             echo '<a class="WarningTogggleHistory" href="#">' . T('Warning.ToggleHistory', 'Toggle History') . '</a>';
         }
         echo '</div>';
     }
 }
   public function GetRolesFromHandshake($Handshake) {
      static $UserOptional = NULL;

      if (is_null($UserOptional)) {
         $UserOptional = Gdn_Format::Unserialize(ArrayValue('UserOptional', $Handshake, array()));
      }
      return ArrayValue('Roles', $UserOptional, '');
   }
Ejemplo n.º 3
0
 public function controller_index($Sender)
 {
     $Sender->Permission(array('Garden.Profiles.Edit'));
     $Args = $Sender->RequestArgs;
     if (sizeof($Args) < 2) {
         $Args = array_merge($Args, array(0, 0));
     } elseif (sizeof($Args) > 2) {
         $Args = array_slice($Args, 0, 2);
     }
     list($UserReference, $Username) = $Args;
     $canEditSignatures = CheckPermission('Plugins.Signatures.Edit');
     // Normalize no image config setting
     if (C('Plugins.Signatures.MaxNumberImages') === 0 || C('Plugins.Signatures.MaxNumberImages') === '0') {
         SaveToConfig('Plugins.Signatures.MaxNumberImages', 'None');
     }
     $Sender->GetUserInfo($UserReference, $Username);
     $UserPrefs = Gdn_Format::Unserialize($Sender->User->Preferences);
     if (!is_array($UserPrefs)) {
         $UserPrefs = array();
     }
     $Validation = new Gdn_Validation();
     $ConfigurationModel = new Gdn_ConfigurationModel($Validation);
     $ConfigArray = array('Plugin.Signatures.Sig' => NULL, 'Plugin.Signatures.HideAll' => NULL, 'Plugin.Signatures.HideImages' => NULL, 'Plugin.Signatures.HideMobile' => NULL, 'Plugin.Signatures.Format' => NULL);
     $SigUserID = $ViewingUserID = Gdn::Session()->UserID;
     if ($Sender->User->UserID != $ViewingUserID) {
         $Sender->Permission(array('Garden.Users.Edit', 'Moderation.Signatures.Edit'), FALSE);
         $SigUserID = $Sender->User->UserID;
         $canEditSignatures = true;
     }
     $Sender->SetData('CanEdit', $canEditSignatures);
     $Sender->SetData('Plugin-Signatures-ForceEditing', $SigUserID == Gdn::Session()->UserID ? FALSE : $Sender->User->Name);
     $UserMeta = $this->GetUserMeta($SigUserID, '%');
     if ($Sender->Form->AuthenticatedPostBack() === FALSE && is_array($UserMeta)) {
         $ConfigArray = array_merge($ConfigArray, $UserMeta);
     }
     $ConfigurationModel->SetField($ConfigArray);
     // Set the model on the form.
     $Sender->Form->SetModel($ConfigurationModel);
     $Data = $ConfigurationModel->Data;
     $Sender->SetData('Signature', $Data);
     $this->SetSignatureRules($Sender);
     // Form submission handling.
     if ($Sender->Form->AuthenticatedPostBack()) {
         $Values = $Sender->Form->FormValues();
         if ($canEditSignatures) {
             $Values['Plugin.Signatures.Sig'] = GetValue('Body', $Values, NULL);
             $Values['Plugin.Signatures.Format'] = GetValue('Format', $Values, NULL);
         }
         //$this->StripLineBreaks($Values['Plugin.Signatures.Sig']);
         $FrmValues = array_intersect_key($Values, $ConfigArray);
         if (sizeof($FrmValues)) {
             if (!GetValue($this->MakeMetaKey('Sig'), $FrmValues)) {
                 // Delete the signature.
                 $FrmValues[$this->MakeMetaKey('Sig')] = NULL;
                 $FrmValues[$this->MakeMetaKey('Format')] = NULL;
             }
             $this->CrossCheckSignature($Values, $Sender);
             if ($Sender->Form->ErrorCount() == 0) {
                 foreach ($FrmValues as $UserMetaKey => $UserMetaValue) {
                     $Key = $this->TrimMetaKey($UserMetaKey);
                     switch ($Key) {
                         case 'Format':
                             if (strcasecmp($UserMetaValue, 'Raw') == 0) {
                                 $UserMetaValue = NULL;
                             }
                             // don't allow raw signatures.
                             break;
                     }
                     $this->SetUserMeta($SigUserID, $Key, $UserMetaValue);
                 }
                 $Sender->InformMessage(T("Your changes have been saved."));
             }
         }
     } else {
         // Load form data.
         $Data['Body'] = GetValue('Plugin.Signatures.Sig', $Data);
         $Data['Format'] = GetValue('Plugin.Signatures.Format', $Data) ?: Gdn_Format::DefaultFormat();
         // Apply the config settings to the form.
         $Sender->Form->SetData($Data);
     }
     $Sender->Render('signature', '', 'plugins/Signatures');
 }
Ejemplo n.º 4
0
 public function ProfileController_Signature_Create(&$Sender)
 {
     if (!C('Plugins.Signatures.Enabled')) {
         return;
     }
     $Args = $Sender->RequestArgs;
     if (sizeof($Args) < 2) {
         $Args = array_merge($Args, array(0, 0));
     } elseif (sizeof($Args) > 2) {
         $Args = array_slice($Args, 0, 2);
     }
     list($UserReference, $Username) = $Args;
     $Sender->Permission('Garden.SignIn.Allow');
     $Sender->GetUserInfo($UserReference, $Username);
     $UserPrefs = Gdn_Format::Unserialize($Sender->User->Preferences);
     if (!is_array($UserPrefs)) {
         $UserPrefs = array();
     }
     $Validation = new Gdn_Validation();
     $ConfigurationModel = new Gdn_ConfigurationModel($Validation);
     $ConfigArray = array('Plugin.Signatures.Sig' => NULL, 'Plugin.Signatures.HideAll' => NULL, 'Plugin.Signatures.HideImages' => NULL);
     $SigUserID = $ViewingUserID = Gdn::Session()->UserID;
     if ($Sender->User->UserID != $ViewingUserID) {
         $Sender->Permission('Garden.Users.Edit');
         $SigUserID = $Sender->User->UserID;
     }
     $Sender->SetData('Plugin-Signatures-ForceEditing', $SigUserID == Gdn::Session()->UserID ? FALSE : $Sender->User->Name);
     // TIM: Waiting for RC3...
     $UserMeta = $this->GetUserMeta($SigUserID, '%');
     // TIM: Leaving this here until RC3+
     // $UserMeta = $this->_GetUserSignatureData($SigUserID);
     //
     if ($Sender->Form->AuthenticatedPostBack() === FALSE && is_array($UserMeta)) {
         $ConfigArray = array_merge($ConfigArray, $UserMeta);
     }
     $ConfigurationModel->SetField($ConfigArray);
     // Set the model on the form.
     $Sender->Form->SetModel($ConfigurationModel);
     // If seeing the form for the first time...
     if ($Sender->Form->AuthenticatedPostBack() === FALSE) {
         // Apply the config settings to the form.
         $Sender->Form->SetData($ConfigurationModel->Data);
     } else {
         $Values = $Sender->Form->FormValues();
         $FrmValues = array_intersect_key($Values, $ConfigArray);
         if (sizeof($FrmValues)) {
             foreach ($FrmValues as $UserMetaKey => $UserMetaValue) {
                 $this->SetUserMeta($SigUserID, $this->TrimMetaKey($UserMetaKey), $UserMetaValue);
                 /*
                                try {
                                   Gdn::SQL()->Insert('UserMeta', array(
                                         'UserID' => $SigUserID,
                                         'Name'   => $UserMetaKey,
                                         'Value'  => $UserMetaValue
                                      ));
                                } catch (Exception $e) {
                                   Gdn::SQL()
                                      ->Update('UserMeta')
                                      ->Set('Value', $UserMetaValue)
                                      ->Where('UserID', $SigUserID)
                                      ->Where('Name', $UserMetaKey)
                                      ->Put();
                                }
                 */
             }
         }
         $Sender->StatusMessage = T("Your changes have been saved.");
     }
     $Sender->Render($this->GetView('signature.php'));
 }
Ejemplo n.º 5
0
 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();
 }
   public function Preferences($UserReference = '', $Username = '', $UserID = '') {
      $Session = Gdn::Session();
      $this->Permission('Garden.SignIn.Allow');
      $this->GetUserInfo($UserReference, $Username, $UserID);
		$UserPrefs = Gdn_Format::Unserialize($this->User->Preferences);
      if (!is_array($UserPrefs))
         $UserPrefs = array();
      $MetaPrefs = UserModel::GetMeta($this->User->UserID, 'Preferences.%', 'Preferences.');


      // Define the preferences to be managed
      $this->Preferences = array(
         'Notifications' => array(
            'Email.WallComment' => T('Notify me when people write on my wall.'),
            'Email.ActivityComment' => T('Notify me when people reply to my wall comments.'),
            'Popup.WallComment' => T('Notify me when people write on my wall.'),
            'Popup.ActivityComment' => T('Notify me when people reply to my wall comments.')
         )
      );
      
      $this->FireEvent('AfterPreferencesDefined');
		
		// Loop through the preferences looking for duplicates, and merge into a single row
		$this->PreferenceGroups = array();
		$this->PreferenceTypes = array();
		foreach ($this->Preferences as $PreferenceGroup => $Preferences) {
			$this->PreferenceGroups[$PreferenceGroup] = array();
			$this->PreferenceTypes[$PreferenceGroup] = array();
			foreach ($Preferences as $Name => $Description) {
            $Location = 'Prefs';
            if (is_array($Description))
               list($Description, $Location) = $Description;

				$NameParts = explode('.', $Name);
				$PrefType = GetValue('0', $NameParts);
				$SubName = GetValue('1', $NameParts);
				if ($SubName != FALSE) {
					// Save an array of all the different types for this group
					if (!in_array($PrefType, $this->PreferenceTypes[$PreferenceGroup]))
						$this->PreferenceTypes[$PreferenceGroup][] = $PrefType;
					
					// Store all the different subnames for the group	
					if (!array_key_exists($SubName, $this->PreferenceGroups[$PreferenceGroup])) {
						$this->PreferenceGroups[$PreferenceGroup][$SubName] = array($Name);
					} else {
						$this->PreferenceGroups[$PreferenceGroup][$SubName][] = $Name;
					}
				} else {
					$this->PreferenceGroups[$PreferenceGroup][$Name] = array($Name);
				}
			}
		}
		
      if ($this->User->UserID != $Session->UserID)
         $this->Permission('Garden.Users.Edit');

      // Loop the preferences, setting defaults from the configuration.
      $Defaults = array();
      foreach ($this->Preferences as $PrefGroup => $Prefs) {
         foreach ($Prefs as $Pref => $Desc) {
            $Location = 'Prefs';
            if (is_array($Desc))
               list($Desc, $Location) = $Desc;

            if ($Location == 'Meta')
               $Defaults[$Pref] = GetValue($Pref, $MetaPrefs, FALSE);
            else
               $Defaults[$Pref] = GetValue($Pref, $UserPrefs, C('Preferences.'.$Pref, '0'));
         }
      }
         
      if ($this->Form->AuthenticatedPostBack() === FALSE) {
         $this->Form->SetData($Defaults);
      } else {
         // Get, assign, and save the preferences.
         $Meta = array();
         foreach ($this->Preferences as $PrefGroup => $Prefs) {
            foreach ($Prefs as $Pref => $Desc) {
               $Location = 'Prefs';
               if (is_array($Desc))
                  list($Desc, $Location) = $Desc;

               $Value = $this->Form->GetValue($Pref, FALSE);

               if ($Location == 'Meta') {
                  $Meta[$Pref] = $Value ? $Value : NULL;
                  if ($Value)
                     $UserPrefs[$Pref] = $Value; // dup for notifications code.
               } else {
                  if (!$Defaults[$Pref] && !$Value)
                     unset($UserPrefs[$Pref]); // save some space
                  else
                     $UserPrefs[$Pref] = $Value;
               }
            }
         }
         $this->UserModel->SavePreference($this->User->UserID, $UserPrefs);
         UserModel::SetMeta($this->User->UserID, $Meta, 'Preferences.');
			$this->InformMessage('<span class="InformSprite Check"></span>'.T('Your preferences have been saved.'), 'Dismissable AutoDismiss HasSprite');
      }
      $this->Render();
   }
 /**
  * Theme management screen.
  */
 public function Themes($ThemeFolder = '', $TransientKey = '')
 {
     $this->AddJsFile('addons.js');
     $this->SetData('Title', T('Themes'));
     $this->Permission('Garden.Themes.Manage');
     $this->AddSideMenu('dashboard/settings/themes');
     $Session = Gdn::Session();
     $ThemeManager = new Gdn_ThemeManager();
     $AvailableThemes = $ThemeManager->AvailableThemes();
     $this->SetData('EnabledThemeFolder', $ThemeManager->EnabledTheme());
     $this->SetData('EnabledTheme', $ThemeManager->EnabledThemeInfo());
     $this->SetData('EnabledThemeName', $this->Data('EnabledTheme.Name', $this->Data('EnabledTheme.Folder')));
     // Loop through all of the available themes and mark them if they have an update available
     // Retrieve the list of themes that require updates from the config file
     $RequiredUpdates = Gdn_Format::Unserialize(Gdn::Config('Garden.RequiredUpdates', ''));
     if (is_array($RequiredUpdates)) {
         foreach ($RequiredUpdates as $UpdateInfo) {
             if (is_object($UpdateInfo)) {
                 $UpdateInfo = Gdn_Format::ObjectAsArray($UpdateInfo);
             }
             $NewVersion = ArrayValue('Version', $UpdateInfo, '');
             $Name = ArrayValue('Name', $UpdateInfo, '');
             $Type = ArrayValue('Type', $UpdateInfo, '');
             foreach ($AvailableThemes as $Theme => $Info) {
                 $CurrentName = ArrayValue('Name', $Info, $Theme);
                 if ($CurrentName == $Name && $Type == 'Theme') {
                     $Info['NewVersion'] = $NewVersion;
                     $AvailableThemes[$Theme] = $Info;
                 }
             }
         }
     }
     $this->SetData('AvailableThemes', $AvailableThemes);
     if ($Session->ValidateTransientKey($TransientKey) && $ThemeFolder != '') {
         try {
             foreach ($this->Data('AvailableThemes') as $ThemeName => $ThemeInfo) {
                 if ($ThemeInfo['Folder'] == $ThemeFolder) {
                     $Session->SetPreference(array('PreviewThemeName' => '', 'PreviewThemeFolder' => ''));
                     // Clear out the preview
                     $ThemeManager->EnableTheme($ThemeName);
                     $this->EventArguments['ThemeName'] = $ThemeName;
                     $this->EventArguments['ThemeInfo'] = $ThemeInfo;
                     $this->FireEvent('AfterEnableTheme');
                 }
             }
         } catch (Exception $Ex) {
             $this->Form->AddError($Ex);
         }
         if ($this->Form->ErrorCount() == 0) {
             Redirect('/settings/themes');
         }
     }
     $this->Render();
 }
Ejemplo n.º 8
0
 public function GetAttribute($UserID, $Attribute, $DefaultValue = FALSE)
 {
     $Data = $this->SQL->Select('Attributes')->From('User')->Where('UserID', $UserID)->Get()->FirstRow();
     if ($Data !== FALSE) {
         $Attributes = Gdn_Format::Unserialize($Data->Attributes);
         if (is_array($Attributes)) {
             return ArrayValue($Attribute, $Attributes, $DefaultValue);
         }
     }
     return $DefaultValue;
 }
 /**
  * Validate User Credential
  *
  * Fetches a user row by email (or name) and compare the password.
  *
  * If the password was not stored as a blowfish hash,
  * the password will be saved again.
  *
  * Return the user's id, admin status and attributes.
  *
  * @param string $Email
  * @param string $Password
  * @return object
  */
 public function ValidateCredentials($Email = '', $ID = 0, $Password)
 {
     $this->EventArguments['Credentials'] = array('Email' => $Email, 'ID' => $ID, 'Password' => $Password);
     $this->FireEvent('BeforeValidateCredentials');
     if (!$Email && !$ID) {
         throw new Exception('The email or id is required');
     }
     try {
         $this->SQL->Select('UserID, Name, Attributes, Admin, Password, HashMethod, Deleted, Banned')->From('User');
         if ($ID) {
             $this->SQL->Where('UserID', $ID);
         } else {
             if (strpos($Email, '@') > 0) {
                 $this->SQL->Where('Email', $Email);
             } else {
                 $this->SQL->Where('Name', $Email);
             }
         }
         $DataSet = $this->SQL->Get();
     } catch (Exception $Ex) {
         $this->SQL->Reset();
         // Try getting the user information without the new fields.
         $this->SQL->Select('UserID, Name, Attributes, Admin, Password')->From('User');
         if ($ID) {
             $this->SQL->Where('UserID', $ID);
         } else {
             if (strpos($Email, '@') > 0) {
                 $this->SQL->Where('Email', $Email);
             } else {
                 $this->SQL->Where('Name', $Email);
             }
         }
         $DataSet = $this->SQL->Get();
     }
     if ($DataSet->NumRows() < 1) {
         return FALSE;
     }
     $UserData = $DataSet->FirstRow();
     // Check for a deleted user.
     if (GetValue('Deleted', $UserData)) {
         return FALSE;
     }
     $PasswordHash = new Gdn_PasswordHash();
     $HashMethod = GetValue('HashMethod', $UserData);
     if (!$PasswordHash->CheckPassword($Password, $UserData->Password, $HashMethod, $UserData->Name)) {
         return FALSE;
     }
     if ($PasswordHash->Weak || $HashMethod && strcasecmp($HashMethod, 'Vanilla') != 0) {
         $Pw = $PasswordHash->HashPassword($Password);
         $this->SQL->Update('User')->Set('Password', $Pw)->Set('HashMethod', 'Vanilla')->Where('UserID', $UserData->UserID)->Put();
     }
     $UserData->Attributes = Gdn_Format::Unserialize($UserData->Attributes);
     return $UserData;
 }
Ejemplo n.º 10
0
 /**
  * Authenticates the user with the provided Authenticator class.
  *
  * @param int $UserID The UserID to start the session with.
  * @param bool $SetIdentity Whether or not to set the identity (cookie) or make this a one request session.
  * @param bool $Persist If setting an identity, should we persist it beyond browser restart?
  */
 public function Start($UserID = FALSE, $SetIdentity = TRUE, $Persist = FALSE)
 {
     if (!C('Garden.Installed', FALSE)) {
         return;
     }
     // Retrieve the authenticated UserID from the Authenticator module.
     $UserModel = Gdn::Authenticator()->GetUserModel();
     $this->UserID = $UserID !== FALSE ? $UserID : Gdn::Authenticator()->GetIdentity();
     $this->User = FALSE;
     // Now retrieve user information
     if ($this->UserID > 0) {
         // Instantiate a UserModel to get session info
         $this->User = $UserModel->GetSession($this->UserID);
         if ($this->User) {
             if ($SetIdentity) {
                 Gdn::Authenticator()->SetIdentity($this->UserID, $Persist);
             }
             $UserModel->EventArguments['User'] =& $this->User;
             $UserModel->FireEvent('AfterGetSession');
             $this->_Permissions = Gdn_Format::Unserialize($this->User->Permissions);
             $this->_Preferences = Gdn_Format::Unserialize($this->User->Preferences);
             $this->_Attributes = Gdn_Format::Unserialize($this->User->Attributes);
             $this->_TransientKey = is_array($this->_Attributes) ? ArrayValue('TransientKey', $this->_Attributes) : FALSE;
             if ($this->_TransientKey === FALSE) {
                 $this->_TransientKey = $UserModel->SetTransientKey($this->UserID);
             }
             // Save any visit-level information.
             $UserModel->UpdateVisit($this->UserID);
         } else {
             $this->UserID = 0;
             $this->User = FALSE;
             if ($SetIdentity) {
                 Gdn::Authenticator()->SetIdentity(NULL);
             }
         }
     }
     // Load guest permissions if necessary
     if ($this->UserID == 0) {
         $this->_Permissions = Gdn_Format::Unserialize($UserModel->DefinePermissions(0));
     }
 }
Ejemplo n.º 11
0
 /**
  * Gets a setting from the configuration array. Returns $DefaultValue if the value isn't found.
  *
  * @param string $Name The name of the configuration setting to get. If the setting is contained
  * within an associative array, use dot denomination to get the setting. ie.
  * <code>$this->Get('Database.Host')</code> would retrieve <code>$Configuration[$Group]['Database']['Host']</code>.
  * @param mixed $DefaultValue If the parameter is not found in the group, this value will be returned.
  * @return mixed The configuration value.
  */
 public function Get($Name, $DefaultValue = FALSE)
 {
     $Path = explode('.', $Name);
     $Value = $this->_Data;
     $Count = count($Path);
     for ($i = 0; $i < $Count; ++$i) {
         if (is_array($Value) && array_key_exists($Path[$i], $Value)) {
             $Value = $Value[$Path[$i]];
         } else {
             return $DefaultValue;
         }
     }
     if (is_string($Value)) {
         $Result = Gdn_Format::Unserialize($Value);
     } else {
         $Result = $Value;
     }
     return $Result;
 }
Ejemplo n.º 12
0
 /**
  * Gets a setting from the configuration array. Returns $DefaultValue if the value isn't found.
  *
  * @param string $Name The name of the configuration setting to get. If the setting is contained
  * within an associative array, use dot denomination to get the setting. ie.
  * <code>$this->Get('Database.Host')</code> would retrieve <code>$Configuration[$Group]['Database']['Host']</code>.
  * @param mixed $DefaultValue If the parameter is not found in the group, this value will be returned.
  * @return mixed The configuration value.
  */
 public function Get($Name, $DefaultValue = FALSE)
 {
     // Shortcut, get the whole config
     if ($Name == '.') {
         return $this->Settings;
     }
     $Keys = explode('.', $Name);
     $KeyCount = count($Keys);
     $Value = $this->Settings;
     for ($i = 0; $i < $KeyCount; ++$i) {
         if (is_array($Value) && array_key_exists($Keys[$i], $Value)) {
             $Value = $Value[$Keys[$i]];
         } else {
             return $DefaultValue;
         }
     }
     if (is_string($Value)) {
         $Result = Gdn_Format::Unserialize($Value);
     } else {
         $Result = $Value;
     }
     return $Result;
 }
Ejemplo n.º 13
0
 /**
  * Queue a notification for sending.
  *
  * @since 2.0.17
  * @access public
  * @param int $ActivityID
  * @param string $Story
  * @param string $Position
  * @param bool $Force
  */
 public function QueueNotification($ActivityID, $Story = '', $Position = 'last', $Force = FALSE)
 {
     $Activity = $this->GetID($ActivityID);
     if (!is_object($Activity)) {
         return;
     }
     $Story = Gdn_Format::Text($Story == '' ? $Activity->Story : $Story, FALSE);
     // If this is a comment on another activity, fudge the activity a bit so that everything appears properly.
     if (is_null($Activity->RegardingUserID) && $Activity->CommentActivityID > 0) {
         $CommentActivity = $this->GetID($Activity->CommentActivityID);
         $Activity->RegardingUserID = $CommentActivity->RegardingUserID;
         $Activity->Route = '/activity/item/' . $Activity->CommentActivityID;
     }
     $User = Gdn::UserModel()->GetID($Activity->RegardingUserID, DATASET_TYPE_OBJECT);
     //$this->SQL->Select('UserID, Name, Email, Preferences')->From('User')->Where('UserID', $Activity->RegardingUserID)->Get()->FirstRow();
     if ($User) {
         if ($Force) {
             $Preference = $Force;
         } else {
             $Preferences = Gdn_Format::Unserialize($User->Preferences);
             $ConfigPreference = C('Preferences.Email.' . $Activity->ActivityType, '0');
             if ($ConfigPreference !== FALSE) {
                 $Preference = ArrayValue('Email.' . $Activity->ActivityType, $Preferences, $ConfigPreference);
             } else {
                 $Preference = FALSE;
             }
         }
         if ($Preference) {
             $ActivityHeadline = Gdn_Format::Text(Gdn_Format::ActivityHeadline($Activity, $Activity->ActivityUserID, $Activity->RegardingUserID), FALSE);
             $Email = new Gdn_Email();
             $Email->Subject(sprintf(T('[%1$s] %2$s'), Gdn::Config('Garden.Title'), $ActivityHeadline));
             $Email->To($User->Email, $User->Name);
             $Message = sprintf($Story == '' ? T('EmailNotification', "%1\$s\n\n%2\$s") : T('EmailStoryNotification', "%3\$s\n\n%2\$s"), $ActivityHeadline, ExternalUrl($Activity->Route == '' ? '/' : $Activity->Route), $Story);
             $Email->Message($Message);
             if (!array_key_exists($User->UserID, $this->_NotificationQueue)) {
                 $this->_NotificationQueue[$User->UserID] = array();
             }
             $Notification = array('ActivityID' => $ActivityID, 'User' => $User, 'Email' => $Email, 'Route' => $Activity->Route, 'Story' => $Story, 'Headline' => $ActivityHeadline, 'Activity' => $Activity);
             if ($Position == 'first') {
                 $this->_NotificationQueue[$User->UserID] = array_merge(array($Notification), $this->_NotificationQueue[$User->UserID]);
             } else {
                 $this->_NotificationQueue[$User->UserID][] = $Notification;
             }
         }
     }
 }
Ejemplo n.º 14
0
 public function DiscussionController_BeforeDiscussionRender_Handler($Sender)
 {
     if (!Gdn::Session()->IsValid()) {
         return;
     }
     $UserPrefs = Gdn_Format::Unserialize(Gdn::Session()->User->Preferences);
     if (!is_array($UserPrefs)) {
         $UserPrefs = array();
     }
     $QuoteFolding = GetValue('Quotes.Folding', $UserPrefs, '1');
     $Sender->AddDefinition('QuotesFolding', $QuoteFolding);
 }
Ejemplo n.º 15
0
 /**
  * Theme management screen.
  */
 public function Themes($ThemeFolder = '', $TransientKey = '')
 {
     $this->Title(T('Themes'));
     $this->Permission('Garden.Themes.Manage');
     $this->AddSideMenu('dashboard/settings/themes');
     $Session = Gdn::Session();
     $ThemeManager = new Gdn_ThemeManager();
     $this->AvailableThemes = $ThemeManager->AvailableThemes();
     $this->EnabledThemeFolder = $ThemeManager->EnabledTheme();
     $this->EnabledTheme = $ThemeManager->EnabledThemeInfo();
     $Name = array_keys($this->EnabledTheme);
     $Name = ArrayValue(0, $Name, 'undefined');
     $this->EnabledTheme = ArrayValue($Name, $this->EnabledTheme);
     $this->EnabledThemeName = ArrayValue('Name', $this->EnabledTheme, $Name);
     // Loop through all of the available themes and mark them if they have an update available
     // Retrieve the list of themes that require updates from the config file
     $RequiredUpdates = Gdn_Format::Unserialize(Gdn::Config('Garden.RequiredUpdates', ''));
     if (is_array($RequiredUpdates)) {
         foreach ($RequiredUpdates as $UpdateInfo) {
             if (is_object($UpdateInfo)) {
                 $UpdateInfo = Gdn_Format::ObjectAsArray($UpdateInfo);
             }
             $NewVersion = ArrayValue('Version', $UpdateInfo, '');
             $Name = ArrayValue('Name', $UpdateInfo, '');
             $Type = ArrayValue('Type', $UpdateInfo, '');
             foreach ($this->AvailableThemes as $Theme => $Info) {
                 $CurrentName = ArrayValue('Name', $Info, $Theme);
                 if ($CurrentName == $Name && $Type == 'Theme') {
                     $Info['NewVersion'] = $NewVersion;
                     $this->AvailableThemes[$Theme] = $Info;
                 }
             }
         }
     }
     if ($Session->ValidateTransientKey($TransientKey) && $ThemeFolder != '') {
         try {
             foreach ($this->AvailableThemes as $ThemeName => $ThemeInfo) {
                 if ($ThemeInfo['Folder'] == $ThemeFolder) {
                     $Session->SetPreference('PreviewTheme', '');
                     // Clear out the preview
                     $Test = ProxyRequest(Url('/dashboard/settings/testaddon/Theme/' . $ThemeName . '/' . $Session->TransientKey() . '?DeliveryType=JSON', TRUE));
                     if ($Test != 'Success') {
                         $this->Form->AddError(sprintf(T('The theme could not be enabled because it generated a fatal error: <pre>%s</pre>'), strip_tags($Test)));
                     } else {
                         $ThemeManager->EnableTheme($ThemeName);
                     }
                 }
             }
         } catch (Exception $e) {
             $this->Form->AddError(strip_tags($e->getMessage()));
         }
         if ($this->Form->ErrorCount() == 0) {
             Redirect('/settings/themes');
         }
     }
     $this->Render();
 }
Ejemplo n.º 16
0
 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));
     }
 }
Ejemplo n.º 17
0
 /**
  * Convert tags from stored format to user-presentable format.
  *
  * @since 2.1
  * @access protected
  *
  * @param string Serialized array.
  * @return string Comma-separated tags.
  */
 protected function formatTags($Tags)
 {
     // Don't bother if there aren't any tags
     if (!$Tags) {
         return '';
     }
     // Get the array
     $TagsArray = Gdn_Format::Unserialize($Tags);
     // Compensate for deprecated space-separated format
     if (is_string($TagsArray) && $TagsArray == $Tags) {
         $TagsArray = explode(' ', $Tags);
     }
     // Safe format
     $TagsArray = Gdn_Format::text($TagsArray);
     // Send back an comma-separated string
     return is_array($TagsArray) ? implode(',', $TagsArray) : '';
 }
 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;
 }
 /**
  * Themes management screen.
  *
  * @since 2.0.0
  * @access public
  * @param string $ThemeName Unique ID.
  * @param string $TransientKey Security token.
  */
 public function Themes($ThemeName = '', $TransientKey = '')
 {
     $this->AddJsFile('addons.js');
     $this->SetData('Title', T('Themes'));
     $this->Permission('Garden.Settings.Manage');
     $this->AddSideMenu('dashboard/settings/themes');
     $ThemeInfo = Gdn::ThemeManager()->EnabledThemeInfo(TRUE);
     $this->SetData('EnabledThemeFolder', GetValue('Folder', $ThemeInfo));
     $this->SetData('EnabledTheme', Gdn::ThemeManager()->EnabledThemeInfo());
     $this->SetData('EnabledThemeName', GetValue('Name', $ThemeInfo, GetValue('Index', $ThemeInfo)));
     // Loop through all of the available themes and mark them if they have an update available
     // Retrieve the list of themes that require updates from the config file
     $RequiredUpdates = Gdn_Format::Unserialize(Gdn::Config('Garden.RequiredUpdates', ''));
     if (is_array($RequiredUpdates)) {
         foreach ($RequiredUpdates as $UpdateInfo) {
             if (is_object($UpdateInfo)) {
                 $UpdateInfo = Gdn_Format::ObjectAsArray($UpdateInfo);
             }
             $NewVersion = ArrayValue('Version', $UpdateInfo, '');
             $Name = ArrayValue('Name', $UpdateInfo, '');
             $Type = ArrayValue('Type', $UpdateInfo, '');
             foreach (Gdn::ThemeManager()->AvailableThemes() as $Theme => $Info) {
                 $CurrentName = ArrayValue('Name', $Info, $Theme);
                 if ($CurrentName == $Name && $Type == 'Theme') {
                     $Info['NewVersion'] = $NewVersion;
                     $AvailableThemes[$Theme] = $Info;
                 }
             }
         }
     }
     $Themes = Gdn::ThemeManager()->AvailableThemes();
     uasort($Themes, array('SettingsController', '_NameSort'));
     // Remove themes that are archived
     $Remove = array();
     foreach ($Themes as $Index => $Theme) {
         $Archived = GetValue('Archived', $Theme);
         if ($Archived) {
             $Remove[] = $Index;
         }
     }
     foreach ($Remove as $Index) {
         unset($Themes[$Index]);
     }
     $this->SetData('AvailableThemes', $Themes);
     if (Gdn::Session()->ValidateTransientKey($TransientKey) && $ThemeName != '') {
         try {
             $ThemeInfo = Gdn::ThemeManager()->GetThemeInfo($ThemeName);
             if ($ThemeInfo === FALSE) {
                 throw new Exception(sprintf(T("Could not find a theme identified by '%s'"), $ThemeName));
             }
             Gdn::Session()->SetPreference(array('PreviewThemeName' => '', 'PreviewThemeFolder' => ''));
             // Clear out the preview
             Gdn::ThemeManager()->EnableTheme($ThemeName);
             $this->EventArguments['ThemeName'] = $ThemeName;
             $this->EventArguments['ThemeInfo'] = $ThemeInfo;
             $this->FireEvent('AfterEnableTheme');
         } catch (Exception $Ex) {
             $this->Form->AddError($Ex);
         }
         if ($this->Form->ErrorCount() == 0) {
             Redirect('/settings/themes');
         }
     }
     $this->Render();
 }
 /**
  * Edit user's preferences (mostly notification settings).
  *
  * @since 2.0.0
  * @access public
  * @param mixed $UserReference Unique identifier, possibly username or ID.
  * @param string $Username.
  * @param int $UserID Unique identifier.
  */
 public function Preferences($UserReference = '', $Username = '', $UserID = '')
 {
     $this->AddJsFile('profile.js');
     $Session = Gdn::Session();
     $this->Permission('Garden.SignIn.Allow');
     // Get user data
     $this->GetUserInfo($UserReference, $Username, $UserID, TRUE);
     $UserPrefs = Gdn_Format::Unserialize($this->User->Preferences);
     if ($this->User->UserID != $Session->UserID) {
         $this->Permission(array('Garden.Users.Edit', 'Moderation.Profiles.Edit'), FALSE);
     }
     if (!is_array($UserPrefs)) {
         $UserPrefs = array();
     }
     $MetaPrefs = UserModel::GetMeta($this->User->UserID, 'Preferences.%', 'Preferences.');
     // Define the preferences to be managed
     $this->Preferences = array('Notifications' => array('Email.WallComment' => T('Notify me when people write on my wall.'), 'Email.ActivityComment' => T('Notify me when people reply to my wall comments.'), 'Popup.WallComment' => T('Notify me when people write on my wall.'), 'Popup.ActivityComment' => T('Notify me when people reply to my wall comments.')));
     // Allow email notification of applicants (if they have permission & are using approval registration)
     if (CheckPermission('Garden.Users.Approve') && C('Garden.Registration.Method') == 'Approval') {
         $this->Preferences['Notifications']['Email.Applicant'] = array(T('NotifyApplicant', 'Notify me when anyone applies for membership.'), 'Meta');
     }
     $this->FireEvent('AfterPreferencesDefined');
     // Loop through the preferences looking for duplicates, and merge into a single row
     $this->PreferenceGroups = array();
     $this->PreferenceTypes = array();
     foreach ($this->Preferences as $PreferenceGroup => $Preferences) {
         $this->PreferenceGroups[$PreferenceGroup] = array();
         $this->PreferenceTypes[$PreferenceGroup] = array();
         foreach ($Preferences as $Name => $Description) {
             $Location = 'Prefs';
             if (is_array($Description)) {
                 list($Description, $Location) = $Description;
             }
             $NameParts = explode('.', $Name);
             $PrefType = GetValue('0', $NameParts);
             $SubName = GetValue('1', $NameParts);
             if ($SubName != FALSE) {
                 // Save an array of all the different types for this group
                 if (!in_array($PrefType, $this->PreferenceTypes[$PreferenceGroup])) {
                     $this->PreferenceTypes[$PreferenceGroup][] = $PrefType;
                 }
                 // Store all the different subnames for the group
                 if (!array_key_exists($SubName, $this->PreferenceGroups[$PreferenceGroup])) {
                     $this->PreferenceGroups[$PreferenceGroup][$SubName] = array($Name);
                 } else {
                     $this->PreferenceGroups[$PreferenceGroup][$SubName][] = $Name;
                 }
             } else {
                 $this->PreferenceGroups[$PreferenceGroup][$Name] = array($Name);
             }
         }
     }
     // Loop the preferences, setting defaults from the configuration.
     $CurrentPrefs = array();
     foreach ($this->Preferences as $PrefGroup => $Prefs) {
         foreach ($Prefs as $Pref => $Desc) {
             $Location = 'Prefs';
             if (is_array($Desc)) {
                 list($Desc, $Location) = $Desc;
             }
             if ($Location == 'Meta') {
                 $CurrentPrefs[$Pref] = GetValue($Pref, $MetaPrefs, FALSE);
             } else {
                 $CurrentPrefs[$Pref] = GetValue($Pref, $UserPrefs, C('Preferences.' . $Pref, '0'));
             }
             unset($MetaPrefs[$Pref]);
         }
     }
     $CurrentPrefs = array_merge($CurrentPrefs, $MetaPrefs);
     $CurrentPrefs = array_map('intval', $CurrentPrefs);
     $this->SetData('Preferences', $CurrentPrefs);
     if (UserModel::NoEmail()) {
         $this->PreferenceGroups = self::_RemoveEmailPreferences($this->PreferenceGroups);
         $this->PreferenceTypes = self::_RemoveEmailPreferences($this->PreferenceTypes);
         $this->SetData('NoEmail', TRUE);
     }
     $this->SetData('PreferenceGroups', $this->PreferenceGroups);
     $this->SetData('PreferenceTypes', $this->PreferenceTypes);
     $this->SetData('PreferenceList', $this->Preferences);
     if ($this->Form->AuthenticatedPostBack()) {
         // Get, assign, and save the preferences.
         $NewMetaPrefs = array();
         foreach ($this->Preferences as $PrefGroup => $Prefs) {
             foreach ($Prefs as $Pref => $Desc) {
                 $Location = 'Prefs';
                 if (is_array($Desc)) {
                     list($Desc, $Location) = $Desc;
                 }
                 $Value = $this->Form->GetValue($Pref, NULL);
                 if (is_null($Value)) {
                     continue;
                 }
                 if ($Location == 'Meta') {
                     $NewMetaPrefs[$Pref] = $Value ? $Value : NULL;
                     if ($Value) {
                         $UserPrefs[$Pref] = $Value;
                     }
                     // dup for notifications code.
                 } else {
                     if (!$CurrentPrefs[$Pref] && !$Value) {
                         unset($UserPrefs[$Pref]);
                     } else {
                         $UserPrefs[$Pref] = $Value;
                     }
                 }
             }
         }
         $this->UserModel->SavePreference($this->User->UserID, $UserPrefs);
         UserModel::SetMeta($this->User->UserID, $NewMetaPrefs, 'Preferences.');
         $this->SetData('Preferences', array_merge($this->Data('Preferences', array()), $UserPrefs, $NewMetaPrefs));
         if (count($this->Form->Errors() == 0)) {
             $this->InformMessage(Sprite('Check', 'InformSprite') . T('Your preferences have been saved.'), 'Dismissable AutoDismiss HasSprite');
         }
     } else {
         $this->Form->SetData($CurrentPrefs);
     }
     $this->Title(T('Notification Preferences'));
     $this->_SetBreadcrumbs($this->Data('Title'), $this->CanonicalUrl());
     $this->Render();
 }
   public function UpdateResponse() {
      // Get the message, response, and transientkey
      $Messages = TrueStripSlashes(GetValue('Messages', $_POST));
      $Response = TrueStripSlashes(GetValue('Response', $_POST));
      $TransientKey = GetIncomingValue('TransientKey', '');
      
      // If the key validates
      $Session = Gdn::Session();
      if ($Session->ValidateTransientKey($TransientKey)) {
         // If messages wasn't empty
         if ($Messages != '') {
            // Unserialize them & save them if necessary
            $Messages = Gdn_Format::Unserialize($Messages);
            if (is_array($Messages)) {
               $MessageModel = new MessageModel();
               foreach ($Messages as $Message) {
                  // Check to see if it already exists, and if not, add it.
                  if (is_object($Message))
                     $Message = Gdn_Format::ObjectAsArray($Message);

                  $Content = ArrayValue('Content', $Message, '');
                  if ($Content != '') {
                     $Data = $MessageModel->GetWhere(array('Content' => $Content));
                     if ($Data->NumRows() == 0) {
                        $MessageModel->Save(array(
                           'Content' => $Content,
                           'AllowDismiss' => ArrayValue('AllowDismiss', $Message, '1'),
                           'Enabled' => ArrayValue('Enabled', $Message, '1'),
                           'Application' => ArrayValue('Application', $Message, 'Dashboard'),
                           'Controller' => ArrayValue('Controller', $Message, 'Settings'),
                           'Method' => ArrayValue('Method', $Message, ''),
                           'AssetTarget' => ArrayValue('AssetTarget', $Message, 'Content'),
                           'CssClass' => ArrayValue('CssClass', $Message, '')
                        ));
                     }
                  }
               }
            }
         }

         // Save some info to the configuration file
         $Save = array();

         // If the response wasn't empty, save it in the config
         if ($Response != '')
            $Save['Garden.RequiredUpdates'] = Gdn_Format::Unserialize($Response);
      
         // Record the current update check time in the config.
         $Save['Garden.UpdateCheckDate'] = time();
         SaveToConfig($Save);
      }
   }
 /**
  * Queue a notification for sending.
  */
 public function QueueNotification($ActivityID, $Story = '')
 {
     $Activity = $this->GetID($ActivityID);
     if (!is_object($Activity)) {
         return;
     }
     $Story = Gdn_Format::Text($Story == '' ? $Activity->Story : $Story, FALSE);
     // If this is a comment on another activity, fudge the activity a bit so that everything appears properly.
     if (is_null($Activity->RegardingUserID) && $Activity->CommentActivityID > 0) {
         $CommentActivity = $this->GetID($Activity->CommentActivityID);
         $Activity->RegardingUserID = $CommentActivity->RegardingUserID;
         $Activity->Route = '/profile/' . $CommentActivity->RegardingUserID . '/' . Gdn_Format::Url($CommentActivity->RegardingName) . '/#Activity_' . $Activity->CommentActivityID;
     }
     $User = $this->SQL->Select('UserID, Name, Email, Preferences')->From('User')->Where('UserID', $Activity->RegardingUserID)->Get()->FirstRow();
     if ($User) {
         $Preferences = Gdn_Format::Unserialize($User->Preferences);
         $Preference = ArrayValue('Email.' . $Activity->ActivityType, $Preferences, Gdn::Config('Preferences.Email.' . $Activity->ActivityType));
         if ($Preference) {
             $ActivityHeadline = Gdn_Format::Text(Gdn_Format::ActivityHeadline($Activity, $Activity->ActivityUserID, $Activity->RegardingUserID), FALSE);
             $Email = new Gdn_Email();
             $Email->Subject(sprintf(T('[%1$s] %2$s'), Gdn::Config('Garden.Title'), $ActivityHeadline));
             $Email->To($User->Email, $User->Name);
             //$Email->From(Gdn::Config('Garden.SupportEmail'), Gdn::Config('Garden.SupportName'));
             $Email->Message(sprintf(T($Story == '' ? 'EmailNotification' : 'EmailStoryNotification'), $ActivityHeadline, Url($Activity->Route == '' ? '/' : $Activity->Route, TRUE), $Story));
             if (!array_key_exists($User->UserID, $this->_NotificationQueue)) {
                 $this->_NotificationQueue[$User->UserID] = array();
             }
             $this->_NotificationQueue[$User->UserID][] = array('ActivityID' => $ActivityID, 'User' => $User, 'Email' => $Email);
         }
     }
 }
Ejemplo n.º 23
0
 /**
  * Authenticates the user with the provided Authenticator class.
  *
  * @param int $UserID The UserID to start the session with.
  * @param bool $SetIdentity Whether or not to set the identity (cookie) or make this a one request session.
  */
 public function Start($UserID = FALSE, $SetIdentity = TRUE)
 {
     if (!Gdn::Config('Garden.Installed')) {
         return;
     }
     // Retrieve the authenticated UserID from the Authenticator module.
     $UserModel = Gdn::Authenticator()->GetUserModel();
     $this->UserID = $UserID ? $UserID : Gdn::Authenticator()->GetIdentity();
     $this->User = FALSE;
     // Now retrieve user information
     if ($this->UserID > 0) {
         // Instantiate a UserModel to get session info
         $this->User = $UserModel->GetSession($this->UserID);
         if ($this->User) {
             if ($UserID && $SetIdentity) {
                 Gdn::Authenticator()->SetIdentity($UserID);
             }
             if (Gdn::Authenticator()->ReturningUser($this->User)) {
                 $UserModel->UpdateLastVisit($this->UserID, $this->User->Attributes, $this->User->Attributes['HourOffset']);
             }
             $UserModel->EventArguments['User'] =& $this->User;
             $UserModel->FireEvent('AfterGetSession');
             $this->_Permissions = Gdn_Format::Unserialize($this->User->Permissions);
             $this->_Preferences = Gdn_Format::Unserialize($this->User->Preferences);
             $this->_Attributes = Gdn_Format::Unserialize($this->User->Attributes);
             $this->_TransientKey = is_array($this->_Attributes) ? ArrayValue('TransientKey', $this->_Attributes) : FALSE;
             if ($this->_TransientKey === FALSE) {
                 $this->_TransientKey = $UserModel->SetTransientKey($this->UserID);
             }
             // If the user hasn't been active in the session-time, update their date last active
             $SessionLength = Gdn::Config('Garden.Session.Length', '15 minutes');
             if (Gdn_Format::ToTimestamp($this->User->DateLastActive) < strtotime($SessionLength . ' ago')) {
                 $UserModel->Save(array('UserID' => $this->UserID, 'DateLastActive' => Gdn_Format::ToDateTime()));
             }
         } else {
             $this->UserID = 0;
             $this->User = FALSE;
             if ($SetIdentity) {
                 Gdn::Authenticator()->SetIdentity(NULL);
             }
         }
     }
     // Load guest permissions if necessary
     if ($this->UserID == 0) {
         $this->_Permissions = Gdn_Format::Unserialize($UserModel->DefinePermissions(0));
     }
 }
Ejemplo n.º 24
0
 public function GetHandshakeData()
 {
     if (is_array($this->_HandshakeData)) {
         return $this->_HandshakeData;
     }
     /*
     $UrlParts = parse_url($this->AuthenticateUrl);
     $Host = $UrlParts['host'];
     $Port = ArrayValue('port', $UrlParts, '80');
     $Path = $UrlParts['path'];
     $Referer = Gdn_Url::WebRoot(TRUE);
     $Query = ArrayValue('query', $UrlParts, '');
     
     // Make a request to the authenticated Url to see if we are logged in.
     $Pointer = @fsockopen($Host, $Port, $ErrorNumber, $Error);
     
     if (!$Pointer)
        throw new Exception(sprintf(T('Encountered an error when attempting to authenticate handshake (%1$s): [%2$s] %3$s'), $this->AuthenticateUrl, $ErrorNumber, $Error));
        
     // Get the cookie.
     $Cookie = '';
     foreach($_COOKIE as $Key => $Value) {
        if(strncasecmp($Key, 'XDEBUG', 6) == 0)
           continue;
        
        if(strlen($Cookie) > 0)
           $Cookie .= '; ';
           
        $Cookie .= $Key.'='.urlencode($Value);
     }
     
     if(strlen($Cookie) > 0)
        $Cookie = "Cookie: $Cookie\r\n";
     */
     //$Header = "GET $Path?$Query HTTP/1.1\r\n" .
     //   "Host: $Host\r\n" .
     // If you've got basic authentication enabled for the app, you're going to need to explicitly define the user/pass for this fsock call
     // "Authorization: Basic ". base64_encode ("username:password")."\r\n" .
     //   "User-Agent: Vanilla/2.0\r\n" .
     //   "Accept: */*\r\n" .
     //   "Accept-Charset: utf-8;\r\n" .
     //   "Referer: $Referer\r\n" .
     //   "Connection: close\r\n" .
     //   $Cookie."\r\n\r\n";
     /*   
     // Send the necessary headers to get the file
     fputs($Pointer, $Header);
     // echo '<br /><textarea style="height: 400px; width: 700px;">'.$Header.'</textarea>';
        
     // Retrieve the response from the remote server
     $Response = '';
     $InBody = FALSE;
     while ($Line = fread($Pointer, 4096)) {
        $Response .= $Line;
     }
     fclose($Pointer);
     // echo '<br /><textarea style="height: 400px; width: 700px;">'.$Response.'</textarea>';
     // exit();
     // Remove response headers
     $Response = trim(substr($Response, strpos($Response, "\r\n\r\n") + 4));
     switch($this->Encoding) {
        case 'json':
           $Result = json_decode($Response, TRUE);
           break;
        case 'ini':
        default:
           $Result = parse_ini_string($Response);
           break;
     }
     */
     // Check for data in the cookie
     $QuickIn = Gdn_Format::Unserialize(stripslashes(ArrayValue('QuickIn', $_COOKIE)));
     // Not found? Check in the url
     if (!is_array($QuickIn)) {
         $QuickIn = Gdn_Format::Unserialize(stripslashes(ArrayValue('QuickIn', $_GET)));
     }
     $this->_HandshakeData = $QuickIn;
     return is_array($this->_HandshakeData) ? $this->_HandshakeData : array();
 }
 public function Preferences($UserReference = '', $Username = '', $UserID = '')
 {
     $Session = Gdn::Session();
     $this->Permission('Garden.SignIn.Allow');
     $this->GetUserInfo($UserReference, $Username, $UserID);
     $UserPrefs = Gdn_Format::Unserialize($this->User->Preferences);
     if (!is_array($UserPrefs)) {
         $UserPrefs = array();
     }
     // Define the preferences to be managed
     $this->Preferences = array('Email Notifications' => array('Email.WallComment' => T('Notify me when people write on my wall.'), 'Email.ActivityComment' => T('Notify me when people reply to my wall comments.')));
     $this->FireEvent('AfterPreferencesDefined');
     if ($this->User->UserID != $Session->UserID) {
         $this->Permission('Garden.Users.Edit');
     }
     if ($this->Form->AuthenticatedPostBack() === FALSE) {
         // Loop the preferences, setting defaults from the configuration
         $Defaults = array();
         foreach ($this->Preferences as $PrefGroup => $Prefs) {
             foreach ($Prefs as $Pref => $Desc) {
                 $Defaults[$Pref] = ArrayValue($Pref, $UserPrefs, Gdn::Config('Preferences.' . $Pref, '0'));
             }
         }
         $this->Form->SetData($Defaults);
     } else {
         // Get, assign, and save the preferences
         foreach ($this->Preferences as $PrefGroup => $Prefs) {
             foreach ($Prefs as $Pref => $Desc) {
                 $UserPrefs[$Pref] = $this->Form->GetValue($Pref, '0');
             }
         }
         $this->UserModel->SavePreference($this->User->UserID, $UserPrefs);
         $this->StatusMessage = T('Your preferences have been saved.');
     }
     $this->Render();
 }
Ejemplo n.º 26
0
 public function GetHandshake()
 {
     $HaveHandshake = Gdn_CookieIdentity::CheckCookie($this->_CookieName);
     if ($HaveHandshake) {
         // Found a handshake cookie, sweet. Get the payload.
         $Payload = Gdn_CookieIdentity::GetCookiePayload($this->_CookieName);
         // Shift the 'userid' and 'expiration' off the front. These were made-up anyway :D
         array_shift($Payload);
         array_shift($Payload);
         // Rebuild the real payload
         $ReconstitutedCookiePayload = Gdn_Format::Unserialize(TrueStripSlashes(array_shift($Payload)));
         return $ReconstitutedCookiePayload;
     }
     return FALSE;
 }