Helper function to actually override a discussion's unread status

@since 2.0
@access private
514108
private function CheckDiscussionDate($Discussion, $DateAllViewed) {
		if (Gdn_Format::ToTimestamp($Discussion->DateInserted) > $DateAllViewed) {
			// Discussion is newer than DateAllViewed
			return;
		}
		
		if (Gdn_Format::ToTimestamp($Discussion->DateLastComment) <= $DateAllViewed) {
			// Covered by AllViewed
			$Discussion->CountUnreadComments = 0; 
		} elseif (Gdn_Format::ToTimestamp($Discussion->DateLastViewed) == $DateAllViewed || !$Discussion->DateLastViewed) {
			// User clicked AllViewed. Discussion is older than click. Last comment is newer than click.
			// No UserDiscussion record found OR UserDiscussion was set by AllViewed
			$Discussion->CountUnreadComments = $this->GetCommentCountSince($Discussion->DiscussionID, $DateAllViewed);
		}
	}
200818
async function ensureCommentRemoval(prNo, topic) {
  try {
    logger.debug(`Ensuring comment "${topic}" in #${prNo} is removed`);
    const comments = await getComments(prNo);
    let commentId;
    comments.forEach(comment => {
      if (comment.text.startsWith(`### ${topic}\n\n`)) {
        commentId = comment.id;
      }
    });
    if (commentId) {
      await deleteComment(prNo, commentId);
    }
  } catch (err) /* istanbul ignore next */ {
    logger.warn({ err }, 'Error ensuring comment removal');
  }
}
340988
protected function resetOriginalReadPreference(){

        /** @var ReadPreference $dbReadPref */
        $dbReadPref = $this->db->__debugInfo()['readPreference'];
        if($this->originalDbReadPreference !== $dbReadPref->getMode())
        {
            $pref = (isset($this->originalDbReadPreference)
                ? $this->originalDbReadPreference
                : $this->readPreference
            );
            $dbTagsets = $dbReadPref->getTagsets();

            $this->db = $this->db->withOptions(array(
                'readPreference' => new ReadPreference($pref, $dbTagsets)
            ));
        }

        // Reset collection object
        /** @var ReadPreference $collReadPref */
        $collReadPref = $this->getCollection()->__debugInfo()['readPreference'];
        if($this->originalCollectionReadPreference !== $collReadPref->getMode()){
            $pref = (isset($this->originalCollectionReadPreference)
                ? $this->originalCollectionReadPreference
                : $this->readPreference
            );
            $collTagsets = $collReadPref->getTagsets();
            $this->collection = $this->collection->withOptions(array(
                'readPreference' => new ReadPreference($pref, $collTagsets)
            ));
        }
    }
727332
protected function controlAccessEditReview()
    {
        if (!$this->config('review_enabled', 1) || empty($this->uid)) {
            $this->outputHttpStatus(403);
        }

        if (!$this->config('review_editable', 1)) {
            $this->outputHttpStatus(403);
        }

        if (isset($this->data_review['review_id']) && $this->data_review['user_id'] != $this->uid) {
            $this->outputHttpStatus(403);
        }
    }
222736
static function set_admin_readonly_js( $page_name ) {
        switch ($page_name) {

            // Enable readonly js fixer for all admin options pages
            case 'options-general.php'
            || 'options-writing.php'
            || 'options-reading.php'
            || 'options-discussion.php'
            || 'options-media.php'
            || 'options-permalink.php'
            || 'options.php':

            $hover_text = self::$hover_text;
            $input_element_ids = array_keys( self::$options );

            // Add javascript which turns $elements into readonly
            add_action( 'admin_footer', function() use ( $input_element_ids, $hover_text ) {
                // Show information about this plugin in element mouseover title for easier debugging
                self::print_admin_readonly_js_script( $input_element_ids, $hover_text );
            });

            // On other pages do nothing
            default:
            return;
        }
    }
1281300
public function RefetchPageInfo($DiscussionID) {
      // Make sure we are posting back.
      if (!$this->Request->IsPostBack())
         throw PermissionException('Javascript');
      
      // Grab the discussion.
      $Discussion = $this->DiscussionModel->GetID($DiscussionID);
      
      if (!$Discussion)
         throw NotFoundException('Discussion');
      
      // Make sure the user has permission to edit this discussion.
      $this->Permission('Vanilla.Discussions.Edit', TRUE, 'Category', $Discussion->PermissionCategoryID);
      
      $ForeignUrl = GetValueR('Attributes.ForeignUrl', $Discussion);
      if (!$ForeignUrl) {
         throw new Gdn_UserException(T("This discussion isn't associated with a url."));
      }
      
      $Stub = $this->DiscussionModel->FetchPageInfo($ForeignUrl, TRUE);
//      decho($Stub);
//      die();
      
      // Save the stub.
      $this->DiscussionModel->SetField($DiscussionID, (array)$Stub);
      
      // Send some of the stuff back.
      if (isset($Stub['Name']))
         $this->JsonTarget('.PageTitle h1', Gdn_Format::Text($Stub['Name']));
      if (isset($Stub['Body']))
         $this->JsonTarget("#Discussion_$DiscussionID .Message", Gdn_Format::To($Stub['Body'], $Stub['Format']));
      
      $this->InformMessage('The page was successfully fetched.');
      
      $this->Render('Blank', 'Utility', 'Dashboard');
   }
1046817
function reset_poll()
	{
		global $db;

		$db->sql_transaction('begin');
		$sql = 'UPDATE ' . POLL_OPTIONS_TABLE . '
			SET poll_option_total = 0
			WHERE topic_id = ' . $this->topic_id;
		$db->sql_query($sql);

		$sql = 'DELETE FROM ' . POLL_VOTES_TABLE . '
			WHERE topic_id = ' . $this->topic_id;
		$db->sql_query($sql);

		$this->poll_start = time();
		$this->poll_last_vote = 0;
		$sql = 'UPDATE ' . TOPICS_TABLE . '
			SET poll_start = ' . $this->poll_start . ',
				poll_last_vote = 0
			WHERE topic_id = ' . $this->topic_id;
		$db->sql_query($sql);

		$db->sql_transaction('commit');
	}
409830
public function onBeforeWrite() {
        parent::onBeforeWrite();
        
        if(empty($this->owner->DefaultPreviewMode)) {
            $this->owner->DefaultPreviewMode=Config::inst()->get('UserPreviewPreference', 'DefaultMode');
        }
        
        
        //If changed ensure their is a session message
        if($this->owner->isChanged('DefaultPreviewMode')) {
            Controller::curr()->getRequest()->getSession()->set('ShowPreviewSettingChangeReload', true);
            $this->isSaving=true;
        }
    }
706694
public function onBeforeWrite()
    {
        parent::onBeforeWrite();
        /** Check if we have translatable and a NewsHolderPage. If no HolderPage available, skip (Create an orphan) */
        if (!$this->NewsHolderPages()->count()) {
            if (!class_exists('Translatable') && $page = NewsHolderPage::get()->first()) {
                $this->NewsHolderPages()->add($page);
            } elseif (class_exists('Translatable')) {
                Translatable::disable_locale_filter();
                $page = NewsHolderPage::get()->first();
                $this->NewsHolderPages()->add($page);
                Translatable::enable_locale_filter();
            }
        }
        if (!$this->Type || $this->Type === '') {
            $this->Type = 'news';
        }
        /** Set PublishFrom to today to prevent errors with sorting. New since 2.0, backward compatible. */
        if (!$this->PublishFrom) {
            $this->PublishFrom = SS_Datetime::now()->Rfc2822();
        }
        /**
         * Make sure the link is valid.
         */
        if (substr($this->External, 0, 4) !== 'http' && $this->External != '') {
            $this->External = 'http://' . $this->External;
        }
        $this->setURLValue();
        $this->setAuthorData();
    }
1343500
public function get_single_discussion_posts_renderer(int $displaymode = null, bool $readonly = false) : posts_renderer {
        $exportedpostssorter = $this->entityfactory->get_exported_posts_sorter();

        switch ($displaymode) {
            case FORUM_MODE_THREADED:
                $template = 'mod_forum/forum_discussion_threaded_posts';
                break;
            case FORUM_MODE_NESTED:
                $template = 'mod_forum/forum_discussion_nested_posts';
                break;
            default;
                $template = 'mod_forum/forum_discussion_posts';
                break;
        }

        return new posts_renderer(
            $this->rendererbase,
            $this->builderfactory->get_exported_posts_builder(),
            $template,
            // Post process the exported posts for our template. This function will add the "replies"
            // and "hasreplies" properties to the exported posts. It will also sort them into the
            // reply tree structure if the display mode requires it.
            function($exportedposts, $forums) use ($displaymode, $readonly, $exportedpostssorter) {
                $forum = array_shift($forums);
                $seenfirstunread = false;
                $postcount = count($exportedposts);
                $exportedposts = array_map(
                    function($exportedpost) use ($forum, $readonly, $seenfirstunread) {
                        if ($forum->get_type() == 'single' && !$exportedpost->hasparent) {
                            // Remove the author from any posts that don't have a parent.
                            unset($exportedpost->author);
                            unset($exportedpost->html['authorsubheading']);
                        }

                        $exportedpost->firstpost = false;
                        $exportedpost->readonly = $readonly;
                        $exportedpost->hasreplycount = false;
                        $exportedpost->hasreplies = false;
                        $exportedpost->replies = [];

                        $exportedpost->isfirstunread = false;
                        if (!$seenfirstunread && $exportedpost->unread) {
                            $exportedpost->isfirstunread = true;
                            $seenfirstunread = true;
                        }

                        return $exportedpost;
                    },
                    $exportedposts
                );

                if ($displaymode === FORUM_MODE_NESTED || $displaymode === FORUM_MODE_THREADED) {
                    $sortedposts = $exportedpostssorter->sort_into_children($exportedposts);
                    $sortintoreplies = function($nestedposts) use (&$sortintoreplies) {
                        return array_map(function($postdata) use (&$sortintoreplies) {
                            [$post, $replies] = $postdata;
                            $sortedreplies = $sortintoreplies($replies);
                            // Set the parent author name on the replies. This is used for screen
                            // readers to help them identify the structure of the discussion.
                            $sortedreplies = array_map(function($reply) use ($post) {
                                if (isset($post->author)) {
                                    $reply->parentauthorname = $post->author->fullname;
                                } else {
                                    // The only time the author won't be set is for a single discussion
                                    // forum. See above for where it gets unset.
                                    $reply->parentauthorname = get_string('firstpost', 'mod_forum');
                                }
                                return $reply;
                            }, $sortedreplies);
                            $post->replies = $sortedreplies;
                            $post->hasreplies = !empty($post->replies);
                            return $post;
                        }, $nestedposts);
                    };
                    // Set the "replies" property on the exported posts.
                    $exportedposts = $sortintoreplies($sortedposts);
                } else if ($displaymode === FORUM_MODE_FLATNEWEST || $displaymode === FORUM_MODE_FLATOLDEST) {
                    $exportedfirstpost = array_shift($exportedposts);
                    $exportedfirstpost->replies = $exportedposts;
                    $exportedfirstpost->hasreplies = true;
                    $exportedposts = [$exportedfirstpost];
                }

                if (!empty($exportedposts)) {
                    // Need to identify the first post so that we can use it in behat tests.
                    $exportedposts[0]->firstpost = true;
                    $exportedposts[0]->hasreplycount = true;
                    $exportedposts[0]->replycount = $postcount - 1;
                }

                return $exportedposts;
            }
        );
    }
53088
def edit
      @post = Post.includes(:user, :discussion).find(params[:id])
      raise Cornerstone::AccessDenied unless @post.created_by?(current_cornerstone_user)
      @discussion = @post.discussion
      respond_with(@discussion, @post)
    end
848657
def discussion_is_still_open(self, discussion_type, auto_close_after):
        
        discussion_enabled = getattr(self, discussion_type)
        if (discussion_enabled and isinstance(auto_close_after, int) and
                auto_close_after >= 0):
            return (timezone.now() - (
                self.start_publication or self.publication_date)).days < \
                auto_close_after
        return discussion_enabled
132993
@Override
    protected void readOnlyChanged()
    {
        for (AbstractCommand abstractCommand : getCommands())
        {
            if (isShowDetailSupported() && abstractCommand == getDetailCommand())
                (abstractCommand).setEnabled(isEnabled());
            else
                (abstractCommand).setEnabled(isEnabled() && !isReadOnly());

        }
    }
1022023
public function setUnread($id, $status)
    {
        return $this->put($this->getPath().'/'.rawurlencode($id).'/unread', array('value' => $status));
    }
1331158
public static function restoreOriginalReadingMode()
    {
        if (
            isset(self::$originalReadingMode) &&
            in_array(self::$originalReadingMode, array('Stage', 'Live'))
        ) {
            Versioned::reading_stage(self::$originalReadingMode);
        }
    }
559900
public function get_discussion_view_first_unread_post_url_from_discussion(discussion_entity $discussion) {
        $viewurl = $this->get_discussion_view_url_from_discussion_id($discussion->get_id());
        $viewurl->set_anchor('unread');

        return $viewurl;
    }
1167237
public function is_timed_discussion() : bool {
        global $CFG;

        return !empty($CFG->forum_enabletimedposts) &&
              ($this->get_time_start() || $this->get_time_end());
    }