<?php

// dbman_filter.inc.php - PHProjekt Version 5.0
// copyright  ©  2000-2005 Albrecht Guenther  ag@phprojekt.com
// www.phprojekt.com
// Author: Albrecht Guenther, $Author: paolo $
// $Id: dbman_filter.inc.php,v 1.60 2005/06/20 14:58:31 paolo Exp $


// provides column name as input field
function col_filter($module, $col_name, $link=null, $cw) {
    global $field_name, $field, $perpage, $page, $img_path, $f_sort, $user_ID;
    global $user_kurz, $sql_user_group, $ID, $page, $perpage, $mode, $keyword;

    $cw = $cw-10;
    if ($link == null) $link = $module;

    // start form
    $str  = "<form action='".$link.".php' name='".$field_name."' method='post' style='display:inline;'>\n";
    $str .= "<input type='hidden' name='mode' value='view' />";
    $str .= "<input type='hidden' name='filter_module' value='$module' />";


    $str .= "
<noscript>
    <a href='$link.php?mode=view&amp;sort_module=$module&amp;direction=ASC&amp;page=$page&amp;perpage=$perpage&amp;sort=$col_name'><img src='../img/ASC".((isset($_REQUEST['direction']) and isset($_REQUEST['sort']) and $_REQUEST['direction'] == 'ASC' and $_REQUEST['sort'] == $col_name) ? '_sel' : '').".gif' alt='ascending' /></a>
    <a href='$link.php?mode=view&amp;sort_module=$module&amp;direction=DESC&amp;page=$page&amp;perpage=$perpage&amp;sort=$col_name'><img src='../img/DESC".((isset($_REQUEST['direction']) and isset($_REQUEST['sort']) and $_REQUEST['direction'] == 'DESC' and $_REQUEST['sort'] == $col_name) ? '_sel' : '').".gif' alt='descending' /></a>
    <br/>
</noscript>
";


    // offer a select Box
    if ($field['form_type'] == 'select_values') {
        $str .= "<input type='hidden' name='rule' value='exact' />";
        $str .= enable_vars($field['form_name'])."<br/><select class='filter_fields' name='keyword'";
        if ($field['form_tooltip'] <> '') $str .= " title='".$field['form_tooltip']."'";
        $str .= read_o($read_o)." onchange='document.".$field_name.".submit();'>";
        // blank value with name of field
        $str .= "<option value=''>--</option>\n";
        foreach (explode('|',$field['form_select']) as $select_value) {
            // split the entry into key and value
            list($key,$value) = explode('#',$select_value);
            if (!$value) $value = $key;
            $str .= "<option value='".$key."'";
            if ($key == $field['value']) $str .= ' selected="selected"';
            $str .= '>'.enable_vars($value)."</option>\n";
        }
        $str .= "</select>\n";
    }

    // project list
    elseif ($field['form_type'] == 'project') {
        $str .= "<input type='hidden' name='rule' value='exact' />";
        $str .= enable_vars($field['form_name'])."<br/><select class='filter_fields' name='keyword'";
        if ($field['form_tooltip'] <> '') $str .= " title='".$field['form_tooltip']."'";
        $str .= read_o($read_o)." onchange='document.".$field_name.".submit();'>";
        $str .= "<option value=''>--</option>\n";
        $str .= show_elements_of_tree('projekte',
                                'name',
                                "where (von = '$user_ID' or acc like 'system' or ((acc like 'group' or acc like '%\"$user_kurz\"%') and $sql_user_group))",
                                'acc'," order by name", $keyword,'parent',0);
        $str .= "</select>\n";
    }
        // select Box on all users where the ID has been stored in this field
        elseif ( $field['form_type'] == 'select_sql' ) {
        $str .= enable_vars($field['form_name'])."<br/><select class='filter_fields' name='keyword'";
        if ($field['form_tooltip'] <> '') $str .= " title='".$field['form_tooltip']."'";
        $str .= read_o($read_o)." onchange='document.".$field_name.".submit();'>";
        // blank value with name of field
        $str .= "<option value=''>--</option>\n";
        $result = db_query(enable_vars($field['form_select']));
            while ($row = db_fetch_row($result)) {
                $first_element = array_shift($row);
                $str .= "<option value='".$first_element."'";
                if ($first_element == $field['value'])$str .= ' selected="selected"';
                $str .= ">".implode(',',$row)."</option>\n";
            }
            $str .= "</select>\n";
        }
    // otherwise a simple input box
    else {
        // define length of input field
        $field_length = ( enable_vars($field['form_name']) > 10) ? enable_vars($field['form_name']) : '10';
        $str .= "<input type='hidden' name='rule' value='like' />";
        $str .= enable_vars($field['form_name'])."<br/><input type='text' class='filter_fields' name='keyword' value=''";
        if ($field['form_type'] == 'contact') { $str .= read_o(1). "/>"; }
        else { $str .= " onfocus=\"this.value=''\" style='width:95%'/>"; }
    }
    // close form
    $hidden = array('filter_module'=>$module, 'mode'=>$mode,'filter'=>$field_name, 'ID'=>$ID,
                    'perpage'=>$perpage,'page'=>$page, 'sort'=>$sort, 'direction'=>$direction);
    if (SID) $hidden[session_name()] = session_id();
    $str .= hidden_fields($hidden);
    $str .= "</form>\n";
    // show icons to sort up and down

    return $str;
}


function main_filter($filter, $rule, $keyword, $filter_ID, $module, $firstchar='') {
    global $fields, $flist, $tablename, $flist_store, $filter_module;
    // 0. action: take values from storage
    if (!isset($flist[$module]) and $flist_store[$module]) { $flist[$module] = $flist_store[$module]; }
    // 1. action: check whether a filter element should be removed
    if (isset($filter_ID)) { unset($flist[$module][$filter_ID]); }
    // 2. action: add the current filter to the filter list
    // 2/a special filter for contacts - select all records where the last name begins with this char
    if ($firstchar <> '') {
        $flist[$module][] = array( 'nachname', 'begins', $firstchar );
    }
    // 2/b look for a 'normal filter
    elseif (isset($keyword) and strlen($keyword)!=0) {
        $flist[$module][] = array($filter,$rule,$keyword);
    }
    // 3. action: apply the filter list
    if ($flist[$module]) {
        // 3.1 apply the filter
        foreach ($flist[$module] as $key => $p_filter) {
            if ($p_filter[2] != '') {
                // if the field string is 'all', it has to be looped over all applicable fields
                $tmp = '';
                if ($p_filter[0] == 'all') { $tmp .= apply_full_filter($p_filter[1],$p_filter[2]); }
                else { $tmp .= apply_filter($p_filter[0],$p_filter[1],$p_filter[2]); }
                if(strlen($tmp)){
                    $where .= ' AND (';
                    $where .= $tmp;
                    $where .= ')';
                }
            }
        }
    }
    if (!$where) $where = ' AND 1=1 ';

    $_SESSION['flist'] =& $flist;
    // one result of the whole thing: the where clause for the sql query
    return $where;
}


function display_filters($module, $link=null) {
    global $flist, $fields, $action, $perpage, $page_n, $where;
    global $sid, $tablename, $ID, $mode;

    if (!$link) $link = $module;
      if ($flist[$module]) {
        $filter_list_text.= "<b>".__('Filtered').":</b> ";
        $i = 0;
        foreach ($flist[$module] as $key => $p_filter) {
            // first fetch the name
            foreach ($fields as $field_name => $field) {
                if ($field_name == $p_filter[0]) {
                    $filtername = enable_vars($field['form_name']);
                }
            }
            if ($i>0) $filter_list_text .= '+';
            // klick on link removes the filter
            $filter_list_text .= " (<a class='filter2' href='".$link.".php?mode=$mode&amp;ID=$ID&amp;filter_module=$module&amp;action=$action&amp;filter_ID=$key&amp;perpage=$perpage&amp;page=$page_n".$sid."' title='".__('Delete')."'>".
                                 $filtername.' '.$p_filter[1].' '.$p_filter[2]."</a>)\n";
            $i++;
        }
    }

/*
    $filter_list_text .= "<script language='javascript'><!--\n";
    $filter_list_text .= "function manage_filters() {
var dp = window.open('../lib/dbman_filter_pop.php?module=$module','dp','left=100,top=100,width=430,height=180,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1');
dp.focus();
}";
    $filter_list_text .= "\n//-->\n</script>";
    $filter_list_text .= "| <a href='#' onclick='manage_filters()'>".__('Edit filter')."</a> ";
*/
    #$filter_list_text = '<div class="relObjFilter">myfilter</div>';
    #$filter_list_text ='myfiklter';
    return $filter_list_text;
}

/**
* Show the "Edit filters" Link
* This function creates the required JavaScript function and Link
* for every module.
*
* @param  string $filtermodule Name of the filtered module
* @return string
*/
function display_manage_filters($filtermodule, $color='') {
    global $module, $mode, $ID, $flist, $module, $path_pre;
    $ret = '
<script type="text/javascript">
//<![CDATA[
function manage_filters_'.$filtermodule.'() {
    var dp = window.open("'.$path_pre.'lib/dbman_filter_pop.php?module='.$filtermodule.'&opener='.$module.'&mode='.$mode.'&ID='.$ID.'","dp","left=100,top=100,width=600,height=200,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1");
    dp.focus();
}
//]]>
</script>
';

    if (count($flist[$module])) {
        $ret .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
    }
    $ret .= '<a title="'.__('This link opens a popup window').'" class="filter1" href="#" onclick="manage_filters_'.$filtermodule.'()">';
    if($color<>''){
        $ret.="<font color='$color'>".__('Edit filter')."</font>";
    }
    else $ret.=__('Edit filter');
    $ret.='</a>';
    return $ret;
}


function apply_filter($field, $rule, $keyword) {
    switch ($rule) {
        case 'begins':
            $w = "$field LIKE '$keyword%'";
            break;
        case 'ends':
            $w = "$field LIKE '%$keyword'";
            break;
        case 'exact':
            $w = "$field = '$keyword'";
            break;
        case '>':
            $w = "$field > '$keyword'";
            break;
        case '>=':
            $w = "$field >= '$keyword'";
            break;
        case '&lt;=':
            $w = "$field <= '$keyword'";
            break;
        case '&lt;':
            $w = "$field < '$keyword'";
            break;
        case 'not like':
            $w = "$field NOT LIKE '%$keyword%'";
            break;
        // default rule: like
        default:
            $w = "$field LIKE '%$keyword%'";
    }
    return $w;
}


function apply_full_filter($rule, $keyword) {
    global $fields;
    foreach ($fields as $field_name => $field) {
        if ($field['filter_show'] != '') $f_list[] = apply_filter($field_name, $rule, $keyword);
    }
    $w = implode(' OR ', $f_list);
    return $w;
}


// checks whether a filter element in the list should be removed
function filter_mode($filter_ID) {
    if (isset($filter_ID)) {
        if (isset($flist['contacts'][$filter_ID])) {
            unset($flist['contacts'][$filter_ID]);
        }
        $_SESSION['flist'] =& $flist;
    }
}


// Filter in navigation bar
function nav_filter($fields) {
    $filter_rules = array( 'like'     => __('contains'),
                           'exact'    => __('exact'),
                           'begins'   => __('starts with'),
                           'ends'     => __('ends with'),
                           '>'        => __('>'),
                           '>='       => __('>='),
                           '&lt;'        => __('<'),
                           '&lt;='       => __('<='),
                           'not like' => __('does not contain')
                         );
    $str .= '
    <b>'.__('Filter').':</b>
';
    $str .= "<select name='filter'><option value='all'>".__('all fields')."</option>\n";
    $filter_list = array();
    if (is_array($fields)) {
        foreach ($fields as $field_name => $field) {
            if ($field['filter_show'] > 0 or $field['filter_show']=='on') $filter_list[$field_name] = enable_vars($field['form_name']);
        }
    }
    // sort array by name
    natcasesort($filter_list);
    reset($filter_list);
    foreach($filter_list as $filter_field => $filter_formname) {
        $str .= "<option value='".$filter_field ."'";
        if ($filter_field == $filter) $str .= ' selected="selected"';
        $str .= '>'.$filter_formname."</option>\n";
    }
    $str .= "</select>";
    // ... rule ...
    $str .= '<span class="strich">&nbsp;</span>';
    $str .= "&nbsp;<select name='rule'>\n";
    foreach ($filter_rules as $showrule => $ruletext) {
        $str .= "<option value='".$showrule."'>".$ruletext."</option>\n";
    }
    $str .= "</select>\n";
    $str .= "<input type='text' size='15' name='keyword' />\n";
    return $str;
}

?>
