<?php
/* $Id: company.class.php,v 1.33 2003/12/11 14:41:24 k-fish Exp $ */
class Company{
    function opMassUpdate($data){
	global $conn;
	if(is_array($data['cids'])){
	  foreach($data['cids'] as $cid)
	    $cids[] = (int)$cid;

	  // mass update groups
	  if($data['group']!==0){
	    $sql="SELECT id,owner FROM mgw_companies WHERE id IN(".implode(',',$cids).")";
	    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	    while($row = $res->FetchRow()){
	      if((($row['owner'] == $_SESSION["MGW"]->userid) &&
		  queryRights2_bool('root_modules_contact_company_modify'))
		 || queryRights2_bool('root_modules_contact_company_modifyothers')){
		$sql = 'UPDATE mgw_companies SET groupid='.(int)$data['group'].' WHERE id='.$row['id'];
		if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	      }
	    }
	  }

	  // mass update action
	  if($data['action']!==0){
	    $sql="SELECT id,owner FROM mgw_companies WHERE id IN(".implode(',',$cids).")";
	    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	    switch($data['action']){
	    case 'delete':
	      while($row = $res->FetchRow()){
		if((($row['owner'] == $_SESSION["MGW"]->userid) &&
		    queryRights2_bool('root_modules_contact_company_delete'))
		   || queryRights2_bool('root_modules_contact_company_deleteothers')){
		  $sql = 'DELETE FROM mgw_companies WHERE id='.$row['id'];
		  if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
		}
	      }
	      break;
	    case 'private':
	      while($row = $res->FetchRow()){
		if((($row['owner'] == $_SESSION["MGW"]->userid) &&
		    queryRights2_bool('root_modules_contact_company_modify'))
		   || queryRights2_bool('root_modules_contact_company_modifyothers')){
		  $sql = 'UPDATE mgw_companies SET ispublic=0 WHERE id='.$row['id'];
		  if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
		}
	      }
	      break;
	    case 'public':
	      while($row = $res->FetchRow()){
		if((($row['owner'] == $_SESSION["MGW"]->userid) &&
		    queryRights2_bool('root_modules_contact_company_modify'))
		   || queryRights2_bool('root_modules_contact_company_modifyothers')){
		  $sql = 'UPDATE mgw_companies SET ispublic=1 WHERE id='.$row['id'];
		  if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
		}
	      }
	    }
	  }
	  return true;
	}
	return false;
    }

    function opCreate($data){
	global $conn;
	queryRights2('root_modules_contact_company_create');

	$id = mgw_genID('mgw__seq_companies');
	$name1 = $conn->QMagic(isset($data["name1"])?$data["name1"]:"");
	$name2 = $conn->QMagic(isset($data["name2"])?$data["name2"]:"");
	$street = $conn->QMagic(isset($data["street"])?$data["street"]:"");
	$add = $conn->QMagic(isset($data["add"])?$data["add"]:"");
	$zip = $conn->QMagic(isset($data["zip"])?$data["zip"]:"");
	$city = $conn->QMagic(isset($data["city"])?$data["city"]:"");
	$state = $conn->QMagic(isset($data["state"])?$data["state"]:"");
	$country = $conn->QMagic(isset($data["country"])?$data["country"]:"");
	$phone = $conn->QMagic(isset($data["phone"])?$data["phone"]:"");
	$fax = $conn->QMagic(isset($data["fax"])?$data["fax"]:"");
	$url = $conn->QMagic(isset($data["url"])?$data["url"]:"");
	$email = $conn->QMagic(isset($data["email"])?$data["email"]:"");
	$note = $conn->QMagic(isset($data["note"])?$data["note"]:"");
	$groupid = isset($data["_group"])?(int) $data["_group"]:0;
	$public = isset($data["public"])?(int) $data["public"]:0;

	$sql="INSERT INTO mgw_companies (id, name1, name2, street, additional, zip, city, state, countrycode, telephone, fax, url, email, note, groupid, ispublic, owner,  lu_user, lu_date) VALUES ($id, $name1, $name2, $street, $add, $zip, $city, $state, $country, $phone, $fax, $url, $email, $note, $groupid, '$public', ".$_SESSION["MGW"]->userid.", ".$_SESSION["MGW"]->userid.", ". $conn->DBTimeStamp(time()). ")";

	if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	return $id;
    }

    function opUpdate($data){
	global $conn;

	$id = isset($data["id"])?(int) $data["id"]:0;

	$sql="SELECT owner FROM mgw_companies WHERE id=$id";
	if(($row = $conn->GetRow($sql))===false) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	if($row['owner'] == $_SESSION["MGW"]->userid)
	    queryRights2('root_modules_contact_company_modify');
	else
	    queryRights2('root_modules_contact_company_modifyothers');

	$name1 = $conn->QMagic(isset($data["name1"])?$data["name1"]:"");
	$name2 = $conn->QMagic(isset($data["name2"])?$data["name2"]:"");
	$street = $conn->QMagic(isset($data["street"])?$data["street"]:"");
	$add = $conn->QMagic(isset($data["add"])?$data["add"]:"");
	$zip = $conn->QMagic(isset($data["zip"])?$data["zip"]:"");
	$city = $conn->QMagic(isset($data["city"])?$data["city"]:"");
	$state = $conn->QMagic(isset($data["state"])?$data["state"]:"");
	$country = $conn->QMagic(isset($data["country"])?$data["country"]:"");
	$phone = $conn->QMagic(isset($data["phone"])?$data["phone"]:"");
	$fax = $conn->QMagic(isset($data["fax"])?$data["fax"]:"");
	$url = $conn->QMagic(isset($data["url"])?$data["url"]:"");
	$email = $conn->QMagic(isset($data["email"])?$data["email"]:"");
	$note = $conn->QMagic(isset($data["note"])?$data["note"]:"");
	$groupid = isset($data["_group"])?(int) $data["_group"]:0;
	$public = isset($data["public"])?(int) $data["public"]:0;

	$sql="UPDATE mgw_companies SET name1=$name1, name2=$name2, street=$street, additional=$add, zip=$zip, city=$city, state=$state, countrycode=$country, telephone=$phone, fax=$fax, url=$url, email=$email, note=$note,groupid = $groupid, ispublic='$public', lu_user=".$_SESSION["MGW"]->userid.", lu_date=". $conn->DBTimeStamp(time()). " WHERE (ispublic=1 or owner=".$_SESSION["MGW"]->userid.") and id=".$id;

	if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	return true;
    }

    function opDelete($id){
	global $conn;

	$sql="SELECT owner FROM mgw_companies WHERE id=$id";
	if(($row = $conn->GetRow($sql))===false) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	if($row['owner'] == $_SESSION["MGW"]->userid)
	    queryRights2('root_modules_contact_company_delete');
	else
	    queryRights2('root_modules_contact_company_deleteothers');

	$sql = "DELETE FROM mgw_companies WHERE (ispublic=1 or owner=".$_SESSION["MGW"]->userid.") and id=".(int)$id;
	if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	return true;
    }

    function viewDelete($id){
	global $smarty, $conn, $appconf;

	$sql="SELECT owner FROM mgw_companies WHERE id=$id";
	if(($row = $conn->GetRow($sql))===false) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	if($row['owner'] == $_SESSION["MGW"]->userid)
	    queryRights2('root_modules_contact_company_delete');
	else
	    queryRights2('root_modules_contact_company_deleteothers');

	$sql = "SELECT * FROM mgw_companies WHERE (ispublic=1 or owner=".$_SESSION["MGW"]->userid.") and id=".(int)$id;
	if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	$row = $res->FetchRow();

	$smarty->assign("menuid", "1");
	$smarty->assign("itemid", $id);
	$smarty->assign("parms", str_replace("delete","list",$_SERVER["QUERY_STRING"]));
	$smarty->assign("reallydeleteitem", Lang::getLanguageString("reallydelcompany"));
	$smarty->assign("deleteheader", Lang::getLanguageString("deletecompanyh"));
	$smarty->assign("deletedetail1", $row["name1"]);
	$smarty->assign("deletedetail2", $row["name2"]);
	$smarty->assign("deletedetail3", $row["city"]);
	$smarty->assign("suclass", "submit");
	$smarty->display($appconf["gentemplates"] ."/delete_item.tpl");

	return true;
    }

    function viewNewForm(){
	global $smarty;
	include(INCLUDEPATH . "mSelectBox.class.php");
	queryRights2('root_modules_contact_company_create');

	$smarty->assign("countrysb", createCountrySB("country"));

	$sb5 = new mSelectBox("_group");
	$sb5->setContentType("sql");
	$sb5->setSQLvalue("id");
	$sb5->setSQLcontent("name_key");
	$sb5->addContent("SELECT id, name_key FROM mgw_contacts_groups ORDER BY name_key");
	$sb5->addOption("0", Lang::getLanguageString("chosegrouptext"), "pre");
	$smarty->assign("groupsb", $sb5->draw());

	$smarty->assign("pubcheckyes", "checked");
	$smarty->assign("pubcheckno", "");
	$smarty->assign("suname", "create");
	$smarty->assign("suvalue", Lang::getLanguageString("create"));
	$smarty->assign("suclass", "submit");
	$smarty->assign("mode", "new");
	$smarty->assign("contentheader", Lang::getLanguageString("createnewcompany"));

	$smarty->display('contact_comp_edit.tpl');

	return true;
    }

    function viewEditForm($id){
	global $conn, $smarty;
	include(INCLUDEPATH . "mSelectBox.class.php");
	$sql="SELECT owner FROM mgw_companies WHERE id=".(int)$id;
	if(($row = $conn->GetRow($sql))===false) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	if($row['owner'] == $_SESSION["MGW"]->userid)
	    queryRights2('root_modules_contact_company_modify');
	else
	    queryRights2('root_modules_contact_company_modifyothers');

	$sql = "SELECT * FROM mgw_companies WHERE (ispublic=1 or owner=".$_SESSION["MGW"]->userid.") and id=".(int)$id;
	if(($row = $conn->GetRow($sql))===false) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	$smarty->assign("countrysb", createCountrySB("country", $row["countrycode"]));

	$sb5 = new mSelectBox("_group");
	$sb5->setContentType("sql");
	$sb5->setSQLvalue("id");
	$sb5->setSQLcontent("name_key");
	$sb5->addContent("SELECT id, name_key FROM mgw_contacts_groups ORDER BY name_key");
	$sb5->addOption("0", Lang::getLanguageString("chosegrouptext"), "pre");
	$smarty->assign("groupsb", $sb5->draw($row["groupid"]));

	if($row["ispublic"] == 1){
	    $smarty->assign("pubcheckyes", "checked");
	    $smarty->assign("pubcheckno", "");
	}
	else{
	    $smarty->assign("pubcheckyes", "");
	    $smarty->assign("pubcheckno", "checked");
	}
    
	$smarty->assign("td", $row);
	$smarty->assign("myurl", $row["url"]);
	$smarty->assign("id",$id);
	$smarty->assign("npage",isset($_GET["npage"])?$_GET["npage"]:"");
	$smarty->assign("suname","edit");
	$smarty->assign("suvalue",Lang::getLanguageString("save"));
	$smarty->assign("suclass","submit");
	$smarty->assign("contentheader", Lang::getLanguageString("editcompany").": ".$row["name1"]);

	$smarty->display('contact_comp_edit.tpl');

	return true;
    }

    function viewDetails($id){
	global $conn, $smarty;
	include(INCLUDEPATH . "mSelectBox.class.php");

	$sql = "SELECT a.*, b.name AS country FROM mgw_companies a LEFT JOIN mgw_countries b ON a.countrycode = b.code WHERE (a.ispublic=1 or a.owner=".$_SESSION["MGW"]->userid.") and a.id=".(int)$id;
	if(($row = $conn->GetRow($sql))===false) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	$row["email"] = linkEmail($row["email"]);

	//display company id?
	$smarty->assign('show_company_id',$_SESSION["MGW"]->settings["show_company_id"]);
	$smarty->assign("searchterm",isset($_GET["searchterm"])?$_GET["searchterm"]:"");
	$smarty->assign("searchtype",isset($_GET["searchtype"])?$_GET["searchtype"]:"");
	$smarty->assign("td", $row);

	// modify only for user with appropriate rights
	if((queryRights2_bool("root_modules_contact_company_modify") && $row["owner"] == $_SESSION["MGW"]->userid)
	OR (queryRights2_bool("root_modules_contact_company_modifyothers") && $row["owner"] <> $_SESSION["MGW"]->userid))
		$smarty->assign("maymod","yes");
	else
		$smarty->assign("maymod","no");

	// delete only for user with appropriate rights
	if((queryRights2_bool("root_modules_contact_company_delete") && $row["owner"] == $_SESSION["MGW"]->userid)
	OR (queryRights2_bool("root_modules_contact_company_deleteothers") && $row["owner"] <> $_SESSION["MGW"]->userid))
                $smarty->assign("maydel","yes");
        else
                $smarty->assign("maydel","no");
		
	$smarty->assign("npage",isset($_GET["npage"])?$_GET["npage"]:"");
	$smarty->assign("suclass","submit");
	$smarty->display('contact_comp_details.tpl');

	return true;
    }

    function viewList(){
	global $conn, $smarty, $appconf;
	include(INCLUDEPATH . "mSelectBox.class.php");
	
	if(isset($_GET["sort"])){
	    if($_GET["sort"] == $_SESSION["contact"]["company"]["prevorderby"]){
		$_SESSION["contact"]["company"]["sort_order"] = ($_SESSION["contact"]["company"]["sort_order"] == "DESC") ? "ASC" : "DESC";
	    }
	    else{
		$_SESSION["contact"]["company"]["sort_order"] = 'ASC';
	    }
	    $_SESSION["contact"]["company"]["prevorderby"] = $_GET["sort"];
	    $_SESSION["contact"]["company"]["sort_by"] = $_GET["sort"];
	}
	elseif(!isset($_SESSION["contact"]["company"]["sort_by"])){
	    $_SESSION["contact"]["company"]["sort_by"] = 'name1';
	    $_SESSION["contact"]["company"]["sort_order"] = 'ASC';
	}

	// if user wants icons, assign icons if not -> not
	$icons = getIconStrings();
	$smarty->assign("prevsym", $icons["prev"]);
	$smarty->assign("nextsym", $icons["next"]);
	$icons["contacts"] = $_SESSION["MGW"]->settings["iconmode"] ? "<img src=\"".$appconf["imgpath"]."/contacts_".$_SESSION["MGW"]->settings["iconid"].".gif\" border=\"0\" alt=\"".Lang::getLanguageString("contacts")."\" title=\"".Lang::getLanguageString("contacts")."\" />" : Lang::getLanguageString("contacts");

	$searchtype = '';
	$searchterm = '';
	$list = '';
	if(isset($_GET["list"]) and $_GET["list"] != "") { // ALPHABET SEARCH ACTIVE
	    $searchterm = $conn->QMagic($_GET["list"]."%");
	    $sql = "SELECT * FROM mgw_companies WHERE name1 LIKE ".$searchterm." AND (owner=".$_SESSION['MGW']->userid." OR ispublic=1) ORDER BY ".$_SESSION["contact"]["company"]["sort_by"].' '.$_SESSION["contact"]["company"]["sort_order"];
	    $smarty->assign("list",$_GET["list"]);
	}
	elseif((isset($_POST["qsearch"]) and $_POST["qsearch"] != "") || (isset($_GET["searchtype"]) and $_GET["searchtype"] == "quick")){ // QUICK SEARCH ACTIVE
	    $searchterm = ($_SERVER["REQUEST_METHOD"] == "POST") ? (isset($_POST["searchterm"])?$_POST["searchterm"]:"") : (isset($_GET["searchterm"])?$_GET["searchterm"]:"");
	    
	    $searchterm2 = $conn->QMagic("%".$searchterm."%");
	    $sql = "SELECT * FROM mgw_companies WHERE name1 LIKE ".$searchterm2." OR name2 LIKE ".$searchterm2." OR city LIKE ".$searchterm2." OR email LIKE ".$searchterm2." AND (owner=".$_SESSION['MGW']->userid." OR ispublic=1) ORDER BY ".$_SESSION["contact"]["company"]["sort_by"].' '.$_SESSION["contact"]["company"]["sort_order"];
	    $smarty->assign("searchterm",$searchterm);
	    $smarty->assign("searchtype","quick");
	    $searchtype = "quick";
	}
	elseif((isset($_POST["groupsearch"]) and $_POST["groupsearch"] != "") || (isset($_GET["searchtype"]) and $_GET["searchtype"] == "group")){ // GROUP SEARCH ACTIVE
	    $searchterm = ($_SERVER["REQUEST_METHOD"] == "POST") ? (isset($_POST["_group"])?(int)$_POST["_group"]:"") : (isset($_GET["searchterm"])?(int)$_GET["searchterm"]:"");
	    if($searchterm != "*") $sql = "SELECT * FROM mgw_companies WHERE groupid=".$searchterm." AND (owner=".$_SESSION['MGW']->userid." OR ispublic=1) ORDER BY ".$_SESSION["contact"]["company"]["sort_by"].' '.$_SESSION["contact"]["company"]["sort_order"];
	    else $sql = "SELECT * FROM mgw_companies WHERE owner=".$_SESSION['MGW']->userid." OR ispublic=1 ORDER BY ".$_SESSION["contact"]["company"]["sort_by"].' '.$_SESSION["contact"]["company"]["sort_order"];
	    $smarty->assign("searchterm",$searchterm);
	    $smarty->assign("searchtype","group");
	    $searchtype = "group";
	}
	else { // NORMAL LIST VIEW
	    $sql = "SELECT * FROM mgw_companies WHERE owner=".$_SESSION['MGW']->userid." OR ispublic=1 ORDER BY ".$_SESSION["contact"]["company"]["sort_by"].' '.$_SESSION["contact"]["company"]["sort_order"];
	}

	if (isset($_GET['npage']) || (isset($_POST['npage']) and $_POST['npage'])){
	    $curr_page = isset($_POST['npage']) ? $_POST['npage'] : $_GET['npage'];
	} else {
	    $curr_page = 1;
	}  		
	$smarty->assign("curr_page", $curr_page);

	if(!$res = $conn->PageExecute($sql, $_SESSION["MGW"]->settings["contacts_per_page"], $curr_page)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	if(!$res->AtFirstPage()) {
	    $smarty->assign("_prev", true); 
	    $smarty->assign("ppage", $res->AbsolutePage() - 1);
	}
	if(!$res->AtLastPage()) {
	    $smarty->assign("_next", true); 
	    $smarty->assign("npage", $res->AbsolutePage() + 1);
	}		

	while($row = $res->FetchRow()) {
	    // build action URLs
	    $detlink = "<a href=\"index.php?mod=contact&amp;obj=company&amp;view=details&amp;id=". $row["id"] ."&amp;searchtype=$searchtype&amp;searchterm=$searchterm&amp;npage=$curr_page&amp;".SID."\" class=\"edit\">".$icons["details"]."</a>";
	    $contactslink = "<a href=\"index.php?mod=contact&amp;obj=person&amp;view=list&amp;compid=". $row["id"] ."&amp;".SID."\" class=\"edit\">".$icons["contacts"]."</a>";
	
	    // modify only for user with appropriate rights
	    if((queryRights2_bool("root_modules_contact_company_modify") && $row["owner"] == $_SESSION["MGW"]->userid)
	       OR (queryRights2_bool("root_modules_contact_company_modifyothers") && $row["owner"] <> $_SESSION["MGW"]->userid)) {
		$editlink = "<a href=\"index.php?mod=contact&amp;obj=company&amp;view=editform&amp;id=". $row["id"] ."&amp;npage=$curr_page&amp;list=$list&amp;searchtype=$searchtype&amp;searchterm=$searchterm&amp;npage=$curr_page&amp;".SID."\" class=\"edit\">".$icons["edit"]."</a>";
	    }
	    else {
		$editlink = "";
	    }
	
	    // delete only for user with appropriate rights
	    if((queryRights2_bool("root_modules_contact_company_delete") && $row["owner"] == $_SESSION["MGW"]->userid)
	       OR (queryRights2_bool("root_modules_contact_company_deleteothers") && $row["owner"] <> $_SESSION["MGW"]->userid)) {
		$dellink = "<a href=\"index.php?mod=contact&amp;obj=company&amp;view=delete&amp;id=". $row["id"]. "&amp;searchtype=$searchtype&amp;searchterm=$searchterm&amp;npage=$curr_page&amp;".SID."\" class=\"delete\">".$icons["delete"]."</a>";
	    }
	    else {
		$dellink = "";
	    }

	    if($row['url'] != '' && !stristr($row["url"], 'http'))
		$row['url'] = 'http://'.$row['url'];
	    //$row["url"] = ($row["url"] != "") ? "<a href=\"".$row["url"]."\" target=\"_blank\">".$row["url"]."</a>" : "";
	    $row['action'] = $detlink ."<br />". $editlink ."<br />". $dellink ."<br />". $contactslink ."<br />"
		."<hr />". linkEmail2($row["email"]);

	    if($row["ispublic"]==1) $row['pimg'] = "&nbsp;";
	    else $row['pimg'] = $icons['private'];

	    $smarty->append("td",$row);
	}

	$columns[]['url'] = "index.php?mod=contact&amp;obj=company&amp;view=list&amp;sort=ispublic";
	$columns[]['url'] = "index.php?mod=contact&amp;obj=company&amp;view=list&amp;sort=name1";
	$columns[]['url'] = "index.php?mod=contact&amp;obj=company&amp;view=list&amp;sort=email";
	$columns[]['url'] = "index.php?mod=contact&amp;obj=company&amp;view=list&amp;sort=street";
	$columns[]['url'] = "index.php?mod=contact&amp;obj=company&amp;view=list&amp;sort=zip";
	$columns[]['url'] = "index.php?mod=contact&amp;obj=company&amp;view=list&amp;sort=city";
	$columns[]['url'] = "index.php?mod=contact&amp;obj=company&amp;view=list&amp;sort=url";
	$columns[]['url'] = "index.php?mod=contact&amp;obj=company&amp;view=list&amp;sort=id";
	$smarty->assign("columns", $columns);

	$smarty->assign('groups', $conn->GetAssoc("SELECT id, name_key FROM mgw_contacts_groups ORDER by name_key"));
	$smarty->assign("actgroup", (isset($_POST["_group"])?$_POST["_group"]:""));
	$smarty->assign("hascreaterights", queryRights2_bool("root_modules_contact_company_create"));
	$smarty->assign('at', alphabet_table("mod=contact&amp;obj=company&amp;view=list"));
	
	if($_SESSION["MGW"]->settings["quicksearchmethod"]=="") $qsbool = false; else $qsbool = true;
	$smarty->assign("qsearchon", $qsbool);

	$smarty->display('contact_comp_list.tpl');
	return true;
    }
}
?>
