<?php
/*
* Copyright (c) 2009-2010 ATMAIL. All rights reserved
* See http://atmail.com/license.php for license agreement
*/
/**
 * Import users from csv file into Atmail6
 *
 * csv format:
 * username, password, domainname, firstname, lastname, passwordhint, 
 * date-of-birth (yyyy-mm-dd), home-address, home-city, home-state, home-postcode, home-country,
 * home-phone, work-phone, mobile-phone, quota, user-group
 *
 * @author : Brad Kowalczyk
 */

ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . '../../library');
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . '../../library/Pear/');
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . '../../application/models');
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . '../../');

require_once('Mail/RFC822.php');

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

// 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);

require_once 'Zend/Loader/Autoloader.php';
$loader = Zend_Loader_Autoloader::getInstance();
//$loader->registerNamespace('App_'); //for model namespacing
$loader->setFallbackAutoloader(true);
$loader->suppressNotFoundWarnings(false);
Zend_Loader::loadFile('Atmail/General.php', null, true);
Zend_Loader::loadFile('Atmail/Exception.php', null, true);


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

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

// Get database configuration    
$dbConfig = new Zend_Config_Ini('config/dbconfig.ini', 'production');
Zend_Registry::set('dbConfig', $dbConfig);
$dbAdapter = Zend_Db::Factory($dbConfig->database);
$dbAdapter->query("SET NAMES 'utf8'");
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'] < 3) {
    die("Usage: php user-import.php [/path/to/users.csv] [admin-username]\n");    
}

$file = $_SERVER['argv'][1];

if (!$fh = fopen($file, 'r')) {
    die("Could not open $file\n");    
}

require_once('../../application/models/api.php');
$_SERVER['PHP_AUTH_USER'] = $_SERVER['argv'][2];
$api = new api( array('directApi' => 1) );

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

while (false !== $user = fgetcsv($fh, 10000, ",")) {
    // Skip blank lines
    if (is_null($user[0]))
        continue;

    // Trim whitespace from start/end of values
    $user = array_map('trim', $user);

    // Skip if migrate file is invalid
    if ( !$user[1] || !$user[2] )
        continue;

    // Add domain if it does not exist
    if (!in_array($user[2], $domains)) {
        fwrite(STDOUT, "Adding new domain-name $user[2]...");
        $res = $api->domainCreate($user[2]);
        if ($res['status']) {
            fwrite(STDOUT, "OK\n");
			$domains[] = $user[2];
        } else {
            fwrite(STDOUT, "ERROR: {$res['msg']}\n");
        }
    }
        
    // Add user
    $userData = array();
    $userData['name']             = "$user[0]@$user[2]";
    $userData['username']         = $user[0];
    $userData['Password']         = $user[1];
    $userData['Domain']           = $user[2];
    $userData['UserFirstName']    = (isset($user[3])) ? ucfirst($user[3]) : '';
    $userData['UserLastName']     = (isset($user[4])) ? ucfirst($user[4]) : '';
    $userData['PasswordQuestion'] = $user[5];
    $userData['UserDOB']          = $user[6];
    $userData['UserHomeAddress']  = $user[7];
    $userData['UserHomeCity']     = $user[8];
    $userData['UserHomeState']    = $user[9];
    $userData['UserHomeZip']      = $user[10];
    $userData['UserHomeCountry']  = $user[11];
	$userData['numberFieldName']  = array('UserHomePhone', 'UserWorkPhone', 'UserHomeMobile');
    $userData['numberValue']      = array($user[12], $user[13], $user[14]);
    $userData['UserQuota']        = $user[15];
    $userData['Ugroup']           = (isset($user[16])) ? $user[16] : 'Default';
    
    fwrite(STDOUT, "Adding user {$userData['name']}... ");

	try {
	    $res = $api->userCreate($userData);		
	} catch( Exception $e ) {
		//print_r($e);
        fwrite(STDOUT, "ERROR: " . $e->getMessage() . "\n");		
	}
 
   if ($res['status']) {
        fwrite(STDOUT, "OK\n");
    }

}

fwrite(STDOUT, "DONE\n");
