<?php
/*************************************************************
* Mambo Community Builder
* Author MamboJoe
* @ Released under GNU/GPL License : http://www.gnu.org/copyleft/gpl.html
*************************************************************/


// ensure this file is being included by a parent file
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

if (!$acl->acl_check( 'administration', 'manage', 'users', $my->usertype, 'components', 'com_users' )) {
	mosRedirect( 'index2.php', _NOT_AUTH );
}

if (file_exists('components/com_comprofiler/language/'.$mosConfig_lang.'.php')) {
  include('components/com_comprofiler/language/'.$mosConfig_lang.'.php');
} else {
  include('components/com_comprofiler/language/english.php');
}

require_once( $mainframe->getPath( 'admin_html' ) );
include_once( "components/com_comprofiler/ue_config.php" );
include_once("components/com_comprofiler/comprofiler.class.php");


$task = trim( mosGetParam( $_REQUEST, 'task', null ) );
$cid = mosGetParam( $_REQUEST, 'cid', array( 0 ) );
if (!is_array( $cid )) {
	$cid = array ( 0 );
}
//echo "<script>alert('Im getting started at the task is:".$task."');</script>";
switch ($task) {
	case "new":
		editUser( 0, $option);
		break;

	case "edit":
		editUser( intval( $cid[0] ), $option );
		break;

	case "save":
		saveUser( $option );
		break;

	case "remove":
		removeUsers( $cid, $option );
		break;
	
	case "block":
		changeUserBlock( $cid, 1, $option );
		break;

	case "unblock":
		changeUserBlock( $cid, 0, $option );
		break;

	case "approve":
	        approveUser( $cid, 1, $option );
	        break;
	
	case "reject":
	        approveUser( $cid, 0, $option );
	        break;

   	case "showconfig":
      		showConfig( $option );
      		break;

   	case "showinstruction":
      		showInstructions($database, $option, $mosConfig_lang);
      		break;

   	case "showsubscription":
      		showSubscription($database, $option, $mosConfig_lang);
      		break;

   	case "saveconfig":
      		saveConfig( $option );
      	break;

	case "newTab":
		editTab( 0, $option);
		break;

	case "editTab":
		editTab( intval( $cid[0] ), $option );
		break;

	case "saveTab":
		saveTab( $option );
		break;

	case "removeTab":
		removeTabs( $cid, $option );
		break;

	case "showTab":
		showTab( $option );
		break;

	case "orderupTab":
		orderTabs( $cid[0], -1, $option );
		break;

	case "orderdownTab":
		orderTabs( $cid[0], 1, $option );
		break;

	case "newField":
		editField( 0, $option);
		break;

	case "editField":
		editField( intval( $cid[0] ), $option );
		break;

	case "saveField":
		saveField( $option );
		break;

	case "removeField":
		removeField( $cid, $option );
		break;

	case "showField":
		showField( $option );
		break;


	case "orderupField":
		orderFields( $cid[0], -1, $option );
		break;

	case "orderdownField":
		orderFields( $cid[0], 1, $option );
		break;

	case "saveList":
		saveList($option );
		break;

	case "editList":
		editList( $cid[0], 1, $option );
		break;
	case "newList":
		editList( 0, $option);
		break;

	case "showLists":
		showLists( $option );
		break;
	case "removeList":
		removeList( $cid, $option );
		break;
	case "orderupList":
		orderLists( $cid[0], -1, $option );
		break;

	case "orderdownList":
		orderLists( $cid[0], 1, $option );
		break;

	case "fieldPublishedYes":
	        publishField( $cid, 1, $option );
	        break;

	case "fieldPublishedNo":
	        publishField( $cid, 0, $option );
	        break;

	case "fieldRequiredYes":
	        requiredField( $cid, 1, $option );
	        break;

	case "fieldRequiredNo":
	        requiredField( $cid, 0, $option );
	        break;

	case "fieldProfileYes":
	        profileField( $cid, 1, $option );
	        break;

	case "fieldProfileNo":
	        profileField( $cid, 0, $option );
	        break;

	case "fieldRegistrationYes":
	        registrationField( $cid, 1, $option );
	        break;

	case "fieldRegistrationNo":
	        registrationField( $cid, 0, $option );
	        break;

	case "listPublishedYes":
	        listPublishedField( $cid, 1, $option );
	        break;

	case "listPublishedNo":
	        listPublishedField( $cid, 0, $option );
	        break;
	case "listDefaultYes":
	        listDefaultField( $cid, 1, $option );
	        break;

	case "listDefaultNo":
	        listDefaultField( $cid, 0, $option );
	        break;

	case "tools":
		loadTools();
		break;

	case "loadSampleData":
	        loadSampleData();
	        break;

	case "syncUsers":
	        syncUsers();
	        break;

	case "showusers":
		showUsers( $option );
		break;

	default:
		HTML_comprofiler::showCredits();
		break;
}

function saveList( $option ) {
	global $database, $my, $_POST;
	global $mosConfig_live_site;
	include_once( "components/com_comprofiler/ue_config.php" );
	include_once ("components/com_comprofiler/comprofiler.class.php");
	//echo "<script>alert('started saveList!');</script>";
	$row = new moscomprofilerLists( $database );
	if (!$row->bind( $_POST )) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	//echo "<script> alert('".$_POST['col1']."'); </script>\n";	
	if(isset($_POST['col1'])) { $row->col1fields = implode("|*|",$_POST['col1']); } else { $row->col1fields = null; } ;
	if(isset($_POST['col2'])) { $row->col2fields = implode("|*|",$_POST['col2']); } else { $row->col2fields = null; } ;
	if(isset($_POST['col3'])) { $row->col3fields = implode("|*|",$_POST['col3']); } else { $row->col3fields = null; } ;
	if(isset($_POST['col4'])) { $row->col4fields = implode("|*|",$_POST['col4']); } else { $row->col4fields = null; } ;

	if ($row->col1enabled != 1) $row->col1enabled=0;
	if ($row->col2enabled != 1) $row->col2enabled=0;
	if ($row->col3enabled != 1) $row->col3enabled=0;
	if ($row->col4enabled != 1) $row->col4enabled=0;
	if ($row->col1captions != 1) $row->col1captions=0;
	if ($row->col2captions != 1) $row->col2captions=0;
	if ($row->col3captions != 1) $row->col3captions=0;
	if ($row->col4captions != 1) $row->col4captions=0;
	if (!$row->store($_POST['listid'],true)) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-2); </script>\n";
		exit();
	}
	//echo $database->getquery();
	mosRedirect( "index2.php?option=$option&task=showLists" );
}

function showLists( $option ) {
	global $database, $mainframe, $my, $acl,$mosConfig_list_limit;
	if(!isset($mosConfig_list_limit)) $limit = 10;
	else $limit=$mosConfig_list_limit;
	$limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $limit );
	$limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
	if($_POST['task']=='showLists') {
		$search = $mainframe->getUserStateFromRequest( "search{$option}", 'search', '' );
		$search = $database->getEscaped( trim( strtolower( $search ) ) );
	}	
	$where = array();
	if (isset( $search ) && $search!= "") {
		$where[] = "(a.title LIKE '%$search%' OR a.description LIKE '%$search%')";
	}

	$database->setQuery( "SELECT COUNT(*)"
		. "\nFROM #__comprofiler_lists AS a"
		. (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "")
	);
	$total = $database->loadResult();
	echo $database->getErrorMsg();

	require_once("includes/pageNavigation.php");
	$pageNav = new mosPageNav( $total, $limitstart, $limit  );
	$database->setQuery( "SELECT listid, title, description, published,`default`"
		. "\nFROM #__comprofiler_lists a"
		. (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "")
		. "\n ORDER BY ordering"
		. "\nLIMIT $pageNav->limitstart, $pageNav->limit"
	);

	$rows = $database->loadObjectList();
	if ($database->getErrorNum()) {
		echo $database->stderr();
		return false;
	}

	HTML_comprofiler::showLists( $rows, $pageNav, $search, $option );
}

function editList( $fid='0', $option='com_comprofiler' ) {
	global $database, $my, $acl;

	$row = new moscomprofilerLists( $database );
	// load the row from the db table
	$row->load( $fid );

	$lists['published'] = mosHTML::yesnoSelectList( 'published', 'class="inputbox" size="1"', $row->published );
	$lists['default'] = mosHTML::yesnoSelectList( 'default', 'class="inputbox" size="1"', $row->default );
	$my_groups = $acl->get_object_groups( 'users', $my->id, 'ARO' );
	//print_r($my_groups);
	if (is_array( $my_groups ) && count( $my_groups ) > 0) {
		$ex_groups = $acl->get_group_children( $my_groups[0], 'ARO', 'RECURSE' );
	} else {
		$ex_groups = array();
	}
	//print_r($ex_groups);
	$gtree = $acl->get_group_children_tree( null, 'USERS', false );
	// remove users 'above' me

	$i = 0;
	while ($i < count( $gtree )) {
		if (in_array( $gtree[$i]->value, $ex_groups )) {
			array_splice( $gtree, $i, 1 );
		} else {
			$i++;
		}
	}

	$gtree2=array();
	$gtree2 = array_merge( $gtree2, $acl->get_group_children_tree( null, 'USERS', false ));

	$usergids=explode(",",$row->usergroupids);
	$ugids = array();
	foreach($usergids as $usergid) {
		$ugids[]->value=$usergid;
	}

	$lists['usergroups'] = moscomprofilerHTML::selectList( $gtree2, 'usergroups', 'size="4" MULTIPLE onblur="loadUGIDs(this);" mosReq=1 mosLabel="User Groups"', 'value', 'text', $ugids,1 );

	$database->setQuery( "SELECT f.fieldid, f.title"
/*		. "\n, u.email"*/
		. "\nFROM #__comprofiler_fields AS f"
/*		. "\nLEFT JOIN #__users AS u ON u.id = f.user_id"*/
		. "\nWHERE f.published = 1 AND f.profile=1" 
		. "\n ORDER BY f.ordering"
	);
	//echo $database->getQuery();
	$field = $database->loadObjectList();
	$fields = array();
	//print_r(array_values($field));
	for ($i=0, $n=count( $field ); $i < $n; $i++) {
		$fieldvalue = array();
		$fieldvalue =& $field[$i];
		//print "fieldid = ".$fieldvalue->fieldid;
		$fields[$fieldvalue->title] = $fieldvalue->fieldid;
	}
	//print_r(array_values($fields));
	HTML_comprofiler::editList( $row, $lists,$fields, $option, $fid );
}

function removeList( $cid, $option ) {
	global $database, $acl;
	include_once( "components/com_comprofiler/ue_config.php" );
	include_once ("components/com_comprofiler/comprofiler.class.php");
	if (!is_array( $cid ) || count( $cid ) < 1) {
		echo "<script> alert('Select an item to delete'); window.history.go(-1);</script>\n";
		exit;
	}
	$msg = '';
	if (count( $cid )) {
		$obj = new moscomprofilerLists( $database );
		foreach ($cid as $id) {
				$obj->delete( $id );
			}
		}
	
	//if($msg!='') echo "<script> alert('".$msg."'); window.history.go(-1);</script>\n";
	mosRedirect( "index2.php?option=$option&task=showLists", $msg );
}

function orderLists( $lid, $inc, $option ) {
	global $database;
	$row = new moscomprofilerLists( $database );
	$row->load( $lid );
	$row->move( $inc );
	mosRedirect( "index2.php?option=$option&task=showLists" );
}

function showField( $option ) {
	global $database, $mainframe, $my, $acl,$_POST,$mosConfig_list_limit;
	if(!isset($mosConfig_list_limit)) $limit = 10;
	else $limit=$mosConfig_list_limit;
	$limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $limit );
	$limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
	if($_POST['task']=='showField') {
		$search = $mainframe->getUserStateFromRequest( "search{$option}", 'search', '' );
		$search = $database->getEscaped( trim( strtolower( $search ) ) );
	}
	$where = array();
	$where[] = "(f.sys = 0)";
	if (isset( $search ) && $search!= "") {
		$where[] = "(f.name LIKE '%$search%' OR f.type LIKE '%$search%')";
	}

	$database->setQuery( "SELECT COUNT(*)"
		. "\nFROM #__comprofiler_fields AS f"
		. (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "")
	);
	$total = $database->loadResult();
	echo $database->getErrorMsg();

	require_once("includes/pageNavigation.php");
	$pageNav = new mosPageNav( $total, $limitstart, $limit  );
	$where[] = "(f.tabid = t.tabid)";
	$database->setQuery( "SELECT f.fieldid, f.title, f.name, f.type, f.required, f.published, f.profile, f.ordering, f.registration, t.title AS 'tab'"
		. "\nFROM #__comprofiler_fields AS f, #__comprofiler_tabs AS t"
		. (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "")
		. "\n ORDER BY t.ordering, f.ordering"
		. "\nLIMIT $pageNav->limitstart, $pageNav->limit"
	);

	$rows = $database->loadObjectList();
	if ($database->getErrorNum()) {
		echo $database->stderr();
		return false;
	}

	HTML_comprofiler::showFields( $rows, $pageNav, $search, $option );
}

function editField( $fid='0', $option='com_comprofiler' ) {
	global $database, $my, $acl;

	$row = new moscomprofilerFields( $database );
	// load the row from the db table
	$row->load( $fid );
	$tabs = $database->setQuery("SELECT tabid, title FROM #__comprofiler_tabs ORDER BY title");
	$tabs = $database->loadObjectList();
	$lists = array();
	$tablist = array();

	for ($i=0, $n=count( $tabs ); $i < $n; $i++) {
		$tab =& $tabs[$i];
	   	$tablist[] = mosHTML::makeOption( $tab->tabid, getLangDefinition($tab->title) );
	}
	
	$lists['tabs'] = mosHTML::selectList( $tablist, 'tabid', 'class="inputbox" size="1" mosReq=1 mosLabel="Tab"', 'value', 'text', $row->tabid );

	$types = array();

	$types[] = mosHTML::makeOption( 'checkbox', 'Check Box' );
	$types[] = mosHTML::makeOption( 'date', 'Date' );
	$types[] = mosHTML::makeOption( 'select', 'Drop Down' );
	$types[] = mosHTML::makeOption( 'emailaddress', 'Email Address' );	
	//$types[] = mosHTML::makeOption( 'password', 'Password Field' );
	$types[] = mosHTML::makeOption( 'editorta', 'Editor Text Area' );
	$types[] = mosHTML::makeOption( 'textarea', 'Text Area' );
	$types[] = mosHTML::makeOption( 'text', 'Text Field' );
	$types[] = mosHTML::makeOption( 'radio', 'Radio Button' );
	$types[] = mosHTML::makeOption( 'webaddress', 'Web Address' );


	$fvalues = $database->setQuery( "SELECT fieldtitle "
		. "\n FROM #__comprofiler_field_values"
		. "\n WHERE fieldid=$fid"
		. "\n ORDER BY ordering" );
	$fvalues = $database->loadObjectList();

	$lists['type'] = mosHTML::selectList( $types, 'type', 'class="inputbox" size="1" onchange="selType(this.options[this.selectedIndex].value);"', 'value', 'text', $row->type );

	$lists['required'] = mosHTML::yesnoSelectList( 'required', 'class="inputbox" size="1"', $row->required );

	$lists['published'] = mosHTML::yesnoSelectList( 'published', 'class="inputbox" size="1"', $row->published );

	$lists['readonly'] = mosHTML::yesnoSelectList( 'readonly', 'class="inputbox" size="1"', $row->readonly );

	$lists['profile'] = mosHTML::yesnoSelectList( 'profile', 'class="inputbox" size="1"', $row->profile );

	$lists['registration'] = mosHTML::yesnoSelectList( 'registration', 'class="inputbox" size="1"', $row->registration );

	HTML_comprofiler::editfield( $row, $lists, $fvalues, $option, $fid );
}

function saveField( $option ) {
	global $database, $my, $_POST;
	global $mosConfig_live_site;
	include_once( "components/com_comprofiler/ue_config.php" );
	include_once ("components/com_comprofiler/comprofiler.class.php");
	$row = new moscomprofilerFields( $database );
	if (!$row->bind( $_POST )) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	if ($row->type == 'textarea') $row->maxlength = $_POST['maxlength2'];
	if($_POST['oldtabid'] != $_POST['tabid']) {
		//Re-order old tab
		$sql="UPDATE #__comprofiler_fields SET ordering = ordering-1 WHERE ordering > ".$_POST['ordering']." AND tabid = ".$_POST['oldtabid']." ";
		$database->setQuery($sql);
		$database->loadResult();
		//print $database->getquery();

		//Select Last Order in New Tab
		$sql="Select max(ordering) from #__comprofiler_fields WHERE tabid=".$_POST['tabid'];
		$database->SetQuery($sql);
		$max = $database->LoadResult();
		$row->ordering=$max+1;
	}
	mosMakeHtmlSafe($row);

	$row->name = str_replace(" ", "", strtolower($row->name));

	if (!$row->check()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-2); </script>\n";
		exit();
	}
	if (!$row->store()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-2); </script>\n";
		exit();
	}
	$fieldValues = array();
	$fieldNames = array();
	$fieldNames=$_POST['vNames'];
	$j=1;
	if($row->fieldid > 0) {
		$database->setQuery( "DELETE FROM #__comprofiler_field_values"
			. " WHERE fieldid='$row->fieldid'" );
		if(!$database->loadResult()) echo $database->getErrorMsg();
	} else {
		$database->setQuery( "SELECT MAX(fieldid) FROM #__comprofiler_fields");
		$maxID=$database->loadResult();
		$row->fieldid=$maxID;
		echo $database->getErrorMsg();
	}
	//for($i=0, $n=count( $fieldNames ); $i < $n; $i++) {
	foreach ($fieldNames as $fieldName) {
		if(trim($fieldName)!=null || trim($fieldName)!='') {
			$database->setQuery( "INSERT INTO #__comprofiler_field_values (fieldid,fieldtitle,ordering)"
				. " VALUES('$row->fieldid','".addslashes(htmlspecialchars($fieldName))."',$j)"
			);
			if(!$database->loadResult()) echo $database->getErrorMsg();
			$j++;
		}

	}

	$limit = intval( mosGetParam( $_REQUEST, 'limit', 10 ) );
	$limitstart	= intval( mosGetParam( $_REQUEST, 'limitstart', 0 ) );
	mosRedirect( "index2.php?option=$option&task=showField" );
}

function removeField( $cid, $option ) {
	global $database, $acl;
	include_once( "components/com_comprofiler/ue_config.php" );
	include_once ("components/com_comprofiler/comprofiler.class.php");
	if (!is_array( $cid ) || count( $cid ) < 1) {
		echo "<script> alert('Select an item to delete'); window.history.go(-1);</script>\n";
		exit;
	}
	$msg = '';
	if (count( $cid )) {
		$obj = new moscomprofilerFields( $database );

		foreach ($cid as $id) {
			$obj->load($id);
			$database->setQuery("SELECT COUNT(*) FROM #__comprofiler_lists".
					" WHERE col1fields like '%|*|$id' OR col1fields like '$id|*|%' OR col1fields like '%|*|$id|*|%' OR col1fields='$id'".
					" OR col2fields like '%|*|$id' OR col2fields like '$id|*|%' OR col2fields like '%|*|$id|*|%' OR col2fields='$id'".
					" OR col3fields like '%|*|$id' OR col3fields like '$id|*|%' OR col3fields like '%|*|$id|*|%' OR col3fields='$id'".
					" OR col4fields like '%|*|$id' OR col4fields like '$id|*|%' OR col4fields like '%|*|$id|*|%' OR col4fields='$id'");
			$onList = $database->loadResult();
			if($onList > 0) {
				$msg .= getLangDefinition($obj->title) . " cannot be deleted because it is on a List. \n";
				$noDelete = 1;
			}
			if($obj->sys==1) {
				$msg .= getLangDefinition($obj->title) ." cannot be deleted because it is a system field. \n";
				$noDelete = 1;
			} 
			if($noDelete != 1) {
				$obj->deleteColumn('#__comprofiler',$obj->name);
				$obj->delete( $id );
				$sql="UPDATE #__comprofiler_fields SET ordering = ordering-1 WHERE ordering > ".$obj->ordering." AND tabid = ".$obj->tabid." ";
				$database->setQuery($sql);
				$database->loadResult();
				//print $database->getquery();
			}
			$noDelete = 0;
		}
	}
	
	//if($msg!='') echo "<script> alert('".$msg."'); window.history.go(-1);</script>\n";
	mosRedirect( "index2.php?option=$option&task=showField", $msg );
}


function orderFields( $fid, $inc, $option ) {
	global $database;
	$row = new moscomprofilerFields( $database );
	$row->load( $fid );
	$row->move( $inc );
	mosRedirect( "index2.php?option=$option&task=showField" );
}


function showTab( $option ) {
	global $database, $mainframe, $my, $acl,$mosConfig_list_limit;
	if(!isset($mosConfig_list_limit)) $limit = 10;
	else $limit=$mosConfig_list_limit;
	$limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $limit );
	$limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
	if($_POST['task']=='showTab') {
		$search = $mainframe->getUserStateFromRequest( "search{$option}", 'search', '' );
		$search = $database->getEscaped( trim( strtolower( $search ) ) );
	}
	$where = array();
	if (isset( $search ) && $search!= "") {
		$where[] = "(title LIKE '%$search%')";
	}

	$database->setQuery( "SELECT COUNT(*)"
		. "\nFROM #__comprofiler_tabs AS a"
		. (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "")
	);
	$total = $database->loadResult();
	echo $database->getErrorMsg();

	require_once("includes/pageNavigation.php");
	$pageNav = new mosPageNav( $total, $limitstart, $limit  );

	$database->setQuery( "SELECT * "
		. "\nFROM #__comprofiler_tabs AS a"
		. (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "")
		. "\n ORDER BY ordering"
		. "\nLIMIT $pageNav->limitstart, $pageNav->limit"
	);

	$rows = $database->loadObjectList();
	if ($database->getErrorNum()) {
		echo $database->stderr();
		return false;
	}

	HTML_comprofiler::showTabs( $rows, $pageNav, $search, $option );
}

function editTab( $tid='0', $option='com_comprofiler' ) {
	global $database, $my, $acl;

	$row = new moscomprofilerTabs( $database );
	// load the row from the db table
	$row->load( $tid );

	$width = array();

	$width[] = mosHTML::makeOption( '.5', 'Half Row' );
	$width[] = mosHTML::makeOption( '1', 'Full Row' );

 	$lists = array();
	$lists['width'] = mosHTML::selectList( $width, 'width', 'class="inputbox" size="1"', 'value', 'text', $row->width );
	$lists['enabled'] = mosHTML::yesnoSelectList( 'enabled', 'class="inputbox" size="1"', $row->enabled );

	HTML_comprofiler::edittab( $row, $option, $lists, $tid );
}

function saveTab( $option ) {
	global $database, $my;
	global $mosConfig_live_site;
	include_once( "components/com_comprofiler/ue_config.php" );
	include_once ("components/com_comprofiler/comprofiler.class.php");
	$row = new moscomprofilerTabs( $database );
	if (!$row->bind( $_POST )) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}

	mosMakeHtmlSafe($row);
	if (!$row->check()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-2); </script>\n";
		exit();
	}
	if (!$row->store()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-2); </script>\n";
		exit();
	}

	$row->checkin();
	$limit = intval( mosGetParam( $_REQUEST, 'limit', 10 ) );
	$limitstart	= intval( mosGetParam( $_REQUEST, 'limitstart', 0 ) );
	mosRedirect( "index2.php?option=$option&task=showTab" );
}

function removeTabs( $cid, $option ) {
	global $database, $acl;
	include_once( "components/com_comprofiler/ue_config.php" );
	include_once ("components/com_comprofiler/comprofiler.class.php");
	if (!is_array( $cid ) || count( $cid ) < 1) {
		echo "<script> alert('Select an item to delete'); window.history.go(-1);</script>\n";
		exit;
	}
	$msg = '';
	if (count( $cid )) {
		$obj = new moscomprofilerTabs( $database );
		foreach ($cid as $id) {
				$database->setQuery("SELECT COUNT(*) FROM #__comprofiler_fields WHERE tabid='$id'");
				$onField = $database->loadResult();
				if($onField==0) {
					$obj->delete( $id );
					$msg .= $obj->getError();
				} else {
					$msg .= "This tab is being referenced by an existing field and cannot be deleted!";
				}
			}
		}

	$limit = intval( mosGetParam( $_REQUEST, 'limit', 10 ) );
	$limitstart	= intval( mosGetParam( $_REQUEST, 'limitstart', 0 ) );
	mosRedirect( "index2.php?option=$option&task=showTab", $msg );
}


function orderTabs( $tid, $inc, $option ) {
	global $database;
	$row = new moscomprofilerTabs( $database );
	$row->load( $tid );
	$row->move( $inc );
	mosRedirect( "index2.php?option=$option&task=showTab" );
}

function showUsers( $option ) {
	global $database, $mainframe, $my, $acl,$mosConfig_list_limit,$_POST;
	if(!isset($mosConfig_list_limit)) $limit = 10;
	else $limit=$mosConfig_list_limit;
	$limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $limit );
	$limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
	if($_POST['task']=='showusers') {
		$search = $mainframe->getUserStateFromRequest( "search{$option}", 'search', '' );
		$search = $database->getEscaped( trim( strtolower( $search ) ) );
	}
	$where = array();
	if (isset( $search ) && $search!= "") {
		$where[] = "(username LIKE '%$search%' OR email LIKE '%$search%' OR a.name LIKE '%$search%')";
	}

	// exclude any child group id's for this user
	//$acl->_debug = true;
	$pgids = $acl->get_group_children( $my->gid, 'ARO', 'RECURSE' );

	if (is_array( $pgids ) && count( $pgids ) > 0) {
		$where[] = "(a.gid NOT IN (" . implode( ',', $pgids ) . "))";
	}

	$database->setQuery( "SELECT COUNT(*)"
		. "\nFROM #__users AS a"
		. (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "")
	);
	$total = $database->loadResult();
	echo $database->getErrorMsg();

	require_once("includes/pageNavigation.php");
	$pageNav = new mosPageNav( $total, $limitstart, $limit  );

	$database->setQuery( "SELECT a.*, g.name AS groupname, s.userid AS loggedin,ue.approved,ue.confirmed"
		. "\nFROM #__users AS a"
		. "\nLEFT JOIN #__comprofiler AS ue ON a.id = ue.id"
		. "\nINNER JOIN #__core_acl_aro AS aro ON aro.value = a.id"	// map user to aro
		. "\nINNER JOIN #__core_acl_groups_aro_map AS gm ON gm.aro_id = aro.aro_id"	// map aro to group
		. "\nINNER JOIN #__core_acl_aro_groups AS g ON g.group_id = gm.group_id"
		. "\n LEFT JOIN #__session AS s ON s.userid = a.id"
		. (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "")
		//. "\nGROUP BY usertype,username"
		//. "\nORDER BY usertype"
		. "\nLIMIT $pageNav->limitstart, $pageNav->limit"
	);

	$rows = $database->loadObjectList();
	if ($database->getErrorNum()) {
		echo $database->stderr();
		return false;
	}

	HTML_comprofiler::showUsers( $rows, $pageNav, $search, $option );
}

function editUser( $uid='0', $option='users' ) {
	global $database, $my, $acl,$ueConfig;

	$row = new mosUser( $database );
	// load the row from the db table
	$row->load( $uid );
	$row->orig_password = $row->password;
	$database->setQuery( "SELECT * FROM #__comprofiler"
	. "\n WHERE id='$uid'");
	$rowExtras = $database->loadObjectList();
	$rowExtras = $rowExtras[0];
	$database->setQuery( "SELECT t.title as 'tab', f.* FROM #__comprofiler_fields f, #__comprofiler_tabs t"
	. "\n WHERE t.tabid = f.tabid AND f.published=1 AND t.enabled=1"
	. "\n ORDER BY t.ordering, f.ordering" );
	$rowFields = $database->loadObjectList();
	$rowFieldValues=array();
	$fieldJS=' ';
	for($i=0, $n=count( $rowFields ); $i < $n; $i++) {
		
		$k = "\$rowExtras->".$rowFields[$i]->name;
		eval("\$k = \"$k\";");
		if($rowFields[$i]->type=='editorta') {
			ob_start();
			getEditorContents( 'editor'.$rowFields[$i]->name, $rowFields[$i]->name ) ;
			$fieldJS .= ob_get_contents();
			ob_end_clean();
		}
		$database->setQuery( "SELECT fieldtitle FROM #__comprofiler_field_values"
		. "\n WHERE fieldid = ".$rowFields[$i]->fieldid
		. "\n ORDER BY ordering" );
		$Values = $database->loadObjectList();
		if($ueConfig['adminrequiredfields']==1) $adminReq=$rowFields[$i]->required;
		else $adminReq=0;
		if(count($Values) > 0) {
			if($rowFields[$i]->type=='radio') $rowFieldValues['lst_'.$rowFields[$i]->name] = moscomprofilerHTML::radioList( $Values, $rowFields[$i]->name, 'class="inputbox" size="1" mosReq="'.$adminReq.'" mosLabel="'.getLangDefinition($rowFields[$i]->title).'"', 'fieldtitle', 'fieldtitle', $k);
			else $rowFieldValues['lst_'.$rowFields[$i]->name] = moscomprofilerHTML::selectList( $Values, $rowFields[$i]->name, 'class="inputbox" size="1" mosReq="'.$adminReq.'" mosLabel="'.getLangDefinition($rowFields[$i]->title).'"', 'fieldtitle', 'fieldtitle', $k);
		}
	}
	$lists = array();

	$my_group = strtolower( $acl->get_group_name( $row->gid, 'ARO' ) );
	if ($my_group == 'super administrator') {
		$lists['gid'] = "<input type=\"hidden\" mosReq=0 name=\"gid\" value=\"$my->gid\" /><strong>Super Administrator</strong>";
	} else {
		// ensure user can't add group higher than themselves
		$my_groups = $acl->get_object_groups( 'users', $my->id, 'ARO' );
		if (is_array( $my_groups ) && count( $my_groups ) > 0) {
			$ex_groups = $acl->get_group_children( $my_groups[0], 'ARO', 'RECURSE' );
		} else {
			$ex_groups = array();
		}
	
		$gtree = $acl->get_group_children_tree( null, 'USERS', false );

		// remove users 'above' me
		$i = 0;
		while ($i < count( $gtree )) {
			if (in_array( $gtree[$i]->value, $ex_groups )) {
				array_splice( $gtree, $i, 1 );
			} else {
				$i++;
			}
		}

		$lists['gid'] = mosHTML::selectList( $gtree, 'gid', 'size="4" mosReq=0', 'value', 'text', $row->gid );
	}

// make the select list for yes/no fields
	$yesno[] = mosHTML::makeOption( '0', 'No' );
	$yesno[] = mosHTML::makeOption( '1', 'Yes' );

// build the html select list
	$lists['block'] = mosHTML::yesnoSelectList( 'block', 'class="inputbox" size="1"', $row->block );
	$lists['approved'] = mosHTML::yesnoSelectList( 'approved', 'class="inputbox" size="1"', $rowExtras->approved );
	$lists['confirmed'] = mosHTML::yesnoSelectList( 'confirmed', 'class="inputbox" size="1"', $rowExtras->confirmed );
// build the html select list
	$lists['sendEmail'] = mosHTML::yesnoSelectList( 'sendEmail', 'class="inputbox" size="1"', $row->sendEmail );

	HTML_comprofiler::edituser( $row,$rowExtras, $rowFields, $rowFieldValues, $lists, $option, $uid,$fieldJS );
}

function saveUser( $option ) {
	global $database, $my;
	global $mosConfig_live_site,$_POST,$ueConfig;
	include_once( "components/com_comprofiler/ue_config.php" );
	include_once ("components/com_comprofiler/comprofiler.class.php");
	$row = new mosUser( $database );
	if (!$row->bind( $_POST )) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	$isNew = !$row->id;
	$pwd = '';
	if ($isNew) {
		// new user stuff
		if ($row->password == '') {
			$pwd = mosMakePassword();
			$row->password = md5( $pwd );
		} else {
			$pwd = $row->password;
			$row->password = md5( $row->password );
		}
		$row->registerDate = date("Y-m-d H:i:s");
	} else {
		// existing user stuff
		if ($row->password == '') {
			// password set to null if empty
			$row->password = null;
		} else {
			$row->password = md5( $row->password );
		}
	}

	SWITCH ($ueConfig['name_style']) {
		case 2: 	
			$row->name = $_POST['firstname'] . ' ' . $_POST['lastname'];
		break;
		case 3:
			if(isset($_POST['middlename'])) $row->name = $_POST['firstname'] . ' ' . $_POST['middlename']. ' ' . $_POST['lastname'];
			else $row->name = $_POST['firstname']. ' ' . $_POST['lastname'];
		break;
	}

	mosMakeHtmlSafe($row);
	if (!$row->check()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-2); </script>\n";
		exit();
	}
	if (!$row->store()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-2); </script>\n";
		exit();
	}

	$sqlFormat = "Y-m-d";
	$selFields = '';
	$database->setQuery( "SELECT f.* FROM #__comprofiler_fields f, #__comprofiler_tabs t"
	. "\n WHERE f.published=1 and f.tabid = t.tabid AND t.enabled=1" );
	$rowFields = $database->loadObjectList();

	if(!$_POST['id'] > 0) {
	$database->setQuery("SELECT id FROM #__users WHERE username = '".$_POST['username']."'");
	$uid = $database->loadResult();
	$sqlType = 'I';
	} else {
	$uid = $row->id;
	$sqlType = 'U';
	}
	$colList = "`id`, `user_id`, `approved`, `confirmed`, `firstname`, `middlename`, `lastname`";
	$valueList = "'$uid','$uid','".$_POST['approved']."','".$_POST['confirmed']."','".$_POST['firstname']."','".$_POST['middlename']."','".$_POST['lastname']."'";
	if(count($rowFields) > 0) {
		for($i=0, $n=count( $rowFields ); $i < $n; $i++) {
		if($i > 0) $selFields .=", ";
				switch($rowFields[$i]->type) {
				CASE 'date': 
					$selFields .= "`".$rowFields[$i]->name."`='".dateConverter($_POST[$rowFields[$i]->name],$ueConfig[date_format],$sqlFormat)."' ";
					$colList .= ", `".$rowFields[$i]->name."`";
					$valueList .= ", '".dateConverter($_POST[$rowFields[$i]->name],$ueConfig[date_format],$sqlFormat)."'";
				break;
				CASE 'webaddress':
				CASE 'emailaddress': 
					$selFields .= "`".$rowFields[$i]->name."`='".htmlspecialchars(addslashes(str_replace(array('mailto:','http://','https://'),'',strtolower($_POST[$rowFields[$i]->name]))))."' ";
					$colList .= ", `".$rowFields[$i]->name."`";
					$valueList .= ", '".htmlspecialchars(addslashes(str_replace(array('mailto:','http://','https://'),'',strtolower($_POST[$rowFields[$i]->name]))))."'";
				break;
				CASE 'editorta': 
					$selFields .= "`".$rowFields[$i]->name."`='".addslashes($_POST[$rowFields[$i]->name])."' ";
					$colList .= ", `".$rowFields[$i]->name."`";
					$valueList .= ", '".addslashes($_POST[$rowFields[$i]->name])."'";
				break;
				DEFAULT:
					$selFields .= "`".$rowFields[$i]->name."`='".addslashes($_POST[$rowFields[$i]->name])."' ";
					$colList .= ", `".$rowFields[$i]->name."`";
					$valueList .= ", '".htmlspecialchars(addslashes($_POST[$rowFields[$i]->name]))."'";
				break;
				}
		}
		$selFields .= ", `lastupdatedate`='".date('Y-m-d\TH:i:s')."', `confirmed`='".$_POST['confirmed']."', `approved`='".$_POST['approved']."', `firstname`='".$_POST['firstname']."', `middlename`='".$_POST['middlename']."', `lastname`='".$_POST['lastname']."'";
		if($sqlType == 'U') $sql = "UPDATE #__comprofiler SET ".stripslashes($selFields)." WHERE `id`='".$row->id."'";
		else $sql = "INSERT INTO #__comprofiler (".stripslashes($colList).") VALUES (".stripslashes($valueList).")";
		$database->setQuery( $sql );
		//print $database->getquery();
		if (!$database->query()) {
			die("SQL error" . $database->stderr(true));
		}
	}

// update the ACL

	if ($isNew) {
	} else {
		$database->setQuery( "SELECT aro_id FROM #__core_acl_aro WHERE value='$row->id'" );
		$aro_id = $database->loadResult();

		$database->setQuery( "UPDATE #__core_acl_groups_aro_map"
			. "\nSET group_id = '$row->gid'"
			. "\nWHERE aro_id = '$aro_id'"
		);
		$database->query() or die( $database->stderr() );
	}

	$row->checkin();
	if ($isNew) {
		//TODO: Add emails configuration code.
		$database->setQuery( "SELECT email FROM #__users WHERE id=$my->id" );
		$adminEmail = $database->loadResult();

		$subject = "New User Details";
		$message = "Hello $row->name,\r \n \r \n";
		$message .= "You have been added as a user to $mosConfig_live_site by an Administrator.\r \n";
		$message .= "This email contains your username and password to log into the $mosConfig_live_site site:\r \n \r \n";
		$message .= "Username - $row->username\r \n";
		$message .= "Password - $pwd\r \n \r \n \r \n";
		$message .= "Please do not respond to this message as it is automatically generated and is for information purposes only\r \n";

		$headers .= "From: $adminEmail\r\n";
		$headers .= "Reply-To: $adminEmail\r\n";
		$headers .= "X-Priority: 3\r\n";
		$headers .= "X-MSMail-Priority: Low\r\n";
		$headers .= "X-Mailer: Mambo Open Source 4.5\r\n";

		mail( $row->email, $subject, $message, $headers );
	}

	$limit = intval( mosGetParam( $_REQUEST, 'limit', 10 ) );
	$limitstart	= intval( mosGetParam( $_REQUEST, 'limitstart', 0 ) );
	mosRedirect( "index2.php?option=$option&task=showusers" );
}

function removeUsers( $cid, $option ) {
	global $database, $acl;
	include_once( "components/com_comprofiler/ue_config.php" );
	include_once ("components/com_comprofiler/comprofiler.class.php");
	if (!is_array( $cid ) || count( $cid ) < 1) {
		echo "<script> alert('Select an item to delete'); window.history.go(-1);</script>\n";
		exit;
	}
	$msg = '';
	if (count( $cid )) {
		$obj = new mosUser( $database );
		$obj2 = new moscomprofiler( $database );
		foreach ($cid as $id) {
			// check for a super admin ... can't delete them
			$groups = $acl->get_object_groups( 'users', $id, 'ARO' );
			$this_group = strtolower( $acl->get_group_name( $groups[0], 'ARO' ) );
			if ($this_group == 'super administrator') {
				$msg .= "You cannot delete a Super Administrator";
			} else {
				$obj->delete( $id );
				$obj2->delete( $id );
				$msg .= $obj->getError();
				$msg .= $obj2->getError();
			}
		}
	}

	$limit = intval( mosGetParam( $_REQUEST, 'limit', 10 ) );
	$limitstart	= intval( mosGetParam( $_REQUEST, 'limitstart', 0 ) );
	mosRedirect( "index2.php?option=$option&task=showusers", $msg );
}

/**
* Blocks or Unblocks one or more user records
* @param array An array of unique category id numbers
* @param integer 0 if unblock, 1 if blocking
* @param string The current url option
*/
function changeUserBlock( $cid=null, $block=1, $option ) {
	global $database, $my;

	if (count( $cid ) < 1) {
		$action = $block ? 'block' : 'unblock';
		echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
		exit;
	}

	$cids = implode( ',', $cid );

	$database->setQuery( "UPDATE #__users SET block='$block'"
	. "\nWHERE id IN ($cids)"
	);
	if (!$database->query()) {
		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		exit();
	}

	mosRedirect( "index2.php?option=$option&task=showusers" );
}

function is_email($email){
	$rBool=false;

	if(preg_match("/[\w\.\-]+@\w+[\w\.\-]*?\.\w{1,4}/", $email)){
		$rBool=true;
	}
	return $rBool;
}
function showConfig( $option ) {
   global $database,$ueConfig,$acl,$my;
   global $mosConfig_lang;

   $configfile = "components/com_comprofiler/ue_config.php";
   @chmod ($configfile, 0766);
   $permission = is_writable($configfile);
   if (!$permission) {
      echo "<center><h1><font color=red>Warning...</FONT></h1><BR>";
      echo "<B>Your config file is /administrator/$configfile</b><BR>";
      echo "<B>You need to chmod this to 766 in order for the config to be updated</B></center><BR><BR>";
   }

   //include_once( $configfile );

   $lists = array();	
   // make a standard yes/no list
   $yesno = array();
   $yesno[] = mosHTML::makeOption( '0', _UE_NO );
    $yesno[] = mosHTML::makeOption( '1', _UE_YES );

    $mypms[] = mosHTML::makeOption( '0', _UE_NO );
    $mypms[] = mosHTML::makeOption( '1', 'Open Source' );
    $mypms[] = mosHTML::makeOption( '2', 'PRO' );

	$dateformats = array();
	$dateformats[] = mosHTML::makeOption('Y/m/d','yyyy/mm/dd');
	$dateformats[] = mosHTML::makeOption('d/m/y','dd/mm/yy');
	$dateformats[] = mosHTML::makeOption('y/m/d','yy/mm/dd');
	$dateformats[] = mosHTML::makeOption('d/m/Y','dd/mm/yyyy');
	$dateformats[] = mosHTML::makeOption('m/d/y','mm/dd/yy');
	$dateformats[] = mosHTML::makeOption('m/d/Y','mm/dd/yyyy');
	$dateformats[] = mosHTML::makeOption('Y-m-d','yyyy-mm-dd');
	$dateformats[] = mosHTML::makeOption('d-m-y','dd-mm-yy');
	$dateformats[] = mosHTML::makeOption('y-m-d','yy-mm-dd');
	$dateformats[] = mosHTML::makeOption('d-m-Y','dd-mm-yyyy');
	$dateformats[] = mosHTML::makeOption('m-d-y','mm-dd-yy');
	$dateformats[] = mosHTML::makeOption('m-d-Y','mm-dd-yyyy');
	$dateformats[] = mosHTML::makeOption('Y.m.d','yyyy.mm.dd');
	$dateformats[] = mosHTML::makeOption('d.m.y','dd.mm.yy');
	$dateformats[] = mosHTML::makeOption('y.m.d','yy.mm.dd');
	$dateformats[] = mosHTML::makeOption('d.m.Y','dd.mm.yyyy');
	$dateformats[] = mosHTML::makeOption('m.d.y','mm.dd.yy');
	$dateformats[] = mosHTML::makeOption('m.d.Y','mm.dd.yyyy');

	$nameformats = array();
	$nameformats[] = mosHTML::makeOption('1','Name Only');
	$nameformats[] = mosHTML::makeOption('2','Name (username)');
	$nameformats[] = mosHTML::makeOption('3','Username Only');
	$nameformats[] = mosHTML::makeOption('4','Username (Name)');

	$namestyles = array();
	$namestyles[] = mosHTML::makeOption('1','Single Name Field');
	$namestyles[] = mosHTML::makeOption('2','First and Last Name Field');
	$namestyles[] = mosHTML::makeOption('3','First, Middle, and Last Name Field');

	$emailhandling = array();
	$emailhandling[] = mosHTML::makeOption('1','Display Email Only');
	$emailhandling[] = mosHTML::makeOption('2','Display Email w/ MailTo link');
	$emailhandling[] = mosHTML::makeOption('3','Display Link to Email Form');
	$emailhandling[] = mosHTML::makeOption('4','Do Not Display Email');


		// ensure user can't add group higher than themselves

		$my_groups = $acl->get_object_groups( 'users', $my->id, 'ARO' );
		//print_r($my_groups);
		if (is_array( $my_groups ) && count( $my_groups ) > 0) {
			$ex_groups = $acl->get_group_children( $my_groups[0], 'ARO', 'RECURSE' );
		} else {
			$ex_groups = array();
		}
		//print_r($ex_groups);
		$gtree = $acl->get_group_children_tree( null, 'USERS', false );
		// remove users 'above' me

		$i = 0;
		while ($i < count( $gtree )) {
			if (in_array( $gtree[$i]->value, $ex_groups )) {
				array_splice( $gtree, $i, 1 );
			} else {
				$i++;
			}
		}

		$gtree2=array();
	        $gtree2[] = mosHTML::makeOption( -2 , '- Everybody -' );
	        $gtree2[] = mosHTML::makeOption( -1, '- All Registered Users -' );
		$gtree2 = array_merge( $gtree2, $acl->get_group_children_tree( null, 'USERS', false ));
	//print_r($gtree);
	if($my_groups[0] >= $ueConfig['imageApproverGid']) {
	   	$lists['imageApproverGid'] = mosHTML::selectList( $gtree, 'cfg_imageApproverGid', 'size="4"', 'value', 'text', $ueConfig['imageApproverGid'] );
	} else {
		$lists['imageApproverGid']="<b>".$acl->get_group_name($ueConfig['imageApproverGid'])."</b>\n<input type='hidden' name='cfg_imageApproverGid' value='".$ueConfig['imageApproverGid']."' />";
	}

	$lists['allow_profileviewbyGID']=mosHTML::selectList( $gtree2, 'cfg_allow_profileviewbyGID', 'size="4"', 'value', 'text', $ueConfig['allow_profileviewbyGID'] );
	$lists['allow_listviewbyGID']=mosHTML::selectList( $gtree2, 'cfg_allow_listviewbyGID', 'size="4"', 'value', 'text', $ueConfig['allow_listviewbyGID'] );
   // registered users only

   $lists['allow_email_display'] = mosHTML::selectList( $emailhandling, 'cfg_allow_email_display', 'class="inputbox" size="1"', 'value', 'text', $ueConfig['allow_email_display'] );

   $lists['name_format'] = mosHTML::selectList($nameformats, 'cfg_name_format','class="inputbox" size="1"', 'value', 'text', $ueConfig['name_format'] );

   $lists['name_style'] = mosHTML::selectList($namestyles, 'cfg_name_style','class="inputbox" size="1"', 'value', 'text', $ueConfig['name_style'] );

   $lists['date_format'] = mosHTML::selectList($dateformats, 'cfg_date_format','class="inputbox" size="1"', 'value', 'text', $ueConfig['date_format'] );

   $lists['usernameedit'] = mosHTML::selectList( $yesno, 'cfg_usernameedit', 'class="inputbox" size="1"', 'value', 'text', $ueConfig['usernameedit'] );

   $lists['allow_profilelink'] = mosHTML::selectList( $yesno, 'cfg_allow_profilelink', 'class="inputbox" size="1"', 'value', 'text', $ueConfig['allow_profilelink'] );

   $lists['allow_email'] = mosHTML::selectList( $yesno, 'cfg_allow_email', 'class="inputbox" size="1"', 'value', 'text', $ueConfig['allow_email'] );
   $lists['allow_im'] = mosHTML::selectList( $yesno, 'cfg_allow_im', 'class="inputbox" size="1"', 'value', 'text', $ueConfig['allow_im'] );
   $lists['allow_onlinestatus'] = mosHTML::selectList( $yesno, 'cfg_allow_onlinestatus', 'class="inputbox" size="1"', 'value', 'text', $ueConfig['allow_onlinestatus'] );
   $lists['allow_website'] = mosHTML::selectList( $yesno, 'cfg_allow_website', 'class="inputbox" size="1"', 'value', 'text', $ueConfig['allow_website'] );
   $lists['allow_email_usercontr'] = mosHTML::selectList( $yesno, 'cfg_allow_email_usercontr', 'class="inputbox" size="1"', 'value', 'text', $ueConfig['allow_email_usercontr'] );

   $lists['reg_enable_toc'] = mosHTML::selectList( $yesno, 'cfg_reg_enable_toc', 'class="inputbox" size="1"', 'value', 'text', $ueConfig['reg_enable_toc'] );

   $lists['admin_approval'] = mosHTML::selectList( $yesno, 'cfg_reg_admin_approval', 'class="inputbox" size="1"', 'value', 'text', $ueConfig['reg_admin_approval'] );

   $lists['confirmation'] = mosHTML::selectList( $yesno, 'cfg_reg_confirmation', 'class="inputbox" size="1"', 'value', 'text', $ueConfig['reg_confirmation'] );

   $lists['allowsubscriptions'] = mosHTML::selectList( $yesno, 'cfg_allowsubscriptions', 'class="inputbox" size="1"', 'value', 'text', $ueConfig['allowsubscriptions'] );

   $lists['allowAvatar'] = mosHTML::selectList( $yesno, 'cfg_allowAvatar', 'class="inputbox" size="1"', 'value', 'text', $ueConfig['allowAvatar'] );

   $lists['allowAvatarUpload'] = mosHTML::selectList( $yesno, 'cfg_allowAvatarUpload', 'class="inputbox" size="1"', 'value', 'text', $ueConfig['allowAvatarUpload'] );

   $lists['allowAvatarGallery'] = mosHTML::selectList( $yesno, 'cfg_allowAvatarGallery', 'class="inputbox" size="1"', 'value', 'text', $ueConfig['allowAvatarGallery'] );

   $lists['avatarUploadApproval'] = mosHTML::selectList( $yesno, 'cfg_avatarUploadApproval', 'class="inputbox" size="1"', 'value', 'text', $ueConfig['avatarUploadApproval'] );

   $lists['rte'] = mosHTML::selectList( $yesno, 'cfg_rte', 'class="inputbox" size="1"', 'value', 'text', $ueConfig['rte'] );

   $lists['pms'] = mosHTML::selectList( $mypms, 'cfg_pms', 'class="inputbox" size="1"', 'value', 'text', $ueConfig['pms'] );

   $lists['allowUserReports'] = mosHTML::selectList( $yesno, 'cfg_allowUserReports', 'class="inputbox" size="1"', 'value', 'text', $ueConfig['allowUserReports'] );
   $lists['allowUserBanning'] = mosHTML::selectList( $yesno, 'cfg_allowUserBanning', 'class="inputbox" size="1"', 'value', 'text', $ueConfig['allowUserBanning'] );
   $lists['autoImageResize'] = mosHTML::selectList( $yesno, 'cfg_autoImageResize', 'class="inputbox" size="1"', 'value', 'text', $ueConfig['autoImageResize'] );
   $lists['adminrequiredfields'] = mosHTML::selectList( $yesno, 'cfg_adminrequiredfields', 'class="inputbox" size="1"', 'value', 'text', $ueConfig['adminrequiredfields'] );
   $lists['moderatorEmail'] = mosHTML::selectList( $yesno, 'cfg_moderatorEmail', 'class="inputbox" size="1"', 'value', 'text', $ueConfig['moderatorEmail'] );
   $lists['allowModUserApproval'] = mosHTML::selectList( $yesno, 'cfg_allowModUserApproval', 'class="inputbox" size="1"', 'value', 'text', $ueConfig['allowModUserApproval'] );


   HTML_comprofiler::showConfig( $ueConfig, $lists, $option );
}

function saveConfig ( $option ) {
   //Add code to check if config file is writeable.
   $configfile = "components/com_comprofiler/ue_config.php";
   @chmod ($configfile, 0766);
   if (!is_writable($configfile)) {
      mosRedirect("index2.php?option=$option", "FATAL ERROR: Config File Not writeable" );
   }

   $txt = "<?php\n";
   foreach ($_POST as $k=>$v) {
      if (strpos( $k, 'cfg_' ) === 0) {
         if (!get_magic_quotes_gpc()) {
            $v = addslashes( $v );
         }
         $txt .= "\$ueConfig['".substr( $k, 4 )."']='$v';\n";
      }
   }
   $txt .= "?>";

   if ($fp = fopen( $configfile, "w")) {
      fputs($fp, $txt, strlen($txt));
      fclose ($fp);
      mosRedirect( "index2.php?option=$option&task=showconfig", "Configuration file saved" );
   } else {
      mosRedirect( "index2.php?option=$option", "FATAL ERROR: File could not be opened." );
   }
}

function approveUser( $cid=null, $approved=1, $option ) {
    global $database, $my, $ueConfig,$mosConfig_emailpass;
	include_once( "components/com_comprofiler/ue_config.php" );
	include_once ("components/com_comprofiler/comprofiler.class.php");
    	if (count( $cid ) < 1) {
       	    $action = $approved ? 'Approve' : 'Reject';
    	    echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
    	    exit;
    	}

    	$cids = implode( ',', $cid );

	foreach ($cid AS $cids) {
		$database->setQuery( "UPDATE #__comprofiler SET approved='$approved' WHERE id = '$cids'");
	    	if ($database->query()) {
			if($approved==1) {
				$row = new mosUser( $database );
				$row->load( $cids );
				if($mosConfig_emailpass == "1") {
					$pwd = makePass();
					$row->password = $pwd;
					$pwd=md5($pwd);
					$database->setQuery( "UPDATE #__users SET password='$pwd' WHERE id = '$cids'");
	    				$database->query();
					createEmail($row, 'welcome', $ueConfig,null,1);
				} else {
	    				createEmail($row, 'welcome', $ueConfig,null,0);	
				}
			}
		}
		
	}
    mosRedirect( "index2.php?option=$option&task=showusers" );
}



function requiredField( $cid=null, $flag=1, $option ) {
    global $database, $my, $ueConfig;
    	if (count( $cid ) < 1) {
       	    $action = $flag ? 'Make Required' : 'Make Non-required';
    	    echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
    	    exit;
    	}

    	$cids = implode( ',', $cid );

	foreach ($cid AS $cids) {
		$database->setQuery( "UPDATE #__comprofiler_fields SET required='$flag' WHERE fieldid = '$cids'");
	    	$database->query();
		//print $database->getquery();
	}
    mosRedirect( "index2.php?option=$option&task=showField" );
}

function publishField( $cid=null, $flag=1, $option ) {
    global $database, $my, $ueConfig;
    	if (count( $cid ) < 1) {
       	    $action = $flag ? 'Publish' : 'UnPublish';
    	    echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
    	    exit;
    	}

    	$cids = implode( ',', $cid );

	foreach ($cid AS $cids) {
		$database->setQuery( "UPDATE #__comprofiler_fields SET published='$flag' WHERE fieldid = '$cids'");
	    	$database->query();
		//print $database->getquery();
	}
    mosRedirect( "index2.php?option=$option&task=showField" );
}

function registrationField( $cid=null, $flag=1, $option ) {
    global $database, $my, $ueConfig;
    	if (count( $cid ) < 1) {
       	    $action = $flag ? 'Add to Registration' : 'Remove from Registration';
    	    echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
    	    exit;
    	}

    	$cids = implode( ',', $cid );

	foreach ($cid AS $cids) {
		$database->setQuery( "UPDATE #__comprofiler_fields SET registration='$flag' WHERE fieldid = '$cids'");
	    	$database->query();
		//print $database->getquery();
	}
    mosRedirect( "index2.php?option=$option&task=showField" );
}

function listPublishedField( $cid=null, $flag=1, $option ) {
    global $database, $my, $ueConfig;
    	if (count( $cid ) < 1) {
       	    $action = $flag ? 'Publish' : 'UnPublish';
    	    echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
    	    exit;
    	}

    	$cids = implode( ',', $cid );

	foreach ($cid AS $cids) {
		$database->setQuery( "UPDATE #__comprofiler_lists SET published='$flag' WHERE listid = '$cids'");
	    	$database->query();
		//print $database->getquery();
	}
    mosRedirect( "index2.php?option=$option&task=showLists" );
}
function listDefaultField( $cid=null, $flag=1, $option ) {
    global $database, $my, $ueConfig;
    	if (count( $cid ) < 1) {
       	    $action = $flag ? 'Make Default' : 'Reset Default';
    	    echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
    	    exit;
    	}

    	$cids = implode( ',', $cid );
	
	if($flag==1) $published = ", published='1'";
	foreach ($cid AS $cids) {
		$database->setQuery( "UPDATE #__comprofiler_lists SET `default`='0'");
	    	$database->query();
		$database->setQuery( "UPDATE #__comprofiler_lists SET `default`='$flag' $published WHERE listid = '$cids'");
	    	$database->query();
		//print $database->getquery();
	}
    mosRedirect( "index2.php?option=$option&task=showLists" );
}

function profileField( $cid=null, $flag=1, $option ) {
    global $database, $my, $ueConfig;
    	if (count( $cid ) < 1) {
       	    $action = $flag ? 'Add to Profile' : 'Remove from Profile';
    	    echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
    	    exit;
    	}

    	$cids = implode( ',', $cid );

	foreach ($cid AS $cids) {
		$database->setQuery( "UPDATE #__comprofiler_fields SET profile='$flag' WHERE fieldid = '$cids'");
	    	$database->query();
		//print $database->getquery();
	}
    mosRedirect( "index2.php?option=$option&task=showField" );
}

function makePass(){
	$makepass="";
	$salt = "abchefghjkmnpqrstuvwxyz0123456789";
	srand((double)microtime()*1000000);
	$i = 0;
	while ($i <= 7) {
		$num = rand() % 33;
		$tmp = substr($salt, $num, 1);
		$makepass = $makepass . $tmp;
		$i++;
	}
	return ($makepass);
}
function loadSampleData() {
    global $database, $my, $ueConfig;
	$sql="SELECT COUNT(*) FROM #__comprofiler_fields"
	."\n WHERE name IN ('website','location','occupation','interests','company','address','city','state','zipcode','country','phone','fax')";
	$database->setQuery($sql);
    	$fieldCount=$database->loadresult();

	IF($fieldCount < 1) {
		$sqlStatements = array();

		$sqlStatements[0]['query'] = "INSERT IGNORE INTO `#__comprofiler_tabs` (`tabid`, `title`, `ordering`, `sys`) "
			."\n VALUES (2, 'Additional Info', 1, 0)";
		$sqlStatements[0]['message'] = "<font color=green>Tab Added Successfully!</font><br />";

		$sqlStatements[1]['query'] = "ALTER TABLE `#__comprofiler` ADD `website` varchar(255) default NULL,"
			  ."\n ADD `location` varchar(255) default NULL,"
			  ."\n ADD `occupation` varchar(255) default NULL,"
			  ."\n ADD `interests` varchar(255) default NULL,"
			  ."\n ADD `company` varchar(255) default NULL,"
			  ."\n ADD `address` varchar(255) default NULL,"
			  ."\n ADD `city` varchar(255) default NULL,"
			  ."\n ADD `state` varchar(255) default NULL,"
			  ."\n ADD `zipcode` varchar(255) default NULL,"
			  ."\n ADD `country` varchar(255) default NULL,"
			  ."\n ADD `phone` varchar(255) default NULL,"
			  ."\n ADD `fax` varchar(255) default NULL";
		$sqlStatements[1]['message'] = "<font color=green>Schema Changes Added Successfully!</font><br />";

		$sqlStatements[2]['query'] = "INSERT IGNORE INTO `#__comprofiler_fields`  (`fieldid`, `name`, `table`, `title`, `type`, `maxlength`, `size`, `required`, `tabid`, `ordering`, `cols`, `rows`, `value`, `default`, `published`, `registration`, `profile`, `calculated`, `sys`) "
			."\n VALUES (30, 'website', '#__comprofiler', '_UE_Website', 'webaddress', 0, 0, 0, 2, 1, 0, 0, NULL, NULL, 1, 0, 1, 0, 0),"
			."\n (31, 'location', '#__comprofiler', '_UE_Location', 'text', 50, 25, 0, 2, 2, 0, 0, NULL, NULL, 1, 0, 1, 0, 0),"
			."\n (32, 'occupation', '#__comprofiler', '_UE_Occupation', 'text', 0, 0, 0, 2, 3, 0, 0, NULL, NULL, 1, 0, 1, 0, 0),"
			."\n (33, 'interests', '#__comprofiler', '_UE_Interests', 'text', 0, 0, 0, 2, 4, 0, 0, NULL, NULL, 1, 0, 1, 0, 0),"
			."\n (34, 'company', '#__comprofiler', '_UE_Company', 'text', 0, 0, 0, 2, 5, 0, 0, NULL, NULL, 1, 1, 1, 0, 0),"
			."\n (35, 'city', '#__comprofiler', '_UE_City', 'text', 0, 0, 0, 2, 6, 0, 0, NULL, NULL, 1, 1, 1, 0, 0),"
			."\n (36, 'state', '#__comprofiler', '_UE_State', 'text', 2, 4, 0, 2, 7, 0, 0, NULL, NULL, 1, 1, 1, 0, 0),"
			."\n (37, 'zipcode', '#__comprofiler', '_UE_ZipCode', 'text', 0, 0, 0, 2, 8, 0, 0, NULL, NULL, 1, 1, 1, 0, 0),"
			."\n (38, 'country', '#__comprofiler', '_UE_Country', 'text', 0, 0, 0, 2, 9, 0, 0, NULL, NULL, 1, 1, 1, 0, 0),"
			."\n (40, 'address', '#__comprofiler', '_UE_Address', 'text', 0, 0, 0, 2, 10, 0, 0, NULL, NULL, 1, 1, 1, 0, 0),"
			."\n (43, 'phone', '#__comprofiler', '_UE_PHONE', 'text', 0, 0, 0, 2, 11, 0, 0, NULL, NULL, 1, 1, 1, 0, 0),"
			."\n (44, 'fax', '#__comprofiler', '_UE_FAX', 'text', 0, 0, 0, 2, 12, 0, 0, NULL, NULL, 1, 1, 1, 0, 0)";
		$sqlStatements[2]['message'] = "<font color=green>Fields Added Successfully!</font><br />";

		$sqlStatements[3]['query'] = "INSERT INTO `#__comprofiler_lists` (`listid`, `title`, `description`, `published`, `default`, `usergroupids`, `sortfields`, `col1title`, `col1enabled`, `col1fields`, `col2title`, `col2enabled`, `col1captions`, `col2fields`, `col2captions`, `col3title`, `col3enabled`, `col3fields`, `col3captions`, `col4title`, `col4enabled`, `col4fields`, `col4captions`) "
					."\n VALUES (2, 'Members List', 'my Description', 1, 1, '29, 18, 19, 20, 21, 30, 23, 24, 25', '`username` ASC', 'Image', 1, '29', 'Name', 1, 0, '41', 0, 'Other', 1, '26|*|28|*|27', 1, '', 0, '', 0)";

		$sqlStatements[3]['message'] = "<font color=green>List Added Successfully!</font><br />"; 	
	
		foreach ($sqlStatements AS $sql) {
			$database->setQuery($sql['query']);
			if (!$database->query()) {
				print("<font color=red>SQL error" . $database->stderr(true)."</font><br />");
				return;
			} else {
				print $sql['message'];
			}
			//print $database->getquery();
		}
	} else {
		print "Sample Data is already loaded!";
	}
 }
function syncUsers() {
    global $database, $my, $ueConfig;
	$sql="INSERT IGNORE INTO #__comprofiler(id,user_id) SELECT id,id FROM #__users";
	$database->setQuery($sql);
	if (!$database->query()) {
		print("<font color=red>SQL error" . $database->stderr(true)."</font><br />");
	} else {
		print "<font color=green>Mambo User Table and Mambo Community Builder User Table now in sync!</font>";
	}
 }
function loadTools() {
	HTML_comprofiler::showTools();
}

?>
