<?php
#-------------------------------------------------------------------------
# Module: Captcha - Enables CAPTCHA support for use in other modules.
#-------------------------------------------------------------------------
# Version 1.0
# maintained by Fernando Morgado AKA Jo Morg since 2017
#-------------------------------------------------------------------------
# Original Author: Dick Ittmann
#-------------------------------------------------------------------------
#
# Captcha is a CMS Made Simple module that enables the web developer to create
# multiple lists throughout a site. It can be duplicated and given friendly
# names for easier client maintenance.
#
#-------------------------------------------------------------------------
# BEGIN_LICENSE
#-------------------------------------------------------------------------
#
# This file is part of Captcha
# Captcha 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 2 of the License, or
# (at your option) any later version.
#
# Captcha 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Or read it online: http://www.gnu.org/licenses/licenses.html#GPL
#
#-------------------------------------------------------------------------
# END_LICENSE
#-------------------------------------------------------------------------
/**
 * hn_captcha
 * @see class.captchalib.php
 * @see CaptchaLib
 * @package Captcha
*/
namespace Captcha;

/**
 * @extends \Captcha\cm_plugin_base
*/
class hn_captcha extends \Captcha\cm_plugin_base
{

	function __construct()
	{
		parent::__construct();
		
    $this->setFriendlyName('HN Captcha');
		$this->setIncludeFiles( array('hn_captcha.class.x1.php') );
		
		$options[] = new plugin_option('chars'                  , 'int'   , '5');
		$options[] = new plugin_option('minsize'                , 'int'   , '20');
		$options[] = new plugin_option('maxsize'                , 'int'   , '30');
		$options[] = new plugin_option('maxrotation'            , 'int'   , '25');
		$options[] = new plugin_option('noise'                  , 'bool'  , '1');
		$options[] = new plugin_option('websafecolors'          , 'bool'  , '0');
		$options[] = new plugin_option('secretstring'           , 'string', 'A very, very secret string which is used to generate a md5-key!');
		$options[] = new plugin_option('secretposition'         , 'int'   , '15');
		$options[] = new plugin_option('collect_garbage_after'  , 'int'   , '10');
		$options[] = new plugin_option('maxlifetime'            , 'int'   , '30');
    foreach($options as $opt) $this->AddOption($opt);
	}
	
	function getCaptcha($options = array())
	{
		
		$this->load($options);
		$parsed = parse_url($this->cmsconfig['root_url']);
		$path = '';
		if( isset($parsed['path']) )
		  $path = $parsed['path'];

		// hn_captcha uses $_SERVER['DOCUMENT_ROOT'] - make sure it's the same as $config['root_path'] - $path (the path part of $config['root_url'])
		if ($_SERVER['DOCUMENT_ROOT'] . $path != str_replace("\\", "/", $this->cmsconfig['root_path']))
		{
			$oldvalue = $_SERVER['DOCUMENT_ROOT'];
			$_SERVER['DOCUMENT_ROOT'] = str_replace($path, '', str_replace("\\", "/", $this->cmsconfig['root_path']));
		}
		$result = $this->object->display_form_part('image');
		
		// reset $_SERVER['DOCUMENT_ROOT'] to the original value
		if (isset($oldvalue))
		{
			$_SERVER['DOCUMENT_ROOT'] = $oldvalue;
		}
		
		return $result;
	}
	
	function checkCaptcha($input, $options = array()) 
	{
		$this->load($options, $input);
		
		return $this->object->validate_submit() == 1;
	}
	
	function load($options = array(), $input = '')
	{
		// Call the parent class load method (includes necessary files)
		parent::load();
		
		// ConfigArray
		$CAPTCHA_INIT = array(
			// hn_captcha expects forward slashes, not backslashes in 'tempfolder'
			'tempfolder'     => str_replace("\\", "/", $this->getImagePath()) . '/',  // string: absolute path (with trailing slash!) to a writeable tempfolder which is also accessible via HTTP!
			'TTF_folder'     => $this->getFontPath() . '/', // string: absolute path (with trailing slash!) to folder which contains your TrueType-Fontfiles.
								// mixed (array or string): basename(s) of TrueType-Fontfiles
			'TTF_RANGE'      => array('FreeSans.ttf', 'FreeSerif.ttf'),
	
			'chars'          => (int) $options['chars'],       // integer: number of chars to use for ID
			'minsize'        => (int) $options['minsize'],      // integer: minimal size of chars
			'maxsize'        => (int) $options['maxsize'],      // integer: maximal size of chars
			'maxrotation'    => (int) $options['maxrotation'],      // integer: define the maximal angle for char-rotation, good results are between 0 and 30
	
			'noise'          => $options['noise'] == '1' ? true : false,    // boolean: TRUE = noisy chars | FALSE = grid
			'websafecolors'  => $options['websafecolors'] == '1' ? true : false,   // boolean
			'refreshlink'    => TRUE,    // boolean
			'lang'           => 'en',    // string:  ['en'|'de']
			'maxtry'         => 3,       // integer: [1-9]
	
			'badguys_url'    => '/',     // string: URL
			'secretstring'   => $options['secretstring'],
			'secretposition' => (int) $options['secretposition'],      // integer: [1-32]
	
			'debug'          => FALSE,

			'counter_filename'		=> '',              // string: absolute filename for textfile which stores current counter-value. Needs read- & write-access!
			'prefix'				=> 'hn_captcha_',   // string: prefix for the captcha-images, is needed to identify the files in shared tempfolders
			'collect_garbage_after'	=> (int) $options['collect_garbage_after'],             // integer: the garbage-collector run once after this number of script-calls
			'maxlifetime'			=> (int) $options['maxlifetime']              // integer: only imagefiles which are older than this amount of seconds will be deleted
		);
		
		if(! isset($this->object))
		{
			$_POST['hncaptcha_private_key'] = $input;

			$this->object = new \hn_captcha_X1($CAPTCHA_INIT);
		}
	}
  
  function NeedsInputField()
  {
    return TRUE;
  }     
}
?>
