<?php

// dmx_run.php
// -------------------------------------------------------------------------------------------------
// Run on every XComponents-enabled page - sets up environment
//
// Revision   > $Rev: 127 $
// Date		  > $Date: 2009-10-21 10:44:27 +0100 (Wed, 21 Oct 2009) $
// Author     > RAK for DML
// Copyright  > (C) Digital Mail Limited (2005-2009)
// -------------------------------------------------------------------------------------------------

// SET UP ERROR REPORTING

if ($dmx_options['error_rep'])
{
	ini_set('display_errors', 1);
	error_reporting(E_ALL);
}
else
{
	ini_set('display_errors', 0);
	error_reporting(0);
}

// -------------------------------------------------------------------------------------------------
// ADDITIONAL OPTIONS

$dmx_options['abs'] = FALSE; // May be overriden by dmABS very soon

// -------------------------------------------------------------------------------------------------
// INITIALISE BENCHMARKING

$dmx_benchmarks = array();			// Holds benchmarks
$dmx_gmt = getdate();				// GMT time
$dmx_time0 = dmx_get_microtime();	// Microtime at start of page

// -------------------------------------------------------------------------------------------------
// CLEANSE INPUT 

if (get_magic_quotes_gpc()) // Clease input if corrupted by magic quotes
{
	$_POST 		= dmx_handle_magic_quotes($_POST);
	$_GET  		= dmx_handle_magic_quotes($_GET);
	$_COOKIE 	= dmx_handle_magic_quotes($_COOKIE);
	$_REQUEST 	= dmx_handle_magic_quotes($_REQUEST);
}

// -------------------------------------------------------------------------------------------------
// INITIALISE JSON SERVICES AND UPDATE DEBUGGING SETTINGS FROM DEBUG COOKIE

// Opensource JSON-PHP data converter from PEAR - See http://mike.teczno.com/json.html
require_once(DOCROOT . '/dmx/core/php/class/json.class.php');
$json = new Services_JSON();

// Read JSON encoded debugging cookie (dmx_debug_settings), if present
if (isset($_COOKIE['dmx_debug_settings']))
{
	$dmx_debug_settings = $json->decode($_COOKIE['dmx_debug_settings']);
}
else
{
	$dmx_debug_settings = new stdClass;
}
$dmx_options['debug_level'] =
$dmx_debug_settings->xcom 	= isset($dmx_debug_settings->xcom) ? $dmx_debug_settings->xcom : $dmx_options['debug_level'];

// Now write current settings if cookie does not yet exist
if (!isset($_COOKIE['dmx_debug_settings']))
{
	setcookie('dmx_debug_settings', $json->encode($dmx_debug_settings), false, '/');
}

// -------------------------------------------------------------------------------------------------
// CLASSES

// Debugging class
require_once(DOCROOT . '/dmx/core/php/class/debug.class.php');
$dmx_debug = new Debug($dmx_options['debug_level'] > 0);

// Substitutions class
require_once('class/substitutions.class.php');
$dmx_glos = NULL;

// PWP communication class
require_once(DOCROOT . '/dmx/core/php/class/pwp.class.php');
$dmshop = new PWP($dmx_protocol['dmshop']['server_urls'], $dmx_protocol['dmshop']['prot_ver']);
$dmshop->client_app_version = $dmx_version;

// Define constants for templates
if (!defined('DMX_SELF')) define('DMX_SELF', $_SERVER['PHP_SELF']);
define('DMX_DIR',  preg_replace('/\/[\w\.\-]*$/', '/', DMX_SELF));

// -------------------------------------------------------------------------------------------------
// START INTERNAL SESSION

session_name('DMXSessionID');
session_start();

// Retrieve dmShop memory from copy stored in session
$dmx_memory = isset($_SESSION['dmx_memory']) ? $_SESSION['dmx_memory'] : array();

// -------------------------------------------------------------------------------------------------
// START OUTPUT BUFFERING

ob_start(array($dmx_glos, 'substitute'));
header('P3P: CP="IDC DSP COR CURa ADMa OUR IND PHY ONL COM STA"');
// Prevent output being cached by browser
header('Pragma: no-cache');							// for HTTP 1.0
header('Cache-Control: no-cache, must-revalidate'); // for HTTP 1.1

// -------------------------------------------------------------------------------------------------

// Retrieve session transfer mechanism and session reference (trolley ID)
$dmx_options['session_mech'] = isset($dmx_options['session_mech']) ? $dmx_options['session_mech'] : 'tst';
if ( !$dmx_options['seeding'] || ($dmx_options['seeding'] && !isset($_GET['dmx_name']) && !isset($_GET['dmx_did'])) )
{
	$dmx_session = dmx_get_session($dmx_options['session_mech']);
}
else
{
	$dmx_session = ''; // Dealer Identity Seeding is permitted and 'dmx_did' or 'dmx_name' have been set in the incoming URL
}

// If we are using TST make any 'tst_public' session information available to PHP in the $tst_public object
// NOTE THIS CAN THEN BE ACCESSED USING OBJECT NOTATION IN PHP eg.
// $tst_public->interest->service->latest
if (strtolower($dmx_options['session_mech']) == 'tst' && isset($_GET['dmb1_additional']))
{
 	$_GET['dmb1_additional'] = urldecode($_GET['dmb1_additional']);
 	$tst_public = $json->decode($_GET['dmb1_additional']);
}

// -------------------------------------------------------------------------------------------------
// LOOK FOR INCOMING NUMBERCHOOSER CONTROL PARAMETERS 

// First look for generic NCP
// These are of the form dmx_service (etc) - and apply to all NumberChoosers on the page

$new_root 		= NULL;
$new_range 		= NULL;
$new_service 	= NULL;
$new_plan 		= NULL;
$new_gold 		= NULL;
$new_areacode 	= NULL;
if (isset($_REQUEST['dmx_root'])) 	 	$new_root	 	= $_REQUEST['dmx_root'];
if (isset($_REQUEST['dmx_range'])) 	 	$new_range	 	= $_REQUEST['dmx_range'];
if (isset($_REQUEST['dmx_service'])) 	$new_service 	= $_REQUEST['dmx_service'];
if (isset($_REQUEST['dmx_plan'])) 		$new_plan 		= $_REQUEST['dmx_plan'];
if (isset($_REQUEST['dmx_gold'])) 		$new_gold 		= $_REQUEST['dmx_gold'];
if (isset($_REQUEST['dmx_areacode']))	$new_areacode	= $_REQUEST['dmx_areacode'];

$dmx_ncp = array();
$dmx_memories_to_update = array();

if ($new_root || $new_range || $new_service || $new_plan || $new_gold || $new_areacode)
{	
	// Generic NCP detected, so clear memory and reset
	$dmx_ncp['NCGLOBAL']['class'] 		= 'NumberChooser_GLOBAL';
	$dmx_ncp['NCGLOBAL']['root'] 		= $new_root;
	$dmx_ncp['NCGLOBAL']['range'] 		= $new_range;
	$dmx_ncp['NCGLOBAL']['service'] 	= $new_service;
	$dmx_ncp['NCGLOBAL']['plan'] 		= $new_plan;
	$dmx_ncp['NCGLOBAL']['gold'] 		= $new_gold;
	$dmx_ncp['NCGLOBAL']['areacode'] 	= $new_areacode;
	$dmx_ncp['NCGLOBAL']['areaname']	= NULL;
	$dmx_ncp['NCGLOBAL']['prefix']		= NULL;
	
	// Keep dmx_memory up-to-date
	$dmx_memory['NCGLOBAL'] = $dmx_ncp['NCGLOBAL'];
	array_push($dmx_memories_to_update, 'NCGLOBAL');
	
	// Hack to prevent dmABS areacode-cacheing causing areacode to be remembered
	// when incoming global NP are detected
	unset($_SESSION['ABS']['last_areacode']);
}

// Incoming global NCP overrite corresponding NumberChooser-specific NCP
if (isset($dmx_ncp['NCGLOBAL']))
{
	// Kill NCP-specific memories
	foreach($dmx_memory as $mem_name => $mem)
	{
		if (!isset($mem['class']) || $mem['class'] != 'NumberChooser') continue;
		$dmx_ncp[$mem_name] = array(
			'class'			=> 'NumberChooser',
			'root'			=> NULL,
			'range' 		=> NULL,
			'service' 		=> NULL,
			'plan' 			=> NULL,
			'gold' 			=> NULL,
			'areacode' 		=> NULL,
			'areaname' 		=> NULL,
			'prefix' 		=> NULL
		);
	}
}

// Now look for NumberChooser-specific NCP
// These are of the form dmx.charlie

preg_match_all('/dmx_root\.(.+?)=([^&]+)?&?/',   	$_SERVER['QUERY_STRING'], $specific['root']); 		// Find specific dmx_root 	  parameters
preg_match_all('/dmx_range\.(.+?)=([^&]+)?&?/',   	$_SERVER['QUERY_STRING'], $specific['range']); 		// Find specific dmx_range 	  parameters
preg_match_all('/dmx_service\.(.+?)=([^&]+)?&?/', 	$_SERVER['QUERY_STRING'], $specific['service']); 	// Find specific dmx_service  parameters
preg_match_all('/dmx_plan\.(.+?)=([^&]+)?&?/', 		$_SERVER['QUERY_STRING'], $specific['plan']); 		// Find specific dmx_service  parameters
preg_match_all('/dmx_gold\.(.+?)=([^&]+)?&?/', 		$_SERVER['QUERY_STRING'], $specific['gold']); 		// Find specific dmx_gold 	  parameters
preg_match_all('/dmx_areacode\.(.+?)=([^&]+)?&?/', 	$_SERVER['QUERY_STRING'], $specific['areacode']); 	// Find specific dmx_areacode parameters

foreach($specific as $ncp => $values)
{
	foreach($values[1] as $nc_name)
	{
		if (!isset($dmx_ncp[$nc_name]))
		{
			$dmx_ncp[$nc_name] = array(
				'class'			=> 'NumberChooser',
				'root'			=> NULL,
				'range' 		=> NULL,
				'service' 		=> NULL,
				'plan' 			=> NULL,
				'gold' 			=> NULL,
				'areacode' 		=> NULL,
				'areaname' 		=> NULL,
				'prefix' 		=> NULL
			);

		}
		$dmx_ncp[$nc_name][$ncp] = array_shift($values[2]);
	}
}

// Validate date and add areanames (if areacode is set);
foreach(array_keys($dmx_ncp) as $nc_name)
{
	$dmx_debug->heading('Processing NCP for ' . $nc_name);
	$dmx_ncp[$nc_name] = dmx_validate_and_augment_state($dmx_ncp[$nc_name]);
	$dmx_debug->msg();
	$dmx_debug->inspect($nc_name, $dmx_ncp[$nc_name]);
}

// $dmx_ncp is shunted into dmShop memory when dmx_initialise_trolley is called
// BUT keep $dmx_memory fully up to date

if (!empty($dmx_ncp))
{
	foreach($dmx_ncp as $mem_name => $value)
	{
		$mem_name = strtoupper($mem_name);
		array_push($dmx_memories_to_update, $mem_name);
		if (isset($dmx_memory[$mem_name])) $value = array_merge($dmx_memory[$mem_name], $value);
		$dmx_memory[$mem_name] = $value;
	}
}

// -------------------------------------------------------------------------------------------------
// LOOK FOR INCOMING AUTOSHOP PARAMETERS 

preg_match_all('/auto_(.+?)=([^&]+)?&?/', $_SERVER['QUERY_STRING'], $matches); // Find auto_* parameters
if (!empty($matches[0]))
{
	// Autoshop parameters detected, so load autoshop
	include(DOCROOT . '/dmx/core/php/autoshop.php');
	foreach($matches[1] as $pname) $dmx_ash[$pname] = array_shift($matches[2]);
	dmx_autoshop($dmx_ash);
}

// -------------------------------------------------------------------------------------------------
// HANDLE ACTIONS

// Retieve 'action' variables if present
$dmx_comp_class = isset($_REQUEST['dmx_comp_class']) ? $_REQUEST['dmx_comp_class'] : ''; // The class of dmshop component
$dmx_comp_name  = isset($_REQUEST['dmx_comp_name'])  ? $_REQUEST['dmx_comp_name']  : ''; // The name of the particular component that issued the action
$dmx_action     = isset($_REQUEST['dmx_action'])     ? $_REQUEST['dmx_action']     : ''; // The action to perfom

// Retieve 'resultcode' array of results and corresponding URLs, if present
$dmx_rc = isset($_REQUEST['dmx_rc']) ? dmx_unserialize($_REQUEST['dmx_rc']) : array();

if ($dmx_session && $dmx_action)
{
	// Wnen an action is passed into the page (as part of a GET or POST)
	// execute this first before rendering any components
	
	$time1 = dmx_add_benchmark('Call ' . $dmx_action);
	
	$dmx_resultcode = dmx_handle_action($dmx_comp_class, $dmx_comp_name, $dmx_action);
	$dmx_resultcode['comp_name'] = $dmx_comp_name;
	
	dmx_add_benchmark('Response from ' . $dmshop->url, $time1);

	// Now deal with any HTTP redirects
	dmx_handle_redirects($dmx_resultcode);
}
else
{
	// Handle results passed to page in a redirect
	$dmx_resultcode = isset($_REQUEST['dmx_resultcode']) ? dmx_unserialize($_REQUEST['dmx_resultcode']) : '';
}

?>