<?php
if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );

/**
*
* @package simpleMembership
* @copyright Andrey Kvasnevskiy-OrdaSoft(akbet@mail.ru); Anton Getman(ljanton@mail.ru);
* Homepage: http://www.ordasoft.com
* @version: 1.2 FREE
*
**/


  $GLOBALS['mainframe']=$mainframe = JFactory::getApplication();
  $GLOBALS['document']=$document = JFactory ::getDocument();

$mosConfig_absolute_path = $GLOBALS['mosConfig_absolute_path']	= JPATH_SITE;
require_once($mosConfig_absolute_path."/administrator/components/com_simplemembership/compat.joomla1.5.php");

require_once( $mosConfig_absolute_path .'/components/com_simplemembership/openinviter/openinviter.php' );
jimport('joomla.html.pagination');
 
// load language
$lang_def_en=0;
$lang =JFactory::getLanguage();
JFactory::getLanguage()->load('com_users', JPATH_SITE, $lang->getTag(), true);//add language for com_users

foreach ($lang->getLocale() as $locale) {
          $mosConfig_lang=$locale;
    if (file_exists($mosConfig_absolute_path."/components/com_simplemembership/language/{$mosConfig_lang}.php" ))     {  
          include_once($mosConfig_absolute_path."/components/com_simplemembership/language/{$mosConfig_lang}.php" );
          include_once($mosConfig_absolute_path."/components/com_simplemembership/language/{$mosConfig_lang}.php" );
          $lang_def_en=1;
    } 
}
if ( $lang_def_en != 1 ) {
   $mosConfig_lang = "english";  
   include_once($mosConfig_absolute_path."/components/com_simplemembership/language/english.php" );
}

/** load the html drawing class */
// require_once($mainframe->getPath('front_html'));
// require_once($mainframe->getPath('class'));
require_once($mosConfig_absolute_path."/administrator/components/com_simplemembership/admin.simplemembership.class.others.php");
require_once($mosConfig_absolute_path."/administrator/components/com_simplemembership/admin.simplemembership.class.conf.php");
require_once($mosConfig_absolute_path."/administrator/components/com_simplemembership/functions.php");
require_once($mosConfig_absolute_path."/components/com_simplemembership/simplemembership.class.php");
require_once($mosConfig_absolute_path."/components/com_simplemembership/simplemembership.html.php");
global $user_configuration, $mosConfig_mailfrom, $mosConfig_live_site;
$GLOBALS['user_configuration'] = $user_configuration;
$GLOBALS['mosConfig_mailfrom'] = $mosConfig_mailfrom;
//$mainframe->setPageTitle( _SIMPLEMEMBERSHIP_TITLE );

$doc =JFactory::getDocument();  
	$doc->addStyleSheet( $mosConfig_live_site.'/administrator/components/com_simplemembership/includes/simplemembership.css' );


$task = trim( mosGetParam( $_REQUEST, 'task', "" ) );
$id = intval( mosGetParam( $_REQUEST, 'id', 0 ) );
$catid = intval(mosGetParam( $_REQUEST, 'catid', 0 ) );
$GLOBALS['Itemid'] = $Itemid = trim( mosGetParam( $_REQUEST, 'Itemid', "" ) );



$userId = trim( mosGetParam( $_REQUEST, 'userId', "" ) );
 
 
//add profile form
jimport('joomla.application.component.modelform');

  //class Temp_class_for_profile_form extends JModelForm {
  class UsersModelRegistration extends JModelForm {
  
    public function getForm($data = array(), $loadData = true)
      {
        // Get the form.
        
        $form = $this->loadForm('com_users.registration', 'registration', array('control' => 'jform', 'load_data' => $loadData));
        if (empty($form)) {
          return false;
        }
        return $form;
      }
  }
//add profile form

function josGetArrayIntsMy( $name, $type=NULL ) {

   $array   =  JRequest::getVar($name, array(), 'default', 'array' );

   return $array;
}

$cid = josGetArrayIntsMy('cid');
require_once('./administrator/components/com_simplemembership/syncexpire.php');
check_users();

if ( isset($_REQUEST['view']) ) $view = mosGetParam( $_REQUEST, 'view', '' ) ; 
if ( (!isset($task) OR $task == '' ) AND  isset($view)  ) $task = $view;

switch ($task)
{
	case 'advregister':
		advregister();
		break;

	case 'advexpire':
		advexpire();
		break;

	case 'activate':
		activate();
		break;

	case 'add_user':
		add_user();
		break;

	case 'update_user':
		update_user();
		break;

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

	case 'show_search':
			showSearchsimplememberships( $option, $catid, $option );
			break;

	case 'search':
		searchsimplememberships( $option, $catid, $option );
		break;

	case 'view':
		showItem( $id, $catid );
		break;

	case 'show_invite':
		show_invite($option);
		break;

	case 'fetch':
		fetch($option);
		break;

	case 'invite':
		invite($cid,$option);
		break;

	case 'congretulation':
		congretulation($option);
		break;
	
	case 'show_users':
		show_users();
		break;

	case 'my_account':
		User_account();
		break;
		
	case 'showUsersProfile':
		ShowUsersProfile($userId);
		break;
	default:
			User_account();
		break;
	}
	
//display user's account
function User_account() 
{
	global $database, $my, $mosConfig_live_site, $mosConfig_absolute_path,$Itemid;
	
	 $user_id = $my->id;
	 if($user_id)
	 { 
	?>
    <div id="mod_user_profile">
    <?php
		$joom_user = new JUser();
		$joom_user->load($user_id);
		$dispatcher = JDispatcher::getInstance();
		JPluginHelper::importPlugin('user');
		JForm::addFormPath($mosConfig_absolute_path.'/components/com_simplemembership/forms');
		$user_profile_form = JForm::getInstance('com_users.module', 'registration');
		$results2 = $dispatcher->trigger('onContentPrepareData', array('com_users.module', $joom_user));
		$results = $dispatcher->trigger('onContentPrepareForm', array($user_profile_form, $joom_user));
		$user_profile_form->bind($joom_user);
		$fields=$user_profile_form->getFieldset('profile');
		$profile_image=$user_profile_form->getValue('file','profile','');
                $html_simplemembership = new HTML_simplemembership();
		$html_simplemembership -> ShowListUsers($user_profile_form, $user_profile_form, $fields, $profile_image, $mosConfig_live_site, $joom_user );
  }else{echo "Login please!!!";}
}
//display user's list
function show_users()
{
	global $mosConfig_live_site,$database;	
	
	$mainframe = JFactory::getApplication();
	// Get pagination request variables
	$limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
	$limitstart = JRequest::getVar('limitstart', 0, '', 'int');
	
	$database->setQuery("SELECT count(*) as total FROM #__users ORDER BY name");
    $total = $database->loadResult();
    echo $database->getErrorMsg();

	$pageNav = new JPagination($total, $limitstart, $limit);
	
	$query="SELECT * FROM #__users ORDER BY name "
		. " limit ".$pageNav->limitstart. " , ". $pageNav->limit;
	$database->setQuery($query);
	$list=$database->loadObjectList();
    echo $database->getErrorMsg();

	
	$query="SELECT `userid`, `username` FROM #__session WHERE guest = 0 AND client_id = 0";
	$database->setQuery($query);
	$ListUsersOnline = $database->loadObjectList();
	
	foreach( $ListUsersOnline as $ListUser)
	{
		$UsersL[] = $ListUser->userid;
	}
	
	 if(!empty($UsersL))
	{
		$UsOnline[] = array_unique($UsersL) ;
		unset($UsersL);
		foreach( $list as $user)
		{
			$UserL[] = $user->id; 
			for($i=0;$i<count($UserL); $i++)
			{
				if(!in_array($UserL[$i] ,$UsOnline[0]))
				{	
					$UsersL[] =  $UserL[$i];
				}
			}
		}	
		$UsOffline[] = array_unique($UsersL) ;
	}else{
		$UsOnline[0]= Array(0);
		$UsOffline[]= Array(0);
	}
	$html_simplemembership = new HTML_simplemembership(); 	
    $html_simplemembership -> UsersList( $list ,$pageNav, $UsOnline, $UsOffline);
}	
//display user's profile
function ShowUsersProfile($userId){	
	global $database, $mosConfig_live_site, $mosConfig_absolute_path, $user_configuration;
		
	$doc =JFactory::getDocument(); 
	$doc->addStyleSheet( $mosConfig_live_site.'/administrator/components/com_simplemembership/includes/vehiclemanager.css' );
	$database = JFactory::getDBO();
	$user =JFactory::getUser();
  $acl =JFactory::getACL();
 
	//print_r($user->id); exit;
  
  if( !checkAccess_SM( $user_configuration['other_profiles'],'NORECURSE', userGID_SM($user->id), $acl) ) 
  {
    echo "You have't right see other profiles";
    return;
  } 
  
	$user_id=$userId;
	?>
    <div id="mod_user_profile">
    <?php
		$joom_user = new JUser();
		$joom_user->load($user_id);
		$dispatcher = JDispatcher::getInstance();
		JPluginHelper::importPlugin('user');
		JForm::addFormPath($mosConfig_absolute_path.'/components/com_simplemembership/forms');
		$user_profile_form = JForm::getInstance('com_users.module', 'registration');
		$results2 = $dispatcher->trigger('onContentPrepareData', array('com_users.module', $joom_user));
		$results = $dispatcher->trigger('onContentPrepareForm', array($user_profile_form, $joom_user));
		$user_profile_form->bind($joom_user);
		$fields=$user_profile_form->getFieldset('profile');
		$profile_image=$user_profile_form->getValue('file','profile','');
                
                $html_simplemembership = new HTML_simplemembership();
		$html_simplemembership -> ShowListUsers($user_profile_form, $user_profile_form, $fields, $profile_image, $mosConfig_live_site, $joom_user );
  
  }
	

	
function ers($ers){
	$contents="<table cellspacing='0' cellpadding='0' style='border:1px solid red;' align='center' class='tbErrorMsgGrad'><tr><td valign='middle' style='padding:3px' valign='middle' class='tbErrorMsg'><img src='/images/ers.gif'></td><td valign='middle' style='color:red;padding:5px;'>";
	foreach ($ers as $key=>$error)
		$contents.="{$error}<br >";
	$contents.="</td></tr></table><br >";
	return $contents;
}

function fetch($option){
	global $database,$my,$mosConfig_absolute_path;
	//from openinviter
	$inviter=new OpenInviter();
	$email_providers=$inviter->getPlugins();

//	$query = "SELECT * FROM #__simplemembership_config";
//	$database->setQuery($query);
//	$database->loadObject($conf);
//
//	if ($database -> getErrorNum()) {
//		echo $database -> stderr();
//		return false;
//	}

	set_time_limit(0);

	//From openinviter
	$ers=array();
	$import_ok=false;

	if (($_SERVER['REQUEST_METHOD']=='POST'))
	{
	 $email_box=mosGetParam( $_REQUEST, 'email_box', '' );
	 $password_box=mosGetParam( $_REQUEST, 'password_box', '' );
	 $provider_box=mosGetParam( $_REQUEST, 'provider_box', '' );

	if (empty($email_box))
		$ers['email']="Email address is missing";
	if (empty($password_box))
		$ers['password']="Password is missing";
	if (empty($provider_box))
		$ers['provider']="Provider is missing";
	
	if (count($ers)==0)
		{
		$inviter->startPlugin($provider_box);
		if (!isset($inviter))
			$ers['inviter']='Invalid email provider';
		elseif (!$inviter->login($email_box,$password_box))
			$ers['login']='Incorrect login';
		elseif (!$contacts=$inviter->getMyContacts())
			$ers['contacts']=_NO_CONTACTS_FETCHED;
		else
			{
			$inviter->logout();
			$import_ok=true;
			}
		}
	}

	$contents=(count($ers)!=0?ers($ers):'');

	if (!$import_ok)
	{
		foreach($ers AS $error)
		$errmsg .= $error.' ';
		//mosRedirect( "index.php?option=$option",_NO_CONTACTS_FETCHED );
		mosRedirect( "index.php?option=$option&task=show_invite",$errmsg );
	}
//print_r($ers);echo '::';print_r($contents);exit;
		$str="";

		if ($import_ok)
		{
			if (count($contacts)==0)
			$contents=_EMPTY_ARRAY;

			else{
			$msg = "";
//			if($conf->use_custom_msg)
//				$msg = $conf->msg;
//				$YOUR_EMAIL=$email_box;

			foreach ($contacts as $email=>$name){
				$name = addslashes($name);
				$query = "INSERT IGNORE INTO #__simplememberships (`invitee_email`,`invitee_name`,`invited_by_email`,`msg`) VALUES ('". $database->getEscaped($email)."','". $database->getEscaped($name)."','". $database->getEscaped($YOUR_EMAIL)."','". $database->getEscaped($msg)."')";
				$database->setQuery($query);
				$database->query();
				if ($database->getErrorNum()) {
					echo $database->stderr();
					return false;
				}
			}
		}
			$query = "SELECT * from #__simplememberships WHERE `invited_by_email`= '$YOUR_EMAIL' ORDER BY `invitee_name`";
			$database->setQuery($query);
			$rows = $database->loadObjectList();
			if ($database->getErrorNum()) {
				echo $database->stderr();
				return false;
			}

			$name='';
			if($my->id)
				$name=$my->name;
                        $html_simplemembership = new HTML_simplemembership();
			$html_simplemembership -> display($option,$rows,$YOUR_EMAIL,$name,$contents);
		}
}

function invite( $cid, $option ){
	global $database,$mosConfig_live_site,$mosConfig_mailfrom,$mosConfig_fromname;
	$query = "SELECT * FROM #__simplemembership_config";
	$database->setQuery($query);
	$database->loadObject($conf);
	if ($database -> getErrorNum()) {
		echo $database -> stderr();
		return false;
	}

	josSpoofCheck();

	if (!is_array( $cid ) || count( $cid ) < 1) {
		echo "<script> alert('Select contact to invite'); window.history.go(-1);</script>\n";
		exit;
	}
	$from_email = mosGetParam($_REQUEST,'from_email','');
	$from_name = mosGetParam($_REQUEST,'name','');
	$msg = mosGetParam( $_REQUEST, 'msg', '' );
	$default_msg = mosGetParam( $_REQUEST, 'default_mesg', '' );
	$msg = $msg.'<br/><br/>'.$default_msg;
	$msgtosave = addslashes($msg);
	$n=0;
	//Warning: Hardcoded text
	$admin_sub="JoomInvites sent";
	$admin_msg = "Hi Admin,<br />$from_name ($from_email) has sent invitation to :-<br/><br />";

	mosArrayToInts( $cid );
	foreach($cid AS $id){
		$query = "UPDATE #__simplememberships SET `invited_by_name`='$from_name', `to_be_invited`=1, `last_sent`=CURDATE(), `msg`='$msgtosave' WHERE `id`=$id";
		$database->setQuery($query);
		$database->query();
		if ($database->getErrorNum()) {
			echo $database->stderr();
			return false;
		}
		$query = "SELECT `invitee_name`, `invitee_email` FROM #__simplememberships WHERE `id`=$id";
		$database->setQuery($query);
		$result = $database->loadObjectList();
		if ($database->getErrorNum()) {
			echo $database->stderr();
			return false;
		}

		$name = $result[0]->invitee_name;
		$to = $result[0]->invitee_email;
		$subject = $conf->custom_subject;
		$default_msg = $conf->msg;
		$subject = preg_replace('/{user}/',$from_name,$subject);
		$subject = preg_replace('/{my_site}/',$mosConfig_live_site,$subject);
		$body = "Hi $name,<br/>";
		$body.= stripslashes($msg);
		$body.="<br/><br/>$default_msg";
		$mailfrom = ($conf->email_from_user?$from_email:$mosConfig_mailfrom);
		$fromname = ($conf->email_from_user?$from_name:$mosConfig_fromname);
		mosMail($mailfrom,$fromname,$to,$subject,$body,1,NULL,NULL,null,$from_email,$from_name);
		$admin_msg.="$name ($to).<br/>";
		$n++;
		//echo "<script> alert('Sent ".$subject." to ".$name." at ".$body."');</script>";
	}
	if($conf->bcc_admin){
		mosMail($mosConfig_mailfrom,$mosConfig_fromname,$mosConfig_mailfrom,$admin_sub,$admin_msg,1);
	}

	//Warning: Hardcoded text
	mosRedirect( "index.php?option=$option&task=congretulation","Successfully invited $n contacts, invite more friends at any time." );
}



function show_invite($option){
        $html_simplemembership = new HTML_simplemembership();
	$html_simplemembership -> front($option);
}

function congretulation($option){
        $html_simplemembership = new HTML_simplemembership();
	$html_simplemembership -> congretulation($option);
}

function activate()
{
	global $database,$user_configuration;
	$msg_body = $user_configuration['activationmsg'];
	if(array_key_exists('activation', $_GET))
	{
		$activation = $_GET['activation'];
		$query = "select * from #__users where activation='$activation'";
		$database->setQuery($query);
		$user_res = $database->loadObjectList();
		if(array_key_exists(0, $user_res))
		{
			$user_res = $user_res[0];
			$uid = $user_res->id;

			$query = "select * from #__simplemembership_users where joomid='$uid'";
			$database->setQuery($query);
			$adv_user = $database->loadObjectList();
			$adv_user = $adv_user[0];
			$ug_id = $adv_user ->advgroup_id;

			$query = "update #__users set block='0' where id='$uid'";
			$database->setQuery($query);
			$database->query();
      $query = "update #__users set activation='' where id='$uid'";
      $database->setQuery($query);
      $database->query();
			$query = "update #__simplemembership_users set block='0' where joomid='$uid'";
			$database->setQuery($query);
			$database->query();

			$add_text = '';

			if($ug_id!=0)
			{
				$query = "select * from #__simplemembership_groups where id='$ug_id'";
				$database->setQuery($query);
				$group = $database->loadObjectList();
				$group = $group[0];
				if($group->product_id==0)
				{
					$user = new JUser();
					$user->load($uid);
					$user->gid = $adv_user->want_gid;
					$user->usertype = $adv_user->want_group;
					$user->save();
					//				$database = JFactory::getDBO();
					$date = date('Y-m-d');
					$date_string = ",last_approved='$date'";
					$query = "UPDATE #__simplemembership_users SET usertype=want_group, approved='0' ".$date_string. " WHERE joomid='$uid'";
					$database->setQuery($query);
					$database->query();
					$add_text = 'Your account is activated and ready to use';
				}
				else
				{
					if($group->product_name != '')
					{
						$add_text .= '<br>You need to buy product('.$group->product_name .') ';
					}
					if($group->link != '')
					{
						$add_text .= 'and follow <a href="'.$group->link.'"><strong>link</strong></a> ';
					}
				}
			}
			else
			{
				$date = date('Y-m-d');
				$date_string = ",last_approved='$date'";
				$query = "UPDATE #__simplemembership_users SET usertype=want_group, approved='0' ".$date_string. " WHERE joomid='$uid'";
				$database->setQuery($query);
				$database->query();
				$add_text = 'Your account is activated and ready to use';
			}
			$msg = '<div class="componentheading">Activation Complete!</div><div class="message">'.$msg_body.$add_text.'</div>
	<br/>
	<a href="index.php?option=com_simplemembership&task=show_invite">Invite friends</a>';
		}
		else
		$msg = '<div class="componentheading">Activation not Complete!</div><div class="message">Invalid activation code.</div>';
	}
	else
	$msg = '<div class="componentheading">Activation not Complete!</div><div class="message">Invalid activation link.</div>';
	echo $msg;
}

function update_user()
{
	global $database, $my, $user_configuration,$mainframe,$mosConfig_live_site;

	$default_group = $user_configuration['default_group']; 
  if(empty($default_group)) {
    $default_group=array('2'=>'2');
    $default_group_name='Registered';
  }
  else {
    $query ="SELECT ug.title FROM #__usergroups AS ug WHERE ug.id IN ( ".implode(",",$default_group)." )";
    $database->setQuery($query);
    $default_group_name=$database->loadResultArray();
    $default_group_name=implode(",",$default_group_name);
    //$default_group=array_combine($default_group,$default_group);
    $f="";
    $s = explode(',',$user_configuration['default_group'] );
    $mosHTML = new mosHTML();
    for($i = 0;$i<count($s);$i++){
        $f[] = $mosHTML -> makeOption($s[$i]);
    }
    $default_group = $f ;
  }


	if($_POST['name'] == '' ||$_POST['email1'] == '' || $_POST['username'] == '')
	{
		$mainframe->enqueueMessage('Fields Name, UserName and email must be filled!. ','error');
		mosRedirect("index.php?option=com_simplemembership");
	}

	$bid = $my->id;

	$new_ug_id = (int)$_POST['advgid'];

	$user = new JUser();


		$query = "SELECT * from #__simplemembership_users where joomid='$bid'";
		$database->setQuery($query);
		$tmp_us = $database->loadObject();
		$adv_uid = $tmp_us->id;
		$joom_id = $tmp_us->joomid;
		$adv_wg = $tmp_us->want_gid;
		$adv_dl = $tmp_us->days_last;
		$user->load($joom_id);

		if($new_ug_id!=-1 && $new_ug_id!=-2)
		{
			$query = "select * from #__simplemembership_groups where id='$new_ug_id'";
			$database->setQuery($query);
			$group = $database->loadObjectList();
			$group = $group[0];

			$g_acl_gid = $group->acl_gid;
			$g_dl = $group->days_last;
		}
		else
		{
			$g_acl_gid = $default_group;
			$g_dl = 0;
		}

		if(($adv_wg!=$g_acl_gid) ||($adv_dl!=$g_dl))
		{
			if($new_ug_id!=-2)
			{
				$user->groups = $default_group;
				$user->usertype = $default_group_name;
			}
		}
if(isset($_POST['password1'])) 
	$_POST['password'] = $_POST ['password1'];
  $user->bind($_POST);
	$user->name = $database->getEscaped($_POST['name']);
	$user->email = $database->getEscaped($_POST['email1']);
	$user->username = $database->getEscaped($_POST['username']);

	$user->registerDate = date('Y-m-d h:i:s');

	if($user->save())
	{
		$al_user = new mos_alUser($database);

		$al_user->load($adv_uid);
		$al_user->bind($_POST);

		$al_user->joomid = $user->id;

		$prev_group = $al_user->advgroup_id;

		if($new_ug_id!=-1)
		{
			$query = "select * from #__simplemembership_groups where id='$new_ug_id'";
			$database->setQuery($query);
			$group = $database->loadObjectList();
			$group = $group[0];

			$al_user->want_gid = $group->acl_gid;
			$al_user->want_group = $group->acl_group;
			$al_user->days_last = $group->days_last;
			$al_user->advgroup_id = $new_ug_id;
		}
		else
		{
			$al_user->want_gid = $default_group_id;
			$al_user->want_group = $default_group_name;
			$al_user->days_last = 0;
			$al_user->advgroup_id = 0;
		}

		if($prev_group!=$new_ug_id)
		{
			if($new_ug_id!=-2)
			{
				$al_user->gid = $default_group_id;
				$al_user->usertype = $default_group_name;
			}
			$al_user->block = $user->block;
			$al_user->approved = 1;
		}
		$al_user->store();
		$mainframe->enqueueMessage('User updated');
	}
	else
	{
		$mainframe->enqueueMessage('User can not be updated. '. $user->getError(),'error');
	}
	mosRedirect("index.php");
}

function add_user()
{
	global $database, $my, $user_configuration,$mainframe,$mosConfig_live_site,$mosConfig_mailfrom;
	$activate = md5(time());
	$activation_link ='<a href="'. $mosConfig_live_site. '/index.php?option=com_simplemembership&task=activate&activation='. $activate .'">Activation link</a>';

	//// Default group

	$default_group = $user_configuration['default_group']; 
  if(empty($default_group) ) {
    $default_group=array('2'=>'2');
    $default_group_name='Registered';
  }
  else {
    $query ="SELECT ug.title FROM #__usergroups AS ug WHERE ug.id IN ($default_group)";
    $database->setQuery($query);
    $default_group_name=$database->loadResultArray();
    $default_group_name=implode(",",$default_group_name);
    //$default_group=array_combine($default_group,$default_group);
    $f="";
    $s = explode(',',$user_configuration['default_group'] );
    $mosHTML = new mosHTML();
    for($i = 0;$i<count($s);$i++){
        $f[] = $mosHTML->makeOption($s[$i]);
    }
    $default_group = $f ;
  }


	$user = new JUser();
	$user->bind($_POST);
  $user->email = $_POST['email1'];
	$user->groups=$default_group;
  $user->usertype =$default_group_name;
	$user->block = 0;
	$user->activation = $activate;
	if($user->save())
	{
		$email = $database->Quote( $_POST['email1'] );
		$query = "SELECT * from #__users where email='".$email."'";
		$database->setQuery($query);
		$added_user = $database->loadObjectList();
		$added_user = $added_user[0];
		$al_user = new mos_alUser($database);
		$al_user->bind($_POST);
    $al_user->email = $_POST['email1'];
		$al_user->joomid = $added_user->id;
// 		$al_user->gid = $default_group_id;
// 		$al_user->usertype = $default_group_name;
		if(array_key_exists('gid', $_POST) && $_POST['gid']!=-1)
		{
  		$query = "SELECT * FROM #__simplemembership_groups WHERE id='".(int)$_POST['gid']."'";
			$database->setQuery($query);
			$group = $database->loadObjectList();
			$group = $group[0];

			$al_user->advgroup_id = (int)$_POST['gid'];
/*			$al_user->want_gid = $group->acl_gid;
			$al_user->want_group = $group->acl_group;*/
			$al_user->days_last = $group->days_last;

			$add_text = ($group->link != '') ? 'And please buy "'.$group->product_name .'" from here: <a href"'.$group->link .'">Product</a>' : '';
			$admin_acc_create_msg = stripslashes($user_configuration['admin_created_msg']). "\n".'Username: '.$_POST['username'] . ' UserGroup:'. $al_user->usertype;
			$postregister_msg = $group->notes;
		}
		else
		{
// 			$al_user->want_gid = $default_group_id;
// 			$al_user->want_group = $default_group_name;
			$al_user->days_last = 0;
			$al_user->advgroup_id = 0;

			$add_text = '';
			$admin_acc_create_msg = stripslashes($user_configuration['admin_created_msg']). "\n".'Username: '.$_POST['username'] . ' UserGroup:'. $default_group_name;
			$postregister_msg ='';
		}
		$al_user->block = 1;
		$al_user->approved = 1;

		$is_created = $al_user->store();

		$user_acc_create_msg = stripslashes($user_configuration['user_created_msg']). "\n".'Please click here to activate your account:'.$activation_link." .\n".$add_text;

		if(!empty ($user_configuration['useradd_notification_email']))
		JUTility::sendMail($mosConfig_mailfrom,'joomla simplemembership',$user_configuration['useradd_notification_email'], 'account creation', $admin_acc_create_msg,1);
		JUTility::sendMail($mosConfig_mailfrom,'joomla simplemembership',$al_user->email , 'account creation',$user_acc_create_msg,1);

    if($postregister_msg!='') $mainframe->enqueueMessage($postregister_msg);
    
    if( $is_created ) $mainframe->enqueueMessage("Your account has been created and an activation link has been sent to the email address you entered. Note that you must activate the account by clicking on the activation link when you get the email before you can login.");
    
    
    
    
	}
	else
	{
		$mainframe->enqueueMessage('User not registered. '. $user->getError(),'error');
	}

}

function accdetail($option)
{
	global $database,$my,$user_configuration,$mosConfig_absolute_path;
	
	$user_id = $my->id;
	if($user_id)
	{ 
		$jom_id = $my->id;
		$query = "select id from #__simplemembership_users where joomid='$jom_id'";
		$database->setQuery($query);
		$bid = $database->loadResult();

		// default group end
		$default_group = $user_configuration['default_group']; 
	  if(empty($default_group)) {
		$default_group=array('2'=>'2');
		$default_group_name='Registered';
	  }
	  else {
		$query ="SELECT ug.title FROM #__usergroups AS ug WHERE ug.id IN ( ".$default_group." )";
		$database->setQuery($query);
		$default_group_name=$database->loadResultArray();
		$default_group_name=implode(",",$default_group_name);
		//$default_group=array_combine($default_group,$default_group);
    $f="";
    $s = explode(',',$user_configuration['default_group'] );
    $mosHTML = new mosHTML();
    for($i = 0;$i<count($s);$i++){
        $f[] = $mosHTML -> makeOption($s[$i]);
    }
    $default_group = $f ;  
	  }
	  
	  
		// 	if($default_group=='')
		// 	$default_group = 2;
		// 	$query = "SELECT title FROM #__usergroups WHERE id='$default_group'";
		// 	$database->setQuery($query);
		// 	$default_group_inf = $database->loadResult();
		// 
		// 	if(!$default_group_inf)
		// 		$default_group_name = 'Registered';
		// 	else
		// 		$default_group_name = $default_group_inf;

		// default group end

		$user = new mos_alUser($database);
		$user->load(intval($bid));
		$options = array();
		$query = "SELECT * FROM #__simplemembership_groups WHERE published='1'";
		$database->setQuery($query);
		$pr_lis = $database->loadObjectList();

		$joom_user = new JUser();
	  $joom_user->load($user->joomid);

	  $joom_user->params=json_decode($joom_user->params, true);
	  
	  
	  
	  if(in_array($default_group, $joom_user->groups) /*$joom_user->gid!=$default_group*/ && $user->advgroup_id==0 && $bid!=0)
		$mosHTML = new mosHTML();
                $options[] = $mosHTML -> makeOption( -2, $joom_user->usertype .'(Joomla group)');

		$options[] = $mosHTML -> makeOption( -1, $default_group_name.'(Joomla group)');

		foreach($pr_lis as $item)
		{
		if($item->id==$user->advgroup_id) $link_for_product=$item->link;
		if($item->id==$user->advgroup_id) $name_of_group=$item->name;
                        $mosHTML = new mosHTML();
			$options[] = $mosHTML -> makeOption( $item->id, $item->name);
		}

		if(array_key_exists(0, $options)){
                        $mosHTML = new mosHTML();
                        $olist = $mosHTML->selectList($options, 'advgid', '', 'value', 'text', $user->advgroup_id);
                }
		else
		$olist = $default_group_name.'(Joomla group)';
	  
		 $last_approved_date=strtotime($user->last_approved);
		 $cur_date=@date("U");
		 $days_gone = (int)($cur_date-$last_approved_date)/86400;
		 if((($user->days_last)-$days_gone)<0){
		  if(isset($name_of_group) && $name_of_group !=''){
			$msg='<br/>You are expired for group <b>'.$name_of_group.'</b>, please buy this product <a href="'.$link_for_product.'">link</a>';
		  }
		  else{
			$msg='<br/>You can be in one of these groups';
		  }
		 }
		 if((($user->days_last)-$days_gone)>0){
		 $msg='<br/>You can be in this group for next '.ceil($user->days_last-$days_gone).'day(s)';
		 }
		 //print_r($msg);
		
		//add profile form

		  // Get the dispatcher and load the users plugins.
		  $dispatcher = JDispatcher::getInstance();
		  JPluginHelper::importPlugin('user');
		  JForm::addFormPath($mosConfig_absolute_path.'/components/com_simplemembership/forms');
		  //JForm::addFormPath($mosConfig_absolute_path.'/components/com_users/models/forms');
		  $user_profile_form = JForm::getInstance('com_users.profile', 'registration');
		  //$user_profile_form->load('com_users.profile', 'profile', array('control' => 'jform', 'load_data' => $joom_user));
		  //JForm::addFormPath($mosConfig_absolute_path.'/components/com_simplemembership/forms');
		  //$user_profile_form->loadFile('params', true);

		  //$results2 = $dispatcher->trigger('onContentPrepareData', array('com_users.registration', $joom_user));
		  $results2 = $dispatcher->trigger('onContentPrepareData', array('com_users.profile', $joom_user));
		  $results = $dispatcher->trigger('onContentPrepareForm', array($user_profile_form, $joom_user));
		  //$user_profile_form->loadFile('params', false);
		// print_r($joom_user);
		//  echo"2222";print_r($user_profile_form);
		  //$user_profile_form->params = array();
		  $user_profile_form->bind($joom_user);
				//$user_profile_form->setValue('editor', 'params' , 'codemirror');
		//  echo "ERROR:";print_r($user_profile_form->getErrors());
		//  echo"3333";print_r($user_profile_form);
		$ToSLink = $dispatcher->trigger('TermsOfService');
                $html_simplemembership = new HTML_simplemembership();
		$html_simplemembership -> accdetail($user,$olist,$option,$msg,$user_profile_form, $ToSLink);
	}else{header("Location:http://localhost/j25/index.php?");}
}

function advregister()
{
	global $database, $user_configuration,$mosConfig_absolute_path;
	sync_users();

	//// Default group

  $default_group = $user_configuration['default_group']; 
 
  if(empty($default_group) )   {
    $default_group=array('2'=>'2');
    $default_group_name='Registered';
  }
  else {
    $query ="SELECT ug.title FROM #__usergroups AS ug WHERE ug.id IN ($default_group)";
    $database->setQuery($query);
    $default_group_name=$database->loadResultArray();
    $database->getErrorMsg();
    $default_group_name=implode(",",$default_group_name);
    //$default_group=array_combine($default_group,$default_group);
    $f="";
    $s = explode(',',$user_configuration['default_group'] );
    $mosHTML = new mosHTML();
    for($i = 0;$i<count($s);$i++){
        $f[] = $mosHTML->makeOption($s[$i]);
    }
    $default_group = $f ;    
  }
  
  
// 	if($default_group=='')
// 	$default_group = 2;
// 	$query = "select name from #__core_acl_aro_groups where id='$default_group'";
// 	$database->setQuery($query);
// 	$default_group_inf = $database->loadResult();
// 
// 	if(!$default_group_inf)
// 	{
// 		$default_group_id = 18;
// 		$default_group_name = 'Registered';
// 	}
// 	else
// 	{
// 		$default_group_id = $default_group;
// 		$default_group_name = $default_group_inf;
// 	}

	$options = array();
	$query = "select * from #__simplemembership_groups where published='1'";
	$database->setQuery($query);
	$pr_lis = $database->loadObjectList();

	$preregister = stripslashes($user_configuration['preregister']);

	if(array_key_exists(0, $pr_lis))
        {
            $mosHTML = new mosHTML();
            $options[] = $mosHTML -> makeOption( -1, $default_group_name.'(Joomla group)');
        }
        $mosHTML = new mosHTML();
	foreach($pr_lis as $item)
	{
		$options[] = $mosHTML->makeOption( $item->id, $item->name);
	}
	if(array_key_exists(0, $options))
        {$mosHTML = new mosHTML();
	$olist = $mosHTML -> selectList($options, 'gid', '', 'value', 'text');
	
        }else
	$olist = '';


//add profile form

      // Get the dispatcher and load the users plugins.
      $dispatcher = JDispatcher::getInstance();
      JPluginHelper::importPlugin('user');
      JForm::addFormPath($mosConfig_absolute_path.'/components/com_users/models/forms');
        $user_profile_form = JForm::getInstance('com_users.registration', 'registration');
      $results = $dispatcher->trigger('onContentPrepareForm', array($user_profile_form, $data=array()));
 $ToSLink = $dispatcher->trigger('TermsOfService');
 $html_simplemembership = new HTML_simplemembership();
  $html_simplemembership -> advregister_form($olist,$preregister,$user_profile_form, $ToSLink);
}

//*****************************************************************************


if(!function_exists('secretImage')){
    function secretImage()
    {
        $session =JFactory::getSession();
        $pas = $session->get('captcha_keystring', 'default');
        $new_img = new PWImage();
        $new_img->set_show_string($pas);
        $new_img->get_show_image(2.2, array(mt_rand(0,50), mt_rand(0,50), mt_rand(0,50)), array(mt_rand(200,255), mt_rand(200,255), mt_rand(200,255)));
        exit();
    }
}

function checkFolderAcess($folder_list, $current_folder)
{
	$pattern = "/^($current_folder,)|(,$current_folder,)|^($current_folder)$|(,$current_folder)$/";
	if(preg_match($pattern, $folder_list))
	{
		return true;
	}
	return false;
}

function checkAccess_SM( $accessgroupid, $recurse, $usersgroupid, $acl) {
	//parse usergroups
	$tempArr = array();
	$tempArr = explode(',',$accessgroupid);
	for($i = 0;$i<count($tempArr);$i++)
	{
	 if($tempArr[$i] == $usersgroupid || $tempArr[$i]==-2){
	 	return 1;
		}else
		if($recurse == 'RECURSE'){
			$groupchildren=array();
			$groupchildren=$acl->get_group_children( $tempArr[$i], 'ARO', $recurse );
			if(is_array($groupchildren)&& count($groupchildren) > 0)
			if (in_array($usersgroupid, $groupchildren))
			return 1;
		}
	}
	return 0;
}

function userGID_SM($oID){
  $database = JFactory::getDBO();
  
  if($oID > 0){
      $query = "SELECT group_id FROM #__user_usergroup_map WHERE user_id  = '".$oID."'";
      $database->setQuery($query);
      $gids = $database->loadAssocList();
      if(count($gids) > 0){
          $ret = '';
          foreach($gids as $gid){
              if ($ret != "" ) $ret .=',';
              $ret .= $gid['group_id'];
          }
          return $ret;
      }
      else return -2;
  }
  else return -2;
}

