<?php
/*
* This file contains functions that will assist in moving blogs
* containing unicode to a different server, or upgrading them to
* support unicode. These functions should be run on the server
* that the files are being moved to.
* 
* Call rehash() on a non-unicode enabled table file to upgrade it
* Call reauth() on any table file to attempt to correct the
* "invalid or corrupt table file" error.
*/

/*Serialize with unicode support*/
function unicode_serialize($var){
	if(is_string($var))
		return '0'.base64_encode($var);
	elseif(is_array($var)) {
		$result=array();
		foreach($var as $key=>$value)
			$result[base64_encode($key)]=unicode_serialize($value);
		return '2'.serialize($result);
	}
	else
		return '1'.serialize($var);
}

function rehash($file) {
	$prefix='<?php die(\'Cannot view this file\'); ?>
';
	$prefixlen=strlen($prefix);
	$filecontent=file_get_contents($file);
	$filedata=substr($filecontent,$prefixlen,strlen($filecontent)-$prefixlen-32);
	$unserialized=unserialize($filedata);
	if($unserialized===false)
		trigger_error('Data corruption.');
	$filedata=$prefix.unicode_serialize($unserialized);
	$filehash=md5($filedata);
	fwrite(fopen($file,'w+'),$filedata.$filehash);
}

function reauth($file) {
	$filecontent=file_get_contents($file);
	$filedata=substr($filecontent,0,strlen($filecontent)-32);
	$filehash=md5($filedata);
	fwrite(fopen($file,'w+'),$filedata.$filehash);
}

include('../backend/fetch.class.php');
$files=array(
'tb_archives',
'tb_categories',
'tb_comments',
'tb_pages',
'tb_users',
'tb_posts',
);
foreach($files as $filename) {
	$filename.='.php';
	echo('Upgrading: '.$filename.'...<br>');
	reauth($filename);
}
?>