Пример #1
0
function wpr_post($camp_id, $keyword="", $retry=1, $manual=0) {
	global $wpdb, $wpr_table_campaigns, $wpr_table_posts, $wpr_table_errors;

	if($retry > 0) {$retrymsg = " <b>(".__("Retry","wprobot")." $retry)</b>";} else {$retrymsg = "";}	
	$time = current_time('mysql');	
	$errors = array();
	
    $options = unserialize(get_option("wpr_options"));	
	$result = $wpdb->get_row("SELECT * FROM " . $wpr_table_campaigns . " WHERE id = '$camp_id'"); 
	if($result->pause == 1 && $manual == 0) {return false;}

	// select KEYWORD
	$keywords = unserialize($result->keywords);
	if(!$keyword) {
		if(empty($keywords)) {
			// SAVE and DISPLAY error
			$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
			$esql .= " ( '$camp_id', '$keyword', '', 'Inactive', ".__("'Post skipped because no keywords were found in the campaign.$retrymsg'", 'wprobot').", '$time' );";
			$results = $wpdb->query($esql);			
			return false;		
		}			
		// REMOVE KEYWORDS WHERE SKIPPED = 5 (better way without loop?)
		$keywords2 = $keywords;
		foreach($keywords as $key => $keyword) {
			if($keyword["skipped"] >= $options['wpr_err_disable'] && !$keyword["feed"]) {
				unset($keywords2[$key]);
			}
		}
		//echo "<pre>";print_r($keywords2);echo "</pre>";	
		//$keywords = array_values($keywords);		
		$rnd = array_rand($keywords2);
		$keyword = $keywords[$rnd][0];
		if($rnd === "" || $keyword === "" && !empty($keyword["feed"]) || !is_numeric($rnd)) {
			// SAVE and DISPLAY error
			$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
			$esql .= " ( '$camp_id', '$keyword', '', 'Inactive', ".__("'No active keywords or feeds for this campaign, possibly because they were disabled due to repeated errors. Check the status and reenable them on the campaign detail page.$retrymsg'", 'wprobot').", '$time' );";
			$results = $wpdb->query($esql);			
			return false;		
		}		
	} else {
		foreach($keywords as $key => $kw) {
			if($kw[0] == $keyword) {
				$rnd = $key;
			}
		}
	}
	$keywordsbackup = $keywords[$rnd];

	// select CATEGORY
	$categories = unserialize($result->categories);
	if(!empty($categories[0]["id"])) {$categories = wpr_transform_cats($categories);}
	$catarray = array();
	if(count($categories) == 1) {
		foreach($categories[0] as $cats) {$catarray[] = $cats["id"];}		
		//$category = $categories[0]["id"];
	} else {
		foreach($categories[$rnd] as $cats) {$catarray[] = $cats["id"];}
		//$category = $categories[$rnd]["id"];	
	}	
	
	// select TEMPLATE
	$templates = unserialize($result->templates);
	$i = 1;
	foreach($templates as $tchance) {
		$tch[$i] = $templates[$i]["chance"];
		$i++;
	}
	
	$random = rand(1,100);
	foreach($tch as $name => $chance){
		$luck += $chance;
		if($random <= $luck && empty($templatenum)){
			$templatenum = $name;
		}
	} 	
	$template = $templates[$templatenum]["content"];
	
	$templateexcerpt = substr(strip_tags($template), 0, 130);
	$templateusedmsg = '<a target="_blank" class="tooltip" href="#">?<span>'.__('The template used for this post was: <strong>Post Template ',"wprobot").$templatenum.__('</strong>, starting with:<br/>',"wprobot").$templateexcerpt.__('<br/><br/><strong>If there was an error please check the associated module messages directly below this one!</strong>',"wprobot") .'</span></a>';

	// Wordpress action hook
	do_action('wpr_before_post', $insert); 	
	
	$content = $template;//echo $template."<br>";
	$noqkeyword = str_replace('"', '', $keyword);
	$content = str_replace("{keyword}", $noqkeyword, $content);
	$content = str_replace("{Keyword}", ucwords($noqkeyword), $content);	
	$content = str_replace("{title}", $title, $content);	
	$catreplace = get_category_link( $catarray[0] );
	if (!is_wp_error($catreplace)) {
	$content = str_replace("{catlink}", $catreplace, $content);	
	} else {$content = str_replace("{catlink}", "", $content);	}
	
	// AMAZON
	preg_match_all('#\{amazonlist(.*)\}#iU', $content, $matches, PREG_SET_ORDER);
	if ($matches) {
		foreach($matches as $match) {
			$match[1] = substr($match[1], 1);
			if($match[1]) {$amanum = $match[1];} else {$amanum = 1;}
			$amalist = wpr_amazon_getlist($keywords[$rnd][0],$amanum);
			if(isset($amalist["error"]) && is_array($amalist)) {$errors[] = $amalist["error"];$content = str_replace($match[0], "", $content);}
			$content = str_replace($match[0], $amalist, $content);				
		}
	}		
	// THUMBNAIL
	preg_match_all('#\{thumbnail(.*)\}#iU', $content, $matches, PREG_SET_ORDER);
	if ($matches) {
		foreach($matches as $match) {
			$match[1] = substr($match[1], 1);
			if($match[1]) {$tkw = $match[1];} else {$tkw = $keywords[$rnd][0];}
			$thumbnail = wpr_flickr_getthumbnail($tkw);
			if(!empty($thumbnail["error"])) {$errors[] = $thumbnail["error"];}
			$content = str_replace($match[0], $thumbnail[0]["content"], $content);				
		}
	}	
	// RANDOM Tags
	$content = wpr_random_tags($content);
	
	$title = $templates[$templatenum]["title"];
	$noqkeyword = str_replace('"', '', $keyword);
	$title = str_replace("{keyword}", $noqkeyword, $title);
	$title = str_replace("{Keyword}", ucwords($noqkeyword), $title);
	if(!empty($keywords[$rnd]["alternative"])) {
		$ll = 1;
		foreach($keywords[$rnd]["alternative"] as $alternative) {
			$content = str_replace("{keyword$ll}", $alternative, $content);	
			$title = str_replace("{keyword$ll}", $alternative, $title);
			$ll++;
		}
	}
	
	// RANDOM Tags
	$title = wpr_random_tags($title);

	$raz[0] = "{";$raz[1] = "}";
	preg_match_all("/\\".$raz[0]."[^\\".$raz[1]."]+\\".$raz[1]."/s", $content, $matches);
	$counts = array_count_values  (  $matches[0]  ); //echo $counts["{amazon}"];		
	$wpr_modulesnum = count($matches[0]);
	if($wpr_modulesnum <= 0) {
		// SAVE and DISPLAY error
		$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
		$esql .= " ( '$camp_id', '$keyword', '', 'Inactive', ".__("'Post skipped because no modules were found in the template.$retrymsg'", 'wprobot').", '$time' );";
		$results = $wpdb->query($esql);			
		return false;		
	}		

	$usql = "INSERT INTO ".$wpr_table_posts." ( campaign, keyword, module, unique_id, time ) VALUES";
	// Get Content for each Module
	// ["content"] = Content of the item (replaced module template code)
	// ["title"] = Title of the item (i.e. Product title)
	// ["unique"] = Unique ID (i.e. ASIN)
	// ["comments"] = Possible comment content of the item (i.e. reviews)
	$contents = array();
	$commentsarray = array();
	$titleerror = 0;
	$duplicatecount = 0;
	$errorcount = 0;
	
	foreach($counts as $module => $count) {
		$modulname = str_replace(array("{","}"), "", $module);
		$function = "wpr_".$modulname."post";
		
		$optional = "";$comments = "";
		switch ($modulname) {
			case "amazon":
				$optional = array($result->amazon_department,$keywords[$rnd]["node"]);
				break;
			case "ebay":
				$optional = $result->ebay_cat;
				break;
			case "flickr":			
				$comments = $templates[$templatenum]["comments"]["$modulname"];
				break;
			case "youtube":
				$comments = $templates[$templatenum]["comments"]["$modulname"];
				break;
			case "yahooanswers":
				$optional = $result->yahoo_cat;
				$comments = $templates[$templatenum]["comments"]["$modulname"];
				break;	
			case "rss":
				$optional = $keywords[$rnd]["feed"];
				break;							
		}
		
		// GET CONTENT
		if(function_exists($function)) {
			$contents["$modulname"] = $function($keyword, $count, $keywords[$rnd][1]["$modulname"], $optional, $comments);
			if(!empty($contents["$modulname"]["error"])) {
				$errors[] = $contents["$modulname"]["error"];
				$errorcount = $errorcount + 1 * $counts["{".$modulname."}"];
			}
		} else {
			$title = str_replace("{".$modulname."title}", "", $title);
			$errors[] = array("module" => ucwords($modulname), "reason" => "Not Installed", "message" => __("$modulname is not installed on this weblog and has been skipped.", 'wprobot'));						
			$errorcount = $errorcount + 1;
		}
		
		// CONTENT REPLACE
		$$modulname = 0;
		$dupl = 0;
	
		foreach ($matches[0] as $element) {
			if($element=="{".$modulname."}") {
				$unique = $contents["$modulname"][$$modulname]["unique"];
				if($unique != "" || $modulname == "ebay" ) {	
					$dcheck = wpr_check_unique($unique);
					//echo "CHECK".$dcheck;
					if($options['wpr_check_unique_old'] == "Yes") {$dcheck2 = wpr_check_unique_old($contents["$modulname"][$$modulname]["title"]);} else {$dcheck2 = false;}
					if($dcheck == false && $dcheck2 == false) {
						$content = preg_replace('/\{'.$modulname.'\}/', $contents["$modulname"][$$modulname]["content"], $content, 1);
						if(!isset($contents["$modulname"]["error"]) ) {
							$unique = $wpdb->escape($unique);
							$ekeyword = $wpdb->escape($keyword);
							$usql .= " ( '$camp_id', '$ekeyword', '$modulname', '$unique', '$time' ),";
						}
						if($templates[$templatenum]["comments"]["$modulname"] == 1) {$commentsarray[] = $contents["$modulname"][$$modulname]["comments"];}
					} else {
						// DUPLICATE POST
						$dupl = 1;
						$duplicatecount++;
						$content = preg_replace('/\{'.$modulname.'\}/', "", $content, 1);	
						$errors[] = array("module" => ucwords($modulname), "reason" => "Duplicate", "message" => __("Skipping ", 'wprobot').ucwords($modulname).__(" module because the content has already been posted.", 'wprobot'));						
						$errorcount = $errorcount + 1;
					}
				}
				
				//echo "------------DEBUG START------------<br/>";
				//echo $dupl." DUPLICATE<br/>";
				//echo $contents["$modulname"]["error"]." ERROR<br/>";
				//echo $counts["{".$modulname."}"]." FIRST COUNT<br/>";
				//echo $$modulname." SECOND COUNT<br/>";
				// TITLE REPLACE	
				$titlecheck = strpos($title, "{".$modulname."title}");
				$titlecheck2 = strpos($title, "{title}");				
				$modulecheckvar = $$modulname + 1;
				if ($titlecheck !== false || $titlecheck2 !== false) {
					if ($counts["{".$modulname."}"] > $modulecheckvar && $dupl == 1 || $counts["{".$modulname."}"] > $modulecheckvar && !empty($contents["$modulname"]["error"])) {
						// Dont Replace Title because there is another title module item
					} elseif($counts["{".$modulname."}"] <= $modulecheckvar && $dupl == 1) {
						// Title Duplicate					
						$titleduplicate = 1;		
					} elseif($counts["{".$modulname."}"] <= $modulecheckvar && !empty($contents["$modulname"]["error"]) || $counts["{".$modulname."}"] <= $modulecheckvar && empty($contents["$modulname"][0]["title"])) {
						// Title Error
						$titleerror = 1;
					} else {
						// Replace Title
						$title = str_replace("{".$modulname."title}", $contents["$modulname"][$$modulname]["title"], $title);
						$title = str_replace("{title}", $contents["$modulname"][$$modulname]["title"], $title);	
					}
				}
				$$modulname++;				
			}		
		}	

		if($contents["$modulname"]["error"]["reason"] == "IncNum") {$incnum = 1;} else {$incnum = 0;}
		// INCREASE NUMS
		if(empty($contents["$modulname"]["error"]) || $contents["$modulname"]["error"]["reason"] == "IncNum") { // don't increase NUMs if ERROR for module
			$keywords[$rnd][1]["$modulname"] = $keywords[$rnd][1]["$modulname"] + $$modulname;

			// RESET POST COUNT
			if($keywords[$rnd][1]["$modulname"] > $options['wpr_resetcount'] && $options['wpr_resetcount'] != "no") {$keywords[$rnd][1]["$modulname"] = 0;}
			if($modulename == "ebay" && $keywords[$rnd][1]["$modulname"] > 50) {$keywords[$rnd][1]["$modulname"] = 0;}		
		}	
		$content = str_replace("{".$modulname."}","",$content);		
	}

	// check ERRORS
	//$errorsnum = count($errors);	
	$errorsnum = $errorcount;	
	$skip = 0;
	if(!empty($keywords[$rnd]["feed"])) {$errkeyword = "Feed";} elseif(!empty($keywords[$rnd]["node"])) {$errkeyword = "Node:".$keywords[$rnd]["node"];} else {$errkeyword = $wpdb->escape($keyword);}
	
	// EXCLUDE KEYWORDS Check $options["wpr_global_exclude"]
	$excludeskip = 0;
	$excludes = unserialize($result->excludekws);
	
	$globals = str_replace("\r", "", $options["wpr_global_exclude"]);
	$globals = explode("\n", $globals);
	$excludes = array_merge($excludes, $globals);
	
	if(!empty($excludes)) {
		foreach($excludes as $exclude) {
			if($exclude != "" && $exclude != " " ) {
				$excheck = stripos($content, $exclude);
				$texcheck = stripos($title, $exclude);
				if($excheck === false && $texcheck === false) {
				} else {
					$excludeskip = 1;	$errors = array();
					$errors[] = array("module" => "", "reason" => "Exclude", "message" => __("Skipping post because exclude keyword $exclude was found.$retrymsg $templateusedmsg", 'wprobot'), "time" => "$time");
					break;
				}
			}
		}
	}
	
	if($excludeskip == 0) {
		// MARK KEYWORD AS yellow, orange, etc
		$wpr_modulessuccess = $wpr_modulesnum - $errorsnum;
		$duplsuccess = $wpr_modulesnum - $duplicatecount;
		if($duplicatecount > $options["wpr_err_maxerr"] || $duplsuccess < $options["wpr_err_minmod"] || $titleduplicate == 1) { // DUPLICATE ERROR - WiTHOUT skipped INCREASE
			$errors[] = array("module" => "", "reason" => "Duplicate Content", "message" => __("Skipping post to prevent duplicate content.", 'wprobot')."$retrymsg $templateusedmsg", "time" => "$time");	
			$skip = 1;	
		} elseif($titleerror == 1) { 			
			if($incnum != 1) {$keywords[$rnd] = $keywordsbackup;}
			$keywords[$rnd]["skipped"] = $keywords[$rnd]["skipped"] + 1;
			$errors[] = array("module" => "", "reason" => "Post skipped", "message" => __("Skipping post because the main module (title module) returned an error.", 'wprobot')."$retrymsg $templateusedmsg", "time" => "$time");	
			$skip = 1;	
		} elseif($errorsnum > $options["wpr_err_maxerr"] || $wpr_modulessuccess < $options["wpr_err_minmod"]) {
			if($incnum != 1) {$keywords[$rnd] = $keywordsbackup;}		
			$keywords[$rnd]["skipped"] = $keywords[$rnd]["skipped"] + 1;
			$errors[] = array("module" => "", "reason" => "Post skipped", "message" => __("Skipping post because too many module errors were encountered.", 'wprobot')."$retrymsg $templateusedmsg", "time" => "$time");	
			$skip = 1;
		} else {
			$keywords[$rnd]["skipped"] = 0;	
		}	
	}		
		
	// SAVE ERRORS
	if($errorsnum > 0 || $excludeskip == 1 || $titleerror == 1) {
		$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
		foreach($errors as $error) {
			$error["message"] = $wpdb->escape($error["message"]);
			$esql .= " ( '$camp_id', '$errkeyword', '".$error["module"]."', '".$error["reason"]."', '".$error["message"]."', '$time' ),";
		}
		$esql = substr_replace($esql ,";",-1);
		$results = $wpdb->query($esql);		
	}		
	
	// SKIP if EXCLUDE found, errors > MAXERRORS or modules < MINMODULES
	if($excludeskip == 1 || $skip == 1) {
		// - update campaign entry with new NUMS	

		$keywords = serialize($keywords);
		$keywords = $wpdb->escape($keywords);
		$sql = "UPDATE " . $wpr_table_campaigns . " SET `keywords` = '".$keywords."' WHERE `id` = '".$camp_id."'";
		$results = $wpdb->query($sql);		
		return false;
	}
	
    // SAVE IMAGES
	if($options['wpr_save_images'] == "Yes") {

		$allimages = wpr_findimages($content);
		$imageurls = $allimages[2];
		//echo "<pre>";print_r($allimages[2]);echo "</pre>";
		
		if(sizeof($imageurls)) {
			foreach($imageurls as $oldurl) {
				if(strpos($oldurl, plugin_basename( dirname(__FILE__) )) === false) {
					$newurl = wpr_saveimage($oldurl,$keyword);
					if($newurl) {$content = str_replace($oldurl, $newurl, $content);}	
				}
			} 
		}		
    }	
	
	// TRANSLATION
	if(function_exists("wpr_translate_partial")) {
		$title = wpr_translate_partial($title);
	}	
	$translation = unserialize($result->translation);
	if($translation["chance"] >= rand(1,100)) {
		if($translation["from"] != "no" && $translation["to1"] != "no") {
			$translationcontent = wpr_translate($content,$translation["from"],$translation["to1"],$translation["to2"],$translation["to3"]);
			//print_r($translationcontent);
			if($options["wpr_trans_titles"] == "yes") {
				$translationtitle = wpr_translate($title,$translation["from"],$translation["to1"],$translation["to2"],$translation["to3"]);
			}
			if(!empty($translationcontent["error"]["reason"])) {
				$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
				$esql .= " ( '$camp_id', '$errkeyword', 'Translation', '".$translationcontent["error"]["reason"]."', '".$translationcontent["error"]["message"]."', '$time' );";
				$results = $wpdb->query($esql);		
				if($options['wpr_trans_fail'] == "skip") {
					$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
					$esql .= " ( '$camp_id', '$errkeyword', '', 'Post skipped', '".__("Skipping post because translation failed ","wprobot")."$retrymsg $templateusedmsg', '$time' );";
					$results = $wpdb->query($esql);		
					return false;
				}
			} elseif(empty($translationcontent)) {
				$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
				$esql .= " ( '$camp_id', '$errkeyword', 'Translation', 'Translation Failed', '".__("The post could not be translated.","wprobot")."', '$time' );";
				$results = $wpdb->query($esql);		
				if($options['wpr_trans_fail'] == "skip") {
					$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
					$esql .= " ( '$camp_id', '$errkeyword', '', 'Post skipped', '".__("Skipping post because translation failed ","wprobot")."$retrymsg $templateusedmsg', '$time' );";
					$results = $wpdb->query($esql);		
					return false;
				}
			} else {
				$content = $translationcontent;
				if($options["wpr_trans_titles"] == "yes") {$title = $translationtitle;}
				if($translation["comments"] == 1) {$transcomments = 1;} else {$transcomments = 0;}
			}
		}
	}

	$yahoocat = unserialize($result->yahoo_cat);	
	if(!is_array($yahoocat)) {
		$yahoocat = array();
		$yahoocat["rw"] = 0;
		$yahoocat["ps"] = $result->yahoo_cat;
		$yahoocat["a"] = "";
	}
	
	// REWRITE
	if($yahoocat["rw"] == 1) {
		$rewriter = array();
		if($options['wpr_rewrite_active_tbs'] == 1 || $options['wpr_rewrite_active'] == "tbs" || $options['wpr_rewrite_active'] == "both") {
			$rewriter[] = "tbs";
		} if($options['wpr_rewrite_active_sc'] == 1 || $options['wpr_rewrite_active'] == "sc" || $options['wpr_rewrite_active'] == "both") {
			$rewriter[] = "sc";
		} if($options['wpr_rewrite_active_schimp'] == 1 || $options['wpr_rewrite_active'] == "schimp" || $options['wpr_rewrite_active'] == "both") {
			$rewriter[] = "schimp";
		} if($options['wpr_rewrite_active_ucg'] == 1 || $options['wpr_rewrite_active'] == "Yes" || $options['wpr_rewrite_active'] == "both") {
			$rewriter[] = "ucg";
		} if($options['wpr_rewrite_active_sr'] == 1) {
			$rewriter[] = "sr";
		} if($options['wpr_rewrite_active_wai'] == 1) {
			$rewriter[] = "wai";
		}
		
		$rand_key = array_rand($rewriter);
		if($rewriter[$rand_key] == "tbs") {
			$options['wpr_rewrite_active'] = "tbs";
		} elseif($rewriter[$rand_key] == "sc") {
			$options['wpr_rewrite_active'] = "sc";
		} elseif($rewriter[$rand_key] == "schimp") {
			$options['wpr_rewrite_active'] = "schimp";
		} elseif($rewriter[$rand_key] == "ucg") {
			$options['wpr_rewrite_active'] = "Yes";
		} elseif($rewriter[$rand_key] == "sr") {
			$options['wpr_rewrite_active'] = "sr";
		} elseif($rewriter[$rand_key] == "wai") {
			$options['wpr_rewrite_active'] = "wai";
		}

		//print_r($rewriter);echo "Rewriter: ".$rand_key . " ". $options['wpr_rewrite_active'] . "\n";
	}

	if($options['wpr_rewrite_active'] == "Yes" && $yahoocat["rw"] == 1) {
		// UCG
		if(empty($options['wpr_rewrite_email']) || empty($options['wpr_rewrite_key'])) {
			$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
			$esql .= " ( '$camp_id', '$errkeyword', 'UCG Rewriter', 'UCG Rewriter', 'You need to enter your API Key and Email in the Options!', '$time' );";
			$results = $wpdb->query($esql);		
		} else {
			//echo "<br/><br/>-------orig-------------<br/><br/>".$content . "<br/><br/>---------rewrite----------<br/><br/>";//////////
			$rewrite = wpr_rewrite($content,$options['wpr_rewrite_level']);
			//echo $rewrite . "<br/><br/>--------------------<br/><br/>";	//////////
			if(!empty($rewrite["error"]["reason"])) {
				$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
				$esql .= " ( '$camp_id', '$errkeyword', 'UCG Rewriter', '".$rewrite["error"]["reason"]."', '".$rewrite["error"]["message"]."', '$time' );";
				$results = $wpdb->query($esql);	
			} else {
				$content = $rewrite;
			}
		}
	} elseif($options['wpr_rewrite_active'] == "tbs" && $yahoocat["rw"] == 1) {
		// TBS
		if(empty($options['wpr_tbs_rewrite_pw']) || empty($options['wpr_tbs_rewrite_email'])) {
			$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
			$esql .= " ( '$camp_id', '$errkeyword', 'TheBestSpinner', 'TheBestSpinner', 'You need to enter your TheBestSpinner email and password in the Options!', '$time' );";
			$results = $wpdb->query($esql);		
		} else {
			//echo "<br/><br/>-------orig-------------<br/><br/>".$content . "<br/><br/>---------rewrite----------<br/><br/>";//////////
			$rewrite = wpr_tbs_rewrite($content,$options['wpr_tbs_rewrite_email'],$options['wpr_tbs_rewrite_pw'],$options['wpr_tbs_spintxt'],$options['wpr_tbs_quality'],$keyword,$options['wpr_rewrite_protected']);
			//echo $rewrite . "<br/><br/>--------------------<br/><br/>";	//////////
			if(!empty($rewrite["error"]["reason"])) {
				$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
				$esql .= " ( '$camp_id', '$errkeyword', 'TheBestSpinner', '".$rewrite["error"]["reason"]."', '".$rewrite["error"]["message"]."', '$time' );";
				$results = $wpdb->query($esql);	
			} else {			
				$content = $rewrite;
			//echo "<br/><br/>-------CONTENT-------------<br/><br/>".$content . "<br/><br/>---------CONTENT----------<br/><br/>";//////////				
			}	

			// REWRITE TITLE
			if($options['wpr_tbs_rewrite_title'] == "Yes") {			
				$rewritetitle = wpr_tbs_rewrite($title,$options['wpr_tbs_rewrite_email'],$options['wpr_tbs_rewrite_pw'],$options['wpr_tbs_spintxt'],$options['wpr_tbs_quality'],$keyword,$options['wpr_rewrite_protected']);
				if(!empty($rewritetitle["error"]["reason"])) {
					$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
					$esql .= " ( '$camp_id', '$errkeyword', 'TheBestSpinner', '".$rewritetitle["error"]["reason"]."', '".$rewritetitle["error"]["message"]."', '$time' );";
					$results = $wpdb->query($esql);	
				} else {
					$title = $rewritetitle;
				}	
			}	
		}
	} elseif($options['wpr_rewrite_active'] == "sc" && $yahoocat["rw"] == 1) {
		// Spinnerchief
		if(empty($options['wpr_sc_rewrite_pw']) || empty($options['wpr_sc_rewrite_email'])) {
			$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
			$esql .= " ( '$camp_id', '$errkeyword', 'SpinnerChief', 'SpinnerChief', 'You need to enter your SpinnerChief username and password in the Options!', '$time' );";
			$results = $wpdb->query($esql);		
		} else {
			//echo "<br/><br/>-------orig-------------<br/><br/><div>".$content . "</div><br/><br/>---------rewrite----------<br/><br/>";//////////
			$rewrite = wpr_sc_rewrite($content,$options['wpr_sc_rewrite_email'],$options['wpr_sc_rewrite_pw'],$options['wpr_sc_quality'],$keyword,$options['wpr_rewrite_protected'],$options['wpr_sc_port'], $options['wpr_sc_thesaurus']);
			//echo "<div>".$rewrite . "</div><br/><br/>--------------------<br/><br/>";	//////////
			if(!empty($rewrite["error"]["reason"])) {
				$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
				$esql .= " ( '$camp_id', '$errkeyword', 'SpinnerChief', '".$rewrite["error"]["reason"]."', '".$wpdb->escape($rewrite["error"]["message"])."', '$time' );";
				$results = $wpdb->query($esql);	
			} else {			
				$content = $rewrite;
			//echo "<br/><br/>-------CONTENT-------------<br/><br/>".$content . "<br/><br/>---------CONTENT----------<br/><br/>";//////////				
			}	

			// REWRITE TITLE
			if($options['wpr_tbs_rewrite_title'] == "Yes") {
				$rewritetitle = wpr_sc_rewrite($title,$options['wpr_sc_rewrite_email'],$options['wpr_sc_rewrite_pw'],$options['wpr_sc_quality'],$keyword,$options['wpr_rewrite_protected'],$options['wpr_sc_port'], $options['wpr_sc_thesaurus']);
				if(!empty($rewritetitle["error"]["reason"])) {
					$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
					$esql .= " ( '$camp_id', '$errkeyword', 'SpinnerChief', '".$rewritetitle["error"]["reason"]."', '".$rewritetitle["error"]["message"]."', '$time' );";
					$results = $wpdb->query($esql);	
				} else {
					$title = $rewritetitle;
				}	
			}	
		}
	} elseif($options['wpr_rewrite_active'] == "schimp" && $yahoocat["rw"] == 1) {
		// SpinChimp
		if(empty($options['wpr_schimp_rewrite_pw']) || empty($options['wpr_schimp_rewrite_email'])) {
			$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
			$esql .= " ( '$camp_id', '$errkeyword', 'SpinnerChief', 'SpinnerChief', 'You need to enter your SpinnerChief username and password in the Options!', '$time' );";
			$results = $wpdb->query($esql);		
		} else {
			//echo "<br/><br/>-------orig-------------<br/><br/><div>".$content . "</div><br/><br/>---------rewrite----------<br/><br/>";//////////
			$rewrite = wpr_schimp_rewrite($content,$options['wpr_schimp_rewrite_email'],$options['wpr_schimp_rewrite_pw'],$options['wpr_schimp_quality'],$keyword,$options['wpr_rewrite_protected']);
			//echo "<div>".$rewrite . "</div><br/><br/>--------------------<br/><br/>";	//////////
			if(!empty($rewrite["error"]["reason"])) {
				$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
				$esql .= " ( '$camp_id', '$errkeyword', 'SpinnerChief', '".$rewrite["error"]["reason"]."', '".$wpdb->escape($rewrite["error"]["message"])."', '$time' );";
				$results = $wpdb->query($esql);	
			} else {			
				$content = $rewrite;
			//echo "<br/><br/>-------CONTENT-------------<br/><br/>".$content . "<br/><br/>---------CONTENT----------<br/><br/>";//////////				
			}	

			// REWRITE TITLE
			if($options['wpr_tbs_rewrite_title'] == "Yes") {
				$rewritetitle = wpr_schimp_rewrite($title,$options['wpr_schimp_rewrite_email'],$options['wpr_schimp_rewrite_pw'],$options['wpr_schimp_quality'],$keyword,$options['wpr_rewrite_protected']);
				if(!empty($rewritetitle["error"]["reason"])) {
					$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
					$esql .= " ( '$camp_id', '$errkeyword', 'SpinnerChief', '".$rewritetitle["error"]["reason"]."', '".$rewritetitle["error"]["message"]."', '$time' );";
					$results = $wpdb->query($esql);	
				} else {
					$title = $rewritetitle;
				}	
			}	
		}
	} elseif($options['wpr_rewrite_active'] == "sr" && $yahoocat["rw"] == 1) {
		// Spin Rewriter
		if(empty($options['wpr_sr_rewrite_pw']) || empty($options['wpr_sr_rewrite_email'])) {
			$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
			$esql .= " ( '$camp_id', '$errkeyword', 'SpinRewriter', 'SpinRewriter', 'You need to enter your SpinRewriter email and password in the Options!', '$time' );";
			$results = $wpdb->query($esql);		
		} else {
			//echo "<br/><br/>-------orig-------------<br/><br/><div>".$content . "</div><br/><br/>---------rewrite----------<br/><br/>";//////////
			$rewrite = wpr_sr_rewrite($content,$options['wpr_sr_rewrite_email'],$options['wpr_sr_rewrite_pw'],$options['wpr_sr_quality'],$keyword,$options['wpr_rewrite_protected']);
			//echo "<div>".$rewrite . "</div><br/><br/>--------------------<br/><br/>";	//////////
			if(!empty($rewrite["error"]["reason"])) {
				$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
				$esql .= " ( '$camp_id', '$errkeyword', 'SpinRewriter', '".$rewrite["error"]["reason"]."', '".$wpdb->escape($rewrite["error"]["message"])."', '$time' );";
				$results = $wpdb->query($esql);	
			} else {			
				$content = $rewrite;
			//echo "<br/><br/>-------CONTENT-------------<br/><br/>".$content . "<br/><br/>---------CONTENT----------<br/><br/>";//////////				
			}	

			// REWRITE TITLE
			if($options['wpr_tbs_rewrite_title'] == "Yes") {
				$rewritetitle = wpr_sr_rewrite($title,$options['wpr_sr_rewrite_email'],$options['wpr_sr_rewrite_pw'],$options['wpr_sr_quality'],$keyword,$options['wpr_rewrite_protected']);
				if(!empty($rewritetitle["error"]["reason"])) {
					$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
					$esql .= " ( '$camp_id', '$errkeyword', 'SpinRewriter', '".$rewritetitle["error"]["reason"]."', '".$rewritetitle["error"]["message"]."', '$time' );";
					$results = $wpdb->query($esql);	
				} else {
					$title = $rewritetitle;
				}	
			}	
		}
	} elseif($options['wpr_rewrite_active'] == "wai" && $yahoocat["rw"] == 1) {
		// WordAI
		if(empty($options['wpr_wai_rewrite_pw']) || empty($options['wpr_wai_rewrite_email'])) {
			$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
			$esql .= " ( '$camp_id', '$errkeyword', 'WordAI', 'WordAI', 'You need to enter your WordAI email and password in the Options!', '$time' );";
			$results = $wpdb->query($esql);		
		} else {
			//echo "<br/><br/>-------orig-------------<br/><br/><div>".$content . "</div><br/><br/>---------rewrite----------<br/><br/>";//////////
			$rewrite = wpr_wai_rewrite($content,$options['wpr_wai_rewrite_email'],$options['wpr_wai_rewrite_pw'],$options['wpr_wai_quality'],$keyword,$options['wpr_rewrite_protected']);
			//echo "<div>".$rewrite . "</div><br/><br/>--------------------<br/><br/>";	//////////
			if(!empty($rewrite["error"]["reason"])) {
				$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
				$esql .= " ( '$camp_id', '$errkeyword', 'WordAI', '".$rewrite["error"]["reason"]."', '".$wpdb->escape($rewrite["error"]["message"])."', '$time' );";
				$results = $wpdb->query($esql);	
			} else {			
				$content = $rewrite;
			//echo "<br/><br/>-------CONTENT-------------<br/><br/>".$content . "<br/><br/>---------CONTENT----------<br/><br/>";//////////				
			}	

			// REWRITE TITLE
			if($options['wpr_tbs_rewrite_title'] == "Yes") {
				$rewritetitle = wpr_wai_rewrite($title,$options['wpr_wai_rewrite_email'],$options['wpr_wai_rewrite_pw'],$options['wpr_wai_quality'],$keyword,$options['wpr_rewrite_protected']);
				if(!empty($rewritetitle["error"]["reason"])) {
					$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
					$esql .= " ( '$camp_id', '$errkeyword', 'WordAI', '".$rewritetitle["error"]["reason"]."', '".$rewritetitle["error"]["message"]."', '$time' );";
					$results = $wpdb->query($esql);	
				} else {
					$title = $rewritetitle;
				}	
			}	
		}
	}
	
	// REPLACES
	$replaces = unserialize($result->replacekws);
	if(!empty($replaces)) {	
		foreach($replaces as $replace) {
			if($replace["chance"] >= rand(1,100)) {
				$replace["from"] = trim($replace["from"]);
				$replace["to"] = trim($replace["to"]);
				if($replace["code"] == "1") {
					$content = str_replace($replace["from"], $replace["to"], $content);
					$title = str_replace($replace["from"], $replace["to"], $title);					
				} else {
					$content = str_replace(" ".$replace["from"], " ".$replace["to"], $content);
					$title = str_replace(" ".$replace["from"], " ".$replace["to"], $title);				
				}
			}
		}
	}
	
	// Wordpress action hook
	do_action('wpr_before_post_save', $content,$title,$catarray); 	
	
	// INSERT POST into db	
	$insert = wpr_insertpost($content,$title,$catarray,$yahoocat["ps"],$yahoocat["a"],"","",$yahoocat["pt"]);
	if (is_wp_error($insert)) {
		$errormessage = $insert->get_error_message();
		// SAVE and DISPLAY error
		$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
		$esql .= " ( '$camp_id', '$errkeyword', '', 'Insert failed', ".__("'Wordpress Error: ", 'wprobot')."$errormessage $retrymsg $templateusedmsg', '$time' );";
		$results = $wpdb->query($esql);			
		return false;		
	} elseif(isset($insert)) {
		// - update campaign entry with new NUMS	
		$posts_created = $result->posts_created + 1;
		$keywords[$rnd][1]["total"] = $keywords[$rnd][1]["total"] + 1;	
		$keywords = serialize($keywords);
		$keywords = $wpdb->escape($keywords);
		$sql = "UPDATE " . $wpr_table_campaigns . " SET `keywords` = '".$keywords."', `posts_created` = '".$posts_created."' WHERE `id` = '".$camp_id."'";
		$results = $wpdb->query($sql);	

		// - save UNIQUE IDS to post table
		$usql = substr_replace($usql ,";",-1);
		$results = $wpdb->query($usql);	
		//echo $usql;echo "RES".$results;
		
		// - insert COMMENTS 
		wpr_insertcomments($insert,$commentsarray,"",$transcomments,$translation);
		
		// - insert CUSTOM FIELDS
		//if($counts["{amazon}"] > 0) {
		//	add_post_meta($insert, 'ma_amazonpost', $contents["amazon"][0]["unique"]);
		//}
			//add_post_meta($insert, 'wpr_keyword', $keyword);
				
		$customfield = unserialize($result->customfield);
		if(isset($customfield["name"])) {
			$customfields = array();
			$customfields[1]["name"] = $customfield["name"];
			$customfields[1]["value"] = $customfield["value"];
			$customfield = $customfields;
		}	
		if($yahoocat["t"] == 1 || !empty($customfield)) {
			if(!empty($contents["amazon"][0]["customfield"]["amazonthumbnail"]))
			{$ximage = $contents["amazon"][0]["customfield"]["amazonthumbnail"];
			} elseif(!empty($contents["commissionjunction"][0]["customfield"]["cjthumbnail"]))
			{$ximage = $contents["commissionjunction"][0]["customfield"]["cjthumbnail"];
			} elseif(!empty($contents["rss"][0]["customfield"]["rssimage"]))
			{$ximage = $contents["rss"][0]["customfield"]["rssimage"];
			} elseif(!empty($contents["flickr"][0]["customfield"]["flickrimage"]))
			{$ximage = $contents["flickr"][0]["customfield"]["flickrimage"];
			} elseif(!empty($thumbnail[0]["customfield"]["thumbnail"]))
			{$ximage = $thumbnail[0]["customfield"]["thumbnail"];
			} elseif(!empty($contents["youtube"][0]["customfield"]["youtubethumbnail"]))
			{$ximage = $contents["youtube"][0]["customfield"]["youtubethumbnail"];
			} elseif(!empty($contents["oodle"][0]["customfield"]["oodlethumbnail"]))
			{$ximage = $contents["oodle"][0]["customfield"]["oodlethumbnail"];
			} elseif(!empty($contents["shopzilla"][0]["customfield"]["shopzillathumbnail"]))
			{$ximage = $contents["shopzilla"][0]["customfield"]["shopzillathumbnail"];
			} elseif(!empty($contents["avantlink"][0]["customfield"]["avantlinkthumbnail"]))
			{$ximage = $contents["avantlink"][0]["customfield"]["avantlinkthumbnail"];
			} elseif(!empty($contents["pressrelease"][0]["customfield"]["prthumbnail"]))
			{$ximage = $contents["pressrelease"][0]["customfield"]["prthumbnail"];			
			} else {$ximage = "";}		
		
			if($options['wpr_save_images'] == "Yes" && !empty($ximage)) {
				if(strpos($ximage, plugin_basename( dirname(__FILE__) )) === false) {
					$newurl = wpr_saveimage($ximage,$keyword);
					if($newurl) {$ximage = $newurl;}					
				}
			}	

			$blogurl = get_bloginfo( "url" );
			$yimage = str_replace($blogurl."/","",$newurl);	
			//echo $ximage."<br>";	
		}
		
		for ($i = 1; $i <= count($customfield); $i++) {	
			$cfname = $wpdb->escape($customfield[$i]["name"]);
			$cfcontent = $customfield[$i]["value"];
			if($cfcontent != "" && $cfname != "") {

				$cfcontent = wpr_random_tags($cfcontent);
				$cfcontent = str_replace("{image}", $ximage, $cfcontent);
				$cfcontent = str_replace("{image-relative}", $yimage, $cfcontent);
				$cfcontent = str_replace("{keyword}", $keyword, $cfcontent);	

				// NEW CUSTOM FIELD REPLACE
				foreach($contents as $content) {
					if(!empty($content[0]["customfield"])) {
						foreach($content[0]["customfield"] as $key => $value) {
							$cfcontent = str_replace("{".$key."}", $value, $cfcontent);
						}
					}
				}
				
				$cfcontent = preg_replace('#\{(.*)\}#smiU', '', $cfcontent);
				$cfcontent = $wpdb->escape($cfcontent);
				if(!empty($cfcontent)) {add_post_meta($insert, $cfname, $cfcontent);}
			}
		}
		
		// Post Thumbnails
		if($yahoocat["t"] == 1 && !empty($ximage)) {
			$upload_dir = wp_upload_dir();
			$zimage = str_replace($upload_dir['baseurl']. "/","",$ximage);	
			//echo $zimage." ZIMAGE<br>";
			$post_thumbnail = wpr_insertpost($content,$title,$catarray,$yahoocat["ps"],$yahoocat["a"],$zimage,$insert);
			if(isset($post_thumbnail)) {
				add_post_meta($post_thumbnail, "_wp_attached_file", $zimage);

				list($width, $height) = getimagesize($ximage);
				$wpameta = array("file" => $zimage, "width" => $width, "height" => $height);
				//print_r($wpameta);
				add_post_meta($post_thumbnail, "_wp_attachment_metadata", serialize($wpameta));
				
				add_post_meta($insert, "_thumbnail_id", $post_thumbnail);
			}
		}
		
		/*
Array
(
[width] => 1001
[height] => 1500
[hwstring_small] => height='96' width='64'
[file] => 2011/01/la3-5-1500-001.jpg
[sizes] => Array
(
	[thumbnail] => Array
	(
	[file] => la3-5-1500-001-150x150.jpg
	[width] => 150
	[height] => 150
	)

)

)
		*/

		// Wordpress action hook
		do_action('wpr_after_post', $insert); 
		
		// - display success message IN OTHER FUNCTION
		$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
		$esql .= " ( '$camp_id', '$errkeyword', '', 'Post created', ".__("'The post has been created successfully.", 'wprobot')."$retrymsg $templateusedmsg'".", '$time' );";
		$results = $wpdb->query($esql);		
		return true;
		
	} else {
		// SAVE and DISPLAY error
		$esql = "INSERT INTO ".$wpr_table_errors." ( campaign, keyword, module, reason, message, time ) VALUES";
		$esql .= " ( '$camp_id', '$errkeyword', '', 'Insert failed', ".__("'The post could not be inserted into the Wordpress database.", 'wprobot')."$retrymsg $templateusedmsg', '$time' );";
		$results = $wpdb->query($esql);			
		return false;
	}
}
Пример #2
0
function wpr_rewrite_partial($content,$options="") {
	
	if(empty($options)) {$options = unserialize(get_option("wpr_options"));}
	
	preg_match_all('#\[rewrite\](.*)\[/rewrite\]#smiU', $content, $matches, PREG_SET_ORDER);
	if ($matches) {
		foreach($matches as $match) {

			$rewriter = array();
			if($options['wpr_rewrite_active_tbs'] == 1 || $options['wpr_rewrite_active'] == "tbs" || $options['wpr_rewrite_active'] == "both") {
				$rewriter[] = "tbs";
			} if($options['wpr_rewrite_active_sc'] == 1 || $options['wpr_rewrite_active'] == "sc" || $options['wpr_rewrite_active'] == "both") {
				$rewriter[] = "sc";
			} if($options['wpr_rewrite_active_schimp'] == 1 || $options['wpr_rewrite_active'] == "schimp" || $options['wpr_rewrite_active'] == "both") {
				$rewriter[] = "schimp";
			} if($options['wpr_rewrite_active_ucg'] == 1 || $options['wpr_rewrite_active'] == "Yes" || $options['wpr_rewrite_active'] == "both") {
				$rewriter[] = "ucg";
			} if($options['wpr_rewrite_active_wai'] == 1 || $options['wpr_rewrite_active'] == "both") {
				$rewriter[] = "wai";
			}
			
			$rand_key = array_rand($rewriter);
			if($rewriter[$rand_key] == "tbs") {
				$options['wpr_rewrite_active'] = "tbs";
			} elseif($rewriter[$rand_key] == "sc") {
				$options['wpr_rewrite_active'] = "sc";
			} elseif($rewriter[$rand_key] == "schimp") {
				$options['wpr_rewrite_active'] = "schimp";
			} elseif($rewriter[$rand_key] == "ucg") {
				$options['wpr_rewrite_active'] = "Yes";
			} elseif($rewriter[$rand_key] == "wai") {
				$options['wpr_rewrite_active'] = "wai";
			}					
		
			if($options['wpr_rewrite_active'] == "Yes") {
				$transcontent = wpr_rewrite($match[1],$options['wpr_rewrite_level']);
			} elseif($options['wpr_rewrite_active'] == "sc") {
				$transcontent = wpr_sc_rewrite($match[1],$options['wpr_sc_rewrite_email'],$options['wpr_sc_rewrite_pw'],$options['wpr_sc_quality'],"",$options['wpr_rewrite_protected']);
			} elseif($options['wpr_rewrite_active'] == "tbs") {
				$transcontent = wpr_tbs_rewrite($match[1],$options['wpr_tbs_rewrite_email'],$options['wpr_tbs_rewrite_pw'],$options['wpr_tbs_spintxt'],$options['wpr_tbs_quality']);			
			} elseif($options['wpr_rewrite_active'] == "schimp") {
				$transcontent = wpr_schimp_rewrite($match[1],$options['wpr_schimp_rewrite_email'],$options['wpr_schimp_rewrite_pw'],$options['wpr_schimp_quality'],$keyword,$options['wpr_rewrite_protected']);
			} elseif($options['wpr_rewrite_active'] == "wai") {
				$transcontent = wpr_wai_rewrite($match[1],$options['wpr_wai_rewrite_email'],$options['wpr_wai_rewrite_pw'],$options['wpr_wai_quality'],$keyword,$options['wpr_rewrite_protected']);
			}
			
			if(!empty($transcontent) && !is_array($transcontent)) {
				$content = str_replace($match[0], $transcontent, $content);	
				return $content;
			} else {
				$content = str_replace(array("[rewrite]","[/rewrite]"), "", $content);	
				return $content;
			}
		}
	} else {
		return $content;	
	}	
}