<?php
/**
 * Response handler for Ajax requests.
 *
 * This program 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 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @ingroup Ajax
 */
use MediaWiki\MediaWikiServices;

/**
 * Handle responses for Ajax requests (send headers, print
 * content, that sort of thing)
 *
 * @ingroup Ajax
 */
class AjaxResponse {
	/**
	 * Number of seconds to get the response cached by a proxy
	 * @var int
	 */
	private $mCacheDuration;

	/**
	 * HTTP header Content-Type
	 * @var string
	 */
	private $mContentType;

	/**
	 * Disables output. Can be set by calling $AjaxResponse->disable()
	 * @var bool
	 */
	private $mDisabled;

	/**
	 * Date for the HTTP header Last-modified
	 * @var string|bool
	 */
	private $mLastModified;

	/**
	 * HTTP response code
	 * @var int|string
	 */
	private $mResponseCode;

	/**
	 * HTTP Vary header
	 * @var string
	 */
	private $mVary;

	/**
	 * Content of our HTTP response
	 * @var string
	 */
	private $mText;

	/**
	 * @var Config
	 */
	private $mConfig;

	/**
	 * @param string|null $text
	 * @param Config|null $config
	 */
	public function __construct( $text = null, Config $config = null ) {
		$this->mCacheDuration = null;
		$this->mVary = null;
		$this->mConfig = $config ?: MediaWikiServices::getInstance()->getMainConfig();

		$this->mDisabled = false;
		$this->mText = '';
		$this->mResponseCode = 200;
		$this->mLastModified = false;
		$this->mContentType = 'application/x-wiki';

		if ( $text ) {
			$this->addText( $text );
		}
	}

	/**
	 * Set the HTTP response code
	 * @param int|string $code
	 */
	public function setResponseCode( $code ) {
		$this->mResponseCode = $code;
	}

	/**
	 * Set the HTTP header Content-Type
	 * @param string $type
	 */
	public function setContentType( $type ) {
		$this->mContentType = $type;
	}

	/**
	 * Disable output.
	 */
	public function disable() {
		$this->mDisabled = true;
	}

	/**
	 * Add content to the response
	 * @param string $text
	 */
	public function addText( $text ) {
		if ( !$this->mDisabled && $text ) {
			$this->mText .= $text;
		}
	}

	/**
	 * Output text
	 */
	public function printText() {
		if ( !$this->mDisabled ) {
			print $this->mText;
		}
	}

	/**
	 * Construct the header and output it
	 */
	public function sendHeaders() {
		if ( $this->mResponseCode ) {
			// For back-compat, it is supported that mResponseCode be a string like " 200 OK"
			// (with leading space and the status message after). Cast response code to an integer
			// to take advantage of PHP's conversion rules which will turn "  200 OK" into 200.
			// https://www.php.net/manual/en/language.types.string.php#language.types.string.conversion
			$n = intval( trim( $this->mResponseCode ) );
			HttpStatus::header( $n );
		}

		header( "Content-Type: " . $this->mContentType );

		if ( $this->mLastModified ) {
			header( "Last-Modified: " . $this->mLastModified );
		} else {
			header( "Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . " GMT" );
		}

		if ( $this->mCacheDuration ) {
			# If CDN caches are configured, tell them to cache the response,
			# and tell the client to always check with the CDN. Otherwise,
			# tell the client to use a cached copy, without a way to purge it.
			if ( $this->mConfig->get( 'UseCdn' ) ) {
				# Expect explicit purge of the proxy cache, but require end user agents
				# to revalidate against the proxy on each visit.
				header( 'Cache-Control: s-maxage=' . $this->mCacheDuration . ', must-revalidate, max-age=0' );
			} else {
				# Let the client do the caching. Cache is not purged.
				header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + $this->mCacheDuration ) . " GMT" );
				header( "Cache-Control: s-maxage={$this->mCacheDuration}," .
					"public,max-age={$this->mCacheDuration}" );
			}

		} else {
			# always expired, always modified
			header( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );    // Date in the past
			header( "Cache-Control: no-cache, must-revalidate" );  // HTTP/1.1
			header( "Pragma: no-cache" );                          // HTTP/1.0
		}

		if ( $this->mVary ) {
			header( "Vary: " . $this->mVary );
		}
	}
}
