<?php

/**
 * Migrate adapter for migrating from SquirrelMail to Atmail.
 * 
 * @todo Need to implement pulling of settings/abook data from a DB if
 *     one is specified in config.php. At the moment we only support
 *     flat file storage scheme.
 * @author Brad Kowalczyk <brad@staff.atmail.com>
 */
 
 class Atmail_Migrate_Adapter_Squirrelmail implements Atmail_Migrate_Adapter_Interface {

	private $_currentUser;
	private $_dh;
    private $_dataDir;
    private $_migrateSingleUser;
    
    
	public function __construct($path, $account=null)
	{
        // If $path is a directory then we ought to assume that
        // the user has passed the data directory path, otherwise
        // we treat is as the path to SquirrelMail config file
        if (is_dir($path)) {
            $this->_dataDir = $path;
        } else {
            require_once($path);
            $this->_dataDir = $data_dir;
        }
                    
        if (!is_dir($this->_dataDir) || !is_readable($this->_dataDir)) {
            die("Path to data dir '{$this->_dataDir}' is invalid!\n");
        }
        
        if (!$this->_dh = opendir($this->_dataDir)) {
            die("Could not open directory {$this->_dataDir} for reading\n");
        }
            
        if (!empty($account)) {
            $this->_currentUser = new Atmail_Migrate_Data_User();
            $this->_currentUser->name($account);
            $this->_migrateSingleUser = true;
        }
    
    }
	
	public function fetchUser()
	{
        if ($this->_migrateSingleUser) {
	        return $this->_currentUser;
        }
        
        if (isset($this->_contacts)) {
            fclose($this->_contacts);
            unset($this->_contacts);
        }
        
        // We need to keep reading the data dir till
        // we find a .pref file (every user has a .pref)
        // from this file we can determine the account name
		while ($file = readdir($this->_dh)) {
            
            if (substr($file, -4) != "pref") {
                continue;
            }
            
            // strip off the .pref extension so we have just
            // the account name
            $account = preg_replace("/\.pref$/", "", $file);
            
            $user = new Atmail_Migrate_Data_User();
            $user->name($account);
            $user->signature($this->_getSignature());
            
            // Read any preferences the user has saved
            $prefs = $this->_processPreferences();
            
            if ($prefs) {
                if (isset($prefs['reply_to'])) {
                    $user->replyTo($prefs['reply_to']);
                }
                
                if (isset($prefs['full_name'])) {
                    $user->realName($prefs['full_name']);
                }
                
                if (isset($prefs['timezone'])) {
                    $user->timeZone($prefs['timezone']);
                }
                
                if (isset($prefs['show_num'])) {
                    $user->msgNum($prefs['show_num']);
                }
                
                if (isset($prefs['language'])) {
                    $user->language($prefs['language']);
                }
            }
            
            $this->_currentUser = $user->name();
            return $user;
		}
        
        return false;
	}
	
    
    public function fetchSettings()
    {
        $settings = new Atmail_Migrate_Data_Settings;
        $settings->signature($this->_getSignature());
        
        // Read any preferences the user has saved
        $prefs = $this->_processPreferences();
        
        if ($prefs) {
            if (isset($prefs['reply_to'])) {
                $settings->replyTo($prefs['reply_to']);
            }
            
            if (isset($prefs['full_name'])) {
                $settings->realName($prefs['full_name']);
            }
            
            if (isset($prefs['timezone'])) {
                $settings->timeZone($prefs['timezone']);
            }
            
            if (isset($prefs['show_num'])) {
                $settings->msgNum($prefs['show_num']);
            }
            
            if (isset($prefs['language'])) {
                $settings->language($prefs['language']);
            }
            
            if (isset($prefs['attachment_common_show_images'])) {
                $settings->DisplayEmailImages($prefs['attachment_common_show_images']);
            }
        }
        
        return $settings;
    }
    
    
    protected function _getSignature()
    {
        $path = $this->_dataDir . "/" . $this->_currentUser->name() . ".sig";
        
        if (file_exists($path)) {
            return file_get_contents($path);
        }
        
        return "";
    }
    
    protected function _processPreferences()
    {
        $path = $this->_dataDir . "/" . $this->_currentUser->name() . ".pref";
        
        if ($prefs = parse_ini_file($path)) {
            return $prefs;
        }
        
        return false;
    }
    
	public function fetchEmail()
	{
        return false;
	}
	
    /**
     * Fetch contacts for a user
     * 
     * At this time only the flat file format
     * used by squirrelmail is supported.
     */
	public function fetchContact()
	{
		/* 
		CREATE TABLE "address" (
		  "owner" varchar(128) NOT NULL,
		  "nickname" varchar(16) NOT NULL,
		  "firstname" varchar(128) NOT NULL,
		  "lastname" varchar(128) NOT NULL,
		  "email" varchar(128) NOT NULL,
		  "label" varchar(255) NOT NULL,
		  CONSTRAINT "address_pkey" PRIMARY KEY ("nickname", "owner")
		);
		CREATE UNIQUE INDEX "address_firstname_key" ON "address"
		  ("firstname", "lastname");
		*/
		
        /*
		if (!isset($this->_contacts)) {
            $username = $this->_db->quote($this->_currentUser);
            //$userId = $this->_db->fetchOne("select user_id from {$this->_tablePrefix}users where username = $username"); 
            $this->_contacts = $this->_db->fetchAll("select email, firstname, lastname from {$this->_tablePrefix}address where owner = ?", $userId);
        }
        
        if (empty($this->_contacts)) {
            return false;
        }
        
        $c = array_pop($this->_contacts);
        */
        
        if (!isset($this->_contacts)) {
            
            $contactsFile = $this->_dataDir . "/" . $this->_currentUser->name() . ".abook";
            
            if (!file_exists($contactsFile)) {
                return false;
            }
            
            // If the current user has no .abook file then return false
            if (!$this->_contacts = fopen($contactsFile, "r")) {
                return false;
            }
        }
        
        // If we have reached the end of the file or there is an
        // error (file corrupted?) then return false which indicates
        // that there are no more contacts for the current user
        if (false === $line = fgets($this->_contacts)) {
            return false;
        }
        
        list($nick, $firstName, $lastName, $email, $info) = explode("|", $line);
        $contact = new Atmail_Migrate_Data_Contact;
        $contact->email($email);
        $contact->firstName($firstName);
        $contact->lastName($lastName);
        $contact->info($info);
        return $contact;
	}
	
    /**
     * Squirrelmail does not support contact groups
     * so we just return false
     */
    public function fetchContactGroup()
	{
		return false;
	}
    
	public function fetchCalEvent()
	{
		return false;
	}

}
