HEX
Server: Apache
System: Linux darrell.nocdirect.com 4.18.0-513.18.2.el8_9.x86_64 #1 SMP Sat Mar 30 06:10:41 EDT 2024 x86_64
User: joderbya (1358)
PHP: 8.0.30
Disabled: NONE
Upload Files
File: /home/joderbya/public_html/ss-servicos/nacala/public/members/new.php
<?php
/* Copyright (C) 2001-2002  Rodolphe Quiedeville    <rodolphe@quiedeville.org>
 * Copyright (C) 2001-2002  Jean-Louis Bergamo      <jlb@j1b.org>
 * Copyright (C) 2006-2013  Laurent Destailleur     <eldy@users.sourceforge.net>
 * Copyright (C) 2012       Regis Houssin           <regis.houssin@inodbox.com>
 * Copyright (C) 2012       J. Fernando Lagrange    <fernando@demo-tic.org>
 * Copyright (C) 2018-2025  Frédéric France         <frederic.france@free.fr>
 * Copyright (C) 2018       Alexandre Spangaro      <aspangaro@open-dsi.fr>
 * Copyright (C) 2021       Waël Almoman            <info@almoman.com>
 * Copyright (C) 2022       Udo Tamm                <dev@dolibit.de>
 * Copyright (C) 2024-2025	MDW						<mdeweerd@users.noreply.github.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */

/**
 *	\file       htdocs/public/members/new.php
 *	\ingroup    member
 *	\brief      Example of form to add a new member
 *
 *  Note that you can add following constant to change behaviour of page
 *  MEMBER_NEWFORM_AMOUNT               Default amount for auto-subscribe form
 *  MEMBER_MIN_AMOUNT                   Minimum amount
 *  MEMBER_NEWFORM_PAYONLINE            Suggest payment with 'all', 'paypal', 'paybox', 'stripe', ...
 *  MEMBER_NEWFORM_DOLIBARRTURNOVER     Show field turnover (specific for dolibarr foundation)
 *  MEMBER_URL_REDIRECT_SUBSCRIPTION    Url to redirect once registration form has been submitted (hidden option, by default we just show a message on same page or redirect to the payment page)
 *  MEMBER_NEWFORM_FORCETYPE            Force type of member
 *  MEMBER_NEWFORM_FORCEMORPHY          Force nature of member (mor/phy)
 *  MEMBER_NEWFORM_FORCECOUNTRYCODE     Force country
 */

if (!defined('NOLOGIN')) {
	define("NOLOGIN", 1); // This means this output page does not require to be logged.
}
if (!defined('NOCSRFCHECK')) {
	define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
}
if (!defined('NOBROWSERNOTIF')) {
	define('NOBROWSERNOTIF', '1');
}


// For MultiCompany module.
// Do not use GETPOST here, function is not defined and define must be done before including main.inc.php
// Because 2 entities can have the same ref.
$entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1));
define("DOLENTITY", $entity);


// Load Dolibarr environment
require '../../main.inc.php';
/**
 * @var Conf $conf
 * @var DoliDB $db
 * @var HookManager $hookmanager
 * @var Societe $mysoc
 * @var Translate $langs
 * @var User $user
 */
require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent_type.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/cunits.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';

// Init vars
$backtopage = GETPOST('backtopage', 'alpha');
$action = GETPOST('action', 'aZ09');

$errmsg = '';
$num = 0;
$error = 0;

// Load translation files
$langs->loadLangs(array("main", "members", "companies", "install", "other", "errors"));

if (isModEnabled('multicompany')) {
	force_switch_entity($entity);
}

// Security check
if (!isModEnabled('member')) {
	httponly_accessforbidden('Module Membership not enabled');
}

if (!getDolGlobalString('MEMBER_ENABLE_PUBLIC')) {
	httponly_accessforbidden("Auto subscription form for public visitors has not been enabled");
}

// Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
$hookmanager->initHooks(array('publicnewmembercard', 'globalcard'));

$extrafields = new ExtraFields($db);

$object = new Adherent($db);

$user->loadDefaultValues();

$captchaobj = null;
if (getDolGlobalString('MAIN_SECURITY_ENABLECAPTCHA_MEMBER')) {
	require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
	$captcha = getDolGlobalString('MAIN_SECURITY_ENABLECAPTCHA_HANDLER', 'standard');
	// List of directories where we can find captcha handlers
	$dirModCaptcha = array_merge(
		array(
			'main' => '/core/modules/security/captcha/'
		),
		is_array($conf->modules_parts['captcha']) ? $conf->modules_parts['captcha'] : array()
	);
	$fullpathclassfile = '';
	foreach ($dirModCaptcha as $dir) {
		$fullpathclassfile = dol_buildpath($dir."modCaptcha".ucfirst($captcha).'.class.php', 0, 2);
		if ($fullpathclassfile) {
			break;
		}
	}
	if ($fullpathclassfile) {
		include_once $fullpathclassfile;
		// Charging the numbering class
		$classname = "modCaptcha".ucfirst($captcha);
		if (class_exists($classname)) {
			$captchaobj = new $classname($db, $conf, $langs, $user);
			'@phan-var-force ModeleCaptcha $captchaobj';
			/** @var ModeleCaptcha $captchaobj */
		} else {
			print 'Error, the captcha handler class '.$classname.' was not found after the include';
		}
	} else {
		print 'Error, the captcha handler '.$captcha.' has no class file found modCaptcha'.ucfirst($captcha);
	}
}

/**
 * Force switching conf of entity, even if user is connected
 * Fox example when trying to go on public form of an other entity
 *
 * @param 	int		$newEntity		New entity
 * @return	void
 */
function force_switch_entity($newEntity)
{
	global $db, $conf;

	if ($newEntity != $conf->entity) {
		$conf->entity = $newEntity;
		$conf->setValues($db);
	}
}

/**
 * Show header for new member
 *
 * Note: also called by functions.lib:recordNotFound
 *
 * @param 	string		$title				Title
 * @param 	string		$head				Head array
 * @param 	int    		$disablejs			More content into html header
 * @param 	int    		$disablehead		More content into html header
 * @param 	string[]|string	$arrayofjs			Array of complementary js files
 * @param 	string[]|string	$arrayofcss			Array of complementary css files
 * @return	void
 */
function llxHeaderVierge($title, $head = "", $disablejs = 0, $disablehead = 0, $arrayofjs = [], $arrayofcss = [])  // @phan-suppress-current-line PhanRedefineFunction
{
	global $conf, $langs, $mysoc;

	top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss); // Show html headers

	print '<body id="mainbody" class="publicnewmemberform">';

	include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
	htmlPrintOnlineHeader($mysoc, $langs, 1, getDolGlobalString('MEMBER_PUBLIC_INTERFACE'), 'MEMBER_IMAGE_PUBLIC_REGISTRATION');

	print '<div class="divmainbodylarge">';
}

/**
 * Show footer for new member
 *
 * Note: also called by functions.lib:recordNotFound
 *
 * @return	void
 */
function llxFooterVierge()  // @phan-suppress-current-line PhanRedefineFunction
{
	global $conf, $langs;

	print '</div>';

	printCommonFooter('public');

	if (!empty($conf->use_javascript_ajax)) {
		print "\n".'<!-- Includes JS Footer of Dolibarr -->'."\n";
		print '<script src="'.DOL_URL_ROOT.'/core/js/lib_foot.js.php?lang='.$langs->defaultlang.'"></script>'."\n";
	}

	print "</body>\n";
	print "</html>\n";
}



/*
 * Actions
 */

$parameters = array();
// Note that $action and $object may have been modified by some hooks
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action);
if ($reshook < 0) {
	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}

// Verify if we can find member
if (empty($reshook) && getDolGlobalInt("MEMBER_SEARCH_MEMBER_PUBLIC_FORM_CREATE") && $action == 'add' && !GETPOSTISSET("nofetchmember")) {	// Test on permission not required here
	$memberfound = false;
	if (!getDolGlobalString('ADHERENT_LOGIN_NOT_REQUIRED') && GETPOSTISSET('login')) {
		$sql = "SELECT rowid as id";
		$sql .= " FROM ".MAIN_DB_PREFIX."adherent as a";
		$sql .= " WHERE a.login = '".$db->escape(GETPOST('login'))."'";
		$sql .= " AND statut = 1";
		$sql .= " AND entity IN (".getEntity($object->element).")";
		$resql = $db->query($sql);
		if ($resql) {
			if ($db->num_rows($resql) == 1) {
				$obj = $db->fetch_object($resql);
				$object->fetch($obj->id);
				$memberfound = true;
			}
		} else {
			dol_print_error($db);
		}
	}

	if (!$memberfound && GETPOST("morphy") == 'mor' && GETPOSTISSET("societe") ) {
		$sql = "SELECT a.rowid as id";
		$sql .= " FROM ".MAIN_DB_PREFIX."adherent as a";
		$sql .= " JOIN ".MAIN_DB_PREFIX."societe as s";
		$sql .= " ON a.fk_soc = s.rowid";
		$sql .= " WHERE s.nom = '".$db->escape(GETPOST("societe", 'alphanohtml'))."'";
		$sql .= " AND a.email = '".$db->escape(preg_replace('/\s+/', '', GETPOST("member_email", 'aZ09arobase')))."'";
		$sql .= " AND a.statut = 1";
		$sql .= " AND a.entity IN (".getEntity($object->element).")";
		$resql = $db->query($sql);
		if ($resql) {
			if ($db->num_rows($resql) == 1) {
				$obj = $db->fetch_object($resql);
				$object->fetch($obj->id);
				$memberfound = true;
			}
		} else {
			dol_print_error($db);
		}
	}

	if (!$memberfound && GETPOST("morphy") == 'phy' && GETPOSTISSET("lastname") && GETPOSTISSET("firstname") && !empty(GETPOST("member_email", 'aZ09arobase'))) {
		$sql = "SELECT rowid as id";
		$sql .= " FROM ".MAIN_DB_PREFIX."adherent";
		$sql .= " WHERE firstname = '".$db->escape(GETPOST("firstname", 'alphanohtml'))."'";
		$sql .= " AND lastname = '".$db->escape(GETPOST("lastname", 'alphanohtml'))."'";
		$sql .= " AND email = '".$db->escape(preg_replace('/\s+/', '', GETPOST("member_email", 'aZ09arobase')))."'";
		$sql .= " AND statut = 1";
		$sql .= " AND entity IN (".getEntity($object->element).")";
		$resql = $db->query($sql);
		if ($resql) {
			if ($db->num_rows($resql) == 1) {
				$obj = $db->fetch_object($resql);
				$object->fetch($obj->id);
				$memberfound = true;
			}
		} else {
			dol_print_error($db);
		}
	}

	if ($memberfound) {
		$action = 'subscription';
	}
}

// Action called when page is submitted
if (empty($reshook) && $action == 'add') {	// Test on permission not required here. This is an anonymous form. Check is done on constant to enable and mitigation.
	$error = 0;
	$urlback = '';

	$db->begin();

	$morphy = GETPOST("morphy", 'alphanohtml');
	$lastname = GETPOST("lastname", 'alphanohtml');
	$firstname = GETPOST("firstname", 'alphanohtml');
	$societe = GETPOST("societe", 'alphanohtml');
	$email = preg_replace('/\s+/', '', GETPOST("member_email", 'aZ09arobase'));
	$country_id = getDolGlobalInt("MEMBER_NEWFORM_FORCECOUNTRYCODE", GETPOSTINT('country_id'));

	if (!in_array($morphy, array('mor', 'phy'))) {
		$error++;
		$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('MemberNature'))."<br>\n";
	}

	// test if login already exists
	if (!getDolGlobalString('ADHERENT_LOGIN_NOT_REQUIRED')) {
		if (!GETPOST('member_email')) {
			$error++;
			$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("EMail"))."<br>\n";
		}
		if (!GETPOST('login')) {
			$error++;
			$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Login"))."<br>\n";
		}
		$sql = "SELECT login FROM ".MAIN_DB_PREFIX."adherent WHERE login = '".$db->escape(GETPOST('login'))."'";
		$result = $db->query($sql);
		if ($result) {
			$num = $db->num_rows($result);
		}
		if ($num != 0) {
			$error++;
			$langs->load("errors");
			$errmsg .= $langs->trans("ErrorLoginAlreadyExists")."<br>\n";
		}
		if (!GETPOSTISSET("pass1") || !GETPOSTISSET("pass2") || GETPOST("pass1", 'none') == '' || GETPOST("pass2", 'none') == '' || GETPOST("pass1", 'none') != GETPOST("pass2", 'none')) {
			$error++;
			$langs->load("errors");
			$errmsg .= $langs->trans("ErrorPasswordsMustMatch")."<br>\n";
		}
	}
	if (GETPOST('typeid') <= 0) {
		$error++;
		$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type"))."<br>\n";
	}

	if ($morphy && $morphy != 'mor' && empty($lastname)) {
		$error++;
		$langs->load("errors");
		$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentities("Lastname"));
	}
	if ($morphy && $morphy != 'mor' && (!isset($firstname) || $firstname == '')) {
		$error++;
		$langs->load("errors");
		$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentities("Firstname"));
	}
	if ($morphy == 'mor' && empty($societe)) {
		$error++;
		$langs->load("errors");
		$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentities("Company"));
	}
	if (empty($country_id)) {
		$error++;
		$langs->load("errors");
		$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentities("Country"));
	}
	if (getDolGlobalString('ADHERENT_MAIL_REQUIRED') && $email && !isValidEmail($email)) {
		$error++;
		$langs->load("errors");
		$errmsg .= $langs->trans("ErrorBadEMail", $email);
	}
	$birthday = dol_mktime(GETPOSTINT("birthhour"), GETPOSTINT("birthmin"), GETPOSTINT("birthsec"), GETPOSTINT("birthmonth"), GETPOSTINT("birthday"), GETPOSTINT("birthyear"));
	if (GETPOST("birthmonth") && empty($birthday)) {
		$error++;
		$langs->load("errors");
		$errmsg .= $langs->trans("ErrorBadDateFormat")."<br>\n";
	}

	// TODO Add this in a hook
	if (getDolGlobalString('MEMBER_NEWFORM_DOLIBARRTURNOVER')) {
		if (GETPOST("morphy") == 'mor' && GETPOSTFLOAT('budget') <= 0) {
			$error++;
			$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TurnoverOrBudget"))."<br>\n";
		}
	}

	// Check Captcha code if is enabled
	$ok = false;
	if (getDolGlobalString('MAIN_SECURITY_ENABLECAPTCHA_MEMBER') && is_object($captchaobj)) {
		if (method_exists($captchaobj, 'validateCodeAfterLoginSubmit')) {
			$ok = $captchaobj->validateCodeAfterLoginSubmit();  // @phan-suppress-current-line PhanUndeclaredMethod
		} else {
			print 'Error, the captcha handler '.get_class($captchaobj).' does not have any method validateCodeAfterLoginSubmit()';
		}
		if (!$ok) {
			$error++;
			$langs->load("errors");
			$errmsg .= $langs->trans("ErrorBadValueForCode")."<br>\n";
			$action = '';
		}
	}

	$public = GETPOSTISSET('public') ? 1 : 0;

	if (!$error) {
		// E-mail looks OK and login does not exist
		$adh = new Adherent($db);
		$adh->statut      = -1;
		$adh->status      = -1;
		$adh->public      = $public;
		$adh->firstname   = GETPOST('firstname');
		$adh->lastname    = GETPOST('lastname');
		$adh->gender      = GETPOST('gender');
		$adh->civility_id = GETPOST('civility_id');
		$adh->company     = GETPOST('societe');
		$adh->societe     = $adh->company;
		$adh->address     = GETPOST('address');
		$adh->zip         = GETPOST('zipcode');
		$adh->town        = GETPOST('town');
		$adh->email       = GETPOST('member_email', 'aZ09arobase');
		if (!getDolGlobalString('ADHERENT_LOGIN_NOT_REQUIRED')) {
			$adh->login = GETPOST('login');
			$adh->pass = GETPOST('pass1', 'password');
		}
		$adh->photo       = GETPOST('photo');
		$adh->country_id  = getDolGlobalInt("MEMBER_NEWFORM_FORCECOUNTRYCODE", GETPOSTINT('country_id'));
		$adh->state_id    = GETPOSTINT('state_id');
		$adh->typeid      = getDolGlobalInt("MEMBER_NEWFORM_FORCETYPE", GETPOSTINT('typeid'));
		$adh->note_private = GETPOST('note_private');
		$adh->morphy      = getDolGlobalString("MEMBER_NEWFORM_FORCEMORPHY", GETPOST('morphy'));
		$adh->birth       = $birthday;
		$adh->phone   = GETPOST('phone');
		$adh->phone_perso = GETPOST('phone_perso');
		$adh->phone_mobile= GETPOST('phone_mobile');

		$adh->ip = getUserRemoteIP();

		$nb_post_max = getDolGlobalInt("MAIN_SECURITY_MAX_POST_ON_PUBLIC_PAGES_BY_IP_ADDRESS", 200);
		$now = dol_now();
		$minmonthpost = dol_time_plus_duree($now, -1, "m");
		// Calculate nb of post for IP
		$nb_post_ip = 0;
		if ($nb_post_max > 0) {	// Calculate only if there is a limit to check
			$sql = "SELECT COUNT(ref) as nb_adh";
			$sql .= " FROM ".MAIN_DB_PREFIX."adherent";
			$sql .= " WHERE ip = '".$db->escape($adh->ip)."'";
			$sql .= " AND datec > '".$db->idate($minmonthpost)."'";
			$resql = $db->query($sql);
			if ($resql) {
				$num = $db->num_rows($resql);
				$i = 0;
				while ($i < $num) {
					$i++;
					$obj = $db->fetch_object($resql);
					$nb_post_ip = $obj->nb_adh;
				}
			}
		}


		// Fill array 'array_options' with data from add form
		$extrafields->fetch_name_optionals_label($adh->table_element);
		$ret = $extrafields->setOptionalsFromPost(null, $adh);
		if ($ret < 0) {
			$error++;
			$errmsg .= $adh->error;
		}

		if ($nb_post_max > 0 && $nb_post_ip >= $nb_post_max) {
			$error++;
			$errmsg .= $langs->trans("AlreadyTooMuchPostOnThisIPAdress");
			array_push($adh->errors, $langs->trans("AlreadyTooMuchPostOnThisIPAdress"));
		}

		if (!$error) {
			$result = $adh->create($user);
			if ($result > 0) {
				require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
				$object = $adh;

				$adht = new AdherentType($db);
				$adht->fetch($object->typeid);

				if ($object->email) {
					$subject = '';
					$msg = '';

					// Send subscription email
					include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
					$formmail = new FormMail($db);
					// Set output language
					$outputlangs = new Translate('', $conf);
					$outputlangs->setDefaultLang(empty($object->thirdparty->default_lang) ? $mysoc->default_lang : $object->thirdparty->default_lang);
					// Load traductions files required by page
					$outputlangs->loadLangs(array("main", "members"));
					// Get email content from template
					$arraydefaultmessage = null;
					$labeltouse = getDolGlobalString('ADHERENT_EMAIL_TEMPLATE_AUTOREGISTER');

					if (!empty($labeltouse)) {
						$arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse);
					}

					if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
						$subject = $arraydefaultmessage->topic;
						$msg     = $arraydefaultmessage->content;
					}

					$substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
					complete_substitutions_array($substitutionarray, $outputlangs, $object);
					$subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
					$texttosend = make_substitutions(dol_concatdesc($msg, $adht->getMailOnValid()), $substitutionarray, $outputlangs);

					if ($subjecttosend && $texttosend) {
						$moreinheader = 'X-Dolibarr-Info: send_an_email by public/members/new.php'."\r\n";

						$result = $object->sendEmail($texttosend, $subjecttosend, array(), array(), array(), "", "", 0, -1, '', $moreinheader);
					}
					/*if ($result < 0) {
						$error++;
						setEventMessages($object->error, $object->errors, 'errors');
					}*/
				}

				// Send email to the foundation to say a new member subscribed with autosubscribe form
				if (getDolGlobalString('MAIN_INFO_SOCIETE_MAIL') && getDolGlobalString('ADHERENT_AUTOREGISTER_NOTIF_MAIL_SUBJECT') &&
					getDolGlobalString('ADHERENT_AUTOREGISTER_NOTIF_MAIL')) {
					// Define link to login card
					$appli = constant('DOL_APPLICATION_TITLE');
					if (getDolGlobalString('MAIN_APPLICATION_TITLE')) {
						$appli = getDolGlobalString('MAIN_APPLICATION_TITLE');
						if (preg_match('/\d\.\d/', $appli)) {
							if (!preg_match('/'.preg_quote(DOL_VERSION, '/').'/', $appli)) {
								$appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core
							}
						} else {
							$appli .= " ".DOL_VERSION;
						}
					} else {
						$appli .= " ".DOL_VERSION;
					}

					$to = $adh->makeSubstitution(getDolGlobalString('MAIN_INFO_SOCIETE_MAIL'));
					$from = getDolGlobalString('ADHERENT_MAIL_FROM', $conf->email_from);
					$mailfile = new CMailFile(
						'['.$appli.'] ' . getDolGlobalString('ADHERENT_AUTOREGISTER_NOTIF_MAIL_SUBJECT'),
						$to,
						$from,
						$adh->makeSubstitution(getDolGlobalString('ADHERENT_AUTOREGISTER_NOTIF_MAIL')),
						array(),
						array(),
						array(),
						"",
						"",
						0,
						-1
					);

					if (!$mailfile->sendfile()) {
						dol_syslog($langs->trans("ErrorFailedToSendMail", $from, $to), LOG_ERR);
					}
				}

				// Auto-create thirdparty on member creation
				if (getDolGlobalString('ADHERENT_DEFAULT_CREATE_THIRDPARTY')) {
					$company = new Societe($db);
					$result = $company->create_from_member($adh);
					if ($result < 0) {
						$error++;
						$errmsg .= implode('<br>', $company->errors);
					}
				}

				if (!empty($backtopage)) {
					$urlback = $backtopage;
				} elseif (getDolGlobalString('MEMBER_URL_REDIRECT_SUBSCRIPTION')) {
					$urlback = getDolGlobalString('MEMBER_URL_REDIRECT_SUBSCRIPTION');
					// TODO Make replacement of __AMOUNT__, etc...
				} else {
					$urlback = $_SERVER["PHP_SELF"]."?action=added&token=".newToken();
				}

				if (getDolGlobalString('MEMBER_NEWFORM_PAYONLINE') && getDolGlobalString('MEMBER_NEWFORM_PAYONLINE') != '-1') {
					if (empty($adht->caneditamount)) {			// If edition of amount not allowed
						// TODO Check amount is same than the amount required for the type of member or if not defined as the default amount into $conf->global->MEMBER_NEWFORM_AMOUNT
						// It is not so important because a test is done on return of payment validation.
					}

					$urlback = getOnlinePaymentUrl(0, 'member', $adh->ref, (float) price2num(GETPOST('amount', 'alpha'), 'MT'), '', 0);

					if (GETPOST('member_email')) {
						$urlback .= '&email='.urlencode(GETPOST('member_email'));
					}
					if (getDolGlobalString('MEMBER_NEWFORM_PAYONLINE') != '-1' && getDolGlobalString('MEMBER_NEWFORM_PAYONLINE') != 'all') {
						$urlback .= '&paymentmethod='.urlencode(getDolGlobalString('MEMBER_NEWFORM_PAYONLINE'));
					}
				} else {
					if (!empty($entity)) {
						$urlback .= '&entity='.((int) $entity);
					}
				}
			} else {
				$error++;
				$errmsg .= implode('<br>', $adh->errors);
			}
		}
	}

	if (!$error) {
		$db->commit();

		header("Location: ".$urlback);
		exit;
	} else {
		$db->rollback();
		$action = "create";
	}
}

// Action called after a submitted was send and member created successfully
// If MEMBER_URL_REDIRECT_SUBSCRIPTION is set to an url, we never go here because a redirect was done to this url. Same if we ask to redirect to the payment page.
// backtopage parameter with an url was set on member submit page, we never go here because a redirect was done to this url.

if (empty($reshook) && $action == 'added') {	// Test on permission not required here
	llxHeaderVierge($langs->trans("NewMemberForm"));

	// If we have not been redirected
	print '<br><br>';
	print '<div class="center">';
	print $langs->trans("NewMemberbyWeb");
	print '</div>';

	llxFooterVierge();
	exit;
}


/*
 * View
 */

$form = new Form($db);
$formcompany = new FormCompany($db);
$adht = new AdherentType($db);
$extrafields->fetch_name_optionals_label($object->table_element); // fetch optionals attributes and labels


llxHeaderVierge($langs->trans("NewSubscription"));

print '<br>';
print load_fiche_titre(img_picto('', 'member_nocolor', 'class="pictofixedwidth"').' &nbsp; '.$langs->trans("NewSubscription"), '', '', 0, '', 'center');


print '<div align="center">';
print '<div id="divsubscribe">';

print '<div class="center subscriptionformhelptext opacitymedium justify">';
if (getDolGlobalString('MEMBER_NEWFORM_TEXT')) {
	print $langs->trans(getDolGlobalString('MEMBER_NEWFORM_TEXT'))."<br>\n";
} else {
	print $langs->trans("NewSubscriptionDesc", getDolGlobalString("MAIN_INFO_SOCIETE_MAIL"))."<br>\n";
}
print '</div>';

dol_htmloutput_errors($errmsg);
dol_htmloutput_events();

if ($action == "subscription") {
	$urltocall = DOL_URL_ROOT.'/public/payment/newpayment.php?source=member&ref='.$object->id;
	print $form->formconfirm($urltocall, $langs->trans("CorrespondingMemberFound"), $langs->trans("CorrespondingMemberFoundQuestion"), "confirm_subscription", '', 'no', 1);
}

// Print form
print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="newmember" id="newmember">'."\n";
print '<input type="hidden" name="token" value="'.newToken().'" />';
print '<input type="hidden" name="entity" value="'.$entity.'" />';
print '<input type="hidden" name="page_y" value="" />';

if (getDolGlobalString('MEMBER_SKIP_TABLE') || getDolGlobalString('MEMBER_NEWFORM_FORCETYPE') || in_array($action, array('create', 'subscription'))) {
	if ($action == 'subscription') {
		print '<input type="hidden" name="nofetchmember" value="nofetchmember" />';
	}
	print '<input type="hidden" name="action" value="add" />';
	print '<br>';

	//$messagemandatory = '<span class="">'.$langs->trans("FieldsWithAreMandatory", '*').'</span>';
	//print '<br>'.$messagemandatory.'<br>';
	//print $langs->trans("FieldsWithIsForPublic",'**').'<br>';

	print dol_get_fiche_head();

	if ($conf->use_javascript_ajax) {
		print "\n".'<script type="text/javascript">'."\n";
		print 'jQuery(document).ready(function () {
			jQuery("#selectcountry_id").change(function() {
				console.log("We change country, so we reload page");
				document.newmember.action.value="create";
				jQuery("#newmember").submit();
			});
			function initfieldrequired() {
				console.log("initfieldrequired");
				jQuery("#tdcompany").removeClass("fieldrequired");
				jQuery("#tdlastname").removeClass("fieldrequired");
				jQuery("#tdfirstname").removeClass("fieldrequired");
				if (jQuery(\'input[name="morphy"]:checked\').val() == \'mor\') {
					jQuery("#tdcompany").addClass("fieldrequired");
				}
				if (jQuery(\'input[name="morphy"]:checked\').val() == \'phy\') {
					jQuery("#tdlastname").addClass("fieldrequired");
					jQuery("#tdfirstname").addClass("fieldrequired");
				}
			}
			jQuery(\'input[name="morphy"]\').change(function() {
				initfieldrequired();
			});
			initfieldrequired();
		})';
		print '</script>'."\n";
	}

	print '<table class="border" summary="form to subscribe" id="tablesubscribe">'."\n";

	// Type
	if (!getDolGlobalString('MEMBER_NEWFORM_FORCETYPE')) {
		$typeid = GETPOSTINT("typeid");
		print '<tr><td class="fieldrequired titlefieldmiddle">'.$langs->trans("MemberType").'</td><td>';
		$listetype = $adht->liste_array(1);
		print img_picto('', $adht->picto, 'class="pictofixedwidth"');
		if (count($listetype)) {
			print $form->selectarray("typeid", $listetype, (GETPOSTINT('typeid') ? GETPOSTINT('typeid') : $typeid), (count($listetype) > 1 ? 1 : 0), 0, 0, '', 0, 0, 0, '', 'minwidth150 maxwidth300 widthcentpercentminusx', 1);
		} else {
			print '<span class="error">'.$langs->trans("NoTypeDefinedGoToSetup").'</span>';
		}
		print '</td></tr>'."\n";
	} else {
		$adht->fetch(getDolGlobalInt('MEMBER_NEWFORM_FORCETYPE'));
		print '<input type="hidden" id="typeid" name="typeid" value="' . getDolGlobalString('MEMBER_NEWFORM_FORCETYPE').'">';
	}

	// Moral/Physic attribute
	$morphys = [
		"phy" => $langs->trans("Physical"),
		"mor" => $langs->trans("Moral"),
	];
	$checkednature = GETPOST("morphy", 'alpha');
	$listetype_natures = $adht->morphyByType(1);		// Load the array of morphy per typeof membership
	$listetype_natures_json = json_encode($listetype_natures);

	if (!getDolGlobalString('MEMBER_NEWFORM_FORCEMORPHY')) {
		if (empty($checkednature) && !empty($listetype_natures[GETPOSTINT('typeid')])) {
			$checkednature = $listetype_natures[GETPOSTINT('typeid')];
		}

		print '<tr><td class="fieldrequired titlefieldmiddle">'.$langs->trans("MemberNature")."</td><td>\n";

		$disabledphy = '';
		$disabledmor = '';
		//$disabledphy = ($checkednature == "mor" ? ' disabled="disabled"' : '');
		//$disabledmor = ($checkednature == "phy" ? ' disabled="disabled"' : '');
		print '<span id="spannature1" class="nonature-back spannature paddinglarge marginrightonly"><label for="phisicalinput" class="valignmiddle">'.$morphys["phy"].'<input id="phisicalinput" class="flat checkforselect marginleftonly valignmiddle" type="radio" name="morphy" value="phy"'.($checkednature == "phy" ? ' checked="checked"' : '').$disabledphy.'></label></span>';
		print '<span id="spannature2" class="nonature-back spannature paddinglarge marginrightonly"><label for="moralinput" class="valignmiddle">'.$morphys["mor"].'<input id="moralinput" class="flat checkforselect marginleftonly valignmiddle" type="radio" name="morphy" value="mor"'.($checkednature == "mor" ? ' checked="checked"' : '').$disabledmor.'></label></span>';

		// Add JS to manage the background of nature
		if ($conf->use_javascript_ajax) {
			print '<script>
				var listetype_natures = '.$listetype_natures_json.';

				jQuery(function($) {
					function refreshNatureCss() {
						$(".spannature").each(function(index) {
							let $span = $("#spannature" + (index + 1));
							let checked = $span.find(".checkforselect").is(":checked");

							if (checked) {
								if (index === 0) {
									$span.addClass("member-individual-back").removeClass("nonature-back member-company-back");
								} else if (index === 1) {
									$span.addClass("member-company-back").removeClass("nonature-back member-individual-back");
								}
							} else {
								$span.removeClass("member-individual-back member-company-back")
									.addClass("nonature-back");
							}
						});
					}

					$(".spannature").on("click", function() {
						console.log("Nature clicked");
						refreshNatureCss();
					});

					$("#typeid").on("change", function() {
						console.log("Type of membership is modified");
						let morphy = listetype_natures[$(this).val()];
						console.log("morphy="+morphy);

						let $phyInput = $("#phisicalinput");
						let $morInput = $("#moralinput");
						let $tdLast = $("#tdlastname");
						let $tdFirst = $("#tdfirstname");
						let $tdCompany = $("#tdcompany");
						let $span1 = $("#spannature1");
						let $span2 = $("#spannature2");

						switch (morphy) {
							case "phy":
								/* $phyInput.prop({disabled: false, checked: true});
								$morInput.prop({disabled: true, checked: false}); */
								$span1.addClass("member-individual-back").removeClass("nonature-back");
								$span2.removeClass("member-company-back").addClass("nonature-back");
								$tdLast.addClass("fieldrequired");
								$tdFirst.addClass("fieldrequired");
								$tdCompany.removeClass("fieldrequired");
								break;

							case "mor":
								/* $phyInput.prop({disabled: true, checked: false});
								$morInput.prop({disabled: false, checked: true}); */
								$span2.addClass("member-company-back").removeClass("nonature-back");
								$span1.removeClass("member-individual-back").addClass("nonature-back");
								$tdCompany.addClass("fieldrequired");
								$tdLast.removeClass("fieldrequired");
								$tdFirst.removeClass("fieldrequired");
								break;

							default:';
			if ($action != "subscription" && !GETPOST('morphy')) {
				print '
				$phyInput.prop({disabled: false, checked: false});
				$morInput.prop({disabled: false, checked: false});
				$span1.removeClass("member-individual-back").addClass("nonature-back");
				$span2.removeClass("member-company-back").addClass("nonature-back");';
			}
			print'}
					});

					// Initial state
					refreshNatureCss();
				});
			</script>';
		}
			print '</td></tr>'."\n";
	} else {
		//print $morphys[$conf->global->MEMBER_NEWFORM_FORCEMORPHY];
		print '<input type="hidden" id="morphy" name="morphy" value="' . getDolGlobalString('MEMBER_NEWFORM_FORCEMORPHY').'">';
	}

	// Company   // TODO : optional hide
	print '<tr id="trcompany" class="trcompany"><td id="tdcompany" class="titlefieldmiddle paddingrightonly'.($checkednature == "mor" ? ' fieldrequired"' : '').'">'.$langs->trans("Company").'</td><td>';
	print img_picto('', 'company', 'class="pictofixedwidth paddingright"');
	print '<input type="text" name="societe" class="minwidth150 widthcentpercentminusx" value="'.dol_escape_htmltag(GETPOST('societe')).'"></td></tr>'."\n";

	// Title
	if (getDolGlobalString('MEMBER_NEWFORM_ASK_TITLE')) {
		print '<tr><td>'.$langs->trans('UserTitle').'</td><td>';
		print $formcompany->select_civility(GETPOST('civility_id'), 'civility_id').'</td></tr>'."\n";
	}

	// Firstname
	print '<tr><td id="tdfirstname" class="classfortooltip'.($checkednature == "phy" ? ' fieldrequired"' : '').'">'.$langs->trans("Firstname").'</td><td><input type="text" name="firstname" class="minwidth150" value="'.dol_escape_htmltag(GETPOST('firstname')).'"></td></tr>'."\n";

	// Lastname
	print '<tr><td id="tdlastname" class="classfortooltip'.($checkednature == "phy" ? ' fieldrequired"' : '').'">'.$langs->trans("Lastname").'</td><td><input type="text" name="lastname" class="minwidth150" value="'.dol_escape_htmltag(GETPOST('lastname')).'"></td></tr>'."\n";

	// EMail
	print '<tr><td>'.(getDolGlobalString('ADHERENT_MAIL_REQUIRED') ? '<span class="fieldrequired">' : '').$langs->trans("EMail").(getDolGlobalString('ADHERENT_MAIL_REQUIRED') ? '</span>' : '').'</td>';
	print '<td>'.img_picto('', 'object_email').' <input type="text" name="member_email" class="minwidth150 maxwidth300 widthcentpercentminusx" maxlength="255" value="'.dol_escape_htmltag(GETPOST('member_email', "aZ09arobase")).'"></td></tr>'."\n";

	// Login
	if (!getDolGlobalString('ADHERENT_LOGIN_NOT_REQUIRED')) {
		print '<tr><td><span class="fieldrequired">'.$langs->trans("Login").' / '.$langs->trans("Id").'</span></td><td><input type="text" name="login" maxlength="50" class="minwidth100" value="'.(GETPOSTISSET("login") ? GETPOST("login", 'alphanohtml', 2) : $object->login).'"></td></tr>'."\n";
		print '<tr><td><span class="fieldrequired">'.$langs->trans("Password").'</span></td><td><input type="password" maxlength="128" name="pass1" class="minwidth100" value="'.dol_escape_htmltag(GETPOST("pass1", "none", 2)).'"></td></tr>'."\n";
		print '<tr><td><span class="fieldrequired">'.$langs->trans("PasswordRetype").'</span></td><td><input type="password" maxlength="128" name="pass2" class="minwidth100" value="'.dol_escape_htmltag(GETPOST("pass2", "none", 2)).'"></td></tr>'."\n";
	}

	// Gender
	print '<tr><td>'.$langs->trans("Gender").'</td>';
	print '<td>';
	$arraygender = array('man' => $langs->trans("Genderman"), 'woman' => $langs->trans("Genderwoman"), 'other' => $langs->trans("Genderother"));
	print $form->selectarray('gender', $arraygender, GETPOST('gender', 'alphanohtml'), 1, 0, 0, '', 0, 0, 0, '', 'minwidth150 maxwidth300 widthcentpercentminusx', 1);
	print '</td></tr>';

	// Address
	print '<tr><td>'.$langs->trans("Address").'</td><td>'."\n";
	print '<textarea name="address" id="address" wrap="soft" class="quatrevingtpercent" rows="'.ROWS_3.'">'.dol_escape_htmltag(GETPOST('address', 'restricthtml'), 0, 1).'</textarea></td></tr>'."\n";

	// Zip / Town
	print '<tr><td>'.$langs->trans('Zip').' / '.$langs->trans('Town').'</td><td>';
	print $formcompany->select_ziptown(GETPOST('zipcode'), 'zipcode', array('town', 'selectcountry_id', 'state_id'), 0, 1, '', 'width75');
	print ' / ';
	print $formcompany->select_ziptown(GETPOST('town'), 'town', array('zipcode', 'selectcountry_id', 'state_id'), 0, 1);
	print '</td></tr>';

	$country_id = GETPOSTINT('country_id');

	// Country
	print '<tr><td class="fieldrequired">'.$langs->trans('Country').'</td><td>';
	print img_picto('', 'country', 'class="pictofixedwidth paddingright"');
	if (!$country_id && getDolGlobalString('MEMBER_NEWFORM_FORCECOUNTRYCODE')) {
		$country_id = getCountry(getDolGlobalString('MEMBER_NEWFORM_FORCECOUNTRYCODE'), '2', $db, $langs);
	}
	if (!$country_id && !empty($conf->geoipmaxmind->enabled)) {
		$country_code = dol_user_country();
		//print $country_code;
		if ($country_code) {
			$new_country_id = getCountry($country_code, '3', $db, $langs);
			//print 'xxx'.$country_code.' - '.$new_country_id;
			if ($new_country_id) {
				$country_id = $new_country_id;
			}
		}
	}
	$country_code = getCountry($country_id, '2', $db, $langs);
	print $form->select_country($country_id, 'country_id', '', 0, 'minwidth150 maxwidth300 widthcentpercentminusx reposition');
	print '</td></tr>';

	// State
	if (!getDolGlobalString('SOCIETE_DISABLE_STATE')) {
		print '<tr><td>'.$langs->trans('State').'</td><td>';
		if ($country_code) {
			print img_picto('', 'state', 'class="pictofixedwidth paddingright"');
			print $formcompany->select_state(GETPOSTINT("state_id"), $country_code, 'state_id', 'minwidth150 maxwidth300 widthcentpercentminusx');
		}
		print '</td></tr>';
	}

	// Pro phone
	print '<tr><td>'.$langs->trans("PhonePro").'</td>';
	print '<td>'.img_picto('', 'object_phoning', 'class="pictofixedwidth"').'<input type="text" name="phone" class="maxwidth300 widthcentpercentminusx" value="'.dol_escape_htmltag(GETPOST('phone')).'"></td></tr>';

	// Personal phone
	print '<tr><td>'.$langs->trans("PhonePerso").'</td>';
	print '<td>'.img_picto('', 'object_phoning', 'class="pictofixedwidth"').'<input type="text" name="phone_perso" class="maxwidth300 widthcentpercentminusx" value="'.dol_escape_htmltag(GETPOST('phone_perso')).'"></td></tr>';

	// Mobile phone
	print '<tr><td>'.$langs->trans("PhoneMobile").'</td>';
	print '<td>'.img_picto('', 'object_phoning_mobile', 'class="pictofixedwidth"').'<input type="text" name="phone_mobile" class="maxwidth300 widthcentpercentminusx" value="'.dol_escape_htmltag(GETPOST('phone_mobile')).'"></td></tr>';

	// Birthday
	print '<tr id="trbirth" class="trbirth"><td>'.$langs->trans("DateOfBirth").'</td><td>';
	print $form->selectDate(!empty($birthday) ? $birthday : "", 'birth', 0, 0, 1, "newmember", 1, 0);
	print '</td></tr>'."\n";

	// Photo
	print '<tr><td>'.$langs->trans("URLPhoto").'</td><td><input type="text" name="photo" class="minwidth150" value="'.dol_escape_htmltag(GETPOST('photo')).'"></td></tr>'."\n";

	// Public
	if (getDolGlobalString('MEMBER_PUBLIC_ENABLED')) {
		$linkofpubliclist = DOL_MAIN_URL_ROOT.'/public/members/public_list.php'.((isModEnabled('multicompany')) ? '?entity='.$conf->entity : '');
		$publiclabel = $langs->trans("Public", getDolGlobalString('MAIN_INFO_SOCIETE_NOM'), $linkofpubliclist);
		print '<tr><td>'.$form->textwithpicto($langs->trans("MembershipPublic"), $publiclabel).'</td><td><input type="checkbox" name="public"></td></tr>'."\n";
	}

	// Other attributes
	$parameters['tpl_context'] = 'public';	// define template context to public
	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php';

	// Comments
	print '<tr>';
	print '<td class="tdtop"></td>';
	print '<td class="tdtop"><textarea placeholder="'.dolPrintHTML($langs->trans("Comments")).'" name="note_private" id="note_private" wrap="soft" class="quatrevingtpercent" rows="'.ROWS_3.'">'.dol_escape_htmltag(GETPOST('note_private', 'restricthtml'), 0, 1).'</textarea></td>';
	print '</tr>'."\n";


	// Define amount by default to suggest
	$typeid = getDolGlobalInt('MEMBER_NEWFORM_FORCETYPE', GETPOSTINT('typeid'));
	$adht = new AdherentType($db);
	$adht->fetch($typeid);
	$caneditamount = $adht->caneditamount;
	$amountbytype = $adht->amountByType(1);		// Load the array of amount per type
	foreach ($amountbytype as $k => $v) {
		$amount = max(0, (float) $v, (float) getDolGlobalInt("MEMBER_NEWFORM_AMOUNT"));
		$amountbytype[$k] = $amount;
	}

	$amountbytype_json = json_encode($amountbytype);
	$caneditamountbytype = $adht->caneditamountByType(1);		// Load the array of caneditamount per type
	$caneditamountbytype_json = json_encode($caneditamountbytype);


	// Set amount for the subscription from the the type and options:
	// - First check the amount of the member type.
	$amount = empty($amountbytype[$typeid]) ? 0 : $amountbytype[$typeid];
	// - If not found, take the default amount only if the user is authorized to edit it
	if (empty($amount) && getDolGlobalString('MEMBER_NEWFORM_AMOUNT')) {
		$amount = getDolGlobalString('MEMBER_NEWFORM_AMOUNT');
	}
	// - If not set, we accept to have amount defined as parameter (for backward compatibility).
	if (empty($amount)) {
		$amount = (GETPOST('amount') ? price2num(GETPOST('amount', 'alpha'), 'MT', 2) : '');
	}
	// - If a min is set, we take it into account
	$amount = max(0, (float) $amount, (float) getDolGlobalInt("MEMBER_MIN_AMOUNT"));

	// Clean the amount
	$amount = price2num($amount);



	// Add hook to complete the form
	$parameters = array('country_id' => $country_id, 'mode' => 'new');
	$reshook = $hookmanager->executeHooks('membershipNewSubscriptionPublicForm', $parameters, $object, $action);
	if ($reshook < 0) {
		setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
		$error++;
	}
	// TODO Move this into previous hook
	if (getDolGlobalString('MEMBER_NEWFORM_DOLIBARRTURNOVER')) {
		// Do not set a default amount MEMBER_NEWFORM_AMOUNT if you use MEMBER_NEWFORM_DOLIBARRTURNOVER
		$s = $langs->trans("AreYouAPreferredPartner", '<a href="https://partners.dolibarr.org" target="_blank">{s1}</a>');
		$s = str_replace('{s1}', 'Peferred Partner', $s);
		print '<tr id="trbudget" class="trcompany"><td class="paddingrightonly"><label for="pp" class="small">'.$s.'</label></td><td>';
		print '<input type="checkbox" name="pp" id="pp" value="1"'.(GETPOST('pp') ? ' checked="checked"' : '').' class="reposition">';
		print '</td></tr>';

		print '<tr id="trbudget" class="trcompany"><td class="fieldrequired paddingrightonly"><span class="small">'.$langs->trans("TurnoverOrBudget").'</span></td><td>';

		$country_code = dol_getIdFromCode($db, $country_id, 'c_country', 'rowid', 'code');
		if ($country_code === 'FR' && $checkednature === 'mor' && GETPOST('pp')) {
			print '<input type="text" name="budget" id="budget" class="flat turnover right width100" value="'.GETPOST('budget').'" required>';
		} else {
			$arraybudget = array('50' => '<= 100 000', '100' => '<= 200 000', '200' => '<= 500 000', '300' => '<= 1 500 000', '600' => '<= 3 000 000', '1000' => '<= 5 000 000', '2000' => '5 000 000+');
			print $form->selectarray('budget', $arraybudget, GETPOSTINT('budget'), 1, 0, '', 0, 0, 0, '');
		}
		print ' € or $';

		print '<script type="text/javascript">
		jQuery(document).ready(function() {
			firstload = true;

			newamount = initturnover();
			jQuery("#amount").val(newamount);

			firstload = false;

			jQuery("#selectcountry_id").change(function() {
				console.log("We change country (code added for association, replace common code), so we reload page");
				jQuery("#budget").val(\'\');
				jQuery("#amount").val(\'\');
				jQuery("#amounthidden").val(\'\');
			});
			jQuery("#phisicalinput,#moralinput").click(function() {
				console.log("We change the nature of membership");
				newamount = initturnover();
				jQuery("#amount").val(newamount);
			});
			jQuery("#pp").change(function() {
				console.log("We change the preferred partner status");
				selectcountry_id = jQuery("#selectcountry_id").val();
				morphy = jQuery("#moralinput").is(\':checked\') ? \'mor\' : \'phy\';
				jQuery("#budget").val(\'\');
				jQuery("#amount").val(\'\');
				jQuery("#amounthidden").val(\'\');
				document.newmember.action.value="create";
				jQuery("#newmember").submit();
			});
			jQuery("#budget").change(function() {
				console.log("Turnover amount has been modified on change");
				newamount = initturnover();
				jQuery("#amount").val(newamount);
				jQuery("#amounthidden").val(newamount);
			});
			jQuery("#budget").keyup(function() {
				console.log("Turnover amount has been modified on keyup");
				newamount = initturnover();
				jQuery("#amount").val(newamount);
				jQuery("#amounthidden").val(newamount);
			});

			function initturnover() {
				newamount = 0;

				morphy = jQuery("#moralinput").is(\':checked\') ? \'mor\' : \'phy\';
				selectcountry_id = jQuery("#selectcountry_id").val();
				pp = jQuery("#pp").is(\':checked\') ? true : false;
				console.log("Set fields according to nature and other properties");
				console.log("morphy="+morphy);
				console.log("selectcountry_id="+selectcountry_id);
				console.log("pp="+pp);

				if (morphy == \'phy\') {
					jQuery(".amount").val('.((float) $amount).');
					jQuery("#trbirth").show();
					jQuery(".trcompany").hide();
					jQuery(".trbudget").hide();
					newamount = '.((float) $amount).';
				} else {
					jQuery(".amount").val(\'\');
					jQuery("#trbirth").hide();
					jQuery(".trcompany").show();
					jQuery(".trbudget").show();
					jQuery(".hideifautoturnover").hide();
					if (firstload) {
						jQuery("#budget").val(\'\');
					}

					if (selectcountry_id == 1) {
						if (pp) {
							console.log("value selected in input text field is "+jQuery("#budget").val());
							newamount = Math.max(Math.round(price2numjs(jQuery("#budget").val()) * 0.005), 50);
							console.log("newamount = "+newamount);
						} else {
							console.log("not a pp");
							if (jQuery("#budget").val() > 0) {
								console.log("value found in budget is "+jQuery("#budget").val());
								newamount = jQuery("#budget").val();
							} else {
								jQuery("#budget").val(\'\');
								newamount = \'\';
							}
						}
					} else {
						if (jQuery("#budget").val() > 0) {
							newamount = jQuery("#budget").val();
						} else {
							jQuery("#budget").val(\'\');
							newamount = \'\';
						}
						console.log("newamount="+newamount);
					}
				}

				return newamount;
			}
		});
		</script>';
		print '</td></tr>'."\n";
	}

	if (getDolGlobalString('MEMBER_NEWFORM_PAYONLINE')) {	// Can be 'all', 'paypal', 'paybox', 'stripe'...
		print '<tr><td>'.$langs->trans("Subscription");
		if (getDolGlobalString('MEMBER_EXT_URL_SUBSCRIPTION_INFO')) {
			print '<br>';
			print '<a href="' . getDolGlobalString('MEMBER_EXT_URL_SUBSCRIPTION_INFO').'" rel="external" target="_blank" rel="noopener noreferrer">';
			print img_picto('', 'url', 'class="pictofixedwidth"').$langs->trans("SeeHere");
			print '</a>';
		}
		print '</td><td class="nowrap">';

		if (empty($amount) && getDolGlobalString('MEMBER_NEWFORM_AMOUNT')) {
			$amount = getDolGlobalString('MEMBER_NEWFORM_AMOUNT');
		}

		$showedamount = $amount > 0 ? $amount : 0;
		if ($caneditamount === "1") {
			print '<input type="text" name="amount" id="amount" class="flat amount right width75" value="'.$showedamount.'">';
			print '<input type="text" name="amount" id="amounthidden" class="flat amount width75 hidden" disabled value="'.$showedamount.'">';
			print ' '.$langs->getCurrencySymbol($conf->currency).'<span class="opacitymedium hideifautoturnover small">';
			if (!getDolGlobalString('MEMBER_NEWFORM_DOLIBARRTURNOVER')) {
				print ' - ';
				print $amount > 0 ? $langs->trans("AnyAmountWithAdvisedAmount", price($amount, 0, $langs, 1, -1, -1, $conf->currency)) : $langs->trans("AnyAmountWithoutAdvisedAmount");
			}
			print '</span>';
		} else {
			print '<input type="text" name="amount" id="amount" class="flat amount width75 right hidden" value="'.$showedamount.'">';
			print '<input type="text" name="amount" id="amounthidden" class="flat amount width75" disabled value="'.$showedamount.'">';
			print ' '.$langs->getCurrencySymbol($conf->currency).'<span class="opacitymedium hideifautoturnover hidden small">';
			if (!getDolGlobalString('MEMBER_NEWFORM_DOLIBARRTURNOVER')) {
				print ' - ';
				print $amount > 0 ? $langs->trans("AnyAmountWithAdvisedAmount", price($amount, 0, $langs, 1, -1, -1, $conf->currency)) : $langs->trans("AnyAmountWithoutAdvisedAmount");
			}
			print '</span>';
		}
		print '</td></tr>';

		// Add JS to manage the background of amount depending on type
		if ($conf->use_javascript_ajax) {
			print "<script>
				var amountbytype = $amountbytype_json;
				var canEditAmount = $caneditamountbytype_json;
			</script>";

			print '<script>
			jQuery(function($) {
				$("#typeid").on("change", function() {
					console.log("Type of membership changed, we force amount update");
					let typeId = $(this).val();
					let amountVal = amountbytype[typeId] || 0;
					let formattedAmount = parseFloat(amountVal);

					if (canEditAmount[typeId] === "1") {
						// Editable mode
						$("#amount").val(formattedAmount).prop("disabled", false).removeClass("hidden");
						$("#amounthidden").addClass("hidden");
						$(".hideifautoturnover").removeClass("hidden");
					} else {
						// Read-only mode
						$("#amounthidden").val(formattedAmount).prop("disabled", true).removeClass("hidden");
						$("#amount").addClass("hidden");
						$(".hideifautoturnover").addClass("hidden");
					}
				});

				// Trigger it once so the amount matches the initial selection
				$("#typeid").trigger("change");
			});
			</script>';
		}
	}

	// Display Captcha code if is enabled
	if (getDolGlobalString('MAIN_SECURITY_ENABLECAPTCHA_MEMBER') && is_object($captchaobj)) {
		print '<tr><td><label><span class="fieldrequired">'.$langs->trans("SecurityCode").'</span></label></td><td><br>';
		if (method_exists($captchaobj, 'getCaptchaCodeForForm')) {
			print $captchaobj->getCaptchaCodeForForm('');  // @phan-suppress-current-line PhanUndeclaredMethod
		} else {
			print 'Error, the captcha handler '.get_class($captchaobj).' does not have any method getCaptchaCodeForForm()';
		}
		print '<br></td></tr>';
	}

	print "</table>\n";

	print dol_get_fiche_end();

	// Save / Submit
	print '<div class="center">';
	print '<input type="submit" value="'.$langs->trans("GetMembershipButtonLabel").'" id="submitsave" class="button">';
	if (!empty($backtopage)) {
		print ' &nbsp; &nbsp; <input type="submit" value="'.$langs->trans("Cancel").'" id="submitcancel" class="button button-cancel">';
	}
	print '</div>';


	print "</form>\n";
	print "<br>";
	print '</div></div>';
} else {  // Show the table of membership types
	// Get units
	$measuringUnits = new CUnits($db);
	$result = $measuringUnits->fetchAll('', '', 0, 0, array('t.active' => 1));
	$units = array();
	foreach ($measuringUnits->records as $lines) {
		$units[$lines->short_label] = $langs->trans(ucfirst((string) $lines->label));
	}

	$publiccounters = getDolGlobalString("MEMBER_COUNTERS_ARE_PUBLIC");
	$hidevoteallowed = getDolGlobalString("MEMBER_HIDE_VOTE_ALLOWED");

	$sql = "SELECT d.rowid, d.libelle as label, d.subscription, d.amount, d.caneditamount, d.vote, d.note, d.duration, d.statut as status, d.morphy,";
	$sql .= " COUNT(a.rowid) AS membercount";
	$sql .= " FROM ".MAIN_DB_PREFIX."adherent_type as d";
	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."adherent as a";
	$sql .= " ON d.rowid = a.fk_adherent_type AND a.statut > 0";
	$sql .= " WHERE d.entity IN (".getEntity('member_type').")";
	$sql .= " AND d.statut=1";
	$sql .= " GROUP BY d.rowid, d.libelle, d.subscription, d.amount, d.caneditamount, d.vote, d.note, d.duration, d.statut, d.morphy";

	$result = $db->query($sql);
	if ($result) {
		$num = $db->num_rows($result);

		print '<br><div class="div-table-responsive">';
		print '<table class="tagtable liste">'."\n";
		print '<input type="hidden" name="action" value="create">';

		print '<tr class="liste_titre">';
		print '<th>'.$langs->trans("Label").'</th>';
		print '<th class="center">'.$langs->trans("MembershipDuration").'</th>';
		print '<th class="center">'.$langs->trans("Amount").'</th>';
		print '<th class="center">'.$langs->trans("MembersNature").'</th>';
		if (empty($hidevoteallowed)) {
			print '<th class="center">'.$langs->trans("VoteAllowed").'</th>';
		}
		if ($publiccounters) {
			print '<th class="center">'.$langs->trans("Members").'</th>';
		}
		print '<th class="center">'.$langs->trans("NewSubscription").'</th>';
		print "</tr>\n";

		$i = 0;
		while ($i < $num) {
			$objp = $db->fetch_object($result);	// Load the member type and information on it

			$caneditamount = $objp->caneditamount;
			$amountbytype = $adht->amountByType(1);		// Load the array of amount per type

			print '<tr class="oddeven">';
			// Label
			print '<td>'.dolPrintHTML($objp->label).'</td>';
			// Duration
			print '<td class="center">';
			$unit = preg_replace("/[^a-zA-Z]+/", "", $objp->duration);
			print max(1, intval($objp->duration)).' '.$units[$unit];
			print '</td>';
			// Amount
			print '<td class="center"><span class="amount nowrap">';

			// Set amount for the subscription from the the type and options:
			// - First check the amount of the member type.
			$amount = empty($amountbytype[$objp->rowid]) ? 0 : $amountbytype[$objp->rowid];
			// - If not found, take the default amount only if the user is authorized to edit it
			if (empty($amount) && getDolGlobalString('MEMBER_NEWFORM_AMOUNT')) {
				$amount = getDolGlobalString('MEMBER_NEWFORM_AMOUNT');
			}
			// - If not set, we accept to have amount defined as parameter (for backward compatibility).
			if (empty($amount)) {
				$amount = (GETPOST('amount') ? price2num(GETPOST('amount', 'alpha'), 'MT', 2) : '');
			}
			// - If a min is set, we take it into account
			$amount = max(0, (float) $amount, (float) getDolGlobalInt("MEMBER_MIN_AMOUNT"));

			$displayedamount = $amount;

			if ($objp->subscription) {
				if ($displayedamount > 0 || !$caneditamount) {
					print price($displayedamount, 1, $langs, 1, 0, -1, $conf->currency);
				}
				if ($caneditamount && $displayedamount > 0) {
					print $form->textwithpicto('', $langs->transnoentities("CanEditAmountShortForValues"), 1, 'help', '', 0, 3);
				} elseif ($caneditamount) {
					print $langs->transnoentities("CanEditAmountShort");
				}
			} else {
				print "–"; // No subscription required
			}
			print '</span></td>';
			print '<td class="center">';
			if ($objp->morphy == 'phy') {
				print $langs->trans("Physical");
			} elseif ($objp->morphy == 'mor') {
				print $langs->trans("Moral");
			} else {
				print $langs->trans("MorAndPhy");
			}
			print '</td>';
			if (empty($hidevoteallowed)) {
				print '<td class="center">'.yn($objp->vote).'</td>';
			}
			$membercount = $objp->membercount > 0 ? $objp->membercount : "–";
			if ($publiccounters) {
				print '<td class="center">'.$membercount.'</td>';
			}
			print '<td class="center"><button class="button button-save reposition" name="typeid" type="submit" name="submit" value="'.$objp->rowid.'">'.$langs->trans("GetMembershipButtonLabel").'</button></td>';
			print "</tr>";
			$i++;
		}

		// If no record found
		if ($num == 0) {
			$colspan = 8;
			print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>';
		}

		print "</table>";
		print '</div>';

		print '</form>';
	} else {
		dol_print_error($db);
	}
}

//htmlPrintOnlineFooter($mysoc, $langs);
llxFooterVierge();

$db->close();