<?php

/* CLASS FILE
----------------------------------*/

class mswsys extends db {

  public $dt;
  public $settings;
  
  public function getCFG($op = 'admin_links', $get = array('op2','op6')) {
    $arr = [];
    $q = db::db_query("SELECT * FROM `" . DB_PREFIX . "cfg` WHERE `op1` = '{$op}' ORDER BY `id`");
    while ($cfg = db::db_object($q)) {
      $arr[$cfg->{$get[0]}] = ($cfg->{$get[1]} ? explode(',', $cfg->{$get[1]}) : []); 
    }
    return $arr;
  }
  
  public function links($fm, $del = 'no') {
    db::db_query("DELETE FROM `" . DB_PREFIX . "cfg` WHERE `op1` = 'admin_links'");
    db::db_truncate(array('cfg'));
    if ($del == 'yes') {
      return false;
    }
    if (!empty($fm['am_sections'])) {
      foreach($fm['am_sections'] AS $section) {
        $op6 = (!empty($fm['am_links'][$section]['links']) ? implode(',', $fm['am_links'][$section]['links']) : '');
        db::db_query("INSERT INTO `" . DB_PREFIX . "cfg` (
        `op1`,
        `op2`,
        `op6`
        ) VALUES (
        'admin_links',
        '" . db::db_escape($section) . "',
        '" . db::db_escape($op6) . "'
        )");
      }
    }
  }
  
  public function paths($path, $type = '') {
    switch($type) {
      case 'i':
        if (substr($path, -1) != '/') {
          $path = $path . '/';
        }
        break;
      case 'file':
        return $path;
        break;
      default:
        if (substr($path, -1) == '/') {
          $path = substr_replace($path, '', -1);
        }
        if (substr($path, -1) == '\\') {
          $path = substr_replace($path, '', -2);
        }
        break;
    }
    return $path;
  }

  public function settings($fm) {
    db::db_query("UPDATE `" . DB_PREFIX . "settings` SET
    `website`     = '" . db::db_escape($fm['website']) . "',
    `email`       = '" . db::db_escape($fm['email']) . "',
    `language`    = '{$fm['language']}',
    `ifolder`     = '" . db::db_escape($fm['protocol'] . '://' . str_replace(array('http://','https://'),[],mswsys::paths($fm['ifolder'], 'i'))) . "',
    `bfolder`     = '" . db::db_escape(mswsys::paths($fm['bfolder'])) . "',
    `dateformat`  = '" . db::db_escape($fm['dateformat']) . "',
    `timeformat`  = '" . db::db_escape($fm['timeformat']) . "',
    `timezone`    = '{$fm['timezone']}',
    `calformat`   = '{$fm['calformat']}',
    `weekstart`   = '{$fm['weekstart']}',
    `afoot`       = '" . db::db_escape($fm['afoot']) . "',
    `pfoot`       = '" . db::db_escape($fm['pfoot']) . "',
    `apikey`      = '" . db::db_escape($fm['apikey']) . "',
    `apilog`      = '{$fm['apilog']}',
    `affcode`     = '" . db::db_escape($fm['affcode']) . "',
    `createaff`   = '{$fm['createaff']}',
    `approve`     = '{$fm['approve']}',
    `approveaff`  = '{$fm['approveaff']}',
    `currency`    = '{$fm['currency']}',
    `priceformat` = '" . db::db_escape($fm['priceformat']) . "',
    `affdel`      = '{$fm['affdel']}',
    `ipmatch`     = '{$fm['ipmatch']}',
    `pr`          = '{$fm['pr']}',
    `pr_areas`    = '" . (!empty($fm['pr_areas']) ? serialize($fm['pr_areas']) : '') . "',
    `delem`       = '{$fm['delem']}'
    ");
  }

  public function email($fm) {
    db::db_query("UPDATE `" . DB_PREFIX . "settings` SET
    `addemails`     = '" . db::db_escape($fm['addemails']) . "',
	  `smtp_host`     = '" . db::db_escape($fm['smtp_host']) . "',
    `smtp_user`     = '" . db::db_escape($fm['smtp_user']) . "',
    `smtp_pass`     = '" . db::db_escape($fm['smtp_pass']) . "',
    `smtp_port`     = '{$fm['smtp_port']}',
    `smtp_from`     = '" . db::db_escape($fm['smtp_from']) . "',
    `smtp_email`    = '" . db::db_escape($fm['smtp_email']) . "',
    `smtp_rfrom`    = '" . db::db_escape($fm['smtp_rfrom']) . "',
    `smtp_remail`   = '" . db::db_escape($fm['smtp_remail']) . "',
    `smtp_security` = '{$fm['smtp_security']}',
    `smtp_debug`    = '{$fm['smtp_debug']}',
    `mailpref`      = '{$fm['mailpref']}',
    `captcha`       = '{$fm['captcha']}',
    `smtp_insec`    = '{$fm['smtp_insec']}'
    ");
    foreach (array_keys($fm['api']) AS $k) {
      foreach ($fm['api'][$k] AS $apiK => $apiV) {
        $Q = db::db_query("SELECT `id`
             FROM `" . DB_PREFIX . "social`
             WHERE `desc` = '{$k}'
             AND `param` = '{$apiK}'
             LIMIT 1
             ");
        $PAR = db::db_object($Q);
        if (isset($PAR->id)) {
          db::db_query("UPDATE `" . DB_PREFIX . "social` SET
          `value`    = '" . db::db_escape($apiV) . "'
          WHERE `id` = '{$PAR->id}'
          ");
        } else {
          db::db_query("INSERT INTO `" . DB_PREFIX . "social` (
          `desc`,
          `param`,
          `value`
          ) VALUES (
          '" . db::db_escape($k) . "',
          '" . db::db_escape($apiK) . "',
          '" . db::db_escape($apiV) . "'
          )");
        }
      }
    }
  }

  public function offline($fm) {
    db::db_query("UPDATE `" . DB_PREFIX . "settings` SET
    `sysstatus`  = '" . db::db_escape($fm['sysstatus']) . "',
    `reason`     = '" . db::db_escape($fm['reason']) . "',
    `autoenable` = '" . $this->dt->jstots($fm['autoenable'], true) . "'
    ");
  }

  public function social() {
    db::db_truncate(array('social'), true);
    if (!empty($_POST['fm'])) {
      $keys = array_keys($_POST['fm']);
      if (!empty($keys)) {
        foreach (array_unique($keys) AS $k) {
          $k = preg_replace('/[^0-9a-zA-Z]/', '', $k);
          if ($k) {
            if ($k != 'protocol') {
              foreach ($_POST['fm'][$k] AS $sK => $sV) {
                if ($sV) {
                  // For links, append protocol
                  if ($k == 'links') {
                    $sV = (isset($_POST['fm']['protocol'][$sK]) && in_array($_POST['fm']['protocol'][$sK], array('http','https')) ? $_POST['fm']['protocol'][$sK] : 'http') . '://' . str_replace(array('http://','https://'),[],$sV);
                  }
                  db::db_query("INSERT INTO `" . DB_PREFIX . "social` (
                  `desc`,
                  `param`,
                  `value`
                  ) VALUES (
                  '" . db::db_escape($k) . "',
                  '" . db::db_escape($sK) . "',
                  '" . db::db_escape($sV) . "'
                  )");
                }
              }
            }
          }
        }
      }
    }
  }

  public function themes($fm) {
    db::db_query("UPDATE `" . DB_PREFIX . "settings` SET
    `theme`   = '" . db::db_escape($fm['theme']) . "',
    `entheme` = '" . db::db_escape($fm['entheme']) . "'
    ");
    db::db_truncate(array('themes'), true);
    for ($i=0; $i<count($fm['thm']); $i++) {
      if ($fm['thm'][$i] != 'none' && $fm['from'][$i] && $fm['to'][$i]) {
        db::db_query("INSERT INTO `" . DB_PREFIX . "themes` (
        `theme`,
        `from`,
        `to`
        ) VALUES (
        '" . db::db_escape($fm['thm'][$i]) . "',
        '" . $this->dt->jstots($fm['from'][$i]) . "',
        '" . $this->dt->jstots($fm['to'][$i]) . "'
        )");
      }
    }
  }

  // Check for new version..
  public function version() {
    $url = 'https://www.maianmedia.com/version-check.php?id=' . SCRIPT_ID;
    $str = [];
    if (defined('SCRIPT_NAME') && defined('SCRIPT_URL')) {
      try {
        if (function_exists('curl_init')) {
          $ch = curl_init();
          curl_setopt($ch, CURLOPT_URL, $url);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
          curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
          curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
          curl_setopt($ch, CURLOPT_CAINFO, GPATH . 'control/system/certs/cacert.pem');
          $r = curl_exec($ch);
          curl_close($ch);
        }
        if ($r) {
          if ($r != $this->settings->version) {
            $str[] = 'Installed Version: <b>' . $this->settings->version . '</b>';
            $str[] = 'Latest Version: <b>' . $r . '</b>';
            $str[] = '<hr style="margin-bottom:7px"><span style="color:#f66f66">Your version of ' . SCRIPT_NAME . ' is out of date</span>.<hr style="margin:7px 0 7px 0">';
            $str[] = '<a href="https://www.' . SCRIPT_URL . '/download" onclick="window.open(this);return false"><i class="fa fa-download fa-fw"></i> Download Latest Version</a>';
            $str[] = '<a href="https://www.' . SCRIPT_URL . '/changelog.txt" onclick="window.open(this);return false"><i class="fa fa-binoculars fa-fw"></i> View changelog</a><hr><span style="font-style:italic">If you are running the commercial version, upgrades are free.</span>';
          } else {
            $str[] = 'Current Version: <b>' . $this->settings->version . '</b><hr><i class="fa fa-check fa-fw"></i> You are currently using the latest version';
          }
        }
      } catch(Exception $e) {
        Debugger::log($e->getMessage());
      }
    }
    // Nothing?
    if (empty($str)) {
      $str[] = 'Server check functions not available.' . mswNL();
      $str[] = 'Please visit <a href="https://www.' . SCRIPT_URL . '/download" onclick="window.open(this);return false"><b>www.' . SCRIPT_URL . '</b></a> to check for updates';
    }
    return implode(mswNL(), $str);
  }

  public function unicode($len = 30, $add = '') {
    return substr(mswEnc(uniqid(rand(),1) . $add), 3, $len);
  }

  public function fileclear($path, $ext) {
    $nuke = [];
    if (is_dir($path)) {
      $files = Nette\Utils\Finder::findFiles(['*' . $ext])
        ->in($path);
      if (!empty($files)) {
        foreach($files AS $file) {
          $nuke[] = $path . '/' . $file->getBasename();
        }
      }
    }
    if (!empty($nuke)) {
      try {
        foreach($nuke AS $n) {
          unlink($n);
        }
      } catch(Exception $e) {
        Debugger::log($e->getMessage());
      } catch(Error $e) {
        Debugger::log($e->getMessage());
      }
    }
  }

}

?>