Recordad que para pedir soporte alguno, debéis facilitar los datos de soporte oportunos por favor, mirad aquí y leer las Normas generales del foro, esto nos servirá de ayuda para dar el mejor soporte..

Gracias.

La Administración de phpBB España.

Multiregistro desde página externa phpBB para dos forosTema Solucionado

Soporte de MODs para phpBB 3.0.x
Dudas sobre AutoMOD aquí por favor.
Cerrado

0
No hay votos
 
Votos totales: 0

dankko.chicho
Usuario/a
Mensajes: 68
Registrado: 06 Sep 2012, 18:07

Multiregistro desde página externa phpBB para dos foros  Tema Solucionado

#1

Mensaje por dankko.chicho »

Tras muchas preguntas, muchos intentos de integración, haber probado otros cms que hicieran de puente... Decidí hacer algo para unir varios foros sin tener que usar más scripts que los propios de phpbb.

Esta modificación está basada en dos foros phpbb instalados EN LA MISMA BASE DE DATOS (si no están en la misma produce errores, por lo que, no lo recomiendo).

¿Qué nos permite esta modificación?

Tener un registro externo, distinto al de phpbb.
Insertar el usuario en la tabla de usuarios correspondiente de cada foro (crea un registro nuevo en cada tabla)
Permisos independientes para el usuario en cada foro (no hay problemas de visualización de los foros, permisos, etc...)
Integración de usuarios para dos foros.
Modificación del formulario de registro externo de alorse para evitar Spambots

Se requiere:

Configuración registro de usuarios (ACP) = Sin activación (Acceso inmediato)
Asignar el grupo Nuevos Usuarios Registrados como grupo por defecto: Sí
Darle permisos al grupo de nuevos usaurios registrados para que puedan ver los foros.
Modificación de archivos
Llamaremos a los foros como Foro 1 y Foro 2.
Empezamos con el FORO 1
1) Abrimos el config.php de foro1 y buscamos:

Código: Seleccionar todo

$table_prefix = 'foro1_';
Y añadimos después:

Código: Seleccionar todo

$table_prefix2 = foro2_';
*Añadimos el prefijo del segundo foro en nuestro config.php. Esto es muy importante porque después vamos a llamar a las tablas del foro 2 desde el archivo constants.php

2) Abrimos includes/constants.php del foro 1 y buscamos:

Código: Seleccionar todo

define('GROUPS_TABLE',				$table_prefix . 'groups');
Y añadimos después:

Código: Seleccionar todo

define('GROUPS_TABLE_2',				$table_prefix2 . 'groups');
Buscamos:

Código: Seleccionar todo

define('USER_GROUP_TABLE',			$table_prefix . 'user_group');
Y Añadimos después:

Código: Seleccionar todo

define('USER_GROUP_TABLE_2',			$table_prefix2 . 'user_group');
Buscamos:

Código: Seleccionar todo

define('USERS_TABLE',				$table_prefix . 'users');
Y añadimos después:

Código: Seleccionar todo

define('USERS_TABLE_2',				$table_prefix2 . 'users');
3) abrimos el archivo includes/functions_user.php y buscamos:

*Cuidado en este paso porque hay que buscar mucho código, ayudaros de las etiquetas que marcan el inicio de las funciones, como por ejemplo, adds an user.

*Este paso es un muy importante.

Código: Seleccionar todo

/**
* Adds an user
*
* @param mixed $user_row An array containing the following keys (and the appropriate values): username, group_id (the group to place the user in), user_email and the user_type(usually 0). Additional entries not overridden by defaults will be forwarded.
* @param string $cp_data custom profile fields, see custom_profile::build_insert_sql_array
* @return the new user's ID.
*/
function user_add($user_row, $cp_data = false)
{
	global $db, $user, $auth, $config, $phpbb_root_path, $phpEx;

	if (empty($user_row['username']) || !isset($user_row['group_id']) || !isset($user_row['user_email']) || !isset($user_row['user_type']))
	{
		return false;
	}

	$username_clean = utf8_clean_string($user_row['username']);

	if (empty($username_clean))
	{
		return false;
	}

	$sql_ary = array(
		'username'			=> $user_row['username'],
		'username_clean'	=> $username_clean,
		'user_password'		=> (isset($user_row['user_password'])) ? $user_row['user_password'] : '',
		'user_pass_convert'	=> 0,
		'user_email'		=> strtolower($user_row['user_email']),
		'user_email_hash'	=> phpbb_email_hash($user_row['user_email']),
		'group_id'			=> $user_row['group_id'],
		'user_type'			=> $user_row['user_type'],
	);

	// These are the additional vars able to be specified
	$additional_vars = array(
		'user_permissions'	=> '',
		'user_timezone'		=> $config['board_timezone'],
		'user_dateformat'	=> $config['default_dateformat'],
		'user_lang'			=> $config['default_lang'],
		'user_style'		=> (int) $config['default_style'],
		'user_actkey'		=> '',
		'user_ip'			=> '',
		'user_regdate'		=> time(),
		'user_passchg'		=> time(),
		'user_options'		=> 230271,
		// We do not set the new flag here - registration scripts need to specify it
		'user_new'			=> 0,

		'user_inactive_reason'	=> 0,
		'user_inactive_time'	=> 0,
		'user_lastmark'			=> time(),
		'user_lastvisit'		=> 0,
		'user_lastpost_time'	=> 0,
		'user_lastpage'			=> '',
		'user_posts'			=> 0,
		'user_dst'				=> (int) $config['board_dst'],
		'user_colour'			=> '',
		'user_occ'				=> '',
		'user_interests'		=> '',
		'user_avatar'			=> '',
		'user_avatar_type'		=> 0,
		'user_avatar_width'		=> 0,
		'user_avatar_height'	=> 0,
		'user_new_privmsg'		=> 0,
		'user_unread_privmsg'	=> 0,
		'user_last_privmsg'		=> 0,
		'user_message_rules'	=> 0,
		'user_full_folder'		=> PRIVMSGS_NO_BOX,
		'user_emailtime'		=> 0,

		'user_notify'			=> 0,
		'user_notify_pm'		=> 1,
		'user_notify_type'		=> NOTIFY_EMAIL,
		'user_allow_pm'			=> 1,
		'user_allow_viewonline'	=> 1,
		'user_allow_viewemail'	=> 1,
		'user_allow_massemail'	=> 1,

		'user_sig'					=> '',
		'user_sig_bbcode_uid'		=> '',
		'user_sig_bbcode_bitfield'	=> '',

		'user_form_salt'			=> unique_id(),
	);
	// Now fill the sql array with not required variables
	foreach ($additional_vars as $key => $default_value)
	{
		$sql_ary[$key] = (isset($user_row[$key])) ? $user_row[$key] : $default_value;
	}

	// Any additional variables in $user_row not covered above?
	$remaining_vars = array_diff(array_keys($user_row), array_keys($sql_ary));

	// Now fill our sql array with the remaining vars
	if (sizeof($remaining_vars))
	{
		foreach ($remaining_vars as $key)
		{
			$sql_ary[$key] = $user_row[$key];
		}
	}

	$sql = 'INSERT INTO ' . USERS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
	$db->sql_query($sql);
	$user_id = $db->sql_nextid();
	
	// Insert Custom Profile Fields
	if ($cp_data !== false && sizeof($cp_data))
	{
		$cp_data['user_id'] = (int) $user_id;

		if (!class_exists('custom_profile'))
		{
			include_once($phpbb_root_path . 'includes/functions_profile_fields.' . $phpEx);
		}

		$sql = 'INSERT INTO ' . PROFILE_FIELDS_DATA_TABLE . ' ' .
			$db->sql_build_array('INSERT', custom_profile::build_insert_sql_array($cp_data));
		$db->sql_query($sql);
	}

	// Place into appropriate group...
	$sql = 'INSERT INTO ' . USER_GROUP_TABLE . ' ' . $db->sql_build_array('INSERT', array(
		'user_id'		=> (int) $user_id,
		'group_id'		=> (int) $user_row['group_id'],
		'user_pending'	=> 0)
	);
	$db->sql_query($sql);

	// Now make it the users default group...
	group_set_user_default($user_row['group_id'], array($user_id), false);

	// Add to newly registered users group if user_new is 1
	if ($config['new_member_post_limit'] && $sql_ary['user_new'])
	{
		$sql = 'SELECT group_id
			FROM ' . GROUPS_TABLE . "
			WHERE group_name = 'NEWLY_REGISTERED'
				AND group_type = " . GROUP_SPECIAL;
		$result = $db->sql_query($sql);
		$add_group_id = (int) $db->sql_fetchfield('group_id');
		$db->sql_freeresult($result);

		if ($add_group_id)
		{
			// Because these actions only fill the log unneccessarily we skip the add_log() entry with a little hack. :/
			$GLOBALS['skip_add_log'] = true;

			// Add user to "newly registered users" group and set to default group if admin specified so.
			if ($config['new_member_group_default'])
			{
				group_user_add($add_group_id, $user_id, false, false, true);
				$user_row['group_id'] = $add_group_id;
			}
			else
			{
				group_user_add($add_group_id, $user_id);
			}

			unset($GLOBALS['skip_add_log']);
		}
	}

	// set the newest user and adjust the user count if the user is a normal user and no activation mail is sent
	if ($user_row['user_type'] == USER_NORMAL || $user_row['user_type'] == USER_FOUNDER)
	{
		set_config('newest_user_id', $user_id, true);
		set_config('newest_username', $user_row['username'], true);
		set_config_count('num_users', 1, true);

		$sql = 'SELECT group_colour
			FROM ' . GROUPS_TABLE . '
			WHERE group_id = ' . (int) $user_row['group_id'];
		$result = $db->sql_query_limit($sql, 1);
		$row = $db->sql_fetchrow($result);
		$db->sql_freeresult($result);

		set_config('newest_user_colour', $row['group_colour'], true);
	}

	return $user_id;
}
Y añadimos después:

Código: Seleccionar todo

/**
* Adds an user
*
* @param mixed $user_row An array containing the following keys (and the appropriate values): username, group_id (the group to place the user in), user_email and the user_type(usually 0). Additional entries not overridden by defaults will be forwarded.
* @param string $cp_data custom profile fields, see custom_profile::build_insert_sql_array
* @return the new user's ID.
*/
function user_add_2($user_row, $cp_data = false)
{
	global $db, $user, $auth, $config, $phpbb_root_path, $phpEx;

	if (empty($user_row['username']) || !isset($user_row['group_id']) || !isset($user_row['user_email']) || !isset($user_row['user_type']))
	{
		return false;
	}

	$username_clean = utf8_clean_string($user_row['username']);

	if (empty($username_clean))
	{
		return false;
	}

	$sql_ary = array(
		'username'			=> $user_row['username'],
		'username_clean'	=> $username_clean,
		'user_password'		=> (isset($user_row['user_password'])) ? $user_row['user_password'] : '',
		'user_pass_convert'	=> 0,
		'user_email'		=> strtolower($user_row['user_email']),
		'user_email_hash'	=> phpbb_email_hash($user_row['user_email']),
		'group_id'			=> $user_row['group_id'],
		'user_type'			=> $user_row['user_type'],
	);

	// These are the additional vars able to be specified
	$additional_vars = array(
		'user_permissions'	=> '',
		'user_timezone'		=> $config['board_timezone'],
		'user_dateformat'	=> $config['default_dateformat'],
		'user_lang'			=> $config['default_lang'],
		'user_style'		=> (int) $config['default_style'],
		'user_actkey'		=> '',
		'user_ip'			=> '',
		'user_regdate'		=> time(),
		'user_passchg'		=> time(),
		'user_options'		=> 230271,
		// We do not set the new flag here - registration scripts need to specify it
		'user_new'			=> 0,

		'user_inactive_reason'	=> 0,
		'user_inactive_time'	=> 0,
		'user_lastmark'			=> time(),
		'user_lastvisit'		=> 0,
		'user_lastpost_time'	=> 0,
		'user_lastpage'			=> '',
		'user_posts'			=> 0,
		'user_dst'				=> (int) $config['board_dst'],
		'user_colour'			=> '',
		'user_occ'				=> '',
		'user_interests'		=> '',
		'user_avatar'			=> '',
		'user_avatar_type'		=> 0,
		'user_avatar_width'		=> 0,
		'user_avatar_height'	=> 0,
		'user_new_privmsg'		=> 0,
		'user_unread_privmsg'	=> 0,
		'user_last_privmsg'		=> 0,
		'user_message_rules'	=> 0,
		'user_full_folder'		=> PRIVMSGS_NO_BOX,
		'user_emailtime'		=> 0,

		'user_notify'			=> 0,
		'user_notify_pm'		=> 1,
		'user_notify_type'		=> NOTIFY_EMAIL,
		'user_allow_pm'			=> 1,
		'user_allow_viewonline'	=> 1,
		'user_allow_viewemail'	=> 1,
		'user_allow_massemail'	=> 1,

		'user_sig'					=> '',
		'user_sig_bbcode_uid'		=> '',
		'user_sig_bbcode_bitfield'	=> '',

		'user_form_salt'			=> unique_id(),
	);
	// Now fill the sql array with not required variables
	foreach ($additional_vars as $key => $default_value)
	{
		$sql_ary[$key] = (isset($user_row[$key])) ? $user_row[$key] : $default_value;
	}

	// Any additional variables in $user_row not covered above?
	$remaining_vars = array_diff(array_keys($user_row), array_keys($sql_ary));

	// Now fill our sql array with the remaining vars
	if (sizeof($remaining_vars))
	{
		foreach ($remaining_vars as $key)
		{
			$sql_ary[$key] = $user_row[$key];
		}
	}

	$sql = 'INSERT INTO ' . USERS_TABLE_2 . ' ' . $db->sql_build_array('INSERT', $sql_ary);
	$db->sql_query($sql);
	$user_id = $db->sql_nextid();
	
	// Insert Custom Profile Fields
	if ($cp_data !== false && sizeof($cp_data))
	{
		$cp_data['user_id'] = (int) $user_id;

		if (!class_exists('custom_profile'))
		{
			include_once($phpbb_root_path . 'includes/functions_profile_fields.' . $phpEx);
		}

		$sql = 'INSERT INTO ' . PROFILE_FIELDS_DATA_TABLE . ' ' .
			$db->sql_build_array('INSERT', custom_profile::build_insert_sql_array($cp_data));
		$db->sql_query($sql);
	}

	// Place into appropriate group...
	$sql = 'INSERT INTO ' . USER_GROUP_TABLE_2 . ' ' . $db->sql_build_array('INSERT', array(
		'user_id'		=> (int) $user_id,
		'group_id'		=> (int) $user_row['group_id'],
		'user_pending'	=> 0)
	);
	$db->sql_query($sql);

	// Now make it the users default group...
	group_set_user_default($user_row['group_id'], array($user_id), false);

	// Add to newly registered users group if user_new is 1
	if ($config['new_member_post_limit'] && $sql_ary['user_new'])
	{
		$sql = 'SELECT group_id
			FROM ' . GROUPS_TABLE_2 . "
			WHERE group_name = 'NEWLY_REGISTERED'
				AND group_type = " . GROUP_SPECIAL;
		$result = $db->sql_query($sql);
		$add_group_id = (int) $db->sql_fetchfield('group_id');
		$db->sql_freeresult($result);

		if ($add_group_id)
		{
			// Because these actions only fill the log unneccessarily we skip the add_log() entry with a little hack. :/
			$GLOBALS['skip_add_log'] = true;

			// Add user to "newly registered users" group and set to default group if admin specified so.
			if ($config['new_member_group_default'])
			{
				group_user_add($add_group_id, $user_id, false, false, true);
				$user_row['group_id'] = $add_group_id;
			}
			else
			{
				group_user_add($add_group_id, $user_id);
			}

			unset($GLOBALS['skip_add_log']);
		}
	}

	// set the newest user and adjust the user count if the user is a normal user and no activation mail is sent
	if ($user_row['user_type'] == USER_NORMAL || $user_row['user_type'] == USER_FOUNDER)
	{
		set_config('newest_user_id', $user_id, true);
		set_config('newest_username', $user_row['username'], true);
		set_config_count('num_users', 1, true);

		$sql = 'SELECT group_colour
			FROM ' . GROUPS_TABLE_2 . '
			WHERE group_id = ' . (int) $user_row['group_id'];
		$result = $db->sql_query_limit($sql, 1);
		$row = $db->sql_fetchrow($result);
		$db->sql_freeresult($result);

		set_config('newest_user_colour', $row['group_colour'], true);
	}

	return $user_id;
}
*Lo que hacemos en este paso es buscar las funciones que añadimos modificadas en el archivo constants.php y les añadimos un "_2".

Ahora vamos con el FORO 2
1) Abrimos el config.php de foro1 y buscamos:

Código: Seleccionar todo

$table_prefix = 'foro2_';
Y añadimos después:

Código: Seleccionar todo

$table_prefix2 = foro1_';
*Si os dais cuenta, es el mismo paso pero ahora el "$table_prefix" principal va a ser el del foro 2"

2) Abrimos includes/constants.php del foro 2 y buscamos:

Código: Seleccionar todo

define('GROUPS_TABLE',				$table_prefix . 'groups');
Y añadimos después:

Código: Seleccionar todo

define('GROUPS_TABLE_2',				$table_prefix2 . 'groups');
Buscamos:

Código: Seleccionar todo

define('USER_GROUP_TABLE',			$table_prefix . 'user_group');
Y Añadimos después:

Código: Seleccionar todo

define('USER_GROUP_TABLE_2',			$table_prefix2 . 'user_group');
Buscamos:

Código: Seleccionar todo

define('USERS_TABLE',				$table_prefix . 'users');
Y añadimos después:

Código: Seleccionar todo

define('USERS_TABLE_2',				$table_prefix2 . 'users');
3) abrimos el archivo includes/functions_user.php del foro 2 y buscamos:

*Cuidado en este paso porque hay que buscar mucho código, ayudaros de las etiquetas que marcan el inicio de las funciones, como por ejemplo, adds an user.

*Este paso es un muy importante.

Código: Seleccionar todo

/**
* Adds an user
*
* @param mixed $user_row An array containing the following keys (and the appropriate values): username, group_id (the group to place the user in), user_email and the user_type(usually 0). Additional entries not overridden by defaults will be forwarded.
* @param string $cp_data custom profile fields, see custom_profile::build_insert_sql_array
* @return the new user's ID.
*/
function user_add($user_row, $cp_data = false)
{
	global $db, $user, $auth, $config, $phpbb_root_path, $phpEx;

	if (empty($user_row['username']) || !isset($user_row['group_id']) || !isset($user_row['user_email']) || !isset($user_row['user_type']))
	{
		return false;
	}

	$username_clean = utf8_clean_string($user_row['username']);

	if (empty($username_clean))
	{
		return false;
	}

	$sql_ary = array(
		'username'			=> $user_row['username'],
		'username_clean'	=> $username_clean,
		'user_password'		=> (isset($user_row['user_password'])) ? $user_row['user_password'] : '',
		'user_pass_convert'	=> 0,
		'user_email'		=> strtolower($user_row['user_email']),
		'user_email_hash'	=> phpbb_email_hash($user_row['user_email']),
		'group_id'			=> $user_row['group_id'],
		'user_type'			=> $user_row['user_type'],
	);

	// These are the additional vars able to be specified
	$additional_vars = array(
		'user_permissions'	=> '',
		'user_timezone'		=> $config['board_timezone'],
		'user_dateformat'	=> $config['default_dateformat'],
		'user_lang'			=> $config['default_lang'],
		'user_style'		=> (int) $config['default_style'],
		'user_actkey'		=> '',
		'user_ip'			=> '',
		'user_regdate'		=> time(),
		'user_passchg'		=> time(),
		'user_options'		=> 230271,
		// We do not set the new flag here - registration scripts need to specify it
		'user_new'			=> 0,

		'user_inactive_reason'	=> 0,
		'user_inactive_time'	=> 0,
		'user_lastmark'			=> time(),
		'user_lastvisit'		=> 0,
		'user_lastpost_time'	=> 0,
		'user_lastpage'			=> '',
		'user_posts'			=> 0,
		'user_dst'				=> (int) $config['board_dst'],
		'user_colour'			=> '',
		'user_occ'				=> '',
		'user_interests'		=> '',
		'user_avatar'			=> '',
		'user_avatar_type'		=> 0,
		'user_avatar_width'		=> 0,
		'user_avatar_height'	=> 0,
		'user_new_privmsg'		=> 0,
		'user_unread_privmsg'	=> 0,
		'user_last_privmsg'		=> 0,
		'user_message_rules'	=> 0,
		'user_full_folder'		=> PRIVMSGS_NO_BOX,
		'user_emailtime'		=> 0,

		'user_notify'			=> 0,
		'user_notify_pm'		=> 1,
		'user_notify_type'		=> NOTIFY_EMAIL,
		'user_allow_pm'			=> 1,
		'user_allow_viewonline'	=> 1,
		'user_allow_viewemail'	=> 1,
		'user_allow_massemail'	=> 1,

		'user_sig'					=> '',
		'user_sig_bbcode_uid'		=> '',
		'user_sig_bbcode_bitfield'	=> '',

		'user_form_salt'			=> unique_id(),
	);
	// Now fill the sql array with not required variables
	foreach ($additional_vars as $key => $default_value)
	{
		$sql_ary[$key] = (isset($user_row[$key])) ? $user_row[$key] : $default_value;
	}

	// Any additional variables in $user_row not covered above?
	$remaining_vars = array_diff(array_keys($user_row), array_keys($sql_ary));

	// Now fill our sql array with the remaining vars
	if (sizeof($remaining_vars))
	{
		foreach ($remaining_vars as $key)
		{
			$sql_ary[$key] = $user_row[$key];
		}
	}

	$sql = 'INSERT INTO ' . USERS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
	$db->sql_query($sql);
	$user_id = $db->sql_nextid();
	
	// Insert Custom Profile Fields
	if ($cp_data !== false && sizeof($cp_data))
	{
		$cp_data['user_id'] = (int) $user_id;

		if (!class_exists('custom_profile'))
		{
			include_once($phpbb_root_path . 'includes/functions_profile_fields.' . $phpEx);
		}

		$sql = 'INSERT INTO ' . PROFILE_FIELDS_DATA_TABLE . ' ' .
			$db->sql_build_array('INSERT', custom_profile::build_insert_sql_array($cp_data));
		$db->sql_query($sql);
	}

	// Place into appropriate group...
	$sql = 'INSERT INTO ' . USER_GROUP_TABLE . ' ' . $db->sql_build_array('INSERT', array(
		'user_id'		=> (int) $user_id,
		'group_id'		=> (int) $user_row['group_id'],
		'user_pending'	=> 0)
	);
	$db->sql_query($sql);

	// Now make it the users default group...
	group_set_user_default($user_row['group_id'], array($user_id), false);

	// Add to newly registered users group if user_new is 1
	if ($config['new_member_post_limit'] && $sql_ary['user_new'])
	{
		$sql = 'SELECT group_id
			FROM ' . GROUPS_TABLE . "
			WHERE group_name = 'NEWLY_REGISTERED'
				AND group_type = " . GROUP_SPECIAL;
		$result = $db->sql_query($sql);
		$add_group_id = (int) $db->sql_fetchfield('group_id');
		$db->sql_freeresult($result);

		if ($add_group_id)
		{
			// Because these actions only fill the log unneccessarily we skip the add_log() entry with a little hack. :/
			$GLOBALS['skip_add_log'] = true;

			// Add user to "newly registered users" group and set to default group if admin specified so.
			if ($config['new_member_group_default'])
			{
				group_user_add($add_group_id, $user_id, false, false, true);
				$user_row['group_id'] = $add_group_id;
			}
			else
			{
				group_user_add($add_group_id, $user_id);
			}

			unset($GLOBALS['skip_add_log']);
		}
	}

	// set the newest user and adjust the user count if the user is a normal user and no activation mail is sent
	if ($user_row['user_type'] == USER_NORMAL || $user_row['user_type'] == USER_FOUNDER)
	{
		set_config('newest_user_id', $user_id, true);
		set_config('newest_username', $user_row['username'], true);
		set_config_count('num_users', 1, true);

		$sql = 'SELECT group_colour
			FROM ' . GROUPS_TABLE . '
			WHERE group_id = ' . (int) $user_row['group_id'];
		$result = $db->sql_query_limit($sql, 1);
		$row = $db->sql_fetchrow($result);
		$db->sql_freeresult($result);

		set_config('newest_user_colour', $row['group_colour'], true);
	}

	return $user_id;
}
Y añadimos después:

Código: Seleccionar todo

/**
* Adds an user
*
* @param mixed $user_row An array containing the following keys (and the appropriate values): username, group_id (the group to place the user in), user_email and the user_type(usually 0). Additional entries not overridden by defaults will be forwarded.
* @param string $cp_data custom profile fields, see custom_profile::build_insert_sql_array
* @return the new user's ID.
*/
function user_add_2($user_row, $cp_data = false)
{
	global $db, $user, $auth, $config, $phpbb_root_path, $phpEx;

	if (empty($user_row['username']) || !isset($user_row['group_id']) || !isset($user_row['user_email']) || !isset($user_row['user_type']))
	{
		return false;
	}

	$username_clean = utf8_clean_string($user_row['username']);

	if (empty($username_clean))
	{
		return false;
	}

	$sql_ary = array(
		'username'			=> $user_row['username'],
		'username_clean'	=> $username_clean,
		'user_password'		=> (isset($user_row['user_password'])) ? $user_row['user_password'] : '',
		'user_pass_convert'	=> 0,
		'user_email'		=> strtolower($user_row['user_email']),
		'user_email_hash'	=> phpbb_email_hash($user_row['user_email']),
		'group_id'			=> $user_row['group_id'],
		'user_type'			=> $user_row['user_type'],
	);

	// These are the additional vars able to be specified
	$additional_vars = array(
		'user_permissions'	=> '',
		'user_timezone'		=> $config['board_timezone'],
		'user_dateformat'	=> $config['default_dateformat'],
		'user_lang'			=> $config['default_lang'],
		'user_style'		=> (int) $config['default_style'],
		'user_actkey'		=> '',
		'user_ip'			=> '',
		'user_regdate'		=> time(),
		'user_passchg'		=> time(),
		'user_options'		=> 230271,
		// We do not set the new flag here - registration scripts need to specify it
		'user_new'			=> 0,

		'user_inactive_reason'	=> 0,
		'user_inactive_time'	=> 0,
		'user_lastmark'			=> time(),
		'user_lastvisit'		=> 0,
		'user_lastpost_time'	=> 0,
		'user_lastpage'			=> '',
		'user_posts'			=> 0,
		'user_dst'				=> (int) $config['board_dst'],
		'user_colour'			=> '',
		'user_occ'				=> '',
		'user_interests'		=> '',
		'user_avatar'			=> '',
		'user_avatar_type'		=> 0,
		'user_avatar_width'		=> 0,
		'user_avatar_height'	=> 0,
		'user_new_privmsg'		=> 0,
		'user_unread_privmsg'	=> 0,
		'user_last_privmsg'		=> 0,
		'user_message_rules'	=> 0,
		'user_full_folder'		=> PRIVMSGS_NO_BOX,
		'user_emailtime'		=> 0,

		'user_notify'			=> 0,
		'user_notify_pm'		=> 1,
		'user_notify_type'		=> NOTIFY_EMAIL,
		'user_allow_pm'			=> 1,
		'user_allow_viewonline'	=> 1,
		'user_allow_viewemail'	=> 1,
		'user_allow_massemail'	=> 1,

		'user_sig'					=> '',
		'user_sig_bbcode_uid'		=> '',
		'user_sig_bbcode_bitfield'	=> '',

		'user_form_salt'			=> unique_id(),
	);
	// Now fill the sql array with not required variables
	foreach ($additional_vars as $key => $default_value)
	{
		$sql_ary[$key] = (isset($user_row[$key])) ? $user_row[$key] : $default_value;
	}

	// Any additional variables in $user_row not covered above?
	$remaining_vars = array_diff(array_keys($user_row), array_keys($sql_ary));

	// Now fill our sql array with the remaining vars
	if (sizeof($remaining_vars))
	{
		foreach ($remaining_vars as $key)
		{
			$sql_ary[$key] = $user_row[$key];
		}
	}

	$sql = 'INSERT INTO ' . USERS_TABLE_2 . ' ' . $db->sql_build_array('INSERT', $sql_ary);
	$db->sql_query($sql);
	$user_id = $db->sql_nextid();
	
	// Insert Custom Profile Fields
	if ($cp_data !== false && sizeof($cp_data))
	{
		$cp_data['user_id'] = (int) $user_id;

		if (!class_exists('custom_profile'))
		{
			include_once($phpbb_root_path . 'includes/functions_profile_fields.' . $phpEx);
		}

		$sql = 'INSERT INTO ' . PROFILE_FIELDS_DATA_TABLE . ' ' .
			$db->sql_build_array('INSERT', custom_profile::build_insert_sql_array($cp_data));
		$db->sql_query($sql);
	}

	// Place into appropriate group...
	$sql = 'INSERT INTO ' . USER_GROUP_TABLE_2 . ' ' . $db->sql_build_array('INSERT', array(
		'user_id'		=> (int) $user_id,
		'group_id'		=> (int) $user_row['group_id'],
		'user_pending'	=> 0)
	);
	$db->sql_query($sql);

	// Now make it the users default group...
	group_set_user_default($user_row['group_id'], array($user_id), false);

	// Add to newly registered users group if user_new is 1
	if ($config['new_member_post_limit'] && $sql_ary['user_new'])
	{
		$sql = 'SELECT group_id
			FROM ' . GROUPS_TABLE_2 . "
			WHERE group_name = 'NEWLY_REGISTERED'
				AND group_type = " . GROUP_SPECIAL;
		$result = $db->sql_query($sql);
		$add_group_id = (int) $db->sql_fetchfield('group_id');
		$db->sql_freeresult($result);

		if ($add_group_id)
		{
			// Because these actions only fill the log unneccessarily we skip the add_log() entry with a little hack. :/
			$GLOBALS['skip_add_log'] = true;

			// Add user to "newly registered users" group and set to default group if admin specified so.
			if ($config['new_member_group_default'])
			{
				group_user_add($add_group_id, $user_id, false, false, true);
				$user_row['group_id'] = $add_group_id;
			}
			else
			{
				group_user_add($add_group_id, $user_id);
			}

			unset($GLOBALS['skip_add_log']);
		}
	}

	// set the newest user and adjust the user count if the user is a normal user and no activation mail is sent
	if ($user_row['user_type'] == USER_NORMAL || $user_row['user_type'] == USER_FOUNDER)
	{
		set_config('newest_user_id', $user_id, true);
		set_config('newest_username', $user_row['username'], true);
		set_config_count('num_users', 1, true);

		$sql = 'SELECT group_colour
			FROM ' . GROUPS_TABLE_2 . '
			WHERE group_id = ' . (int) $user_row['group_id'];
		$result = $db->sql_query_limit($sql, 1);
		$row = $db->sql_fetchrow($result);
		$db->sql_freeresult($result);

		set_config('newest_user_colour', $row['group_colour'], true);
	}

	return $user_id;
}
Formulario de registro página externa
Yo me ayudé del tutorial para crear un registro en una página externa pero le hice varias modificaciones. De todas formas es muy importante leerselo para continuar el tutorial.

http://www.phpbb-es.com/biblioteca/kb_show.php?id=25

4) Crear archivo registro.php:

Código: Seleccionar todo

<!DOCTYPE html>
<html lang="es">
<head>
   <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
    <title>Crear cuenta en FIFA Community Spain</title>
	<link rel="stylesheet" media="screen" href="styles.css" >
    <!--[if IE]>
        <script src="http://html5shiv.googlecode.com/svn/trunk
/html5.js"></script>
        <![endif]-->
</head>
<body>


   <?php
    /*
     * Script para registrar usuarios en phpBB3 desde una página externa.
     * Implementado por Alorse para phpBB-es.COM
     */
    define('IN_PHPBB', true);
    $phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : '../foro/'; 
    $phpEx = substr(strrchr(__FILE__, '.'), 1);
    include($phpbb_root_path . 'common.' . $phpEx);
    require($phpbb_root_path . 'includes/functions_user.' . $phpEx); // Archivo necesario para el registro
    // Start session management
    $user->session_begin();
    $auth->acl($user->data);
    $user->setup();

    // Añadido nuevo* Si el usuario ya se encuentra registrado e idenficado le mustra un aviso en vez del formulario de registro
    if ($user->data['is_registered']) {
		print "<meta http-equiv=Refresh content=\"0.2 ; url=../foro\">";
    }
	else{
?>

<div style="width:100%: text-align:center;"><img src=""></div>
    <form method="post" action="./acc-register.php" class="contact_form" >
        <li>
             <h2>Crear nueva cuenta en el foro</h2>
			 <h2>Al crear una cuenta en cualquiera de los foros o en la página principal, se te crea una cuenta para poder acceder a toda la web</h2>
        </li>	
        <li>
            <dt><label>Nombre de Usuario:</label></dt>
            <dd><input type="text" name="username" size="25" /></dd>
        </li>
        <li>
                <dt><label>Dirección de email:</label></dt>
                <dd><input type="text" name="email" size="25" maxlength="100" /></dd>
		</li>
		<li>
				<dt><label for="email_confirm">Confirmar email:</label></dt>
				<dd><input type="text" name="email_confirm" id="email_confirm" size="25" maxlength="100" class="inputbox autowidth" title="{L_CONFIRM_EMAIL}" /></dd>
		</li>			
        <li>
                <dt><label>Contraseña:</label></dt>
                <dd><input type="password" name="password" size="25" /></dd>
        </li>
        <li>
                <dt><label>Confirmar contraseña:</label></dt>
                <dd><input type="password"  name="password_confirm" size="25" /></dd>
        <li>
				<div style="text-align:center;">777</div>
                <dt><label>Código Anti-Spam:</label></dt>
                <dd><input type="text" name="captcha" size="25" /></dd>
        </li>
		<li>		
                <dt><label>Confirmar código Anti-Spam:</label></dt>
                <dd><input type="text" name="captcha_confirm" size="25" /></dd>
        </li>		
            <button type="reset" value="Limpiar" name="reset" />Limpiar</button>
            <button type="submit" name="register" value="Registrarse" />Registrarse</button>
		</li>
    </form>
	<?php
	}
	?>
</body>	

IMPORTANTE:

Código: Seleccionar todo

				<div style="text-align:center;">777</div>
                <dt><label>Código Anti-Spam:</label></dt>
                <dd><input type="text" name="captcha" size="25" /></dd>
        </li>
		<li>		
                <dt><label>Confirmar código Anti-Spam:</label></dt>
                <dd><input type="text" name="captcha_confirm" size="25" /></dd>
        </li>		
Para evitar el registro de spam bots. También es recomendable crear una imagen.php (en google hay varios tutoriales) con varios códigos anti-spam y que salgan de forma aleatoria. aunque de todas formas el texto escrito también es válido. Yo he puesto un 777 como ejemplo.

Buscar:

Código: Seleccionar todo

print "<meta http-equiv=Refresh content=\"0.2 ; url=../foro\">";
Modificar y poner la ruta de vuestro foro, ya que yo lo tengo apuntando hacia donde está el mío.

5) Crear el archivo que hará la acción de registro a través de los datos que le manda el formulario.

acc-register.php

Código: Seleccionar todo

<!DOCTYPE html>
<html lang="es">
<head>
   <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
    <title>Mi registro</title>
</head>

   <?php
    /*
     * Script para registrar usuarios en phpBB3 desde una página externa.
     * Implementado por Alorse para phpBB-es.COM
     */
    define('IN_PHPBB', true);
    $phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : '../foro/'; 
    $phpEx = substr(strrchr(__FILE__, '.'), 1);
    include($phpbb_root_path . 'common.' . $phpEx);
    require($phpbb_root_path . 'includes/functions_user.' . $phpEx); // Archivo necesario para el registro
    // Start session management
    $user->session_begin();
    $auth->acl($user->data);
    $user->setup();

    // Si el usuario ya se encuentra registrado e idenficado le mustra un aviso en vez del formulario de registro
    if ($user->data['is_registered'] || isset($_REQUEST['not_agreed'])) {
        exit($user->data['username'] . ' ya te encuentras registrado.');
    }

    // Si envia el formulario empieza con el proceso.
    $register = request_var('register', '');
    if ($register) {

        //Buscamos cual es el grupo por defecto
        $coppa = (isset($_REQUEST['coppa'])) ? ((!empty($_REQUEST['coppa'])) ? 1 : 0) : false;
        $group_name = ($coppa) ? 'REGISTERED_COPPA' : 'REGISTERED';
        $sql = 'SELECT group_id
            FROM ' . GROUPS_TABLE . "
            WHERE group_name = '" . $db->sql_escape($group_name) . "'
                AND group_type = " . GROUP_SPECIAL;
        $result = $db->sql_query($sql);
        $row = $db->sql_fetchrow($result);
        $group_id = $row['group_id'];

        // Tomamos los valores del formulario.
        $username = request_var('username', '');
        $email = request_var('email', '');
        $password = phpbb_hash(request_var('password', '', true));
        $password_confirm = phpbb_hash(request_var('password_confirm', '', true));

        // Pasamos todos lo datos de registro a un vector.
        $user_row = array(
            'username' => $username,
            'user_email' => $email,
            'user_password' => $password,
            'group_id' => $group_id,
            'user_type' => '0',
            'user_new' => 1, // Entrara al grupo de nuevos usuarios registrados.
        );

        $query = 'SELECT username, user_email
            FROM ' . USERS_TABLE . '
            WHERE username = "' . $username . '"
                OR user_email = "' . $email . '"';
        $res = $db->sql_query($query);

        // Verificamos que el usuario no exista y que las contraseñas sean iguales.
        if ($db->sql_fetchrow($res) || (request_var('password', '', true) != request_var('password_confirm', '', true))) {
            echo 'El nombre de usuario o email ya se encuentran registrados, las contraseñas no concuerdan o no te falta algún dato.<br />';
			print "<meta http-equiv=Refresh content=\"2 ; url=./index.php\">";
        } elseif ($db->sql_fetchrow($res) || (request_var('email', '', true) != request_var('email_confirm', '', true))) {
            echo 'los emails no coinciden.<br />';
			print "<meta http-equiv=Refresh content=\"2 ; url=./index.php\">";	
		}  elseif ($db->sql_fetchrow($res) || (request_var('captcha', '', true) != request_var('captcha_confirm', '', true))) {
            echo 'El código anti-spam es incorrecto.<br />';
			print "<meta http-equiv=Refresh content=\"2 ; url=./index.php\">";	
		} else {
            // La funcion user_add() del /includes/functions_user.php se encarga del resto.
            user_add($user_row);
	    user_add_2($user_row); //importante, realiza el doble registro
            echo '<h2>Tu cuenta ha sido creada. Ahora puedes identificarte con tu nombre de usuario y su contraseña.</h2>';
			print "<meta http-equiv=Refresh content=\"2 ; url=../foro\">";
        }
    }
    ?>
*La parte final del código es la que verifica si el nombre de usuario ya está creado, si la confirmación del email es correcta, si la confirmación de la contraseña era correcta y si el código anti-spam, también es correcto.

*Recordar modificar las rutas de redirección ya que pueden no estar apuntando a vuestro foro (lo más seguro).


6) Crear el mismo formulario de registro en ambos foros, ya que el registro que se haga en el foro 1, se creará en el foro 2 y el registro que se haga en foro 2 se creará en el foro 1.

Podéis comprobarlo si tenéis el phpmyadmin abierto y ver como en dos tablas (foro1_users y foro2_users) se crean los usuarios con sus respectivos permisos.
Versión phpBB: 3.0.11
MODs Instalados:
phpbb socialnet
phpbb_follower
cBB Blockgets
mssti_advanced_bbcode_box_3_3_0_11
ultimate_points_v1.1.2
nv_who_was_here_1_2_1
phpbbcalendarmod

Plantilla(s) usada(s): ProBoot
Servidor: De pago
Actualización desde otra versión: No
Conversión desde otro sistema de foros: No
URL: http://www.manager.fifacommunityspain.es

Cerrado

Volver a “Soporte de MODs”