<?php 

/*
  SOFTWARE CONTROLLER FILE
  Please DO NOT make changes to this file, thank you

  This software is protected by UK laws. To modify this
  file to bypass the licence system is strictly forbidden

  Kindly consider a commercial licence to support this project.

  More info @ https://www.maianaffiliate.com
--------------------------------------------------------------------*/


if (!defined('PARENT')) {exit;}

if (!function_exists('openssl_encrypt')) {
  die('Software Load Failure.<br><br>PHP <b>must</b> be compiled with <a href="https://www.php.net/manual/en/ref.openssl.php">openssl</a> support.<br><br>Try enabling the openssl extension in the PHP.ini file and rebooting the server or recompile with openssl support.');
}

if (!function_exists('mysqli_connect')) {
  die('Software Load Failure.<br><br>PHP <b>must</b> be compiled with <a href="https://www.php.net/manual/en/book.mysqli.php">mysqli_connect</a> support.');
}

define('LIC_PATH', __dir__ . '/../../../');
define('LIC_DOM', (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''));
define('LIC_DOM_HOST', substr((isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''), 4));
define('LIC_UNI', '616BAF25D8A54EFE2C5C1750B3EBEC1255165D27');
define('LIC_ENC_SALT', 'wQdu9Eej3ARoge8tZJq4Mm16WfOpyMb3TNqkoKzdg8Irn8pU6vR26xvbYB0t3LWUv5YMI8Ddyw73jUT5EL6kFg==');
define('LIC_SOFTWARE', 'affiliate');
define('RESTR_BOXES', 3);
define('RESTR_PAGES', 3);
define('RESTR_PRODUCTS', 2);
define('RESTR_ADM_PAGES', 3);
define('RESTR_AFFILIATES', 300);

// Log cron data..
if (defined('LOG_CRON_GLOBALS')) {
  mswPUT(LIC_PATH . 'logs/cron_info.txt', print_r($GLOBALS, true));
}

class mswLic extends db {

  private $cronFiles = [];

  private function _le() {
    return PHP_EOL;
  }

  public function _check() {
    if (file_exists(LIC_PATH . 'licence.lic')) {
      $Q       = db::db_query("SELECT `prodkey` FROM `" . DB_PREFIX . "settings`", true);
      if ($Q == 'err') {
        $fatalErr = true;
      } else {
        $s = db::db_object($Q);
      }
      $licfile = file_get_contents(LIC_PATH . 'licence.lic');
      $file    = explode('------ MSW LIC FILE DATA -------', $licfile);
      // Decode here..
      $dec     = mswLic::_decoder((isset($file[2]) ? $file[2] : '#:#'));
      preg_match("/<mswlic>(.+)<\/mswlic>/si", $dec, $match);
      // If the prodkey field is missing, show message..
      if (isset($fatalErr) || (!isset($fatalErr) && !isset($s->prodkey))) {
        echo mswLic::_runtime();
        exit;
      }
      if (isset($match[1]) && $match[1] == 'failed-cipher') {
        echo mswLic::_runtime('cipher');
        exit;
      }
      if (isset($match[1]) && isset($s->prodkey)) {
        // Is this the free version?
        if (strtolower($match[1]) == 'free-' . LIC_SOFTWARE) {
          return (defined('LIC_DEV') ? 'unlocked' : 'locked');
        } else {
          if (isset($match[1])) {
            $block = explode('|', $match[1]);
            $alld  = [];
            $key   = (isset($block[0]) ? strtoupper($block[0]) : '');
            $uni   = (isset($block[1]) ? strtoupper($block[1]) : '');
            $scr   = (isset($block[2]) ? $block[2] : '');
            $dom   = (isset($block[3]) ? strtolower($block[3]) : '');
            $exp   = (isset($block[4]) ? $block[4] : '');
            // Domains to array..
            if (strpos($dom, ',') !== false) {
              $alld = explode(',', $dom);
            } else {
              $alld[] = $dom;
            }
            if ($key && $uni && $scr && $dom) {
              // Check expiry..
              if ($exp && strtotime($exp) > 0) {
                if ($exp < date('Y-m-d')) {
                  echo mswLic::_event_handler(7, '', '', '', strtotime($exp));
                  exit;
                }
              }
              // Localhost and cron jobs..
              // Prevents cron running with errors..
              $cronHost = [
                'localhost',
                '127.0.0.1',
                '::1'
              ];
              if (isset($_SERVER['argv'][0]) && in_array(basename($_SERVER['argv'][0]), $this->cronFiles)) {
                define('CRON_RUNNING', 1);
              }
              if (isset($_SERVER['_']) && !defined('CRON_RUNNING')) {
                define('CRON_RUNNING', 1);
              }
              // Logging..
              if (defined('LOG_CRON_GLOBALS')) {
                $string  = 'LICENCE VALUES' . mswLic::_le() . str_repeat('=', 50) . mswLic::_le();
                $string .= 'LIC_DOM VALUE: ' . LIC_DOM . mswLic::_le();
                $string .= 'LIC_DOM_HOST VALUE: ' . LIC_DOM_HOST . mswLic::_le();
                $string .= 'Localhost: ' . print_r($cronHost, true) . mswLic::_le();
                $string .= 'All Domains: ' . print_r($alld, true) . mswLic::_le();
                $string .= 'Dom Value: ' . $dom . mswLic::_le();
                $string .= 'Server Vars: ' . print_r($_SERVER, true) . mswLic::_le();
                mswPUT(LIC_PATH . LOG_FOLDER . '/cron_info.txt', trim($string));
              }
              // Check key..
              if ($key != strtoupper($s->prodkey)) {
                echo mswLic::_event_handler(3, '', $key, $s);
                exit;
                // Check domain.
              } else if (!defined('LIC_BYPASS') && !defined('CRON_RUNNING') && !in_array(LIC_DOM, $cronHost) && !in_array(strtolower(LIC_DOM), $alld) && !in_array(strtolower(LIC_DOM_HOST), $alld) && strpos(LIC_DOM, $dom) === false) {
                echo mswLic::_event_handler(2, $dom, '', $s);
                exit;
                // Check software..
              } else if (($uni != LIC_UNI) || ($scr != LIC_SOFTWARE)) {
                echo mswLic::_event_handler(6, '', '', $s);
                exit;
                // All good..
              } else {
                return 'unlocked';
              }
            } else {
              // Corrupt..
              echo mswLic::_event_handler(5, '', '', $s);
              exit;
            }
          } else {
            // Corrupt..
            echo mswLic::_event_handler(5, '', '', $s);
            exit;
          }
        }
      } else {
        // Corrupt..
        echo mswLic::_event_handler(5, '', '', $s);
        exit;
      }
    } else {
      // Missing..
      echo mswLic::_event_handler(1);
      exit;
    }
  }

  public function _event_handler($code, $domain = '', $key = '', $s = '', $exp = 0) {
    if (defined('LOG_CRON_GLOBALS')) {
      $string  = 'CODE LOGGING' . mswLic::_le() . str_repeat('=', 50) . mswLic::_le();
      $string .= $code . mswLic::_le();
      mswPUT(LIC_PATH . LOG_FOLDER . '/cron_info.txt', trim($string));
    }
    switch ($code) {
      case '1':
        $e = 'This software requires a &quot;licence.lic&quot; file. It should be in the root of your software installation.';
        break;
      case '2':
        $e = 'The &quot;licence.lic&quot; file within this installation cannot run on this server because the domain specified in the licence instructions (' . $domain . ') is different to the installation domain (' . LIC_DOM . '). If you need to change the domain for your licence, please log into the <a href="https://www.maianmedia.com/accounts/view/dashboard" onclick="window.open(this);return false">licence centre</a>';
        break;
      case '3':
        $e = 'The &quot;licence.lic&quot; file within this installation contains an invalid product key (' . $key . ').<br><br>This may be due to entering the key incorrectly on licence creation or you may have re-installed the software again, which created a new key.<br><br>If you have re-installed, please <a href="https://www.maianmedia.com/accounts/view/dashboard" onclick="window.open(this);return false">update your product key</a> and re-download the licence again.';
        break;
      case '5':
        $e = 'This &quot;licence.lic&quot; file appears to be corrupt. Please open the licence.lic file in a text editor and make sure that the domain is correct and that the licence key matches the value in your prodKey column in your database settings table.';
        break;
      case '6':
        $e = 'This &quot;licence.lic&quot; file appears to be for different software. Please re-download and try again.';
        break;
      case '7':
        $e = 'This licence expired on ' . date('j/M/Y', $exp) . '.';
        break;
      default:
        $e = 'Unknown error. Please contact us for assistance.';
        break;
    }
    $help = 'If the above message wasn\'t helpful and you still need assistance, you should first see if a solution is in the software documentation.<br><br>If that doesn\'t help, please <a href="https://www.maianmedia.com/support" onclick="window.open(this);return false">contact us</a> for assistance.<br><br>If you have paid for a commercial licence, please send a message via the <a href="https://www.maianmedia.com/accounts/view/dashboard" onclick="window.open(this);return false">Licence Centre</a>, thank you.<br><br>We apologise for any inconvenience and hope this issue is resolved as soon as possible.<hr>Development Team - Maian Media</span>';
    return mswLic::_wrapper($help, $e);
  }

  public function _encode($string) {
    $data = base64_encode($string);
    $data = str_replace([
      '+','/','='
    ], [
      '-','_',''
    ], $data);
    return $data;
  }

  private function _decode($string) {
    $data = str_replace([
      '-','_'
    ], [
      '+','/'
    ], $string);
    $mod4 = strlen($data) % 4;
    if ($mod4) {
      $data .= substr('====', $mod4);
    }
    return base64_decode($data);
  }

  private function _encoder($value) {
    if (!$value) {
      return false;
    }
    $text      = $value;
    $iv        = openssl_random_pseudo_bytes(openssl_cipher_iv_length('AES-256-CBC'));
    $encrypted = openssl_encrypt($text, 'AES-256-CBC', LIC_ENC_KEY, 0, $iv);
    return trim($encrypted . ':' . mswLic::_encode($iv));
  }

  private function _decoder($value) {
    if (!$value) {
      return false;
    }
    $ciphers     = openssl_get_cipher_methods();
    $parts       = explode(':', $value);
    // Uppercase...
    if (isset($parts[0], $parts[1]) && in_array('AES-256-CBC', $ciphers)) {
      return trim(openssl_decrypt($parts[0], 'AES-256-CBC', LIC_ENC_KEY, 0, mswLic::_decode($parts[1])));
    }
    // Might even be lowercase..
    if (isset($parts[0], $parts[1]) && in_array('aes-256-cbc', $ciphers)) {
      return trim(openssl_decrypt($parts[0], 'aes-256-cbc', LIC_ENC_KEY, 0, mswLic::_decode($parts[1])));
    }
    return 'failed-cipher';
  }

  public function _sys_check() {
    $err = [];
    $cnt = 0;
    if (defined('SCRIPT_MIN_PHP_VERSION') && phpVersion() < SCRIPT_MIN_PHP_VERSION) {
      $err[] = '(' . (++$cnt) . ') Your PHP version of ' . phpVersion() . ' is too old to run this software. v' . SCRIPT_MIN_PHP_VERSION . '+ is required';
    } else {
      if (is_dir(LIC_PATH . 'install')) {
        $err[] = '(' . (++$cnt) . ') Please remove or rename the "install" folder in your software directory.';
      }
      if (SECRET_KEY == 'Your secret key value goes here') {
        $err[] = '(' . (++$cnt) . ') Personal secret key in database connection file (control/_cfg.php) MUST be set for security.';
      }
      if (!function_exists('json_encode')) {
        $err[] = '(' . (++$cnt) . ') <a href="https://www.php.net//manual/en/book.json.php" onclick="window.open(this);return false">JSON</a> functions NOT enabled. Please recompile server with json support.';
      }
      if (!function_exists('openssl_encrypt')) {
        $err[] = '(' . (++$cnt) . ') <a href="https://www.php.net/manual/en/ref.openssl.php" onclick="window.open(this);return false">OPENSSL</a> functions NOT found. Please recompile server with openssl support.';
      }
      if (!function_exists('curl_init')) {
        $err[] = '(' . (++$cnt) . ') <a href="https://www.php.net/manual/en/book.curl.php" onclick="window.open(this);return false">CURL</a> functions NOT enabled. Please recompile server with curl support.';
      }
    }
    if (!empty($err)) {
      $help    = 'If any modules are missing and you don\'t understand how to enable them, please contact your web host who should be able to assist as in most cases, root server access is required.<br><br>If you require information, please <a href="https://www.maianmedia.com/support" onclick="window.open(this);return false">contact us</a> for assistance.<br><br>If you have paid for a commercial licence, please send a message via the <a href="https://www.maianmedia.com/accounts/view/dashboard" onclick="window.open(this);return false">Licence Centre</a>, thank you.<br><br>We apologise for any inconvenience.<hr>Development Team - Maian Media';
      return mswLic::_wrapper($help, implode('<br><br>', $err));
    }
  }

  public function _runtime($flag = '') {
    $err     = [];
    if ($flag == 'cipher') {
      $err[] = 'PHP must be compiled with OpenSSL support and the "AES-256-CBC" cipher must be available.<br><br>Please recompile PHP and reboot server';
    } else {
      $url = (isset($_SERVER['PHP_SELF']) && strpos(basename(dirname($_SERVER['PHP_SELF'])), 'admin') !== false ? '../' : '');
      $err[]   = 'Database failed. Did you run the installer? <a href="' . $url . 'install/">Attempt to Load Installer</a><br><br>If link fails, access the "/install/" directory in your installation.';
    }
    $help    = 'If you don\'t understand the above message and require assistance, please <a href="https://www.maianmedia.com/support" onclick="window.open(this);return false">contact us</a> for assistance.<br><br>If you have paid for a commercial licence, please send a message via the <a href="https://www.maianmedia.com/accounts/view/dashboard" onclick="window.open(this);return false">Licence Centre</a>, thank you.<br><br>We apologise for any inconvenience.<hr>Development Team - Maian Media';
    return mswLic::_wrapper($help, implode('<br><br>', $err));
  }

  public function _free_check() {
    $err = [];
    $cnt = 0;
    if ($this->db_rowcount('products') > RESTR_PRODUCTS) {
      $err[] = '(' . (++$cnt) . ') The free version permits the following number of products: ' . RESTR_PRODUCTS;
    }
    if ($this->db_rowcount('affiliates') > RESTR_AFFILIATES) {
      $err[] = '(' . (++$cnt) . ') The free version permits the following number of affiliates: ' . RESTR_AFFILIATES;
    }
    if ($this->db_rowcount('boxes') > RESTR_BOXES) {
      $err[] = '(' . (++$cnt) . ') The free version permits the following number of menu boxes: ' . RESTR_BOXES;
    }
    if ($this->db_rowcount('pages') > RESTR_PAGES) {
      $err[] = '(' . (++$cnt) . ') The free version permits the following number of additional pages: ' . RESTR_PAGES;
    }
    if ($this->db_rowcount('admin_pages') > RESTR_ADM_PAGES) {
      $err[] = '(' . (++$cnt) . ') The free version permits the following number of additional admin pages: ' . RESTR_ADM_PAGES;
    }
    if (!empty($err)) {
      $help    = 'If you made manual changes in your database, please revert these changes back to remove this error. If you have paid for a commercial licence, please generate your licence at the <a href="https://www.maianmedia.com/accounts/view/dashboard" onclick="window.open(this);return false">Licence Centre</a> to remove this error, thank you.<br><br>A commercial licence offers the following benefits:<br><br><span style="font-style:italic;display:block">
      + ALL Future upgrades FREE of Charge<br>
      + Notifications of new version releases<br>
      + All features unlocked and unlimited<br>
      + Copyright removal included in price<br>
      + No links in email footers<br>
      + One off payment, no subscriptions<br>
      + 3 Months personal support (renewable)</span><br>Click the purchase link in your admin area for more information.<br><br>We apologise for any inconvenience.<hr>Development Team - Maian Media</span>';
      return mswLic::_wrapper($help, implode('<br><br>', $err));
    }
  }
  
  public function _wrapper($html, $errs) {
    if (file_exists(dirname(__file__) . '/layout.html')) {
      $str = file_get_contents(dirname(__file__) . '/layout.html');
    } else {
      $str = '{errors}<br><br>{html}';
    }
    return strtr($str, [
      '{errors}' => $errs,
      '{html}' => $html,
      '{copyright}' => SCRIPT_RELEASE_YR . '-' . date('Y') . ' ' . SCRIPT_NAME,
      '{website}' => SCRIPT_URL,
      '{script_name}' => SCRIPT_NAME,
      '{docs}' => (isset($_SERVER['PHP_SELF']) && defined('ADM_FLDR_NAME') ?
        (strpos($_SERVER['PHP_SELF'], ADM_FLDR_NAME) !== false ? '../docs/' : 'docs/') :
        SCRIPT_URL
      )
    ]);
  }

}

// Initialise..
$MSWLIC = new mswLic();
define('LIC_ENC_KEY', sha1(sha1($MSWLIC->_encode(LIC_ENC_SALT))) . sha1($MSWLIC->_encode(LIC_ENC_SALT)));
define('LICENCE_VER', $MSWLIC->_check());

// System check..
if (!defined('LIC_DEV')) {
  $err = $MSWLIC->_sys_check();
  if ($err) {
    echo $err;
    exit;
  }
}
// Free version check..
if (!defined('LIC_DEV') && !defined('ADMIN_PANEL')) {
  if (LICENCE_VER == 'locked') {
    $err = $MSWLIC->_free_check();
    if ($err) {
      echo $err;
      exit;
    }
  }
}

?>