<?php
// +---------------------------------------------------------------------------+
// | CAPTCHA v2 Plugin                                                         |
// +---------------------------------------------------------------------------+
// | functions.inc                                                             |
// |                                                                           |
// +---------------------------------------------------------------------------+
// | Copyright (C) 2006 by the following authors:                              |
// |                                                                           |
// | Author: Mark R. Evans - mevans@ecsnet.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 2            |
// | 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, write to the Free Software Foundation,   |
// | Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.           |
// |                                                                           |
// +---------------------------------------------------------------------------+
//

// this file can't be used on its own
if (strpos ($_SERVER['PHP_SELF'], 'functions.inc') !== false)
{
    die ('This file can not be used on its own.');
}

$langfile = $_CONF['path'] . 'plugins/captcha/language/' . $_CONF['language'] . '.php';

if (file_exists ($langfile)) {
    include_once ($langfile);
} else {
    include_once ($_CONF['path'] . 'plugins/captcha/language/english.php');
}
/*
* Include captcha config file
*/
require_once($_CONF['path'] . 'plugins/captcha/config.php');

if (!isset ($_SESSION)) {
    session_start();
    header("Cache-control: private");
}

function plugin_commentPreSave_captcha($uid, $title, $comment, $sid, $pid, $type, $postmode) {
    global $_CP_CONF, $_USER, $_POST;

    if ( $_CP_CONF['enable_comment'] != 1 ) {
        return 0;
    }

    if ( ($_CP_CONF['anonymous_only'] && empty($_USER['username'])) || $_CP_CONF['anonymous_only'] == 0 ) {
        $str = $_POST['captcha'];
        list( $rc, $msg )  = CAPTCHA_checkInput( 'comment',$str );
        if ( $rc == 1 )
            return 0;
        else
            return 1;
    }
    return 0;
}

function plugin_itemPreSave_captcha( $type='registration', $content='' ) {
    global $_CP_CONF, $_USER, $_POST;

    $msg = '';

    switch( $type ) {
        case 'comment' :
            if ( $_CP_CONF['enable_comment'] != 1 ) {
                return '';
            }
            break;
        case 'story' :
            if ( $_CP_CONF['enable_story'] != 1 ) {
                return '';
            }
            break;
        case 'registration' :
            if ( $_CP_CONF['enable_registration'] != 1 ) {
                return '';
            }
            break;
        case 'contact' :
            if ( $_CP_CONF['enable_contact'] != 1 ) {
                return '';
            }
            break;
        case 'emailstory' :
            if ( $_CP_CONF['enable_emailstory'] != 1 ) {
                return '';
            }
            break;
        case 'forum' :
            if ( $_CP_CONF['enable_forum'] != 1 ) {
                return '';
            }
            break;
        default :
            return '';
    }
    if ( ($_CP_CONF['anonymous_only'] && empty($_USER['username'])) || $_CP_CONF['anonymous_only'] == 0 ) {
        $str = COM_applyFilter($_POST['captcha']);
        list( $rc, $msg )  = CAPTCHA_checkInput( $type, $str );
        return $msg;
    }
    return '';
}

function plugin_templatesetvars_captcha($name, &$template) {
    global $_CP_CONF, $_USER;

    switch( $name ) {
        case 'comment' :
            if ( $_CP_CONF['enable_comment'] != 1 ) {
                $template->set_var('captcha', '');
                return;
            }
            break;
        case 'story' :
            if ( $_CP_CONF['enable_story'] != 1 ) {
                $template->set_var('captcha', '');
                return;
            }
            break;
        case 'registration' :
            if ( $_CP_CONF['enable_registration'] != 1 ) {
                $template->set_var('captcha', '');
                return;
            }
            break;
        case 'contact' :
            if ( $_CP_CONF['enable_contact'] != 1 ) {
                $template->set_var('captcha', '');
                return;
            }
            break;
        case 'emailstory' :
            if ( $_CP_CONF['enable_emailstory'] != 1 ) {
                $template->set_var('captcha', '');
                return;
            }
            break;
        case 'forum' :
            if ( $_CP_CONF['enable_forum'] != 1 ) {
                $template->set_var('captcha', '');
                return;
            }
            break;
        default :
            $template->set_var('captcha', '');
            return;
            break;
    }

    if ( ($_CP_CONF['anonymous_only'] && empty($_USER['username'])) || $_CP_CONF['anonymous_only'] == 0 ) {
        $captcha = CAPTCHA_getHTML($name);
        $template->set_var('captcha', $captcha);
    } else {
        $template->set_var('captcha', '');
    }
}

// Internal CAPTCHA functions...

function CAPTCHA_getHTML( $type='general' ) {
    global $_CONF, $_CP_CONF, $LANG_CP00;

    $retval = '';

    $T = new Template($_CONF['path'] . 'plugins/captcha/templates');
    switch ( $type ) {
        case 'comment' :
            $T->set_file('page', 'captcha_comment.thtml');
            break;
        case 'story' :
            $T->set_file('page', 'captcha_story.thtml');
            break;
        case 'registration' :
            $T->set_file('page', 'captcha_registration.thtml');
            break;
        case 'contact' :
            $T->set_file('page', 'captcha_contact.thtml');
            break;
        case 'emailstory' :
            $T->set_file('page', 'captcha_emailstory.thtml');
            break;
        case 'forum' :
            $T->set_file('page', 'captcha_forum.thtml');
            break;
        default :
            return '';
            break;
    }

    $T->set_var(array(
        'lang_captcha_help'     => $LANG_CP00['captcha_help'],
        'lang_refresh'          => $LANG_CP00['refresh'],
        'lang_alt'              => $LANG_CP00['captcha_alt'],
        'captcha_image'         => $_CONF['site_url'] . '/captcha/captcha.php?.' . $_CP_CONF['gfxFormat'],
    ));

    $T->parse('output', 'page');
    $retval .= $T->finish($T->get_var('output'));

    return $retval;
}

function CAPTCHA_checkInput( $type, $str ) {
    global $_CONF, $_CP_CONF, $LANG_CP00, $_SERVER;

   $msg = '';
   $rc = 0;

   if ( $_SESSION['CAPTCHAString'] == '' ) {
       CAPTCHA_errorLog("CAPTCHA: Detected an attempt to bypass CAPTCHA in " . $type . " - IP Address: " . $_SERVER['REMOTE_ADDR'] );
       $msg = $LANG_CP00['bypass_error'];
       $rc = 0;
   } elseif ( $_SESSION['CAPTCHAString'] != $str ) {
       $msg = $LANG_CP00['entry_error'];
       CAPTCHA_errorLog("CAPTCHA: An invalid CAPTCHA string was entered in " . $type . " - IP Address: " . $_SERVER['REMOTE_ADDR'] );
       $rc = 0;
   } elseif ( $_SESSION['CAPTCHAString'] == $str ) {
       $rc = 1;
   }

   $_SESSION['captcha_result'] = $rc;

   return ( array( $rc, $msg ) );
}

function CAPTCHA_errorLog( $logentry ) {
    global $_CONF;

    if( !empty( $logentry )) {
        $timestamp = strftime( '%c' );
        $logfile = $_CONF['path_log'] . 'captcha.log';

        if( $file = fopen( $logfile, 'a' )) {
            fputs( $file, "$timestamp - $logentry \n" );
            fclose($file);
        }
    }
}

function plugin_chkVersion_captcha() {
    global $_CP_CONF;

    return $_CP_CONF['version'];
}

/**
* This will put an option for the plugin in the command and control block on moderation.php
*
* Add the plugin name, icon and link to the command and control block in moderation.php
*
* @return   array   Array containing (plugin name, admin url, url of plugin icon)
*
*/

function plugin_cclabel_captcha() {
    global $_CONF, $LANG_CP00;

    if (SEC_inGroup('Root') ) {
        return array($LANG_CP00['plugin'],
            $_CONF['site_admin_url'] . '/plugins/captcha/index.php',
            $_CONF['site_url'] . '/captcha/captcha.png');
    } else {
        return '';
    }
}

/**
* Returns the administrative option for this plugin
*
* Adds the plugin to the Admin menu
*
* Universal Plugin:  Modify/Uncomment use it
*
* @return   array   Array containing (plugin name, plugin admin url, # of items in plugin or '')
*
*/
function plugin_getadminoption_captcha() {
    global $_CONF, $_TABLES, $LANG_CP00;

    if (SEC_inGroup('Root')) {
        return array($LANG_CP00['plugin'], $_CONF['site_admin_url'] . '/plugins/captcha/index.php','');
    }
}

/**
* Removes the data structures for this plugin from the Geeklog database.
* This routine will get called from the Plugin install program if user select De-Install or if Delete is used in the Plugin Editor.
* The Plugin Installer will also call this routine upon and install error to remove anything it has created.
* The Plugin installer will pass the optional parameter which will then double check that plugin has first been disabled.
*
* For this plugin, this routine will also remove the Block definition.
*
* Returns True if all Plugin related data is removed without error
*
* @param    string   $installCheck     Defult is blank but if set, check if plugin is disabled first
*
* @return   boolean True if successful false otherwise
*
*/
function plugin_uninstall_captcha($installCheck='') {
    global $_DB_table_prefix, $_TABLES, $LANG_CP00;

    $pi_name    = 'captcha';

    // Check and see if plugin is still enabled - if so display warning and exit
    if ($installCheck != '' && DB_getItem($_TABLES['plugins'],'pi_enabled', 'pi_name = "' .$pi_name. '"')) {
        COM_errorLog("Plugin is installed and enabled. Disable first if you want to de-install it",1);
        $display .= COM_startBlock($LANG_CP00['warning']);
        $display .= $LANG_CP00['enabled'];
        $display .= COM_endBlock();
        echo $display;
        return false;
        exit;
    }

    // Ok to proceed and delete plugin

    // Unregister the plugin with Geeklog
    COM_errorLog('Attempting to unregister the CAPTCHA Plugin from Geeklog',1);
    DB_query("DELETE FROM {$_TABLES['plugins']} WHERE pi_name = 'captcha'",1);

    COM_errorLog('...success',1);
    return true;
}
?>