<?php


// +---------------------------------------------------------------------------+
// | CONFIGURATION                                                             |
// +---------------------------------------------------------------------------+

// Connect to database
$dbhost "localhost";
$dbuser "***";
$dbpass "***";
$database "matthai";
$dbconnect mysql_connect($dbhost$dbuser$dbpass) or die("Cannot connect to database!<br>");
$dbselect mysql_select_db($database$dbconnect);

// +---------------------------------------------------------------------------+


// Get data from table wt_moving
// +---------------------------+

$sql "SELECT * FROM wt_moving";
if(!
mysql_query($sql)) {
  echo(
"SQL error selecting table wt_moving<br><p>");
}
$result mysql_query($sql);

// +---------------------------------------------------------------------------+

$website = array();

$fp fopen("data.txt""w");   // open file for writing
flock ($fp,2);                  // exclusive lock
$error 0;

while (
$myfield mysql_fetch_array($result)) {
  
$userID $myfield['sessid'];

  
// Remove PHPSESSID from URL...
  
$loc explode("/"$myfield['location']);
  
$webscript explode("?PHPSESSID"$myfield['location']);
  
$webscriptonly explode("?"$webscript[0]);

// +-----------------------------------------+

  // Location without PHPSESSID in URL
  
$web $webscript[0];

  
// Location without ANY parameter in URL
  // $web = $webscriptonly[0];

  // Full location (not recommended!)
  // $web = $myfield['location'];

// +-----------------------------------------+

  
$data[$userID][$web]++;

  if ( !
in_array$web$website ) ) { $website[] = $web;}
}

if (
fwrite($fp"userID")==-1) {
  
$error 1;
}
# print 'userID\t';

for($i=0;$i<count($website);$i++) {

  if (
fwrite($fp"\t$website[$i]")==-1) {
    
$error 1;
  }
}

if (
fwrite($fp"\n")==-1) {
  
$error 1;
}

foreach( 
$data as $user=>$sites ) {
  if (
fwrite($fp"$user\t")==-1) {
    
$error 1;
  }

  for(
$i=0;$i<count($website);$i++) {
    
$writeme $sites[$website[$i]];
    if (
$writeme == "") {
      
$writeme "0";
    }

    if (
fwrite($fp"$writeme")==-1) {
      
$error 1;
    }
    if (
fwrite($fp"\t")==-1) {
      
$error 1;
    }
  }

  if (
fwrite($fp"\n")==-1) {
    
$error 1;
  }
}

flock ($fp,3);                   // release the lock
fclose($fp);                     // close text file

if ($error == 0) {
  echo 
"Download data: <a href=data.txt>data.txt</a>.";
}
else {
  echo 
"Error writing file.";
}

?>