<?php

/**
 * main file server class
 */
class fileServer
{
	static function getAvailableServerId()
	{
        // connect db
		$db = Database::getDatabase(true);
        
        // if user logged in, check for server override
        $Auth = Auth::getAuth();
        if($Auth->loggedIn() == true)
        {
            // user is logged in, check for server override
            if((int)$Auth->user->uploadServerOverride)
            {
                // double check via the database
                $uploadServerOverride = (int)$db->getValue('SELECT uploadServerOverride FROM users WHERE id = '.(int)$Auth->id.' LIMIT 1');
                if($uploadServerOverride)
                {
                    return $uploadServerOverride;
                }
            }
        }

		// check plugins for server to use
		$params = pluginHelper::includeAppends('functions_get_available_server_id.php', array('serverId' => null));
		if ((int) $params['serverId'])
		{
			return $params['serverId'];
		}

		// choose server
		switch (SITE_CONFIG_C_FILE_SERVER_SELECTION_METHOD)
		{
			case 'Least Used Space':
				$sQL = "SELECT file_server.id ";
				$sQL .= "FROM file_server ";
				$sQL .= "WHERE statusId = 2 ";
				$sQL .= "ORDER BY totalSpaceUsed ASC";

				$serverDetails = $db->getRow($sQL);
				if (is_array($serverDetails))
				{
					return $serverDetails['id'];
				}

				// none found so return the default local
				return 1;

				break;
			case 'Until Full':
				$sQL = "SELECT file_server.id ";
				$sQL .= "FROM file_server ";
				$sQL .= "WHERE IF(maximumStorageBytes > 0, totalSpaceUsed <= maximumStorageBytes, 1=1) AND statusId = 2 ";
				$sQL .= "ORDER BY priority ASC, id ASC";

				$serverDetails = $db->getRow($sQL);
				if (is_array($serverDetails))
				{
					return $serverDetails['id'];
				}

				// none found so return the default local
				return 1;

				break;
			default:
				$sQL           = "SELECT id FROM file_server WHERE serverLabel = " . $db->quote(SITE_CONFIG_DEFAULT_FILE_SERVER) . " AND statusId = 2 LIMIT 1";
				$serverDetails = $db->getRow($sQL);
				if (is_array($serverDetails))
				{
					return $serverDetails['id'];
				}

				// none found so return the default local
				return 1;

				break;
		}

		// fall back
		return 1;
	}
    
    static function nginxXAccelRedirectEnabled()
    {
        // apache, look for config value
        if (SITE_CONFIG_DOWNLOAD_USE_NGINX_XACCELREDIRECT == 'yes')
        {
            return true;
        }
        
        return false;
    }
    
    static function apacheXSendFileEnabled()
    {
        // apache, look for config value
        if (SITE_CONFIG_DOWNLOAD_USE_APACHE_XSENDFILE == 'yes')
        {
            return true;
        }
        
        return false;
    }
}
