<?php

/**
 * Command line learn driver
 * @version 1.1
 * @author Philip Weir
 * Patched by Julien Vehent to support DSPAM
 */
function learn_spam($uids)
{
    do_salearn($uids, true);
}

function learn_ham($uids)
{
    do_salearn($uids, false);
}

function do_salearn($uids, $spam)
{
    $rcmail = rcmail::get_instance();
    $temp_dir = realpath($rcmail->config->get('temp_dir'));

    if ($spam)
        $command = $rcmail->config->get('markasjunk2_spam_cmd');
    else
        $command = $rcmail->config->get('markasjunk2_ham_cmd');

    if (!$command)
        return;

    $command = str_replace('%u', $_SESSION['username'], $command);
    $command = str_replace('%l', $rcmail->user->get_username('local'), $command);
    $command = str_replace('%d', $rcmail->user->get_username('domain'), $command);

    $identity_arr = $rcmail->user->get_identity();
    $command = str_replace('%i', $identity_arr['email'], $command);

    foreach (explode(",", $uids) as $uid) {

        $raw_message = $rcmail->imap->get_raw_body($uid);

        $tmpfname = tempnam($temp_dir, 'rcmSALearn');
        file_put_contents($tmpfname, $raw_message);

        $tmp_command = str_replace('%f', $tmpfname, $command);

        // get dspam signature header (if %s macro is used)
        if(preg_match("/%s/",$command)){

            preg_match("/X-DSPAM-Signature: (.*)/i",$raw_message, $match);
            $dspam_signature = $match[1];

            $tmp_command = str_replace('%s', $dspam_signature,$command);
        }
        exec($tmp_command, $output);

        if ($rcmail->config->get('markasjunk2_debug')) {
            write_log('markasjunk2', $tmp_command);
            write_log('markasjunk2', $output);
        }

        unlink($tmpfname);
        $output = '';
    }
}

?>