#!/usr/bin/php
<?php
/**
    @file
    @brief Moves Mail from one IMAP account to another

Copyright (C) 2009 Edoceo, Inc

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Run Like:
    php ./imap-move.php \
        --source imap-ssl://userA:secret-password@imap.example.com:993/ \
        --target imap-ssl://userB:secret-passwrod@imap.example.com:993/sub-folder \
        [ --wipe --fake --copy ]

    --fake to just list what would be copied
    --wipe to remove messages after they are copied
    --copy to store copies of the messages in a path

*/

error_reporting(E_ALL | E_STRICT);

_args($argc,$argv);

echo "Connecting Source...\n";
$S = new IMAP($_ENV['src']);

echo "Connecting Target...\n";
$T = new IMAP($_ENV['tgt']);

$src_path_list = $S->listPath();
foreach ($src_path_list as $path) {

    echo "S: path {$path['name']} = {$path['attribute']}\n";

    // Skip Logic Below
    if (_path_skip($path)) {
        echo "S: skip {$path['name']}\n";
        continue;
    }

    // Source Path
    $S->setPath($path['name']);
    $src_path_stat = $S->pathStat();
    // print_r($src_path_stat);
    echo "S: {$src_path_stat['mail_count']} messages\n";
    if (empty($src_path_stat['mail_count'])) {
        echo "S: skip\n";
        continue;
    }

    // Target Path
    $tgt_path = null;
    if (preg_match('/}(.+)$/',$path['name'],$m)) {
        $tgt_path = strtolower($m[1]);
        if ($tgt_path == 'inbox') $tgt_path = null;
    }
    $T->setPath($tgt_path); // Creates if needed

    // Show info on Target
    $tgt_path_stat = $T->pathStat();
    echo "T: {$tgt_path_stat['mail_count']} messages\n";

    // Build Index of Target
    echo "T: Indexing....\n";
    $tgt_mail_list = array();
    for ($i=1;$i<=$tgt_path_stat['mail_count'];$i++) {
        $mail = $T->mailStat($i);
        $tgt_mail_list[ $mail['message_id'] ] = $mail['subject'];
    }
    // print_r($tgt_mail_list);
    // for ($i=1;$i<=$src_path_stat['mail_count'];$i++) {
    for ($i=$src_path_stat['mail_count'];$i>=1;$i--) {

        $stat = $S->mailStat($i);
        $stat['answered'] = trim($stat['Answered']);
        $stat['unseen'] = trim($stat['Unseen']);
        // print_r($stat['message_id']); exit;

        if (array_key_exists($stat['message_id'],$tgt_mail_list)) {
            echo "Source: Mail: {$stat['subject']} Copied Already\n";
            $S->mailWipe($i);
            continue;
        }

        echo "S: {$stat['subject']} {$stat['MailDate']}\n";

        $S->mailGet($i);
        $opts = array();
        if (empty($stat['unseen'])) $opts[] = '\Seen';
        if (!empty($stat['answered'])) {
            // var_dump($stat);
            // die("Answered!");
            $opts[] = '\Answered';
        }
        $opts = implode(' ',$opts);
        $date = strftime('%d-%b-%Y %H:%M:%S +0000',strtotime($stat['MailDate']));
        // echo "mailPut(file_get_contents('mail'),$opts,$date);\n";
        if ($_ENV['fake']) {
            continue;
        }

        $res = $T->mailPut(file_get_contents('mail'),$opts,$date);
        echo "T: $res\n";
        $S->mailWipe($i);

        if ($_ENV['once']) die("--one and done\n");

    }
}

class IMAP
{
    private $_c; // Connection Handle
    private $_c_host; // Server Part {}
    private $_c_base; // Base Path Requested
    /**
        Connect to an IMAP
    */
    function __construct($uri)
    {
        $this->_c = null;
        $this->_c_host = sprintf('{%s',$uri['host']);
        if (!empty($uri['port'])) {
            $this->_c_host.= sprintf(':%d',$uri['port']);
        }
        switch (strtolower(@$uri['scheme'])) {
        case 'imap-ssl':
            $this->_c_host.= '/ssl';
            break;
        case 'imap-tls':
            $this->_c_host.= '/tls';
            break;
        default:
        }
        $this->_c_host.= '}';

        $this->_c_base = $this->_c_host;
        // Append Path?
        if (!empty($uri['path'])) {
            $x = ltrim($uri['path'],'/');
            if (!empty($x)) {
                $this->_c_base = $x;
            }
        }
        echo "imap_open($this->_c_host)\n";
        $this->_c = imap_open($this->_c_host,$uri['user'],$uri['pass']);
        // echo implode(', ',imap_errors());
    }
    /**
        List folders matching pattern
        @param $pat * == all folders, % == folders at current level
    */
    function listPath($pat='*')
    {
        $ret = array();
        $list = imap_getmailboxes($this->_c, $this->_c_host,$pat);
        foreach ($list as $x) {
            $ret[] = array(
                'name' => $x->name,
                'attribute' => $x->attributes,
                'delimiter' => $x->delimiter,
            );
        }
        return $ret;
    }

    /**
        Get a Message
    */
    function mailGet($i)
    {
        // return imap_body($this->_c,$i,FT_PEEK);
        return imap_savebody($this->_c,'mail',$i,null,FT_PEEK);
    }

    /**
        Store a Message with proper date
    */
    function mailPut($mail,$opts,$date)
    {
        $stat = $this->pathStat();
        // print_r($stat);
        // $opts = '\\Draft'; // And Others?
        // $opts = null;
        // exit;
        $ret = imap_append($this->_c,$stat['check_path'],$mail,$opts,$date);
        print_r(imap_errors());
        return $ret;

    }

    /**
        Message Info
    */
    function mailStat($i)
    {
        $head = imap_headerinfo($this->_c,$i);
        return (array)$head;
        // $stat = imap_fetch_overview($this->_c,$i);
        // return (array)$stat[0];
    }

    /**
        Immediately Delete and Expunge the message
    */
    function mailWipe($i)
    {
        if ( ($_ENV['wipe']) && (imap_delete($this->_c,$i)) ) return imap_expunge($this->_c);
    }

    /**
        Sets the Current Mailfolder, Creates if Needed
    */
    function setPath($p,$make=false)
    {
        // echo "setPath($p);\n";
        if (substr($p,0,1)!='{') {
            $p = $this->_c_host . trim($p,'/');
        }
        // echo "setPath($p);\n";

        $ret = imap_reopen($this->_c,$p);
        // print_r($ret);
        print_r(imap_errors());

        // $ret = imap_createmailbox($this->_c,$p);
        // // print_r($ret);
        // print_r(imap_errors());

        return $ret;
    }

    /**
        Returns Information about the current Path
    */
    function pathStat()
    {
        $res = imap_mailboxmsginfo($this->_c);
        $ret = array(
            'date' => $res->Date,
            'path' => $res->Mailbox,
            'mail_count' => $res->Nmsgs,
            'size' => $res->Size,
        );
        $res = imap_check($this->_c);
        $ret['check_date'] = $res->Date;
        $ret['check_mail_count'] = $res->Nmsgs;
        $ret['check_path'] = $res->Mailbox;
        // $ret = array_merge($ret,$res);
        return $ret;
    }
}

/**
    Process CLI Arguments
*/
function _args($argc,$argv)
{

    $_ENV['src'] = null;
    $_ENV['tgt'] = null;
    $_ENV['copy'] = false;
    $_ENV['fake'] = false;
    $_ENV['once'] = false;
    $_ENV['wipe'] = false;

    for ($i=1;$i<$argc;$i++) {
        switch ($argv[$i]) {
        case '--source':
        case '-s':
            $i++;
            if (!empty($argv[$i])) {
                $_ENV['src'] = parse_url($argv[$i]);
            }
            break;
        case '--target':
        case '-t': // Destination
            $i++;
            if (!empty($argv[$i])) {
                $_ENV['tgt'] = parse_url($argv[$i]);
            }
            break;
        case '--copy':
            // Given a Path to Copy To?
            $chk = $argv[$i+1];
            if (substr($chk,0,1)!='-') {
                $_ENV['copy_path'] = $chk;
                if (!is_dir($chk)) {
                    echo "Creating Copy Directory\n";
                    mkdir($chk,0755,true);
                }
                $i++;
            }
            break;
        case '--fake':
            $_ENV['fake'] = true;
            break;
        case '--once':
            $_ENV['once'] = true;
            break;
        case '--wipe':
            $_ENV['wipe'] = true;
            break;
        default:
            echo "arg: {$argv[$i]}\n";
        }
    }
    
    if ( (empty($_ENV['src']['path'])) || ($_ENV['src']['path']=='/') ) {
        $_ENV['src']['path'] = '/INBOX';
    }
    if ( (empty($_ENV['tgt']['path'])) || ($_ENV['tgt']['path']=='/') ) {
        $_ENV['tgt']['path'] = '/INBOX';
    }
}

/**
    @return true if we should skip this path
*/
function _path_skip($path)
{
    $ret = false;
    if ( ($path['attribute'] & LATT_NOSELECT) == LATT_NOSELECT) {
        $ret = true;
    }
    // All Mail, Trash, Starred have this attribute
    if ( ($path['attribute'] & 96) == 96) {
        $ret = true;
    }
    // Skip by Pattern
    if (preg_match('/}(.+)$/',$path['name'],$m)) {
        switch ($m[1]) {
        case '[Gmail]/All Mail':
        case '[Gmail]/Sent Mail':
        case '[Gmail]/Spam':
        case '[Gmail]/Starred':
            $ret = true;
            break;
        }
    }

    return $ret;
}

