<?php
/**
 * Titan CMS Initialization File
 *
 * This file must be placed within the site root of the website that is
 * using the titan cms to display content.
 *
 * @package TitanCMS
 * @author    $LastChangedBy: paul $
 * @copyright Copyright (c) 2009 Titan Interactive (http://www.titaninteractive.com.au/)
 * @version   $Rev: 1996 $
 *            $URL: svn+ssh://remoteuser@sparticus/svn/titan-cms/tags/2.4/titan-cms.php $
 *            $LastChangedDate: 2010-08-24 14:47:03 +0800 (Tue, 24 Aug 2010) $
 */

/**
 * Site-Specific Configuration File
 *
 * The site specific configuration file is included only if it is present within the site.  This file is used for configuring core settings on a site-specific basis, and should seldom be used.
 *
 */
!file_exists( '../config/local.configuration.php' )
	or require_once '../config/local.configuration.php';

/// DIRECTORY DETECTION --------------------------------------------------------
/// Determine the path to the current site
if ( ! defined( 'WEBSITE_PATH' ) ) define( 'WEBSITE_PATH', dirname( getcwd() ) );

/**
 * Absolute Path to the Titan CMS
 *
 * This path is automatically detected within the initialization file.
 *
 * @var string
 */
if ( ! defined( 'TITANCMS_PATH' ) ) define( 'TITANCMS_PATH', dirname( __FILE__ ) );

/// SERVER CONFIGURATION -------------------------------------------------------

/// Load the server configuration settings from the local server configuration
/// files.
if( is_file( TITANCMS_PATH . '/config/local.configuration.php' ) ) require_once TITANCMS_PATH . '/config/local.configuration.php';

/// URL DETECTION --------------------------------------------------------------

/**
 * Base URL
 *
 * Used when detecting urls and generating urls that will work in all
 * environments.
 *
 * Although this path will work in most environments, it will need to be set in
 * some.  If there are problems with links site-wide, try defining this variable
 * within the local configuration file.
 *
 * @var string
 */
if ( ! defined( 'BASE_URL' ) )
{
	/// If the website name (from the path) is within the server name, assume
	/// that this server is on the base directory of the domain
	if( stripos( $_SERVER['SERVER_NAME'], basename( WEBSITE_PATH ) ) !== false ) define( 'BASE_URL', '/' );
	
	/// Otherwise, find the httpdocs directory within the website path and use
	/// that to anchor the base name
	elseif ( ( $pos = stripos( $_SERVER['REQUEST_URI'], '/httpdocs/' ) ) !== false )
	{
		/** @ignore this definition for documentation purposes */
		define( 'BASE_URL', substr( $_SERVER['REQUEST_URI'], 0, $pos ).'/httpdocs/' );
		unset( $pos );
	}
	else define( 'BASE_URL', '/' );
}

/**
 * Relative URL
 *
 * The URL that is relative to the base url for the current request.  Used to
 * detemine the request without needing to reference the base url.
 *
 * @var string
 */
if ( ! defined( 'RELATIVE_URL' ) )
	define( 'RELATIVE_URL', str_replace( BASE_URL, '', $_SERVER['REQUEST_URI'] ) );

/**
 * Server URL
 *
 * The absolute URL of the server that this site is hosted on
 *
 * @var string
 */
if ( ! defined( 'SERVER_URL' ) )
	define( 'SERVER_URL', "http://{$_SERVER['SERVER_NAME']}" );

/**
 * Absolute URL
 *
 * The absolute URL of the site is determined by both the site server and the
 * base url.
 *
 * @var string
 */
if ( ! defined( 'ABSOLUTE_URL' ) )
	define( 'ABSOLUTE_URL', SERVER_URL . BASE_URL );


/// SITE DETECTION -------------------------------------------------------------
if ( ! isset($_SERVER['REQUEST_URI']) )
{
	$sarr = explode("/",getcwd());
	$site = array_pop($sarr);
	if ( $site == "httpdocs" )
		$site = array_pop($sarr);

	define('SITENAME',$site);
}

/// Only automatically detect the site name if it has not already been defined.
if ( ! defined( 'SITENAME' ) )
{
	/// If the site is not within a subdirectory of the domain, determine the site
	/// name from the domain name
	if ( BASE_URL == '/' )
	{
		/// Determine the site name from the url specified
		$site = $_SERVER['SERVER_NAME'];
	

		/// Devour any prefixes that should be automatically removed
		foreach( array( 'www.' ) as $prefix )
		{
			/// With each prefix, if it is present within the base site name,
			/// remove it.
			if( substr( $site, 0, strlen( $prefix ) ) == $prefix ) $site = substr( $site, strlen( $prefix ) );
		}

		/// Devour any suffixes that should be automatially removed
		foreach( array( '.zeus.titaninteractive.com.au'
		              , '.atlas.titaninteractive.com.au'
		              , '.bizwa.com.au'
		              , '.titandemo.com'
		              , '.au'
		              , '.com'
		              , '.net'
		              , '.localhost' ) as $suffix )
		{
			/// With each suffix, if it is present within the base site name,
			/// remove it.
			if( substr( $site, -(strlen( $suffix )) ) == $suffix ) $site = substr( $site, 0, -( strlen( $suffix ) ) );
		}
	}

	/// The best method of site detection lies within the current working directory
	/// so by default this will be used to determine the site name
	else
	{
		/// Determine the directory of the current working directory
		$site = basename( WEBSITE_PATH );

		/// Strip anything after the domain seperator (.) out of the site directory
		if( ( $pos = strpos( '.', $site ) ) !== false ) $site = substr( $site, 0, $pos );

		/// Cleanup the variables within this scope
		unset( $pos );
	}

	/**
	 * Site name of the site that is using the titan cms
	 *
	 * @var string
	 */
	define( "SITENAME", $site );

	/// Cleanup the variables
	unset( $site );
}

/// ENVIRONMENT DETECTION ------------------------------------------------------

/**
 * LIVE Environment Flag
 *
 * The flag that is used to identify the LIVE environment
 *
 * @var int
 */
define( 'LIVE', 0x1 );

/**
 * UAT Environment Flag
 *
 * The flag that is used to identify the UAT environment.
 *
 * @var int
 */
define( 'UAT', 0x2 );

/**
 * TEST Environment Flag
 *
 * The flag that is used to identify the TEST environment.
 *
 * @var int
 */
define( 'TEST', 0x4 );

/**
 * DEV Environment Flag
 *
 * The flag that is used to identify the DEV environment.
 *
 * @var int
 */
define( 'DEV', 0x8 );

/**
 * FirePHP Logging Flag
 *
 * The presence of this flag within the environment variable indicates that
 * FirePHP logging will be used.
 *
 * NOTE: FirePHP sends headers out when messages are logged, and therefore will
 *       intefere with any redirect methods.
 *
 * @var int
 */
define( 'LOG_FIREPHP', 0x010 );

/**
 * Email Logging Flag
 *
 * The presence of this flag within the environment variable indicates that
 * email logging will be used.
 *
 * @var int
 */
define( 'LOG_EMAIL', 0x020 );

/**
 * File Logging Flag
 *
 * The presence of this flag within the environment variable indicates that
 * file based logging will be used.
 *
 * @var int
 */
define( 'LOG_FILE', 0x040 );

/**
 * Command Line Flag
 *
 * Indicates that the current enviroment has been initialized by a script.
 *
 * @var int
 */
define( 'COMMAND_LINE', 0x0100 );

/**
 * Script Flag
 *
 * Detects whether the current environment has been initialized by a script.
 * The script that is running could either be from a web environment (i.e. a
 * custom script, or a command line script)
 *
 * @var int
 */
define( 'SCRIPT', 0x0200 );

/// Prepare a variable for use when defining the current environment
$environment = 0x0;

/// Determine if the current environment could be the DEV or TEST environment.
/// This is characterized by the presence of a base url that contains the
/// httpdocs folder
if ( strpos( $_SERVER['REQUEST_URI'], 'httpdocs' ) !== false
  || $_SERVER['SERVER_NAME'] == 'localhost' )
{
	/// If the base url contains 'test' within the url path, the current site must
	/// be in test mode
	if( substr( BASE_URL, 0, 6) == '/test/' ) $environment|= TEST;

	/// Otherwise, assume that the site is in dev mode
	else $environment|= DEV;
}

/// Otherwise, the site is either part of a uat or live domain
else
{
	/// Indicate that email logging should be used in this environment
	$environment|= LOG_EMAIL;

	/// If the suffix of the current server is one of the uat environments, this
	/// is the live environment
	foreach( array( '.titandemo.com'
	              , '.zeus.titaninteractive.com.au'
	              , '.atlas.titaninteractive.com.au' ) as $uat_server )
	{
		/// If the server name contains a uat server, this is the uat
		/// environment
		if( stristr( $_SERVER['SERVER_NAME'], $uat_server ) )
		{
			$environment|= UAT;

			// while we're here, lets define the UAT environment as non crawlable
			define('ROBOTS_TXT',"User-agent: *\r\nDisallow: *\r\n");
			break;
		}
	}
	/// If the environment does not currently have a staging environment defined
	/// assume that the site is in the live environment
	if( !( (DEV|TEST|UAT) & $environment ) ) $environment|= LIVE;
}

if( DEV|TEST|UAT & $environment ) $environment|= LOG_FIREPHP;

/// Determine if the Titan CMS has been initialized from the command line
if ( ! empty( $argv )
  || ! $_SERVER['SERVER_NAME'] ) $environment|= COMMAND_LINE;
  
/// Determine if the Titan CMS as been initialized from a script
if ( basename( $_SERVER['SCRIPT_NAME'] ) != basename( __FILE__ ) ) $environment|= SCRIPT;

/// If the server environment has settings enabled, specify them as being enabled
/// in the current environment
if( defined( 'SERVER_ENVIRONMENT_ENABLE' ) ) $environment|= SERVER_ENVIRONMENT_ENABLE;

/// If the server environment has settings disabled, specify them as being
/// disabled in the current environment
if( defined( 'SERVER_ENVIRONMENT_DISABLE' ) ) $environment&= ~SERVER_ENVIRONMENT_DISABLE;

/// If the site environment has settings enabled, specify them as being enabled
/// in the current environment
if( defined( 'SITE_ENVIRONMENT_ENABLE' ) ) $environment|= SITE_ENVIRONMENT_ENABLE;

/// If the site environment has settings disabled, specify them as being
/// disabled in the current environment
if( defined( 'SITE_ENVIRONMENT_DISABLE' ) ) $environment&= ~SITE_ENVIRONMENT_DISABLE;

/**
 * Environment
 *
 * Contains a set of flags that define the current environment.
 *
 * This constant is defined automatically, so it cannot be modified in the
 * server or site configuration files.
 *
 * To modify environment flags within the site or server configuration file use
 * the *_ENVIRONMENT_ENABLE and *_ENVIRONMENT_DISABLE
 *
 * @see SERVER_ENVIRONMENT_ENABLE
 * @see SERVER_ENVIRONMENT_DISABLE
 * @see SITE_ENVIRONMENT_ENABLE
 * @see SITE_ENVIRONMENT_DISABLE
 * @var int
 */
define( 'ENVIRONMENT', $environment );

/// Cleanup the environment variable
unset( $environment );

/// DATABASE CONFIGURATION -----------------------------------------------------

/**
 * MySQL Server Configuration
 *
 * The mysql server in which the mysql database resides.
 *
 * @var string
 */
if ( ! defined( 'DATABASE_SERVER' ) ) define( 'DATABASE_SERVER', 'localhost' );

/**
 * Database User
 *
 * The user that will be used for all queries to the database.
 *
 * @var string
 */
if ( ! defined( 'DATABASE_USER' ) ) define( 'DATABASE_USER', substr( SITENAME, 0, 11 ) . '_user' );

/**
 * Database Password
 *
 * The password that will be used to access the database for the current site.
 *
 * This password is generated using a UUID from the database upon user creation
 * and must be defined within the site configuration file, or it will be set to
 * the web_user password.
 *
 * @var string
 */
if ( ! defined( 'DATABASE_PASSWORD' ) ) define( 'DATABASE_PASSWORD', '' );

/**
 * Mysql Database
 *
 * The database on the mysql server in which all data will be stored for the
 * current user.
 *
 * @var string DATABASE_NAME
 */
//// Check if site is on uat and set up uat database if it exists
if ( UAT & $environment || (stristr( $_SERVER['SERVER_NAME'] , '.atlas.titaninteractive.com.au' ))  )
{              
    /// Perform a query on the database to check whether the database table exists
    $sql = sprintf( "SHOW TABLES IN %s LIKE %s"
                                    , '`'.substr( SITENAME, 0, 61 ) . '_uat`'
                            , "'titancms_modules'" );
    $result =  mysql_query( $sql, mysql_connect( DATABASE_SERVER, DATABASE_USER, DATABASE_PASSWORD ) );
    /// If there is at least one row this table exists
    $exists = ( ! $result ? false : ( mysql_num_rows( $result ) > 0 ) );
    //// if UAT database exists, use it. Otherwise use standard live database
    if ($exists) define( 'DATABASE_NAME', substr( SITENAME, 0, 61 ) . '_uat' );
    elseif ( ! defined( 'DATABASE_NAME' ) ) define( 'DATABASE_NAME', substr( SITENAME, 0, 61 ) . '_db' );
}
//// Otherwise the site may be under construction, is live db doesn't exist, use uat one.
else
{             
    /// Perform a query on the database to check whether the database table exists
    $sql = sprintf( "SHOW TABLES IN %s LIKE %s"
                                    , '`'.substr( SITENAME, 0, 61 ) . '_db`'
                            , "'titancms_modules'" );
    $result =  mysql_query( $sql, mysql_connect( DATABASE_SERVER, DATABASE_USER, DATABASE_PASSWORD ) );
    /// If there is at least one row this table exists
    $exists = ( ! $result ? false : ( mysql_num_rows( $result ) > 0 ) );
    //// if UAT database exists, use it. Otherwise use standard live database
    if ($exists) define( 'DATABASE_NAME', substr( SITENAME, 0, 61 ) . '_db' );
    elseif ( ! defined( 'DATABASE_NAME' ) ) define( 'DATABASE_NAME', substr( SITENAME, 0, 61 ) . '_uat' );
}

/// APPLICATION CONFIGURATION --------------------------------------------------

/// Include the application defaults. All configuration direcives within this
/// file can be overwritten by site and server configuration files.
require_once TITANCMS_PATH ."/config/default.configuration.php";

/// LEGACY CONFIGURATION -------------------------------------------------------

/// Include the legacy configuration file from the titan cms to get any config
/// variables that have been depricated.
require_once TITANCMS_PATH ."/config/legacy.configuration.php";

/// APPLICATION START ----------------------------------------------------------

/// Include the TitanCMS object so that the application can be started.
require_once TITANCMS_PATH ."/library/TitanCMS.php";

/// Initialize the TitanCMS
TitanCMS::Initialize();
	
/// If the titan-cms is run in command line mode, include the cli script
if ( COMMAND_LINE & ENVIRONMENT
  && basename( $argv[0], '.php' ) == basename( __FILE__, '.php' ) ) TitanCMS::CommandLine();

/// Run the titan cms to handle the request that has been sent.
/// If the current environment is a command line environment, the titan cms
/// should not be automatically run.
elseif ( ! ( COMMAND_LINE & ENVIRONMENT )
      && ! ( SCRIPT & ENVIRONMENT ) ) TitanCMS::Run();

