<?php
/**
 * Include library for guestbook. 
 * 
 * This application is designed for website generated by RVSiteBuilder.
 * Unauthorized copy of the script is prohibited.
 * 
 * @version 1.00
 * @author pairote@rvglobalsoft.com
 * @copyright Copyright &copy; http://www.rvglobalsoft.com/index.php/rvsitebuilder/sitebuilderbilling/action/terms
 * @package rvsitebuilder
 */

if (@is_file('../testmode')) { 
    // Start PHP session for Captcha
    @session_start();
    $settingIniPath = '';
    $aConfig = parse_ini_file($settingIniPath  . 'setting.ini.php');    
}

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;
    }
}  
/**
 * Define config
 */
    define('RVSLIB_PATH', $aConfig['rvslibPath']);
    define('SCRIPT_PATH', $aConfig['scriptPath']);    
    define('SCRIPT_URL', $aConfig['scriptUrl']);        
    define('NOTIFY', $aConfig['notify']);       
    define('ADMIN_EMAIL', $aConfig['admin_email']);
    define('APPROVAL', $aConfig['approval']);
            
    
   /* if (defined('SGL_LIB_PEAR_DIR') && defined('RVS_AUTO_SETUP')) {
    	define('RVSLIB_PEAR_PATH', SGL_LIB_PEAR_DIR . '/');
    } else {
    	if (ini_set('include_path', RVSLIB_PATH . 'Pear')) {
    		define('RVSLIB_PEAR_PATH', '');
    	} else {
    		define('RVSLIB_PEAR_PATH', RVSLIB_PATH . 'Pear/');
    	}
    }*/
    
    $ok = @ini_set('include_path', RVSLIB_PATH . 'Pear');
    if ($ok) {
    	define('RVSLIB_PEAR_PATH', '');
    } else {
    	define('RVSLIB_PEAR_PATH', RVSLIB_PATH . 'Pear/');
    }
    
/**
 * Load Language files and set locale
 */
    $aLang = loadLangFileAndLocale($aConfig);

/**
 * Below is the Sub Functions
 */ 
function genCaptcha()
{
	 if (( isset($_ENV['CPANEL']) && ($_ENV['CPANEL']=='active') ) && (preg_match('/RvSitebuilderPreview/', __FILE__))) {
	 	return false;
	 }	

	 ///fixed require_once cannot ini_set('include_path') : apiruk
	 if (defined('RVSLIB_PEAR_PATH')) {
	 	require_once RVSLIB_PEAR_PATH . 'Text/CAPTCHA.php';
	 } else {
	 	require_once 'Text/CAPTCHA.php';
	 }
	 ///END:apiruk

        // Set CAPTCHA options (font must exist!)
        $options = array(
            'font_size' => 24,
            'font_path' => RVSLIB_PATH . 'Pear/Text/CAPTCHA/',
            'font_file' => 'Loma.ttf'
        );
           
        // Generate a new Text_CAPTCHA object, Image driver
        $c = Text_CAPTCHA::factory('Image');
        $retval = $c->init(200, 65, null, $options);
        if (PEAR::isError($retval)) {
            echo '<font color="red">Error generating CAPTCHA!</font>';
            return false;      
        }
    
        // Set verifiingCaptcha to the old captcha    
        if(isset($_SESSION['captcha'])) { 
            $_SESSION['verifingCaptcha'] = $_SESSION['captcha'];
        }
         // Get CAPTCHA secret passphrase    
        $_SESSION['captcha'] = $c->getPhrase();        
        
        // Get CAPTCHA image (as PNG)
        $png = $c->getCAPTCHAAsPNG();
        if (PEAR::isError($png)) {
            echo 'Error generating CAPTCHA!';
            exit;
        }
        
        if(is_file(SCRIPT_PATH . 'data/' . md5(session_id()) . '.png')) {
            unlink(SCRIPT_PATH . 'data/' . md5(session_id()) . '.png');
        }
        
        file_put_contents(SCRIPT_PATH . 'data/' . md5(session_id()) . '.png', $png);
        $imgTag ='<img src="' . SCRIPT_URL . 'data/' . md5(session_id()) . '.png?' . time() . '" />';
        return $imgTag;
}

function isDataFolderWriteable()
{
    if (!is_writable(SCRIPT_PATH . 'data')) {
        echo 'Warning: Data file is not writeable. You can only view the guestbook.';
    }
}

function loadLangFileAndLocale($aConfig)
{   
    $aLang = array();
    if (is_file(SCRIPT_PATH . 'language/' . $aConfig['language'])) {
        require_once(SCRIPT_PATH . 'language/' . $aConfig['language']);
    }
    else {
        require_once(SCRIPT_PATH . 'language/english-iso-8859-15.php');
    }
    
    if (isset($aConfig['locale'])) {
    	$locale = explode(',',$aConfig['locale']);
    	if (!setlocale(LC_TIME,$locale)) {
    	     setlocale(LC_TIME,'en_US');
    	}
    }
    else {
        setlocale(LC_TIME,'en_US');    	
    }
    return $aLang;
}

/**
 * General function to send email
 * 
 * Beware tanted data, cc and bcc header in the message
 * 1 = Send notify email to the admin 
 * 2 = Send approval notice to the admin
 * @TODO 3 = Send approved email to the submitter
 */
function sendEmail($mailId, $name, $senderEmail)
{   
     if (ADMIN_EMAIL) {
        global $aLang, $aConfig;
       # filter tainted data $name, $senderEmail
       # - remove cc and bcc
       # - htmlspecialchars for $name, $email






        $headers  = 'MIME-Version: 1.0' . "\r\n";
        if($aConfig['language']) {
            $charset = str_replace('.php', '', $aConfig['language']);
            $expCharset = explode('-', $charset, 2);
            $charset = $expCharset[1];
        }
        else {
            $charset = 'iso-8859-1';
        }            
        $headers .= 'Content-type: text/html; charset=' . $charset . "\r\n";
               
        if ($mailId == 1) {
            $to      = ADMIN_EMAIL;
            $subject = $aLang['Email subject notfiy'];
            
            $message = $aLang['Email message notfiy1'];
            $message .= ' ' . strftime($aConfig['date_format']);
            $message .= '<p><a href="http://' . $_SERVER['HTTP_HOST'] . '/' . $_SERVER['REQUEST_URI'] . '">';
            $message .= $aLang['Email message notfiy2'];
            $message .= '</a> ';
            $message .= $aLang['Email message notfiy3'];
            $message .= '</p>';           
            
            if ($name != '') {   
                $headers .= 'From: ' . $name . '<' . $senderEmail . '>' . "\r\n";
            }
            else {
            	$headers .= 'From: ' . $senderEmail . "\r\n";
            }
            $headers .= 'Reply-To: ' . $senderEmail . "\r\n";
            $headers .='X-Mailer: PHP/' . phpversion();
            $sendmailOption = '-f' . ADMIN_EMAIL;            
        }
        else if ($mailId == 2) {
            $to      = ADMIN_EMAIL;
            $subject = $aLang['Email subject approval'];
            
            $message = $aLang['Email message approval1'];
            $message .= ' ' . strftime($aConfig['date_format']);
            $message .= '<p>' .  $aLang['Email message approval2'] . ' <a href="http://' . $_SERVER['HTTP_HOST'] . '/' . $_SERVER['REQUEST_URI'] . '">';
            $message .= $aLang['Email message approval3'];
            $message .= '</a> ';
            $message .= $aLang['Email message approval4'];
            $message .= '</p>';           
            
            if ($name != '') {   
                $headers .= 'From: ' . $name . '<' . $senderEmail . '>' . "\r\n";
            }
            else {
                $headers .= 'From: ' . $senderEmail . "\r\n";
            }
            $headers .= 'Reply-To: ' . $senderEmail . "\r\n";
            $headers .='X-Mailer: PHP/' . phpversion();
            $sendmailOption = '-f' . ADMIN_EMAIL;            
        }
        
        $message = wordwrap($message, 72);        
        mail($to, $subject, $message, $headers, $sendmailOption);        
    }

    return true;
}

/**
* Check multi-line inputs:
* Returns false if text contains newline followed by
* email-header specific string
*/ 
function has_no_emailheaders($text)
{
   return preg_match("/(%0A|%0D|\\n+|\\r+)(content-type:|to:|cc:|bcc:)/i", $text) == 0;	
}

?>

<?php if (@is_file('../testmode')) { ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo $aConfig['language']; ?>" />
<title>Untitled Document</title>
<link href="<?php echo $aConfig['theme']; ?>/g.css" rel="stylesheet" type="text/css" />
</head>

<body>
<?php } ?>