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


defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

$access = new stdClass();
$access->canEdit = $acl->acl_check( 'action', 'edit', 'users', $my->usertype, 'content', 'all' );
$access->canEditOwn = $acl->acl_check( 'action', 'edit', 'users', $my->usertype, 'content', 'own' );

require_once ( $mainframe->getPath( 'front_html' ) );
	include_once( "administrator/components/com_comprofiler/ue_config.php" );
	include_once ("administrator/components/com_comprofiler/comprofiler.class.php");
$mosConfig_lang=$mainframe->getCfg( 'lang' );
$UEAdminPath=$mainframe->getCfg( 'absolute_path' ).'/administrator/components/com_comprofiler';


if (file_exists($UEAdminPath.'/language/'.$mosConfig_lang.'.php')) {
  include_once($UEAdminPath.'/language/'.$mosConfig_lang.'.php');
} else {
  include_once($UEAdminPath.'/language/english.php');
}

//print $ueConfig['allow_profileviewbyGID'];

$form=mosGetParam( $_REQUEST, 'reportform', 1 );
$uid=mosGetParam( $_REQUEST, 'uid', 0 );
$act=mosGetParam( $_REQUEST, 'act', 1 );

switch( $task ) {

	case "userDetails":
	userEdit( $option, $my->id, _UE_UPDATE );
	break;

	case "saveUserEdit":
	userSave( $option, $my->id );
	break;
	
	case "userProfile":
	userProfile($option, $my->id, _UE_UPDATE);
	break;

	case "usersList":
	usersList($option, $my->id, _UE_UPDATE, $listCuerdas);
	break;

	case "userAvatar":
	userAvatar($option, $my->id, _UE_UPDATE);
	break;

	case "lostPassword":
	lostPassForm( $option );
	break;

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

	case "registers":
	registerForm( $option, $mosConfig_emailpass );
	break;

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

	case "login":
	login();
	break;

	case "confirm":
	confirm($confirmCode);
	break;

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

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

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

	case "approveImage":
	approveImage();
	break;

	case "reportUser":
	reportUser($option,$form,$uid);
	break;

	case "processReports":
	processReports();
	break;

	case "banProfile":
	banUser($option,$uid,$form,$act);
	break;

	case "viewReports":
	viewReports($option,$uid);
	break;

	case "emailUser":
	emailUser($option,$uid);
	break;

	case "pendingApprovalUser":
	pendingApprovalUsers($option);
	break;

	case "approveUser":
	approveUser($option,$uids);
	break;

	case "rejectUser":
	rejectUser($option,$uids);
	break;

	case "sendUserEmail":
	sendUserEmail($_POST['toID'],$_POST['fromID'],$_POST['emailSubject'],$_POST['emailBody']);
	break;

	default:
	userProfile($option, $my->id, _UE_UPDATE);
	break;
}

function sendUserEmail($toid,$fromid,$subject,$message) {
global $database,$ueConfig,$my,$_SERVER,$mosConfig_live_site,$mosConfig_sitename;

$rowFrom = new mosUser( $database );
$rowFrom->load( $fromid );

$rowTo = new mosUser( $database );
$rowTo->load( $toid );
$uname=getNameFormat($rowFrom->name,$rowFrom->username,$ueConfig['name_format']);	
$to=$rowTo->email;
$from= $uname. " @ ".$mosConfig_sitename." <" . $rowFrom->email . ">";
$subject=$subject;
$premessage=sprintf(_UE_SENDEMAILNOTICE,$uname,$mosConfig_sitename,$mosConfig_live_site,$mosConfig_sitename);
$message=$premessage."\r\n\r\n".stripslashes($message);
$header  = "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$header .= "Organization: ".$mosConfig_sitename."\r\n";
$header .= "Content-Transfer-encoding: 8bit\r\n";
$header .= "From: ".$from."\r\n";
$header .= "Reply-To: ".$from."\r\n";
$header .= "Message-ID: <".md5(uniqid(time()))."@{$_SERVER['SERVER_NAME']}>\r\n";
$header .= "Return-Path: ".$from."\r\n";            
$header .= "X-Priority: 3\r\n"; 
$header .= "X-MSmail-Priority: Low\r\n"; 
$header .= "X-Mailer: PHP\r\n"; //hotmail and others dont like PHP mailer. --Microsoft Office Outlook, Build 11.0.5510
$header .= "X-Sender: ".$from."\r\n";



if(mail ($to,$subject,$message,$header)) echo _UE_SENTEMAILSUCCESS;
else echo _UE_SENTEMAILFAILED;

}

function emailUser($option,$uid) {
	global $database,$ueConfig,$my;
	if ($my->id == 0) {
		mosNotAuth();
		return;
	}
	$rowFrom = new mosUser( $database );
	$rowFrom->load( $my->id );
	
	$rowTo = new mosUser( $database );
	$rowTo->load( $uid );	
	HTML_comprofiler::emailUser($option,$rowFrom,$rowTo);
}

function userEdit( $option, $uid, $submitvalue) {
	global $database,$ueConfig;
	if ($uid == 0) {
		mosNotAuth();
		return;
	}
	$row = new mosUser( $database );

	// Rodax Software
	//$row->load( $uid );
	if(!$_REQUEST['user']) 	{
		$row->load( $uid );
	} else {
		$row->load( $_REQUEST['user'] );
	}
		
	$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',t.description as 'tabdesc', 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();
			$fieldJS .= "\ncoll.".$rowFields[$i]->name.".setAttribute('mosReq',".$rowFields[$i]->required."); \ncoll.".$rowFields[$i]->name.".setAttribute('mosLabel','".getLangDefinition($rowFields[$i]->title)."');\n";

		}
		$database->setQuery( "SELECT fieldtitle FROM #__comprofiler_field_values"
		. "\n WHERE fieldid = ".$rowFields[$i]->fieldid
		. "\n ORDER BY ordering" );
		$Values = $database->loadObjectList();
		if($rowFields[$i]->readonly == 1) $oreadonly = " DISABLED ";
		else $oreadonly = " ";
		if(count($Values) > 0) {
			if($rowFields[$i]->type=='radio') $rowFieldValues['lst_'.$rowFields[$i]->name] = moscomprofilerHTML::radioList( $Values, $rowFields[$i]->name, 'class="inputbox" size="1" '.$oreadonly.' mosReq="'.$rowFields[$i]->required.'" mosLabel="'.getLangDefinition($rowFields[$i]->title).'"', 'fieldtitle', 'fieldtitle', stripslashes($k));
			else $rowFieldValues['lst_'.$rowFields[$i]->name] = moscomprofilerHTML::selectList( $Values, $rowFields[$i]->name, 'class="inputbox" size="1" '.$oreadonly.' mosReq="'.$rowFields[$i]->required.'" mosLabel="'.getLangDefinition($rowFields[$i]->title).'"', 'fieldtitle', 'fieldtitle', stripslashes($k));
		}
	}


	HTML_comprofiler::userEdit( $row, $rowExtras, $rowFields, $rowFieldValues, $option, $submitvalue,$fieldJS);
}

function userAvatar( $option, $uid, $submitvalue) {
	global $database;
	if ($uid == 0) {
		mosNotAuth();
		return;
	}
	$row = new mosUser( $database );

	// Rodax Software
	//	$row->load( $uid );
	if(!$_REQUEST['user']) 	{
		$row->load( $uid );
	} else {
		$row->load( $_REQUEST['user'] );
	}

	$row->orig_password = $row->password;
	HTML_comprofiler::userAvatar( $row, $option, $submitvalue);
}

function userProfile( $option, $uid, $submitvalue) {
	global $database, $_REQUEST, $ueConfig,$acl,$my;
	if (!allowAccess( $ueConfig['allow_profileviewbyGID'],'RECURSE', userGID($my->id), $acl)) {
		echo _UE_NOT_AUTHORIZED;
		return;
	}
	if (!$_REQUEST['user'] && $uid==0) {
		echo _UE_REGISTERFORPROFILE;
		return;
	}
	$row = new mosUser( $database );
	if(!$_REQUEST['user']) 	{
		$database->setQuery( "SELECT * FROM #__comprofiler c, #__users u WHERE c.id=u.id AND c.id='".$uid."'");
	} else {
		$database->setQuery( "SELECT * FROM #__comprofiler c, #__users u WHERE c.id=u.id AND c.id='".$_REQUEST['user']."'");
	}
	$users = $database->loadObjectList();
	$user = $users[0];
	IF ($ueConfig['allow_email_display']==0) $whereAdd = " AND f.type != 'emailaddress' "; 
	$database->setQuery( "SELECT f.*, t.title as tab, t.width FROM #__comprofiler_fields f, #__comprofiler_tabs t"
	. "\n WHERE f.published=1 AND f.profile=1 AND f.tabid = t.tabid AND t.enabled=1"
	. $whereAdd
	. "\n ORDER BY t.ordering, f.ordering" );
	$rowFields = $database->loadObjectList();
	
	$i=1;
	$t=1;
	$tabs=0;
	$sqlFormat = "Y-m-d";
	$colCount=0;
	$tabevenodd = $tabcount % 2;
	$tablist = array();
	$poldtab=$rowFields[0]->tab;
	$tabwidth=$rowFields[0]->width;
for($i=0, $n=count( $rowFields ); $i < $n; $i++) {

	if($poldtab <> $rowFields[$i]->tab)  {
		if($tabfields != '') {
			$tablist[$tabs][name]=$poldtab;
			$tablist[$tabs][content]=$tabfields;
			$tablist[$tabs][width]=$tabwidth;
			$tabs++;

			$tabfields='';
		}
	}

	$poldtab=$rowFields[$i]->tab;
	$tabwidth=$rowFields[$i]->width;
	$fValue='$user->'.$rowFields[$i]->name;
	eval("\$fValue = \"".$fValue."\";");
	$oValue = getFieldValue($rowFields[$i]->type,stripslashes($fValue),$user);
	if($oValue!=null || trim($oValue)!='') {
		$evenodd = $t % 2;
		if ($evenodd == 0) {
			$class = "sectiontableentry1";
		} else {
			$class = "sectiontableentry2";
		}
		$t++;
		$tabfields .= "\n\t\t\t\t<tr>";
		$tabfields .= "\n\t\t\t\t\t<td class=".$class." width=40% style=\"font-weight:bold;\">". getLangDefinition($rowFields[$i]->title) .":</td>"; 

		$tabfields .= "\n\t\t\t\t\t<td class=".$class.">".$oValue."</td>";
		$tabfields .= "\n\t\t\t\t</tr>";
	}
	if($i==$n-1) {
		if($tabfields != '') {
			$tablist[$tabs][name]=$poldtab;
			$tablist[$tabs][content]=$tabfields;
			$tablist[$tabs][width]=$tabwidth;
			$tabs++;

			$tabfields='';
		}
	}

}

	HTML_comprofiler::userProfile( $user, $tablist, $option, $submitvalue);
}

function usersList( $option, $uid, $submitvalue, $listCuerdas) {
	global $database,$my,$ueConfig,$acl,$_POST,$_REQUEST;
	if (!allowAccess( $ueConfig['allow_listviewbyGID'],'RECURSE', userGID($my->id), $acl)) {
		echo _UE_NOT_AUTHORIZED;
		return;
	}
	$database->setQuery("SELECT listid, title FROM #__comprofiler_lists WHERE published=1 ORDER BY ordering");
	$plists = $database->loadObjectList();
	$lists = array();
	$publishedlists = array();

	for ($i=0, $n=count( $plists ); $i < $n; $i++) {
		$plist =& $plists[$i];
	   	$publishedlists[] = mosHTML::makeOption( $plist->listid, getLangDefinition($plist->title) );
	}

	if(!isset($_POST['listid']) && !isset($_REQUEST['listid'])) {
		$database->setQuery( "SELECT listid FROM #__comprofiler_lists "
		. "\n WHERE `default`=1 AND published=1" );
		$listid = $database->loadresult();
	} else {
		if(isset($_POST['listid'])) $listid = $_POST['listid'];
		else $listid = $_REQUEST['listid'];
	}
	if(!$listid > 0) {
		echo _UE_NOLISTFOUND;
		return;
	}

//	$lists['plists'] = mosHTML::selectList( $publishedlists, 'listid', 'class="inputbox" size="1" onchange="document.ueform.submit();"', 'value', 'text', $listid );
	$lists['plists'] = moscomprofilerHTML::selectlistcuerdas('listCuerdas', $listCuerdas);
//	$lists['plists'] = $html;
	
	$database->setQuery( "SELECT l.* FROM #__comprofiler_lists l"
	. "\n WHERE l.listid='$listid' AND l.published=1" );
	$row = $database->loadObjectList();
	$col=$row[0]->col1fields;
	$col=explode('|*|',$col);	

	for ($i=0, $n=count( $col ); $i < $n; $i++) {
		if($i==0) $lfields .= "<td valign=top>\n";
		else $lfields .= "<br/>\n";			
		if($col[$i]!='' && $col[$i]!=null) {
			$database->setQuery( "SELECT f.name, f.title, f.type "
				. "\nFROM #__comprofiler_fields AS f"
				. "\nWHERE f.published = 1 AND f.fieldid=".$col[$i]);
			$cfield = $database->loadObjectList();
			$cfield = $cfield[0];
			if($row[0]->col1captions==1)  $oTitle =  getLangDefinition($cfield->title).": ";
			else $oTitle='';
			$lfields .=  " \".getFieldValue('".$cfield->type."',\$user->".$cfield->name.",\$user,'".$oTitle."').\"";
		}
	}
	$lfields .= "</td>\n";	

	if($row[0]->col2enabled) {
		$col=$row[0]->col2fields;
		$col=explode('|*|',$col);	
		for ($i=0, $n=count( $col ); $i < $n; $i++) {
		    if($i==0) $lfields .= "<td valign=top>\n";
			else $lfields .= "<br/>\n";
			if($col[$i]!='' && $col[$i]!=null) {
				$database->setQuery( "SELECT f.name, f.title, f.type "
					. "\nFROM #__comprofiler_fields AS f"
					. "\nWHERE f.published = 1 AND f.fieldid=".$col[$i]);
				$cfield = $database->loadObjectList();
				$cfield = $cfield[0];
				if($row[0]->col2captions==1) $oTitle =  getLangDefinition($cfield->title).": ";
				else $oTitle='';
				$lfields .=  " \".getFieldValue('".$cfield->type."',\$user->".$cfield->name.",\$user,'".$oTitle."').\"";
			}	
		}
		$lfields .= "</td>\n";
	}

	if($row[0]->col3enabled) {
		$col=$row[0]->col3fields;
		$col=explode('|*|',$col);	
		for ($i=0, $n=count( $col ); $i < $n; $i++) {
			if($i==0) $lfields .= "<td valign=top>\n";
			else $lfields .= "<br/>\n";
			$database->setQuery( "SELECT f.name, f.title, f.type "
				. "\nFROM #__comprofiler_fields AS f"
				. "\nWHERE f.published = 1 AND f.fieldid=".$col[$i]);
			$cfield = $database->loadObjectList();
			$cfield = $cfield[0];
			if($row[0]->col3captions==1)  $oTitle =  getLangDefinition($cfield->title).": ";
			else $oTitle='';
			$lfields .=  " \".getFieldValue('".$cfield->type."',\$user->".$cfield->name.",\$user,'".$oTitle."').\"";
		}
		$lfields .= "</td>\n";
	}

	if($row[0]->col4enabled) {
		$col=$row[0]->col4fields;
		$col=explode('|*|',$col);	
		for ($i=0, $n=count( $col ); $i < $n; $i++) {
			if($i==0) $lfields .= "<td valign=top>\n";
			else $lfields .= "<br/>\n";
			if($col[$i]!='' && $col[$i]!=null) {
				$database->setQuery( "SELECT f.name, f.title, f.type "
					. "\nFROM #__comprofiler_fields AS f"
					. "\nWHERE f.published = 1 AND f.fieldid=".$col[$i]);
				$cfield = $database->loadObjectList();
				$cfield = $cfield[0];
				if($row[0]->col4captions==1)  $oTitle =  getLangDefinition($cfield->title).": ";
				else $oTitle='';
				$lfields .=  " \".getFieldValue('".$cfield->type."',\$user->".$cfield->name.",\$user,'".$oTitle."').\"";
			}		

		}
		$lfields .= "</td>\n";
	}	
	$row=$row[0];
	HTML_comprofiler::usersList($row,$lfields,$lists,$listid,$listCuerdas);
}

function userSave( $option, $uid) {
	global $database,$ueConfig,$_REQUEST,$_POST;

	$user_id = intval( mosGetParam( $_POST, 'id', 0 ));

	// Rodax Software
	$isModerator = isModerator($uid);
	
	// do some security checks
	if ($uid == 0 || $user_id == 0 || (($user_id <> $uid) && (!isModerator))) {
		mosNotAuth();
		return;
	}
	$row = new mosUser( $database );
	$row->load( $user_id );
	$row->orig_password = $row->password;


	if (!$row->bind( $_POST )) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}

	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(isset($_POST["password"]) && $_POST["password"] != "") {
		if(isset($_POST["verifyPass"]) && ($_POST["verifyPass"] == $_POST["password"])) {
			$row->password = md5($_POST["password"]);
		} else {
			echo "<script> alert(\""._PASS_MATCH."\"); window.history.go(-1); </script>\n";
			exit();
		}
	} else {
		// Restore 'original password'
		$row->password = $row->orig_password;
	}
	if (!$row->check()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}

	unset($row->orig_password); // prevent DB error!!

	if (!$row->store()) {
		echo "<script> alert('store:".$row->getError()."'); window.history.go(-1); </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();	
	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)."' ";
		break;
		CASE 'webaddress':
		CASE 'emailaddress': 
			$selFields .= "`".$rowFields[$i]->name."`='".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])."' ";
		break;
		DEFAULT:
			$selFields .= "`".$rowFields[$i]->name."`='".htmlspecialchars(addslashes($_POST[$rowFields[$i]->name]))."' ";
		break;
		}
	}
	if($selFields !='') $selFields .=", ";
	$selFields .= " `lastupdatedate`='".date('Y-m-d\TH:i:s')."', `firstname`='".$_POST['firstname']."', `middlename`='".$_POST['middlename']."', `lastname`='".$_POST['lastname']."'";
	$sql = "UPDATE #__comprofiler SET ".stripslashes($selFields)." WHERE id='$user_id'";
	$database->setQuery( $sql );
	if (!$database->query()) {
		die("SQL error" . $database->stderr(true));
	}

	$database->setQuery("SELECT id FROM #__menu WHERE link = 'index.php?option=com_comprofiler'");
	$Itemid = $database->loadResult();
	mosRedirect ("index.php?option=com_comprofiler&Itemid=".$Itemid."&task=userDetails&user=".$user_id, _USER_DETAILS_SAVE);
	//mosRedirect ("index.php?option=$option&Itemid=".$Itemid, _USER_DETAILS_SAVE);
}
	function mosGetConfig() {
	   $configfile = "administrator/components/com_comprofiler/ue_config.php";
		include_once( $configfile );
		RETURN $ueConfig;
	}

function lostPassForm( $option ) {
	HTML_comprofiler::lostPassForm($option);
}

function sendNewPass( $option ) {
	global $database, $Itemid;
	global $mosConfig_live_site, $mosConfig_sitename,$ueConfig;

	$_live_site = $mosConfig_live_site;
	$_sitename = $mosConfig_sitename;

	// ensure no malicous sql gets past
	$checkusername = trim( mosGetParam( $_POST, 'checkusername', '') );
	$checkusername = $database->getEscaped( $checkusername );
	$confirmEmail = trim( mosGetParam( $_POST, 'confirmEmail', '') );
	$confirmEmail = $database->getEscaped( $confirmEmail );

	$database->setQuery( "SELECT id FROM #__users"
	. "\nWHERE username='$checkusername' AND email='$confirmEmail'"
	);

	if (!($user_id = $database->loadResult()) || !$checkusername || !$confirmEmail) {
		mosRedirect( "index.php?option=$option&task=lostPassword&mosmsg="._ERROR_PASS );
	}

	$newpass = makePass();
	$message = _NEWPASS_MSG;
	eval ("\$message = \"$message\";");
	$subject = _NEWPASS_SUB;
	eval ("\$subject = \"$subject\";");
	$headers = "";
	$headers .= "From: ".$ueConfig['reg_email_name']." <".$ueConfig['reg_email_from'].">\r\n";
	$headers .= "Reply-To: <".$ueConfig['reg_email_replyto'].">\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( $confirmEmail, $subject, $message, $headers );

	$newpass = md5( $newpass );
	$sql = "UPDATE #__users SET password='$newpass' WHERE id='$user_id'";
	$database->setQuery( $sql );
	if (!$database->query()) {
		die("SQL error" . $database->stderr(true));
	}

	mosRedirect( "index.php?Itemid=$Itemid&mosmsg="._NEWPASS_SENT );
}

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 registerForm( $option, $emailpass ) {
	global $mosConfig_allowUserRegistration, $database, $my, $acl;

	$database->setQuery( "SELECT f.* FROM #__comprofiler_fields f, #__comprofiler_tabs t"
	. "\n WHERE t.tabid = f.tabid AND f.published=1 AND f.registration=1 AND t.enabled=1"
	. "\n ORDER BY t.ordering, f.ordering" );
	$rowFields = $database->loadObjectList();
	$rowFieldValues=array();
	for($i=0, $n=count( $rowFields ); $i < $n; $i++) {
		
		$k = "\$rowExtras->".$rowFields[$i]->name;
		eval("\$k = \"$k\";");
		$database->setQuery( "SELECT fieldtitle FROM #__comprofiler_field_values"
		. "\n WHERE fieldid = ".$rowFields[$i]->fieldid
		. "\n ORDER BY ordering" );
		$Values = $database->loadObjectList();
		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="'.$rowFields[$i]->required.'" 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="'.$rowFields[$i]->required.'" mosLabel="'.getLangDefinition($rowFields[$i]->title).'"', 'fieldtitle', 'fieldtitle', $k);
		}
	}


	HTML_comprofiler::registerForm($option, $emailpass, $rowFields, $rowFieldValues);
}

function saveRegistration( $option ) {
	global $database, $my, $acl,$ueConfig,$_POST;
	global $mosConfig_live_site, $mosConfig_emailpass, $mosConfig_allowUserRegistration,$uDetails;

	if ($mosConfig_allowUserRegistration=="0") {
		mosNotAuth();
		return;
	}

	$database->setQuery("SELECT id FROM #__users WHERE email = '".$_POST['email']."' AND username='0'");
	$uid = $database->loadResult();

	if($uid >0 ) $_POST['id'] = $uid;

	$row = new mosUser( $database );
	
	if (!$row->bind( $_POST )) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}

	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);
	$pwd = '';
	$row->gid = $acl->get_group_id('Registered','ARO');

	if (!$row->password) {
		$pwd = makePass();
		$row->password = md5( $pwd );
		$includePWD=1;
	} else {
		$pwd = $row->password;
		$row->password = md5( $row->password );
		$includePWD=0;
	}

	$row->registerDate = date("Y-m-d\TH:i:s");

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

	if (!$row->store()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </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 f.registration=1 and t.enabled=1" );
	$rowFields = $database->loadObjectList();

	$database->setQuery("SELECT id FROM #__users WHERE username = '".$_POST['username']."'");
	$uid = $database->loadResult();
	$sqlType = 'I';

	if ($ueConfig['reg_admin_approval']=="0") {
		$approved="1";
	} else {
		$approved="0";
	} 
	if ($ueConfig['reg_confirmation']=="0") {
		$confirmed="1";
	} else {
		$confirmed="0";
	} 
	$acceptedterms=$_POST['acceptedterms'];

	$colList = "id, user_id, approved, confirmed, acceptedterms, firstname, lastname";
	$valueList = "'$uid','$uid','$approved','$confirmed','$acceptedterms','".$_POST['firstname']."','".$_POST['lastname']."'";
	for($i=0, $n=count( $rowFields ); $i < $n; $i++) {
	if($i > 0) $selFields .=", ";

			switch($rowFields[$i]->type) {
			CASE 'date': 
				$colList .= ", ".$rowFields[$i]->name;
				$valueList .= ", '".dateConverter($_POST[$rowFields[$i]->name],$ueConfig[date_format],$sqlFormat)."'";
			break;
			CASE 'webaddress':
			CASE 'emailaddress': 
				$colList .= ", ".$rowFields[$i]->name;
				$valueList .= ", '".addslashes(str_replace(array('mailto:','http://','https://'),'',strtolower($_POST[$rowFields[$i]->name])))."'";
			break;
			DEFAULT:
				$colList .= ", ".$rowFields[$i]->name;
				$valueList .= ", '".addslashes($_POST[$rowFields[$i]->name])."'";
			break;
			}
	}
	$sql = "INSERT INTO #__comprofiler (".stripslashes($colList).") VALUES (".stripslashes($valueList).")";
	$database->setQuery( $sql );
	if (!$database->query()) {
		die("SQL error" . $database->stderr(true));
	}
	$row->checkin();
	if($mosConfig_emailpass == "1") $row->password =$pwd ;
	else $mosConfig_emailpass=0;

	if($confirmed==0) { 
		createEmail($row,'pending',$ueConfig,null,$includePWD);
		$emailType=null;
 	} elseif($approved==0 && $confirmed==1) { 
		createEmail($row,'pending',$ueConfig);
		$emailType='pendingAdmin';
 	} else { 
		createEmail($row,'welcome',$ueConfig);
		$emailType='welcomeAdmin';
	}
	if($emailType!=null) {
		if($ueConfig['moderatorEmail']==1) {
			$database->setQuery( "SELECT name, username, email FROM #__users"
			."\n WHERE gid >='".$ueConfig['imageApproverGid']."'" );
			$rowAdmins = $database->loadObjectList();
			foreach ($rowAdmins AS $rowAdmin) {
				createEmail($row,$emailType,$ueConfig,$rowAdmin);
			}
		}
	}

	if ($mosConfig_emailpass == "1" && $ueConfig['reg_admin_approval']=="1" && $ueConfig['reg_confirmation']=="0"){
		echo _UE_REG_COMPLETE_NOPASS_NOAPPR;
	} elseif ($mosConfig_emailpass == "1" && $ueConfig['reg_admin_approval']=="1" && $ueConfig['reg_confirmation']=="1") {
		echo _UE_REG_COMPLETE_NOPASS_NOAPPR_CONF;
	} elseif ($mosConfig_emailpass == "1" && $ueConfig['reg_admin_approval']=="0" && $ueConfig['reg_confirmation']=="0") {
		echo _UE_REG_COMPLETE_NOPASS;
	} elseif ($mosConfig_emailpass == "1" && $ueConfig['reg_admin_approval']=="0" && $ueConfig['reg_confirmation']=="1") {
		echo _UE_REG_COMPLETE_NOPASS_CONF;
	} elseif ($mosConfig_emailpass == "0" && $ueConfig['reg_admin_approval']=="1" && $ueConfig['reg_confirmation']=="0") {
		echo _UE_REG_COMPLETE_NOAPPR;
	} elseif ($mosConfig_emailpass == "0" && $ueConfig['reg_admin_approval']=="1" && $ueConfig['reg_confirmation']=="1") {
		echo _UE_REG_COMPLETE_NOAPPR_CONF;
	} elseif ($mosConfig_emailpass == "0" && $ueConfig['reg_admin_approval']=="0" && $ueConfig['reg_confirmation']=="1") {
		echo _UE_REG_COMPLETE_CONF;
	} else {
		echo _UE_REG_COMPLETE;
	}

}


function login( $username=null,$passwd=null ) {
        global $acl,$database,$_COOKIE,$_POST,$mainframe;

        $usercookie = mosGetParam( $_COOKIE, 'usercookie', '' );
        $sessioncookie = mosGetParam( $_COOKIE, 'sessioncookie', '' );
        if (!$username || !$passwd) {
                $return = trim( mosGetParam( $_POST, 'return', '' ) );
                $username = trim( mosGetParam( $_POST, 'username', '' ) );
                $passwd2 = trim( mosGetParam( $_POST, 'passwd', '' ) );
                $passwd = md5( $passwd2 );
        }
        $remember = trim( mosGetParam( $_POST, 'remember', '' ) );

		if (!$username || !$passwd) {
			echo "<script> alert(\""._LOGIN_INCOMPLETE."\"); window.history.go(-1); </script>\n";
			exit();
		} else {
			$database->setQuery( "SELECT u.id, u.gid, u.block, u.usertype, ue.approved, ue.confirmed"
			. "\nFROM #__users u, "
			. "\n#__comprofiler ue"
			. "\nWHERE u.username='$username' AND u.password='$passwd' AND u.id = ue.id"
			);
			$row = null;
			if ($database->loadObject( $row )) {
				if ($row->block == 1) {
					echo "<script>alert(\""._LOGIN_BLOCKED."\"); window.history.go(-1); </script>\n";
					exit();
				}
		                else if ($row->approved == 2){
		                    echo "<script>alert(\""._LOGIN_REJECTED."\"); window.history.go(-1); </script>\n";
		                    exit();
		                }
		                else if ($row->approved == 0){
		                    echo "<script>alert(\""._LOGIN_NOT_APPROVED."\"); window.history.go(-1); </script>\n";
		                    exit();
		                }
		                else if ($row->confirmed != 1){
		                    echo "<script>alert(\""._LOGIN_NOT_CONFIRMED."\"); window.history.go(-1); </script>\n";
		                    exit();
		                }
			} else {
				echo "<script>alert(\""._LOGIN_INCORRECT."\"); window.history.go(-1); </script>\n";
				exit();
			}
	echo "<div style='visibility:hidden;'><form action=".sefRelToAbs("index.php?option=login")." method=post name=login2 id=login2>\n";
		echo "<input type=hidden name=username value='$username' />\n";
		echo "<input type=hidden name=passwd value='$passwd2' />\n";
		echo "<input type=hidden name=op2 value='login' />\n";
		echo "<input type=hidden name=lang value='$mosConfig_lang' />\n";
		echo "<input type=hidden name=return value='$return' />\n";
		echo "<input type=hidden name=remember value='$remember' />\n";
		echo "<input type=submit name=btnsubmit />\n";
	echo "</form></div>\n";

	echo "<script> document.login2.submit(); </script>\n";

        }
}
function confirm($confirmCode){
  global $database,$my,$ueConfig;
	if($my->id < 1) {

		$query = "SELECT * FROM #__comprofiler c JOIN #__users u ON c.id=u.id WHERE md5(c.id) = '" . $confirmCode . "'";
		$database->setQuery($query);
		$user = $database->loadObjectList();

		$query = "UPDATE #__comprofiler SET confirmed = 1 WHERE md5(id) = '" . $confirmCode . "'";
		$database->setQuery($query);
		$database->query();
		
		if(mysql_affected_rows() == 0){
			echo _UE_USER_NOTCONFIRMED;
		}
		elseif($user[0]->approved == 0) {
			if($ueConfig['moderatorEmail']==1) {
				$database->setQuery( "SELECT name, username, email FROM #__users"
				."\n WHERE gid >='".$ueConfig['imageApproverGid']."'" );
				$rowAdmins = $database->loadObjectList();
				foreach ($rowAdmins AS $rowAdmin) {
					createEmail($user[0],'pendingAdmin',$ueConfig,$rowAdmin);
				}
			}
			echo _UE_USER_CONFIRMED_NEEDAPPR . "<br>";

		} else {
			if($ueConfig['moderatorEmail']==1) {
				$database->setQuery( "SELECT name, username, email FROM #__users"
				."\n WHERE gid >='".$ueConfig['imageApproverGid']."'" );
				$rowAdmins = $database->loadObjectList();
				foreach ($rowAdmins AS $rowAdmin) {
					createEmail($user[0],'welcomeAdmin',$ueConfig,$rowAdmin);
				}
			}
		  	echo _UE_USER_CONFIRMED . "<br>";
		}  
	

	} else {
		$database->setQuery("SELECT id FROM #__menu WHERE link = 'index.php?option=com_comprofiler'");
		$Itemid = $database->loadResult();
		mosRedirect(sefRelToAbs('index.php?option=com_comprofiler&Itemid'.$Itemid));
	}

}


function approveImage(){
  global $database,$_POST,$_REQUEST,$mosConfig_absolute_path,$my,$ueConfig;
	$isModerator=isModerator($my->id);
	if ($isModerator == 0) {
		mosNotAuth();
		return;
	}
	$avatars=array();
	if(isset($_POST['avatar'])) $avatars=$_POST['avatar'];
	else $avatars[] = $_REQUEST['avatars'];
	if(isset($_POST['act'])) $act=$_POST['act'];
	else $act = $_REQUEST['flag'];
	if($act=='1') {
		foreach ($avatars AS $avatar) {
			$query = "UPDATE #__comprofiler SET avatarapproved = 1, lastupdatedate='".date('Y-m-d\TH:i:s')."' WHERE id = '" . $avatar . "'";
			$database->setQuery($query);
			$database->query();
			echo $database->getquery();
			$database->setQuery( "SELECT name, email FROM #__users"
			."\n WHERE id='$avatar'" );
			$rows = $database->loadObjectList();
			echo $database->getquery();
			foreach ($rows AS $row) {
				createEmail($row,'imageApproved',$ueConfig);
			}
		}
	} else {
		foreach ($avatars AS $avatar) {
			$query = "SELECT avatar FROM #__comprofiler WHERE id = '" . $avatar . "'";
			$database->setQuery($query);
			$file = $database->loadResult();
		   	if(eregi("gallery/",$file)==false && is_file($mosConfig_absolute_path."/images/comprofiler/".$file)) {
				unlink($mosConfig_absolute_path."/images/comprofiler/".$file);
				if(is_file($mosConfig_absolute_path."/images/comprofiler/tn".$file)) unlink($mosConfig_absolute_path."/images/comprofiler/tn".$file);
			}
			$query = "UPDATE #__comprofiler SET avatarapproved = 1, avatar=null WHERE id = '" . $avatar . "'";
			$database->setQuery($query);
			$database->query();
			$database->setQuery( "SELECT name, email FROM #__users"
			."\n WHERE id='$avatar'" );
			$rows = $database->loadObjectList();
			foreach ($rows AS $row) {
				createEmail($row,'imageRejected',$ueConfig);
			}
		}

	}
	mosRedirect(sefRelToAbs('index.php?option=com_comprofiler&task=moderateImages'));
}

function isModerator($oID){
  	global $ueConfig;
	$gid = userGID($oID);
	if($gid >= $ueConfig['imageApproverGid']) return 1;
	else return 0;
}

function userGID($oID){
  	global $database,$ueConfig;
	if($oID > 0) {
	$query = "SELECT gid FROM #__users WHERE id = '".$oID."'";
	$database->setQuery($query);
	$gid = $database->loadResult();
	return $gid;
	}
	else return 0;
}

function reportUser($option,$form=1,$uid=0) {
	  global $database,$ueConfig,$_POST;
	if($ueConfig['allowUserReports']==0) {
			echo _UE_FUNCTIONALITY_DISABLED;
			exit();
	}
	if($form==1) {
		HTML_comprofiler::reportUserForm($option,$uid);
	} else {
		$row = new moscomprofilerUserReport( $database );
		
		if (!$row->bind( $_POST )) {
			echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
			exit();
		}
	
		mosMakeHtmlSafe($row);
	
		$row->reportedondate = date("Y-m-d\TH:i:s");
	
		if (!$row->check()) {
			echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
			exit();
		}
	
		if (!$row->store()) {
			echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
			exit();
		}
		if($ueConfig['moderatorEmail']==1) {
			$database->setQuery( "SELECT name, email FROM #__users"
			."\n WHERE gid >='".$ueConfig['imageApproverGid']."'" );
			$rowAdmins = $database->loadObjectList();
			foreach ($rowAdmins AS $rowAdmin) {
				createEmail($row,'reportAdmin',$ueConfig,$rowAdmin);
			}
		}
		echo _UE_USERREPORT_SUCCESSFUL;
	}
}

function banUser($option,$uid,$form=1,$act=1) {
	  global $database,$ueConfig,$_POST,$my;
	$isModerator=isModerator($my->id);
	if($ueConfig['allowUserBanning']==0) {
			echo _UE_FUNCTIONALITY_DISABLED;
			exit();
	}
	if($form==1) {
		$database->setquery("SELECT bannedreason FROM #__comprofiler WHERE id = '$uid'");
		$orgbannedreason=$database->loadresult();
		HTML_comprofiler::banUserForm($option,$uid,$act,$orgbannedreason);
	} else {
		if($act==1) {
			if ($isModerator!=1){
				mosNotAuth();
				return;
			}
			$sql="UPDATE #__comprofiler SET banned='1', bannedby='".$_POST['bannedby']."', banneddate='".date('Y-m-d\TH:i:s')."', bannedreason='<b>".htmlspecialchars("["._UE_MODERATORBANRESPONSE."]")."</b>\n".$_POST['bannedreason']."' WHERE id='$uid'";
			$database->SetQuery($sql);
			$database->query();
			$database->setQuery( "SELECT name, email FROM #__users"
			."\n WHERE id='$uid'" );
			$rows = $database->loadObjectList();
			foreach ($rows AS $row) {
				createEmail($row,'banUser',$ueConfig);
			}
			echo _UE_USERBAN_SUCCESSFUL;
		} elseif($act==0) {
			if ($isModerator!=1){
				mosNotAuth();
				return;
			}
			$sql="UPDATE #__comprofiler SET banned='0', bannedby=null, banneddate=null, bannedreason=null WHERE id='$uid'";
			$database->SetQuery($sql);
			$database->query();

			$database->setQuery( "SELECT name, email FROM #__users"
			."\n WHERE id='$uid'" );
			$rows = $database->loadObjectList();
			foreach ($rows AS $row) {
				createEmail($row,'unbanUser',$ueConfig);
			}

			echo _UE_USERUNBAN_SUCCESSFUL;
		}elseif($act==2) {
			if ($my->id!=$uid){
				mosNotAuth();
				return;
			}
			$bannedreason = "<b>".htmlspecialchars("["._UE_USERBANRESPONSE."]")."</b>\n".$_POST['bannedreason']."\n".$_POST['orgbannedreason'];
			$sql="UPDATE #__comprofiler SET banned='2', bannedreason='$bannedreason' WHERE id='$uid'";
			$database->SetQuery($sql);
			$database->query();
		if($ueConfig['moderatorEmail']==1) {
			$database->setQuery( "SELECT name, email FROM #__users"
			."\n WHERE gid >='".$ueConfig['imageApproverGid']."'" );
			$rowAdmins = $database->loadObjectList();
			foreach ($rowAdmins AS $rowAdmin) {
				createEmail($row,'unbanAdmin',$ueConfig,$rowAdmin);
			}
		}
			echo _UE_USERUNBANREQUEST_SUCCESSFUL;

		}
	}
}

function processReports(){
  global $database,$_POST,$mosConfig_absolute_path,$my;
	$isModerator=isModerator($my->id);
	if ($isModerator == 0) {
		mosNotAuth();
		return;
	}
	$reports=array();
	$reports=$_POST['reports'];
		foreach ($reports AS $report) {
			$query = "UPDATE #__comprofiler_userreports SET reportedstatus = 1 WHERE reportid = '" . $report . "'";
			$database->setQuery($query);
			$database->query();
		}
	mosRedirect(sefRelToAbs('index.php?option=com_comprofiler&task=moderateReports'));
}
function moderator(){
  global $database,$_POST,$mosConfig_absolute_path,$my;
	$isModerator=isModerator($my->id);
	if ($isModerator == 0) {
		mosNotAuth();
		return;
	}
	$query = "SELECT count(*) FROM #__comprofiler  WHERE avatarapproved=0";
	if(!$database->setQuery($query)) print $database->getErrorMsg();
	$totalimages = $database->loadResult();

	$query = "SELECT count(*) FROM #__comprofiler_userreports  WHERE reportedstatus=0 ";
	if(!$database->setQuery($query)) print $database->getErrorMsg();
	$totaluserreports = $database->loadResult();

	$query = "SELECT count(*) FROM #__comprofiler WHERE banned=2";
	if(!$database->setQuery($query)) print $database->getErrorMsg();
	$totalunban = $database->loadResult();

	if($totalunban > 0 || $totaluserreports > 0 || $totalimages > 0) {
		if($totalunban > 0) echo "<div>".$totalunban._UE_UNBANREQUIREACTION."</div>";
		if($totaluserreports > 0) echo "<div>".$totaluserreports._UE_USERREPORTSREQUIREACTION."</div>";
		if($totalimages > 0) echo "<div>".$totalimages._UE_IMAGESREQUIREACTION."</div>";


	} else {
		echo _UE_NOACTIONREQUIRED;

	}

}


function approveUser($option,$uids) {
	global $database,$ueConfig,$_POST,$my,$mosConfig_emailpass;
	$isModerator=isModerator($my->id);
	if($ueConfig['allowModUserApproval']==0) {
			echo _UE_FUNCTIONALITY_DISABLED;
			exit();
	}
	if ($isModerator!=1){
		mosNotAuth();
		return;
	}
	if($mosConfig_emailpass!=1) $mosConfig_emailpass=0;

	foreach($uids AS $uid) {
			$sql="UPDATE #__comprofiler SET approved='1'WHERE id='$uid'";
			$database->SetQuery($sql);
			$database->query();
			$database->setQuery( "SELECT name, username, email FROM #__users"
			."\n WHERE id='$uid'" );
			$rows = $database->loadObjectList();
			foreach ($rows AS $row) {
				createEmail($row,'welcome',$ueConfig,null,$mosConfig_emailpass);
			}
	//$comment='comment'.$uid;
	$comment=$_POST[$comment];
	//print $uid;
//	print "<br>".$_POST['comment'.$uid];
	}
	echo _UE_USERAPPROVAL_SUCCESSFUL;

}

function rejectUser($option,&$uids) {
	global $database,$ueConfig,$_POST,$my,$mosConfig_emailpass;
	$isModerator=isModerator($my->id);
	if($ueConfig['allowModUserApproval']==0) {
			echo _UE_FUNCTIONALITY_DISABLED;
			exit();
	}
	if ($isModerator!=1){
		mosNotAuth();
		return;
	}
	if($mosConfig_emailpass!=1) $mosConfig_emailpass=0;
	foreach($uids AS $uid) {
		$sql="UPDATE #__comprofiler SET approved='2'WHERE id='$uid'";
		$database->SetQuery($sql);
		$database->query();
		$database->setQuery( "SELECT name, username, email FROM #__users"
		."\n WHERE id='$uid'" );
		$rows = $database->loadObjectList();
		foreach ($rows AS $row) {
			createEmail($row,'rejectUser',$ueConfig,$_POST['comment'.$uid],$mosConfig_emailpass);
		}
	}
	echo _UE_USERREJECT_SUCCESSFUL;

}

function pendingApprovalUsers($option) {
	global $database,$ueConfig,$_POST,$my,$mosConfig_emailpass;
	$isModerator=isModerator($my->id);
	if($ueConfig['allowModUserApproval']==0) {
			echo _UE_FUNCTIONALITY_DISABLED;
			exit();
	}
	if ($isModerator!=1){
		mosNotAuth();
		return;
	}
	if($mosConfig_emailpass!=1) $mosConfig_emailpass=0;

	$database->setQuery( "SELECT u.id, u.name, u.username, u.email, u.registerDate "
	."\n FROM #__users u, #__comprofiler c "
	."\n WHERE u.id=c.id AND c.approved=0 AND c.confirmed=1" );
	$rows = $database->loadObjectList();
	
	HTML_comprofiler::pendingApprovalUsers($option, $rows);	
}

?>
