Garden is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Garden is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Garden. If not, see . Contact Mark O'Sullivan at mark [at] lussumo [dot] com
/**
 */
function smarty_function_signin_link($Params, &$Smarty)
{
    if (!Gdn::Session()->IsValid()) {
        $Wrap = GetValue('wrap', $Params, 'li');
        return Gdn_Theme::Link('signinout', GetValue('text', $Params, ''), GetValue('format', $Params, Wrap('<a href="%url" rel="nofollow" class="%class">%text</a>', $Wrap)), $Params);
    }
}
 public function pluginController_quoteMention_create($sender, $discussionID, $commentID, $username)
 {
     $sender->deliveryMethod(DELIVERY_METHOD_JSON);
     $user = Gdn::userModel()->getByUsername($username);
     $discussionModel = new DiscussionModel();
     $discussion = $discussionModel->getID($discussionID);
     if (!$user || !$discussion) {
         throw notFoundException();
     }
     // Make sure this endpoint can't be used to snoop around.
     $sender->permission('Vanilla.Discussions.View', true, 'Category', $discussion->PermissionCategoryID);
     // Find the previous comment of the mentioned user in this discussion.
     $item = Gdn::sql()->getWhere('Comment', ['DiscussionID' => $discussion->DiscussionID, 'InsertUserID' => $user->UserID, 'CommentID <' => $commentID], 'CommentID', 'desc', 1)->firstRow();
     // The items ID in the DOM used for highlighting.
     if ($item) {
         $target = '#Comment_' . $item->CommentID;
         // The mentioned user might be the discussion creator.
     } elseif ($discussion->InsertUserID == $user->UserID) {
         $item = $discussion;
         $target = '#Discussion_' . $item->DiscussionID;
     }
     if (!$item) {
         // A success response code always means that a comment was found.
         $sender->statusCode(404);
     }
     $sender->renderData($item ? ['html' => nl2br(sliceString(Gdn_Format::plainText($item->Body, $item->Format), c('QuoteMention.MaxLength', 400))), 'target' => $target] : []);
 }
Example #3
0
 /**
  * Function for quick modify sorting for modules in configuration file.
  * See library/core/class.controller.php ~ L: 118
  * If $PositionItem is False (default) $ModuleName will be added to the edn of the list.
  * If $PositionItem is integer (positive or negative) ...
  * If $PositionItem is string ...
  * 
  * @param string $ModuleSortContainer, container name.
  * @param string $AssetName, asset name.
  * @param string $ModuleName, module name which need to add to config.
  * @param mixed $PositionItem.
  * @return bool. Return FALSE on failure.
  */
 function SetModuleSort($ModuleSortContainer, $AssetName, $ModuleName, $PositionItem = False)
 {
     $ModuleSort = Gdn::Config('Modules');
     $AssetSort = GetValueR("{$ModuleSortContainer}.{$AssetName}", $ModuleSort, array());
     if (!is_array($AssetSort)) {
         $AssetSort = array();
     }
     if ($PositionItem !== False) {
         if (!is_numeric($PositionItem)) {
             $Position = substr($PositionItem, 0, 1);
             if (in_array($Position, array('-', '+'))) {
                 $PositionItem = substr($PositionItem, 1);
             }
             $PositionItem = array_search($PositionItem, $AssetSort);
             if ($Position == '+') {
                 $PositionItem = (int) $PositionItem + 1;
             }
         }
         $PositionItem = (int) $PositionItem;
         array_splice($AssetSort, $PositionItem, 0, array($ModuleName));
     } else {
         array_push($AssetSort, $ModuleName);
     }
     $AssetSort = array_unique($AssetSort);
     // Make sure that we put in config strings only.
     $VarExport = create_function('$Value', 'return var_export(strval($Value), True);');
     $ModuleList = implode(', ', array_map($VarExport, $AssetSort));
     $PhpArrayCode = "\n\$Configuration['Modules']['{$ModuleSortContainer}']['{$AssetName}'] = array({$ModuleList});";
     $ConfigFile = PATH_CONF . '/config.php';
     $Result = file_put_contents($ConfigFile, $PhpArrayCode, FILE_APPEND | LOCK_EX);
     return $Result !== False;
 }
/**
 * A placeholder for future menu items.
 *
 * @param array $Params The parameters passed into the function.
 * @param Smarty $Smarty The smarty object rendering the template.
 * @return string
 */
function smarty_function_custom_menu($Params, &$Smarty)
{
    $Controller = $Smarty->Controller;
    if (is_object($Menu = val('Menu', $Controller))) {
        $Format = val('format', $Params, wrap('<a href="%url" class="%class">%text</a>', val('wrap', $Params, 'li')));
        $Result = '';
        foreach ($Menu->Items as $Group) {
            foreach ($Group as $Item) {
                // Make sure the item is a custom item.
                if (valr('Attributes.Standard', $Item)) {
                    continue;
                }
                // Make sure the user has permission for the item.
                if ($Permission = val('Permission', $Item)) {
                    if (!Gdn::session()->checkPermission($Permission)) {
                        continue;
                    }
                }
                if (($Url = val('Url', $Item)) && ($Text = val('Text', $Item))) {
                    $Attributes = val('Attributes', $Item);
                    $Result .= Gdn_Theme::link($Url, $Text, $Format, $Attributes) . "\r\n";
                }
            }
        }
        return $Result;
    }
    return '';
}
 /**
  * Custom finalization.
  *
  * @throws Exception
  */
 public function afterImport()
 {
     // Set up the routes to redirect from their older counterparts.
     $Router = Gdn::router();
     // Categories
     $Router->SetRoute('forumdisplay\\.php\\?f=(\\d+)', 'categories/$1', 'Permanent');
     $Router->SetRoute('archive\\.php/f-(\\d+)\\.html', 'categories/$1', 'Permanent');
     // Discussions & Comments
     $Router->SetRoute('showthread\\.php\\?t=(\\d+)', 'discussion/$1', 'Permanent');
     //$Router->SetRoute('showthread\.php\?p=(\d+)', 'discussion/comment/$1#Comment_$1', 'Permanent');
     //$Router->SetRoute('showpost\.php\?p=(\d+)', 'discussion/comment/$1#Comment_$1', 'Permanent');
     $Router->SetRoute('archive\\.php/t-(\\d+)\\.html', 'discussion/$1', 'Permanent');
     // Profiles
     $Router->SetRoute('member\\.php\\?u=(\\d+)', 'profile/$1/x', 'Permanent');
     $Router->SetRoute('usercp\\.php', 'profile', 'Permanent');
     $Router->SetRoute('profile\\.php', 'profile', 'Permanent');
     // Other
     $Router->SetRoute('attachment\\.php\\?attachmentid=(\\d+)', 'discussion/download/$1', 'Permanent');
     $Router->SetRoute('search\\.php', 'discussions', 'Permanent');
     $Router->SetRoute('private\\.php', 'messages/all', 'Permanent');
     $Router->SetRoute('subscription\\.php', 'discussions/bookmarked', 'Permanent');
     // Make different sizes of avatars
     $this->ProcessAvatars();
     // Prep config for ProfileExtender plugin based on imported fields
     $this->ProfileExtenderPrep();
     // Set guests to System user to prevent security issues
     $SystemUserID = Gdn::userModel()->GetSystemUserID();
     $this->SQL->update('Discussion')->set('InsertUserID', $SystemUserID)->where('InsertUserID', 0)->put();
     $this->SQL->update('Comment')->set('InsertUserID', $SystemUserID)->where('InsertUserID', 0)->put();
 }
 /**
  * List all update checks.
  *
  * @param bool|false $Offset
  * @param string $SortField
  */
 public function index($Offset = false, $SortField = '')
 {
     $this->permission('Garden.Settings.Manage');
     $this->addSideMenu('updates');
     $this->addJsFile('jquery.gardenmorepager.js');
     $this->title('Remote Updates');
     $this->Form->Method = 'get';
     $Limit = 30;
     $SortField = $SortField == 'CountComments' ? 'c.CountComments' : 'c.DateInserted';
     // Input Validation
     $Offset = is_numeric($Offset) ? $Offset : 0;
     // What the actual model in my controller, guy?
     $this->UpdateData = Gdn::sql()->query("\n            select s.Location, s.RemoteIp, c.DateInserted, c.CountUsers, c.CountDiscussions, c.CountComments\n            from GDN_UpdateCheckSource s\n            join (select SourceID, max(UpdateCheckID) as UpdateCheckID from GDN_UpdateCheck group by SourceID) mc\n                on s.SourceID = mc.SourceID\n            join GDN_UpdateCheck c\n                on mc.UpdateCheckID = c.UpdateCheckID\n            order by {$SortField} desc\n            limit {$Offset}, {$Limit}");
     $TotalRecords = Gdn::sql()->select('SourceID', 'count', 'CountSources')->from('UpdateCheckSource')->get()->firstRow()->CountSources;
     // Build a pager
     $PagerFactory = new Gdn_PagerFactory();
     $this->Pager = $PagerFactory->getPager('MorePager', $this);
     $this->Pager->MoreCode = 'More';
     $this->Pager->LessCode = 'Previous';
     $this->Pager->ClientID = 'Pager';
     $this->Pager->Wrapper = '<tr %1$s><td colspan="6">%2$s</td></tr>';
     $this->Pager->configure($Offset, $Limit, $TotalRecords, 'updates/index/%1$s/' . urlencode($SortField));
     // Deliver json data if necessary
     if ($this->_DeliveryType != DELIVERY_TYPE_ALL) {
         $this->setJson('LessRow', $this->Pager->toString('less'));
         $this->setJson('MoreRow', $this->Pager->toString('more'));
     }
     $this->render();
 }
    public function ToString()
    {
        $String = '';
        ob_start();
        ?>
      <div class="Box">
         <h4><?php 
        echo Gdn::Translate('In this Discussion');
        ?>
</h4>
         <ul class="PanelInfo">
         <?php 
        foreach ($this->_UserData->Result() as $User) {
            ?>
            <li>
               <strong><?php 
            echo Anchor($User->Name, '/profile/' . urlencode($User->Name), 'UserLink');
            ?>
</strong>
               <?php 
            echo Format::Date($User->DateLastActive);
            ?>
            </li>
            <?php 
        }
        ?>
         </ul>
      </div>
      <?php 
        $String = ob_get_contents();
        @ob_end_clean();
        return $String;
    }
Example #8
0
 public function Base_Render_Before(&$Sender)
 {
     // Add menu items.
     $Session = Gdn::Session();
     if ($Sender->Menu) {
         $Sender->Menu->AddLink('Dashboard', 'Dashboard', '/garden/settings', array('Garden.Settings.Manage'));
         $Sender->Menu->AddLink('Dashboard', 'Users', '/user/browse', array('Garden.Users.Add', 'Garden.Users.Edit', 'Garden.Users.Delete'));
         $Sender->Menu->AddLink('Activity', 'Activity', '/activity');
         $Authenticator = Gdn::Authenticator();
         if ($Session->IsValid()) {
             $Sender->Menu->AddLink('SignOut', 'Sign Out', '/entry/leave/{Session_TransientKey}', FALSE, array('class' => 'NonTab'));
             $Notifications = Gdn::Translate('Notifications');
             $CountNotifications = $Session->User->CountNotifications;
             if (is_numeric($CountNotifications) && $CountNotifications > 0) {
                 $Notifications .= '<span>' . $CountNotifications . '</span>';
             }
             $Sender->Menu->AddLink('User', '{Username}', '/profile/{Username}', array('Garden.SignIn.Allow'));
             $Sender->Menu->AddLink('User', '\\' . $Notifications, 'profile/notifications/{Username}');
         } else {
             $Sender->Menu->AddLink('Entry', 'Sign In', $Authenticator->SignInUrl());
         }
     }
     // Enable theme previewing
     if ($Session->IsValid()) {
         $PreviewTheme = $Session->GetPreference('PreviewTheme', '');
         if ($PreviewTheme != '') {
             $Sender->Theme = $PreviewTheme;
         }
     }
 }
 public function ToString()
 {
     if (!Gdn::Session()->IsValid()) {
         return parent::ToString();
     }
     return '';
 }
 public function Save($FormPostValues)
 {
     $Session = Gdn::Session();
     // Define the primary key in this model's table.
     $this->DefineSchema();
     // Add & apply any extra validation rules:
     $this->Validation->ApplyRule('Body', 'Required');
     $this->AddInsertFields($FormPostValues);
     // Validate the form posted values
     $MessageID = FALSE;
     if ($this->Validate($FormPostValues)) {
         $Fields = $this->Validation->SchemaValidationFields();
         // All fields on the form that relate to the schema
         $MessageID = $this->SQL->Insert($this->Name, $Fields);
         $ConversationID = ArrayValue('ConversationID', $Fields, 0);
         // Update the conversation's DateUpdated field
         $this->SQL->Update('Conversation')->Set('DateUpdated', Format::ToDateTime())->Set('UpdateUserID', $Session->UserID)->Where('ConversationID', $ConversationID)->Put();
         // NOTE: INCREMENTING COUNTS INSTEAD OF GETTING ACTUAL COUNTS COULD
         // BECOME A PROBLEM. WATCH FOR IT.
         // Update the message counts for all users in the conversation
         $this->SQL->Update('UserConversation')->Set('CountMessages', 'CountMessages + 1', FALSE)->Where('ConversationID', $ConversationID)->Put();
         $this->SQL->Update('UserConversation')->Set('CountNewMessages', 'CountNewMessages + 1', FALSE)->Where('ConversationID', $ConversationID)->Where('UserID <>', $Session->UserID)->Put();
         // Update the CountUnreadConversations count on each user related to the discussion.
         $this->UpdateCountUnreadConversations($ConversationID, $Session->UserID);
         // Update the userconversation records to reflect the most recently
         // added message for all users other than the one that added the
         // message (otherwise they would see their name/message on the
         // conversation list instead of the person they are conversing with).
         $this->SQL->Update('UserConversation')->Set('LastMessageID', $MessageID)->Where('ConversationID', $ConversationID)->Where('UserID <>', $Session->UserID)->Put();
     }
     return $MessageID;
 }
 /**
  * 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 = array_column($Activities, 'ActivityID');
     $ActivityModel->setNotified($ActivityIDs);
     $Sender->EventArguments['Activities'] =& $Activities;
     $Sender->fireEvent('InformNotifications');
     foreach ($Activities as $Activity) {
         if ($Activity['Photo']) {
             $UserPhoto = anchor(img($Activity['Photo'], array('class' => 'ProfilePhotoMedium')), $Activity['Url'], 'Icon');
         } else {
             $UserPhoto = '';
         }
         $Excerpt = Gdn_Format::plainText($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'));
     }
 }
Example #12
0
 public function Comment()
 {
     $Session = Gdn::Session();
     $this->Form->SetModel($this->ActivityModel);
     $NewActivityID = 0;
     if ($this->Form->AuthenticatedPostBack()) {
         $Body = $this->Form->GetValue('Body', '');
         $ActivityID = $this->Form->GetValue('ActivityID', '');
         if ($Body != '' && is_numeric($ActivityID) && $ActivityID > 0) {
             $NewActivityID = $this->ActivityModel->Add($Session->UserID, 'ActivityComment', $Body, '', $ActivityID, '', TRUE);
         }
     }
     // Redirect back to the sending location if this isn't an ajax request
     if ($this->_DeliveryType === DELIVERY_TYPE_ALL) {
         Redirect($this->Form->GetValue('Return', Gdn_Url::WebRoot()));
     } else {
         // Load the newly added comment
         $this->Comment = $this->ActivityModel->GetID($NewActivityID);
         $this->Comment->ActivityType .= ' Hidden';
         // Hide it so jquery can reveal it
         // Set it in the appropriate view
         $this->View = 'comment';
         // And render
         $this->Render();
     }
 }
 public function __construct(&$Sender = '')
 {
     $Session = Gdn::Session();
     if (property_exists($Sender, 'Conversation')) {
         $this->Conversation = $Sender->Conversation;
     }
     $this->Form = Gdn::Factory('Form', 'AddPeople');
     // $this->Form->Action = $Sender->SelfUrl;
     // If the form was posted back, check for people to add to the conversation
     if ($this->Form->AuthenticatedPostBack()) {
         $NewRecipientUserIDs = array();
         $NewRecipients = explode(',', $this->Form->GetFormValue('AddPeople', ''));
         $UserModel = Gdn::Factory("UserModel");
         foreach ($NewRecipients as $Name) {
             if (trim($Name) != '') {
                 $User = $UserModel->GetByUsername(trim($Name));
                 if (is_object($User)) {
                     $NewRecipientUserIDs[] = $User->UserID;
                 }
             }
         }
         $Sender->ConversationModel->AddUserToConversation($this->Conversation->ConversationID, $NewRecipientUserIDs);
         // if ($Sender->DeliveryType() == DELIVERY_TYPE_ALL)
         //    Redirect('/messages/'.$this->Conversation->ConversationID);
         $Sender->StatusMessage = T('Your changes were saved.');
         $Sender->RedirectUrl = Url('/messages/' . $this->Conversation->ConversationID);
     }
     $this->_ApplicationFolder = $Sender->Application;
     $this->_ThemeFolder = $Sender->Theme;
 }
 /**
  * Is the application/plugin/theme removable?
  *
  * @param string $Type self::TYPE_APPLICATION or self::TYPE_PLUGIN or self::TYPE_THEME
  * @param string $Name
  * @return boolean
  */
 public static function isRemovable($Type, $Name)
 {
     switch ($Type) {
         case self::TYPE_APPLICATION:
             $ApplicationManager = Gdn::Factory('ApplicationManager');
             if ($IsRemovable = !array_key_exists($Name, $ApplicationManager->EnabledApplications())) {
                 $ApplicationInfo = arrayValue($Name, $ApplicationManager->AvailableApplications(), array());
                 $ApplicationFolder = arrayValue('Folder', $ApplicationInfo, '');
                 $IsRemovable = IsWritable(PATH_APPLICATIONS . DS . $ApplicationFolder);
             }
             break;
         case self::TYPE_PLUGIN:
             if ($IsRemovable = !array_key_exists($Name, Gdn::pluginManager()->EnabledPlugins())) {
                 $PluginInfo = arrayValue($Name, Gdn::pluginManager()->AvailablePlugins(), false);
                 $PluginFolder = arrayValue('Folder', $PluginInfo, false);
                 $IsRemovable = IsWritable(PATH_PLUGINS . DS . $PluginFolder);
             }
             break;
         case self::TYPE_THEME:
             // TODO
             $IsRemovable = false;
             break;
     }
     return $IsRemovable;
 }
 public function AddQuery($Sender, $Options = FALSE)
 {
     if ($Sender->ControllerName == 'searchcontroller' && $Options['Landing'] == FALSE && $this->Settings['Admin']->LimitRelatedThreadsMain > 0) {
         $Sanitized = $this->ValidateInputs();
         $this->SphinxClient->ResetFilters();
         $this->SphinxClient->ResetGroupBy();
         $this->SphinxClient->SetSortMode(SPH_SORT_RELEVANCE);
         $this->SphinxClient->SetRankingMode(SPH_RANK_WORDCOUNT);
         $this->SphinxClient->SetLimits(0, $this->Settings['Admin']->LimitRelatedThreadsMain);
         //must first clear any special characters in query string if using the extended syntax
         //@todo probably better to use the 'words' index
         $Query = $this->FieldSearch($this->OperatorOrSearch($this->ClearFromTags($Sanitized['Query'])), array(SS_FIELD_TITLE));
         //echo $Query; die;
         //Make sure results respect category permissions depending on user performing search
         $Permissions = Gdn::Session()->GetPermissions();
         // Get user permissions
         $Permissions = $Permissions['Vanilla.Discussions.View'];
         // Only care about 'viewing' permissions
         $this->SphinxClient->SetFilter(SS_ATTR_CATPERMID, $Permissions);
         $QueryIndex = $this->SphinxClient->AddQuery($Query . ' ', $Index = SS_INDEX_DIST, $this->Name);
         $this->Queries[] = array('Name' => $this->Name, 'Index' => $QueryIndex);
         return $this->Queries;
     } else {
         return FALSE;
     }
 }
 public function GetData()
 {
     $TagQuery = Gdn::SQL();
     $this->AutoContext();
     $TagCacheKey = "TagModule-{$this->ParentType}-{$this->ParentID}";
     switch ($this->ParentType) {
         case 'Discussion':
             $Tags = TagModel::instance()->getDiscussionTags($this->ParentID, false);
             break;
         case 'Category':
             $TagQuery->Join('TagDiscussion td', 't.TagID = td.TagID')->Select('COUNT(DISTINCT td.TagID)', '', 'NumTags')->Where('td.CategoryID', $this->ParentID)->GroupBy('td.TagID')->Cache($TagCacheKey, 'get', array(Gdn_Cache::FEATURE_EXPIRY => 120));
             break;
         case 'Global':
             $TagCacheKey = 'TagModule-Global';
             $TagQuery->Where('t.CountDiscussions >', 0, FALSE)->Cache($TagCacheKey, 'get', array(Gdn_Cache::FEATURE_EXPIRY => 120));
             if ($this->CategorySearch) {
                 $TagQuery->Where('t.CategoryID', '-1');
             }
             break;
     }
     if (isset($Tags)) {
         $this->_TagData = new Gdn_DataSet($Tags, DATASET_TYPE_ARRAY);
     } else {
         $this->_TagData = $TagQuery->Select('t.*')->From('Tag t')->OrderBy('t.CountDiscussions', 'desc')->Limit(25)->Get();
     }
     $this->_TagData->DatasetType(DATASET_TYPE_ARRAY);
 }
 public function DiscussionModel_BeforeSaveDiscussion_Handler($Sender, &$Args)
 {
     if ($Args['FormPostValues']['InsertUserID'] != Gdn::Session()->UserID) {
         return;
     }
     $this->SetAttributes($Sender, $Args);
 }
Example #18
0
 public function ToString()
 {
     if (Gdn::Config('Vanilla.Categories.Use') == TRUE) {
         return parent::ToString();
     }
     return '';
 }
Example #19
0
 /**
  * Register the debug database that captures the queries.
  *
  * This event happens as early as possible so that all queries can be captured.
  *
  * @param Gdn_PluginManager $sender The {@link Gdn_PluginManager} firing the event.
  */
 public function gdn_pluginManager_afterStart_handler($sender)
 {
     $tmp = Gdn::factoryOverwrite(true);
     Gdn::factoryInstall(Gdn::AliasDatabase, 'Gdn_DatabaseDebug', dirname(__FILE__) . DS . 'class.databasedebug.php', Gdn::FactorySingleton, array('Database'));
     Gdn::factoryOverwrite($tmp);
     unset($tmp);
 }
Example #20
0
 public function PluginController_SingleSignOn_Create($Sender, $EventArguments)
 {
     $Sender->Head->Title('Single Sign-on');
     $Sender->AddSideMenu('garden/plugin/singlesignon');
     $Validation = new Gdn_Validation();
     $ConfigurationModel = new Gdn_ConfigurationModel($Validation);
     $ConfigurationModel->SetField(array('Garden.Authenticator.Type', 'Garden.Authenticator.Encoding', 'Garden.Authenticator.AuthenticateUrl', 'Garden.Authenticator.SignInUrl', 'Garden.Authenticator.SignOutUrl', 'Garden.Authenticator.RegisterUrl', 'Garden.Cookie.Path'));
     // Set the model on the form.
     $Sender->Form = new Gdn_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);
         $Sender->Form->SetValue('EnableSSO', Gdn::Config('Garden.Authenticator.Type') == 'Handshake' ? 'TRUE' : '');
     } else {
         // Make sure to force some values
         $Sender->Form->SetFormValue('Garden.Authenticator.Type', $Sender->Form->GetFormValue('EnableSSO', '') == 'TRUE' ? 'Handshake' : 'Password');
         $Sender->Form->SetFormValue('Garden.Authenticator.Encoding', 'ini');
         $Sender->Form->SetFormValue('Garden.Cookie.Path', '/');
         // <-- Make sure that Vanilla's cookies don't have a path
         if ($Sender->Form->Save() !== FALSE) {
             $Sender->StatusMessage = Translate("Your changes have been saved successfully.");
         }
     }
     $Sender->Render(PATH_PLUGINS . DS . 'SingleSignOn' . DS . 'views' . DS . 'index.php');
 }
Example #21
0
    /**
     * Show buttons after OP message body.
     */
    public function DiscussionController_AfterDiscussionBody_Handler($Sender)
    {
        $PublisherNumber = C('Plugin.ShareThis.PublisherNumber', 'Publisher Number');
        $ViaHandle = C('Plugin.ShareThis.ViaHandle', '');
        $CopyNShare = C('Plugin.ShareThis.CopyNShare', false);
        $doNotHash = $CopyNShare ? 'false' : 'true';
        $doNotCopy = $CopyNShare ? 'false' : 'true';
        $Domain = Gdn::Request()->Scheme() == 'https' ? 'https://ws.sharethis.com' : 'http://w.sharethis.com';
        echo <<<SHARETHIS
      <script type="text/javascript">var switchTo5x=true;</script>
      <script type="text/javascript" src="{$Domain}/button/buttons.js"></script>
      <script type="text/javascript">stLight.options({
         publisher: "{$PublisherNumber}",
         doNotHash: {$doNotHash},
         doNotCopy: {$doNotCopy},
         hashAddressBar: false
      });</script>
      <div class="ShareThisButtonWrapper Right">
         <span class="st_twitter_hcount ShareThisButton" st_via="{$ViaHandle}" displayText="Tweet"></span>
         <span class="st_facebook_hcount ShareThisButton" displayText="Facebook"></span>
         <span class="st_linkedin_hcount ShareThisButton Hidden" displayText="LinkedIn"></span>
         <span class="st_googleplus_hcount ShareThisButton Hidden" displayText="Google +"></span>
         <span class="st_reddit_hcount ShareThisButton Hidden" displayText="Reddit"></span>
         <span class="st_pinterest_hcount ShareThisButton Hidden" displayText="Pinterest"></span>
         <span class="st_email_hcount ShareThisButton" displayText="Email"></span>
         <span class="st_sharethis_hcountShareThisButton" displayText="ShareThis"></span>
      </div>
SHARETHIS;
    }
 public function ToString()
 {
     $HasPermission = Gdn::Session()->CheckPermission('Vanilla.Discussions.Add', TRUE, 'Category', 'any');
     if ($HasPermission) {
         echo Anchor(T('Ask a Question'), '/post/discussion?Type=Question', 'Button BigButton NewQuestion');
     }
 }
Example #23
0
 public function Base_Render_Before(&$Sender)
 {
     $Session = Gdn::Session();
     // Enable theme previewing
     if ($Session->IsValid()) {
         $PreviewThemeFolder = $Session->GetPreference('PreviewThemeFolder', '');
         // echo 'test'.$PreviewThemeFolder;
         if ($PreviewThemeFolder != '') {
             $Sender->Theme = $PreviewThemeFolder;
             $Sender->AddAsset('Content', $Sender->FetchView('previewtheme', 'settingscontroller', 'dashboard'));
             $Sender->AddCssFile('previewtheme.css');
         }
     }
     // Add Message Modules (if necessary)
     $MessageCache = Gdn::Config('Garden.Messages.Cache', array());
     $Location = $Sender->Application . '/' . substr($Sender->ControllerName, 0, -10) . '/' . $Sender->RequestMethod;
     if ($Sender->MasterView != 'empty' && in_array('Base', $MessageCache) || InArrayI($Location, $MessageCache)) {
         $MessageModel = new MessageModel();
         $MessageData = $MessageModel->GetMessagesForLocation($Location);
         foreach ($MessageData as $Message) {
             $MessageModule = new MessageModule($Sender, $Message);
             $Sender->AddModule($MessageModule);
         }
     }
 }
Example #24
0
 public function Index($Offset = 0, $Limit = NULL)
 {
     $this->AddJsFile('/js/library/jquery.gardenmorepager.js');
     $this->AddJsFile('search.js');
     $this->Title(Translate('Search'));
     if (!is_numeric($Limit)) {
         $Limit = Gdn::Config('Garden.Search.PerPage', 20);
     }
     $Search = $this->Form->GetFormValue('Search');
     $ResultSet = $this->SearchModel->Search($Search, $Offset, $Limit);
     $this->SetData('SearchResults', $ResultSet, TRUE);
     $this->SetData('SearchTerm', Format::Text($Search), TRUE);
     $NumResults = $ResultSet->NumRows();
     if ($NumResults == $Offset + $Limit) {
         $NumResults++;
     }
     // Build a pager
     $PagerFactory = new PagerFactory();
     $Pager = $PagerFactory->GetPager('MorePager', $this);
     $Pager->MoreCode = 'More Results';
     $Pager->LessCode = 'Previous Results';
     $Pager->ClientID = 'Pager';
     $Pager->Configure($Offset, $Limit, $NumResults, 'garden/search/%1$s/%2$s/?Search=' . Format::Url($Search));
     $this->SetData('Pager', $Pager, TRUE);
     $this->View = 'results';
     $this->Render();
 }
Example #25
0
 public function Edit($MessageID = '')
 {
     $this->AddJsFile('js/library/jquery.autogrow.js');
     $this->AddJsFile('messages.js');
     $this->Permission('Garden.Messages.Manage');
     $this->AddSideMenu('garden/message');
     // Generate some Controller & Asset data arrays
     $this->LocationData = $this->_GetLocationData();
     $this->AssetData = $this->_GetAssetData();
     // Set the model on the form.
     $this->Form->SetModel($this->MessageModel);
     $this->Message = $this->MessageModel->GetID($MessageID);
     // Make sure the form knows which item we are editing.
     if (is_numeric($MessageID) && $MessageID > 0) {
         $this->Form->AddHidden('MessageID', $MessageID);
     }
     // If seeing the form for the first time...
     if ($this->Form->AuthenticatedPostBack() === FALSE) {
         $this->Form->SetData($this->Message);
     } else {
         if ($MessageID = $this->Form->Save()) {
             // Reset the message cache
             $this->MessageModel->SetMessageCache();
             // Redirect
             $this->StatusMessage = Gdn::Translate('Your changes have been saved.');
             $this->RedirectUrl = Url('garden/message');
         }
     }
     $this->Render();
 }
Example #26
0
/**
 * Writes the search box to the page.
 *
 * @param array The parameters passed into the function. This currently takes no parameters.
 * @param Smarty The smarty object rendering the template.
 * @return The url.
 */
function smarty_function_searchbox($Params, &$Smarty)
{
    $Form = Gdn::Factory('Form');
    $Form->InputPrefix = '';
    $Result = $Form->Open(array('action' => Url('/search'), 'method' => 'get')) . $Form->TextBox('Search', array('placeholder' => T('Search'))) . $Form->Button('Go', array('Name' => '')) . $Form->Close();
    return $Result;
}
Example #27
0
 /**
  *
  *
  * @param $ForeignType
  * @param array $ForeignIDs
  * @return Gdn_DataSet
  */
 public function getAll($ForeignType, $ForeignIDs = array())
 {
     if (count($ForeignIDs) == 0) {
         return new Gdn_DataSet(array());
     }
     return Gdn::sql()->select('*')->from('Regarding')->where('ForeignType', $ForeignType)->whereIn('ForeignID', $ForeignIDs)->get();
 }
Example #28
0
/**
 * Writes the search box to the page.
 *
 * @param array The parameters passed into the function. This currently takes no parameters.
 * @param $smarty The smarty object rendering the template.
 * @return The url.
 */
function smarty_function_searchbox($params, &$smarty)
{
    $placeholder = array_key_exists('placeholder', $params) ? val('placeholder', $params, '', true) : t('SearchBoxPlaceHolder', 'Search');
    $form = Gdn::factory('Form');
    $result = $form->open(array('action' => url('/search'), 'method' => 'get')) . $form->textBox('Search', array('placeholder' => $placeholder, 'accesskey' => '/')) . $form->button('Go', array('Name' => '')) . $form->close();
    return $result;
}
 public function DiscussionsController_Participated_Create(&$Sender, $Args)
 {
     $Sender->Permission('Garden.SignIn.Allow');
     $Page = GetValue(0, $Args);
     $Limit = GetValue(1, $Args);
     list($Offset, $Limit) = OffsetLimit($Page, Gdn::Config('Vanilla.Discussions.PerPage', 30));
     // Get Discussions
     $DiscussionModel = new DiscussionModel();
     $Sender->DiscussionData = $DiscussionModel->GetParticipated(Gdn::Session()->UserID, $Offset, $Limit);
     $Sender->SetData('Discussions', $Sender->DiscussionData);
     $CountDiscussions = $DiscussionModel->GetCountParticipated(Gdn::Session()->UserID);
     $Sender->SetData('CountDiscussions', $CountDiscussions);
     // Build a pager
     $PagerFactory = new Gdn_PagerFactory();
     $Sender->EventArguments['PagerType'] = 'Pager';
     $Sender->FireEvent('BeforeBuildPager');
     $Sender->Pager = $PagerFactory->GetPager($Sender->EventArguments['PagerType'], $Sender);
     $Sender->Pager->ClientID = 'Pager';
     $Sender->Pager->Configure($Offset, $Limit, $CountDiscussions, 'discussions/participated/%1$s');
     $Sender->FireEvent('AfterBuildPager');
     // Deliver JSON data if necessary
     if ($Sender->DeliveryType() != DELIVERY_TYPE_ALL) {
         $Sender->SetJson('LessRow', $Sender->Pager->ToString('less'));
         $Sender->SetJson('MoreRow', $Sender->Pager->ToString('more'));
         $Sender->View = 'discussions';
     }
     // Add modules
     $Sender->AddModule('NewDiscussionModule');
     $Sender->AddModule('CategoriesModule');
     $BookmarkedModule = new BookmarkedModule($Sender);
     $BookmarkedModule->GetData();
     $Sender->AddModule($BookmarkedModule);
     $Sender->Render($this->GetView('participated.php'));
 }
Example #30
-1
 /**
  * Delete a single draft.
  *
  * Redirects user back to Index unless DeliveryType is set.
  *
  * @since 2.0.0
  * @access public
  *
  * @param int $DraftID Unique ID of draft to be deleted.
  * @param string $TransientKey Single-use hash to prove intent.
  */
 public function delete($DraftID = '', $TransientKey = '')
 {
     $Form = Gdn::factory('Form');
     $Session = Gdn::session();
     if (is_numeric($DraftID) && $DraftID > 0) {
         $Draft = $this->DraftModel->getID($DraftID);
     }
     if ($Draft) {
         if ($Session->validateTransientKey($TransientKey) && (val('InsertUserID', $Draft) == $Session->UserID || checkPermission('Garden.Community.Manage'))) {
             // Delete the draft
             if (!$this->DraftModel->deleteID($DraftID)) {
                 $Form->addError('Failed to delete draft');
             }
         } else {
             throw permissionException('Garden.Community.Manage');
         }
     } else {
         throw notFoundException('Draft');
     }
     // Redirect
     if ($this->_DeliveryType === DELIVERY_TYPE_ALL) {
         $Target = GetIncomingValue('Target', '/drafts');
         redirect($Target);
     }
     // Return any errors
     if ($Form->errorCount() > 0) {
         $this->setJson('ErrorMessage', $Form->errors());
     }
     // Render default view
     $this->render();
 }