<?php
/* Copyright (C) 2006-2011  Laurent Destailleur     <eldy@users.sourceforge.net>
 * Copyright (C) 2024		Frédéric France			<frederic.france@free.fr>
 * Copyright (C) 2024		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/>.
 * or see https://www.gnu.org/
 */

/**
 *      \file       htdocs/core/modules/security/captcha/modCaptchaStandard.class.php
 *      \ingroup    core
 *		\brief      File to manage captcha generation according to dolibarr native code
 */

require_once DOL_DOCUMENT_ROOT.'/core/modules/security/captcha/modules_captcha.php';
require_once DOL_DOCUMENT_ROOT.'/core/modules/security/generate/modGeneratePassStandard.class.php';


/**
 *	Class to generate a password according to a dolibarr standard rule (12 random chars)
 */
class modCaptchaStandard extends ModeleCaptcha
{
	/**
	 * @var string ID
	 */
	public $id;

	/**
	 * @var string
	 */
	public $picto = 'fa-shield-alt';

	/**
	 *	Constructor
	 *
	 *  @param		DoliDB		$db			Database handler
	 *	@param		Conf		$conf		Handler de conf
	 *	@param		Translate	$langs		Handler de langue
	 *	@param		User		$user		Handler du user connected
	 */
	public function __construct($db, $conf, $langs, $user)
	{
		$this->id = strtolower(preg_replace('/^modCaptcha/i', '', get_class($this)));

		$this->db = $db;
		$this->conf = $conf;
		$this->langs = $langs;
		$this->user = $user;
	}

	/**
	 *		Return description of module
	 *
	 *      @return     string      Description of module
	 */
	public function getDescription()
	{
		global $langs;
		return $langs->trans("DolibarrStandardCaptcha");
	}

	/**
	 * 		Return an example of password generated by this module
	 *
	 *      @return     string      Example of password
	 */
	public function getExample()
	{
		global $db, $conf, $langs, $user;

		$generator = new modGeneratePassStandard($db, $conf, $langs, $user);
		$example = $generator->getExample();

		if (function_exists("imagecreate") && function_exists("imagepng")) {
			$img = imagecreate(80, 32);
			if (!$img) {
				return "Problem with GD creation";
			}
			//$background_color = imagecolorallocate($img, 250, 250, 250);
			$ecriture_color = imagecolorallocate($img, 0, 0, 0);
			imagestring($img, 4, 15, 8, $example, $ecriture_color);

			ob_start();
			imagepng($img);
			$image_data = ob_get_contents();
			ob_end_clean();

			return '<img class="inline-block valignmiddle" src="data:image/png;base64,' . base64_encode($image_data) . '" border="0" width="80" height="32" />';
		} else {
			// Image grise
			$image_data_base64 = 'iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAIAAAACUFjqAAAAFElEQVR4nGNsaGhgwA2Y8MiNYGkA22EBlPG3fjQAAAAASUVORK5CYII=';
			return '<img class="inline-block valignmiddle" src="data:image/png;base64,' . $image_data_base64 . '" border="0" width="80" height="32" />';
		}
	}

	/**
	 * 	Return the HTML content to output on a form that need the captcha
	 *
	 *  @param		string	$php_self	An URL for the a href link
	 *  @return     string				The HTML code to output
	 */
	public function getCaptchaCodeForForm($php_self = '')
	{
		global $langs;

		// Output the image by calling /core/antispamimage.php
		// This antispamimage also record the value of code into $_SESSION['dol_antispam_value'] so we will be able to validate by calling
		// validateCodeAfterLoginSubmit() later when we submit the login form.

		$out = '<!-- Captcha -->
		<div class="trinputlogin">
		<div class="tagtd tdinputlogin nowrap none valignmiddle">

		<span class="fa fa-unlock"></span>
		<span class="nofa span-icon-security inline-block">
		<input id="securitycode" placeholder="'.$langs->trans("SecurityCode").'" class="flat input-icon-security width125" type="text" maxlength="5" name="code" tabindex="3" autocomplete="off" />
		</span>
		<span class="nowrap inline-block">
		<img class="inline-block valignmiddle" src="'.DOL_URL_ROOT.'/core/antispamimage.php" border="0" width="80" height="32" id="img_securitycode" />
		<a class="inline-block valignmiddle" href="'.$php_self.'" tabindex="4" data-role="button" onclick="submitFormFromCaptcha(event)">'.img_picto($langs->trans("Refresh"), 'refresh', 'id="captcha_refresh_img"').'</a>
		</span>

		</div>
		</div>

		<script>
		function submitFormFromCaptcha(event) {
			console.log("submitFormFromCaptcha");

			// Prevent the default action of the link
			event.preventDefault();
			// Search the form
			const form = event.target.closest("form");

			// Submit the form if found
			if (form) {
				console.log("we set actionlogin to value \"disabled\"");
				document.getElementById("actionlogin").value = "disabled";

				form.submit();
			}
		}
		</script>
		<!-- End code for Captcha -->'."\n";

		return $out;
	}



	/**
	 * 	Validate a captcha
	 * 	This function is called after a log to validate a captcha, before validating a password.
	 *
	 *  @return     int					0 if KO, >0 if OK
	 */
	public function validateCodeAfterLoginSubmit()
	{
		$sessionkey = 'dol_antispam_value';		// The same key than set into the /core/antispamimage.php file.

		$ok = (array_key_exists($sessionkey, $_SESSION) && (strtolower($_SESSION[$sessionkey]) === strtolower(GETPOST('code', 'restricthtml')))) ? 1 : 0;

		return $ok;
	}
}
