<?php /*

 ocPortal
 Copyright (c) ocProducts, 2004-2012

 See text/EN/licence.txt for full licencing information.


 NOTE TO PROGRAMMERS:
   Do not edit this file. If you need to make changes, save your changed file to the appropriate *_custom folder
   **** If you ignore this advice, then your website upgrades (e.g. for bug fixes) will likely kill your changes ****

*/

/**
 * @license		http://opensource.org/licenses/cpal_1.0 Common Public Attribution License
 * @copyright	ocProducts Ltd
 * @package		core_ocf
 */

/**
 * Module page class.
 */
class Module_admin_ocf_join
{

	/**
	 * Standard modular info function.
	 *
	 * @return ?array	Map of module info (NULL: module is disabled).
	 */
	function info()
	{
		$info=array();
		$info['author']='Chris Graham';
		$info['organisation']='ocProducts';
		$info['hacked_by']=NULL;
		$info['hack_version']=NULL;
		$info['version']=2;
		$info['locked']=false;
		return $info;
	}

	/**
	 * Standard modular entry-point finder function.
	 *
	 * @return ?array	A map of entry points (type-code=>language-code) (NULL: disabled).
	 */
	function get_entry_points()
	{
		return array('menu'=>'MEMBERS','misc'=>'ADD_MEMBER','delurk'=>'DELETE_LURKERS','download_csv'=>'DOWNLOAD_MEMBER_CSV','import_csv'=>'IMPORT_MEMBER_CSV','group_member_timeouts'=>'GROUP_MEMBER_TIMEOUTS');
	}

	/**
	 * Standard modular run function.
	 *
	 * @return tempcode	The result of execution.
	 */
	function run()
	{
		$GLOBALS['HELPER_PANEL_PIC']='pagepics/addmember';
		$GLOBALS['HELPER_PANEL_TUTORIAL']='tut_adv_members';

		if (get_forum_type()!='ocf') warn_exit(do_lang_tempcode('NO_OCF')); else ocf_require_all_forum_stuff();
		require_code('ocf_members_action');
		require_code('ocf_members_action2');

		$type=get_param('type','misc');

		if ($type=='menu') return $this->menu();
		if ($type=='misc') return $this->step1();
		if ($type=='step2') return $this->step2();
		if ($type=='delurk') return $this->delurk();
		if ($type=='_delurk') return $this->_delurk();
		if ($type=='__delurk') return $this->__delurk();
		if ($type=='download_csv') $this->download_csv();
		if ($type=='import_csv') return $this->import_csv();
		if ($type=='_import_csv') return $this->_import_csv();
		if ($type=='group_member_timeouts') return $this->group_member_timeouts();
		if ($type=='_group_member_timeouts') return $this->_group_member_timeouts();

		return new ocp_tempcode();
	}

	/**
	 * The do-next manager for choosing what to do
	 *
	 * @return tempcode		The UI
	 */
	function menu()
	{
		$GLOBALS['HELPER_PANEL_PIC']='pagepics/editmember';
		$GLOBALS['HELPER_PANEL_TUTORIAL']='tut_members';

		require_lang('submitban');
		require_lang('security');
		if (addon_installed('welcome_emails')) require_lang('ocf_welcome_emails');
		if (addon_installed('ecommerce')) require_lang('ecommerce');
		if (addon_installed('staff')) require_lang('staff');

		require_code('templates_donext');
		return do_next_manager(get_page_title('MEMBERS'),comcode_lang_string('DOC_MEMBERS'),
					array(
						/*	 type							  page	 params													 zone	  */
						array('addmember',array('admin_ocf_join',array('type'=>'misc'),get_module_zone('admin_ocf_join')),do_lang_tempcode('ADD_MEMBER'),('DOC_ADD_MEMBER')),
						(!has_specific_permission(get_member(),'member_maintenance'))?NULL:array('editmember',array('members',array('type'=>'misc'),get_module_zone('members'),do_lang_tempcode('SWITCH_ZONE_WARNING')),do_lang_tempcode('EDIT_MEMBER'),('DOC_EDIT_MEMBER')),
						array('merge_members',array('admin_ocf_merge_members',array('type'=>'misc'),get_module_zone('admin_ocf_merge_members')),do_lang_tempcode('MERGE_MEMBERS'),('DOC_MERGE_MEMBERS')),
						array('deletelurkers',array('admin_ocf_join',array('type'=>'delurk'),get_module_zone('admin_ocf_join')),do_lang_tempcode('DELETE_LURKERS'),('DOC_DELETE_LURKERS')),
						array('download_csv',array('admin_ocf_join',array('type'=>'download_csv'),get_module_zone('admin_ocf_join')),do_lang_tempcode('DOWNLOAD_MEMBER_CSV'),('DOC_DOWNLOAD_MEMBER_CSV')),
						array('import_csv',array('admin_ocf_join',array('type'=>'import_csv'),get_module_zone('admin_ocf_join')),do_lang_tempcode('IMPORT_MEMBER_CSV'),('DOC_IMPORT_MEMBER_CSV')),
						addon_installed('ocf_cpfs')?array('customprofilefields',array('admin_ocf_customprofilefields',array('type'=>'misc'),get_module_zone('admin_ocf_customprofilefields')),do_lang_tempcode('CUSTOM_PROFILE_FIELDS'),('DOC_CUSTOM_PROFILE_FIELDS')):NULL,
						addon_installed('welcome_emails')?array('welcome_emails',array('admin_ocf_welcome_emails',array('type'=>'misc'),get_module_zone('admin_ocf_welcome_emails')),do_lang_tempcode('WELCOME_EMAILS'),('DOC_WELCOME_EMAILS')):NULL,
						array('investigateuser',array('admin_lookup',array(),get_module_zone('admin_lookup')),do_lang_tempcode('INVESTIGATE_USER'),('DOC_INVESTIGATE_USER')),
						array('usergroups_temp',array('admin_ocf_join',array('type'=>'group_member_timeouts'),get_module_zone('admin_ocf_join')),do_lang_tempcode('GROUP_MEMBER_TIMEOUTS'),('DOC_GROUP_MEMBER_TIMEOUTS')),
						addon_installed('ecommerce')?array('ecommerce',array('admin_ecommerce',array('type'=>'misc'),get_module_zone('admin_ecommerce')),do_lang_tempcode('CUSTOM_PRODUCT_USERGROUP'),('DOC_ECOMMERCE')):NULL,
						array('usergroups',array('admin_ocf_groups',array('type'=>'misc'),get_module_zone('admin_ocf_groups'),do_lang_tempcode('SWITCH_SECTION_WARNING')),do_lang_tempcode('USERGROUPS'),('DOC_GROUPS')),
						addon_installed('staff')?array('staff',array('admin_staff',array('type'=>'misc'),get_module_zone('admin_staff'),do_lang_tempcode('SWITCH_SECTION_WARNING')),do_lang_tempcode('STAFF'),('DOC_STAFF')):NULL,
					),do_lang('MEMBERS')
		);
	}

	/**
	 * The UI for adding a member.
	 *
	 * @return tempcode		The UI
	 */
	function step1()
	{
		$title=get_page_title('ADD_MEMBER');

		list($fields,$hidden)=ocf_get_member_fields(false);

		$text=do_lang_tempcode('_ENTER_PROFILE_DETAILS');

		breadcrumb_set_parents(array(array('_SEARCH:admin_ocf_join:menu',do_lang_tempcode('MEMBERS'))));
		breadcrumb_set_self(do_lang_tempcode('ADD_MEMBER'));

		$submit_name=do_lang_tempcode('ADD_MEMBER');
		$url=build_url(array('page'=>'_SELF','type'=>'step2'),'_SELF');
		return do_template('FORM_SCREEN',array('_GUID'=>'3724dec184e27bb1bfebc5712e8faec2','PREVIEW'=>true,'HIDDEN'=>$hidden,'TITLE'=>$title,'FIELDS'=>$fields,'TEXT'=>$text,'SUBMIT_NAME'=>$submit_name,'URL'=>$url));
	}

	/**
	 * The actualiser for adding a member.
	 *
	 * @return tempcode		The UI
	 */
	function step2()
	{
		$title=get_page_title('ADD_MEMBER');

		// Read in data
		$username=trim(post_param('username'));
		$password=trim(post_param('password'));
	/*	$password_confirm=trim(post_param('password_confirm'));
		if ($password!=$password_confirm) warn_exit(make_string_tempcode(escape_html(do_lang('PASSWORD_MISMATCH'))));*/
		$email_address=trim(post_param('email_address',''));
		$dob_day=post_param_integer('dob_day',NULL);
		$dob_month=post_param_integer('dob_month',NULL);
		$dob_year=post_param_integer('dob_year',NULL);
		$reveal_age=post_param_integer('reveal_age',0);
		$timezone=post_param('timezone',get_site_timezone());
		$language=post_param('language',get_site_default_lang());
		$allow_emails=post_param_integer('allow_emails',0);
		$allow_emails_from_staff=post_param_integer('allow_emails_from_staff',0);
		$custom_fields=ocf_get_all_custom_fields_match(ocf_get_all_default_groups(true));
		$actual_custom_fields=ocf_read_in_custom_fields($custom_fields);
		$validated=post_param_integer('validated',0);
		$primary_group=(has_specific_permission(get_member(),'assume_any_member'))?post_param_integer('primary_group'):NULL;
		$theme=post_param('theme','');
		$views_signatures=post_param_integer('views_signatures',0);
		$preview_posts=post_param_integer('preview_posts',0);
		$auto_monitor_contrib_content=post_param_integer('auto_monitor_contrib_content',0);
		$pt_allow=array_key_exists('pt_allow',$_POST)?implode(',',$_POST['pt_allow']):'';
		$tmp_groups=$GLOBALS['OCF_DRIVER']->get_usergroup_list(true,true);
		$all_pt_allow='';
		foreach (array_keys($tmp_groups) as $key)
		{
			if ($key!=db_get_first_id())
			{
				if ($all_pt_allow!='') $all_pt_allow.=',';
				$all_pt_allow.=strval($key);
			}
		}
		if ($pt_allow==$all_pt_allow) $pt_allow='*';
		$pt_rules_text=post_param('pt_rules_text','');

		breadcrumb_set_parents(array(array('_SEARCH:admin_ocf_join:menu',do_lang_tempcode('MEMBERS')),array('_SELF:_SELF:misc',do_lang_tempcode('ADD_MEMBER'))));
		breadcrumb_set_self(do_lang_tempcode('DETAILS'));

		// Add member
		$id=ocf_make_member($username,$password,$email_address,NULL,$dob_day,$dob_month,$dob_year,$actual_custom_fields,$timezone,$primary_group,$validated,time(),NULL,'',NULL,'',0,$preview_posts,$reveal_age,'','','',$views_signatures,$auto_monitor_contrib_content,$language,$allow_emails,$allow_emails_from_staff,'','','',true,'','',post_param_integer('zone_wide',0),NULL,NULL,post_param_integer('highlighted_name',0),$pt_allow,$pt_rules_text);

		// Secondary groups
		if (array_key_exists('secondary_groups',$_POST))
		{
			require_code('ocf_groups_action2');
			$members_groups=array();
			$group_count=$GLOBALS['FORUM_DB']->query_value('f_groups','COUNT(*)');
			$groups=list_to_map('id',$GLOBALS['FORUM_DB']->query_select('f_groups',array('*'),($group_count>200)?array('g_is_private_club'=>0):NULL));
			foreach ($_POST['secondary_groups'] as $group_id)
			{
				$group=$groups[intval($group_id)];

				if (($group['g_hidden']==1) && (!in_array($group['id'],$members_groups)) && (!has_specific_permission(get_member(),'see_hidden_groups'))) continue;

				if ((in_array($group['id'],$members_groups)) || (has_specific_permission(get_member(),'assume_any_member')) || ($group['g_open_membership']==1))
					ocf_add_member_to_group($id,$group['id']);
			}
		}

		$special_links=array();

		if (addon_installed('galleries'))
		{
			require_lang('galleries');
			$special_links[]=array('galleries',array('cms_galleries',array('type'=>'gimp','id'=>$id),get_module_zone('cms_galleries')),do_lang('ADD_GALLERY'));
		}

		require_code('templates_donext');
		return do_next_manager($title,do_lang_tempcode('SUCCESS'),
						NULL,
						NULL,
						/*		TYPED-ORDERED LIST OF 'LINKS'		*/
						/*	 page	 params				  zone	  */
						array('_SELF',array('type'=>'misc'),'_SELF'),								 // Add one
						NULL,// Edit this
						NULL,																						// Edit one
						array('members',array('type'=>'view','id'=>$id),get_module_zone('members')),		 // View this
						array('members',array('type'=>'misc'),get_module_zone('members'),do_lang_tempcode('MEMBERS')),				// View archive
						NULL,						// Add to category
						NULL,							 // Add one category
						NULL,							 // Edit one category
						NULL,  // Edit this category
						NULL,						// View this category
						/*	  SPECIALLY TYPED 'LINKS'				  */
						$special_links,
						NULL,
						NULL,
						NULL,
						NULL,
						do_lang_tempcode('MEMBERS')
		);
	}

	/**
	 * The UI for managing temporary usergroup memberships.
	 *
	 * @return tempcode		The UI
	 */
	function group_member_timeouts()
	{
		$title=get_page_title('GROUP_MEMBER_TIMEOUTS');

		if (!cron_installed()) attach_message(do_lang_tempcode('CRON_NEEDED_TO_WORK',escape_html(brand_base_url().'/docs'.strval(ocp_version()).'/pg/tut_configuration')),'warn');

		$GLOBALS['HELPER_PANEL_PIC']='pagepics/usergroups_temp';

		breadcrumb_set_parents(array(array('_SEARCH:admin_ocf_join:menu',do_lang_tempcode('MEMBERS'))));

		require_code('form_templates');
		require_code('templates_results_table');

		$start=get_param_integer('start',0);
		$max=get_param_integer('max',100);
		$max_rows=$GLOBALS[(get_forum_type()=='ocf')?'FORUM_DB':'SITE_DB']->query_value('f_group_member_timeouts','COUNT(*)');
		$fields_title=results_field_title(array(
			do_lang_tempcode('USERNAME'),
			do_lang_tempcode('_USERGROUP'),
			do_lang_tempcode('TIME'),
		));

		$timeouts=$GLOBALS[(get_forum_type()=='ocf')?'FORUM_DB':'SITE_DB']->query_select('f_group_member_timeouts',array('member_id','group_id','timeout'),NULL,'',$max,$start);

		$usergroups=$GLOBALS['FORUM_DRIVER']->get_usergroup_list();

		$tfields=new ocp_tempcode();
		foreach ($timeouts as $timeout)
		{
			$tfields->attach(results_entry(array(
				$GLOBALS['FORUM_DRIVER']->get_username($timeout['member_id']),
				isset($usergroups[$timeout['group_id']])?$usergroups[$timeout['group_id']]:do_lang('UNKNOWN'),
				display_time_period($timeout['timeout']-time()),
			),true));
		}

		$results_table=results_table(do_lang('GROUP_MEMBER_TIMEOUTS'),$start,'start',$max,'max',$max_rows,$fields_title,$tfields);

		$fields=new ocp_tempcode();
		$fields->attach(form_input_username(do_lang_tempcode('USERNAME'),'','username','',true));
		$_usergroups=new ocp_tempcode();
		foreach ($usergroups as $uid=>$name)
		{
			if ($uid!=db_get_first_id())
				$_usergroups->attach(form_input_list_entry($uid,false,$name));
		}
		require_lang('dates');
		$fields->attach(form_input_list(do_lang_tempcode('_USERGROUP'),'','group_id',$_usergroups,NULL,false,true));
		$fields->attach(form_input_integer(do_lang_tempcode('_MINUTES'),do_lang_tempcode('DESCRIPTION_GROUPMT_MINUTES'),'num_minutes',60,true));

		$post_url=build_url(array('page'=>'_SELF','type'=>'_group_member_timeouts'),'_SELF');
		$submit_name=do_lang_tempcode('ADD');

		$form=do_template('FORM',array('TABINDEX'=>strval(get_form_field_tabindex()),'HIDDEN'=>'','TEXT'=>'','FIELDS'=>$fields,'URL'=>$post_url,'SUBMIT_NAME'=>$submit_name));

		return do_template('RESULTS_TABLE_SCREEN',array('TITLE'=>$title,'RESULTS_TABLE'=>$results_table,'FORM'=>$form));
	}

	/**
	 * The actualiser for managing temporary usergroup memberships.
	 *
	 * @return tempcode		The UI
	 */
	function _group_member_timeouts()
	{
		$title=get_page_title('GROUP_MEMBER_TIMEOUTS');

		$group_id=post_param_integer('group_id');

		if (!$GLOBALS['FORUM_DRIVER']->is_super_admin(get_member())) // Security issue, don't allow privilege elevation
		{
			$admin_groups=$GLOBALS['FORUM_DRIVER']->get_super_admin_groups();
			if (in_array($group_id,$admin_groups)) warn_exit(do_lang_tempcode('INTERNAL_ERROR'));
		}

		$username=post_param('username');
		$num_minutes=post_param_integer('num_minutes');
		$prefer_for_primary_group=false;//(post_param_integer('prefer_for_primary_group',0)==1); Don't promote this bad choice

		$member_id=$GLOBALS['FORUM_DRIVER']->get_member_from_username($username);
		if (is_null($member_id)) warn_exit(do_lang_tempcode('_USER_NO_EXIST',escape_html($username)));

		require_code('group_member_timeouts');
		bump_member_group_timeout($member_id,$group_id,$num_minutes,$prefer_for_primary_group);

		$url=build_url(array('page'=>'_SELF','type'=>'group_member_timeouts'),'_SELF');

		return redirect_screen($title,$url,do_lang_tempcode('SUCCESS'));
	}

	/**
	 * The UI for choosing delurk criteria.
	 *
	 * @return tempcode		The UI
	 */
	function delurk()
	{
		$title=get_page_title('DELETE_LURKERS');

		breadcrumb_set_parents(array(array('_SEARCH:admin_ocf_join:menu',do_lang_tempcode('MEMBERS'))));

		$GLOBALS['HELPER_PANEL_PIC']='pagepics/deletelurkers';

		require_code('form_templates');

		require_lang('ocf_lurkers');

		$hidden=new ocp_tempcode();

		$_max_posts=get_value('delurk__max_posts');
		$_max_points=get_value('delurk__max_points');
		$_max_logged_actions=get_value('delurk__max_logged_actions');
		$_min_days_since_login=get_value('delurk__min_days_since_login');
		$_min_days_since_join=get_value('delurk__min_days_since_join');
		$_usergroups=get_value('delurk__usergroups');
		if (is_null($_max_posts)) $max_posts=2; else $max_posts=intval($_max_posts);
		if (is_null($_max_points)) $max_points=150; else $max_points=intval($_max_points);
		if (is_null($_max_logged_actions)) $max_logged_actions=2; else $max_logged_actions=intval($_max_logged_actions);
		if (is_null($_min_days_since_login)) $min_days_since_login=60; else $min_days_since_login=intval($_min_days_since_login);
		if (is_null($_min_days_since_join)) $min_days_since_join=90; else $min_days_since_join=intval($_min_days_since_join);
		if (is_null($_usergroups))
		{
			$usergroups=array();
		} else
		{
			$temp=explode(',',$_usergroups);
			$usergroups=array();
			foreach ($temp as $t)
			{
				$usergroups[]=intval($t);
			}
		}

		$fields=new ocp_tempcode();
		$fields->attach(form_input_integer(do_lang_tempcode('DELURK_MAX_POSTS'),do_lang_tempcode('DELURK_MAX_POSTS_DESCRIPTION'),'max_posts',$max_posts,true));
		if (addon_installed('points'))
		{
			$fields->attach(form_input_integer(do_lang_tempcode('DELURK_MAX_POINTS'),do_lang_tempcode('DELURK_MAX_POINTS_DESCRIPTION'),'max_points',$max_points,true));
		} else
		{
			$hidden->attach(form_input_hidden('max_points','0'));
		}
		$fields->attach(form_input_integer(do_lang_tempcode('DELURK_MAX_LOGGED_ACTIONS'),do_lang_tempcode('DELURK_MAX_LOGGED_ACTIONS_DESCRIPTION'),'max_logged_actions',$max_logged_actions,true));
		$fields->attach(form_input_integer(do_lang_tempcode('DELURK_MIN_DAYS_SINCE_LOGIN'),do_lang_tempcode('DELURK_MIN_DAYS_SINCE_LOGIN_DESCRIPTION'),'min_days_since_login',$min_days_since_login,true));
		$fields->attach(form_input_integer(do_lang_tempcode('DELURK_MIN_DAYS_SINCE_JOIN'),do_lang_tempcode('DELURK_MIN_DAYS_SINCE_JOIN_DESCRIPTION'),'min_days_since_join',$min_days_since_join,true));
		$groups=new ocp_tempcode();
		$group_count=$GLOBALS['FORUM_DB']->query_value('f_groups','COUNT(*)');
		$rows=$GLOBALS['FORUM_DB']->query_select('f_groups',array('id','g_name'),($group_count>200)?array('g_is_private_club'=>0):NULL);
		foreach ($rows as $row)
		{
			if ($row['id']!=db_get_first_id())
				$groups->attach(form_input_list_entry(strval($row['id']),in_array($row['id'],$usergroups),get_translated_text($row['g_name'],$GLOBALS['FORUM_DB'])));
		}
		$fields->attach(form_input_multi_list(do_lang_tempcode('EXCEPT_IN_USERGROUPS'),do_lang_tempcode('DELURK_USERGROUPS_DESCRIPTION'),'usergroups',$groups));

		$submit_name=do_lang_tempcode('PROCEED');
		$post_url=build_url(array('page'=>'_SELF','type'=>'_delurk'),'_SELF');
		$text=do_lang_tempcode('CHOOSE_DELURK_CRITERIA');

		return do_template('FORM_SCREEN',array('_GUID'=>'f911fc5be2865bdd065abf7c636530d4','TITLE'=>$title,'HIDDEN'=>$hidden,'FIELDS'=>$fields,'URL'=>$post_url,'TEXT'=>$text,'SUBMIT_NAME'=>$submit_name));
	}

	/**
	 * Find a mapping of member IDs to usernames, of those who'll get delurked.
	 *
	 * @param  integer			Maximum forum posts
	 * @param  integer			Maximum points
	 * @param  integer			Maximum logged actions
	 * @param  integer			Minimum days since last login
	 * @param  integer			Minimum days since joining
	 * @param  array				List of usergroups
	 * @return array				Mapping of lurkers
	 */
	function find_lurkers($max_posts,$max_points,$max_logged_actions,$min_days_since_login,$min_days_since_join,$usergroups)
	{
		$start=0;
		do
		{
			$rows=$GLOBALS['FORUM_DB']->query('SELECT id,m_username FROM '.$GLOBALS['FORUM_DB']->get_table_prefix().'f_members WHERE id<>'.strval($GLOBALS['FORUM_DRIVER']->get_guest_id()).' AND m_cache_num_posts<'.strval(intval($max_posts)).' AND m_last_visit_time<'.strval(time()-$min_days_since_login*60*60*24).' AND m_join_time<'.strval(time()-$min_days_since_join*60*60*24),500,$start);
			$out=array();
			if (addon_installed('points'))
			{
				require_code('points');
			}
			foreach ($rows as $row)
			{
				if (addon_installed('points'))
				{
					if (total_points($row['id'])>$max_points) continue;
				}
				$_usergroups=$GLOBALS['FORUM_DRIVER']->get_members_groups($row['id']);
				foreach ($_usergroups as $g_id)
				{
					if (in_array($g_id,$usergroups)) continue 2;
				}
				$num_actions=$GLOBALS['SITE_DB']->query_value('adminlogs','COUNT(*)',array('the_user'=>$row['id']));
				if ($num_actions>$max_logged_actions) continue;

				if (count($out)==500)
				{
					attach_message(do_lang_tempcode('TOO_MANY_LURKERS'),'warn');
					return $out;
				}

				$out[$row['id']]=$row['m_username'];
			}
			$start+=500;
		}
		while (count($rows)==500);

		return $out;
	}

	/**
	 * The UI for confirming the deletion results of delurk criteria.
	 *
	 * @return tempcode		The UI
	 */
	function _delurk()
	{
		$title=get_page_title('DELETE_LURKERS');

		if (function_exists('set_time_limit')) @set_time_limit(100);

		require_lang('ocf_lurkers');

		$GLOBALS['HELPER_PANEL_PIC']='pagepics/deletelurkers';

		$max_posts=post_param_integer('max_posts');
		$max_points=post_param_integer('max_points');
		$max_logged_actions=post_param_integer('max_logged_actions');
		$min_days_since_login=post_param_integer('min_days_since_login');
		$min_days_since_join=post_param_integer('min_days_since_join');
		$usergroups=array();
		if (array_key_exists('usergroups',$_POST))
			foreach ($_POST['usergroups'] as $g_id)
				$usergroups[]=intval($g_id);
		$lurkers=$this->find_lurkers($max_posts,$max_points,$max_logged_actions,$min_days_since_login,$min_days_since_join,$usergroups);

		if (count($lurkers)==0) inform_exit(do_lang_tempcode('NO_LURKERS_FOUND'));

		$_lurkers=array();
		foreach ($lurkers as $id=>$username)
		{
			if (is_guest($id)) warn_exit(do_lang_tempcode('INTERNAL_ERROR'));

			$_lurkers[]=array('ID'=>strval($id),'USERNAME'=>$username,'PROFILE_URL'=>$GLOBALS['FORUM_DRIVER']->member_profile_url($id,false,true));
		}

		$url=build_url(array('page'=>'_SELF','type'=>'__delurk'),'_SELF');

		breadcrumb_set_parents(array(array('_SEARCH:admin_ocf_join:menu',do_lang_tempcode('MEMBERS')),array('_SEARCH:admin_ocf_join:delurk',do_lang_tempcode('DELETE_LURKERS'))));
		breadcrumb_set_self(do_lang_tempcode('CONFIRM'));

		return do_template('OCF_DELURK_CONFIRM',array('_GUID'=>'52870b8546653782e354533602531970','TITLE'=>$title,'LURKERS'=>$_lurkers,'URL'=>$url));
	}

	/**
	 * The actualiser for deletion members according to delurk criteria.
	 *
	 * @return tempcode		The UI
	 */
	function __delurk()
	{
		$title=get_page_title('DELETE_LURKERS');

		$GLOBALS['HELPER_PANEL_PIC']='pagepics/deletelurkers';

		require_lang('ocf_lurkers');

		foreach($_POST as $key=>$val)
		{
			if (substr($key,0,7)=='lurker_')
			{
				$member_id=intval(substr($key,7));
				ocf_delete_member($member_id);
			}
		}

		breadcrumb_set_parents(array(array('_SEARCH:admin_ocf_join:menu',do_lang_tempcode('MEMBERS')),array('_SEARCH:admin_ocf_join:delurk',do_lang_tempcode('DELETE_LURKERS'))));

		return inform_screen($title,do_lang_tempcode('SUCCESS'));
	}

	/**
	 * Get field mapping data for CSV import/export.
	 *
	 * @return array		A map of heading information (human name to field name/encoding details)
	 */
	function _get_csv_headings()
	{
		$headings=array(
			'ID'=>'id',
			'Username'=>'m_username',
			'E-mail address'=>'m_email_address',
			'Password'=>'m_pass_hash_salted/m_pass_salt/m_password_compat_scheme'
		);
		if (addon_installed('ocf_member_avatars')) $headings+=array(
			'Avatar'=>'#m_avatar_url',
		);
		if (addon_installed('ocf_member_photos')) $headings+=array(
			'Photo'=>'#m_photo_url',
		);
		$headings+=array(
			'Signature'=>'*m_signature',
			'Validated'=>'!m_validated',
			'Join time'=>'&m_join_time',
			'Last visit'=>'&m_last_visit_time',
			'Number of posts'=>'m_cache_num_posts',
			'Usergroup'=>'@m_primary_group',
			'Banned'=>'!m_is_perm_banned',
			'Date of birth'=>'m_dob_year/m_dob_month/m_dob_day',
			'Reveal age'=>'!m_reveal_age',
			'Language'=>'m_language',
			'Accept member e-mails'=>'!m_allow_emails',
			'Opt-in'=>'!m_allow_emails_from_staff',
		);
		return $headings;
	}

	/**
	 * The actualiser to download a CSV of members.
	 */
	function download_csv()
	{
		$filename='members-'.date('Y-m-d').'.csv';

		if (function_exists('set_time_limit')) @set_time_limit(0);

		header('Content-type: text/csv');
		if (strstr(ocp_srv('HTTP_USER_AGENT'),'MSIE')!==false)
			header('Content-Disposition: filename="'.str_replace(chr(13),'',str_replace(chr(10),'',addslashes($filename))).'"');
		else
			header('Content-Disposition: attachment; filename="'.str_replace(chr(13),'',str_replace(chr(10),'',addslashes($filename))).'"');

		@ini_set('ocproducts.xss_detect','0');

		$fields=array('id','m_username','m_email_address','m_last_visit_time','m_cache_num_posts','m_pass_hash_salted','m_pass_salt','m_password_compat_scheme','m_signature','m_validated','m_join_time','m_primary_group','m_is_perm_banned','m_dob_day','m_dob_month','m_dob_year','m_reveal_age','m_language','m_allow_emails','m_allow_emails_from_staff','m_notes');
		if (addon_installed('ocf_member_avatars')) $fields[]='m_avatar_url';
		if (addon_installed('ocf_member_photos')) $fields[]='m_photo_url';
		$groups=$GLOBALS['FORUM_DRIVER']->get_usergroup_list(false,false,true);
		$member_groups_count=$GLOBALS['FORUM_DB']->query_value('f_group_members','COUNT(*)',array('gm_validated'=>1));
		if ($member_groups_count<500)
		{
			$member_groups=$GLOBALS['FORUM_DB']->query_select('f_group_members',array('gm_member_id','gm_group_id'),array('gm_validated'=>1));
		} else $member_groups=array();
		$cpfs=$GLOBALS['FORUM_DB']->query_select('f_custom_fields',array('id','cf_type','cf_name'),NULL,'ORDER BY cf_order');
		$member_count=$GLOBALS['FORUM_DB']->query_value('f_members','COUNT(*)');
		if ($member_count<700)
		{
			$member_cpfs=list_to_map('mf_member_id',$GLOBALS['FORUM_DB']->query_select('f_member_custom_fields',array('*')));
		} else
		{
			$member_cpfs=array();
		}

		$headings=$this->_get_csv_headings();
		foreach ($cpfs as $i=>$c) // CPFs take precedence over normal fields of the same name
		{
			$cpfs[$i]['text_original']=get_translated_text($c['cf_name'],$GLOBALS['FORUM_DB']);
			$headings[$cpfs[$i]['text_original']]=NULL;
		}

		foreach (array_keys($headings) as $i=>$h)
		{
			if ($i!=0) echo ',';
			echo '"'.str_replace('"','""',$h).'"';
		}
		echo chr(10);

		$at=mixed();

		$limit=get_param_integer('max',200); // Set 'max' if you don't want all records

		$start=0;
		do
		{
			$members=$GLOBALS['FORUM_DB']->query_select('f_members',$fields,NULL,'',$limit,$start);

			if ($member_count>=700)
			{
				$or_list='';
				foreach ($members as $m)
				{
					if ($or_list!='') $or_list.=' OR ';
					$or_list.='mf_member_id='.strval($m['id']);
				}
				$member_cpfs=list_to_map('mf_member_id',$GLOBALS['FORUM_DB']->query('SELECT * FROM '.$GLOBALS['FORUM_DB']->get_table_prefix().'f_member_custom_fields WHERE '.$or_list));
			}

			foreach ($members as $m)
			{
				if (is_guest($m['id'])) continue;

				if ($member_groups_count>=500)
				{
					$member_groups=$GLOBALS['FORUM_DB']->query_select('f_group_members',array('gm_member_id','gm_group_id'),array('gm_validated'=>1,'gm_member_id'=>$m['id']));
				}

				$out=$this->_get_csv_member_record($member_cpfs,$m,$groups,$headings,$cpfs,$member_groups);
				$i=0;
				foreach ($out as $wider)
				{
					if ($i!=0) echo ',';
					echo '"'.str_replace('"','""',$wider).'"';
					$i++;
				}
				echo chr(10);
			}

			$start+=200;

			flush();
		}
		while (count($members)==200);

		$GLOBALS['SCREEN_TEMPLATE_CALLED']='';
		exit();
	}

	/**
	 * Get a CSV-outputtable row for a member.
	 *
	 * @param  array			A map of member CPF maps
	 * @param  array			Member row
	 * @param  array			Map of usergroup details
	 * @param  array			List of headings to pull from the member row
	 * @param  array			List of CPFS to pull
	 * @param  array			List of member group membership records
	 * @return array			The row
	 */
	function _get_csv_member_record($member_cpfs,$m,$groups,$headings,$cpfs,$member_groups)
	{
		$at=mixed();
		$out=array();
		$i=0;
		foreach ($headings as $written_heading=>$f)
		{
			if (is_null($f)) continue;
			$parts=explode('/',$f);
			$wider='';
			foreach ($parts as $part)
			{
				switch (substr($part,0,1))
				{
					case '*': // lang string
						$at=get_translated_text($m[substr($part,1)],$GLOBALS['FORUM_DB']);
						break;

					case '!': // binary
						$at=($m[substr($part,1)]==1)?'Yes':'No'; // Hard-coded in English, because we need a multi-language standard
						break;

					case '&': // timestamp
						$at=date('Y-m-d',intval($m[substr($part,1)]));
						break;

					case '#': // url
						$at=$m[substr($part,1)];
						if ((url_is_local($at)) && ($at!='')) $at=get_complex_base_url($at).'/'.$at;
						break;

					case '@': // append other groups
						$at=isset($groups[$m[substr($part,1)]])?$groups[$m[substr($part,1)]]:'';

						foreach ($member_groups as $g)
						{
							if ($g['gm_member_id']==$m['id'])
							{
								if (array_key_exists($g['gm_group_id'],$groups))
									$at.='/'.$groups[$g['gm_group_id']];
							}
						}
						break;

					default: // string
						$at=$m[$part];
						break;
				}
				if ($wider!='') $wider.='/';
				$wider.=is_integer($at)?strval($at):(is_null($at)?'':$at);
			}
			$out[$written_heading]=$wider;

			$i++;
		}
		foreach ($cpfs as $c)
		{
			if (!array_key_exists($m['id'],$member_cpfs))
			{
				$at='';
			} else
			{
				$at=$member_cpfs[$m['id']]['field_'.strval($c['id'])];
				if (is_null($at))
				{
					$at='';
				} else
				{
					if (strpos($c['cf_type'],'_trans')!==false)
					{
						$at=get_translated_text($at);
					} elseif (!is_string($at))
					{
						$at=strval($at);
					}
				}
			}
			$out[$c['text_original']]=$at;
		}
		return $out;
	}

	/**
	 * The UI for importing a CSV file.
	 *
	 * @return tempcode		The UI
	 */
	function import_csv()
	{
		$title=get_page_title('IMPORT_MEMBER_CSV');

		breadcrumb_set_parents(array(array('_SEARCH:admin_ocf_join:menu',do_lang_tempcode('MEMBERS'))));

		$GLOBALS['HELPER_PANEL_PIC']='pagepics/import_csv';

		require_code('form_templates');

		require_lang('ocf');

		$hidden=new ocp_tempcode();

		$fields=new ocp_tempcode();
		handle_max_file_size($hidden);
		$fields->attach(form_input_upload(do_lang_tempcode('UPLOAD'),do_lang_tempcode('DESCRIPTION_IMPORT_CSV'),'file',true,NULL,NULL,true,'csv,txt'));
		$fields->attach(form_input_line(do_lang_tempcode('DEFAULT_PASSWORD'),do_lang_tempcode('DESCRIPTION_DEFAULT_PASSWORD'),'default_password','',false));

		$submit_name=do_lang_tempcode('IMPORT_MEMBER_CSV');
		$post_url=build_url(array('page'=>'_SELF','type'=>'_import_csv'),'_SELF');
		$text='';

		return do_template('FORM_SCREEN',array('TITLE'=>$title,'HIDDEN'=>$hidden,'FIELDS'=>$fields,'URL'=>$post_url,'TEXT'=>$text,'SUBMIT_NAME'=>$submit_name));
	}

	/**
	 * The actualiser for importing a CSV file.
	 *
	 * @return tempcode		The UI
	 */
	function _import_csv()
	{
		$title=get_page_title('IMPORT_MEMBER_CSV');

		$GLOBALS['HELPER_PANEL_PIC']='pagepics/import_csv';

		if (function_exists('set_time_limit')) @set_time_limit(0);

		require_lang('ocf');
		require_lang('import');
		require_code('ocf_members_action');

		$default_password=post_param('default_password');
		$num_added=0;
		$num_edited=0;
		$done=0;

		$headings=$this->_get_csv_headings();
		$all_cpfs=$GLOBALS['FORUM_DB']->query_select('f_custom_fields',array('id','cf_default','cf_type','cf_name'),NULL,'ORDER BY cf_order');
		foreach ($all_cpfs as $i=>$c) // CPFs take precedence over normal fields of the same name
		{
			$c['text_original']=get_translated_text($c['cf_name'],$GLOBALS['FORUM_DB']);
			$all_cpfs[$i]=$c;
			$headings[$c['text_original']]=NULL;
		}
		$_all_groups=$GLOBALS['FORUM_DRIVER']->get_usergroup_list(false,false,true);
		$all_groups=array_flip($_all_groups);
		$all_members=collapse_2d_complexity('id','m_username',$GLOBALS['FORUM_DB']->query_select('f_members',array('id','m_username')));
		$all_members_flipped=array_flip($all_members);

		// Import
		require_code('uploads');
		if ((is_swf_upload(true)) || ((array_key_exists('file',$_FILES)) && (is_uploaded_file($_FILES['file']['tmp_name']))))
		{
			$_csv_data=array();

			$fixed_contents=unixify_line_format(file_get_contents($_FILES['file']['tmp_name']));
			$myfile=@fopen($_FILES['file']['tmp_name'],'wb');
			if ($myfile!==false)
			{
				fwrite($myfile,$fixed_contents);
				fclose($myfile);
			}

			$myfile=fopen($_FILES['file']['tmp_name'],'rb');
			$del=',';
			$csv_header=fgetcsv($myfile,102400,$del);
			if ($csv_header===false) warn_exit(do_lang_tempcode('NO_DATA_IMPORTED'));
			if ((count($csv_header)==1) && (strpos($csv_header[0],';')!==false))
			{
				$del=';';
				rewind($myfile);
				$csv_header=fgetcsv($myfile,102400,$del);
			}
			while (($csv_line=fgetcsv($myfile,102400,$del))!==false)
			{
				$line=array();
				foreach ($csv_header as $i=>$h)
				{
					$extracted_value=trim(unixify_line_format(array_key_exists($i,$csv_line)?$csv_line[$i]:''));

					if (strpos($h,':')!==false) // Special syntax to allow merging of columns together into a single multi-line field
					{
						$parts=explode(':',$h,2);
						$h=trim($parts[0]);
						if ($extracted_value!='') $extracted_value=$parts[1].': '.$extracted_value;
					}

					if (array_key_exists($h,$line))
					{
						if ($extracted_value!='') $line[$h].=(($line[$h]!='')?chr(10):'').$extracted_value;
					} else
					{
						$line[$h]=$extracted_value;
					}
				}

				if ((!array_key_exists('Username',$line)) || ($line['Username']==''))
				{
					// Can we auto-generate it
					$forename=NULL;
					if (array_key_exists('Forenames',$line)) $forename=$line['Forenames'];
					if (array_key_exists('Forename',$line)) $forename=$line['Forename'];
					if (array_key_exists('First name',$line)) $forename=$line['First name'];
					if (array_key_exists('First Name',$line)) $forename=$line['First Name'];
					$surname=NULL;
					if (array_key_exists('Surname',$line)) $surname=$line['Surname'];
					if (array_key_exists('Last name',$line)) $surname=$line['Last name'];
					if (array_key_exists('Last Name',$line)) $surname=$line['Last Name'];
					if ((!is_null($forename)) || (!is_null($surname)))
					{
						// Can we get a year too?
						$year='';
						foreach ($line as $tl_key=>$tl_val)
						{
							if (substr($tl_key,0,4)=='Year')
							{
								$year=$tl_val;
								break;
							}
						}
						if ((strlen($year)==4) && ((substr($year,0,2)=='19') || (substr($year,0,2)=='20'))) $year=substr($year,2);

						// Tidy up forename
						$_forename=preg_replace('#[^\w]#','',preg_replace('#[\s\.].*#','',$forename));

						// Tidy up surname (last bit strips like 'OBE')
						$_surname=preg_replace('#[^\w]#','',trim(preg_replace('#\s*[A-Z\d][A-Z\d]+#','',$surname)));

						// Put it together
						$line['Username']=ucfirst($_forename).ucfirst($_surname).$year;
					} else
					{
						continue; // This field is needed
					}
				}

				$username=$line['Username'];

				$linked_id=NULL;
				if (array_key_exists('ID',$line)) $linked_id=(($line['ID']!='')&&(array_key_exists(intval($line['ID']),$all_members)))?intval($line['ID']):NULL;
				if (is_null($linked_id)) $linked_id=array_key_exists($username,$all_members_flipped)?$all_members_flipped[$username]:NULL;
				$new_member=is_null($linked_id);

				$email_address_key='E-mail address';
				if (array_key_exists('Email address',$line)) $email_address_key='Email address';
				if (array_key_exists('E-mail Address',$line)) $email_address_key='E-mail Address';
				if (array_key_exists('Email Address',$line)) $email_address_key='Email Address';
				if (array_key_exists('E-mail',$line)) $email_address_key='E-mail';
				if (array_key_exists('Email',$line)) $email_address_key='Email';

				$dob_key='Date of birth';
				if (array_key_exists('Date Of Birth',$line)) $dob_key='Date Of Birth';
				if (array_key_exists('DOB',$line)) $dob_key='DOB';

				// If it's an edited member, add in their existing CSV details, so that if it's a partial merge it'll still work without deleting anything!
				if (!$new_member)
				{
					$member_groups=$GLOBALS['FORUM_DB']->query_select('f_group_members',array('gm_member_id','gm_group_id'),array('gm_validated'=>1,'gm_member_id'=>$linked_id));
					$member_cpfs=list_to_map('mf_member_id',$GLOBALS['FORUM_DB']->query_select('f_member_custom_fields',array('*'),array('mf_member_id'=>$linked_id),'',1));
					$this_record=$this->_get_csv_member_record($member_cpfs,$GLOBALS['FORUM_DRIVER']->get_member_row($linked_id),$_all_groups,$headings,$all_cpfs,$member_groups); // Remember "+" in PHP won't overwrite existing keys
					if (!array_key_exists($email_address_key,$line)) unset($this_record['E-mail address']);
					if (!array_key_exists($dob_key,$line)) unset($this_record['Date of birth']);
					$line+=$this_record;
				}

				// Set up member row
				if ((array_key_exists('Password',$line)) && ($line['Password']!=''))
				{
					$parts=explode('/',$line['Password']);
					$password=$parts[0];
					$salt=array_key_exists(1,$parts)?$parts[1]:NULL;
					$password_compatibility_scheme=array_key_exists(2,$parts)?$parts[2]:NULL;
				} else
				{
					$password=NULL;
					$salt=NULL;
					$password_compatibility_scheme=NULL;
				}
				$matches=array();
				if (array_key_exists($email_address_key,$line)) $email_address=$line[$email_address_key]; else $email_address=NULL;
				if (preg_match('#^([^\s]*)\s+\(.*\)$#',$email_address,$matches)!=0) $email_address=$matches[1];
				if (preg_match('#^.*\s+<(.*)>$#',$email_address,$matches)!=0) $email_address=$matches[1];
				if (array_key_exists($dob_key,$line))
				{
					$parts=explode('/',$line[$dob_key]);
					$dob_day=array_key_exists(2,$parts)?intval($parts[2]):NULL;
					$dob_month=array_key_exists(1,$parts)?intval($parts[1]):NULL;
					$dob_year=array_key_exists(0,$parts)?intval($parts[0]):NULL;
				} else
				{
					$dob_day=NULL;
					$dob_month=NULL;
					$dob_year=NULL;
				}
				$validated=array_key_exists('Validated',$line)?((strtoupper($line['Validated'])=='YES' || $line['Validated']=='1' || strtoupper($line['Validated'])=='Y' || strtoupper($line['Validated'])=='ON')?1:0):1;
				if (array_key_exists('Join time',$line))
				{
					if (strpos($line['Join time'],'-')!==false)
					{
						$parts=explode('-',$line['Join time']);
					} else
					{
						$parts=explode('/',$line['Join time']);
					}
					if (!array_key_exists(1,$parts)) $parts[1]='1';
					if (!array_key_exists(2,$parts)) $parts[2]='1';
					if (strlen($parts[2])!=4) // Would be nice to be smarter but unfortunately Open Office saves as yy not yyyy
					{
						$join_time=mktime(0,0,0,intval($parts[1]),intval($parts[2]),intval($parts[0])); // yy(yy)-mm-dd
					} else
					{
						$join_time=mktime(0,0,0,intval($parts[1]),intval($parts[0]),intval($parts[2])); // dd-mm-yyyy
					}
				} else
				{
					$join_time=NULL;
				}

				$avatar_url=array_key_exists('Avatar',$line)?$line['Avatar']:'';
				if (substr($avatar_url,0,strlen(get_base_url()))==get_base_url()) $avatar_url=substr($avatar_url,strlen(get_base_url()));
				$signature=array_key_exists('Signature',$line)?$line['Signature']:'';
				$is_perm_banned=array_key_exists('Banned',$line)?((strtoupper($line['Banned'])=='YES' || $line['Banned']=='1' || strtoupper($line['Banned'])=='Y' || strtoupper($line['Banned'])=='ON')?1:0):0;
				$reveal_age=array_key_exists('Reveal age',$line)?((strtoupper($line['Reveal age'])=='YES' || $line['Reveal age']=='1' || strtoupper($line['Reveal age'])=='Y' || strtoupper($line['Reveal age'])=='ON')?1:0):0;
				$language=array_key_exists('Language',$line)?$line['Language']:'';
				$allow_emails=array_key_exists('Accept member e-mails',$line)?((strtoupper($line['Accept member e-mails'])=='YES' || $line['Accept member e-mails']=='1' || strtoupper($line['Accept member e-mails'])=='Y' || strtoupper($line['Accept member e-mails'])=='ON')?1:0):0;
				$allow_emails_from_staff=array_key_exists('Opt-in',$line)?((strtoupper($line['Opt-in'])=='YES' || $line['Opt-in']=='1' || strtoupper($line['Opt-in'])=='Y' || strtoupper($line['Opt-in'])=='ON')?1:0):0;
				$primary_group=NULL;
				$groups=NULL;
				if (array_key_exists('Usergroup',$line))
				{
					$parts=explode('/',$line['Usergroup']);
					foreach ($parts as $p)
					{
						if (!array_key_exists($p,$all_groups))
						{
							require_code('ocf_groups_action');
							$g_id=ocf_make_group($p,0,0,0,'');
							$all_groups[$p]=$g_id;
							$_group_edit_url=build_url(array('page'=>'admin_ocf_groups','type'=>'_ed','id'=>$g_id),get_module_zone('admin_ocf_groups'));
							$group_edit_url=$_group_edit_url->evaluate();
							attach_message(do_lang_tempcode('MEMBER_IMPORT_GROUP_ADDED',escape_html($p),escape_html($group_edit_url)),'inform');
						}
					}
					$primary_group=$all_groups[$parts[0]];
					unset($parts[0]);
					$groups=array();
					foreach ($parts as $p)
					{
						$groups[]=$all_groups[$p];
					}
				}
				$photo_url=array_key_exists('Photo',$line)?$line['Photo']:'';
				if ($photo_url!='')
				{
					require_code('images');
					$photo_thumb_url='uploads/ocf_photos_thumbs/'.uniqid('').'.png';
					convert_image($photo_url,$photo_thumb_url,-1,-1,intval(get_option('thumb_width')),false);
				} else $photo_thumb_url='';
				$custom_fields=array();
				foreach ($all_cpfs as $cpf)
				{
					$custom_fields[$cpf['id']]=array_key_exists($cpf['text_original'],$line)?$line[$cpf['text_original']]:$cpf['cf_default'];
					if ((!array_key_exists($cpf['text_original'],$line)) && ($cpf['cf_type']=='list'))
					{
						$parts=explode($custom_fields[$cpf['id']],'|');
						$custom_fields[$cpf['id']]=$parts[0];
					}
					if ($cpf['cf_type']=='integer')
					{
						$custom_fields[$cpf['id']]=intval($custom_fields[$cpf['id']]);
					} elseif ($cpf['cf_type']=='tick')
					{
						$custom_fields[$cpf['id']]=((strtoupper($custom_fields[$cpf['id']])=='YES' || strtoupper($custom_fields[$cpf['id']])=='Y' || strtoupper($custom_fields[$cpf['id']])=='ON' || $custom_fields[$cpf['id']]=='1')?1:0);
					} elseif (($cpf['cf_type']=='short_text') || ($cpf['cf_type']=='short_trans'))
					{
						$custom_fields[$cpf['id']]=substr(str_replace(chr(10),', ',str_replace(','.chr(10),chr(10),$custom_fields[$cpf['id']])),0,255);
					} elseif (($cpf['cf_type']=='long_text') || ($cpf['cf_type']=='long_trans'))
					{
						$custom_fields[$cpf['id']]=$custom_fields[$cpf['id']];
					} elseif ($cpf['cf_type']=='float')
					{
						if (preg_match('#^(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\n(\d\d\d\d)$#',$custom_fields[$cpf['id']])!=0) // Convert to float based date
						{
							$parts=explode(chr(10),$custom_fields[$cpf['id']],2);
							$month_lookup=array(
								'Jan'=>0.1,
								'Feb'=>0.2,
								'Mar'=>0.3,
								'Apr'=>0.4,
								'May'=>0.5,
								'Jun'=>0.6,
								'Jul'=>0.7,
								'Aug'=>0.8,
								'Sep'=>0.9,
								'Oct'=>0.10,
								'Nov'=>0.11,
								'Dec'=>0.12,
							);
							$custom_fields[$cpf['id']]=floatval($parts[1])+$month_lookup[$parts[0]];
						} else
						{
							$custom_fields[$cpf['id']]=floatval($custom_fields[$cpf['id']]);
						}
					}
					unset($line[$cpf['text_original']]);
				}
				foreach (array_keys($headings) as $h) unset($line[$h]);
				unset($line[$email_address_key]);
				unset($line[$dob_key]);
				foreach ($line as $h=>$f) // New CPFs
				{
					$cf_id=ocf_make_custom_field($h,0,'','',0,0,0,0,'long_text');
					$_cpf_edit_url=build_url(array('page'=>'admin_ocf_customprofilefields','type'=>'_ed','id'=>$cf_id),get_module_zone('admin_ocf_customprofilefields'));
					$cpf_edit_url=$_cpf_edit_url->evaluate();
					attach_message(do_lang_tempcode('MEMBER_IMPORT_CPF_ADDED',escape_html($h),escape_html($cpf_edit_url)),'inform');
					$custom_fields[$cf_id]=$f;
					$all_cpfs[]=array('id'=>$cf_id,'cf_default'=>'','text_original'=>$h,'cf_type'=>'short_line');
				}
				if ($new_member)
				{
					if (is_null($password)) $password=$default_password;
					if (is_null($salt)) $salt='';
					if (is_null($password_compatibility_scheme)) $password_compatibility_scheme='';

					$linked_id=ocf_make_member($username,$password,is_null($email_address)?'':$email_address,$groups,$dob_day,$dob_month,$dob_year,$custom_fields,NULL,$primary_group,$validated,$join_time,NULL,'',$avatar_url,$signature,$is_perm_banned,(get_option('default_preview_guests')=='1')?1:0,$reveal_age,'',$photo_url,$photo_thumb_url,1,1,$language,$allow_emails,$allow_emails_from_staff,'',NULL,'',false,$password_compatibility_scheme,$salt,1,NULL,NULL,0,'*','');
					$num_added++;
				} else
				{
					$old_username=$GLOBALS['OCF_DRIVER']->get_member_row_field($linked_id,'m_username');
					if ($old_username==$username) $username=NULL;

					ocf_edit_member($linked_id,$email_address,NULL,$dob_day,$dob_month,$dob_year,NULL,$primary_group,$custom_fields,NULL,$reveal_age,NULL,NULL,$language,$allow_emails,$allow_emails_from_staff,$validated,$username,$password,NULL,NULL,NULL,NULL,NULL,$join_time,$avatar_url,$signature,$is_perm_banned,$photo_url,$photo_thumb_url,$salt,$password_compatibility_scheme,true);
					$num_edited++;
				}

				$done++;
			}
			fclose($myfile);
		} else warn_exit(do_lang_tempcode('IMPROPERLY_FILLED_IN_UPLOAD'));

		if ($done==0) warn_exit(do_lang_tempcode('NO_DATA_IMPORTED'));

		breadcrumb_set_parents(array(array('_SEARCH:admin_ocf_join:menu',do_lang_tempcode('MEMBERS')),array('_SEARCH:admin_ocf_join:import_csv',do_lang_tempcode('IMPORT_MEMBER_CSV'))));
		breadcrumb_set_self(do_lang_tempcode('DONE'));

		return inform_screen($title,do_lang_tempcode('NUM_MEMBERS_IMPORTED',escape_html(integer_format($num_added)),escape_html(integer_format($num_edited))));
	}

}


