Inheritance: extends VanillaModel
 public function getData($Limit = 20, $DiscussionID = '')
 {
     $Session = Gdn::session();
     if ($Session->isValid()) {
         $DraftModel = new DraftModel();
         $this->Data = $DraftModel->get($Session->UserID, 0, $Limit, $DiscussionID);
     }
     $this->Form = $this->_Sender->Form;
 }
 public function Index($DiscussionID = '', $DiscussionStub = '', $Offset = '', $Limit = '')
 {
     $this->AddCssFile('vanilla.css');
     $Session = Gdn::Session();
     $this->AddJsFile('jquery.resizable.js');
     $this->AddJsFile('jquery.ui.packed.js');
     $this->AddJsFile('jquery.autogrow.js');
     //      $this->AddJsFile('jquery.gardenmorepager.js');
     $this->AddJsFile('options.js');
     $this->AddJsFile('bookmark.js');
     $this->AddJsFile('discussion.js');
     $this->AddJsFile('autosave.js');
     // Load the discussion record
     $DiscussionID = is_numeric($DiscussionID) && $DiscussionID > 0 ? $DiscussionID : 0;
     $this->SetData('Discussion', $this->DiscussionModel->GetID($DiscussionID), TRUE);
     if (!is_object($this->Discussion)) {
         return Gdn::Dispatcher()->Dispatch('Default404');
     }
     // Check Permissions
     $this->Permission('Vanilla.Discussions.View', TRUE, 'Category', $this->Discussion->CategoryID);
     $this->SetData('CategoryID', $this->CategoryID = $this->Discussion->CategoryID, TRUE);
     // Setup
     $this->Title($this->Discussion->Name);
     // Actual number of comments, excluding the discussion itself
     $ActualResponses = $this->Discussion->CountComments - 1;
     // Define the query offset & limit
     if (!is_numeric($Limit) || $Limit < 0) {
         $Limit = C('Vanilla.Comments.PerPage', 50);
     }
     $OffsetProvided = $Offset != '';
     list($Offset, $Limit) = OffsetLimit($Offset, $Limit);
     // If $Offset isn't defined, assume that the user has not clicked to
     // view a next or previous page, and this is a "view" to be counted.
     if ($Offset == '') {
         $this->DiscussionModel->AddView($DiscussionID);
     }
     $this->Offset = $Offset;
     if (C('Vanilla.Comments.AutoOffset')) {
         if (!is_numeric($this->Offset) || $this->Offset < 0 || !$OffsetProvided) {
             // Round down to the appropriate offset based on the user's read comments & comments per page
             $CountCommentWatch = $this->Discussion->CountCommentWatch > 0 ? $this->Discussion->CountCommentWatch : 0;
             if ($CountCommentWatch > $ActualResponses) {
                 $CountCommentWatch = $ActualResponses;
             }
             // (((67 comments / 10 perpage) = 6.7) rounded down = 6) * 10 perpage = offset 60;
             $this->Offset = floor($CountCommentWatch / $Limit) * $Limit;
         }
         if ($ActualResponses <= $Limit) {
             $this->Offset = 0;
         }
         if ($this->Offset == $ActualResponses) {
             $this->Offset -= $Limit;
         }
     } else {
         if ($this->Offset == '') {
             $this->Offset = 0;
         }
     }
     if ($this->Offset < 0) {
         $this->Offset = 0;
     }
     // Set the canonical url to have the proper page title.
     $this->CanonicalUrl(Url(ConcatSep('/', 'discussion/' . $this->Discussion->DiscussionID . '/' . Gdn_Format::Url($this->Discussion->Name), PageNumber($this->Offset, $Limit, TRUE)), TRUE));
     // Make sure to set the user's discussion watch records
     $this->CommentModel->SetWatch($this->Discussion, $Limit, $this->Offset, $this->Discussion->CountComments);
     // Load the comments
     $this->SetData('CommentData', $this->CommentModel->Get($DiscussionID, $Limit, $this->Offset), TRUE);
     $this->SetData('Comments', $this->CommentData);
     // Build a pager
     $PagerFactory = new Gdn_PagerFactory();
     $this->Pager = $PagerFactory->GetPager('Pager', $this);
     $this->Pager->ClientID = 'Pager';
     $this->Pager->Configure($this->Offset, $Limit, $ActualResponses, 'discussion/' . $DiscussionID . '/' . Gdn_Format::Url($this->Discussion->Name) . '/%1$s');
     //      $this->Pager->MoreCode = '%1$s more comments';
     //      $this->Pager->LessCode = '%1$s older comments';
     //      $this->Pager->ClientID = 'Pager';
     //      $this->Pager->Configure(
     //         $this->Offset,
     //         $Limit,
     //         $ActualResponses,
     //         'discussion/'.$DiscussionID.'/'.Gdn_Format::Url($this->Discussion->Name).'/%1$s/%2$s/'
     //      );
     // Define the form for the comment input
     $this->Form = Gdn::Factory('Form', 'Comment');
     $this->Form->Action = Url('/vanilla/post/comment/');
     $this->DiscussionID = $this->Discussion->DiscussionID;
     $this->Form->AddHidden('DiscussionID', $this->DiscussionID);
     $this->Form->AddHidden('CommentID', '');
     // Retrieve & apply the draft if there is one:
     $DraftModel = new DraftModel();
     $Draft = $DraftModel->Get($Session->UserID, 0, 1, $this->Discussion->DiscussionID)->FirstRow();
     $this->Form->AddHidden('DraftID', $Draft ? $Draft->DraftID : '');
     if ($Draft) {
         $this->Form->SetFormValue('Body', $Draft->Body);
     }
     // 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->View = 'comments';
     }
     // Add Modules
     $this->AddModule('NewDiscussionModule');
     $this->AddModule('CategoriesModule');
     $BookmarkedModule = new BookmarkedModule($this);
     $BookmarkedModule->GetData();
     $this->AddModule($BookmarkedModule);
     $this->FireEvent('BeforeDiscussionRender');
     $this->Render();
 }
    /**
     * Alternate version of Index that uses the embed master view.
     *
     * @param int $DiscussionID Unique identifier, if discussion has been created.
     * @param string $DiscussionStub Deprecated.
     * @param int $Offset
     * @param int $Limit
     */
    public function embed($DiscussionID = '', $DiscussionStub = '', $Offset = '', $Limit = '')
    {
        $this->title(t('Comments'));
        // Add theme data
        $this->Theme = c('Garden.CommentsTheme', $this->Theme);
        Gdn_Theme::section('Comments');
        // Force view options
        $this->MasterView = 'empty';
        $this->CanEditComments = false;
        // Don't show the comment checkboxes on the embed comments page
        // Add some css to help with the transparent bg on embedded comments
        if ($this->Head) {
            $this->Head->addString('<style type="text/css">
body { background: transparent !important; }
</style>');
        }
        // Javascript files & options
        $this->addJsFile('jquery.gardenmorepager.js');
        $this->addJsFile('jquery.autosize.min.js');
        $this->addJsFile('discussion.js');
        $this->removeJsFile('autosave.js');
        $this->addDefinition('DoInform', '0');
        // Suppress inform messages on embedded page.
        $this->addDefinition('SelfUrl', Gdn::request()->PathAndQuery());
        $this->addDefinition('Embedded', true);
        // Define incoming variables (prefer querystring parameters over method parameters)
        $DiscussionID = is_numeric($DiscussionID) && $DiscussionID > 0 ? $DiscussionID : 0;
        $DiscussionID = getIncomingValue('vanilla_discussion_id', $DiscussionID);
        $Offset = getIncomingValue('Offset', $Offset);
        $Limit = getIncomingValue('Limit', $Limit);
        $vanilla_identifier = getIncomingValue('vanilla_identifier', '');
        // Only allow vanilla identifiers of 32 chars or less - md5 if larger
        if (strlen($vanilla_identifier) > 32) {
            $vanilla_identifier = md5($vanilla_identifier);
        }
        $vanilla_type = getIncomingValue('vanilla_type', 'page');
        $vanilla_url = getIncomingValue('vanilla_url', '');
        $vanilla_category_id = getIncomingValue('vanilla_category_id', '');
        $ForeignSource = array('vanilla_identifier' => $vanilla_identifier, 'vanilla_type' => $vanilla_type, 'vanilla_url' => $vanilla_url, 'vanilla_category_id' => $vanilla_category_id);
        $this->setData('ForeignSource', $ForeignSource);
        // Set comment sorting
        $SortComments = c('Garden.Embed.SortComments') == 'desc' ? 'desc' : 'asc';
        $this->setData('SortComments', $SortComments);
        // Retrieve the discussion record
        $Discussion = false;
        if ($DiscussionID > 0) {
            $Discussion = $this->DiscussionModel->getID($DiscussionID);
        } elseif ($vanilla_identifier != '' && $vanilla_type != '') {
            $Discussion = $this->DiscussionModel->GetForeignID($vanilla_identifier, $vanilla_type);
        }
        // Set discussion data if we have one for this page
        if ($Discussion) {
            // Allow Vanilla.Comments.View to be defined to limit access to embedded comments only.
            // Otherwise, go with normal discussion view permissions. Either will do.
            $this->permission(array('Vanilla.Discussions.View', 'Vanilla.Comments.View'), false, 'Category', $Discussion->PermissionCategoryID);
            $this->setData('Discussion', $Discussion, true);
            $this->setData('DiscussionID', $Discussion->DiscussionID, true);
            $this->title($Discussion->Name);
            // Actual number of comments, excluding the discussion itself
            $ActualResponses = $Discussion->CountComments;
            // Define the query offset & limit
            if (!is_numeric($Limit) || $Limit < 0) {
                $Limit = c('Garden.Embed.CommentsPerPage', 30);
            }
            $OffsetProvided = $Offset != '';
            list($Offset, $Limit) = offsetLimit($Offset, $Limit);
            $this->Offset = $Offset;
            if (c('Vanilla.Comments.AutoOffset')) {
                if ($ActualResponses <= $Limit) {
                    $this->Offset = 0;
                }
                if ($this->Offset == $ActualResponses) {
                    $this->Offset -= $Limit;
                }
            } elseif ($this->Offset == '') {
                $this->Offset = 0;
            }
            if ($this->Offset < 0) {
                $this->Offset = 0;
            }
            // Set the canonical url to have the proper page title.
            $this->canonicalUrl(discussionUrl($Discussion, pageNumber($this->Offset, $Limit)));
            // Load the comments.
            $CurrentOrderBy = $this->CommentModel->orderBy();
            if (stringBeginsWith(GetValueR('0.0', $CurrentOrderBy), 'c.DateInserted')) {
                $this->CommentModel->orderBy('c.DateInserted ' . $SortComments);
                // allow custom sort
            }
            $this->setData('Comments', $this->CommentModel->get($Discussion->DiscussionID, $Limit, $this->Offset), true);
            if (count($this->CommentModel->where()) > 0) {
                $ActualResponses = false;
            }
            $this->setData('_Count', $ActualResponses);
            // Build a pager
            $PagerFactory = new Gdn_PagerFactory();
            $this->EventArguments['PagerType'] = 'MorePager';
            $this->fireEvent('BeforeBuildPager');
            $this->Pager = $PagerFactory->getPager($this->EventArguments['PagerType'], $this);
            $this->Pager->ClientID = 'Pager';
            $this->Pager->MoreCode = 'More Comments';
            $this->Pager->configure($this->Offset, $Limit, $ActualResponses, 'discussion/embed/' . $Discussion->DiscussionID . '/' . Gdn_Format::url($Discussion->Name) . '/%1$s');
            $this->Pager->CurrentRecords = $this->Comments->numRows();
            $this->fireEvent('AfterBuildPager');
        }
        // Define the form for the comment input
        $this->Form = Gdn::Factory('Form', 'Comment');
        $this->Form->Action = url('/post/comment/');
        $this->Form->addHidden('CommentID', '');
        $this->Form->addHidden('Embedded', 'true');
        // Tell the post controller that this is an embedded page (in case there are custom views it needs to pick up from a theme).
        $this->Form->addHidden('DisplayNewCommentOnly', 'true');
        // Only load/display the new comment after posting (don't load all new comments since the page last loaded).
        // Grab the page title
        if ($this->Request->get('title')) {
            $this->Form->setValue('Name', $this->Request->get('title'));
        }
        // Set existing DiscussionID for comment form
        if ($Discussion) {
            $this->Form->addHidden('DiscussionID', $Discussion->DiscussionID);
        }
        foreach ($ForeignSource as $Key => $Val) {
            // Drop the foreign source information into the form so it can be used if creating a discussion
            $this->Form->addHidden($Key, $Val);
            // Also drop it into the definitions so it can be picked up for stashing comments
            $this->addDefinition($Key, $Val);
        }
        // Retrieve & apply the draft if there is one:
        $Draft = false;
        if (Gdn::session()->UserID && $Discussion) {
            $DraftModel = new DraftModel();
            $Draft = $DraftModel->get(Gdn::session()->UserID, 0, 1, $Discussion->DiscussionID)->firstRow();
            $this->Form->addHidden('DraftID', $Draft ? $Draft->DraftID : '');
        }
        if ($Draft) {
            $this->Form->setFormValue('Body', $Draft->Body);
        } else {
            // Look in the session stash for a comment
            $StashComment = Gdn::session()->getPublicStash('CommentForForeignID_' . $ForeignSource['vanilla_identifier']);
            if ($StashComment) {
                $this->Form->setValue('Body', $StashComment);
                $this->Form->setFormValue('Body', $StashComment);
            }
        }
        // Deliver JSON data if necessary
        if ($this->_DeliveryType != DELIVERY_TYPE_ALL) {
            if ($this->Discussion) {
                $this->setJson('LessRow', $this->Pager->toString('less'));
                $this->setJson('MoreRow', $this->Pager->toString('more'));
            }
            $this->View = 'comments';
        }
        // Ordering note for JS
        if ($SortComments == 'desc') {
            $this->addDefinition('PrependNewComments', '1');
        }
        // Report the discussion id so js can use it.
        if ($Discussion) {
            $this->addDefinition('DiscussionID', $Discussion->DiscussionID);
        }
        $this->fireEvent('BeforeDiscussionRender');
        $this->render();
    }
 public function Index($DiscussionID = '', $DiscussionStub = '', $Offset = '', $Limit = '')
 {
     $this->AddCssFile('vanilla.css');
     $Session = Gdn::Session();
     $this->AddJsFile('/js/library/jquery.resizable.js');
     $this->AddJsFile('/js/library/jquery.ui.packed.js');
     $this->AddJsFile('/js/library/jquery.autogrow.js');
     $this->AddJsFile('/js/library/jquery.gardenmorepager.js');
     $this->AddJsFile('options.js');
     $this->AddJsFile('bookmark.js');
     $this->AddJsFile('discussion.js');
     $this->AddJsFile('autosave.js');
     // Load the discussion record
     $DiscussionID = is_numeric($DiscussionID) && $DiscussionID > 0 ? $DiscussionID : 0;
     $this->SetData('Discussion', $this->DiscussionModel->GetID($DiscussionID), TRUE);
     if (!is_object($this->Discussion)) {
         Redirect('FileNotFound');
     }
     // Check Permissions
     $this->Permission('Vanilla.Discussions.View', TRUE, 'Category', $this->Discussion->CategoryID);
     $this->SetData('CategoryID', $this->CategoryID = $this->Discussion->CategoryID, TRUE);
     if ($this->Discussion === FALSE) {
         Redirect('dashboard/home/filenotfound');
     } else {
         // Setup
         $this->Title(Gdn_Format::Text($this->Discussion->Name));
         // Actual number of comments, excluding the discussion itself
         $ActualResponses = $this->Discussion->CountComments - 1;
         // Define the query offset & limit
         if (!is_numeric($Limit) || $Limit < 0) {
             $Limit = Gdn::Config('Vanilla.Comments.PerPage', 50);
         }
         $this->Offset = $Offset;
         if (!is_numeric($this->Offset) || $this->Offset < 0) {
             // Round down to the appropriate offset based on the user's read comments & comments per page
             $CountCommentWatch = $this->Discussion->CountCommentWatch > 0 ? $this->Discussion->CountCommentWatch : 0;
             if ($CountCommentWatch > $ActualResponses) {
                 $CountCommentWatch = $ActualResponses;
             }
             // (((67 comments / 10 perpage) = 6.7) rounded down = 6) * 10 perpage = offset 60;
             $this->Offset = floor($CountCommentWatch / $Limit) * $Limit;
         }
         if ($ActualResponses <= $Limit) {
             $this->Offset = 0;
         }
         if ($this->Offset < 0) {
             $this->Offset = 0;
         }
         // Make sure to set the user's discussion watch records
         $this->CommentModel->SetWatch($this->Discussion, $Limit, $this->Offset, $this->Discussion->CountComments);
         // Load the comments
         $this->SetData('CommentData', $this->CommentModel->Get($DiscussionID, $Limit, $this->Offset), TRUE);
         $this->SetData('Comments', $this->CommentData);
         // Build a pager
         $PagerFactory = new Gdn_PagerFactory();
         $this->Pager = $PagerFactory->GetPager('MorePager', $this);
         $this->Pager->MoreCode = '%1$s more comments';
         $this->Pager->LessCode = '%1$s older comments';
         $this->Pager->ClientID = 'Pager';
         $this->Pager->Configure($this->Offset, $Limit, $ActualResponses, 'vanilla/discussion/' . $DiscussionID . '/' . Gdn_Format::Url($this->Discussion->Name) . '/%1$s/%2$s/');
     }
     // Define the form for the comment input
     $this->Form = Gdn::Factory('Form', 'Comment');
     $this->Form->Action = Url('/vanilla/post/comment/');
     $this->DiscussionID = $this->Discussion->DiscussionID;
     $this->Form->AddHidden('DiscussionID', $this->DiscussionID);
     $this->Form->AddHidden('CommentID', '');
     // Retrieve & apply the draft if there is one:
     $DraftModel = new DraftModel();
     $Draft = $DraftModel->Get($Session->UserID, 0, 1, $this->Discussion->DiscussionID)->FirstRow();
     $this->Form->AddHidden('DraftID', $Draft ? $Draft->DraftID : '');
     if ($Draft) {
         $this->Form->SetFormValue('Body', $Draft->Body);
     }
     // 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->View = 'comments';
     }
     // Add Modules
     $this->AddModule('NewDiscussionModule');
     $this->AddModule('CategoriesModule');
     $BookmarkedModule = new BookmarkedModule($this);
     $BookmarkedModule->GetData();
     $this->AddModule($BookmarkedModule);
     $this->FireEvent('BeforeDiscussionRender');
     $this->Render();
 }
    /**
     * Alternate version of Index that uses the embed master view.
     */
    public function Embed($DiscussionID = '', $DiscussionStub = '', $Offset = '', $Limit = '')
    {
        $this->CanEditComments = FALSE;
        // Don't show the comment checkboxes on the embed comments page
        $this->Theme = 'default';
        // Force the default theme on embedded comments
        // Add some css to help with the transparent bg on embedded comments
        if ($this->Head) {
            $this->Head->AddString('<style type="text/css">
body { background: transparent !important; }
ul.MessageList li.Item { background: #fff; }
ul.MessageList li.Item.Mine { background: #E3F4FF; }
</style>');
        }
        $Session = Gdn::Session();
        $this->AddJsFile('jquery.ui.packed.js');
        $this->AddJsFile('jquery.gardenmorepager.js');
        $this->AddJsFile('jquery.autogrow.js');
        $this->AddJsFile('options.js');
        $this->AddJsFile('discussion.js');
        $this->MasterView = 'empty';
        // Define incoming variables (prefer querystring parameters over method parameters)
        $DiscussionID = is_numeric($DiscussionID) && $DiscussionID > 0 ? $DiscussionID : 0;
        $DiscussionID = GetIncomingValue('vanilla_discussion_id', $DiscussionID);
        $Offset = GetIncomingValue('Offset', $Offset);
        $Limit = GetIncomingValue('Limit', $Limit);
        $ForeignID = GetIncomingValue('vanilla_identifier', '');
        $ForeignType = GetIncomingValue('vanilla_type', '');
        $ForeignName = GetIncomingValue('vanilla_name', '');
        $ForeignUrl = GetIncomingValue('vanilla_url', '');
        $this->SetData('ForeignUrl', $ForeignUrl);
        $this->AddDefinition('ForeignUrl', $ForeignUrl);
        $ForeignBody = GetIncomingValue('vanilla_body', '');
        $CategoryID = GetIncomingValue('vanilla_category_id', '');
        // Retrieve the discussion record.
        $Discussion = FALSE;
        if ($DiscussionID > 0) {
            $Discussion = $this->DiscussionModel->GetID($DiscussionID);
        } else {
            if ($ForeignID != '' && $ForeignType != '') {
                $Discussion = $this->DiscussionModel->GetForeignID($ForeignID, $ForeignType);
            }
        }
        // If no discussion record was found, but foreign id was provided, create it now
        if (!$Discussion && $ForeignID != '' && $ForeignType != '') {
            if ($ForeignName == '' || $ForeignBody == '') {
                $PageInfo = FetchPageInfo($ForeignUrl);
                if (!$PageInfo['Exception']) {
                    $ForeignName = $PageInfo['Title'];
                    $ForeignBody = Wrap(Anchor($ForeignName, $ForeignUrl), 'strong') . "\n" . '<br />' . Wrap(Anchor($ForeignUrl, $ForeignUrl), 'small') . "\n" . Wrap($PageInfo['Description'], 'p');
                    if (count($PageInfo['Images']) > 0) {
                        $ForeignBody = Anchor(Img($PageInfo['Images'][0], array('alt' => $ForeignName, 'class' => 'Thumbnail')), $ForeignUrl) . "\n" . $ForeignBody;
                    }
                }
            }
            $Body = $ForeignBody;
            if ($Body == '' && $ForeignUrl != '') {
                $Body = $ForeignUrl;
            }
            if ($Body == '') {
                $Body = T('This discussion is related to an undefined foriegn content source.');
            }
            // Validate the CategoryID for inserting
            if (!is_numeric($CategoryID)) {
                $CategoryID = C('Vanilla.Embed.DefaultCategoryID', 0);
                if ($CategoryID <= 0) {
                    // No default category defined, so grab the first non-root category and use that.
                    try {
                        $CategoryID = $this->DiscussionModel->SQL->Select('CategoryID')->From('Category')->Where('CategoryID >', 0)->Get()->FirstRow()->CategoryID;
                    } catch (Exception $ex) {
                        // No categories in the db? default to 0
                        $CategoryID = 0;
                    }
                }
            }
            $SystemUserID = Gdn::UserModel()->GetSystemUserID();
            $DiscussionID = $this->DiscussionModel->SQL->Insert('Discussion', array('InsertUserID' => $SystemUserID, 'DateInserted' => Gdn_Format::ToDateTime(), 'UpdateUserID' => $SystemUserID, 'DateUpdated' => Gdn_Format::ToDateTime(), 'CategoryID' => $CategoryID == '' ? NULL : $CategoryID, 'ForeignID' => $ForeignID, 'Type' => $ForeignType, 'Name' => $ForeignName == '' ? T('Undefined foreign content') : $ForeignName, 'Body' => $Body, 'Attributes' => serialize(array('ForeignUrl' => $ForeignUrl))));
            $ValidationResults = $this->DiscussionModel->ValidationResults();
            if (count($ValidationResults) == 0 && $DiscussionID > 0) {
                $Discussion = $this->DiscussionModel->GetID($DiscussionID);
                // Update the category discussion count
                if ($CategoryID > 0) {
                    $this->DiscussionModel->UpdateDiscussionCount($CategoryID, $DiscussionID);
                }
            }
        }
        // If no discussion was found, 404
        if (!$Discussion) {
            $this->Render('FileNotFound', 'HomeController', 'Dashboard');
            return;
        }
        $this->SetData('Discussion', $Discussion, TRUE);
        $this->SetData('DiscussionID', $Discussion->DiscussionID, TRUE);
        $this->Title($this->Discussion->Name);
        // Actual number of comments, excluding the discussion itself
        $ActualResponses = $this->Discussion->CountComments - 1;
        // Define the query offset & limit
        if (!is_numeric($Limit) || $Limit < 0) {
            $Limit = C('Vanilla.Comments.PerPage', 30);
        }
        $OffsetProvided = $Offset != '';
        list($Offset, $Limit) = OffsetLimit($Offset, $Limit);
        $this->Offset = $Offset;
        if (C('Vanilla.Comments.AutoOffset')) {
            if ($ActualResponses <= $Limit) {
                $this->Offset = 0;
            }
            if ($this->Offset == $ActualResponses) {
                $this->Offset -= $Limit;
            }
        } else {
            if ($this->Offset == '') {
                $this->Offset = 0;
            }
        }
        if ($this->Offset < 0) {
            $this->Offset = 0;
        }
        // Set the canonical url to have the proper page title.
        $this->CanonicalUrl(Url(ConcatSep('/', 'discussion/' . $this->Discussion->DiscussionID . '/' . Gdn_Format::Url($this->Discussion->Name), PageNumber($this->Offset, $Limit, TRUE)), TRUE));
        // Load the comments
        $this->CommentModel->OrderBy('c.DateInserted desc');
        // allow custom sort
        $this->SetData('CommentData', $this->CommentModel->Get($this->Discussion->DiscussionID, $Limit, $this->Offset), TRUE);
        // Build a pager
        $PagerFactory = new Gdn_PagerFactory();
        $this->EventArguments['PagerType'] = 'MorePager';
        $this->FireEvent('BeforeBuildPager');
        $this->Pager = $PagerFactory->GetPager($this->EventArguments['PagerType'], $this);
        $this->Pager->ClientID = 'Pager';
        $this->Pager->MoreCode = 'More Comments';
        $this->Pager->Configure($this->Offset, $Limit, $ActualResponses, 'discussion/embed/' . $this->Discussion->DiscussionID . '/' . Gdn_Format::Url($this->Discussion->Name) . '/%1$s');
        $this->FireEvent('AfterBuildPager');
        // Define the form for the comment input
        $this->Form = Gdn::Factory('Form', 'Comment');
        $this->Form->Action = Url('/vanilla/post/comment/');
        $this->Form->AddHidden('DiscussionID', $this->Discussion->DiscussionID);
        $this->Form->AddHidden('CommentID', '');
        $this->Form->AddHidden('DisplayNewCommentOnly', 'true');
        // Only load/display the new comment after posting (don't load all new comments since the page last loaded).
        // Retrieve & apply the draft if there is one:
        $Draft = FALSE;
        if (Gdn::Session()->UserID) {
            $DraftModel = new DraftModel();
            $Draft = $DraftModel->Get($Session->UserID, 0, 1, $this->Discussion->DiscussionID)->FirstRow();
            $this->Form->AddHidden('DraftID', $Draft ? $Draft->DraftID : '');
        }
        if ($Draft) {
            $this->Form->SetFormValue('Body', $Draft->Body);
        } else {
            // Look in the session stash for a comment
            $StashComment = $Session->Stash('CommentForDiscussionID_' . $this->Discussion->DiscussionID, '', FALSE);
            if ($StashComment) {
                $this->Form->SetFormValue('Body', $StashComment);
            }
        }
        // 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->View = 'comments';
        }
        $this->AddDefinition('PrependNewComments', '1');
        $this->AddDefinition('DiscussionID', $Discussion->DiscussionID);
        // Report the discussion id so js can use it.
        $this->FireEvent('BeforeDiscussionRender');
        $this->Render();
    }
   /**
    * Alternate version of Index that uses the embed master view.
    */
   public function Embed($DiscussionID = '', $DiscussionStub = '', $Offset = '', $Limit = '') {
      $Session = Gdn::Session();
      $this->AddJsFile('jquery.ui.packed.js');
      $this->AddJsFile('jquery.gardenmorepager.js');
      $this->AddJsFile('jquery.autogrow.js');
      $this->AddJsFile('options.js');
      $this->AddJsFile('discussion.js');
      $this->MasterView = 'empty';
      
      // Define incoming variables (prefer querystring parameters over method parameters)
      $DiscussionID = (is_numeric($DiscussionID) && $DiscussionID > 0) ? $DiscussionID : 0;
      $DiscussionID = GetIncomingValue('vanilla_discussion_id', $DiscussionID);
      $Offset = GetIncomingValue('Offset', $Offset);
      $Limit = GetIncomingValue('Limit', $Limit);
      $ForeignID = GetIncomingValue('vanilla_identifier', '');
      $ForeignType = GetIncomingValue('vanilla_type', '');
      $ForeignName = GetIncomingValue('vanilla_name', '');
      $ForeignUrl = GetIncomingValue('vanilla_url', '');
      $ForeignBody = GetIncomingValue('vanilla_body', '');
      $CategoryID = GetIncomingValue('vanilla_category_id', '');
      
      // Retrieve the discussion record.
      $Discussion = FALSE;
      if ($DiscussionID > 0)
         $Discussion = $this->DiscussionModel->GetID($DiscussionID);
      else if ($ForeignID != '' && $ForeignType != '')
         $Discussion = $this->DiscussionModel->GetForeignID($ForeignID, $ForeignType);
      
      // If no discussion record was found, but foreign id was provided, create it now
      if (!$Discussion && $ForeignID != '' && $ForeignType != '') {
         $Body = $ForeignBody;
         if ($Body == '' && $ForeignUrl != '')
            $Body = $ForeignUrl;
         if ($Body == '')
            $Body = T('This discussion is related to an undefined foriegn content source.');
            
         // Validate the CategoryID for inserting
         if (!is_numeric($CategoryID)) {
            $CategoryID = C('Vanilla.Embed.DefaultCategoryID', 0);
            if ($CategoryID <= 0) {
               // No default category defined, so grab the first non-root category and use that.
               try {
                  $CategoryID = $this->DiscussionModel
                     ->SQL
                     ->Select('CategoryID')
                     ->From('Category')
                     ->Where('CategoryID >', 0)
                     ->Get()
                     ->FirstRow()
                     ->CategoryID;
               } catch (Exception $ex) {
                  // No categories in the db? default to 0
                  $CategoryID = 0;
               }
            }
         }

         $DiscussionID = $this->DiscussionModel->Save(
            array(
               'CategoryID' => $CategoryID == '' ? NULL : $CategoryID,
               'ForeignID' => $ForeignID,
               'Type' => $ForeignType,
               'Name' => $ForeignName == '' ? T('Undefined foreign content') : $ForeignName,
               'Body' => $Body,
               'Attributes' => serialize(array('ForeignUrl' => $ForeignUrl))
            )
         );
         $ValidationResults = $this->DiscussionModel->ValidationResults();
         if (count($ValidationResults) == 0 && $DiscussionID > 0)
            $Discussion = $this->DiscussionModel->GetID($DiscussionID);
      }
      
      // If no discussion was found, 404
      if (!$Discussion) {
         $this->Render('FileNotFound', 'HomeController', 'Dashboard');
         return;
      } 
      $this->SetData('Discussion', $Discussion, TRUE);
      $this->SetData('DiscussionID', $Discussion->DiscussionID, TRUE);
      $this->Title($this->Discussion->Name);

      // Actual number of comments, excluding the discussion itself
      $ActualResponses = $this->Discussion->CountComments - 1;
      // Define the query offset & limit
      if (!is_numeric($Limit) || $Limit < 0)
         $Limit = C('Vanilla.Comments.PerPage', 50);

      $OffsetProvided = $Offset != '';
      list($Offset, $Limit) = OffsetLimit($Offset, $Limit);
      $this->Offset = $Offset;
      if (C('Vanilla.Comments.AutoOffset')) {
         if ($ActualResponses <= $Limit)
            $this->Offset = 0;

         if ($this->Offset == $ActualResponses)
            $this->Offset -= $Limit;
      } else if ($this->Offset == '')
         $this->Offset = 0;

      if ($this->Offset < 0)
         $this->Offset = 0;

      // Set the canonical url to have the proper page title.
      $this->CanonicalUrl(Url(ConcatSep('/', 'discussion/'.$this->Discussion->DiscussionID.'/'. Gdn_Format::Url($this->Discussion->Name), PageNumber($this->Offset, $Limit, TRUE)), TRUE));

      // Load the comments
      $this->CommentModel->OrderBy('c.DateInserted desc'); // allow custom sort
      $this->SetData('CommentData', $this->CommentModel->Get($this->Discussion->DiscussionID, $Limit, $this->Offset), TRUE);
      
      // Build a pager
      $PagerFactory = new Gdn_PagerFactory();
		$this->EventArguments['PagerType'] = 'MorePager';
		$this->FireEvent('BeforeBuildPager');
      $this->Pager = $PagerFactory->GetPager($this->EventArguments['PagerType'], $this);
      $this->Pager->ClientID = 'Pager';
      $this->Pager->MoreCode = 'More Comments';
      $this->Pager->Configure(
         $this->Offset,
         $Limit,
         $ActualResponses,
         'discussion/embed/'.$this->Discussion->DiscussionID.'/'.Gdn_Format::Url($this->Discussion->Name).'/%1$s'
      );
      $this->FireEvent('AfterBuildPager');
      
      // Define the form for the comment input
      $this->Form = Gdn::Factory('Form', 'Comment');
      $this->Form->Action = Url('/vanilla/post/comment/');
      $this->Form->AddHidden('DiscussionID', $this->Discussion->DiscussionID);
      $this->Form->AddHidden('CommentID', '');
      $this->Form->AddHidden('DisplayNewCommentOnly', 'true'); // Only load/display the new comment after posting (don't load all new comments since the page last loaded).

      // Retrieve & apply the draft if there is one:
      $DraftModel = new DraftModel();
      $Draft = $DraftModel->Get($Session->UserID, 0, 1, $this->Discussion->DiscussionID)->FirstRow();
      $this->Form->AddHidden('DraftID', $Draft ? $Draft->DraftID : '');
      if ($Draft)
         $this->Form->SetFormValue('Body', $Draft->Body);
      else {
         // Look in the session stash for a comment
         $StashComment = $Session->Stash('CommentForDiscussionID_'.$this->Discussion->DiscussionID, '', FALSE);
         if ($StashComment)
            $this->Form->SetFormValue('Body', $StashComment);
      }
      
      // 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->View = 'comments';
      }
      
      $this->AddDefinition('PrependNewComments', '1');
      $this->AddDefinition('DiscussionID', $Discussion->DiscussionID);
      
      // Report the discussion id so js can use it.      
      $this->FireEvent('BeforeDiscussionRender');
      $this->Render();
   }