<?php

require_once('library/Atmail/Update/Versions.php');

class Atmail_Update_Cli extends Atmail_Update_Abstract
{	
	public $client;

	/*
	function _template()
	{
		if($this->client)
		{
			// client only	
		}
		else
		{
			//is server
			if( !is_file('/usr/local/atmail/mailserver/bin/atmail-update-version') )
			{
			
				//stuff that should only run if NOT appliance (e.g. recompiling source (Appliance unpacked as prebuilt binaries so dont recompile) )
			}
		
		}
	}
	*/

	function _6_6_2()
	{
		if(!$this->client)
		{
			echo "Updating Exim version...\n";
			_republishExim(array('rebuild' => 1));
		}
	}


	/************************************************* 6.6.0 *******************************************************/
	function _6_6_0()
	{
		echo "Updating daily task...\n";
		// copy the clean-logs.php script into the daily cron
		foreach (array("/etc/cron.daily", "/etc/periodic/daily") as $cronDir) {
			if (is_dir($cronDir)) {
				echo "Copying new log-rotation scripts to $cronDir ...\n";
				copy(APP_ROOT . "/utilities/tools/clean-logs.php", $cronDir . "/clean-logs.php");
				exec('chown root ' . $cronDir . '/clean-logs.php; chmod u+x ' . $cronDir . '/clean-logs.php');
				echo "New log-rotation enabled. Specify log rotation date-range via the Webadmin > Settings > Global Settings\n\n";
				break;
			}
		}

	}
	
	function _6_5_1()
	{
		echo "Optimize dav backend...\n";
		system("php utilities/migration/sabredav-optimize.php");

	}
	/************************************************* PLACEHOLDER 6.5 *******************************************************/
	/************************************************* 6.4 *******************************************************/
	function _6_4_0()
	{
		if(!$this->client)
		{

			// call the dep checker
			echo "Checking new dependancy requirements..\n";
			check_deps( array('--install=1', '--updatecli=1' ) );
			
			echo "Upgrading SpamAssassin version...\n";
			if(is_dir("/usr/local/atmail/spamassassin"))
			{
				system("rm -rf /usr/local/atmail/spamassassin");
			}
			_republishSA(array('rebuild' => 1, 'admin_email' => $this->getAdminEmail(), 'verbose' => false));

			echo "Upgrading Dovecot version...\n";
			_republishDovecot(array('updateAll' =>1, 'rebuild' => 1));
			
			echo "Updating Exim version...\n";
			_republishExim(array('rebuild' => 1));		

			_controlServerServices(true);

			echo "Updating ClamAV version ...\n";
			_republishAv(array('rebuild' => 1));

			_controlServerServices(false);

			echo "Adding Atmail automation script for AV/Spam updates\n";
			if (file_exists("/etc/cron.daily/"))
			{
				copy("/usr/local/atmail/server_source/scripts/atmail-automation.php", "/etc/cron.daily/atmail-automation.php");
				system("chmod 755 /etc/cron.daily/atmail-automation.php");
			}
			elseif (file_exists("/etc/periodic/daily/"))
			{
				copy("/usr/local/atmail/server_source/scripts/atmail-automation.php", "/etc/periodic/daily/502.atmail-automation.php");
				system("chmod 755 /etc/periodic/daily/502.atmail-automation.php");
			}
			else
			{
				echo "NOTE: Daily cron directory not detected on system. Please configure the system\ncrontab to automatically run the:\n\n/usr/local/atmail/server_source/scripts/atmail-automation.php command on a daily basis.\n\nThis is required to download the latest AV and Anti-Spam files.\n";
			}
		}
	}

	function _6_3_7()
	{
		if(!$this->client) 
		{
			// server
			echo "Upgrading Exim configure to new version.\n";
			
			$output = `cp /usr/local/atmail/mailserver/configure /usr/local/atmail/mailserver/configure.prev.6.3.7`;
			echo "Previous config file available at /usr/local/atmail/mailserver/configure.prev.6.3.7\n";
			echo "Please re-apply any custom changes after the update.\n";
			
			_republishExim(array());
		}
	}
	
	/************************************************* PLACE HOLDER 6.3.6 *******************************************************/
	/************************************************* PLACE HOLDER 6.3.5 *******************************************************/
	/************************************************* PLACE HOLDER 6.3.4 *******************************************************/
	/************************************************* PLACE HOLDER 6.3.3 *******************************************************/
	/************************************************* PLACE HOLDER 6.3.2.8327 *******************************************************/
	/************************************************* PLACE HOLDER 6.3.2 *******************************************************/
	/************************************************* 6.3.1 *******************************************************/
	function _6_3_1()
	{
		// common server/client
		// session auto start check
		echo "Checking required php settings...\n";
		$text .= " * Session Auto Start Off: ";
		if(ini_get('session.auto_start') == '1')
		{
			if(editIni('session.auto_start', 'Off'))
			{
				$text .= "FIXED - Session auto start now off as required by Atmail\n";
			}
			else
			{
				$text .= "FAILED -  Atmail requires session auto start disabled\n";
			}
		}
		else
			$text .= "OK\n";
		
		echo $text;
	}

	/************************************************* 6.3 *******************************************************/
	function _6_3_0()
	{
		if( file_exists('/usr/local/atmail/calendarserver/server/run') || file_exists('/usr/local/atmail/calserver.img') )
		{
			// mount the calendar server in case we are a xattr enabled loop back device
	        system('php ' . APP_ROOT . '/utilities/migration/darwin-to-sabredav.php');
		    _updateStartupScripts();
		}
			
		// **************** SETUP / UPDATE FOR APACHE FOR SABRE USE ***************** //
		$apacheModification = true;
		$webserverBin = webserverFindBin();
	
		if(!is_executable($webserverBin))
		{
			fwrite(STDOUT, "\nError: No executable found at $webserverBin\n");
			$apacheModification = false;
		}
	
		$httpdConf = webserverFindConfig($webserverBin);
		
		// Find if we have an Apache conf.d directory, where we can copy the atmail config files in easier for updates
		$apacheConfD = webserverFindConfD($httpdConf);
		
		if(!is_file($httpdConf))
		{
			fwrite(STDOUT, "\nError: No apache configuration found at $httpdConf\n");
			$apacheModification = false;
		}
		$clientDir = '/usr/local/atmail/webmail';
		if(is_file('./.VERSION'))
		{
			$clientDir = realpath('./');
		}
		if(is_file('./webmail/.VERSION'))
		{
			$clientDir = realpath('./webmail/');
		}

$davConfig =<<<EOF
# CalDAV server for Atmail - Requires port 8008
Listen 8008
<VirtualHost *:8008>
  DocumentRoot {$clientDir}/dav/
  RewriteEngine On
  RewriteRule ^/(.*)$ /rootserver.php [L]
</VirtualHost>
# CardDAV iOS device auto-probe redirect
RewriteEngine On
RewriteRule ^/\.well-known\/carddav /mail/dav/ [R]
EOF;
$detected_msg = <<<EOF

SabreDAV support: \033[1;32mDetected\033[0;39m

Solution:
A CalDAV / CardDAV server was installed, and is currently operational.
However, some Cal- and CardDAV clients will require this server to run on its
own endpoint. To do this, the following lines will have to be added to your apache
configuration file.
$httpdConf:

$davConfig

EOF;

		if($apacheModification)
		{
			$confDir = dirname($httpdConf) . '/conf.d/';
			fwrite(STDOUT, "Reading $httpdConf: \n");
			$confVars = webserverParseConfiguration('/usr/local/atmail/', $httpdConf);
			extract($confVars);
	
			// If the httpd.conf includes links to other conf file, load them.
			if(isset($httpIncludes) && count($httpdIncludes))
			{
				foreach ($httpdIncludes as $include)
				{
					fwrite(STDOUT, "Scanning Webserver include file: $include\n");
					$incVars = webserverParseConfiguration('/usr/local/atmail/', $include);
					extract($incVars);
				}
			}
	
			if( isset($sabreDavVhost) && $sabreDavVhost == true && isset($mod_rewrite) && $mod_rewrite == false )
			{
	
				fwrite(STDOUT, "SabreDAV Vhost: OK\n");
	
			}
			else if( $mod_rewrite == false || $mod_rewrite == null )
			{

print <<<EOF

DAV support: \033[1;31mFailed\033[0;39m

Solution:
Atmail includes a complete CalDAV (Calenaring) and CardDAV (Contact)
server. For remote desktop-clients and mobile (iOS) devices to connect,
Apache must be configured to accept connections for *DAV services.

Enable the rewrite_module in your Apache configuration, then restart this installer.
See online documentation at http://www.atmail.com/support/index.php/Atmail6ServerInstall/CalendarInstall

EOF;
	
			}
			else
			{
				// mod_expires support detected, but not installed
				fwrite(STDOUT, $detected_msg . "\n");
				fwrite(STDOUT, "Update is attempting to edit httpd.conf automatically...\n");
				$addedondate = "\n# ADDED BY Atmail " . date('Y-m-d H:i:s') . "\n";
				
				appendApacheConf($apacheConfD, $httpdConf, $apacheAddedOnDate);
							
				$restart = true;
				$sabreDavVhost = true;
			}
			if(isset($restart) && $restart)
			{
print <<<EOF
The installer has edited your httpd.conf ($httpdConf).

For changes to take effect, you are required to restart Apache.
The installer will attempt to restart Apache (if this fails, restart the
Apache service manually).

EOF;
				webserverRestart();
			}
		}
		else
		{
			// something went wrong finding the apache configuration.
			// inform the user that a manual process must be done
			fwrite(STDOUT, $detected_msg . "\n");
		}
	}

	/************************************************* 6.2.13 *******************************************************/
	function _6_2_13()
	{
		echo "Ensuring permissions.\n";
		system("php utilities/tools/ensurePermissions.php");
	}
	
	/************************************************* PLACE HOLDER 6.2.12 *******************************************************/
	/************************************************* PLACE HOLDER 6.2.11 *******************************************************/
	/************************************************* 6.2.10 *******************************************************/
	function _6_2_10()
	{
		if(!$this->client) 
		{
			// server
			echo "Upgrading Exim configure to new version.\n";
			
			$output = `cp /usr/local/atmail/mailserver/configure /usr/local/atmail/mailserver/configure.prev`;
			echo "Previous config file available at /usr/local/atmail/mailserver/configure.prev\n";
			echo "Please re-apply any custom changes after the update.\n";
			
			_republishExim(array('rebuild' => 1));
		}
	}
	
	/************************************************* 6.2.8 *******************************************************/
	function _6_2_8()
	{
		// cli was not correct marked for execution in 6.20.7, lets rerun
		$this->_6_2_7();
		
		// ensure correct ownership and permissions for all .htaccess files
		if(is_dir('/usr/local/atmail/'))
		{
			system('cd /usr/local/atmail/webmail/; find . -name .htaccess -exec chown root:root {} \;');
			system('cd /usr/local/atmail/webmail/; find . -name .htaccess -exec chmod 644 {} \;');	
		}
		if(is_dir('../../webmail'))
		{
			system('cd ../../webmail/; find . -name .htaccess -exec chown root:root {} \;');
			system('cd ../../webmail/; find . -name .htaccess -exec chmod 644 {} \;');	
		}
	}
	
	/************************************************* 6.2.7 *******************************************************/
	function _6_2_7()
	{
		// ensure correct ownership of logs
		if(is_dir('/usr/local/atmail/webmail/log'))
		{
			system('chown -R atmail /usr/local/atmail/webmail/log');	
			if(file_exists('/usr/local/atmail/webmail/log/pushdebug.log'))
			{
				unlink('/usr/local/atmail/webmail/log/pushdebug.log');
			}
		}
		if(is_dir('../../log'))
		{
			system('chown -R atmail ../../log');	
			if(file_exists('../../log/pushdebug.log'))
			{
				unlink('../../log/pushdebug.log');
			}
		}
	}
	
	/************************************************* 6.2.6 *******************************************************/
	function _6_2_6()
	{	
		if(!$this->client) 
		{
			
			echo "Rebuilding Exim to allow apostrophes in email addresses ...\n";
			_republishExim(array('rebuild' => 1));		
			
			echo "Copying latest Spamassassin 72_active.cf ruleset ...\n";
			copy("/usr/local/atmail/server_source/etc/72_active.cf", "/usr/local/atmail/spamassassin/etc/72_active.cf");
			
		}
	}
	
	/************************************************* 6.2.5 *******************************************************/
	function _6_2_5()
	{
		// copy the clean-logs.php script into the daily cron
		foreach (array("/etc/cron.daily", "/etc/periodic/daily") as $cronDir) {	
			if (is_dir($cronDir)) {
				echo "Copying new log-rotation scripts to $cronDir ...\n";
				copy(APP_ROOT . "/utilities/tools/clean-logs.php", $cronDir . "/clean-logs.php");
				exec('chown root ' . $cronDir . '/clean-logs.php; chmod u+x ' . $cronDir . '/clean-logs.php');
				echo "New log-rotation enabled. Specify log rotation date-range via the Webadmin > Settings > Global Settings\n\n";
				break;
			}
		}
	
	}
	
	/************************************************* 6.2.4 *******************************************************/
	function _6_2_4()
	{
		// copy the clean-logs.php script into the daily cron
		foreach (array("/etc/cron.daily", "/etc/periodic/daily") as $cronDir) {	
			if (is_dir($cronDir)) {
				echo "Copying new log-rotation scripts to $cronDir ...\n";
				copy(APP_ROOT . "/utilities/tools/clean-logs.php", $cronDir . "/clean-logs.php");
				exec('chown root ' . $cronDir . '/clean-logs.php; chmod u+x ' . $cronDir . '/clean-logs.php');
				echo "New log-rotation enabled. Specify log rotation date-range via the Webadmin > Settings > Global Settings\n\n";
				break;
			}
		}
		
		if(!$this->client)
		{
			
			// call the dep checker
			echo "Checking new dependancy requirements..\n";
			check_deps( array('--install=1', '--updatecli=1' ) );
			
			echo "Rebuilding Exim for security patch ...\n";
			_republishExim(array('rebuild' => 1));		
			
			echo "Updating ClamAV version ...\n";
			_republishAv(array('rebuild' => 1));
			
		}
	
	}
	
	/************************************************* 6.2.3 *******************************************************/
	function _6_2_3()
	{
		// 6.2.3 update
		if(!$this->client)
		{
			echo "Correcting directory permissions..\n";
			if(file_exists('/usr/local/atmail/webmail/config'))
			{
				system('chown atmail /usr/local/atmail/webmail/config');	
			}
			if(file_exists('/usr/local/atmail/webmail/log'))
			{
				system('chown -R atmail /usr/local/atmail/webmail/log');	
			}
			if(file_exists('/usr/local/atmail/webmail/library/HTMLPurifier/DefinitionCache/Serializer/HTML'))
			{
				system('chown -R atmail /usr/local/atmail/webmail/library/HTMLPurifier/DefinitionCache/Serializer/HTML');	
			}
		}
	}
	
	/************************************************* 6.2.2 *******************************************************/
	function _6_2_2()
	{
		// 6.20.2 update	
		_patchCalendarServer();
	}
	
	/************************************************* PLACE HOLDER 6.2.1 *******************************************************/
	/************************************************* 6.2 *******************************************************/
	function _6_2()
	{
		if(!$this->client)
		{
			echo "Adding Atmail automation script for AV/Spam updates..\n";
			system('php /usr/local/atmail/server_source/scripts/buildav.php');
		}
	}
	
	/************************************************* 6.1.9 *******************************************************/
	function _6_1_9()
	{
		_patchCalendarServer();
	}
	
	/************************************************* 6.1.8 *******************************************************/
	function _6_1_8()
	{
		_patchCalendarServer();
	
		if(!$this->client)
		{
			echo "Correcting spam assassin permissions..\n";
			if(file_exists('/usr/local/atmail/spamassassin/etc/sqlsettings.cf'))
			{
				system('chown -R atmail /usr/local/atmail/spamassassin');	
			}
			
			_republishDovecot(array('updateAuth'=>1, 'updateDB'=>1));
					
			echo "Updating user creation files..\n";
			$output = `cp /usr/local/atmail/server_source/etc/create-imap.sh /usr/local/atmail/mailserver/etc/create-imap.sh`;
			echo $output . "\n";
			$output = `cp /usr/local/atmail/server_source/etc/create-pop.sh /usr/local/atmail/mailserver/etc/create-pop.sh`;
			echo $output . "\n";
	
			_republishExim();
		}
	}
	
	/************************************************* 6.1.7 *******************************************************/
	function _6_1_7()
	{
		if(!$this->client)
		{
			_republishExim();
		}
	}
	
	/************************************************* PLACE HOLDER 6.1.6 *******************************************************/
	/************************************************* PLACE HOLDER 6.1.5 *******************************************************/
	/************************************************* 6.1.4 *******************************************************/
	function _6_1_4()
	{
		_patchCalendarServer();
		
		if(!$this->client)
		{
			echo "Correcting spamassassin sql settings config permissions..\n";
			system("chown atmail:atmail /usr/local/atmail/spamassassin/etc/sqlsettings.cf");
			
			_republishDovecot(array('updateAll'=>1, 'updateDB'=>1));
		} 
	}
	
	/************************************************* 6.1.3 *******************************************************/
	function _6_1_3()
	{
		if(!$this->client)
		{
			// call the dep checker
			echo "Checking new dependancy requirements..\n";
			check_deps( array('--install=1', '--updatecli=1' ) );
			
			// depcheck has already installed mysql ( I HOPE SO! ) so no need to check for sql restart
			if(file_exists('/usr/local/atmail/webmail/library/Atmail/.mysqlrestart'))
			{
				unlink('/usr/local/atmail/webmail/library/Atmail/.mysqlrestart');
			}
			
			_republishExim(array('rebuild'=>1));
			_republishDovecot(array('rebuild'=>1, 'updateAll'=>1));
		
			echo "Updating Spamassassin configuration file..\n";
			$output = `cp /usr/local/atmail/server_source/etc/local.cf /usr/local/atmail/spamassassin/etc/local.cf`;
			system("chown atmail /usr/local/atmail/spamassassin/etc/local.cf");
			system("mkdir /usr/local/atmail/spamassassin/bayes");
			system("chown atmail /usr/local/atmail/spamassassin/bayes");
			config::publishServerConfigFiles('spamassassin');
			system("chown atmail:atmail /usr/local/atmail/spamassassin/etc/sqlsettings.cf");
			
			echo "Updating SQL settings to configuration files..\n";
			config::modifyDbConfigInExistingServerConfigFiles($global);
		}
	}
	
	/************************************************* 6.1.2 *******************************************************/
	function _6_1_2()
	{
		_patchCalendarServer();
	}
	
	/************************************************* 6.1.1 *******************************************************/
	function _6_1_1()
	{
		if(!$this->client)
		{
			_republishExim();
			_republishDovecot(array('rebuild'=>1, 'publishDB'=>1, 'updateAuth'=>1));
			
			echo "Changing ownership of /usr/local/atmail/users to chmod 700 for security..\n";
			for ($i=97; $i <= 123; $i++)
	    	{
	            if ($i == 123)
				{
	                    $a = 'other';
	            }
				else
				{
	                    $a = chr($i);
				}			
	            system("chmod -R 700 /usr/local/atmail/users/$a");
				echo ".";
	    	}
			echo "\n";
		}
	}
	
	/************************************************* 6.1 *******************************************************/
	function _6_1()
	{
		if(!$this->client)
		{
			_republishDovecot(array('rebuild'=>1));
		    $output = `chown -R atmail /usr/local/atmail/webmail/log/`;
		  	echo $output . "\n";
		}
		
		_patchCalendarServer();
	}
	
	
	/************************************************* 6.0.11 *******************************************************/
	function _6_0_11()
	{
		if(!$this->client)
		{
			echo "Updating Atmail service startup script\n";	
			if (file_exists('/etc/init.d'))
			{
			    system("cp -f /usr/local/atmail/server_source/scripts/atmailserver.sysvinit /etc/init.d/atmailserver");
			    system("chmod 755 /etc/init.d/atmailserver");           
			}
			elseif (file_exists('/etc/rc.d/'))
			{
				system("cp /usr/local/atmail/server_source/scripts/atmailserver.sysvinit /etc/rc.d/atmailserver");
				system("chmod 755 /etc/rc.d/atmailserver");
			}
			elseif (file_exists("/usr/local/etc/rc.d/"))
			{
				system("cp /usr/local/atmail/server_source/scripts/atmailserver.sysvinit /usr/local/etc/rc.d/z-atmailserver.sh");
				system("chmod 755 /usr/local/etc/rc.d/z-atmailserver.sh");
			}
			else
			{
				fwrite(STDOUT, "Please copy the /usr/local/atmail/server_source/scripts/atmailserver.sysvinit to your system startup file");
			}
		}
	}
	
	
	/************************************************* 6.0.10 *******************************************************/
	function _6_0_10()
	{
		if(!$this->client)
		{	
			_republishExim();
		}
	}
	
	/************************************************* 6.0.9 *******************************************************/
	function _6_0_9()
	{
		if(!$this->client)
		{
			_republishExim();
	
			_republishAv(array('rebuild' => 1));
		
			echo "Adding Atmail automation script for AV/Spam updates\n";
			if (file_exists("/etc/cron.daily/"))
			{
				copy("/usr/local/atmail/server_source/scripts/atmail-automation.php", "/etc/cron.daily/atmail-automation.php");
				system("chmod 755 /etc/cron.daily/atmail-automation.php");
				system("php /etc/cron.daily/atmail-automation.php");
			}
			elseif (file_exists("/etc/periodic/daily/"))
			{
				copy("/usr/local/atmail/server_source/scripts/atmail-automation.php", "/etc/periodic/daily/502.atmail-automation.php");
				system("chmod 755 /etc/periodic/daily/502.atmail-automation.php");
				system("php /etc/periodic/daily/502.atmail-automation.php");
			}
			else
			{
				echo "NOTE: Daily cron directory not detected on system. Please configure the system\ncrontab to automatically run the:\n\n/usr/local/atmail/server_source/scripts/atmail-automation.php command on a daily basis.\n\nThis is required to download the latest AV and Anti-Spam files.\n";
			}
		}
		
		_reinstallCalendarServer();
	}
	
	/************************************************* 6.0.8 *******************************************************/
	function _6_0_8()
	{
		_reinstallCalendarServer();
	}
	
	/************************************************* 6.0.7 *******************************************************/
	function _6_0_7()
	{
		if(!$this->client)
		{
			_republishExim();
		}
	}
	
	/************************************************* 6.0.5 *******************************************************/
	function _6_0_5()
	{
		if(!$this->client)
		{
			_republishExim(array('rebuild'=>1));
			_republishDovecot(array('updatessl'=>1));
		}
		
		_patchCalendarServer();
	}
	
	// overload updateAll function to set previous
	// updates cli status
	//
	// no cli.version or cli.version == null means previous
	// cli update has completed or was not required
	public function updateAll()
	{
		$result = parent::updateAll();
		$this->updateConfig('global', 'cli.version', '', 'String');
		return $result;		
	}
	
	public function filterVersions($versions_in)
	{
		$versions = array();
		$dbVersion = generateVersionString($this->dbAdapter->fetchOne('select keyValue from Config where keyName = "version"'), true);
		foreach($versions_in as $version)
		{
			if( version_compare($dbVersion, generateVersionString($version, true), '>='))
			{
				$versions[] = $version;
			}
		}
		return $versions;
	}
	
	// ****** CLASS DEFINED HERE ****** //
	public function __construct(&$dbAdapter, $client = false)
	{
		parent::__construct($dbAdapter);
		$this->setKeyname('cli.version');
		$this->client = $client;
	}	
}
