<?php
/*
*     Author: Alex Scott
*      Email: alex@cgi-central.net
*        Web: http://www.cgi-central.net
*    Details: Startup file
*    FileName rconfig.inc.php
* 
* Please direct bug reports,suggestions or feedback to the cgi-central forums.
* http://www.cgi-central.net/forum/
*                                                                          
* aMember PRO is a commercial software. Any distribution is strictly prohibited.
* Decoding and de-compilation of this file is also a copyright violation and is
* strictly prohibited.
 */
// BEGIN AMEMBER STARTUP CODE
if (!defined('INCLUDED_AMEMBER_CONFIG')) 
    die("Direct access to this location is not allowed");


error_reporting(error_reporting() ^ 8192); 


function normalizePath($path){
	if (substr(PHP_OS, 0, 3) == 'WIN'){	
    	$path = preg_replace('|^[A-Za-z]:|', '', $path);
    	$path = str_replace("\\", '/', $path);
	}
	return $path;
}
    

if ($config['root_dir'] == dirname(__FILE__))
	$config['root_dir'] = normalizePath($config['root_dir']);
	
define('ROOT_DIR', $config['root_dir']);
define('LIB_DIR',  $config['root_dir'] . '/lib');
define('INC_DIR',  $config['root_dir'] . '/includes');


    
function memUsage($op){
    if (!defined('MEM_DEBUG') || !MEM_DEBUG) return;
    static $prev;
    $t = memory_get_usage();
    $tt = $t / 1024;
    $u = $t - intval($prev);
    $u /= 1024; 
    print "\n<br><small>Memory Usage [$op] = ";
    printf("%d KB, Total %d KB</small>\n<br>", $u, $tt);
    $prev = $t;
}

function tmUsage($op, $init=false, $start_anyway=false){
    if (!$start_anyway)
        if (!defined('TM_DEBUG') || !TM_DEBUG) return;
    static $prev;
    static $first;
    list($usec, $sec) = explode(" ",microtime()); 
    $tt = ((float)$usec + (float)$sec);
    if ($init) { $first = $prev = $tt; return ; }
    print "\n<br><small>Time Used [$op] = ";
    printf("%.3f sec. Total [%.3f] sec</small>\n<br>", $tt - $prev, $tt - $first);
    $prev = $tt;
}

tmUsage(null, true, true);
memUsage(null, true);

function is_lite(){
    return '@LITE@' != ('@' . 'LITE@');
}
function is_trial(){
    return '@TRIAL@' != ('@' . 'TRIAL@');
}

function check_lite($errmsg="Sorry, this function is available in aMember Pro version only"){
    if (is_lite()){  
        fatal_error($errmsg, 1);
    }
}
function check_trial($errmsg="Sorry, this function is available in aMember Pro not-trial version only"){
    if (is_trial()){  
        fatal_error($errmsg, 1);
    }
}

function read_db_config(&$config){
    global $plugin_config;
    $this_config = $plugin_config['db']['mysql'];
    global $config;
    if ($config['use_mysql_connect']){
        if (!$link=@mysql_connect(
            $this_config['host'],
            $this_config['user'],
            $this_config['pass']
        )) amDie("Cannot connect to MySQL: " . mysql_error());
    } else {
        if (!$link=@mysql_pconnect(
            $this_config['host'],
            $this_config['user'],
            $this_config['pass']
        )) amDie("Cannot connect to MySQL: " . mysql_error());
    };
    if ($this_config['charset'])
        mysql_set_charset($this_config['charset'], $link);
    if (!@mysql_select_db($this_config['db']))
       amDie("Cannot select MySQL db");
    
    $q = @mysql_query("SELECT COUNT(*)
        FROM {$this_config['prefix']}config");
    $c = 0;
    list($c) = @mysql_fetch_row($q);
    if ($c <= 0) {
        amDie("aMember is not configured yet (database config table is not exists or empty), please remove amember/config.inc.php, and run <a href='setup.php'>amember/setup.php</a> first", 0);
    }
       
    
    $q = mysql_query("SELECT name,type,value,blob_value
        FROM {$this_config['prefix']}config");
    while (list($n,$t,$v,$bv) = mysql_fetch_row($q)){
        switch ($t){
            case 0: break;
            case 1: $v = unserialize($bv); break;
            case 2: $v = $bv; $bv = ''; break;
            case 3: $v = amember_decrypt($v); break;
            case 4: $v = eval($v); break;
            default: amDie("Unknown type in config");
        }
        $nn = preg_split('/\./', $n);
        if (count($nn) > 1){
            $p = & $config;
            foreach ($nn as $x)
                $p = & $p[$x];
            $p = $v;
        } else
            $config[$n] = $v;
    }

}


function add_fields_from_config(){
    global $config;
    foreach ((array)$config['member_fields'] as $f){
        add_member_field($f['name'], $f['title'],
            $f['type'], $f['description'], $f['validate_func'],
                (array)$f['additional_fields']+array('from_config'=>1));
    }
    foreach ((array)$config['product_fields'] as $f){
        add_product_field($f['name'], $f['title'],
            $f['type'], $f['description'], $f['validate_func'],
                (array)$f['additional_fields']+array('from_config'=>1));
    }
    foreach ((array)$config['payment_fields'] as $f){
        add_payment_field($f['name'], $f['title'],
            $f['type'], $f['description'], $f['validate_func'],
                (array)$f['additional_fields']+array('from_config'=>1));
    }
}

function amember_crypt($string){
    if ($err = _amember_get_iconf()) amDie("License Error: $err");
    $key = 'Xjk23cbnmk28;ajandb4b300zxchB&!@^#$DOFCNCccc334ff,masd';
    $cc = __internal_crypt($string, $key);
    return rawurlencode($cc);
}

function amember_decrypt($string){
    $key = 'Xjk23cbnmk28;ajandb4b300zxchB&!@^#$DOFCNCccc334ff,masd';
    return rawurldecode(rawurlencode(__internal_crypt(rawurldecode($string), $key)));
}

function __internal_crypt($data, $pwd) {
    $cb=''; settype($cb,'array');
    settype($tt, 'string');
    $kk=''; settype($kk,'array');
    for ($i=0,$pl=strlen($pwd);$i<256;$i++){
        $kk[$i]=ord(substr($pwd, ($i % $pl), 1)); $cb[$i]=$i;
    }
    for ($i=0,$j=0;$i<256;$i++){
        $j = ($j + $cb[$i] + $kk[$i]) % 256; $tt = $cb[$i];
        $cb[$i] = $cb[$j]; $cb[$j] = $tt;
    }
    $tttt = $k = $news = $newss = '';
    $a = 0; $j = 0;
    for ($i = 0; $i < strlen($data); $i++) {
        $a +=       1; $a %= 256;
        $j += $cb[$a]; $j %= 256;
        $tttt = $cb[$a]; $cb[$a] = $cb[$j]; $cb[$j] = $tttt;
        $k = $cb[(($cb[$a] + $cb[$j]) % 256)];
        $newss .= chr(ord(substr($data, $i, 1)) ^ $k);
    }
    return $newss;
}


function get_min_domain($domain){
    $domain = preg_replace('/(\:\d+)$/', '', $domain);
    if ($domain == 'localhost') return $domain;
    $tlds = preg_split('/\s+/', ".com .net .org .co.uk .org.uk .ltd.uk .plc.uk .edu .mil .br.com .cn.com
    .eu.com .hu.com .no.com .qc.com .sa.com .se.com .se.net .us.com .uy.com
    .za.com .ac .co.ac .gv.ac .or.ac .ac.ac .af .am .as .at .ac.at .co.at
    .gv.at .or.at .asn.au .com.au .edu.au .org.au .net.au .be .ac.be .biz .br
    .adm.br .adv.br .am.br .arq.br .art.br .bio.br .cng.br .cnt.br .com.br
    .ecn.br .eng.br .esp.br .etc.br .eti.br .fm.br .fot.br .fst.br .g12.br
    .gov.br .ind.br .inf.br .jor.br .lel.br .med.br .mil.br .net.br .nom.br
    .ntr.br .odo.br .org.br .ppg.br .pro.br .psc.br .psi.br .rec.br .slg.br
    .tmp.br .tur.br .tv.br .vet.br .zlg.br .ca .ab.ca .bc.ca .mb.ca .nb.ca
    .nf.ca .ns.ca .nt.ca .on.ca .pe.ca .qc.ca .sk.ca .yk.ca .cc .ac.cn .com.cn
    .edu.cn .gov.cn .net.cn .org.cn .bj.cn .sh.cn .tj.cn .cq.cn .he.cn .nm.cn
    .ln.cn .jl.cn .hl.cn .js.cn .zj.cn .ah.cn .hb.cn .hn.cn .gd.cn .gx.cn
    .hi.cn .sc.cn .gz.cn .yn.cn .xz.cn .sn.cn .gs.cn .qh.cn .nx.cn .xj.cn
    .tw.cn .hk.cn .mo.cn .cx .cz .de .dk .fo .com.ec .org.ec .net.ec .mil.ec
    .fin.ec .med.ec .gov.ec .fr .tm.fr .com.fr .asso.fr .presse.fr .gf .gs
    .co.il .org.il .net.il .ac.il .k12.il .gov.il .muni.il .ac.in .co.in
    .ernet.in .gov.in .net.in .res.in .info .is .it .ac.jp .co.jp .go.jp
    .or.jp .ne.jp .ac.kr .co.kr .go.kr .ne.kr .nm.kr .or.kr .re.kr .li .lt .lu
    .asso.mc .tm.mc .com.mm .org.mm .net.mm .edu.mm .gov.mm .ms .mx .com.mx
    .org.mx .net.mx .edu.mx .gov.mx .name .nl .no .nu .pl .com.pl .net.pl
    .org.pl .pt .com.ro .org.ro .store.ro .tm.ro .firm.ro .www.ro .arts.ro
    .rec.ro .info.ro .nom.ro .nt.ro .ru .com.ru .net.ru .org.ru .se .si
    .com.sg .org.sg .net.sg .gov.sg .sk .st .tc .tf .ac.th .co.th .go.th
    .mi.th .net.th .or.th .tj .tm .to .bbs.tr .com.tr .edu.tr .gov.tr .k12.tr
    .mil.tr .net.tr .org.tr .com.tw .org.tw .net.tw .ac.uk .uk.co .uk.com
    .uk.net .gb.com .gb.net .vg .ac.za .alt.za .co.za .edu.za .gov.za .mil.za
    .net.za .ngo.za .nom.za .org.za .school.za .tm.za .web.za .sh .kz .ch
    .info .ua .biz .ws .nz .com.nz .co.nz .org.nz .com.pk .int .eu .tv");
    $min = '';
    foreach ($tlds as $d){
        $dd = preg_quote($d);
        if (preg_match("/([^\.]+?$dd)\$/",$domain, $regs)){
            if (strlen($regs[1]) > strlen($min)){
                $min = $regs[1];
            }
        }
    }
    if (!strlen($min)) { 
        if (preg_match("/(\w+\.\w+)$/", $domain, $regs)){
            $min = $regs[1];
        } else {
            amDie("Cannot create license: unknown TLD for domain: $domain");
        }
    }
    $dc = $min;
    return strtolower($dc);
}

function decode_ha($myin) {
    $myout = '';
    for ($i=0; $i<strlen($myin)/2; $i++) {
        $myout.=chr(base_convert(substr($myin,$i*2,2),16,10));
    }
    return $myout;
}

function decode_hb($license, &$dmm, &$smm, &$exp){
    $dmm = $smm = $exp = "";
    if (!strlen($license))
        return "License empty - please visit aMember Pro Control Panel -> Setup/Configuration -> License";
    if (!preg_match('|=====.+?=====\s+(\w+)\s+(\w+)\s+(\w+)\s+(\w+)\s+=====|', $license, $line))
        return "License invalid - please contact CGI-Central Support";
    array_shift($line);
    
    $exp = substr($line[1], 32+3, -1); $exp = decode_ha($exp);
    $dmm = substr($line[2], 1, -32-3); $dmm = decode_ha($dmm);
    $smm = substr($line[3], 32+1, -1); $smm = decode_ha($smm);
    
    $fs = is_lite() ? "OIuj3oPih29tbf" : "UmCv0)9237**7231" ;
    $ls = is_lite() ? "!^aslj34cxq2|xO#sx" : ".,nm!#($*^jAdCMy*(&78z76234nkcsP':?z";
    $md5 = strtoupper(md5($fs . $dmm . $exp . ".,nm!#($*^jAdCMy*(&7813nc52asasa|||z"));
    $sd5 = strtoupper(md5("Umxv0)5786*I7x31" . $smm . $exp . $ls));
    $md5o = substr($line[1], 1, 32);
    $sd5o = substr($line[2], strlen($line[2])-33, 32);

    if ($sd5o != $sd5) return "License error - secure domain check incorrect";
    if ($md5o != $md5) return "License error - domain check incorrect";
    if (($sd5o != $sd5) && ($md5o != $md5))
        return "License error - domain check failed";
    if (!$exp) {
        return "License expiration date incorrect";
    }
}

function _amember_get_iconf(){ 
    global $config;

    $domain = $_SERVER['HTTP_HOST'];
    if (!$domain) {
        $domain = parse_url($config['root_url']);
        $domain = $domain['host'];
    }
    if (!$domain) $domain = $_SERVER['SERVER_NAME'];
    if ($domain == '')
        amDie("Cannot get domain name");
    $domain = get_min_domain($domain);
    
    $sdomain = '';

        $sdomain = $_SERVER['HTTP_HOST'];
        if (!$sdomain) {
            $sdomain = parse_url($config['root_surl']);
            $sdomain = $sdomain['host'];
        }
        if (!$sdomain) $sdomain = $_SERVER['SERVER_NAME'];
        if ($sdomain == '')
            amDie("Cannot get secure domain name");
        $sdomain = get_min_domain($sdomain);

    
    if (trim($config['license']) == ''){
        return "After upgrading from aMember Trial to aMember Pro, it is necessary to install <br />

		license key. You can find your license key in the <a target='_blank' href='https://www.amember.com/amember/member.php'>aMember Pro Customers Area</a>";
    }
        
        
    $date = date('Y-m-d');
    global $_amember_license;
    $_amember_license = array();
    foreach (preg_split('|===== ENF OF LICENSE =====[\r\n\s]*|m', $config['license'], -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $v){
        $v .= "===== ENF OF LICENSE =====";
        if ($error = decode_hb($v, $dmm, $smm, $exp))
            return $error;
        if (date('Y-m-d') > $exp){
            mail_admin("
            Your aMember Pro license expired. Please login into CGI-Central
            Members section and get new license file in order to continue
            aMember Pro usage.
            ", "URGENT: License Expired (aMember Pro)");
            return "License expired";
        } elseif (date('Y-m-d') == $exp){
            mail_admin("
            Your aMember Pro license is about to expire. Expiration date: $exp
            Please login into CGI-Central Members section and get new license
            file.
            ", "URGENT: License Expiration (aMember Pro)");
        }
        $_amember_license['expire']          = $exp;
        $_amember_license['domain'][]        = $dmm;
        $_amember_license['secure_domain'][] = $smm;
    }
    
    $up = parse_url($config['root_url']);
    if ($up['host'] == '')
        return "Root URL is empty";
    $root_domain = get_min_domain($up['host']);

    $up = parse_url($config['root_surl']);
    if ($up['host'] == '')
        return "Secure Root URL is empty";
    $sroot_domain = get_min_domain($up['host']);

    $matched_domain = 0; 
    $matched_sdomain = 0;
    $matched_root_url = 0;
    $matched_sroot_url = 0;
    foreach (array_merge($_amember_license['domain'], $_amember_license['secure_domain']) as $d){
        if ($domain == $d) $matched_domain++;
        if ($sdomain == $d) $matched_sdomain++;
        $d = preg_quote($d);
        if (preg_match("/(^|\.)$d\$/", $root_domain)) $matched_root_url++;
        if (preg_match("/(^|\.)$d\$/", $sroot_domain)) $matched_sroot_url++;
    }
    $list_domains = join(',', array_unique(array_merge($_amember_license['domain'], $_amember_license['secure_domain'])));
    
    $url  = ($_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $url .= "$domain$_SERVER[REQUEST_URI]";
    $ref = $_SERVER['HTTP_REFERER'];
    
    if (!$matched_domain) 
        return "License error - license domain does not match your domain ($domain!=$list_domains)<br />\nat $url<br />\nref from $ref";
    if (!$matched_sdomain) 
        return "License error - license domain does not match your secure domain ($sdomain!=$list_domains)<br />\nat $url<br />\nref from $ref";
    if (!$matched_root_url)        
        return "Configured Root URL '$config[root_url]' doesn't match license domain ($list_domains)<br />\nat $url<br />\nref from $ref";
    if (!$matched_sroot_url)        
        return "Configured Secure Root URL '$config[root_surl]' doesn't match license domain ($list_domains)<br />\nat $url<br />\nref from $ref";
    
    return '';
}
    
function _amember_error_handler($errno, $errstr, $errfile, $errline) {
 global $db;
 if (error_reporting() == 0 ) return;
 switch ($errno) {
 case E_ERROR:
 case E_PARSE:
 case E_CORE_ERROR:
 case E_COMPILE_ERROR:
   fatal_error("FATAL [$errno] $errstr\nin line $errline of file $errfile");
   exit(1);
   break;
 case E_USER_ERROR:
   fatal_error("ERROR [$errno] $errstr\nin line $errline of file $errfile");
   break;
 case E_USER_WARNING:
 case E_WARNING:
   $ef = basename($errfile);
   if (!defined('SILENT_AMEMBER_ERROR_HANDLER'))
       print("<b>WARNING:</b> $errstr\nin line $errline of file $ef<br />");
   if ($GLOBALS['AMEMBER_DONT_LOG_NEXT_ERROR']){
       $GLOBALS['AMEMBER_DONT_LOG_NEXT_ERROR'] = null;
   } else {
       $db->log_error("<b>WARNING:</b> $errstr\nin line $errline of file $errfile");
   }
   break;
 }
}


require_once("$config[root_dir]/common.inc.php");

if (isset($_REQUEST['GLOBALS']) || isset($_FILES['GLOBALS']))
    amDie("Request tainting attempted");
$GLOBALS['AMEMBER_DONT_LOG_NEXT_ERROR'] = null;

global $config;

$config['plugins_dir']['payment'] = "$config[root_dir]/plugins/payment";
$config['plugins_dir']['protect'] = "$config[root_dir]/plugins/protect";
$config['plugins_dir']['db']      = "$config[root_dir]/plugins/db";
$config['data_dir']               = "$config[root_dir]/data";
$plugin_config = $config;
read_db_config($config);
set_session_cookie_domain();
start_amember_session();
$plugin_config = $config;
$plugin_error = array();
$plugins = $config['plugins'];
$plugins['db'][0] = 'mysql';

if ($config['site_title'] == '') $config['site_title'] = 'aMember';

require_once("$config[root_dir]/db.inc.php");
require_once("$config[root_dir]/paysys.inc.php");
require_once("$config[root_dir]/member.inc.php");
require_once("$config[root_dir]/product.inc.php");
require_once("$config[root_dir]/payment.inc.php");
require_once("$config[root_dir]/plugins.inc.php");
require_once("$config[root_dir]/plugins/protect/php_include/bruteforce.inc.php");
add_fields_from_config();

require_once("$config[root_dir]/aff.inc.php");

if (file_exists("$config[root_dir]/site.inc.php"))
    require_once("$config[root_dir]/site.inc.php");


if ($config['send_signup_mail'])
    setup_plugin_hook('finish_waiting_payment', 'check_for_signup_mail');
if ($config['send_payment_admin'])
    setup_plugin_hook('finish_waiting_payment', 'mail_payment_admin');
setup_plugin_hook('daily', 'mail_expire_members');
setup_plugin_hook('daily', 'check_expire_members');
setup_plugin_hook('daily', 'clear_access_log');
setup_plugin_hook('daily', 'delete_old_newsletters');
setup_plugin_hook('finish_waiting_payment', 'remove_newsletter_guest');

if (defined('AMEMBER_LICENSE_FIX')){
    function get_current_root_url(){
        $p = ($_SERVER['SERVER_PORT'] == 443) ? 'https' : 'http';
        $h = $_SERVER['HTTP_HOST'];
        $u = $_SERVER['PHP_SELF'];
        $u = preg_replace('|(/admin/license.php.*)$|', '', $u);
        
        return "$p://$h$u";    
    }
    function amember_license_fix(){
        global $config, $db;
        $t = new_smarty();
        admin_check_permissions('setup');

        $vars = get_input_vars();
        if ($vars['do'] == 'save'){
            if (!$vars['root_url']) fatal_error("Please enter correct Root URL", false);
            if (!$vars['root_surl']) fatal_error("Please enter correct Secure Root URL", false);
            if (!$vars['license']) fatal_error("Please enter correct License Key", false);
            
            
            $db->config_set('root_url', $vars['root_url'], 0);
            $db->config_set('root_surl', $vars['root_surl'], 0);
            $db->config_set('license', $vars['license'], 2);
            admin_html_redirect($_SERVER['PHP_SELF'], 'Changes Applied', "License key and urls are updated", true); 
            exit();
        }

        global $config;
        $t->assign('msg', _amember_get_iconf());
        $t->assign('current_url', get_current_root_url());
        $t->display('admin/license.html');
    }
    require dirname(__FILE__)."/admin/login.inc.php";
    amember_license_fix();
    exit();
}



function amember_get_iconf_r() {
    global $config, $db;
    $in_license_php = @$_REQUEST['__amember_fix_products_12'] ? true : false;
    unset($_REQUEST['__amember_fix_products_12']); 
    
    if ($in_license_php && preg_match('|/license.php$|', @$_SERVER['PHP_SELF'])){
        $GLOBALS['__hooks'] = array();
        return null; 
    }
    
    if ($msg = _amember_get_iconf()){ 
        $msg .= "<br><a href='$config[root_url]/admin/license.php'>If you are the site administrator, click this link to fix</a>";
        fatal_error($msg, 0);
    }
}
amember_get_iconf_r();

if (!$config['use_cron'])
    check_cron();
     
// END OF AMEMBER STARTUP CODE