<?php
/**
 * $Horde: ingo/rule.php,v 1.63.8.1 2005/01/03 12:25:37 jan Exp $
 *
 * Copyright 2002-2005 Mike Cochrane <mike@graftonhall.co.nz>
 * Copyright 2003-2005 Michael Slusarz <slusarz@bigworm.colorado.edu>
 *
 * See the enclosed file LICENSE for license information. If you
 * did not receive this file, see http://www.horde.org/licenses.
 */

/* Define the key to use to indicate a user-defined header is
 * requested. */
define('INGO_USER_HEADER', '++USER_HEADER++');

@define('INGO_BASE',  dirname(__FILE__));
require_once INGO_BASE . '/lib/base.php';
require_once INGO_BASE . '/lib/Driver.php';

/* Load the Ingo_Script:: driver. */
$ingo_script = &Ingo::loadIngoScript();

/* Redirect if no rules are available. */
$availActions = $ingo_script->availableActions();
if (empty($availActions)) {
    $notification->push(_("Individual rules are not supported in the current filtering driver."), 'horde.error');
    header('Location: ' . Horde::applicationUrl('filters.php', true));
    exit;
}

/* This provides the $ingo_fields array. */
require INGO_BASE . '/config/fields.php';

/* Get the current rules. The current rule will be stored in $rule. */
$edit_number = Util::getFormData('edit');
$filters = $ingo_storage->retrieve(INGO_STORAGE_ACTION_FILTERS);

/* Run through action handlers. */
$actionID = Util::getFormData('actionID');
switch ($actionID) {
case 'create_folder':
case 'rule_save':
case 'rule_update':
case 'rule_delete':
    $rule = array();
    $rule['name'] = Util::getFormData('name');
    $rule['combine'] = Util::getFormData('combine');
    $rule['conditions'] = array();

    $field = Util::getFormData('field');
    $match = Util::getFormData('match');
    $userheader = Util::getFormData('userheader');
    $value = Util::getFormData('value');
    if ($ingo_script->caseSensitive()) {
        $casesensitive = Util::getFormData('case');
    }
    foreach ($field as $key => $val) {
        if (!empty($val)) {
            $condition = array();
            if ($val == INGO_USER_HEADER) {
                $condition['field'] = (empty($userheader[$key])) ? '' : $userheader[$key];
                $condition['type'] = INGO_STORAGE_TYPE_HEADER;
            } else {
                $condition['field'] = $val;
                $condition['type'] = $ingo_fields[$val]['type'];
            }
            $condition['match'] = isset($match[$key]) ? $match[$key] : '';
            $condition['value'] = isset($value[$key]) ? $value[$key] : '';
            if (isset($casesensitive)) {
                $condition['case'] = isset($casesensitive[$key]) ? $casesensitive[$key] : '';
            }
            $rule['conditions'][] = $condition;
        }
    }

    if ($actionID == 'create_folder') {
        $rule['action-value'] = Util::getFormData('new_folder_name');
        Ingo::createFolder($rule['action-value']);
    } else {
        $rule['action-value'] = Util::getFormData('actionvalue');
    }

    $rule['action'] = Util::getFormData('action');
    $rule['stop'] = Util::getFormData('stop');

    $rule['flags'] = 0;
    $flags = Util::getFormData('flags', array());
    if (!empty($flags)) {
        foreach ($flags as $val) {
            $rule['flags'] |= $val;
        }
    }

    /* Update the timestamp for the rules. */
    $_SESSION['ingo']['change'] = time();

    /* Save the rule. */
    if ($actionID == 'rule_save') {
        if (is_null($edit_number)) {
            $filters->addRule($rule);
        } else {
            $filters->updateRule($rule, $edit_number);
        }
        $ingo_storage->store($filters);
        $notification->push(_("Changes saved."), 'horde.success');

        if ($prefs->getValue('auto_update')) {
            Ingo::updateScript();
        }

        header('Location: ' . Horde::applicationUrl('filters.php'));
        exit;
    } elseif ($actionID == 'rule_delete') {
        $cond_num = Util::getFormData('conditionnumber');
        if (!is_null($cond_num)) {
            unset($rule['conditions'][$cond_num]);
            $rule['conditions'] = array_values($rule['conditions']);
        }
    }

    break;

default:
    if (is_null($edit_number)) {
        $rule = $filters->getDefaultRule();
    } else {
        $rule = $filters->getRule($edit_number);
    }
    break;
}

if (!$rule) {
    $notification->push(_("Filter not found."), 'horde.error');
    header('Location: ' . Horde::applicationUrl('filters.php', true));
    exit;
}

if ($registry->hasMethod('mail/createFolder')) {
    Horde::addScriptFile('new_folder.js');
}

$title = $rule['name'];
require INGO_TEMPLATES . '/common-header.inc';
require INGO_TEMPLATES . '/menu.inc';
require INGO_TEMPLATES . '/rule/header.inc';

/* Add new, blank condition. */
$rule['conditions'][] = array();

/* Available conditions. */
$avail_types = $ingo_script->availableTypes();
$lastcond = count($rule['conditions']) - 1;

/* Display the conditions. */
foreach ($rule['conditions'] as $cond_num => $condition) {
    $lastfield = ($lastcond == $cond_num) ? true : false;

    /* Create the field listing. */
    $field_select = '';
    $option_selected = !isset($condition['field']);

    if ($lastfield) {
        $field_select .= '<option value="">' . _("Select a field") . "</option>\n";
        $field_select .= "<option value=\"\"> --------- </option>\n";
    }

    foreach ($ingo_fields as $key => $val) {
        if (in_array($val['type'], $avail_types)) {
            $field_select .= '<option value="' . $key . '"';
            if (isset($condition['field'])) {
                if ($key == $condition['field']) {
                    $field_select .= ' selected';
                    $option_selected = true;
                }
            }
            $field_select .= '>' . $val['label'] . "</option>\n";
        }
    }

    /* Add user defined header option. */
    $header_entry = false;
    if ($conf['rules']['userheader']) {
        $field_select .= "<option value=\"\"> --------- </option>\n";
        $field_select .= '<option value="' . INGO_USER_HEADER . '"' . ((!$option_selected) ? ' selected' : '') . '>' . _("Self-Defined Header") . (($lastfield) ? '' : ':') . "</option>\n";
        if (!$option_selected) {
            $header_entry = true;
            $userheader = Util::getFormData('userheader');
            if (empty($userheader)) {
                $userheader = isset($condition['field']) ? $condition['field'] : '';
            } else {
                $userheader = $userheader[$cond_num];
            }
        }
    }

    if ($lastfield) {
        require INGO_TEMPLATES . '/rule/filter.inc';
        continue;
    }

    /* Create the match listing. */
    if (!isset($condition['field']) ||
        ($condition['field'] == INGO_USER_HEADER) ||
        !isset($ingo_fields[$condition['field']]['tests'])) {
        $avail_tests = $ingo_script->availableTests();
    } else {
        $avail_tests = $ingo_fields[$condition['field']]['tests'];
    }

    $match_select = '';

    if (empty($avail_tests)) {
        $match_select = "<option value=\"\"> --------- </option>\n";
    } else {
        foreach ($avail_tests as $test) {
            $testOb = $ingo_storage->getTestInfo($test);
            $match_select .= '<option value="' . $test . '"';
            if (!empty($condition['match'])) {
                if ($test == $condition['match']) {
                    $match_select .= ' selected';
                }
            }
            $match_select .= '>' . $testOb->label . "</option>\n";
        }
    }

    /* Create the matching input elements. */
    $testOb = $ingo_storage->getTestInfo(!empty($condition['match']) ? $condition['match'] : 'contains');
    $value = isset($condition['value']) ? htmlspecialchars($condition['value']): '';

    $match_value = '<input name="value[' . $cond_num . ']" size="40" value="' . $value . '" />';

    switch ($testOb->type) {
    case 'text':
        if ($ingo_script->caseSensitive()) {
            $match_value .= '<input type="checkbox" name="case[' . $cond_num . ']" value="1" ';
            $match_value .= (isset($condition['case']) && $condition['case']) ? 'checked="checked" ' : '';
            $match_value .= '/> ' . _("Case Sensitive");
        }
        break;
    }
    require INGO_TEMPLATES . '/rule/filter.inc';
}

/* Get the action select output. */
$actionselect = '';
$actionlist = $ingo_script->availableActions();
foreach ($actionlist as $val) {
    $actionselect .= '<option value="' . $val . '"';
    $action = $ingo_storage->getActionInfo($val);
    if ($val == $rule['action']) {
        $actionselect .= ' selected';
        $current_action = $action;
        $action->label .= ':';
    }
    $actionselect .= '>' . $action->label . "</option>\n";
}

/* Get the action value output. */
$actionvalue = '';
switch ($current_action->type) {
case 'folder':
    $actionvalue = Ingo::flistSelect($rule['action-value'], 'rule');
    break;

case 'text':
case 'int':
    $actionvalue = '<input name="actionvalue" size="40" value="' . $rule['action-value'] . '" />';
    break;
}

require INGO_TEMPLATES . '/rule/footer.inc';
require $registry->get('templates', 'horde') . '/common-footer.inc';
