<?php
/**
 * Plugin Name: Multisite URL Fixer
 * Description: Fix WordPress multisite issues with home & site URLs
 * Version: 1.0.0
 * Author: Krikstudio
 * Author URI: http://krikstudio.com
 * License: MIT
 * License URI: http://opensource.org/licenses/MIT
 * Based on Roots
 */

namespace Krik\WP;

if (!is_multisite()) {
	return;
}

/**
 * Class MsUrlFixer
 */
class MsUrlFixer
{
	/** @var Singleton instance */
	private static $instance = null;

	/**
	 * Singleton.
	 */
	public static function instance()
	{
		if (null === self::$instance) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	/**
	 * Add filters to verify / fix URLs.
	 */
	public function addFilters()
	{
		add_filter('option_home', array($this, 'fixHomeUrl'));
		add_filter('option_siteurl', array($this, 'fixSiteUrl'));
		add_filter('network_site_url', array($this, 'fixNetworkSiteUrl'), 10, 3);
	}

	/**
	 * Ensure that home URL does not contain the /wp subdirectory.
	 */
	public function fixHomeUrl($value)
	{
		if ('/wp' === substr($value, -3)) {
			$value = substr($value, 0, -3);
		}
		return $value;
	}

	/**
	 * Ensure that site URL contains the /wp subdirectory.
	 */
	public function fixSiteUrl($value)
	{
		if ('/wp' !== substr($value, -3)) {
			$value .= '/wp';
		}
		return $value;
	}

	/**
	 * Ensure that the network site URL contains the /wp subdirectory.
	 */
	public function fixNetworkSiteUrl($url, $path, $scheme)
	{
		$path = ltrim($path, '/');
		$url = substr($url, 0, strlen($url) - strlen($path));

		if ('wp/' !== substr($url, -3)) {
			$url .= 'wp/';
		}

		return $url . $path;
	}
}

MsUrlFixer::instance()->addFilters();
