<?php

//  Usage: call the function on the commandline (PHP CLI needed)
//  entereing the path of the persistent.log and the path of the userdb.txt
//  attention only run the script once

main("persistent.log","userdb.txt");

function main($path_to_log, $path_to_db) {
	$successful=create_backup($path_to_db);
	if ($successful==true) { migrate_db($path_to_log, $path_to_db);} 
	else { print_r("The backup copy failed, so there was no transition. Please check permissions."); }
}

function create_backup($path_to_db) {   
	$path_to_backup=$path_to_db.".version1";
	if (copy($path_to_db,$path_to_backup)) 
		{ print_r("A backup copy  of your file has been saved to ".$path_to_backup."\n"); return true;}
	else { print_r("Something went wrong!"); return false; }
}

function parse_log($path_to_log) {
	$tmp_file_s=$path_to_log."_sort";
	$tmp_file_u=$path_to_log."_uniq";
	system("sort -u ".$path_to_log." > ".$tmp_file_s);
	system("uniq -u ".$tmp_file_s." ".$tmp_file_u);

//  read file into a two dimensional array

	$lines = file($tmp_file_u,FILE_IGNORE_NEW_LINES);

	foreach ($lines as $line_num => $line) {
		$tmp_array=preg_split("/ /", $line, 4);
		$conversion[$line_num]['uniqueid']     = $tmp_array[2];
		$conversion[$line_num]['persistentid'] = $tmp_array[1];
	}

	return $conversion;
}

//  returns the corresponding persistentid to the uniqueid 
//  or returns false when nothing was found


function get_persistentid_to_uniqueid($search, $multidimensionalarray) {
	foreach($multidimensionalarray as $key => $values) { 
		if (in_array($search, $values)) { 
			if ($search !=  $values['persistentid']) {return $values['persistentid'];}
//   if the search input is already a persistent ID, then the userdb file has already been migrated			
    		else {print_r("It seems that you are running the script for the second time.");}
    	}
    }
  	return false;
}

function migrate_db($path_to_log,$path_to_db) {
	$conversion=parse_log($path_to_log);
	$counter=0;
	$text="";
	$notmigrated="";
//  read each line of the userdb file into an array
	$lines = file($path_to_db,FILE_IGNORE_NEW_LINES);
//  go through all users and try to replace the line with the persistentid instead of the uniqueid
	foreach ($lines as $line_num => $line) {
  		$tmp_array=preg_split("/ /", $line, 2);
  		$persistentid=get_persistentid_to_uniqueid($tmp_array[0],$conversion);
		if ($persistentid != false) { 
	    	$tmp_array[0]=$persistentid;
			$line = implode(" ", $tmp_array);	
			$counter++;
		}
		else {$notmigrated=$notmigrated.$tmp_array[0]."\n\n";}
		$text=$text.$line."\n";
	}
	$fh = fopen($path_to_db, 'w') or die("can't open file".$path_to_db);
	fwrite($fh, $text);
	fclose($fh);
	
    $numberofunchancheduid=$line_num-$counter;
    
    print "Attention, you have unmigrated uids. A total of ".$numberofunchancheduid."has not been changed";
	print "A total of ".$counter." uids have been changed";
	print_r("The not migrated".$notmigrated);

}

?>