<?php
/*
* Form Parsing code
*
* 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__) . '/php5_functions.php');
require_once(dirname(__FILE__) . '/string_functions.php');
require_once(dirname(__FILE__) . '/captcha_model.php');
require_once(dirname(__FILE__) . '/dbc_client.3.php' );

function wtg_parse_real_options( $text, &$cur_pos, $tag = '' ) {
	$option = wtg_get_all_attributes_from_tag($text, $cur_pos, $tag);
	if ( empty($tag) ) {
		return false;
	} else if ( $tag != 'option' ) {
		die ( 'parse_real_options: wrong tag' );
	}

	$option['text'] = trim(wtg_get_string_between('', array('<option', '</option'), $text, $cur_pos, false, false, false, false));
	return $option;
}

function wtg_parse_options( $text, &$cur_pos ) {
	$select     = wtg_get_string_between('', '</select', $text, $cur_pos, false, false, false);
	$options    = array();
	$optgroup   = '';
	$select_pos = 0;
	while ( $select_pos < strlen($select) ) {
		$tag = '';
		$option = wtg_get_all_attributes_from_tag($select, $select_pos, $tag);
		if ( !empty($tag) ) {
			if ( $tag == 'optgroup' ) {
				if ( !isset($option['label']) ) {
					//					echo "Wrong 'label' here!" ;
				}
				$option_group_text = wtg_get_string_between('', '</optgroup', $select, $select_pos, false, false, false);
				$option_group_text_pos = 0;
				while ( $option_group_text_pos < strlen($option_group_text) ) {
					$val = wtg_parse_real_options($option_group_text, $option_group_text_pos);
					if ( $val !== false )
						$options[ $option['label'] ][] = $val;
				}
			} else if ( $tag != 'option' ) {
				//				echo  'Wrong tag here!' ;
			} else {
				$option['text'] = trim(wtg_get_string_between('', array('<option', '</option'), $select, $select_pos, false, false, false, false));
				$options[''][]  = $option; // m-t-a-a-k-j
			}
		}
	}
	return $options;
}

function wtg_parse_forms( $text, $aggregator ) {
	$forms = array();
	$page_counter = 0;

	// remove comments
	$text = preg_replace( '|<!--.*-->|iUms', '', $text );

	// remove javascript
	//$text = preg_replace( '|<script.*</script>|iUms', '', $text );

	while ( $page_counter < strlen($text) ) {
		$form = wtg_get_string_between( '<form', '</form', $text, $page_counter, false, true, true );
		if ( !empty($form) ) {
			$tag_name = '';
			$cur_pos  = 0;
			$form_arr = array( 'fields' => array() );
			while ( $cur_pos < strlen($form) ) {
				$attribs = wtg_get_all_attributes_from_tag( $form, $cur_pos, $tag_name );
				// seems not correct
				//				if ( isset($attribs['name']) )
				//				{
				switch( $tag_name ) {
					case 'form':
						$form_arr[$tag_name] = $attribs;
						break;

					case 'input':
						$form_arr['fields'][] = $attribs;
						break;

					case 'textarea':
						$attribs['value'] = wtg_get_string_between('', '</textarea', $form, $cur_pos, false, false, false);
						$attribs['type'] = 'textarea';
						$form_arr['fields'][] = $attribs;
						break;

					case 'select':
						$attribs['choices'] = wtg_parse_options( $form, $cur_pos );
						$attribs['type'] = 'select';
						$form_arr['fields'][] = $attribs;
						break;
					case 'script':
						$form_arr['fields'][] = $attribs;
						break;
					case 'img':
						if (isset($attribs['src']) )
						{
							$attribs['src']=$attribs['src'];
							$form_arr['fields'][]=$attribs;
						}
						break;
				}
				//				}
				
				// parse captcha for feedage.com
				if($aggregator->name == 'feedage.com' || $aggregator->name == 'jordomedia.com' || $aggregator->name == 'bloglines.com' || $aggregator->name == 'rss-spider.com' || $aggregator->name == 'feedlisting.com' || $aggregator->name == 'blogville.us' || $aggregator->name == 'blogged.com') {
					$src='';
					if($tag_name == 'iframe' && isset($attribs['src'])) {
						$src=$attribs['src'];
					} else if($tag_name == 'script' && isset($attribs['src'])) {
						$u = @parse_url($attribs['src']);
						if($u[query]) {
							list($k, $srcValue)=split("=", $u[query]);
						}
						if($k = 'k' && $srcValue) {
							$src='http://api.recaptcha.net/noscript?k='.$srcValue;
						}
					}
					if($src) {
						list($recaptcha_chalange, $recaptcha_response)=wtg_parse_captcha_feedage($src);
						$form_arr['fields'][] = $recaptcha_chalange;
						$form_arr['fields'][] = $recaptcha_response;
					}
				} else if ($aggregator->name == 'rssnetworkfeedsdirectory.com') { // parse captcha for rssnetworkfeedsdirectory.com
					if($attribs['name'] == 'capt') {
						$recaptcha_response=wtg_parse_captcha_rssnfd();
						$form_arr['fields'][] = $recaptcha_response;
					}
				} else if($aggregator->name == 'rssbuffet.com' || $aggregator->name == 'bloglisting' || $aggregator->name == 'Submitblognow') {
					if($attribs['name'] == 'IMAGEHASH') { 
						if($aggregator->name == 'rssbuffet.com') {
							$img_src="http://www.rssbuffet.com/captcha.php?imagehash=".$attribs['value'];
						} else if ($aggregator->name == 'bloglisting') {
							$img_src="http://www.bloglisting.net/captcha.php?imagehash=".$attribs['value'];
						} else if ($aggregator->name == 'Submitblognow') {
							$img_src="http://www.submitblognow.info/captcha.php?imagehash=".$attribs['value'];
						}
						$recaptcha_response=wtg_parse_captcha_RSSbuffet($img_src);
						$form_arr['fields'][] = $recaptcha_response;
					}
				} else if($aggregator->name == 'solarwarp.net') {
					if($attribs['name'] == 'IMAGEHASH') { 
						$recaptcha_response=wtg_parse_captcha_SolarWarp($attribs['value']);
						$form_arr['fields'][] = $recaptcha_response;
					}
				} else if($aggregator->name == 'rssmountain.com') {
					if($attribs['name'] == 'secure') { 
						$imgsrc="http://www.rssmountain.com/php_captcha.php";
						$recaptcha_response=wtg_parse_captcha_rssmountain($imgsrc);
						$form_arr['fields'][] = $recaptcha_response;
					}
				} else if($aggregator->name == 'blogbunch.com') {
					if($tag_name == 'img' && isset($attribs['src'])) { 
						$recaptcha_response=wtg_parse_captcha_blogbunch($attribs['src']);
						$form_arr['fields'][] = $recaptcha_response;
					}
				} else if($aggregator->name == 'feedcat.net') {
					if($tag_name == 'img' && isset($attribs['src']) && preg_match("/captcha/", $attribs['src'])) { 
							$src='http://www.feedcat.net/'.$attribs['src'];
							$recaptcha_response=wtg_parse_captcha_FeedCat($src);
							$form_arr['fields'][] = $recaptcha_response;
					}
				} else if($aggregator->name == 'rssmicro.com') {
					if($attribs['name'] == 'img_code') { 
						$src="http://www.rssmicro.com/captcha_image.web";
						$recaptcha_response=wtg_parse_captcha_RSSmicro($src);
						$form_arr['fields'][] = $recaptcha_response;
					}
				}  else if($aggregator->name == 'millionrss.com') {
					if($tag_name == 'img' && isset($attribs['src'])) { 
						$src='http://www.millionrss.com/'.$attribs['src'];
						$recaptcha_response=wtg_parse_captcha_millionrss($src);
						$form_arr['fields'][] = $recaptcha_response;
					}
				}
						
				$tag_name = '';
			}
			$forms[] = $form_arr;
		}
	}

	return $forms;
}

define('SEARCH_START_ATTRIBUTE', 1);
define('SEARCH_END_ATTRIBUTE'  , 2);
define('SEARCH_FIND_EQUAL'     , 3);
define('SEARCH_START_VALUE'    , 4);
define('SEARCH_END_VALUE'      , 5);

function wtg_get_all_attributes_from_tag( $txt, &$start_from, &$tag_name ) {
	$retVal = array();
	if ( $tag_name == '' ) {
		// We don't know what tag it is... Discover...
		while( true ) {
			$pos = strpos($txt, '<', $start_from);
			if ( $pos === false ) {
				$start_from = strlen($txt);
				return $retVal;
			}
			if ( $txt{$pos+1} == '/' ) {// Closing tag... Skip till next '>'
				$pos = strpos($txt, '>', $pos);
				if ( $pos === false ) {
					$start_from = strlen($txt);
					return $retVal;
				}
				$start_from = $pos + 1;
			} else {
				$start_from = $pos + 1;
				break;
			}
		}
		for ( $i = $start_from, $tot = strlen($txt); $i < $tot; $i++ ) {
			$start_from = $i;

			if ( wtg_is_space($txt{$i}) )
				break;
			else if ( '>' == $txt{$i} )
				break;
			else if ( '/' == $txt{$i} and '>' == $txt{$i+1} )
				break;

			$tag_name .= $txt{$i};
		}
	}
	$tag_name	= strtolower(trim($tag_name));
	$status		= SEARCH_START_ATTRIBUTE;
	$quote		= '';
	$attribute	= '';
	$value		= '';
	for ( $i = $start_from, $tot = strlen($txt); $i < $tot; $i++ ) {
		switch( $txt{$i} ) {
			// Possible end of tag
			case '>':
				switch( $status ) {
					case SEARCH_END_VALUE:
						if ( !empty($quote) ) {
							$value .= $txt{$i};
							break;
						}
						// else --> fall through
					case SEARCH_START_ATTRIBUTE:
					case SEARCH_START_VALUE:
					case SEARCH_FIND_EQUAL:
					case SEARCH_END_ATTRIBUTE:
						$start_from = $i + 1;
						break 3;
				}
				break;

			// whitespace
			case " ":
			case "\r":
			case "\n":
			case "\t":
				switch( $status ) {
					case SEARCH_START_ATTRIBUTE:
					case SEARCH_START_VALUE:
					case SEARCH_FIND_EQUAL:
						break;

					case SEARCH_END_ATTRIBUTE:
						// we're at the end!
						$status = SEARCH_FIND_EQUAL;
						break;

					case SEARCH_END_VALUE:
						if ( empty($quote) ) { // we reached the end...
							$attribute=strtolower($attribute); 
							$retVal[ $attribute ] = $value;
							$status    = SEARCH_START_ATTRIBUTE;
							$attribute = '';
							$quote     = '';
							$value     = '';
						} else {
							$value .= $txt{$i};
						}
						break;
				}
				break;

			case "'":
			case '"':
				switch( $status ) {
					case SEARCH_START_ATTRIBUTE:  // Wrong place...
						break; // Don't do anything, just continue searching

					case SEARCH_FIND_EQUAL:       // Wrong place...
					case SEARCH_END_ATTRIBUTE:    // Wrong place...
						$status = SEARCH_END_VALUE; // Interpret it as if the '=' is already passed
						$value  = '';
						$quote  = $txt{$i};
						break;

					case SEARCH_START_VALUE:  // Ok, search the end...
						$status = SEARCH_END_VALUE;
						$value  = '';
						$quote  = $txt{$i};
						break;

					case SEARCH_END_VALUE:
						if ( $quote == $txt{$i} and $txt{$i-1} != "\\" ) {
							$attribute=strtolower($attribute);
							$retVal[ $attribute ] = $value;
							$status    = SEARCH_START_ATTRIBUTE;
							$attribute = '';
							$quote     = '';
							$value     = '';
						} else { // escaped quote
							if ( $quote == $txt{$i} and $txt{$i-1} == "\\" )
							$value = substr($value, 0, -1);
							$value .= $txt{$i};
						}
						break;
				}
				break;

			case '=':
				switch( $status ) {
					case SEARCH_START_ATTRIBUTE:  // Wrong place...
					case SEARCH_START_VALUE:
						die('Wrong equal sign!');
						break;

					case SEARCH_FIND_EQUAL:
					case SEARCH_END_ATTRIBUTE:
						$status = SEARCH_START_VALUE;
						$value = '';
						$quote = '';
						break;

					case SEARCH_END_VALUE:
						$value .= $txt{$i};
						break;
				}
				break;

			default:
				switch( $status ) {
					case SEARCH_START_ATTRIBUTE:
						$status    = SEARCH_END_ATTRIBUTE;
						$attribute = $txt{$i};
						$value     = '';
						$quote     = '';
						break;

					case SEARCH_START_VALUE:
						$status    = SEARCH_END_VALUE;
						$value     = $txt{$i};
						$quote     = '';
						break;

					case SEARCH_FIND_EQUAL:
						$attribute=strtolower($attribute);
						if ( !empty($attribute) )
							$retVal[$attribute] = $attribute;
						$status    = SEARCH_END_ATTRIBUTE;
						$attribute = $txt{$i};
						$value     = '';
						$quote     = '';
						break;

					case SEARCH_END_ATTRIBUTE:
						$attribute .= $txt{$i};
						break;

					case SEARCH_END_VALUE:
						$value .= $txt{$i};
						break;
				}
				break;
		}
	}
	if ( $status == SEARCH_END_VALUE and !empty($attribute) )
		$retVal[$attribute] = $value;

	return $retVal;
}

function wtg_get_url_relative( $url, $lrs ) {
	$url  = parse_url($url);
	$path = explode  ('/', $url['path']);
	$lrs  = trim($lrs);
	$new_url = $url['scheme'] . '://';
	if ( !empty($url['user']) ) {
		$new_url .= $url['user'];
		if ( !empty($url['password']) )
			$new_url .= ':' . $url['password'];
		$new_url .= '@';
	}
	$new_url .= $url['host'];
	if ( $lrs{0} == '/' ) {
		// Full path...
		return $new_url . $lrs;
	} else if ( strpos($lrs, '://') !== false && strpos(substr($lrs, 0,  strpos($lrs, '://')), '?') === false ) {
		return $lrs;
	} else {
		// handle subdirectory in given URL
		// if URL like ../directory/submit.php
		if(preg_match('/^(\.\.)\//', $lrs) || preg_match('/^(\.)\//', $lrs)) {
			$lrs = preg_replace('/^(\.\.)\//', '', $lrs );
			$lrs = preg_replace('/^(\.)\//', '', $lrs );
		} else {
			// Like http://www.test.com/directory/
			// It will not check if form action url contains directory like /directory/submit.php
			 if(!preg_match("/\//", $lrs)){
				$path=substr($url['path'], 0, strrpos($url['path'], '/'));
				if($path) {
					$new_url.=$path;
				}
			 }
		 }
		
		if ( substr($new_url, -1) == '/' )
			return $new_url .= $lrs;
		else
			return $new_url .= '/' . $lrs;
	}
}

function wtg_build_postvars( $parsed_form, &$postvars, $defaults=array(), &$postfiles ) {
	$postvars = array();
	$postfiles = array();

	if ( is_null($parsed_form) )
		return;

	foreach( $parsed_form['fields'] as $idx => $field ) {
		if ( !isset($field['type']) )
			$field['type'] = 'text';

		switch( strtolower(trim($field['type'])) ) {
			case 'file':
				if ( isset($defaults[ $field['name'] ]) )
					$postfiles[ $field['name'] ][] = $defaults[ $field['name'] ];
				else
					$postfiles[ $field['name'] ][] = '';
				break;

			case 'radio':
			case 'checkbox':
				$is_checked = false;
				foreach( $field as $k => $v ) {
					if ( strtolower(trim($k)) == 'checked' ) {
						$is_checked = true;
						break;
					}
				}

				if ( isset($defaults[$field['name']]) ) {
					$postvars[ $field['name'] ] = array($defaults[$field['name']]);
				} else if ( $is_checked ) {
					if ( strtolower(trim($field['type'])) == 'radio' ) {
						$postvars[ $field['name'] ] = array( isset($field['value']) ? $field['value'] : 'on' );
					} else {
						$postvars[ $field['name'] ][] = isset($field['value']) ? $field['value'] : 'on';
					}
				}
				break;

			case 'select':
				if ( isset($field['choices']) ) {
					// Get the selected choice
					$is_multi_select = false;
					foreach( $field as $k => $v ) {
						if ( strtolower(trim($k)) == 'multiple' ) {
							$is_multi_select = true;
							break;
						}
					}
					$is_selected = false;
					$first_option = null;
					foreach( $field['choices'] as $optgroup => $options ) {
						foreach( $options as $idx => $option ) {
							if ( is_null($first_option) )
								$first_option = $option;

							foreach( $option as $k => $v ) {
								if ( strtolower(trim($k)) == 'selected' ) {
									if ( !isset($defaults[$field['name']]) )
										$postvars[ $field['name'] ][] = isset($field['value']) ? $field['value'] : $field['text'];
									else
										$postvars[ $field['name'] ] = array($defaults[$field['name']]);

									$is_selected = true;

									// Stop if we don't allow multiple selections
									if ( !$is_multi_select )
										break 3;
								}
							}
						}
					}

					if ( !$is_selected ) {
						if ( isset($defaults[$field['name']]) )
							$postvars[ $field['name'] ] = array($defaults[$field['name']]);
						else if ( !is_null($first_option) )
							$postvars[ $field['name'] ][] = isset($first_option['value']) ? $first_option['value'] : $first_option['text'];
						else
							$postvars[ $field['name'] ][] = '';
					}

					break;
				}
				// else --> fall down

			case 'hidden':
			case 'text':
			case 'password':
			case 'input':
			case 'textarea':
			case 'image':
			case 'submit':
				if (isset($field['name'])){
					if ( !isset($defaults[$field['name']]) )
						$postvars[ $field['name'] ][] = isset($field['value']) ? $field['value'] : '';
					else
						$postvars[ $field['name'] ] = array($defaults[$field['name']]);
				}
				break;

			default:
				//				var_dump($field);
				//				echo 'Wrong field' ;
				//				break;
		} // switch
	} // foreach
}


// parse captcha
function wtg_parse_captcha_feedage($img_src) {
	if($img_src) {
		$html=wtg_fetch_url($img_src, $returned_headers, $last_url);
		preg_match_all('/<img[^>]+>/i',$html, $result); 
		$img = array();
		$c=0;
		foreach( $result as $img_tag)
		{
			preg_match_all('/(id|src)="([^"]*)"/i',$img_tag[$c], $img);
			$c++;
		}
		//print_r($img);
		if($img[2][0]) {
			$img_fn="http://api.recaptcha.net/".$img[2][0];
		}
		$u = @parse_url($img[2][0]);
		if($u[query]) {
			//print $u[query];
			list($c, $recaptcha_challenge_field)=split("=", $u[query]);
			if($c == 'c') {
				$recaptcha_chalange['value']=$recaptcha_challenge_field;
				$recaptcha_chalange['type']='hidden';
				$recaptcha_chalange['name']='recaptcha_challenge_field';
			}
		}

		$image=wtg_get_captcha_img($img_fn);
		if($image) {
			$results=wtg_get_captcha_result($image);
			if($results) {
				$recaptcha_response['value']=$results;
				$recaptcha_response['type']='hidden';
				$recaptcha_response['name']='recaptcha_response_field';
			}
			
			if(file_exists($image)) {
				unlink($image);
			}
		}
	}
	return array($recaptcha_chalange, $recaptcha_response);
}

function wtg_parse_captcha_rssnfd () {
	$img_src='http://www.rssnetworkfeedsdirectory.com/captcha_img.php';
	$image=wtg_get_captcha_img($img_src);
	if($image) {
		$results=wtg_get_captcha_result($image);
		if($results) {
			$recaptcha_response['value']=$results;
			$recaptcha_response['type']='text';
			$recaptcha_response['name']='capt';
		}
		if(file_exists($image)) {
			unlink($image);
		}
	}
	return $recaptcha_response;
}

function wtg_parse_captcha_RSSbuffet($img_src) {
	if($img_src) {
		$image=wtg_get_captcha_img($img_src);
		if($image) {
			$results=wtg_get_captcha_result($image);
			if($results) {
				$recaptcha_response['value']=$results;
				$recaptcha_response['type']='text';
				$recaptcha_response['name']='CAPTCHA';
			}
			if(file_exists($image)) {
				unlink($image);
			}
		}
	}
	return $recaptcha_response;
}

function wtg_parse_captcha_SolarWarp ($value) {
	if($value) {
		$img_fn="http://www.solarwarp.net/captcha.php?imagehash=".$value;
		$image=wtg_get_captcha_img($img_fn);
		if($image) {
			$results=wtg_get_captcha_result($image);
			if($results) {
				$recaptcha_response['value']=$results;
				$recaptcha_response['type']='text';
				$recaptcha_response['name']='CAPTCHA';
			}
			if(file_exists($image)) {
				unlink($image);
			}
		}
	}
	return $recaptcha_response;
}

function wtg_parse_captcha_rssmountain($img_src) {
	if($img_src) {
		$image=wtg_get_captcha_img($img_src);
		if($image) {
			$results=wtg_get_captcha_result($image);
			if($results) {
				$recaptcha_response['value']=$results;
				$recaptcha_response['type']='text';
				$recaptcha_response['name']='secure';
			}
			if(file_exists($image)) {
				unlink($image);
			}
		}
	}
	return $recaptcha_response;
}

function wtg_parse_captcha_blogbunch($img_src) {
	if($img_src) {
		$image=wtg_get_captcha_img($img_src);
		if($image) {
			$results=wtg_get_captcha_result($image);
			if($results) {
				$recaptcha_response['value']=$results;
				$recaptcha_response['type']='text';
				$recaptcha_response['name']='captcha_input';
			}
			if(file_exists($image)) {
				unlink($image);
			}
		}
	}
	return $recaptcha_response;
}

function wtg_parse_captcha_FeedCat($img_src) {
	if($img_src) {
		$image=wtg_get_captcha_img($img_src);
		if($image) {
			$results=wtg_get_captcha_result($image);
			if($results) {
				$recaptcha_response['value']=$results;
				$recaptcha_response['type']='text';
				$recaptcha_response['name']='captcha';
			}
			if(file_exists($image)) {
				unlink($image);
			}
		}
	}
	return $recaptcha_response;
}

function wtg_parse_captcha_RSSmicro ($img_src) {
	if($img_src) {
		$image=wtg_get_captcha_img($img_src);
		if($image) {
			$results=wtg_get_captcha_result($image);
			if($results) {
				$recaptcha_response['value']=$results;
				$recaptcha_response['type']='text';
				$recaptcha_response['name']='img_code';
			}
			if(file_exists($image)) {
				unlink($image);
			}
		}
	}
	return $recaptcha_response;
}


function wtg_parse_captcha_millionrss ($img_src) {
	if($img_src) {
		$image=wtg_get_captcha_img($img_src);
		if($image) {
			$results=wtg_get_captcha_result($image);
			if($results) {
				$recaptcha_response['value']=$results;
				$recaptcha_response['type']='text';
				$recaptcha_response['name']='security_code';
			}
			if(file_exists($image)) {
				unlink($image);
			}
		}
	}
	return $recaptcha_response;
}

function wtg_get_captcha_result($image) {
	$cp = new WTG_Captcha();
	$cp->initDB();
	$captcha_info = $cp->get_enabled_captchaDB();
	if($captcha_info->name == 'decaptcher.com') {
		$results = wtg_get_poster_decaptcher($captcha_info->user, $captcha_info->password, $image);
	} else if($captcha_info->name == 'deathbycaptcha') {
		$results = wtg_get_captcha_result_by_deathbycaptcha($captcha_info->user, $captcha_info->password, $image);
	} else if($captcha_info->name == 'bypasscaptcha.com') {
		$results = wtg_submit_captcha($captcha_info->key,  $image);
	}
	return $results;
}