<?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
#-------------------------------------------------------------------------
/**
 * PEAR captcha library
 * @see class.captchalib.php
 * @see CaptchaLib
 * @package Captcha
*/
namespace Captcha;
//use \PEAR as ROOT_PEAR;

//if (!function_exists('file_put_contents')) {
//    function file_put_contents($filename, $content) {
//        if (!($file = fopen($filename, 'w'))) {
//            return false;
//        }
//        $n = fwrite($file, $content);
//        fclose($file);
//        return $n ? $n : false;
//    }
//}

/**
 * @extends CaptchaLib
*/
class pear extends \Captcha\cm_plugin_base
{

	function __construct()
	{
	  parent::__construct();
		
		$options[] = new plugin_option('font_size'          , 'int',      '30');
		$options[] = new plugin_option('width'              , 'int',      '150');
		$options[] = new plugin_option('height'             , 'int',      '70');
		$options[] = new plugin_option('font'	              , 'string',   'FreeSerif.ttf');
		$options[] = new plugin_option('text_color'	        , 'string',   '#DDFF99');
		$options[] = new plugin_option('lines_color'	      , 'string',   '#CCEEDD');
		$options[] = new plugin_option('background_color'	  , 'string',   '#555555');
    foreach($options as $opt) $this->AddOption($opt);
	}
	
	/**
	* Check availability of the PEAR Captcha library
	* Overrides the CaptchaLib->checkAvailability() method
	* @return bool
	*/
	function checkAvailability() 
  {
    $ret = (bool)@include_once('Text/CAPTCHA.php');
    $this->setIsAvailable($ret);
		return $ret;
	}
	
	function createCaptchaImage($options)
	{
		$imageOptions = array(
			'font_size' => $options['font_size'],
			'font_path' => $this->getFontPath() . DIRECTORY_SEPARATOR,
			'font_file' => $options['font'],
			'text_color' => $options['text_color'],
			'lines_color' => $options['lines_color'],
			'background_color' => $options['background_color']
		);

		$options = array(
			'width' => (int) $options['width'],
			'height' => (int) $options['height'],
			'output' => 'jpeg',
			'imageOptions' => $imageOptions
		);

    require_once 'PEAR.php'; // not sure why the lack of this didn't puke before ... (JM)
    
		$retval = $this->object->init($options);
		if (\PEAR::isError($retval)) {
			printf('Error initializing CAPTCHA: %s!', $retval->getMessage());
			exit;
    }

		$_SESSION['captcha_phrase'] = $this->object->getPhrase();

    $image_data = $this->object->getCAPTCHA();
    if (\PEAR::isError($image_data)) {
        printf('Error generating CAPTCHA: %s!',
            $image_data->getMessage());
        exit;
    }

		file_put_contents(cms_join_path($this->getImagePath(), md5(session_id()) . '.jpg'), $image_data);

	}
	
	/**
	* Sets the session variable and returns the HTML to show the captcha
	*/
	function getCaptcha($options = array()) 
	{
		#session_start();
    if (!session_id()) session_start();
    
		$this->load();
	
		$this->createCaptchaImage($options);
	
		return ('<img src="' . $this->getImageUrl() . '/'. md5(session_id()) . '.jpg?' . time() . '" width="' . $options['width'] . '" height="' . $options['height'] . '" />');
	}
	
	function checkCaptcha($input, $options = array())
	{
		unlink(cms_join_path($this->getImagePath(), md5(session_id()) . '.jpg'));
		return (
			isset($_SESSION['captcha_phrase']) &&
			is_string($_SESSION['captcha_phrase']) &&
			strlen($input) > 0 &&
			strlen($_SESSION['captcha_phrase']) > 0 &&
			$input == $_SESSION['captcha_phrase']
		) ? TRUE : FALSE;
	}
	
	function load()
	{
		if (! $this->checkAvailability())
		{
			return;
		}
		// Call the parent class load method (includes necessary files)
		parent::load(); 
	
		if(!isset($this->object))
		{
			$this->object = \Text_CAPTCHA::factory('Image');
		}
	}
  
  function NeedsInputField()
  {
    return TRUE;
  }   
}
?>