<?php
/*
* Import Aggregators
*
* 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__) . '/simplexml.php');
require_once(dirname(__FILE__) . '/other_functions.php');
wtg_db_check_and_create();
wtg_messages();

function wtg_import_aggregators() {
	global $wpdb;
	if (!empty($_POST['upload'])) {
		if(isset($_FILES['import_feed']) && ($_FILES['import_feed']['tmp_name'])) {
			$xml_doc = file_get_contents($_FILES['import_feed']['tmp_name']);
			$xml_doc = stripslashes(htmlspecialchars_decode ($xml_doc));
			$xml_doc = str_replace("&", "and", $xml_doc);
			//echo $xml_doc ;
			//$xml_doc = html_entity_decode($xml_doc, ENT_COMPAT);
		}
		if(isset($xml_doc)) {
			$a = new WTG_Extrafeed();
			if (!is_array($a->wtg_parse_extrafeed_xml($xml_doc))) {
				echo '<div id="message" class="updated fade"><p>It seems that the configuration file is not compatible with the current version of the plugin.</p></div>';
			} else {
				$newarr = $a->wtg_parse_extrafeed_xml($xml_doc);
				
				$count = 0;
				if (isset($newarr['extrafeed']))
				{
					foreach($newarr['extrafeed'] as $extrafeed)
					{
						if (isset($extrafeed['title']) && isset($extrafeed['url']) && isset($extrafeed['desc']))
						{
							$ag = new WTG_Extrafeed();
							$ag->initDB();
							//insert into DB
							$id = $ag->add_extrafeedDB(trim($extrafeed['title']), trim($extrafeed['url']), trim($extrafeed['desc']));
							$count++;
						}
						else{
							echo '<div id="message" class="updated fade"><p>It seems that the configuration file is not compatible with the current version of the plugin.</p></div>';
							break;
						}
						
					}
					if ($count == count($newarr['extrafeed']))
						echo '<div id="message" class="updated fade"><p>The configuration file was updated.</p></div>';
				}
				
			}
		} else {
			$xml_doc = file_get_contents($_FILES['import']['tmp_name']);
			$xml_doc = stripslashes($xml_doc);
			$a = new WTG_Aggregator();
			
			if (!is_array($a->_parse_aggregators_xml($xml_doc))) {
				echo '<div id="message" class="updated fade"><p>It seems that the configuration file is not compatible with current version of the plugin.</p></div>';
			} else {
				//echo "backup: ". copyemz(AGGREGATORS_XML_TEMPLATE,AGGREGATORS_XML_TEMPLATE.time());
				$newarr = $a->wtg_parse_aggregators_xml($xml_doc);
				//echo "<pre>";print_r($newarr['aggregator']);echo "</pre>";
				
				$count = 0;
				if (isset($newarr['aggregator']))
				{
					$table_name_agg_submit = $wpdb->prefix . "_wtg_agg_submit";
					foreach($newarr['aggregator'] as $aggregator)
					{
						$name = str_replace("*","",trim($aggregator['name']));
						$name = str_replace(" ","",trim($name));
						$enabled = $aggregator['@attributes']['enabled'];

						//search if feed name exists
						$ag1 = new WTG_Aggregator();
						$ag1->initDB();
						$aggInDB = $ag1->searchAggNameDB($name);
						if($aggInDB != false)
						{
							//if it exists, search for these parameters and modify the,
							$steps = $aggregator['step'];
							$order = "";
							$id = $aggInDB->id;
							
							// if more than 1 step
							if (isset($steps[0]))
							{
								foreach($steps as $step)
								{
									$order = (int) $step['order'];
									//echo "&nbsp; &nbsp; order: ". $order."<br/>";
									$params = $step['params']['param'];
									
									//if more than 1 parameter
									$args = array();
									if (isset($params[0]))
									{
										//parameters in the file
										foreach($params as $param)
										{
											$type = $param['@attributes']['type'];
											$name = $param['name'];
											$value = $param['value'];
											
											$ag = new WTG_Aggregator();
											$ag->initDB();
											$agg_details = $ag->get_aggregatorDetailsDB($id);
											$stepsDB = unserialize($agg_details->steps);
											$stepDB = $stepsDB[$order];
											//echo "<pre>";print_r($stepDB);echo "</pre>";
											if ($order == 1)
											{
												$profile_params = array();
												
												foreach ($params as $param)
												{
													$single_profile_param = array();
													$type = $param['@attributes']['type'];
													$name = $param['name'];
													$value = $param['value'];
													$single_profile_param['param_name']  = $name;
													$single_profile_param['param_type']  = $type;
													$single_profile_param['param_value'] = $value;
													$profile_params[] = $single_profile_param;
												}
												
												$stepDB['params'] = $profile_params;
												$stepsDB[$order] = $stepDB;
												$serializedData = serialize($stepsDB);
												$wpdb->update( $table_name_agg_submit , array( 'steps' => $serializedData ), array( 'id' => $id ));
											}
											else
											{
												foreach($ag->get_aggregator_paramsDB($id, $order) as $index => $paramDB)
												{
													if ($paramDB['param_name'] == $name)
													{
														$stepDB['params'][$index]['param_value'] =  $value;
														$stepsDB[$order] = $stepDB;
														$serializedData = serialize($stepsDB);
														$wpdb->update( $table_name_agg_submit , array( 'steps' => $serializedData ), array( 'id' => $id ));
													}
												}
											}
										}
									}
									//if there is just 1 parameter
									else
									{
										$type = $params['@attributes']['type'];
										$name = $params['name'];
										$value = $params['value'];
										
										$ag = new WTG_Aggregator();
										$ag->initDB();										
										$agg_details = $ag->get_aggregatorDetailsDB($id);
										$steps = unserialize($agg_details->steps);
										$step = $steps[$order];
										
										foreach($ag->get_aggregator_paramsDB($id, $order) as $index => $paramDB)
										{
											if ($paramDB['param_name'] == $name)
											{
												$step['params'][$index]['param_value'] =  $value;
												$steps[$order] = $step;
												$serializedData = serialize($steps);
												$wpdb->update( $table_name_agg_submit , array( 'steps' => $serializedData ), array( 'id' => $id ));																					
											}
										}
									}
								}
							}
							//there is just 1 step
							else
							{
								$order = (int) $steps['order'];
								//echo "&nbsp; &nbsp; order: ". $order."<br/>";
								$params = $steps['params']['param'];
								//if there is more than 1 parameters
								if (isset($params[0]))
								{
									foreach($params as $param)
									{
										$type = $param['@attributes']['type'];
										$name = $param['name'];
										$value = $param['value'];
										
										$ag = new WTG_Aggregator();
										$ag->initDB();
										$agg_details = $ag->get_aggregatorDetailsDB($id);
										$steps = unserialize($agg_details->steps);
										$step = $steps[$order];
										
										foreach($ag->get_aggregator_paramsDB($id, $order) as $index => $paramDB)
										{
											if ($paramDB['param_name'] == $name)
											{
												$step['params'][$index]['param_value'] =  $value;
												
												$steps[$order] = $step;
												$serializedData = serialize($steps);
												$wpdb->update( $table_name_agg_submit , array( 'steps' => $serializedData ), array( 'id' => $id ));																					
											}
										}
									}
								}
								//if there is just 1 parameter
								else
								{
									$type = $params['@attributes']['type'];
									$name = $params['name'];
									$value = $params['value'];
										
									$ag = new WTG_Aggregator();
									$ag->initDB();
									$agg_details = $ag->get_aggregatorDetailsDB($id);
									$steps = unserialize($agg_details->steps);
									$step = $steps[$order];
									
									foreach($ag->get_aggregator_paramsDB($id, $order) as $index => $paramDB)
									{
										if ($paramDB['param_name'] == $name)
										{
											$step['params'][$index]['param_value'] =  $value;
											$steps[$order] = $step;
											$serializedData = serialize($steps);
											$wpdb->update( $table_name_agg_submit , array( 'steps' => $serializedData ), array( 'id' => $id ));																					
										}
									}
								}
							}
						
						
						}
					}
					//update aggregator states
					foreach ($ag->get_all_aggregatorsDB() as $aggregator)
					{
						if ($aggregator->hasLogin == 1)
						{
							$aggregator_id = $aggregator->id;
							$agg = $ag->get_aggregatorDB($aggregator_id);
							$agg_details = $ag->get_aggregatorDetailsDB($aggregator_id);
							$steps = unserialize($agg_details->steps);
							$param = $steps[1]['params'];
							
							if (($param[0]['param_value'] == "") || ($param[1]['param_value'] == ""))
								$wpdb->update( $table_name_aggregators , array( 'isReady' => 0 ), array( 'id' => $aggregator->id ));
						}
					}
					//if ($count == count($newarr['extrafeed']))
						echo '<div id="message" class="updated fade"><p>The configuration file was updated.</p></div>';
				}
				/*wtg_import_check($newarr);
				$ag = new WTG_Aggregator();
				$ag->init();
				$previous_list = $ag->_parse_aggregators_xml(file_get_contents(AGGREGATORS_XML_TEMPLATE));
				wtg_merge_with_previous($newarr, $previous_list);
				$simple_xml = new MySimpleXML();
				$xml_doc=$simple_xml->asXML($newarr);
				if (wtg_handle_import($xml_doc) != 0){
					echo '<div id="message" class="updated fade"><p>The configuration file was updated.</p></div>';
				} else {
					echo '<div id="message" class="error"><p>Failed to update the configuration file. Please make sure to change the permissions on '. AGGREGATORS_XML_TEMPLATE . ' to 0666.</p></div>';
				}*/
			}
		}
	}

?>
	<div class="wrap">
		<h2>Import</h2>
		<p>This allows you to restore your configuration. Select your file and click Import.</p>
		<p></p>
		<p><b>Aggregators:</b></p>
		<form enctype="multipart/form-data"  method="post" action="">
		<p>
			<label>Choose the configuration file you wish to use:</label>
			<input type="file" name="import" size="25" />
		</p>
		<p>* Only the parameters will be imported (usernames, passwords, categories, etc.)
			</p>
		<p class="submit">
			<input type="submit" name="upload" value="Upload file and import &raquo;" />
                </p>
        </form>
        <p><b>Extra Feeds:</b></p>
		<form enctype="multipart/form-data"  method="post" action="">
		<p>
			<label>Choose the configuration file you wish to use:</label>
			<input type="file" name="import_feed" size="25" />
		</p>
		<p class="submit">
			<input type="submit" name="upload" value="Upload file and import &raquo;" />
      		 </p>
    		</form>
</div>
<?php
}

function wtg_handle_import($doc) {
	return file_put_contents(AGGREGATORS_XML_TEMPLATE, $doc);
}

function wtg_handle_extrafeed_import($doc) {
	return file_put_contents(EXTRAFEED_XML, $doc);
}

function wtg_import_check(&$aggregators_list) {
    // Aggregators that can't work
    $invalidset = array();
    $invalidset[0] = "goldenfeed.com";
    $invalidset[1] = "readablog.com";
    $invalidset[2] = "rss2.com *";
    $invalidset[3] = "feeds4all.nl";

    // Don't import Aggregators that are invalid
    foreach (wtg_to_array($aggregators_list['aggregator']) as $k => $aggregator) {
		if (in_array($aggregator['name'], $invalidset)) {
			unset($aggregators_list['aggregator'][$k]);
		}
    }

    // Basic list of aggregators, working with the plugin
	$validset = array();
	$validset[0]="feedagg.com";
	$validset[1]="feedage.com";
	$validset[2]="rssmotron.com";
	$validset[3]="plazoo.com";
	$validset[4]="overskrift.dk";
	$validset[5]="feeds2read.net";
	$validset[6]="newsisfree.com";
	$validset[7]="rss-network.com";
	$validset[8]="rss-feeds.info";
	$validset[9]="devasp.com";
	$validset[10]="feedgy.com";
    $validset[11]="feedest.com";
	$validset[12]="rssnetworkfeedsdirectory.com";
    $validset[13]="feedboy.com";
	$validset[14]="feedshoster.com";
	$validset[15]="blogpulse.com";
	$validset[16]="icerocket.com";
	$validset[17]="ngoid.sourceforge.net";

	/*foreach (wtg_to_array($aggregators_list['aggregator']) as $k => $aggregator) {
		if (!in_array($aggregator['name'], $validset)) {
			unset($aggregators_list['aggregator'][$k]);
		}
    }*/
    // the callback functions need the _wtg prefix!
    foreach (wtg_to_array($aggregators_list['aggregator']) as $i => $aggregator) {
        foreach (wtg_to_array($aggregators_list['aggregator'][$i]['step']) as $j => $step) {
            if (isset($aggregators_list['aggregator'][$i]['step'][$j]['params'])) {
                foreach (wtg_to_array($aggregators_list['aggregator'][$i]['step'][$j]['params']['param']) as $k => $param) {
                    if (strcmp((string)$param['@attributes']['type'], 'callbackFunction') == 0) {
                        // fix values when it doesn't start with wtg_
                        if (strpos((string)$param['value'], 'callback') == 0) {
                            $val = (string)$param['value'];
                            $aggregators_list['aggregator'][$i]['step'][$j]['params']['param'][$k]['value'] = 'wtg_' . $val;
                        }
                    }
                }
            }
        }
	}

    // the successRegex may have to be corrected (known issues)
    foreach (wtg_to_array($aggregators_list['aggregator']) as $i => $aggregator) {
        // feedagg.com
        if (strcmp((string)$aggregators_list['aggregator'][$i]['name'], $validset[0]) == 0) {
            foreach (wtg_to_array($aggregators_list['aggregator'][$i]['step']) as $j => $step) {
                if (strcmp((string)$aggregators_list['aggregator'][$i]['step'][$j]['order'], '2') == 0) {
                    $aggregators_list['aggregator'][$i]['step'][$j]['successRegx'] = '|add a relevant lens now|';
                }
            }
        }
        // feeds2read.net
        if (strcmp((string)$aggregators_list['aggregator'][$i]['name'], $validset[6]) == 0) {
            foreach (wtg_to_array($aggregators_list['aggregator'][$i]['step']) as $j => $step) {
                if (strcmp((string)$aggregators_list['aggregator'][$i]['step'][$j]['order'], '2') == 0) {
                    $aggregators_list['aggregator'][$i]['step'][$j]['successRegx'] = '|rssmaindesc|';
                }
            }
        }
    }
}

function wtg_merge_with_previous(&$aggregators_list, &$previous_list) {
    //$actual_list = wtg_to_array($aggregators_list['aggregator']);
    $actual_list_names = array();
    foreach (wtg_to_array($aggregators_list['aggregator']) as $i => $aggregator) {
        array_push($actual_list_names, (string)$aggregator['name']);
    }
    foreach (wtg_to_array($previous_list['aggregator']) as $i => $previous_aggregator) {
        if (!in_array((string)$previous_aggregator['name'], $actual_list_names)) {
            array_push($aggregators_list['aggregator'], $previous_aggregator);
		}
    }
}

function wtg_merge_feed_with_previous(&$extrafeed_list, &$previous_list) {
    $actual_list_names = array();
    foreach (wtg_to_array($extrafeed_list['extrafeed']) as $i => $extrafeed) {
        array_push($actual_list_names, (string)$extrafeed['id']);
    }
    foreach (wtg_to_array($previous_list['extrafeed']) as $i => $previous_extrafeed) {
        if (!in_array((string)$previous_extrafeed['id'], $actual_list_names)) {
            array_push($extrafeed_list['extrafeed'], $previous_extrafeed);
	}
    }
}