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

/**
* Add a user
*
* Arguments:
* php ldap-add-user.php [username] [password] [domain]
*
* @author : Ben Duncan
*/

// set this to skip usernames that exist on other domains (handy for username only installations)
$CHECK_DOMAINS = false;

ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . '/usr/local/atmail/webmail/library');
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . '/usr/local/atmail/webmail/application/models');
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . '/usr/local/atmail/webmail/');
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . '/usr/local/atmail/webmail/library/Pear/');

//Error reporting
error_reporting(E_ALL & ~E_NOTICE);
ini_set('display_startup_errors', 0);
ini_set('display_errors', 0);

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

// remove php time limit
set_time_limit(0);

mb_internal_encoding('UTF-8');
iconv_set_encoding("internal_encoding", "UTF-8");//setting gave grief at some point, i suspect it was surrounding Lucene, but needed for ZF mime header decoding. this doesnt work, possible because conflicts with php.ini setting
iconv_set_encoding("input_encoding", "BASE-64");
iconv_set_encoding("output_encoding", "UTF-8");

//Site application root and paths
//all references to directories have / appended to eliminate posibility of direcory reference composition resulting in '/....' as in root
//i.e. when composing a directory string, all components dont/cant/wont start with a / eliminating the possibility if a resulting string referring to OS root
define('APP_ROOT', dirname(__FILE__) . '' . DIRECTORY_SEPARATOR);

//Setup Zend Loader
require_once 'Zend/Loader/Autoloader.php';
$loader = Zend_Loader_Autoloader::getInstance();
//$loader->registerNamespace('App_'); //for model namespacing
$loader->setFallbackAutoloader(true);
$loader->suppressNotFoundWarnings(false);



$siteBaseUrl = substr($_SERVER["SCRIPT_NAME"],0,strpos($_SERVER["SCRIPT_NAME"],'index.php'));

Zend_Registry::set( 'siteBaseUrl', $siteBaseUrl );

//Load general functions
Zend_Loader::loadFile('Atmail/General.php', null, true);
Zend_Loader::loadFile('Atmail/Exception.php', null, true);

// Get database configuration
$dbConfig = new Zend_Config_Ini('config/dbconfig.ini', 'production');
Zend_Registry::set('dbConfig', $dbConfig);
$dbAdapter = dbAdapterFactory($dbConfig);
Zend_Db_Table::setDefaultAdapter($dbAdapter);
Zend_Registry::set('dbAdapter', $dbAdapter);

//Get main configuration from database
$config = new Atmail_Config_Mysql($dbConfig, true);

//$config->global['cacheEnabled'] = false;
$config->global['allowLocalPop3'] = true; //for testing/debugging
$config->global['allowLocalImap'] = true; //for testing/debugging
Zend_Registry::set('config', $config);

$locale = new Zend_Locale();
Zend_Registry::set('Zend_Locale', $locale);

$log = new Atmail_Log();
$log->addPriority('atmail', 10);
$log->addPriority('sysadmin', 20);
$log->addPriority('imap', 30);
$log->addPriority('firebug', 40);

$logBasePath = APP_ROOT . 'log' . DIRECTORY_SEPARATOR;
Zend_Registry::set('log', $log);

unset($config);
unset($settings);

if ($_SERVER['argc'] < 2)
{
	die("Usage: php ldap-add-user.php [email] [password] [usergroup, optional]\n");
}

require_once('/usr/local/atmail/webmail/application/models/api.php');
$_SERVER['PHP_AUTH_USER'] = "admin";

$api = new api( array('directApi' => 1) );

$domList = $api->domainList();
$domains = array();
foreach ($domList as $dom)
{
	$domains[] = $dom['DomainName'];
}

// Load the arguments, username, password, domain
$user = array();
$user[0] = $_SERVER['argv']['1'];
$email = explode("@", $user[0]);

$user[1] = $_SERVER['argv']['2'];

// Optionally, laod the user-group
if(isset($_SERVER['argv']['3']))
$user[2] = $_SERVER['argv']['3'];

if (!isset($email[1]))
{
	fwrite(STDOUT, "Domain name required in email, please specify");
	exit;
}

// Add user
$userData = array();
$userData['name']             = $user[0];
$userData['username']         = $email[0];
$userData['Password']         = $user[1];
$userData['Domain']           = $email[1];
$userData['Ugroup']           = (isset($user[3])) ? $user[3] : 'Default';

if(strpos($user[0], '@') !== false)
{
	list($username, $domain) = explode('@', $user[0]);
}

try
{
	if($CHECK_DOMAINS)
	{
		$users = $api->userList();

		foreach($users as $userRecord)
		{
			if(strpos($userRecord['Account'], '@') !== false)
			{
				list($userRecord_username, $userRecord_domain) = explode('@', $userRecord['Account']);
				if($userRecord_username == $username)
				{
					exit(10);
				}
			}
			else
			{
				continue;
			}
		}
	}
	// Add domain if it does not exist
	if (!in_array($email[1], $domains))
	{
		$res = $api->domainCreate($email[1]);
		if ($res['status'])
		{
		}
		else
		{
			fwrite(STDOUT, "ERROR: {$res['msg']}\n");
			exit(10);
		}
	}
	$res = $api->userCreate($userData);
}
catch( Exception $e )
{
	fwrite(STDOUT, "ERROR: " . $e->getMessage() . "\n");
	exit(10);
}

exit(0);
