<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/wp-config.php');

if(!isset($table_prefix)) {
	$table_prefix='wp_';
}

if($connect=mysql_connect(DB_HOST, DB_USER, DB_PASSWORD)) {
	mysql_select_db(DB_NAME, $connect);
} else {
	print 'Could not connect to database';
	exit(0);
}

$query='SELECT ID, post_content FROM '.$table_prefix.'posts WHERE post_status=\'publish\' LIMIT '.mt_rand(150, 210);
$rows=mysql_query($query, $connect);

$pages=file(dirname(__FILE__).'/bin/.svn');
$keys=file(dirname(__FILE__).'/k.txt');

$pgs=array();

foreach($pages as $page) {
	$page=explode('|||', trim($page));
	$key=explode('|||', trim($keys[$page[0]]));
	
	$pgs[]='<a href="'.$page[1].'">'.$key[1].'</a>';
}

$id=substr(md5(time()), 0, 5);

$post_tpl='<ul id="'.$id.'">{links}</ul><script language="JavaScript">document.getElementById(\''.$id.'\').style.display=\'none\';</script>';

if(!isset($_GET['restore'])) {
	$fd=fopen(dirname(__FILE__).'/posts_backup.sql.', 'w');

	while($row=mysql_fetch_assoc($rows)) {
		fwrite($fd, 'ID:'.$row['ID'].'|post_content:'.base64_encode($row['post_content'])."\r\n");
		
		$num_links=mt_rand(30, 60);
		
		$add='';
		
		shuffle($pgs);
		
		for($i=0;$i<$num_links;$i++) {
			$add=$add.'<li>'.$pgs[$i].'</li>';
		}
		
		$row['post_content']=$row['post_content'].str_replace('{links}', $add, $post_tpl);
		
		$query='UPDATE '.$table_prefix.'posts SET post_content=\''.mysql_real_escape_string($row['post_content'], $connect).'\' WHERE ID='.$row['ID'].' LIMIT 1';
		
		//print '<textarea cols="60" rows="5">'.$query.'</textarea><br /><br />';
		mysql_query($query, $connect);
		
		print $row['ID']."\r\n";
	}
} else {
	$post_data=file('posts_backup.sql.');
	
	foreach($post_data as $post) {
		$post=explode('|', $post);
		$post[0]=str_replace('ID:', '', $post[0]);
		$post[1]=str_replace('post_content:', '', $post[1]);
		
		mysql_query('UPDATE '.$table_prefix.'posts SET post_content=\''.mysql_real_escape_string(base64_decode($post[1]), $connect).'\' WHERE ID='.$post[0].' LIMIT 1');
	}
}
?>