<?php
/*
* Submit
*
* Web Traffic Genius Pro v3.5.4
* Copyright (c) 2008-2010
* Success on the Internet Pty Ltd
* PO Box 25
* Salisbury SA 5108
* Australia
* Phone: +61 422 512 549
* Fax: +61 8 8425 9657
* Web: http://www.webtrafficgenius.com
* Support: http://www.marketing-assassins.com
*
*/

require_once(dirname(__FILE__) . '/config.php');
require_once(dirname(__FILE__) . '/php5_functions.php');
require_once(dirname(__FILE__) . '/http_functions.php');
require_once(dirname(__FILE__) . '/curl_functions.php');
require_once(dirname(__FILE__) . '/form_parser.php');
require_once(dirname(__FILE__) . '/feed_generator.php');
require_once(dirname(__FILE__) . '/aggregator_model.php');
require_once(dirname(__FILE__) . '/rss_log.php');
require_once(dirname(__FILE__) . '/callback_functions.php');
require_once(dirname(__FILE__) . '/rss_database.php');
require_once(dirname(__FILE__) . '/rss_cron_job.php');

//Dear future me. Please forgive me. 
//I can't even begin to express how sorry I am.  


function wtg_submit_rss() {
    global $logger, $indent;

    $wtg_option = get_option('wtg_option');

    $logger->debug(str_repeat(' ', $indent) . 'Getting the rss aggregator website list');
    $ag = new WTG_Aggregator();
    $ag->initDB();
    $db = new WTG_DB();

    $aggregators = $ag->get_all_aggregatorsDB();
    $logger->debug(str_repeat(' ', $indent) . 'Total ' . count($aggregators) . ' rss aggregator websites ');
    
    $post_scheduled = false;
    // clear the cookie jar
    file_put_contents(COOKIEJAR, '');
    
    foreach ($aggregators as $aggregator) {
        //$aggregator = $aggregators[$i];
        if ($aggregator->enabled == 0) {
            //$logger->info(str_repeat(' ', $indent = 2) . "Aggregator website {$aggregator->name} is disabled");
            continue;
        }
        if ($aggregator->isReady == 0) {
            $logger->info(str_repeat(' ', $indent = 2) . "Aggregator website {$aggregator->name} is not ready (not configured)");
            continue;
        }

        if (!empty($wtg_option['cron_enabled']) && defined('DEFER_NEW_POSTPROCESSING') && DEFER_NEW_POSTPROCESSING) {
            wtg_set_cron_job_complete(false);
            if ($db->add_job($GLOBALS['wtg']['postID'], $GLOBALS['wtg']['feedName'], $aggregator->id)) {
                $logger->info(str_repeat(' ', $indent) . "Add post event({$aggregator->name}) to schedule job list SUCCESS(post_id={$GLOBALS['wtg']['postID']}, feed_name={$GLOBALS['wtg']['feedName']}, aggregator_id={$aggregator->id})");
                $post_scheduled = true;
            } else {
                $logger->info(str_repeat(' ', $indent) . "Add post event({$aggregator->name}) to schedule job list FAIL(post_id={$GLOBALS['wtg']['postID']}, feed_name={$GLOBALS['wtg']['feedName']}, aggregator_id={$aggregator->id})");
            }
        } else { // Post feeds immediately - tgb
            wtg_submit_feed_to_one_site($GLOBALS['wtg']['postID'], $GLOBALS['wtg']['feedName'], $aggregator->id);
        }

    }
    
    if ($post_scheduled) {
        $db->add_scheduled_post($GLOBALS['wtg']['postID']);
    }

    if (!empty($wtg_option['cron_enabled'])) {
        // Start the schedule job
        $scheduled = wtg_schedule_next_event();
        if ($scheduled) { // bindy
            $logger->info(str_repeat(' ', $indent = 2) . 'Schedule cron job SUCCESS. Start at ' . date('l jS \of F Y h:i:s A', $scheduled) . '.');
        } else {
            $logger->info(str_repeat(' ', $indent = 2) . 'Schedule cron job FAIL');
        }
    }

}

function wtg_submit_page_rss() {
    global $logger, $indent;
	$logger = new WTG_Rss_Log();
	$logger->openlog();

    $wtg_option = get_option('wtg_option');

    $logger->debug(str_repeat(' ', $indent) . 'Getting the rss aggregator website list');
    $ag = new WTG_Aggregator();
    $ag->initDB();
    $db = new WTG_DB();

    $aggregators = $ag->get_all_aggregatorsDB();
    $logger->debug(str_repeat(' ', $indent) . 'Total ' . count($aggregators) . ' rss aggregator websites ');
    
    $post_scheduled = false;
    // clear the cookie jar
    file_put_contents(COOKIEJAR, '');
    
    foreach ($aggregators as $aggregator) {
        //$aggregator = $aggregators[$i];
        if ($aggregator->enabled == 0) {
            //$logger->info(str_repeat(' ', $indent = 2) . "Aggregator website {$aggregator['name']} is disabled");
            continue;
        }
        if ($aggregator->isReady == 0) {
            $logger->info(str_repeat(' ', $indent = 2) . "Aggregator website {$aggregator->name} is not ready (not configured)");
            continue;
        }

        wtg_submit_page_feed_to_one_site($GLOBALS['wtg']['pageID'], $GLOBALS['wtg']['feedName'], $aggregator->id);
        

    }
    
    if (!empty($wtg_option['cron_enabled'])) {
        // Start the schedule job
        $scheduled = wtg_schedule_next_event();
        if ($scheduled) { // bindy
            $logger->debug(str_repeat(' ', $indent = 2) . 'Schedule cron job SUCCESS. Start at ' . date('l jS \of F Y h:i:s A', $scheduled) . '.');
        } else {
            $logger->debug(str_repeat(' ', $indent = 2) . 'Schedule cron job FAIL');
        }
    }
	$logger->closelog();

}

function wtg_submit_page_feed_to_one_site($post_id, $feed_name, $aggregator_id) {
    global $logger, $indent;

    $GLOBALS['wtg']['postID'] = $post_id;
    $GLOBALS['wtg']['feedName'] = $feed_name;

    $ag = new WTG_Aggregator();
    $ag->initDB();

    $aggregator = $ag->get_aggregatorDB($aggregator_id);
	$agg_details = $ag->get_aggregatorDetailsDB($aggregator_id);
	
	$fail = false; // indicator whether this session is successful or not
	$steps = unserialize($agg_details->steps);

    $logger->info(str_repeat(' ', $indent = 2) . 'Starting to submit rss feed to aggregator ' . $aggregator->name);
    // do them
    foreach ($steps as $k => $step) {
		$logger->debug(str_repeat(' ', $indent = 4) . 'Starting to do step(order id=' . $k . ')');
		$url = $step['url'];
		
		// get information of this step
		$which_form = array('formIDType' => $step['formIDType'], 'formIDValue' => $step['formIDValue'], 'method' => "POST" );
        $success_regx = $step['successRegx'];
		
        //$params = wtg_to_array($step['params']);
		$params = $step['params'];
		
		
		if (count($params) > 1) { // multi profile found
            $profile_index = rand(0, count($params) - 1);
            $logger->debug(str_repeat(' ', $indent) . "Multiple profiles found. Use profile {$profile_index}.");
        } else {
            $profile_index = 0;
        }
		$logger->debug(str_repeat(' ', $indent = 2) . 'URL is: ' . $step['url']);
        //$params = wtg_to_array($params[$profile_index]['param']);
		//$params = $params[$profile_index]['param'];
		
		if (strcmp((string)$step['url'], '[auto]') == 0) {
			//$logger->info(str_repeat(' ', $indent) . " wtg_process_form().");
            $result = wtg_process_page_form($result['url'], $result['html'], $params, $success_regx, $which_form, $aggregator);
        } else {
            // call submit function
			//$logger->info(str_repeat(' ', $indent) . " wtg_process_request().");
            $result = wtg_process_page_request($step['url'], $params, $success_regx, $which_form, $aggregator);
        }

        if (empty($result)) {
            $fail = true;
            $logger->error(str_repeat(' ', $indent = 2) . "Failed to to do step(order id=$k) Will skip other steps.");
            // skip this aggregator
            break;
        }
    }
	
	if ($fail) {
        $logger->error(str_repeat(' ', $indent = 0) . "Submit rss feed to aggregator {$aggregator->name} FAIL\n");
    } else {
        $logger->info(str_repeat(' ', $indent = 0) . "Submit rss feed to aggregator {$aggregator->name} SUCCESS\n");
        $db = new WTG_DB();
        $db->add_scheduled_post($post_id);
    }
}

function wtg_process_page_request($url, $params, $success_regx, $which_form = array(), $aggregator) {
    global $logger, $indent;
    $header = array();
    $last_url = '';

    $logger->buf(str_repeat(' ', $indent += 2) . 'Fetching url ' . $url);
    $html = wtg_fetch_url($url, $header, $last_url);

    if (empty($html)) {
        $logger->debug(' FAIL');
        return false;
    }
    $logger->debug(' SUCCESS');

    return wtg_process_page_form($last_url, $html, $params, $success_regx, $which_form, $aggregator);
}

function wtg_process_page_form($last_url, $html, $params, $success_regx, $which_form = array(), $aggregator) {
    global $logger, $indent;
    $header = array();

    $logger->debug(str_repeat(' ', $indent) . 'Parsing forms');
    $forms = wtg_parse_forms($html, $aggregator);

    $logger->buf(str_repeat(' ', $indent) . "Searching for the specific form({$which_form['formIDType']}={$which_form['formIDValue']})");
    $found = false;

    if (!empty($which_form)) {
        foreach ($forms as $index => $form) {
            if ($which_form['formIDType'] == 'name' && $form['form']['name'] == $which_form['formIDValue']) {
                $found = true;  // arbor
                break;
            } elseif ($which_form['formIDType'] == 'index' && $index == $which_form['formIDValue']) {
                $found = true;
                break;
            } elseif ($which_form['formIDType'] == 'id' && $form['form']['id'] == $which_form['formIDValue']) {
                $found = true;
                break;
            }
        }
    }
    if (!$found) {
        $form = $forms[0];
        $logger->debug(' FAIL(use form[0] instead)');
    } else {
        $logger->debug(' SUCCESS');
    }

    $logger->debug(str_repeat(' ', $indent) . 'Preparing for the post parmeters');
    $indent += 2;
    foreach($params as $param)
	{
		//$logger->info(str_repeat(' ', $indent -= 2) . 'callback type'. $param['param_type'] . ' with value '.  $param['param_value']);
        //parameter type is callback function
		if (strcmp((string)$param['param_type'], 'callbackFunction') == 0) {
            if (preg_match('|(.+)\((.*)\)|', $params[$j]['param_value'], $matches)) { // function with parameters and 5108
                $function_name = $matches[1];
                $function_args = array_map('trim', explode(',', $matches[2]));
            } else { // function without parameters
                $function_name = $param['param_value'];
                $function_args = array();
            }
            $values[(string)$param['param_name']] = call_user_func($function_name, array('postID' => $GLOBALS['wtg']['postID'], 'url' => $last_url, 'html' => $html, 'feed_name' => $GLOBALS['wtg']['feedName'], 'extra_args' => $function_args));
           //$logger->info(str_repeat(' ', $indent) . '    [' . $param['param_name'] . '] => [' . $values[(string)$param['param_name']] . "]({$params[$j]['param_value']}(postID={$GLOBALS['wtg']['postID']}, url=$last_url, ...))");
        } else { // parameter type is value
            // $values[(string)$params[$j]['name']] = $params[$j]['value'];
            $value=split("\|\|\|",$param['param_value']);
            $values[(string)$param['param_name']] = $value[0];
            //$logger->info(str_repeat(' ', $indent) . '    [' . $param['param_name'] . '] => [' . $values[(string)$param['param_name']] . "](value)");
        }
    }

    $logger->debug(str_repeat(' ', $indent -= 2) . 'Merging post values');
    wtg_build_postvars($form, $postvars, $values, $postfiles);
    $indent += 2;
    foreach ($postvars as $pk => $pv) {
        $logger->debug(str_repeat(' ', $indent) . '[' . (string)$pk . '] => [' . implode($pv) . ']');
    }
    $indent -= 2;

    $return_url = '';

    if(!empty($form['form']['ACTION'])) {
       $form['form']['action']=$form['form']['ACTION'];
    }

    if (empty($form['form']['action'])) {
    	$form['form']['action'] = $last_url;
    }
    $url = wtg_get_url_relative($last_url, $form['form']['action']);
    $logger->debug(str_repeat(' ', $indent) . 'Submitting to ' . $url);
    $html = wtg_submit_url($url, $postvars, $header, $return_url, "post");
    
    $logger->buf(str_repeat(' ', $indent) . "Validating the result with regular expression($success_regx)");
	//$logger->buf(str_repeat(' ', $indent) . "html:". $html);
    if (empty($html) || !preg_match($success_regx, $html)) {
    	//print $url;
       // print $html;
        $logger->info(' FAIL');
        return false;
    }

    $logger->info(' SUCCESS');

    return array('url' => $return_url, 'html' => $html);
	
}

function wtg_submit_feed_to_one_site($post_id, $feed_name, $aggregator_id) {
    global $logger, $indent;

    $GLOBALS['wtg']['postID'] = $post_id;
    $GLOBALS['wtg']['feedName'] = $feed_name;

    $ag = new WTG_Aggregator();
    $ag->initDB();

    $aggregator = $ag->get_aggregatorDB($aggregator_id);
	$agg_details = $ag->get_aggregatorDetailsDB($aggregator_id);

    $fail = false; // indicator whether this session is successful or not
	$steps = unserialize($agg_details->steps);


    $logger->info(str_repeat(' ', $indent = 2) . 'Starting to submit rss feed to aggregator ' . $aggregator->name);
    
	// do them
	if (isset($steps) && is_array($steps))
	{
	//echo"<pre>";print_r($steps);echo"</pre>";
		foreach ($steps as $k => $step) {
			$logger->info(str_repeat(' ', $indent = 4) . 'Starting to do step(order id=' . $k . ')');
			$url = $step['url'];
			
			// get information of this step
			$which_form = array('formIDType' => $step['formIDType'], 'formIDValue' => $step['formIDValue'], 'method' => "POST" );
			$success_regx = $step['successRegx'];
			
			//$params = wtg_to_array($step['params']);
			$params = $step['params'];
			
			if ((count($params)/2 > 1) && ($k == 1)) { // multi profile found
				$profile_index = rand(0, count($params)/2) - 1;
				$logger->info(str_repeat(' ', $indent) . "Multiple profiles found. Use profile {$profile_index}.");
				//$params = $params[$profile_index]['param'];
				$newparams = array();
				$newparams[] = $params[$profile_index];
				$newparams[] = $params[$profile_index+1];
				$params = $newparams;
			}
			
			$logger->debug(str_repeat(' ', $indent = 2) . 'URL is: ' . $step['url']);
			//$params = wtg_to_array($params[$profile_index]['param']);
			//$params = $params[$profile_index]['param'];
			
			if (strcmp((string)$step['url'], '[auto]') == 0) {
				//$logger->info(str_repeat(' ', $indent) . " wtg_process_form().");
				$result = wtg_process_form($result['url'], $result['html'], $params, $success_regx, $which_form, $aggregator);
			} else {
				// call submit function
				//$logger->info(str_repeat(' ', $indent) . " wtg_process_request().");
				$result = wtg_process_request($step['url'], $params, $success_regx, $which_form, $aggregator);
			}

			if (empty($result)) {
				$fail = true;
				$logger->error(str_repeat(' ', $indent = 2) . "Failed to to do step(order id=$k) Will skip other steps.");
				// skip this aggregator
				break;
			}
		}
    }
	else $fail = true;
	
    if ($fail) {
        $logger->error(str_repeat(' ', $indent = 0) . "Submit rss feed to aggregator {$aggregator->name} FAIL\n");
    } else {
        $logger->info(str_repeat(' ', $indent = 0) . "Submit rss feed to aggregator {$aggregator->name} SUCCESS\n");
        $db = new WTG_DB();
        $db->add_scheduled_post($post_id);
    }
}

function wtg_process_form($last_url, $html, $params, $success_regx, $which_form = array(), $aggregator) {
    global $logger, $indent;
    $header = array();

    $logger->info(str_repeat(' ', $indent) . 'Parsing forms');
    $forms = wtg_parse_forms($html, $aggregator);

    $logger->info(str_repeat(' ', $indent) . "Searching for the specific form({$which_form['formIDType']}={$which_form['formIDValue']})");
    $found = false;

    if (!empty($which_form)) {
        foreach ($forms as $index => $form) {
            if ($which_form['formIDType'] == 'name' && $form['form']['name'] == $which_form['formIDValue']) {
                $found = true;  // arbor
                break;
            } elseif ($which_form['formIDType'] == 'index' && $index == $which_form['formIDValue']) {
                $found = true;
                break;
            } elseif ($which_form['formIDType'] == 'id' && $form['form']['id'] == $which_form['formIDValue']) {
                $found = true;
                break;
            }
        }
    }
    if (!$found) {
        $form = $forms[0];
        $logger->info(' FAIL(use form[0] instead)');
    } else {
        $logger->info(' SUCCESS');
    }

    $logger->info(str_repeat(' ', $indent) . 'Preparing for the post parmeters');
    $indent += 2;
	foreach($params as $param)
	{
		//$logger->info(str_repeat(' ', $indent -= 2) . 'callback type'. $param['param_type'] . ' with value '.  $param['param_value']);
		//parameter type is callback function
		if (strcmp((string)$param['param_type'], 'callbackFunction') == 0) {
            if (preg_match('|(.+)\((.*)\)|', $param['param_value'], $matches)) { // function with parameters and 5108
                $function_name = $matches[1];
                $function_args = array_map('trim', explode(',', $matches[2]));
            } else { // function without parameters
                $function_name = $param['param_value'];
                $function_args = array();
            }
            $values[(string)$param['param_name']] = call_user_func($function_name, array('postID' => $GLOBALS['wtg']['postID'], 'url' => $last_url, 'html' => $html, 'feed_name' => $GLOBALS['wtg']['feedName'], 'extra_args' => $function_args));
            //$logger->info(str_repeat(' ', $indent) . '    [' . $param['param_name'] . '] => [' . $values[(string)$param['param_name']] . "]({$params[$j]['param_value']}(postID={$GLOBALS['wtg']['postID']}, url=$last_url, ...))");
        } else { // parameter type is value
            // $values[(string)$params[$j]['name']] = $params[$j]['value'];
            $value=split("\|\|\|",$param['param_value']);
            $values[(string)$param['param_name']] = $value[0];
            //$logger->info(str_repeat(' ', $indent) . '    [' . $param['param_name'] . '] => [' . $values[$param['param_name']] . "](value) => ".$param['param_value']);
        }
	}
	
	$logger->info(str_repeat(' ', $indent -= 2) . 'Merging post values');
    wtg_build_postvars($form, $postvars, $values, $postfiles);
    $indent += 2;
    foreach ($postvars as $pk => $pv) {
        $logger->buf(str_repeat(' ', $indent) . '[' . (string)$pk . '] => [' . implode($pv) . ']');
    }
    $indent -= 2;

    $return_url = '';

    if(!empty($form['form']['ACTION'])) {
       $form['form']['action']=$form['form']['ACTION'];
    }

    if (empty($form['form']['action'])) {
    	$form['form']['action'] = $last_url;
    }
    $url = wtg_get_url_relative($last_url, $form['form']['action']);
    $logger->debug(str_repeat(' ', $indent) . 'Submitting to ' . $url);
    $html = wtg_submit_url($url, $postvars, $header, $return_url, "post");
    
    $logger->buf(str_repeat(' ', $indent) . "Validating the result with regular expression($success_regx)");
	//$logger->buf(str_repeat(' ', $indent) . "html:". $html);
    if (empty($html) || !preg_match($success_regx, $html)) {
    	//print $url;
       // print $html;
        $logger->info(' FAIL');
        return false;
    }

    $logger->info(' SUCCESS');

    return array('url' => $return_url, 'html' => $html);
	
}

function wtg_process_request($url, $params, $success_regx, $which_form = array(), $aggregator) {
    global $logger, $indent;
    $header = array();
    $last_url = '';

    $logger->info(str_repeat(' ', $indent += 2) . 'Fetching url ' . $url);
    $html = wtg_fetch_url($url, $header, $last_url);

    if (empty($html)) {
        $logger->debug(' FAIL');
        return false;
    }
    $logger->debug(' SUCCESS');

    return wtg_process_form($last_url, $html, $params, $success_regx, $which_form, $aggregator);
}

function wtg_test_login($ag_id, $profile_index) {
    global $logger;
    $logger = new WTG_Rss_Log();
    $logger->openlog();

    $logger->debug('Getting all the aggregator website list');
    $ag = new WTG_Aggregator();
    $ag->initDB();
    $step = $ag->get_aggregator_login_stepDB($ag_id);
    $aggregator = $ag->get_aggregatorDB($ag_id);
    
    if (empty($step) || empty($step['params'])) {
        $logger->error('No login information found');
        $logger->closelog();
        return false;
    }
    // clear the cookie jar
    file_put_contents(COOKIEJAR, '');

    $logger->info('Starting to test login(aggregator id=' . $ag_id . ', profile_index=' . $profile_index . ')');

    $url = $step['url'];

    $which_form = array('formIDType' => $step['formIDType'], 'formIDValue' => $step['formIDValue']);
    $success_regx = $step['successRegx'];
    //wtg_to_array($step['params']);
    //$params = wtg_to_array($step['params'][$profile_index]['param']);
	$params = $step['params'];
	
    $result = wtg_process_request($url, $params, $success_regx, $which_form, $aggregator);

    if (empty($result)) {
        $logger->error("Test login FAIL");
        $logger->closelog();
        return false;
    } else {
        $logger->info("Test login SUCCESS");
        $logger->closelog();
        return true;
    }
}

function wtg_submit_existing() {
    $db = new WTG_DB();
    $scheduled_list = array();
    $scheduled_posts = $db->get_scheduled_posts();
    foreach ($scheduled_posts as $scheduled_post) {
        array_push($scheduled_list, $scheduled_post->post_id);
    }
    //$scheduled_posts = array($db->get_scheduled_posts());
	
	$wtg_option = get_option('wtg_option');
	if (isset($wtg_option['posts_per_cron_job']))
		$posts_per_cron_job = $wtg_option['posts_per_cron_job'];
	else $posts_per_cron_job = POSTS_PER_CRON_JOB_DEFAULT;
	
    $args = array(
        'post_status'   => 'publish',
        'post__not_in'  => $scheduled_list,
        'numberposts'   => $posts_per_cron_job,
        'orderby'       => 'post_date',
		'order'         => 'DESC');
    $posts = get_posts($args);
    foreach ($posts as $post) {
        wtg_publish_post($post);
    }
}