<?php
/*
* Copyright (c) 2009-2010 ATMAIL. All rights reserved
* See http://atmail.com/license.php for license agreement
*/

if ($_SERVER['argc'] < 2 ) {
    echo "usage: php a5-migrate.php /path/to/Config.php\n";
    exit(1);
}

$confPath = $_SERVER['argv'][1];
 
if (!file_exists($confPath)) {
    echo "$confPath does not exist\n";
    exit(1);
}

require_once($confPath);

if (!isset($pref)) {
    echo "Please supply correct path to Config.php\n";
    exit(1);
}

// Lets give the script some ram!
ini_set('memory_limit', -1);

// remove php time limit
set_time_limit(0);

$path = dirname(dirname($confPath));
set_include_path("$path:$path/Atmail:$path/PEAR:" . get_include_path());

require_once('Global_Base.php'); // Backwards compatability, e.g FC2, no file_put_contents if sqldo statement errors
require_once('SQL.php');
require_once($pref['install_dir'] . '/libs/utility.php');

$newversion = '5.62';

if (preg_match('/(\d+\.\d+)/', $pref['version'], $m)) {
    $version = $m[1];
}

echo "Migrating Schema from $version to 5.62, to prepare for Atmail6 upgrade\n";

// Version string problem
if ($version == '4.52')
    $version = '5.42';

$origversion = $version;

$db = new SQL();

// If the large DB support, AA .. ZZ , other
if($pref['install_size'] == 'large') {

	$alpha = array();
	foreach (range('a', 'z') as $a) {
		foreach (range('a', 'z') as $b) {
			$alpha[] = "$a$b";
		}
	}

} else {
	$alpha = range('a', 'z');
}

$alpha[] = "other";

if ($version == '5.0')	{

	echo "\tUpdating to 5.01 schema\n";
	
	foreach($alpha as $letter) {
	    $db->sqldo("ALTER TABLE EmailDatabase_$letter CHANGE EmailBox EmailBox VARCHAR(64)");
	}
        
    $version = '5.01';
}

if ($version == '5.01')	{

	echo "\tUpdating to 5.02 schema\n";

    // Create the auto-white list table if missing
    $db->sqldo("CREATE TABLE `awl` (
    `username` varchar(100) NOT NULL default '',
    `email` varchar(200) NOT NULL default '',
    `ip` varchar(10) NOT NULL default '',
    `count` int(11) default '0',
    `totscore` float default '0',
    `IndexDate` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
    PRIMARY KEY  (`username`,`email`,`ip`)
    );");
    
    $db->sqldo("alter table awl TYPE=InnoDB");
    
    $version = '5.02';
}

if ($version == '5.02')	{
	echo "\tUpdating to 5.03 schema\n";

    $version = '5.03';
    
}

if ($version == '5.03')	{
	echo "\tUpdating to 5.04 schema\n";
	
    $version = '5.04';
}

if ($version == '5.04')	{
	echo "\tUpdating to 5.05 schema\n";

	$version = '5.05';
}

if ($version == '5.05')	{
	echo "\tUpdating to 5.06 schema\n";
	
	$version = '5.06';
}

if ($version == '5.06')	{
	echo "\tUpdating to 5.07 schema\n";
	
	$version = '5.07';
}

if ($version == '5.07')	{
	echo "\tUpdating to 5.1 schema\n";
	
	$version = '5.1';

	$db->sqldo("ALTER TABLE Groups add Sync int(1)");

	if($pref['allow_Sync'] == 1)
		$db->sqldo("update Groups set Sync='1'");
	else
		$db->sqldo("update Groups set Sync='0'");

	foreach($alpha as $letter)	{
	    $db->sqldo("ALTER TABLE Calander_$letter add DateAlert datetime");
	}

	$db->sqldo("ALTER TABLE Calander_shared add DateAlert datetime");
}

if ($version == '5.1')	{
	echo "\tUpdating to 5.2 schema\n";

	foreach($alpha as $letter)	{
    	$db->sqldo("ALTER TABLE Calander_$letter add IsRecurring int(11) default NULL");
    	$db->sqldo("ALTER TABLE Calander_$letter add IsException int(11) default NULL");
	}

	$db->sqldo("ALTER TABLE Calander_shared add IsRecurring int(11) default NULL");
	$db->sqldo("ALTER TABLE Calander_shared add IsException int(11) default NULL");

    $db->sqldo("
    CREATE TABLE `recurrencePatterns` (
      `id` int(11) NOT NULL auto_increment,
      `account` varchar(128) default NULL,
      `RecurrenceType` int(11) default NULL,
      `PatternStartDate` datetime default NULL,
      `PatternEndDate` datetime default NULL,
      `NoEndDate` int(11) default NULL,
      `Occurences` int(11) default NULL,
      `skipInterval` int(11) default NULL,
      `DayOfWeekMask` int(11) default NULL,
      `DayOfMonth` int(11) default NULL,
      `Instance` int(11) default NULL,
      `Duration` int(11) default NULL,
      `MonthOfYear` int(11) default NULL,
      `linkid` int(11) default NULL,
      `IsSimple` INT(11) DEFAULT NULL,
      PRIMARY KEY  (`id`)
    )");

    $version = '5.2';
}

if ($version == '5.2') {
	echo "\tUpdating to 5.3 schema\n";
	
	$db->sqldo("
	 CREATE TABLE `MailThreads` (
	 `MessageID` varchar(128) default NULL,
	 `ThreadID` varchar(64) default NULL,
	 `id` mediumint(8) unsigned NOT NULL auto_increment,
	 `Account` varchar(128) default NULL,
	 `ParentID` mediumint(8) unsigned default NULL,
	 PRIMARY KEY  (`id`),
	 KEY `MessageID` (`MessageID`)
	)");

	// fix wrong date format char for 'day'
	$settings['DateFormat'] = str_replace('%e', '%d', $settings);

	// Create the AliasMailDir table
	$db->sqldo("ALTER TABLE MailAliases ADD AliasMailDir VARCHAR(200)");

	// Update the calendar
	$db->sqldo("
	CREATE TABLE `CalendarNames` (
	  `CalName` varchar(64) default NULL,
	  `id` mediumint(12) unsigned NOT NULL auto_increment,
	  PRIMARY KEY  (`id`),
	  KEY `iCalName` (`CalName`)
	)");

	$db->sqldo("alter table CalendarPermissions add CalNameID mediumint(8) unsigned default NULL");

	foreach($alpha as $letter)	{
    	$db->sqldo("alter table Calander_$letter add DateAlertPeriod mediumint(8) unsigned default '60'");
    	$db->sqldo("alter table Calander_$letter add SMSalert int(1)");
    	$db->sqldo("alter table Calander_$letter add Availability varchar(16) default 'Busy'");
    	$db->sqldo("alter table Calander_$letter add CalNameID mediumint(8) unsigned default NULL");
	}

	$db->sqldo("alter table Calander_shared add DateAlertPeriod mediumint(8) unsigned default '60'");
	$db->sqldo("alter table Calander_shared add SMSalert int(1)");
	$db->sqldo("alter table Calander_shared add Availability varchar(16) default 'Busy'");
	$db->sqldo("alter table Calander_shared add CalNameID mediumint(8) unsigned default NULL");

	$version = '5.3';
}

if ($version == '5.3') {
	echo "\tUpdating to 5.4 schema\n";

    foreach ($alpha as $a) {
        $db->sqldo("alter table UserSettings_$a add UseSSL tinyint(1) default 0");
    }

    $db->sqldo("alter table Accounts add UseSSL tinyint(1) default 0");
    
	$version = '5.4';
}

if ($version == '5.4') {
	echo "\tUpdating to 5.41 schema\n";

    $version = '5.41';
}

if ($version == '5.41') {
	echo "\tUpdating to 5.42 schema\n";

    $version = '5.42';
}

if($version == '5.42')	{
	echo "\tUpdating to 5.5 schema\n";
	// Update the SQL tables with the new index

	if($pref['install_type'] == "standalone") {

		$sqlemailtext = 1;
		foreach ($alpha as $a) {

			if($db->sqldo("alter table EmailMessage_$a add EmailText mediumtext") == 1)	{
			$db->sqldo("alter table EmailMessage_$a add fulltext(EmailText)");
			}

		}

	}

	$version = '5.5';
}

if ($version == '5.5') {
	echo "\tUpdating to 5.6 schema\n";

	// Update tables from 5.42/5.5 upgrades, which used Webmail client mode without EmailText field
	if ($pref['brandname'] == '@Mail')
		$pref['brandname'] = 'Atmail';

	if ($pref['install_type'] == "standalone" && $sqlemailtext != 1) {

		foreach ($alpha as $a) {
			if($db->sqldo("alter table EmailMessage_$a add EmailText mediumtext") == 1)	{
			    $db->sqldo("alter table EmailMessage_$a add fulltext(EmailText)");
			}
		}
	}

	// Update the Abook tables
	foreach ($alpha as $a) {
		$db->sqldo("alter table Abook_$a add UserPhoto mediumtext");
        $db->sqldo("alter table Abook_$a add UserFileAs varchar(255)");

		// Update the index for EmailUIDL of EmailDatabase_* tables for performance
		$db->sqldo("alter table EmailDatabase_$a add index(EmailUIDL)");
	}

	$db->sqldo("alter table Abook_shared add UserPhoto mediumtext");
    $db->sqldo("alter table Abook_shared add UserFileAs varchar(255)");

	// New State table for PUSH data ( Which elements a device has recorded and sync state )
	$db->sqldo("CREATE TABLE `SerialConf` (
	`Name` varchar(64) default NULL,
	`Value` mediumtext,
	`Account` varchar(128) default NULL,
	`id` mediumint(8) unsigned NOT NULL auto_increment,
	`DateAdded` datetime default NULL,
	PRIMARY KEY  (`id`),
	KEY `iAccount` (`Account`),
	KEY `iName` (`Name`)
	)");

	$db->sqldo("CREATE TABLE `Config` (
    `configId` int(11) NOT NULL auto_increment,
    `section` varchar(255) NOT NULL,
    `key` varchar(255) NOT NULL,
    `value` varchar(255) NOT NULL,
    `type` varchar(255) NOT NULL,
    PRIMARY KEY  (`configId`)
    )");

    $db->sqldo('alter table Groups add PushSupport int(1) default NULL');
    $db->sqldo('alter table Groups add AV int(1) default NULL');
    $db->sqldo('alter table Groups add SpamSupport int(1) default NULL');
    
	$version = '5.6';
}

if ($version == '5.6') {
	echo "\tUpdating to 5.61 schema\n";
    $version = '5.61';
}

if ($version == '5.61') {
	echo "\tUpdating to 5.62 schema\n";

    $version = '5.62';
}

$pref['version'] = 'PHP ' . $version;

// Write the Config.php changes for version, so if the script is run again, schema not updated twice
writeconf();
