Esempio n. 1
0
 public function ApplyTheme($OriginalPath, $CachePath, $InsertNames = TRUE)
 {
     // Get the theme settings.
     $SQL = Gdn::SQL();
     if (is_null($this->ThemeSettings)) {
         $Data = $SQL->Get('ThemeSetting')->ResultArray();
         $Data = ConsolidateArrayValuesByKey($Data, 'Name', 'Setting', '');
         $this->ThemeSettings = $Data;
     }
     $Css = file_get_contents($OriginalPath);
     // Process the urls.
     $Css = preg_replace_callback(self::UrlRegEx, array($this, '_ApplyUrl'), $Css);
     // Go through the css and replace its colors with the theme colors.
     $Css = preg_replace_callback(self::RegEx, array($this, '_ApplyThemeSetting'), $Css);
     // Insert the missing settings into the database.
     if ($InsertNames) {
         foreach ($this->MissingSettings as $Name => $Setting) {
             $SQL->Insert('ThemeSetting', array('Name' => $Name, 'Setting' => $Setting));
         }
         $this->MissingSettings = array();
     }
     // Save the theme to the cache path.
     file_put_contents($CachePath, $Css);
     return $CachePath;
 }
 /**
  * Grabs all new notifications and adds them to the sender's inform queue.
  *
  * This method gets called by dashboard's hooks file to display new
  * notifications on every pageload. 
  *
  * @since 2.0.18
  * @access public
  *
  * @param Gdn_Controller $Sender The object calling this method.
  */
 public static function InformNotifications($Sender)
 {
     $Session = Gdn::Session();
     if (!$Session->IsValid()) {
         return;
     }
     $ActivityModel = new ActivityModel();
     // Get five pending notifications.
     $Where = array('NotifyUserID' => Gdn::Session()->UserID, 'Notified' => ActivityModel::SENT_PENDING);
     // If we're in the middle of a visit only get very recent notifications.
     $Where['DateUpdated >'] = Gdn_Format::ToDateTime(strtotime('-5 minutes'));
     $Activities = $ActivityModel->GetWhere($Where, 0, 5)->ResultArray();
     $ActivityIDs = ConsolidateArrayValuesByKey($Activities, 'ActivityID');
     $ActivityModel->SetNotified($ActivityIDs);
     foreach ($Activities as $Activity) {
         if ($Activity['Photo']) {
             $UserPhoto = Anchor(Img($Activity['Photo'], array('class' => 'ProfilePhotoMedium')), $Activity['Url'], 'Icon');
         } else {
             $UserPhoto = '';
         }
         $Excerpt = Gdn_Format::Display($Activity['Story']);
         $ActivityClass = ' Activity-' . $Activity['ActivityType'];
         $Sender->InformMessage($UserPhoto . Wrap($Activity['Headline'], 'div', array('class' => 'Title')) . Wrap($Excerpt, 'div', array('class' => 'Excerpt')), 'Dismissable AutoDismiss' . $ActivityClass . ($UserPhoto == '' ? '' : ' HasIcon'));
     }
 }
Esempio n. 3
0
 public function DefaultRoles()
 {
     $this->Permission('Garden.Roles.Manage');
     $this->AddSideMenu('');
     $this->Title(T('Default Roles'));
     // Load roles for dropdowns.
     $RoleModel = new RoleModel();
     $this->SetData('RoleData', $RoleModel->Get());
     if ($this->Form->AuthenticatedPostBack() === FALSE) {
         // Get a list of default member roles from the config.
         $DefaultRoles = C('Garden.Registration.DefaultRoles');
         $this->Form->SetValue('DefaultRoles', $DefaultRoles);
         // Get the guest roles.
         $GuestRolesData = $RoleModel->GetByUserID(0);
         $GuestRoles = ConsolidateArrayValuesByKey($GuestRolesData, 'RoleID');
         $this->Form->SetValue('GuestRoles', $GuestRoles);
         // The applicant role.
         $ApplicantRoleID = C('Garden.Registration.ApplicantRoleID', '');
         $this->Form->SetValue('ApplicantRoleID', $ApplicantRoleID);
     } else {
         $DefaultRoles = $this->Form->GetFormValue('DefaultRoles');
         $ApplicantRoleID = $this->Form->GetFormValue('ApplicantRoleID');
         SaveToConfig(array('Garden.Registration.DefaultRoles' => $DefaultRoles, 'Garden.Registration.ApplicantRoleID' => $ApplicantRoleID));
         $GuestRoles = $this->Form->GetFormValue('GuestRoles');
         $UserModel = new UserModel();
         $UserModel->SaveRoles(0, $GuestRoles, FALSE);
         $this->StatusMessage = T("Saved");
     }
     $this->Render();
 }
   public function GetData($Limit = 10) {
      $this->Data = FALSE;
      if (Gdn::Session()->IsValid() && C('Vanilla.Modules.ShowBookmarkedModule', TRUE)) {
         $BookmarkIDs = Gdn::SQL()
            ->Select('DiscussionID')
            ->From('UserDiscussion')
            ->Where('UserID', Gdn::Session()->UserID)
            ->Where('Bookmarked', 1)
            ->Get()->ResultArray();
         $BookmarkIDs = ConsolidateArrayValuesByKey($BookmarkIDs, 'DiscussionID');

         if (count($BookmarkIDs)) {
            $DiscussionModel = new DiscussionModel();
            DiscussionModel::CategoryPermissions();

            $DiscussionModel->SQL->WhereIn('d.DiscussionID', $BookmarkIDs);
            
            $this->Data = $DiscussionModel->Get(
               0,
               $Limit
            );
         } else {
            $this->Data = FALSE;
         }
      }
   }
Esempio n. 5
0
 public function GetUserInfo($UserReference = '')
 {
     $this->Roles = array();
     if ($UserReference == '') {
         $Session = Gdn::Session();
         $this->User = $this->UserModel->Get($Session->UserID);
     } else {
         $UserReference = is_numeric($UserReference) ? $UserReference : urldecode($UserReference);
         $this->User = $this->UserModel->Get($UserReference);
     }
     if ($this->User === FALSE) {
         return $this->ReDispatch('garden/home/filenotfound');
     } else {
         $this->RoleData = $this->UserModel->GetRoles($this->User->UserID);
         if ($this->RoleData !== FALSE && $this->RoleData->NumRows() > 0) {
             $this->Roles = ConsolidateArrayValuesByKey($this->RoleData->ResultArray(), 'Name');
         }
     }
     // Make sure the userphoto module gets added to the page
     $UserPhotoModule = new UserPhotoModule($this);
     $UserPhotoModule->User = $this->User;
     $this->AddModule($UserPhotoModule);
     $this->AddSideMenu();
     return TRUE;
 }
Esempio n. 6
0
 /**
  * Returns an array of RoleID => RoleName pairs.
  *
  * @return array
  */
 public function GetArray()
 {
     // $RoleData = $this->GetEditablePermissions();
     $RoleData = $this->Get();
     $RoleIDs = ConsolidateArrayValuesByKey($RoleData->ResultArray(), 'RoleID');
     $RoleNames = ConsolidateArrayValuesByKey($RoleData->ResultArray(), 'Name');
     return ArrayCombine($RoleIDs, $RoleNames);
 }
Esempio n. 7
0
 public function AvailableLocales()
 {
     // Get the list of locales that are supported.
     $Locales = array_unique(ConsolidateArrayValuesByKey($this->AvailableLocalePacks(), 'Locale'), SORT_STRING);
     asort($Locales);
     $Locales = array_combine($Locales, $Locales);
     return $Locales;
 }
 protected function attachBadge($sender)
 {
     $roles = array();
     $userModel = new UserModel();
     $roleData = $userModel->GetRoles($sender->EventArguments['Author']->UserID);
     if ($roleData !== FALSE && $roleData->NumRows(DATASET_TYPE_ARRAY) > 0) {
         $roles = ConsolidateArrayValuesByKey($roleData->Result(), 'Name');
     }
     foreach ($roles as $role) {
         echo '<span class="RoleBadges ' . $role . 'Badge"></span>';
     }
 }
   public function ApplyBan($NewBan = NULL, $OldBan = NULL) {
      if (!$NewBan && !$OldBan)
         return;

      $OldUsers = array();
      $OldUserIDs = array();

      $NewUsers = array();
      $NewUserIDs = array();
      
      $AllBans = $this->AllBans();
      
      if ($NewBan) {
         // Get a list of users affected by the new ban.
         if (isset($NewBan['BanID']))
            $AllBans[$NewBan['BanID']] = $NewBan;

         $NewUsers = $this->SQL
            ->Select('u.UserID, u.Banned')
            ->From('User u')
            ->Where($this->BanWhere($NewBan))
            ->Get()->ResultArray();
         $NewUserIDs = ConsolidateArrayValuesByKey($NewUsers, 'UserID');
      } elseif (isset($OldBan['BanID'])) {
         unset($AllBans[$OldBan['BanID']]);
      }

      if ($OldBan) {
         // Get a list of users affected by the old ban.
         $OldUsers = $this->SQL
            ->Select('u.UserID, u.LastIPAddress, u.Name, u.Email, u.Banned')
            ->From('User u')
            ->Where($this->BanWhere($OldBan))
            ->Get()->ResultArray();
         $OldUserIDs = ConsolidateArrayValuesByKey($OldUsers, 'UserID');
      }

      // Check users that need to be unbanned.
      foreach ($OldUsers as $User) {
         if (in_array($User['UserID'], $NewUserIDs))
            continue;
         // TODO check the user against the other bans.
         $this->SaveUser($User, FALSE);
      }

      // Check users that need to be banned.
      foreach ($NewUsers as $User) {
         if ($User['Banned'])
            continue;
         $this->SaveUser($User, TRUE);
      }
   }
 /**
  * @param Gdn_Controller $Sender
  * @param array $Args
  */
 public function EntryController_Render_Before($Sender, $Args)
 {
     if ($Sender->RequestMethod != 'passwordreset') {
         return;
     }
     if (isset($Sender->Data['User'])) {
         // Get all of the users with the same email.
         $Email = $Sender->Data('User.Email');
         $Users = Gdn::SQL()->Select('Name')->From('User')->Where('Email', $Email)->Get()->ResultArray();
         $Names = ConsolidateArrayValuesByKey($Users, 'Name');
         SetValue('Name', $Sender->Data['User'], implode(', ', $Names));
     }
 }
 public function GetFacebookIDs($Datas, $UserIDColumn)
 {
     $UserIDs = array();
     foreach ($Datas as $Data) {
         if ($UserID = GetValue($UserIDColumn, $Data)) {
             $UserIDs[] = $UserID;
         } else {
             $IDs = ConsolidateArrayValuesByKey($Data, $UserIDColumn);
             $UserIDs = array_merge($UserIDs, $IDs);
         }
     }
     $FbIDs = Gdn::SQL()->WhereIn('UserID', array_unique($UserIDs))->GetWhere('UserAuthentication', array('ProviderKey' => 'facebook'))->ResultArray();
     $Result = ConsolidateArrayValuesByKey($FbIDs, 'UserID', 'ForeignUserKey');
     return $Result;
 }
 public function GetData()
 {
     if (Gdn::Session()->IsValid()) {
         $BookmarkIDs = Gdn::SQL()->Select('DiscussionID')->From('UserDiscussion')->Where('UserID', Gdn::Session()->UserID)->Where('Bookmarked', 1)->Get()->ResultArray();
         $BookmarkIDs = ConsolidateArrayValuesByKey($BookmarkIDs, 'DiscussionID');
         if (count($BookmarkIDs)) {
             $DiscussionModel = new DiscussionModel();
             DiscussionModel::CategoryPermissions();
             $DiscussionModel->SQL->WhereIn('d.DiscussionID', $BookmarkIDs);
             $Bookmarks = $DiscussionModel->Get(0, $this->Limit, array('w.Bookmarked' => '1'));
             $this->SetData('Bookmarks', $Bookmarks);
         } else {
             $this->SetData('Bookmarks', new Gdn_DataSet());
         }
     }
 }
Esempio n. 13
0
 public function Index()
 {
     $this->AddJsFile('activity.js');
     $this->Title(T('Recent Activity'));
     $Session = Gdn::Session();
     $this->ActivityData = $this->ActivityModel->Get();
     if ($this->ActivityData->NumRows() > 0) {
         $ActivityData = $this->ActivityData->ResultArray();
         $ActivityIDs = ConsolidateArrayValuesByKey($ActivityData, 'ActivityID');
         $this->CommentData = $this->ActivityModel->GetComments($ActivityIDs);
     } else {
         $this->CommentData = FALSE;
     }
     $this->View = 'all';
     $this->Render();
 }
Esempio n. 14
0
 /**
  * Delete all of the Vanilla related information for a specific user.
  * @param int $UserID The ID of the user to delete.
  * @param array $Options An array of options:
  *  - DeleteMethod: One of delete, wipe, or NULL
  * @since 2.1
  */
 public function DeleteUserData($UserID, $Options = array(), &$Data = NULL)
 {
     $SQL = Gdn::SQL();
     // Remove discussion watch records and drafts.
     $SQL->Delete('UserDiscussion', array('UserID' => $UserID));
     Gdn::UserModel()->GetDelete('Draft', array('InsertUserID' => $UserID), $Data);
     // Comment deletion depends on method selected
     $DeleteMethod = GetValue('DeleteMethod', $Options, 'delete');
     if ($DeleteMethod == 'delete') {
         // Clear out the last posts to the categories.
         $SQL->Update('Category c')->Join('Discussion d', 'd.DiscussionID = c.LastDiscussionID')->Where('d.InsertUserID', $UserID)->Set('c.LastDiscussionID', NULL)->Set('c.LastCommentID', NULL)->Put();
         $SQL->Update('Category c')->Join('Comment d', 'd.CommentID = c.LastCommentID')->Where('d.InsertUserID', $UserID)->Set('c.LastDiscussionID', NULL)->Set('c.LastCommentID', NULL)->Put();
         // Grab all of the discussions that the user has engaged in.
         $DiscussionIDs = $SQL->Select('DiscussionID')->From('Comment')->Where('InsertUserID', $UserID)->GroupBy('DiscussionID')->Get()->ResultArray();
         $DiscussionIDs = ConsolidateArrayValuesByKey($DiscussionIDs, 'DiscussionID');
         Gdn::UserModel()->GetDelete('Comment', array('InsertUserID' => $UserID), $Data);
         // Update the comment counts.
         $CommentCounts = $SQL->Select('DiscussionID')->Select('CommentID', 'count', 'CountComments')->Select('CommentID', 'max', 'LastCommentID')->WhereIn('DiscussionID', $DiscussionIDs)->GroupBy('DiscussionID')->Get('Comment')->ResultArray();
         foreach ($CommentCounts as $Row) {
             $SQL->Put('Discussion', array('CountComments' => $Row['CountComments'] + 1, 'LastCommentID' => $Row['LastCommentID']), array('DiscussionID' => $Row['DiscussionID']));
         }
         // Update the last user IDs.
         $SQL->Update('Discussion d')->Join('Comment c', 'd.LastCommentID = c.CommentID', 'left')->Set('d.LastCommentUserID', 'c.InsertUserID', FALSE, FALSE)->Set('d.DateLastComment', 'c.DateInserted', FALSE, FALSE)->WhereIn('d.DiscussionID', $DiscussionIDs)->Put();
         // Update the last posts.
         $Discussions = $SQL->WhereIn('DiscussionID', $DiscussionIDs)->Where('LastCommentUserID', $UserID)->Get('Discussion');
         // Delete the user's dicussions
         Gdn::UserModel()->GetDelete('Discussion', array('InsertUserID' => $UserID), $Data);
         // Update the appropriat recent posts in the categories.
         $CategoryModel = new CategoryModel();
         $Categories = $CategoryModel->GetWhere(array('LastDiscussionID' => NULL))->ResultArray();
         foreach ($Categories as $Category) {
             $CategoryModel->SetRecentPost($Category['CategoryID']);
         }
     } else {
         if ($DeleteMethod == 'wipe') {
             // Erase the user's dicussions
             $SQL->Update('Discussion')->Set('Body', T('The user and all related content has been deleted.'))->Set('Format', 'Deleted')->Where('InsertUserID', $UserID)->Put();
             // Erase the user's comments
             $SQL->From('Comment')->Join('Discussion d', 'c.DiscussionID = d.DiscussionID')->Delete('Comment c', array('d.InsertUserID' => $UserID));
             $SQL->Update('Comment')->Set('Body', T('The user and all related content has been deleted.'))->Set('Format', 'Deleted')->Where('InsertUserID', $UserID)->Put();
         } else {
             // Leave comments
         }
     }
     // Remove the user's profile information related to this application
     $SQL->Update('User')->Set(array('CountDiscussions' => 0, 'CountUnreadDiscussions' => 0, 'CountComments' => 0, 'CountDrafts' => 0, 'CountBookmarks' => 0))->Where('UserID', $UserID)->Put();
 }
/**
 * Get all tutorials, or a specific one.
 */
function GetTutorials($TutorialCode = '')
{
    // Define all Tutorials
    $Tutorials = array(array('Code' => 'introduction', 'Name' => 'Introduction to Vanilla', 'Description' => 'This video gives you a brief overview of the Vanilla administrative dashboard and the forum itself.', 'VideoID' => '31043422'), array('Code' => 'using-the-forum', 'Name' => 'Using the Forum', 'Description' => 'Learn how to start, announce, close, edit and delete discussions and comments.', 'VideoID' => '31502992'), array('Code' => 'private-conversations', 'Name' => 'Private Conversations', 'Description' => 'Learn how to start new private conversations and add people to them.', 'VideoID' => '31498383'), array('Code' => 'user-profiles', 'Name' => 'User Profiles', 'Description' => 'Learn how to use and manage your user profile. ', 'VideoID' => '31499266'), array('Code' => 'appearance', 'Name' => 'Changing the appearance of your forum', 'Description' => 'This tutorial takes you through the "Appearance" section of the Vanilla Forums administrative dashboard.', 'VideoID' => '31089641'), array('Code' => 'roles-and-permissions', 'Name' => 'Managing Roles and Permissions in Vanilla', 'Description' => 'This tutorial walks you through how to create new roles and how to use permissions.', 'VideoID' => '31091056'), array('Code' => 'users', 'Name' => 'Finding &amp; Managing Users', 'Description' => 'This tutorial shows you how to search for and manage users.', 'VideoID' => '31094514'), array('Code' => 'category-management-and-advanced-settings', 'Name' => 'Category Management &amp; Advanced Settings', 'Description' => 'Learn how to add, edit, and manage categories. Also learn about advanced forum settings.', 'VideoID' => '31492046'), array('Code' => 'user-registration', 'Name' => 'User Registration', 'Description' => 'Learn to control how new users get into your community.', 'VideoID' => '31493119'));
    // Default Thumbnails
    $Thumbnail = Asset('applications/dashboard/design/images/help-tn-200.jpg');
    $LargeThumbnail = Asset('applications/dashboard/design/images/help-tn-640.jpg');
    for ($i = 0; $i < count($Tutorials); $i++) {
        $Tutorials[$i]['Thumbnail'] = $Thumbnail;
        $Tutorials[$i]['LargeThumbnail'] = $LargeThumbnail;
    }
    if ($TutorialCode != '') {
        $Keys = ConsolidateArrayValuesByKey($Tutorials, 'Code');
        $Index = array_search($TutorialCode, $Keys);
        if ($Index === FALSE) {
            return FALSE;
        }
        // Not found!
        // Found it, so define it's thumbnail location
        $Tutorial = GetValue($Index, $Tutorials);
        $VideoID = GetValue('VideoID', $Tutorial);
        try {
            $Vimeo = unserialize(file_get_contents("http://vimeo.com/api/v2/video/" . $Tutorial['VideoID'] . ".php"));
            $Tutorial['Thumbnail'] = GetValue('thumbnail_medium', GetValue('0', $Vimeo));
            $Tutorial['LargeThumbnail'] = GetValue('thumbnail_large', GetValue('0', $Vimeo));
        } catch (Exception $Ex) {
            // Do nothing
        }
        return $Tutorial;
    } else {
        // Loop through each tutorial populating the thumbnail image location
        try {
            foreach ($Tutorials as $Key => $Tutorial) {
                $Vimeo = unserialize(file_get_contents("http://vimeo.com/api/v2/video/" . $Tutorial['VideoID'] . ".php"));
                $Tutorials[$Key]['Thumbnail'] = GetValue('thumbnail_medium', GetValue('0', $Vimeo));
                $Tutorials[$Key]['LargeThumbnail'] = GetValue('thumbnail_large', GetValue('0', $Vimeo));
            }
        } catch (Exception $Ex) {
            // Do nothing
        }
        return $Tutorials;
    }
}
Esempio n. 16
0
 protected function GetUserEmails($FormValues)
 {
     $SQL = Gdn::SQL();
     $UserModel = Gdn::UserModel();
     if (ArrayValue('SendMeOnly', $FormValues)) {
         $Session = Gdn::Session();
         $UserID = GetValueR('User.UserID', $Session);
         $User = $UserModel->Get($UserID);
         $Result[$User->Email] = $User->Name;
         return $Result;
     }
     $Roles = ArrayValue('Roles', $FormValues);
     if (is_array($Roles) && count($Roles) > 0) {
         $DataSet = $SQL->Select('u.Name, u.Email')->From('UserRole r')->Join('User u', 'u.UserID = r.UserID')->WhereIn('r.RoleID', $Roles)->Get();
     } else {
         $DataSet = $SQL->Select('u.Name, u.Email')->From('User u')->Get();
     }
     $Result = ConsolidateArrayValuesByKey($DataSet->ResultArray(), 'Email', 'Name');
     return $Result;
 }
Esempio n. 17
0
 public function Index()
 {
     if ($this->Head) {
         $this->Head->AddScript('/applications/garden/js/activity.js');
         $this->Head->Title(Translate('Recent Activity'));
     }
     $Session = Gdn::Session();
     $this->ActivityData = $this->ActivityModel->Get();
     if ($this->ActivityData->NumRows() > 0) {
         $ActivityData = $this->ActivityData->ResultArray();
         $ActivityIDs = ConsolidateArrayValuesByKey($ActivityData, 'ActivityID');
         $this->CommentData = $this->ActivityModel->GetComments($ActivityIDs);
     } else {
         $this->CommentData = FALSE;
     }
     $GuestModule = new GuestModule($this);
     $GuestModule->MessageCode = "Just checking up on recent activity? When you're ready to get involved, click one of these buttons!";
     $this->AddModule($GuestModule);
     $this->View = 'all';
     $this->Render();
 }
 public function Index($RoleID = '')
 {
     $this->Permission('Garden.Activity.View');
     // Limit to specific RoleIDs?
     if ($RoleID != '') {
         $RoleID = explode(',', $RoleID);
     }
     $this->AddJsFile('activity.js');
     $this->Title(T('Recent Activity'));
     $Session = Gdn::Session();
     $Comment = $this->Form->GetFormValue('Comment');
     $this->CommentData = FALSE;
     if ($Session->UserID > 0 && $this->Form->AuthenticatedPostBack() && !StringIsNullOrEmpty($Comment)) {
         $Comment = substr($Comment, 0, 1000);
         // Limit to 1000 characters...
         // Update About if necessary
         $ActivityType = 'WallComment';
         $NewActivityID = $this->ActivityModel->Add($Session->UserID, $ActivityType, $Comment);
         if ($this->_DeliveryType === DELIVERY_TYPE_ALL) {
             Redirect('activity');
         } else {
             // Load just the single new comment
             $this->HideActivity = TRUE;
             $this->ActivityData = $this->ActivityModel->GetWhere('ActivityID', $NewActivityID);
             $this->View = 'activities';
         }
     } else {
         $this->ActivityData = is_array($RoleID) ? $this->ActivityModel->GetForRole($RoleID) : $this->ActivityModel->Get();
         if ($this->ActivityData->NumRows() > 0) {
             $ActivityData = $this->ActivityData->ResultArray();
             $ActivityIDs = ConsolidateArrayValuesByKey($ActivityData, 'ActivityID');
             $this->CommentData = $this->ActivityModel->GetComments($ActivityIDs);
         }
         $this->View = 'all';
     }
     $this->Render();
 }
Esempio n. 19
0
 /**
  * Returns the xhtml for a list of checkboxes; sorted into groups related to
  * the TextField value of the dataset.
  *
  * @param string $FieldName The name of the field that is being displayed/posted with this input. It
  * should related directly to a field name in a user junction table.
  * ie. LUM_UserRole.RoleID
  *
  * @param mixed $DataSet The data to fill the options in the select list. Either an associative
  * array or a database dataset. ie. RoleID, Name from LUM_Role.
  *
  * @param mixed $ValueDataSet The data that should be checked in $DataSet. Either an associative array
  * or a database dataset. ie. RoleID from LUM_UserRole for a single user.
  *
  * @param array $Attributes An associative array of attributes for the select. Here is a list of
  * "special" attributes and their default values:
  *
  * Attribute   Options                        Default
  * ------------------------------------------------------------------------
  * ValueField  The name of the field in       'value'
  *             $DataSet that contains the
  *             option values.
  * TextField   The name of the field in       'text'
  *             $DataSet that contains the
  *             option text.
  *
  * @return string
  */
 public function CheckBoxGrid($FieldName, $DataSet, $ValueDataSet, $Attributes)
 {
     // Never display individual inline errors for these CheckBoxes
     $Attributes['InlineErrors'] = FALSE;
     $Return = '';
     $CheckedValues = $ValueDataSet;
     if (is_object($ValueDataSet)) {
         $CheckedValues = ConsolidateArrayValuesByKey($ValueDataSet->ResultArray(), $FieldName);
     }
     $i = 1;
     if (is_object($DataSet)) {
         $ValueField = ArrayValueI('ValueField', $Attributes, 'value');
         $TextField = ArrayValueI('TextField', $Attributes, 'text');
         $LastGroup = '';
         $Group = array();
         $Rows = array();
         $Cols = array();
         $CheckBox = '';
         foreach ($DataSet->Result() as $Data) {
             // Define the checkbox
             $Instance = $Attributes;
             $Instance = RemoveKeyFromArray($Instance, array('TextField', 'ValueField'));
             $Instance['value'] = $Data->{$ValueField};
             $Instance['id'] = $FieldName . $i;
             if (is_array($CheckedValues) && in_array($Data->{$ValueField}, $CheckedValues)) {
                 $Instance['checked'] = 'checked';
             }
             $CheckBox = $this->CheckBox($FieldName . '[]', '', $Instance);
             // Organize the checkbox into an array for this group
             $CurrentTextField = $Data->{$TextField};
             $aCurrentTextField = explode('.', $CurrentTextField);
             $aCurrentTextFieldCount = count($aCurrentTextField);
             $GroupName = array_shift($aCurrentTextField);
             $ColName = array_pop($aCurrentTextField);
             if ($aCurrentTextFieldCount >= 3) {
                 $RowName = implode('.', $aCurrentTextField);
                 if ($GroupName != $LastGroup && $LastGroup != '') {
                     // Render the last group
                     $Return .= $this->GetCheckBoxGridGroup($LastGroup, $Group, $Rows, $Cols);
                     // Clean out the $Group array & Rowcount
                     $Group = array();
                     $Rows = array();
                     $Cols = array();
                 }
                 if (array_key_exists($ColName, $Group) === FALSE || is_array($Group[$ColName]) === FALSE) {
                     $Group[$ColName] = array();
                     if (!in_array($ColName, $Cols)) {
                         $Cols[] = $ColName;
                     }
                 }
                 if (!in_array($RowName, $Rows)) {
                     $Rows[] = $RowName;
                 }
                 $Group[$ColName][$RowName] = $CheckBox;
                 $LastGroup = $GroupName;
             }
             ++$i;
         }
     }
     /*elseif (is_array($DataSet)) {
              foreach ($DataSet as $Text => $ID) {
                 $Instance = $Attributes;
                 $Instance = RemoveKeyFromArray($Instance, array('TextField', 'ValueField'));
                 $Instance['id'] = $FieldName.$i;
                 if (is_numeric($Text))
                    $Text = $ID;
     
                 $Instance['value'] = $ID;
                 if (in_array($ID, $CheckedValues))
                    $Instance['checked'] = 'checked';
     
                 $Return .= $this->CheckBox($FieldName.'[]', $Text, $Instance)."\n";
                 $i++;
              }
           }
           */
     return $Return . $this->GetCheckBoxGridGroup($LastGroup, $Group, $Rows, $Cols);
 }
   /**
    * Retrieve the user to be manipulated. If no params are passed, this will
    * retrieve the current user from the session.
    */
   public function GetUserInfo($UserReference = '', $Username = '', $UserID = '') {
		if ($this->_UserInfoRetrieved)
			return;
		
      if (!C('Garden.Profile.Public') && !Gdn::Session()->IsValid())
         Redirect('dashboard/home/permission');
      
		// If a UserID was provided as a querystring parameter, use it over anything else:
		if ($UserID) {
			$UserReference = $UserID;
			$Username = '******'; // Fill this with a value so the $UserReference is assumed to be an integer/userid.
		}
		   
      $this->Roles = array();
      if ($UserReference == '') {
         $this->User = $this->UserModel->Get(Gdn::Session()->UserID);
      } else if (is_numeric($UserReference) && $Username != '') {
         $this->User = $this->UserModel->Get($UserReference);
      } else {
         $this->User = $this->UserModel->GetByUsername($UserReference);
      }
         
      if ($this->User === FALSE) {
         throw NotFoundException();
      } else if ($this->User->Deleted == 1) {
         Redirect('dashboard/home/deleted');
      } else {
         $this->RoleData = $this->UserModel->GetRoles($this->User->UserID);
         if ($this->RoleData !== FALSE && $this->RoleData->NumRows(DATASET_TYPE_ARRAY) > 0) 
            $this->Roles = ConsolidateArrayValuesByKey($this->RoleData->Result(), 'Name');
			
			$this->SetData('Profile', $this->User);
			$this->SetData('UserRoles', $this->Roles);
			
			// If the photo contains an http://, it is just an icon (probably from facebook or some external service), don't show it here because the Photo property is used to define logic around allowing thumbnail edits, etc.
			if ($this->User->Photo != '' && in_array(strtolower(substr($this->User->Photo, 0, 7)), array('http://', 'https:/')))
				$this->User->Photo = '';
			
      }
      
      // Make sure the userphoto module gets added to the page
      $UserPhotoModule = new UserPhotoModule($this);
      $UserPhotoModule->User = $this->User;
      $this->AddModule($UserPhotoModule);
      
      $this->AddSideMenu();
		$this->_UserInfoRetrieved = TRUE;
      return TRUE;
   }
Esempio n. 21
0
 public function Counts($Column)
 {
     $Result = array('Complete' => TRUE);
     switch ($Column) {
         case 'CountDiscussions':
             $this->Database->Query(DBAModel::GetCountSQL('count', 'Category', 'Discussion'));
             break;
         case 'CountComments':
             $this->Database->Query(DBAModel::GetCountSQL('sum', 'Category', 'Discussion', $Column, 'CountComments'));
             break;
         case 'LastDiscussionID':
             $this->Database->Query(DBAModel::GetCountSQL('max', 'Category', 'Discussion'));
             break;
         case 'LastCommentID':
             $Data = $this->SQL->Select('d.CategoryID')->Select('c.CommentID', 'max', 'LastCommentID')->Select('d.DiscussionID', 'max', 'LastDiscussionID')->Select('c.DateInserted', 'max', 'DateLastComment')->Select('d.DateInserted', 'max', 'DateLastDiscussion')->From('Comment c')->Join('Discussion d', 'd.DiscussionID = c.DiscussionID')->GroupBy('d.CategoryID')->Get()->ResultArray();
             // Now we have to grab the discussions associated with these comments.
             $CommentIDs = ConsolidateArrayValuesByKey($Data, 'LastCommentID');
             // Grab the discussions for the comments.
             $this->SQL->Select('c.CommentID, c.DiscussionID')->From('Comment c')->WhereIn('c.CommentID', $CommentIDs);
             $Discussions = $this->SQL->Get()->ResultArray();
             $Discussions = Gdn_DataSet::Index($Discussions, array('CommentID'));
             foreach ($Data as $Row) {
                 $CategoryID = (int) $Row['CategoryID'];
                 $Category = CategoryModel::Categories($CategoryID);
                 $CommentID = $Row['LastCommentID'];
                 $DiscussionID = GetValueR("{$CommentID}.DiscussionID", $Discussions, NULL);
                 $DateLastComment = Gdn_Format::ToTimestamp($Row['DateLastComment']);
                 $DateLastDiscussion = Gdn_Format::ToTimestamp($Row['DateLastDiscussion']);
                 $Set = array('LastCommentID' => $CommentID);
                 if ($DiscussionID) {
                     $LastDiscussionID = GetValue('LastDiscussionID', $Category);
                     if ($DateLastComment >= $DateLastDiscussion) {
                         // The most recent discussion is from this comment.
                         $Set['LastDiscussionID'] = $DiscussionID;
                     } else {
                         // The most recent discussion has no comments.
                         $Set['LastCommentID'] = NULL;
                     }
                 } else {
                     // Something went wrong.
                     $Set['LastCommentID'] = NULL;
                     $Set['LastDiscussionID'] = NULL;
                 }
                 $this->SetField($CategoryID, $Set);
             }
             break;
         case 'LastDateInserted':
             $Categories = $this->SQL->Select('ca.CategoryID')->Select('d.DateInserted', '', 'DateLastDiscussion')->Select('c.DateInserted', '', 'DateLastComment')->From('Category ca')->Join('Discussion d', 'd.DiscussionID = ca.LastDiscussionID')->Join('Comment c', 'c.CommentID = ca.LastCommentID')->Get()->ResultArray();
             foreach ($Categories as $Category) {
                 $DateLastDiscussion = GetValue('DateLastDiscussion', $Category);
                 $DateLastComment = GetValue('DateLastComment', $Category);
                 $MaxDate = $DateLastComment;
                 if (is_null($DateLastComment) || $DateLastDiscussion > $MaxDate) {
                     $MaxDate = $DateLastDiscussion;
                 }
                 if (is_null($MaxDate)) {
                     continue;
                 }
                 $CategoryID = (int) $Category['CategoryID'];
                 $this->SetField($CategoryID, 'LastDateInserted', $MaxDate);
             }
             break;
     }
     self::ClearCache();
     return $Result;
 }
Esempio n. 22
0
 /**
  * Delete spam and optionally delete the users.
  * @param type $LogIDs 
  */
 public function DeleteSpam($LogIDs)
 {
     $this->Permission('Garden.Moderation.Manage');
     if (!$this->Request->IsPostBack()) {
         throw PermissionException('Javascript');
     }
     $LogIDs = explode(',', $LogIDs);
     // Ban the appropriate users.
     $UserIDs = $this->Form->GetFormValue('UserID', array());
     if (!is_array($UserIDs)) {
         $UserIDs = array();
     }
     if (!empty($UserIDs)) {
         // Grab the rest of the log entries.
         $OtherLogIDs = $this->LogModel->GetWhere(array('Operation' => 'Spam', 'RecordUserID' => $UserIDs));
         $OtherLogIDs = ConsolidateArrayValuesByKey($OtherLogIDs, 'LogID');
         $LogIDs = array_merge($LogIDs, $OtherLogIDs);
         foreach ($UserIDs as $UserID) {
             Gdn::UserModel()->Ban($UserID, array('Reason' => 'Spam', 'DeleteContent' => TRUE, 'Log' => TRUE));
         }
     }
     // Grab the logs.
     $this->LogModel->Delete($LogIDs);
     $this->Render('Blank', 'Utility');
 }
   public function Structure($AppName = 'all', $CaptureOnly = '1', $Drop = '0', $Explicit = '0') {
      $this->Permission('Garden.Settings.Manage');
      $Files = array();
      $AppName = $AppName == '' ? 'all': $AppName;
      if ($AppName == 'all') {
			// Load all application structure files.
			$ApplicationManager = new Gdn_ApplicationManager();
			$Apps = $ApplicationManager->EnabledApplications();
			$AppNames = ConsolidateArrayValuesByKey($Apps, 'Folder');
			foreach ($AppNames as $AppName) {
				$Files[] = CombinePaths(array(PATH_APPLICATIONS, $AppName, 'settings', 'structure.php'), DS);
			}
			$AppName = 'all';
      } else {
			 // Load that specific application structure file.
         $Files[] = CombinePaths(array(PATH_APPLICATIONS, $AppName, 'settings', 'structure.php'), DS);
      }
      $Validation = new Gdn_Validation();
      $Database = Gdn::Database();
      $Drop = $Drop == '0' ? FALSE : TRUE;
      $Explicit = $Explicit == '0' ? FALSE : TRUE;
      $CaptureOnly = !($CaptureOnly == '0');
      $Structure = Gdn::Structure();
      $Structure->CaptureOnly = $CaptureOnly;
      $SQL = Gdn::SQL();
      $SQL->CaptureModifications = $CaptureOnly;
      $this->SetData('CaptureOnly', $Structure->CaptureOnly);
      $this->SetData('Drop', $Drop);
      $this->SetData('Explicit', $Explicit);
      $this->SetData('ApplicationName', $AppName);
      $this->SetData('Status', '');
      $FoundStructureFile = FALSE;
      foreach ($Files as $File) {
         if (file_exists($File)) {
			   $FoundStructureFile = TRUE;
			   try {
			      include($File);
			   } catch (Exception $Ex) {
			      $this->Form->AddError($Ex);
			   }
			}
      }

      // Run the structure of all of the plugins.
      $Plugins = Gdn::PluginManager()->EnabledPlugins();
      foreach ($Plugins as $PluginKey => $Plugin) {
         $PluginInstance = Gdn::PluginManager()->GetPluginInstance($PluginKey, Gdn_PluginManager::ACCESS_PLUGINNAME);
         if (method_exists($PluginInstance, 'Structure'))
            $PluginInstance->Structure();
      }

      if (property_exists($Structure->Database, 'CapturedSql'))
         $this->SetData('CapturedSql', (array)$Structure->Database->CapturedSql);
      else
         $this->SetData('CapturedSql', array());

      if ($this->Form->ErrorCount() == 0 && !$CaptureOnly && $FoundStructureFile)
         $this->SetData('Status', 'The structure was successfully executed.');

		$this->AddSideMenu('dashboard/settings/configure');
      $this->AddCssFile('admin.css');
      $this->SetData('Title', T('Database Structure Upgrades'));
      $this->Render();
   }
 /**
  * Configuration of registration settings.
  *
  * Events: BeforeRegistrationUpdate
  *
  * @since 2.0.0
  * @access public
  * @param string $RedirectUrl Where to send user after registration.
  */
 public function Registration($RedirectUrl = '')
 {
     $this->Permission('Garden.Settings.Manage');
     $this->AddSideMenu('dashboard/settings/registration');
     $this->AddJsFile('registration.js');
     $this->Title(T('Registration'));
     // Create a model to save configuration settings
     $Validation = new Gdn_Validation();
     $ConfigurationModel = new Gdn_ConfigurationModel($Validation);
     $ConfigurationModel->SetField(array('Garden.Registration.Method' => 'Captcha', 'Garden.Registration.CaptchaPrivateKey', 'Garden.Registration.CaptchaPublicKey', 'Garden.Registration.InviteExpiration', 'Garden.Registration.ConfirmEmail', 'Garden.Registration.ConfirmEmailRole'));
     // Set the model on the forms.
     $this->Form->SetModel($ConfigurationModel);
     // Load roles with sign-in permission
     $RoleModel = new RoleModel();
     $this->RoleData = $RoleModel->GetByPermission('Garden.SignIn.Allow');
     $this->SetData('_Roles', ConsolidateArrayValuesByKey($this->RoleData->ResultArray(), 'RoleID', 'Name'));
     // Get the currently selected default roles
     // $this->ExistingRoleData = Gdn::Config('Garden.Registration.DefaultRoles');
     // if (is_array($this->ExistingRoleData) === FALSE)
     //    $this->ExistingRoleData = array();
     // Get currently selected InvitationOptions
     $this->ExistingRoleInvitations = Gdn::Config('Garden.Registration.InviteRoles');
     if (is_array($this->ExistingRoleInvitations) === FALSE) {
         $this->ExistingRoleInvitations = array();
     }
     // Get the currently selected Expiration Length
     $this->InviteExpiration = Gdn::Config('Garden.Registration.InviteExpiration', '');
     // Registration methods.
     $this->RegistrationMethods = array('Captcha' => "New users fill out a simple form and are granted access immediately.", 'Approval' => "New users are reviewed and approved by an administrator (that's you!).", 'Invitation' => "Existing members send invitations to new members.", 'Connect' => "New users are only registered through SSO plugins.");
     // Options for how many invitations a role can send out per month.
     $this->InvitationOptions = array('0' => T('None'), '1' => '1', '2' => '2', '5' => '5', '-1' => T('Unlimited'));
     // Options for when invitations should expire.
     $this->InviteExpirationOptions = array('-1 week' => T('1 week after being sent'), '-2 weeks' => T('2 weeks after being sent'), '-1 month' => T('1 month after being sent'), 'FALSE' => T('never'));
     if ($this->Form->AuthenticatedPostBack() === FALSE) {
         $this->Form->SetData($ConfigurationModel->Data);
     } else {
         // Define some validation rules for the fields being saved
         $ConfigurationModel->Validation->ApplyRule('Garden.Registration.Method', 'Required');
         // if($this->Form->GetValue('Garden.Registration.Method') != 'Closed')
         //    $ConfigurationModel->Validation->ApplyRule('Garden.Registration.DefaultRoles', 'RequiredArray');
         if ($this->Form->GetValue('Garden.Registration.ConfirmEmail')) {
             $ConfigurationModel->Validation->ApplyRule('Garden.Registration.ConfirmEmailRole', 'Required');
         }
         // Define the Garden.Registration.RoleInvitations setting based on the postback values
         $InvitationRoleIDs = $this->Form->GetValue('InvitationRoleID');
         $InvitationCounts = $this->Form->GetValue('InvitationCount');
         $this->ExistingRoleInvitations = ArrayCombine($InvitationRoleIDs, $InvitationCounts);
         $ConfigurationModel->ForceSetting('Garden.Registration.InviteRoles', $this->ExistingRoleInvitations);
         // Event hook
         $this->EventArguments['ConfigurationModel'] =& $ConfigurationModel;
         $this->FireEvent('BeforeRegistrationUpdate');
         // Save!
         if ($this->Form->Save() !== FALSE) {
             $this->InformMessage(T("Your settings have been saved."));
             if ($RedirectUrl != '') {
                 $this->RedirectUrl = $RedirectUrl;
             }
         }
     }
     $this->Render();
 }
Esempio n. 25
0
 public function SaveRoles($UserID, $RoleIDs, $RecordActivity = TRUE)
 {
     if (is_string($RoleIDs) && !is_numeric($RoleIDs)) {
         // The $RoleIDs are a comma delimited list of role names.
         $RoleNames = preg_split('/\\s*,\\s*/', $RoleIDs);
         $RoleIDs = $this->SQL->Select('r.RoleID')->From('Role r')->WhereIn('r.Name', $RoleNames)->Get()->ResultArray();
         $RoleIDs = ConsolidateArrayValuesByKey($RoleIDs, 'RoleID');
     }
     if (!is_array($RoleIDs)) {
         $RoleIDs = array($RoleIDs);
     }
     // Get the current roles.
     $OldRoleIDs = array();
     $OldRoleData = $this->SQL->Select('ur.RoleID, r.Name')->From('Role r')->Join('UserRole ur', 'r.RoleID = ur.RoleID')->Where('ur.UserID', $UserID)->Get()->ResultArray();
     if ($OldRoleData !== FALSE) {
         $OldRoleIDs = ConsolidateArrayValuesByKey($OldRoleData, 'RoleID');
     }
     // 1a) Figure out which roles to delete.
     $DeleteRoleIDs = array_diff($OldRoleIDs, $RoleIDs);
     // 1b) Remove old role associations for this user.
     if (count($DeleteRoleIDs) > 0) {
         $this->SQL->WhereIn('RoleID', $DeleteRoleIDs)->Delete('UserRole', array('UserID' => $UserID));
     }
     // 2a) Figure out which roles to insert.
     $InsertRoleIDs = array_diff($RoleIDs, $OldRoleIDs);
     // 2b) Insert the new role associations for this user.
     foreach ($InsertRoleIDs as $InsertRoleID) {
         if (is_numeric($InsertRoleID)) {
             $this->SQL->Insert('UserRole', array('UserID' => $UserID, 'RoleID' => $InsertRoleID));
         }
     }
     // 3. Remove the cached permissions for this user.
     // Note: they are not reset here because I want this action to be
     // performed in one place - /dashboard/library/core/class.session.php
     // It is done in the session because when a role's permissions are changed
     // I can then just erase all cached permissions on the user table for
     // users that are assigned to that changed role - and they can reset
     // themselves the next time the session is referenced.
     $this->SQL->Put('User', array('Permissions' => ''), array('UserID' => $UserID));
     if ($RecordActivity && (count($DeleteRoleIDs) > 0 || count($InsertRoleIDs) > 0)) {
         $User = $this->Get($UserID);
         $Session = Gdn::Session();
         $OldRoles = FALSE;
         if ($OldRoleData !== FALSE) {
             $OldRoles = ConsolidateArrayValuesByKey($OldRoleData, 'Name');
         }
         $NewRoles = FALSE;
         $NewRoleData = $this->SQL->Select('r.RoleID, r.Name')->From('Role r')->Join('UserRole ur', 'r.RoleID = ur.RoleID')->Where('ur.UserID', $UserID)->Get()->ResultArray();
         if ($NewRoleData !== FALSE) {
             $NewRoles = ConsolidateArrayValuesByKey($NewRoleData, 'Name');
         }
         $RemovedRoles = array_diff($OldRoles, $NewRoles);
         $NewRoles = array_diff($NewRoles, $OldRoles);
         $RemovedCount = count($RemovedRoles);
         $NewCount = count($NewRoles);
         $Story = '';
         if ($RemovedCount > 0 && $NewCount > 0) {
             $Story = sprintf(T('%1$s was removed from the %2$s %3$s and added to the %4$s %5$s.'), $User->Name, implode(', ', $RemovedRoles), Plural($RemovedCount, 'role', 'roles'), implode(', ', $NewRoles), Plural($NewCount, 'role', 'roles'));
         } else {
             if ($RemovedCount > 0) {
                 $Story = sprintf(T('%1$s was removed from the %2$s %3$s.'), $User->Name, implode(', ', $RemovedRoles), Plural($RemovedCount, 'role', 'roles'));
             } else {
                 if ($NewCount > 0) {
                     $Story = sprintf(T('%1$s was added to the %2$s %3$s.'), $User->Name, implode(', ', $NewRoles), Plural($NewCount, 'role', 'roles'));
                 }
             }
         }
         AddActivity($Session->UserID != 0 ? $Session->UserID : $UserID, 'RoleChange', $Story, $UserID);
     }
 }
Esempio n. 26
0
   /**
    *
    * @param array $Data
    * @param array $Columns The columns/table information for the join. Depending on the argument's index it will be interpreted differently.
    *  - <b>numeric</b>: This column will come be added to the resulting join. The value can be either a string or a two element array where the second element specifies an alias.
    *  - <b>alias</b>: The alias of the child table in the query.
    *  - <b>child</b>: The name of the child column.
    *  - <b>column</b>: The name of the column to put the joined data into. Can't be used with <b>prefix</b>.
    *  - <b>parent</b>: The name of the parent column.
    *  - <b>table</b>: The name of the child table in the join.
    *  - <b>prefix</b>: The name of the prefix to give the columns. Can't be used with <b>column</b>.
    * @param array $Options An array of extra options.
    *  - <b>sql</b>: A Gdn_SQLDriver with the child query.
    *  - <b>type</b>: The join type, either JOIN_INNER, JOIN_LEFT. This defaults to JOIN_INNER.
    */
   public static function Join(&$Data, $Columns, $Options = array()) {
      $Options = array_change_key_case($Options);
      
      $Sql = Gdn::SQL(); //GetValue('sql', $Options, Gdn::SQL());
      $ResultColumns = array();
      
      // Grab the columns.
      foreach ($Columns as $Index => $Name) {
         if (is_numeric($Index)) {
            // This is a column being selected.
            if (is_array($Name)) {
               $Column = $Name[0];
               $ColumnAlias = $Name[1];
            } else {
               $Column = $Name;
               $ColumnAlias = '';
            }
            
            if (($Pos = strpos($Column, '.')) !== FALSE) {
               $Sql->Select($Column, '', $ColumnAlias);
               $Column = substr($Column, $Pos + 1);
            } else {
               $Sql->Select(isset($TableAlias) ? $TableAlias.'.'.$Column : $Column, '', $ColumnAlias);
            }
            if ($ColumnAlias)
               $ResultColumns[] = $ColumnAlias;
            else
               $ResultColumns[] = $Column;
         } else {
            switch (strtolower($Index)) {
               case 'alias':
                  $TableAlias = $Name;
                  break;
               case 'child':
                  $ChildColumn = $Name;
                  break;
               case 'column':
                  $JoinColumn = $Name;
                  break;
               case 'parent':
                  $ParentColumn = $Name;
                  break;
               case 'prefix':
                  $ColumnPrefix = $Name;
                  break;
               case 'table':
                  $Table = $Name;
                  break;
               case 'type':
                  // The type shouldn't be here, but handle it.
                  $Options['Type'] = $Name;
                  break;
               default:
                  throw new Exception("Gdn_DataSet::Join(): Unknown column option '$Index'.");
            }
         }
      }
      
      if (!isset($TableAlias)) {
         if (isset($Table))
            $TableAlias = 'c';
         else
            $TableAlias = 'c';
      }
      
      if (!isset($ParentColumn)) {
         if (isset($ChildColumn))
            $ParentColumn = $ChildColumn;
         elseif (isset($Table))
            $ChildColumn = $Table.'ID';
         else
            throw Exception("Gdn_DataSet::Join(): Missing 'parent' argument'.");
      }
      
      // Figure out some options if they weren't specified.
      if (!isset($ChildColumn)) {
         if (isset($ParentColumn))
            $ChildColumn = $ParentColumn;
         elseif (isset($Table))
            $ChildColumn = $Table.'ID';
         else
            throw Exception("Gdn_DataSet::Join(): Missing 'child' argument'.");
      }
      
      if (!isset($ColumnPrefix) && !isset($JoinColumn)) {
         $ColumnPrefix = StringEndsWith($ParentColumn, 'ID', TRUE, TRUE);
      }
      
      $JoinType = strtolower(GetValue('Type', $Options, JOIN_LEFT));
      
      // Start augmenting the sql for the join.
      if (isset($Table))
         $Sql->From("$Table $TableAlias");
      $Sql->Select("$TableAlias.$ChildColumn");
      
      // Get the IDs to generate an in clause with.
      $IDs = ConsolidateArrayValuesByKey($Data, $ParentColumn);
      $Sql->WhereIn($ChildColumn, $IDs);
      
      $ChildData = $Sql->Get()->ResultArray();
      $ChildData = self::Index($ChildData, $ChildColumn, array('unique' => isset($ColumnPrefix)));
      
      $NotFound = array();

      // Join the data in.
      foreach ($Data as $Index => &$Row) {
         $ParentID = GetValue($ParentColumn, $Row);
         if (isset($ChildData[$ParentID])) {
            $ChildRow = $ChildData[$ParentID];
            
            if (isset($ColumnPrefix)) {
               // Add the data to the columns.
               foreach ($ChildRow as $Name => $Value) {
                  SetValue($ColumnPrefix.$Name, $Row, $Value);
               }
            } else {
               // Add the result data.
               SetValue($JoinColumn, $Row, $ChildRow);
            }
         } else {
            if ($JoinType == JOIN_LEFT) {
               if (isset($ColumnPrefix)) {
                  foreach ($ResultColumns as $Name) {
                     SetValue($ColumnPrefix.$Name, $Row, NULL);
                  }
               } else {
                  SetValue($JoinColumn, $Row, array());
               }
            } else {
               $NotFound[] = $Index;
            }
         }
      }
      
      // Remove inner join rows.
      if ($JoinType == JOIN_INNER) {
         foreach ($NotFound as $Index) {
            unset($Data[$Index]);
         }
      }
   }
Esempio n. 27
0
 public function RunStructure($AddonCode = NULL, $Explicit = FALSE, $Drop = FALSE)
 {
     // Get the structure files for all of the enabled applications.
     $ApplicationManager = new Gdn_ApplicationManager();
     $Apps = $ApplicationManager->EnabledApplications();
     $AppNames = ConsolidateArrayValuesByKey($Apps, 'Folder');
     $Paths = array();
     foreach ($Apps as $Key => $AppInfo) {
         $Path = PATH_APPLICATIONS . "/{$AppInfo['Folder']}/settings/structure.php";
         if (file_exists($Path)) {
             $Paths[] = $Path;
         }
         Gdn::ApplicationManager()->RegisterPermissions($Key, $this->Validation);
     }
     // Execute the structures.
     $Database = Gdn::Database();
     $SQL = Gdn::SQL();
     $Structure = Gdn::Structure();
     foreach ($Paths as $Path) {
         include $Path;
     }
     // Execute the structures for all of the plugins.
     $PluginManager = Gdn::PluginManager();
     $Registered = $PluginManager->RegisteredPlugins();
     foreach ($Registered as $ClassName => $Enabled) {
         if (!$Enabled) {
             continue;
         }
         try {
             $Plugin = $PluginManager->GetPluginInstance($ClassName, Gdn_PluginManager::ACCESS_CLASSNAME);
             if (method_exists($Plugin, 'Structure')) {
                 Trace("{$ClassName}->Structure()");
                 $Plugin->Structure();
             }
         } catch (Exception $Ex) {
             // Do nothing, plugin wouldn't load/structure.
             if (Debug()) {
                 throw $Ex;
             }
         }
     }
 }
 /**
  * Retrieve the user to be manipulated. If no params are passed, this will
  * retrieve the current user from the session.
  */
 public function GetUserInfo($UserReference = '', $Username = '', $UserID = '')
 {
     if (!C('Garden.Profile.Public') && !Gdn::Session()->IsValid()) {
         Redirect('dashboard/home/permission');
     }
     // If a UserID was provided as a querystring parameter, use it over anything else:
     if ($UserID) {
         $UserReference = $UserID;
         $Username = '******';
         // Fill this with a value so the $UserReference is assumed to be an integer/userid.
     }
     $this->Roles = array();
     if ($UserReference == '') {
         $this->User = $this->UserModel->Get(Gdn::Session()->UserID);
     } else {
         if (is_numeric($UserReference) && $Username != '') {
             $this->User = $this->UserModel->Get($UserReference);
         } else {
             $this->User = $this->UserModel->GetByUsername($UserReference);
         }
     }
     if ($this->User === FALSE) {
         throw NotFoundException();
     } else {
         if ($this->User->Deleted == 1) {
             Redirect('dashboard/home/deleted');
         } else {
             $this->RoleData = $this->UserModel->GetRoles($this->User->UserID);
             if ($this->RoleData !== FALSE && $this->RoleData->NumRows(DATASET_TYPE_ARRAY) > 0) {
                 $this->Roles = ConsolidateArrayValuesByKey($this->RoleData->Result(), 'Name');
             }
             $this->SetData('Profile', $this->User);
             $this->SetData('UserRoles', $this->Roles);
         }
     }
     // Make sure the userphoto module gets added to the page
     $UserPhotoModule = new UserPhotoModule($this);
     $UserPhotoModule->User = $this->User;
     $this->AddModule($UserPhotoModule);
     $this->AddSideMenu();
     return TRUE;
 }
Esempio n. 29
0
 /**
  * @param DiscussionController $Sender
  */
 public function DiscussionController_Render_Before($Sender, $Args)
 {
     $ConversationID = $Sender->Data('Discussion.Attributes.WhisperConversationID');
     if (!$ConversationID) {
         return;
     }
     if ($ConversationID === TRUE) {
         $UserIDs = $Sender->Data('Discussion.Attributes.WhisperUserIDs');
         // Grab the users that are in the conversaton.
         $WhisperUsers = array();
         foreach ($UserIDs as $UserID) {
             $WhisperUsers[] = array('UserID' => $UserID);
         }
     } else {
         // There is already a conversation so grab its users.
         $WhisperUsers = Gdn::SQL()->Select('UserID')->From('UserConversation')->Where('ConversationID', $ConversationID)->Where('Deleted', 0)->Get()->ResultArray();
         $UserIDs = ConsolidateArrayValuesByKey($WhisperUsers, 'UserID');
     }
     if (!Gdn::Session()->CheckPermission('Conversations.Moderation.Manage') && !in_array(Gdn::Session()->UserID, $UserIDs)) {
         $Sender->Data['Discussion']->Closed = TRUE;
         return;
     }
     Gdn::UserModel()->JoinUsers($WhisperUsers, array('UserID'));
     $Sender->SetData('WhisperUsers', $WhisperUsers);
 }
Esempio n. 30
0
 /**
  * Save conversation from form submission.
  * 
  * @since 2.0.0
  * @access public
  *
  * @param array $FormPostValues Values submitted via form.
  * @param object $MessageModel Message starting the conversation.
  * @return int Unique ID of conversation created or updated.
  */
 public function Save($FormPostValues, $MessageModel)
 {
     $Session = Gdn::Session();
     // Define the primary key in this model's table.
     $this->DefineSchema();
     $MessageModel->DefineSchema();
     if (!GetValue('RecipientUserID', $FormPostValues) && isset($FormPostValues['To'])) {
         $To = explode(',', $FormPostValues['To']);
         $To = array_map('trim', $To);
         $RecipientUserIDs = $this->SQL->Select('UserID')->From('User')->WhereIn('Name', $To)->Get();
         $RecipientUserIDs = ConsolidateArrayValuesByKey($RecipientUserIDs, 'UserID');
         $FormPostValues['RecipientUserID'] = $RecipientUserIDs;
     }
     // Add & apply any extra validation rules:
     $this->Validation->ApplyRule('Body', 'Required');
     $MessageModel->Validation->ApplyRule('Body', 'Required');
     // Make sure that there is at least one recipient
     $this->Validation->AddRule('OneOrMoreArrayItemRequired', 'function:ValidateOneOrMoreArrayItemRequired');
     $this->Validation->ApplyRule('RecipientUserID', 'OneOrMoreArrayItemRequired');
     // Add insert/update fields
     $this->AddInsertFields($FormPostValues);
     $this->AddUpdateFields($FormPostValues);
     // Validate the form posted values
     $ConversationID = FALSE;
     if ($this->Validate($FormPostValues) && $MessageModel->Validate($FormPostValues)) {
         $Fields = $this->Validation->ValidationFields();
         // All fields on the form that relate to the schema
         // Define the recipients, and make sure that the sender is in the list
         $RecipientUserIDs = GetValue('RecipientUserID', $Fields, 0);
         if (!in_array($Session->UserID, $RecipientUserIDs)) {
             $RecipientUserIDs[] = $Session->UserID;
         }
         // Also make sure there are no duplicates in the recipient list
         $RecipientUserIDs = array_unique($RecipientUserIDs);
         sort($RecipientUserIDs);
         $Fields = $this->Validation->SchemaValidationFields();
         // All fields on the form that relate to the schema
         $Fields['Contributors'] = Gdn_Format::Serialize($RecipientUserIDs);
         $ConversationID = $this->SQL->Insert($this->Name, $Fields);
         $FormPostValues['ConversationID'] = $ConversationID;
         $MessageID = $MessageModel->Save($FormPostValues);
         $this->SQL->Update('Conversation')->Set('FirstMessageID', $MessageID)->Where('ConversationID', $ConversationID)->Put();
         // Now that the message & conversation have been inserted, insert all of the recipients
         foreach ($RecipientUserIDs as $UserID) {
             $CountReadMessages = $UserID == $Session->UserID ? 1 : 0;
             $this->SQL->Options('Ignore', TRUE)->Insert('UserConversation', array('UserID' => $UserID, 'ConversationID' => $ConversationID, 'LastMessageID' => $MessageID, 'CountReadMessages' => $CountReadMessages, 'DateConversationUpdated' => $FormPostValues['DateUpdated']));
         }
         // And update the CountUnreadConversations count on each user related to the discussion.
         $this->UpdateUserUnreadCount($RecipientUserIDs, TRUE);
         // Add notifications (this isn't done by the conversationmessagemodule
         // because the conversation has not yet been created at the time they are
         // inserted)
         $UnreadData = $this->SQL->Select('uc.UserID')->From('UserConversation uc')->Where('uc.ConversationID', $ConversationID)->Where('uc.UserID <>', $Session->UserID)->Get();
         $ActivityModel = new ActivityModel();
         foreach ($UnreadData->Result() as $User) {
             // Notify the users of the new message.
             $ActivityID = $ActivityModel->Add($Session->UserID, 'ConversationMessage', '', $User->UserID, '', "/messages/{$ConversationID}#{$MessageID}", FALSE);
             $Story = ArrayValue('Body', $FormPostValues, '');
             $ActivityModel->SendNotification($ActivityID, $Story);
         }
     } else {
         // Make sure that all of the validation results from both validations are present for view by the form
         foreach ($MessageModel->ValidationResults() as $FieldName => $Results) {
             foreach ($Results as $Result) {
                 $this->Validation->AddValidationResult($FieldName, $Result);
             }
         }
     }
     return $ConversationID;
 }