<?php
/**
 * Sign form page for guestbook. 
 * 
 * This application is designed for website generated by RVSiteBuilder.
 * Unauthorized copy of the script is prohibited.
 * 
 * @version 1.00
 * @autshor pairote@rvglobalsoft.com
 * @copyright Copyright &copy; http://www.rvglobalsoft.com/index.php/rvsitebuilder/sitebuilderbilling/action/terms
 * @package rvsitebuilder
 */
require_once('include.php'); 
isDataFolderWriteable();
if(isset($aConfig['surbl_query_spam_protection']) && $aConfig['surbl_query_spam_protection']) {
    
	///fixed require_once cannot ini_set('include_path') : apiruk
	if (defined('RVSLIB_PEAR_PATH')) {
		require_once(RVSLIB_PEAR_PATH . 'Net/DNS.php');
		require_once(RVSLIB_PEAR_PATH . 'Net/URL.php');
	} else {
		require_once('Net/DNS.php');
		require_once('Net/URL.php');
	}
	///END:apiruk
	    
}

///fixed require_once cannot ini_set('include_path') : apiruk
if (defined('RVSLIB_PEAR_PATH')) {
	require_once(RVSLIB_PEAR_PATH . 'HTML/QuickForm.php');
	require_once (RVSLIB_PEAR_PATH . 'HTML/QuickForm/Renderer/QuickHtml.php');
} else {
	require_once('HTML/QuickForm.php');
	require_once ('HTML/QuickForm/Renderer/QuickHtml.php');
}
///END:apiruk

// Instantiate the HTML_QuickForm object
$form = new HTML_QuickForm('guestForm');
///RVS fix $_SERVER['PHP_SELF'] != $_SERVER['SCRIPT_NAME']
$form->_attributes['action'] = ($form->_attributes['action'] == $_SERVER['SCRIPT_NAME'])
                                ? $form->_attributes['action']
                                : $_SERVER['SCRIPT_NAME'];
$guestbookfile = basename($form->_attributes['action']);
$encodefilename = urlencode($guestbookfile);
$form->_attributes['action'] = str_replace($guestbookfile, $encodefilename, $form->_attributes['action']);

// get our render
$renderer =& new HTML_QuickForm_Renderer_QuickHtml();

// create the elements
require_once('shareform.php');
createElements($form, $aConfig, $aLang);
_createElements($form, $aConfig, $aLang);

// set their values
_setValues($form, $aConfig, $aLang);

// Do the magic of creating the form.  NOTE: order is important here: this must
// be called after creating the form elements, but before rendering them.
//$form->accept($renderer);

// Try to validate a form
$aError = array(); 
if(isset($_POST['post'])) {
	$valid = true;
    // QuickForm validation
    $valid= ($form->validate() && $valid ===true)? true:false;
    
    if ($aConfig['captcha']) {
        // Validate Captcha if required
        $valid= (_validateCaptcha($aError, $aLang) && $valid ===true)? true:false;
    }
    
    if ($aConfig['surbl_query_spam_protection']) {        
        preg_match_all("/(http[s]?:\/\/?[^\s]+)/i",$form->exportValue('field_msg'),$aWebsite);
        $valid= (_validateSurbl($aWebsite[0], $aError, 'field_msg') && $valid ===true)? true:false;
        
        if ($aConfig['field_website'] && $form->exportValue('field_website')) {
            // if submitted website doesn't begin with http or https add to the url'
            if (!eregi("^(http:|https:)", $form->exportValue('field_website'))) {
                $aWebsite = array('http://' . $form->exportValue('field_website'));        
            }
            else {
                $aWebsite = array($form->exportValue('field_website'));              	
            }
                        
            $valid= (_validateSurbl($aWebsite, $aError, 'field_website') && $valid ===true)? true:false;
        }
    }
}


// Output the form


if(!isset($valid) || !$valid) {
    // Make our form table using some of the widget functions.
    
    // spam bot
    if ($aConfig['spambot_allow']) {
        $rvblocker=new formSpamBotBlocker();
        $minSubmit = ($aConfig['spambot_min_time']) ? $aConfig['spambot_min_time'] : 2;
        $maxSubmit = ($aConfig['spambot_max_time']) ? $aConfig['spambot_max_time'] : 14400;
        $rvblocker->setTimeWindow($minSubmit,$maxSubmit);
        $rvblocker->setTrap(true, $aConfig['spambot_key_value'] ,"Do not enter anything in this field!");
        $rvblocker->getArrayTag();
    
        foreach ($rvblocker->aFsbbOpts as $codeKey => $codeValue) {
            $form->addElement('hidden', $codeKey, $codeValue);
        }
    }
        $form->accept($renderer);
    
        $registeredOption = $form->toArray();
        $data = _pageHead($aConfig, $aLang,$aError);
        //add hiddenTag fsbb for validate spam bot
        //$data .= $hiddenTags;
        $data .= rendererFormTable($renderer, $registeredOption, $aConfig, $aLang,$aError);
    
        // Wrap the form and any remaining elements (i.e. hidden elements) into the form tags.
        echo '<div align="center">';
        echo $renderer->toHtml($data);
        echo '</div>';
    } else {
	   # If the form validates then freeze the data
        $form->freeze();
    
        // Remove the CAPTCHA image
        cleanCaptcha();
    if ($aConfig['spambot_allow']) {
        $rvblocker=new formSpamBotBlocker();
        $minSubmit = ($aConfig['spambot_min_time']) ? $aConfig['spambot_min_time'] : 2;
        $maxSubmit = ($aConfig['spambot_max_time']) ? $aConfig['spambot_max_time'] : 14400;
        $rvblocker->setTimeWindow($minSubmit,$maxSubmit);
        $rvblocker->setTrap(true, $aConfig['spambot_key_value'] ,"Do not enter anything in this field!");
        $isnotSpamBot = $rvblocker->isnotSpamBot(); 
        if ($isnotSpamBot  == true) {
	// Insert data into db text file
            $form->process('process_data', false);
            showMessage($aConfig, $aLang);
        } else {
            showSpamMessage($aConfig, $aLang);
        }
    } else {
        $form->process('process_data', false);
        showMessage($aConfig, $aLang);
    }
}


/**
 * ******************************************************************
 * Sub function start here
 * ******************************************************************
 */

function _createElements(&$form, &$aConfig, $aLang)
{
    $form->addElement('hidden', 'post');         
}

function _setValues(&$form, $aConfig, $aLang)
{
    $constants = array('captcha' => '',
                                 'post' => '1');
    $form->setConstants($constants);
    $form->setJsWarnings ($aLang['Pre JS warning'], $aLang['Post JS warning']);
}

 function _validateCaptcha(&$aError, $aLang)
 {
    if (isset($_POST['captcha']) && isset($_SESSION['verifingCaptcha']) &&
    strlen($_POST['captcha']) > 0 && strlen($_SESSION['verifingCaptcha']) > 0 &&
    $_POST['captcha'] == $_SESSION['verifingCaptcha']) {  
        $valid = true;
    }
    else {
        $aError['captcha'] = $aLang['captcha error'];
        $valid = false;
    }
    
    return $valid;
 }
 
 function cleanCaptcha()
 {
 	// Remove catcha image
    unset($_SESSION['captcha']);
    unset($_SESSION['verifingCaptcha']);          
    @unlink(SCRIPT_PATH . 'data/' . md5(session_id()) . '.png');
 }
 
function _validateSurbl($aWebsite,&$aError, $fieldName)
{     
    $i = 0;
    $aDomain =array();
    $surbl = 'multi.surbl.org';
    $resolver = new Net_DNS_Resolver();    
    foreach ($aWebsite as $domain) {
        if(!isset($aCctld)) {
        	$filename = SCRIPT_PATH . 'cctld.db';     
            $aCctld = file($filename);    
        }
        
        $url = new Net_URL($domain);
        $domain = cutDomain($url->host, $aCctld);
        $query = $domain . '.' . $surbl;
        $response = $resolver->query($query, 'A');
        if ($response){
            if (eregi('127.0.0.[0-9]+',$response->answer[0]->address)){
                // Domain listed in SURBL
                $aError[$fieldName] = 'Sorry, your domain ' . $domain . ' is listed in the spam database.';
                $aError[$fieldName] .= ' [ <a href="http://www.rulesemporium.com/cgi-bin/uribl.cgi?total=1&domain0=';
                $aError[$fieldName] .= $domain  . '&bl0=1&query=Check+It%21" target="_blank">' . 'more info' . '</a> ]';
                return false;
            }       
        } 
    }
        
    return true;
}

function cutDomain($domain, $aCctld){
        $i = 2;
        $domain2 = $domain;
        $count = count(split('[.]', $domain));
        while ($i < $count){
            $domain = eregi_replace('^[a-zA-Z0-9_-]+[.]','',$domain); 
            if (cctldTest($domain, $aCctld)){
                    break;
            }
            $domain2 = $domain;      
            $i++;    
        }
        
        return $domain2;
}

function cctldTest($domain, $aCctld)
{
        if ($domain==NULL){
            return false;
        }
        
        foreach($aCctld as $line){
            $line = trim($line);
            if (!(strcmp($domain,$line))){
                return true;            
            }
        }
        return false;
}
        
function getIp() 
{
    if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
        if (isset($_SERVER["HTTP_CLIENT_IP"])) {
            $proxy = $_SERVER["HTTP_CLIENT_IP"];
        } else {
            $proxy = $_SERVER["REMOTE_ADDR"];
        }
        $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    } else {
        if (isset($_SERVER["HTTP_CLIENT_IP"])) {
           $ip = $_SERVER["HTTP_CLIENT_IP"];
        } else {
            $ip = $_SERVER["REMOTE_ADDR"];
        }
    }
    
    if (isset($proxy)){ 
        $ip = $ip . '<br>&nbsp;&nbsp;&nbsp; [' .  $proxy . ']';
    }    
    return $ip;
} 

function process_data($values) 
{    
    $values['field_msg'] = nl2br($values['field_msg']);

    // Remove /t characters    
    $values = str_replace("\t", "", $values);
    $values = str_replace("\r", "", $values);    
    $values = str_replace("\n", "", $values);
        
    $values['field_name'] = (isset($values['field_name'])) ? $values['field_name'] : '';       
    $values['field_email'] = (isset($values['field_email'])) ? $values['field_email'] : '';    
    $values['field_location'] = (isset($values['field_location'])) ? $values['field_location'] : '';
    $values['field_website'] = (isset($values['field_website'])) ? $values['field_website'] : '';
    $values['field_icq'] = (isset($values['field_icq'])) ? $values['field_icq'] : '';
    $values['field_aim'] = (isset($values['field_aim'])) ? $values['field_aim'] : '';
    $values['field_yahoo'] = (isset($values['field_yahoo'])) ? $values['field_yahoo'] : '';
    $values['field_email'] = (isset($values['field_email'])) ? $values['field_email'] : '';
    $values['field_skype'] = (isset($values['field_skype'])) ? $values['field_skype'] : '';
    $values['field_msn'] = (isset($values['field_msn'])) ? $values['field_msn'] : '';
    $values['field_msg'] = (isset($values['field_msg'])) ? $values['field_msg'] : '';       
    $values['field_ip'] = (isset($values['field_ip'])) ? $values['field_ip'] : '';        
    $values['field_optional1'] = (isset($values['field_optional1'])) ? $values['field_optional1'] : '';
    $values['field_optional2'] = (isset($values['field_optional2'])) ? $values['field_optional2'] : '';
    $values['field_optional3'] = (isset($values['field_optional3'])) ? $values['field_optional3'] : '';
    $values['field_optional4'] = (isset($values['field_optional4'])) ? $values['field_optional4'] : '';
    $values['field_optional5'] = (isset($values['field_optional5'])) ? $values['field_optional5'] : '';

    $writeData = md5(microtime() . SID);
    $writeData .= "\t" . time();    
    $writeData .= "\t" . $values['field_name'];
    $writeData .= "\t" . $values['field_email'];    
    $writeData .= "\t" . $values['field_location'];    
    $writeData .= "\t" . $values['field_website'];    
    $writeData .= "\t" . $values['field_icq'];
    $writeData .= "\t" . $values['field_aim'];    
    $writeData .= "\t" . $values['field_yahoo'];        
    $writeData .= "\t" . $values['field_skype'];    
    $writeData .= "\t" . $values['field_msn'];    
    $writeData .= "\t" . $values['field_msg'];    
    $writeData .= "\t" . $values['field_ip'];
    $writeData .= "\t" . $values['field_optional1'];
    $writeData .= "\t" . $values['field_optional2'];
    $writeData .= "\t" . $values['field_optional3'];
    $writeData .= "\t" . $values['field_optional4'];
    $writeData .= "\t" . $values['field_optional5'];                    
    $writeData .= "\n" ;   
    
    if (APPROVAL) {
        $file = fopen(SCRIPT_PATH . 'data/dataAsRawForApproval.txt', 'a');             
    }
    else {
        $file = fopen(SCRIPT_PATH . 'data/dataAsRaw.txt', 'a');
    }    
    fwrite($file, $writeData);
    fclose($file);   
# md5(microtime.SID)    date    name  email   location    website icq AIM yahoo Skype   MSN comment Ip  optional1   optional2   optional3   optional4   optional5
    
    if (NOTIFY) {
    	sendEmail(1, $values['field_name'], $values['field_email']);
    }
    
    if (APPROVAL) {
        sendEmail(2, $values['field_name'], $values['field_email']);
    }
}

function _pageHead(&$aConfig, $aLang,$aError)
{
        $data = "<div align=\"center\"><table cellpadding=\"0\" cellspacing=\"0\" class=\"borderoutside\" width=\"90%\" align=\"center\">\n" . 
                "    <tr>\n" . 
                "        <td align=\"right\">" .
//                "        <img src=\"" . SCRIPT_URL . $aConfig['theme'] . "/images/admin.gif\" alt=\"\" width=\"12\" height=\"12\" /> \n" . 
//                "        <a href=\"?page=admin\" class=\"signlink\">Administration</a> | \n" .
                "        <img src=\"" . SCRIPT_URL . $aConfig['theme'] . "/images/signicn.gif\" alt=\"\" width=\"12\" height=\"12\" /> \n" . 
                "        <a href=\"?page=list\" class=\"signlink\">" . $aLang['View the Guestbook'] . "</a>\n" . 
                "        </td>\n" . 
                "    </tr>\n" . 
                "    <tr>\n" . 
                "        <td><b>" . strftime($aConfig['date_format']) . "</b><br />\n" . 
                "        </td>\n" . 
                "    </tr>\n" . 
                "    <tr>\n" . 
                "        <td height=\"10\"></td>\n" . 
                "    </tr>\n" .
                "    <tr>\n" . 
                "        <td>\n" . 
                "        <table cellpadding=\"1\" cellspacing=\"1\" width=\"100%\">\n" . 
                "            <tr>\n" . 
                "                <td class=\"txtheadb\" align=\"left\">" . $aLang['Sign the Guestbook'] . ":</td>\n" . 
                "            </tr>\n" . 
                "            <tr>\n" . 
                "                <td><p>" .  $aLang['signInfo'] . "</p>";
        if (count($aError) > 0) {
            $data .= '<p align="center"><font color="red">';
            $data .= $aLang['Please fill in all the indicated fields and try again.'];
            $data .= '</font></p>';
        }
        if (isset($_ENV['CPANEL'])&&(preg_match('/RvSitebuilderPreview/', __FILE__))) {
           	$data .= '<p align="left"><font color="red">';
            $data .= $aLang['warning captcha'];
            $data .= '</font></p>';
        }         
        $data .="                 </td>\n" . 
                "            </tr>\n" .                 
                "            <tr>\n" . 
                "                <td class=\"bgtabcolor\" height=\"4\"></td>\n" . 
                "            </tr>\n" . 
                "            <tr>\n" . 
                "                <td class=\"bglinecolor\" height=\"1\"></td>\n" . 
                "            </tr>\n" . 
                "            <tr>\n" . 
                "                <td>\n" . 
                "                <table cellpadding=\"1\" cellspacing=\"1\" width=\"100%\">";	
        return $data;                
}

function showMessage($aConfig, $aLang)
{

  echo "<table cellpadding=\"0\" cellspacing=\"0\" class=\"borderoutside\" width=\"90%\" align=\"center\">\n" . 
            "    <tr>\n" . 
            "        <td align=\"right\">" .
//            "        <img src=\"" . SCRIPT_URL . $aConfig['theme'] . "/images/admin.gif\" alt=\"\" width=\"12\" height=\"12\" /> \n" . 
//            "        <a href=\"?page=admin\" class=\"signlink\">Administration</a> | \n" .
            "        <img src=\"" . SCRIPT_URL . $aConfig['theme'] . "/images/signicn.gif\" alt=\"\" width=\"12\" height=\"12\" /> \n" . 
            "        <a href=\"?page=list\" class=\"signlink\">" . $aLang['View the Guestbook'] . "</a>\n" . 
            "        </td>\n" . 
            "    </tr>\n" . 
            "    <tr>\n" . 
            "        <td><b>" . strftime($aConfig['date_format']) . "</b><br />\n" . 
            "        </td>\n" . 
            "    </tr>\n" . 
            "    <tr>\n" . 
            "        <td height=\"10\"></td>\n" . 
            "    </tr>\n" .
            "    <tr>\n" . 
            "        <td>\n" . 

            "        <table cellpadding=\"1\" cellspacing=\"1\" width=\"100%\">\n" . 
            "            <tr>\n" . 
            "                 <td class=\"bgtabcolor\" height=\"2\"><img src=\"" . SCRIPT_URL . $aConfig['theme'] . "/images/spacer.gif\" alt=\"\" width=\"1\" height=\"2\" /></td>\n" . 
            "            </tr>\n" .             
            "            <tr>\n" . 
            "                <td class=\"txtheadb\">" . $aLang['Signed Guestbook'] . ":</td>\n" . 
            "            </tr>\n" . 
            "            <tr>\n" . 
            "                <td class=\"bgtabcolor\" height=\"4\"></td>\n" . 
            "            </tr>\n" . 
            "            <tr>\n" . 
            "                <td class=\"bglinecolor\" height=\"1\"></td>\n" . 
            "            </tr>\n" . 
            "            <tr>\n" . 
            "                <td></td>\n" . 
            "            </tr>" .
            "        </table>";     
              
        echo '<div align="center"><br /><br /><br />';      
        echo $aLang['Thank you for signing'];
        echo '<br /><a href="?page=list">' . $aLang['Sign message notify1'] . ' ' . $aLang['Sign message notify2'] . '</a>';
        echo '<br /><br /><br /></div>';
    
        echo '   </td>';
        echo '  </tr>'; 
        echo '</table>';    
}

function showSpamMessage($aConfig, $aLang)
{
  echo "<table cellpadding=\"0\" cellspacing=\"0\" class=\"borderoutside\" width=\"90%\" align=\"center\">\n" . 
            "    <tr>\n" . 
            "        <td align=\"right\">" .
//            "        <img src=\"" . SCRIPT_URL . $aConfig['theme'] . "/images/admin.gif\" alt=\"\" width=\"12\" height=\"12\" /> \n" . 
//            "        <a href=\"?page=admin\" class=\"signlink\">Administration</a> | \n" .
            "        <img src=\"" . SCRIPT_URL . $aConfig['theme'] . "/images/signicn.gif\" alt=\"\" width=\"12\" height=\"12\" /> \n" . 
            "        <a href=\"?page=list\" class=\"signlink\">" . $aLang['View the Guestbook'] . "</a>\n" . 
            "        </td>\n" . 
            "    </tr>\n" . 
            "    <tr>\n" . 
            "        <td><b>" . strftime($aConfig['date_format']) . "</b><br />\n" . 
            "        </td>\n" . 
            "    </tr>\n" . 
            "    <tr>\n" . 
            "        <td height=\"10\"></td>\n" . 
            "    </tr>\n" .
            "    <tr>\n" . 
            "        <td>\n" . 

            "        <table cellpadding=\"1\" cellspacing=\"1\" width=\"100%\">\n" . 
            "            <tr>\n" . 
            "                 <td class=\"bgtabcolor\" height=\"2\"><img src=\"" . SCRIPT_URL . $aConfig['theme'] . "/images/spacer.gif\" alt=\"\" width=\"1\" height=\"2\" /></td>\n" . 
            "            </tr>\n" .             
            "            <tr>\n" . 
            "                <td class=\"txtheadb\">" . $aLang['Signed Guestbook'] . ":</td>\n" . 
            "            </tr>\n" . 
            "            <tr>\n" . 
            "                <td class=\"bgtabcolor\" height=\"4\"></td>\n" . 
            "            </tr>\n" . 
            "            <tr>\n" . 
            "                <td class=\"bglinecolor\" height=\"1\"></td>\n" . 
            "            </tr>\n" . 
            "            <tr>\n" . 
            "                <td></td>\n" . 
            "            </tr>" .
            "        </table>";     
              
        echo '<div align="center"><br /><br /><br /><font color ="red">';      
        echo $aLang['This was an INVALID submission. You have acted like a spambot!'];
        echo '</font><br /><a href="?page=list">' . $aLang['Click here to view.'] . '</a>';
        echo '<br /><br /><br /></div>';
    
        echo '   </td>';
        echo '  </tr>'; 
        echo '</table>';    
    
}

?>
