<?php
/* $Id: download.php 256 2007-05-22 03:26:08Z hodaka $
 *  ------------------------------------------------------------------------ *
 *                XOOPS - PHP Content Management System                      *
 *                    Copyright (c) 2000 XOOPS.org                           *
 *                       <http://www.xoops.org/>                             *
 *  ------------------------------------------------------------------------ *
 *                      MyAddress - XOOPS addressbook                        *
 *                        <http://www.kuri3.net/>                            *
 *              Copyright (c) 2004 by hodaka <hodaka@kuri3.net>              *
 * ------------------------------------------------------------------------- *
 * This program is free software; you can redistribute it and/or modify      *
 * it under the terms of the GNU General Public License as published by      *
 * the Free Software Foundation; either version 2 of the License, or         *
 * (at your option) any later version.                                       *
 *                                                                           *
 * You may not change or alter any portion of this comment or credits        *
 * of supporting developers from this source code or any supporting          *
 * source code which is considered copyrighted (c) material of the           *
 * original comment or credit authors.                                       *
 *                                                                           *
 * This program is distributed in the hope that it will be useful,           *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of            *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             *
 * GNU General Public License for more details.                              *
 *                                                                           *
 * You should have received a copy of the GNU General Public License         *
 * along with this program; if not, write to the Free Software               *
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA  *
 */

include("header.php");

// reject no perm modified on v1.23
if( empty($xoopsModuleConfig['myaddress_guestperm']) && !is_object($xoopsUser) ) {
	redirect_header( XOOPS_URL."/user.php" , 2 , _MD_MYADDRESS_YOUMUSTREG );
	exit();
} elseif( !haveGroupPerm() ) {
	redirect_header( XOOPS_URL."/index.php", 2, _MD_MYADDRESS_YOUHAVENOPERM );
	exit();
}

$op = isset( $_POST['search'])? "search" : ( isset($_POST['download'])? "download" : "form" );

if ( $op == "form" ) {
//--------------------------------------------------------------------//
//                       show form                                    //
//--------------------------------------------------------------------//
	$xoopsOption['template_main'] = 'myaddress_searchform.html';
	include XOOPS_ROOT_PATH."/header.php";
	include_once XOOPS_ROOT_PATH."/class/xoopsformloader.php";

// category
	$category_select = new XoopsFormSelect(_MD_MYADDRESS_CATEGORY, "cid");
	$category_select->addOption( 0, "-----" );
	$tree = $cattree->getChildTreeArray(0,$myaddress_catorder);
	$tree = push_gperm_array( $tree, "myadrs_category" );
	foreach( $tree as $leaf ) {
		$leaf['prefix'] = substr($leaf['prefix'], 0, -1);
		$leaf['prefix'] = str_replace(".","--",$leaf['prefix']);
		$category_select->addOption( $leaf['cid'],$leaf['prefix'].$leaf['title'] );
	}

// uname
	$useronly_radio = new XoopsFormRadioYN( _MD_MYADDRESS_USERONLY, "useronly", 1, _YES, _NO );

	$iamadmin = false;
	if ( $xoopsUser && $xoopsUser->isAdmin() ) {
		$iamadmin = true;
	}
	if ( $iamadmin ) {
		$uname_text = new XoopsFormText("", "user_uname", 30, 60);
		$uname_match = new XoopsFormSelectMatchOption("", "user_uname_match");
		$uname_tray = new XoopsFormElementTray(_AM_MYADDRESS_SUBMITTER, "&nbsp;");
		$uname_tray->addElement($uname_match);
		$uname_tray->addElement($uname_text);
	}

// relations
	$relations_select = new XoopsFormSelect(_MD_MYADDRESS_RELATIONS, "relations");
	$relations_select->addOption( 0, "-----" );
	$relarray = getSelBoxRelations();
	foreach( $relarray as $rel ) {
		$relations_select->addOption( $rel['value'], $rel['label'] );
	}

// cname_jh
	$cname_jh_text = new XoopsFormText("", "cname_jh", 30, 60);
	$cname_jh_match = new XoopsFormSelectMatchOption("", "cname_jh_match");
	$cname_jh_tray = new XoopsFormElementTray(_MD_MYADDRESS_COMPANY_JH, "&nbsp;");
	$cname_jh_tray->addElement($cname_jh_match);
	$cname_jh_tray->addElement($cname_jh_text);


// fullname
	$fullname_text = new XoopsFormText("", "fullname", 30, 60);
	$fullname_match = new XoopsFormSelectMatchOption("", "fullname_match");
	$fullname_tray = new XoopsFormElementTray(_MD_MYADDRESS_FULLNAME, "&nbsp;");
	$fullname_tray->addElement($fullname_match);
	$fullname_tray->addElement($fullname_text);

// fullname_jh
	$fullname_jh_text = new XoopsFormText("", "fullname_jh", 30, 60);
	$fullname_jh_match = new XoopsFormSelectMatchOption("", "fullname_jh_match");
	$fullname_jh_tray = new XoopsFormElementTray(_MD_MYADDRESS_FULLNAME_JH, "&nbsp;");
	$fullname_jh_tray->addElement($fullname_jh_match);
	$fullname_jh_tray->addElement($fullname_jh_text);

// comments
	$comments_text = new XoopsFormText("", "comments", 30, 100);
	$comments_match = new XoopsFormSelectMatchOption("", "comments_match");
	$comments_tray = new XoopsFormElementTray(_MD_MYADDRESS_COMMENTS, "&nbsp;");
	$comments_tray->addElement($comments_match);
	$comments_tray->addElement($comments_text);

// time updated
	$updated_text = new XoopsFormText("", "updated", 30, 60);
	$updated_date = new XoopsFormSelect("", "updated_date");
	$updated_date->addOptionArray(array(
		"4"=>_MD_MYADDRESS_YEAR,
		"6"=>_MD_MYADDRESS_YEARMONTH,
		"8"=>_MD_MYADDRESS_YEARMONTHDAY));
	$updated_match = new XoopsFormSelect("", "updated_match");
	$updated_match->addOptionArray(array(" > "=>_MD_MYADDRESS_LARGER, " >= "=>_MD_MYADDRESS_NOTLESS, " = "=>_MD_MYADDRESS_EQUAL, " <= "=>_MD_MYADDRESS_NOTMORE, " < "=>_MD_MYADDRESS_LESS));
//	$updated_match = new XoopsFormSelectMatchOption("", "updated_match");
	$updated_tray = new XoopsFormElementTray(_MD_MYADDRESS_UPDATED, "&nbsp;");
	$updated_tray->addElement($updated_date);
	$updated_tray->addElement($updated_match);
	$updated_tray->addElement($updated_text);

// time updated2 added on Nov.7,2004
	$updated_text2 = new XoopsFormText("", "updated2", 30, 60);
	$updated_date2 = new XoopsFormSelect("", "updated_date2");
	$updated_date2->addOptionArray(array(
		"4"=>_MD_MYADDRESS_YEAR,
		"6"=>_MD_MYADDRESS_YEARMONTH,
		"8"=>_MD_MYADDRESS_YEARMONTHDAY));
	$updated_match2 = new XoopsFormSelect("", "updated_match2");
	$updated_match2->addOptionArray(array(" > "=>_MD_MYADDRESS_LARGER, " >= "=>_MD_MYADDRESS_NOTLESS, " = "=>_MD_MYADDRESS_EQUAL, " <= "=>_MD_MYADDRESS_NOTMORE, " < "=>_MD_MYADDRESS_LESS));
//	$updated_match = new XoopsFormSelectMatchOption("", "updated_match");
	$updated_tray2 = new XoopsFormElementTray(_MD_MYADDRESS_UPDATED._MD_MYADDRESS_AND, "&nbsp;");
	$updated_tray2->addElement($updated_date2);
	$updated_tray2->addElement($updated_match2);
	$updated_tray2->addElement($updated_text2);

// sort key
	$sort_select = new XoopsFormSelect(_MD_MYADDRESS_SORT, "sort_key", "fullname_jh");
	$sort_select->addOptionArray(array("cid"=>_MD_MYADDRESS_CATEGORY,"relations"=>_MD_MYADDRESS_RELATIONS,"fullname_jh"=>_MD_MYADDRESS_FULLNAME_JH,"updated"=>_MD_MYADDRESS_UPDATED));

// sort order
	$order_select = new XoopsFormSelect(_MD_MYADDRESS_ORDER, "sort_order", "ASC");
	$order_select->addOptionArray(array("ASC"=>_MD_MYADDRESS_ASC,"DESC"=>_MD_MYADDRESS_DESC));

	$limit_select = new XoopsFormSelect(_MD_MYADDRESS_NUMPERPAGE, "limit", 25);
	$limit_select->addOptionArray(array('5' => 5, '10' => 10, '15' => 15, '20' => 20, '25' => 25, '30' => 30, '50' => 50));

	$submit_search = new XoopsFormButton("", "search", _MD_MYADDRESS_BUTTONFORSEARCH, "submit");
	$submit_download = new XoopsFormButton("", "download", _MD_MYADDRESS_BUTTONFORDOWNLOAD, "submit");
	$submit_tray = new XoopsFormElementTray("", "&nbsp;");
	$submit_tray->addElement($submit_search);
	$submit_tray->addElement($submit_download);


	$form = new XoopsThemeForm("", "searchform", "download.php");
	$form->addElement( $useronly_radio );
	if ( $iamadmin ) {
		$form->addElement($uname_tray);
	}
	$form->addElement($category_select);
	$form->addElement($relations_select);
	$form->addElement($cname_jh_tray);
	$form->addElement($fullname_tray);
	$form->addElement($fullname_jh_tray);
	$form->addElement($comments_tray);
	$form->addElement($updated_tray);
// added on Nov.7,2004
	$form->addElement($updated_tray2);
	$form->addElement($sort_select);
	$form->addElement($order_select);
	$form->addElement($limit_select);
	$form->addElement($submit_tray);

	$form->assign($xoopsTpl);

	$xoopsTpl->assign('lang_advanced_search', _MD_MYADDRESS_ADVANCED_SEARCH);
//	$xoopsTpl->assign('lang_records', sprintf(_MD_MYADDRESS_TOTALRECORDS, '<span style="color:#ff0000;">'.$total.'</span>'));
include_once XOOPS_ROOT_PATH."/footer.php";
} elseif ( $op == "search" ) {
//--------------------------------------------------------------------//
//                  search and show results                           //
//--------------------------------------------------------------------//
	$xoopsOption['template_main'] = 'myaddress_results.html';
	include XOOPS_ROOT_PATH."/header.php";
	include_once XOOPS_ROOT_PATH."/class/xoopsformloader.php";
	$myts =& MyTextSanitizer::getInstance();
	$_POST['search'] = "search";
// 2007.5.22 v1.24.1
$sql ="SELECT l.aid, l.cid, l.fullname, l.myphone, l.mycellphone1, l.myemail1, l.updated, c.title, l.c_id, co.cname FROM ($table_addressbook l LEFT JOIN $table_cat c ON l.cid=c.cid) LEFT JOIN $table_company co ON l.c_id=co.c_id";
//	$sql ="SELECT l.aid, l.cid, l.fullname, l.myphone, l.mycellphone1, l.myemail1, l.updated, c.title FROM $table_addressbook l LEFT JOIN $table_cat c ON l.cid=c.cid";	// 2004/12/21 v1.142 for addition of a category title 
//	$sql ="SELECT aid, cid, fullname, myphone, mycellphone1, myemail1, updated FROM $table_addressbook";

	$where = makeWhereClause();
	$order = makeOrderClause();

	// get total counts of affected addressbook
//	$res_total = $xoopsDB->query( "SELECT count(aid) FROM $table_addressbook ".$where );
// 2004/12/21 v1.142 for addition of a category title 
	$res_total = $xoopsDB->query( "SELECT count(l.aid) FROM $table_addressbook l ".$where );
	list( $total ) = $xoopsDB->fetchRow( $res_total );
	$total = intval($total);

	$limit = (!empty($_POST['limit'])) ? intval($_POST['limit']) : 20;
	$start = (!empty($_POST['start'])) ? intval($_POST['start']) : 0;

	$xoopsTpl->assign('lang_search', _MD_MYADDRESS_SEARCH);
	$xoopsTpl->assign('lang_results', _MD_MYADDRESS_RESULTS);

	if ( $total == 0 ) {
		$xoopsTpl->assign('lang_nonefound', _MD_MYADDRESS_NOFOUND);
	} elseif ( $start < $total ) {
		$xoopsTpl->assign('total_found', $total);
		$xoopsTpl->assign('mode', 9);

		// assign header
		$xoopsTpl->assign('lang_fullname', _MD_MYADDRESS_FULLNAME);
		$xoopsTpl->assign('lang_myphone', _MD_MYADDRESS_PHONE);
		$xoopsTpl->assign('lang_mycellphone1', _MD_MYADDRESS_CELLPHONE);
		$xoopsTpl->assign('lang_myemail1', _MD_MYADDRESS_EMAIL1);
		$xoopsTpl->assign('lang_updated', _MD_MYADDRESS_UPDATED);
		$xoopsTpl->assign('lang_title', _MD_MYADDRESS_CATEGORY);	// 2004/12/21 v1.142 for addition of a category title 
        $xoopsTpl->assign('lang_company', _MD_MYADDRESS_CO_NAME); // 2007.5.22 v1.24.1  

		$result = $xoopsDB->query( $sql.$where.$order, $limit, $start );

		$myaddressdata = array();
		// assign addressbook data to template
// 2004/12/21 v1.142 for addition of a category title 
//		while( list($aid, $cid, $fullname, $myphone, $mycellphone1, $myemail1, $updated, $title ) = $xoopsDB->fetchRow( $result ) ) {
// 2007.5.22 v1.24.1
        while( list($aid, $cid, $fullname, $myphone, $mycellphone1, $myemail1, $updated, $title, $c_id, $company ) = $xoopsDB->fetchRow( $result ) ) {
			$myaddressdata['fullname'] = "<A HREF='viewaddress.php?mode=1&cid=$cid&op=edit&aid=". $aid ."'>". $myts->MakeTboxData4Show($fullname) . "</A>";
			$myaddressdata['myphone'] = $myts->MakeTboxData4Show($myphone);
			$myaddressdata['mycellphone1'] = $myts->MakeTboxData4Show($mycellphone1);
			if ( $myemail1 != "" ) {
						$myaddressdata['myemail1'] = "<A HREF='mailto:". $myts->MakeTboxData4Show($myemail1) ."'><IMG SRC='".XOOPS_URL."/images/icons/email.gif' BORDER='0' ALT='".sprintf( _SENDEMAILTO, $myts->MakeTboxData4Show($myemail1) )."' /></A>";
//				$myaddressdata['myemail1'] = "<A HREF='mailto:". $myts->MakeTboxData4Show($myemail1) ."'>".$myts->MakeTboxData4Show($myemail1)."</A>";
			} else {
				$myaddressdata['myemail1'] = "";
			}
//			if ( $myemail2 != "" ) {
//						$myaddressdata['myemail2'] = "<A HREF='mailto:". $myemail2 ."'><IMG SRC='".XOOPS_URL."/images/icons/email.gif' BORDER='0' ALT='".sprintf( _SENDEMAILTO, $myemail2 )."' /></A>";
//				$myaddressdata['myemail2'] = "<A HREF='mailto:". $myemail2 ."'>".$myemail2."</A>";
//			} else {
//				$myaddressdata['myemail2'] = "";
//			}
//					$myaddressdata['adminlink'] = "<A HREF='". $mod_url ."/viewaddress.php?mode=$mode&cid=$cid&op=edit&aid=". $aid ."'>". _MD_MYADDRESS_EDIT. "</A> | <A HREF='". $mod_url ."/viewaddress.php?mode=$mode&cid=$cid&op=del&aid=". $aid ."'>". _MD_MYADDRESS_DELETE ."</A>";
			$myaddressdata['updated'] = $myts->MakeTboxData4Show($updated);
			$myaddressdata['title'] = $myts->MakeTboxData4Show($title);	// 2004/12/21 v1.4.2
            // 2007.5.27 v1.24.2
            $myaddressdata['company'] = '<a href="viewcompany.php?mode=1&amp;op=list&amp;c_id='.$c_id.'">'.$myts->MakeTboxData4Show($company).'</a>';
			$xoopsTpl->append('myaddresses', $myaddressdata );
		}

		$totalpages = ceil($total / $limit);
		if ( $totalpages > 1 ) {
			$hiddenform = "<FORM NAME='findnext' ACTION='download.php' METHOD='POST'>";
			foreach ( $_POST as $k => $v ) {
				$hiddenform .= "<INPUT TYPE='hidden' NAME='".$myts->oopsHtmlSpecialChars($k)."' value='".$myts->makeTboxData4PreviewInForm($v)."' />\n";
			}
			if (!isset($_POST['limit'])) {
				$hiddenform .= "<INPUT TYPE='hidden' NAME='limit' VALUE='".$limit."' />\n";
			}
			if (!isset($_POST['start'])) {
				$hiddenform .= "<INPUT TYPE='hidden' NAME='start' VALUE='".$start."' />\n";
			}
			$prev = $start - $limit;
			if ( $start - $limit >= 0 ) {
				$hiddenform .= "<A HREF='#0' ONCLICK='javascript:document.findnext.start.value=".$prev.";document.findnext.submit();'>"._MD_MYADDRESS_PREVIOUS."</A>&nbsp;\n";
        	}
			$counter = 1;
			$currentpage = ($start+$limit) / $limit;
			while ( $counter <= $totalpages ) {
				if ( $counter == $currentpage ) {
					$hiddenform .= "<b>".$counter."</b> ";
				} elseif ( ($counter > $currentpage-4 && $counter < $currentpage+4) || $counter == 1 || $counter == $totalpages ) {
					if ( $counter == $totalpages && $currentpage < $totalpages-4 ) {
						$hiddenform .= "... ";
					}
					$hiddenform .= "<A HREF='#".$counter."' ONCLICK='javascript:document.findnext.start.value=".($counter-1)*$limit.";document.findnext.submit();'>".$counter."</A> ";
					if ( $counter == 1 && $currentpage > 5 ) {
						$hiddenform .= "... ";
					}
				}
				$counter++;
			}
			$next = $start+$limit;
			if ( $total > $next ) {
				$hiddenform .= "&nbsp;<A HREF='#".$total."' ONCLICK='javascript:document.findnext.start.value=".$next.";document.findnext.submit();'>"._MD_MYADDRESS_NEXT."</a>\n";
			}
			$hiddenform .= "</FORM>";
			$xoopsTpl->assign('pagenav', $hiddenform);
			$xoopsTpl->assign('lang_numfound', sprintf(_MD_MYADDRESS_ADRSFOUND, $total));
		}
	}
include_once XOOPS_ROOT_PATH."/footer.php";
} else {
//--------------------------------------------------------------------//
//                         download csv file                          //
//--------------------------------------------------------------------//
	$myts =& MyTextSanitizer::getInstance();

	$today = date("YmdHi");

	header("Content-Type: application/octet-stream");
	header("Content-Disposition: attachment; filename=".$today."myaddress.csv");

	$rs_adrs = $xoopsDB->query("SELECT * FROM $table_addressbook LIMIT 1");
	for($i=0;$i<mysql_num_fields($rs_adrs);$i++) {
		print(mysql_field_name($rs_adrs,$i).",");
	}
	print("title,");	// 2005/01/12 added category name
	
	$rs_comp = $xoopsDB->query("SELECT * FROM $table_company LIMIT 1");
	$numf = mysql_num_fields($rs_comp);
	for($i=0;$i<mysql_num_fields($rs_comp);$i++) {
		print(mysql_field_name($rs_comp,$i).",");
	}
	print("\n");

	$sql = "SELECT l.*, c.title FROM $table_addressbook l LEFT JOIN $table_cat c ON l.cid=c.cid";
	$where = makeWhereClause();
	$order = makeOrderClause();

	$rs_adrs = $xoopsDB->query($sql.$where.$order);
	
	for($j=0;$j<mysql_num_rows($rs_adrs);$j++){
		for($k=0;$k<mysql_num_fields($rs_adrs);$k++){
			$str=mysql_result($rs_adrs,$j,$k);
			$str = mb_convert_encoding($str, "SJIS", "EUC-JP");
			print($str.",");
		}
		$c_id = intval(mysql_result($rs_adrs,$j,"c_id"));
		$rs_comp = $xoopsDB->query("SELECT * FROM $table_company WHERE c_id=$c_id");
		if (mysql_num_rows($rs_comp) == 0) {
			print($str."0,");
			for($k=1;$k<$numf;$k++){
				print($str.",");
			}
		} else {
			for($k=0;$k<mysql_num_fields($rs_comp);$k++){
				$str=mysql_result($rs_comp,0,$k);
				$str = mb_convert_encoding($str, "SJIS", "EUC-JP");
				print($str.",");
			}
		}
		print("\n");
	}
}

//--------------------------------------------------------------------//
//                       criteria things function                      //
//--------------------------------------------------------------------//
function makeWhereClause() {
	global $xoopsUser;
	global $xoopsModule;
	global $xoopsDB;
	global $cattree;
	global $myts;
	global $myaddress_catorder;
	global $table_company;
	global $table_cat;	// v1.142 for addition of a category title 
	global $myaddress_mid, $my_uid, $my_groups, $mod_url;

	$uid = $xoopsUser->uid();

	$where = " WHERE";

	$iamadmin = false;
	if ( $xoopsUser && $xoopsUser->isAdmin() ) {
		$iamadmin = true;
	}
	if ( $iamadmin ) {
		$criteria = new CriteriaCompo();
		if ( !empty($_POST['user_uname']) ) {
			$match = (!empty($_POST['user_uname_match'])) ? intval($_POST['user_uname_match']) : XOOPS_MATCH_START;
			switch ( $match ) {
			case XOOPS_MATCH_START:
				$criteria->add(new Criteria('uname', $myts->addSlashes(trim($_POST['user_uname'])).'%', 'LIKE'));
				break;
			case XOOPS_MATCH_END:
				$criteria->add(new Criteria('uname', '%'.$myts->addSlashes(trim($_POST['user_uname'])), 'LIKE'));
				break;
			case XOOPS_MATCH_EQUAL:
				$criteria->add(new Criteria('uname', $myts->addSlashes(trim($_POST['user_uname']))));
				break;
			case XOOPS_MATCH_CONTAIN:
				$criteria->add(new Criteria('uname', '%'.$myts->addSlashes(trim($_POST['user_uname'])).'%', 'LIKE'));
				break;
			}
			$member_handler =& xoops_gethandler('member');
			$foundusers =& $member_handler->getUsers($criteria, true);
			$where .= " l.uid IN (";
			$isPlural = FALSE;
			foreach (array_keys($foundusers) as $j) {
				$userid = $foundusers[$j]->getVar("uid");
				if (!$isPlural) {
					$where .= "$userid";
					$isPlural = TRUE;
				} else {
					$where .= ",$userid";
				}
			}
			$where .= ")";
		} else {
			if ( !$_POST['useronly'] ) {
				$where .= " (l.uid=$uid || l.disclosed=1)";
			} else {
				$where .= " l.uid=$uid";
			}
		}
	} else {
		if ( $_POST['useronly'] ) {
			$where .= " l.uid=$uid";
		} else {
			$where .= " (l.uid=$uid || l.disclosed= 1)";
		}
	}
	if ( !empty($_POST['relations']) ) {
		$relations = trim($_POST['relations']);
		$where .= " AND l.relations='$relations'";
	}

	if ( !empty($_POST['fullname']) && $_POST['fullname'] != "") {
		$match = (!empty($_POST['fullname_match'])) ? intval($_POST['fullname_match']) : XOOPS_MATCH_START;
		$fullname = trim($_POST['fullname']);
		$where .= " AND";

		switch ($match) {
		case XOOPS_MATCH_START:
			$where .= " l.fullname like '".$fullname."%'";
			break;
		case XOOPS_MATCH_END:
			$where .= " l.fullname like '%".$fullname."'";
			break;
		case XOOPS_MATCH_EQUAL:
			$where .= " l.fullname='".$fullname."'";
			break;
		case XOOPS_MATCH_CONTAIN:
			$where .= " l.fullname like '%".$fullname."%'";
			break;
		}
	}

	if ( !empty($_POST['fullname_jh']) && $_POST['fullname_jh'] != "") {
		$match = (!empty($_POST['fullname_jh_match'])) ? intval($_POST['fullname_jh_match']) : XOOPS_MATCH_START;
		$where .= " AND";
		$fullname_jh = trim($_POST['fullname_jh']);

		switch ($match) {
		case XOOPS_MATCH_START:
			$where .= " l.fullname_jh like '".$fullname_jh."%'";
			break;
		case XOOPS_MATCH_END:
			$where .= " l.fullname_jh like '%".$fullname_jh."'";
			break;
		case XOOPS_MATCH_EQUAL:
			$where .= " l.fullname_jh='".$fullname_jh."'";
			break;
		case XOOPS_MATCH_CONTAIN:
			$where .= " l.fullname_jh like '%".$fullname_jh."%'";
			break;
		}
	}

	if ( !empty($_POST['comments']) && $_POST['comments'] != "") {
		$match = (!empty($_POST['comments_match'])) ? intval($_POST['comments_match']) : XOOPS_MATCH_START;
		$where .= " AND";
		$comments = trim($_POST['comments']);

		switch ($match) {
		case XOOPS_MATCH_START:
			$where .= " l.mycomments like '".$comments."%'";
			break;
		case XOOPS_MATCH_END:
			$where .= " l.mycomments like '%".$comments."'";
			break;
		case XOOPS_MATCH_EQUAL:
			$where .= " l.mycomments='".$comments."'";
			break;
		case XOOPS_MATCH_CONTAIN:
			$where .= " l.mycomments like '%".$comments."%'";
			break;
		}
	}

	if ( !empty($_POST['updated']) && is_numeric($_POST['updated'])) {
		$match = (!empty($_POST['updated_match'])) ? trim($_POST['updated_match']) : _MD_MYADDRESS_LARGER;
		$updated = trim($_POST['updated']);
		$date = (!empty($_POST['updated_date'])) ? trim($_POST['updated_date']) : 4;
		$where .= " AND substring(l.updated, 1, $date)".$match.substr($updated, 0, $date);
	}
// added on Nov.7,2004
	if ( !empty($_POST['updated2']) && is_numeric($_POST['updated2'])) {
		$match2 = (!empty($_POST['updated_match2'])) ? trim($_POST['updated_match2']) : _MD_MYADDRESS_LARGER;
		$updated2 = trim($_POST['updated2']);
		$date2 = (!empty($_POST['updated_date2'])) ? trim($_POST['updated_date2']) : 4;
		$where .= " AND substring(l.updated, 1, $date2)".$match2.substr($updated2, 0, $date2);
	}

	if ( !empty($_POST['cid']) && $_POST['cid'] != 0) {
		$cid = intval($_POST['cid']);
		$children = $cattree->getAllChildId( $cid );
		$children = push_gperm_array( $children, "myadrs_category" );
//		$children = $cattree->getPermittedChildId( $cid, $myaddress_catorder, $children=array(), $perm_name, $my_groups, $myaddress_mid );

		$where .= " AND l.cid IN (";
		foreach( $children as $child ) {
			$where .= " $child,";
		}
		$where .= " $cid )";
	}

	if ( !empty($_POST['cname_jh']) && $_POST['cname_jh'] != "") {
		$match = (!empty($_POST['cname_jh_match'])) ? intval($_POST['cname_jh_match']) : XOOPS_MATCH_START;
		$cname_jh = trim($_POST['cname_jh']);

		switch ($match) {
		case XOOPS_MATCH_START:
			$whr = " cname_jh like '".$cname_jh."%'";
			break;
		case XOOPS_MATCH_END:
			$whr = " cname_jh like '%".$cname_jh."'";
			break;
		case XOOPS_MATCH_EQUAL:
			$whr = " cname_jh='".$cname_jh."'";
			break;
		case XOOPS_MATCH_CONTAIN:
			$whr = " cname_jh like '%".$cname_jh."%'";
			break;
		}

		$rs = $xoopsDB->query("SELECT c_id FROM $table_company WHERE $whr");
		if ( mysql_num_rows( $rs ) > 0 ) {
			$where .= " AND l.c_id IN (";
			$isPlural = FALSE;
			while( list($c_id) = $xoopsDB->fetchRow( $rs )) {
				if (!$isPlural) {
					$where .= "$c_id";
					$isPlural = TRUE;
				} else {
					$where .= ",$c_id";
				}
			}
			$where .= ")";
		}
	}
	return $where;
}

function makeOrderClause() {
	$validsort = array("cid", "relations", "fullname_jh", "updated");
	$sort = " ORDER BY ";
	$sort .= (!empty($_POST['sort_key']) && !in_array($_POST['sort_key'], $validsort)) ? " l.fullname_jh" : (($_POST['sort_key'] == "fullname_jh") ? trim($_POST['sort_key']) : " l.".$_POST['sort_key'].",l.fullname_jh");

	$order = " ASC";
	if ( isset($_POST['sort_order']) && $_POST['sort_order'] == "DESC") {
		$order = " DESC";
	}
	$order = $sort.$order;
	return $order;
}
?>