<?php
class S
{
  public static function parse_csv($csv_string, $delimiter = ",", $skip_empty_lines = true, $trim_fields = true)
  {
    return array_map(
      function ($line) use ($delimiter, $trim_fields)
      {
        return array_map(
          function ($field)
          {
            return str_replace('!!Q!!', '"', utf8_decode(urldecode($field)));
          },
          $trim_fields ? array_map('trim', explode($delimiter, $line)) : explode(
            $delimiter,
            $line
          )
        );
      },
      preg_split(
        $skip_empty_lines ? ($trim_fields ? '/( *\R)+/s' : '/\R+/s') : '/\R/s',
        preg_replace_callback(
          '/"(.*?)"/s',
          function ($field)
          {
            return urlencode(utf8_encode($field[1]));
          },
          $enc = preg_replace('/(?<!")""/', '!!Q!!', $csv_string)
        )
      )
    );
  }

  public static function generateRandomString($length = 5)
  {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++)
    {
      $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
  }

  public static function get_domain($url)
  {
    $url = parse_url($url, PHP_URL_HOST);
    $url = str_replace("www.", "", $url);
    return $url;
  }

  public static function array_sort_by_column(&$arr, $col, $dir = SORT_ASC)
  {
    $sort_col = array();
    foreach ($arr as $key => $row)
    {
      $sort_col[$key] = $row[$col];
    }

    array_multisort($sort_col, $dir, $arr);
  }

  function getUrlData($url)
  {
    $result = false;

    $contents = \S::getUrlContents($url);

    if (isset($contents) && is_string($contents))
    {
      $title = null;
      $metaTags = null;

      preg_match('/<title>([^>]*)<\/title>/si', $contents, $match);

      if (isset($match) && is_array($match) && count($match) > 0)
      {
        $title = strip_tags($match[1]);
      }

      preg_match_all('/<[\s]*meta[\s]*name="?' . '([^>"]*)"?[\s]*' . 'content="?([^>"]*)"?[\s]*[\/]?[\s]*>/si', $contents, $match);

      if (isset($match) && is_array($match) && count($match) == 3)
      {
        $originals = $match[0];
        $names = $match[1];
        $values = $match[2];

        if (count($originals) == count($names) && count($names) == count($values))
        {
          $metaTags = array();

          for ($i = 0, $limiti = count($names); $i < $limiti; $i++)
          {
            $metaTags[$names[$i]] = array(
              'html' => htmlentities($originals[$i]),
              'value' => $values[$i]
            );
          }
        }
      }

      $result = array(
        'title' => $title,
        'metaTags' => $metaTags
      );
    }

    return $result;
  }

  function getUrlContents($url, $maximumRedirections = 1, $currentRedirection = 0)
  {
    $result = false;

    $contents = @file_get_contents($url);

    // Check if we need to go somewhere else

    if (isset($contents) && is_string($contents))
    {
      preg_match_all('/<[\s]*meta[\s]*http-equiv="?REFRESH"?' . '[\s]*content="?[0-9]*;[\s]*URL[\s]*=[\s]*([^>"]*)"?' . '[\s]*[\/]?[\s]*>/si', $contents, $match);

      if (isset($match) && is_array($match) && count($match) == 2 && count($match[1]) == 1)
      {
        if (!isset($maximumRedirections) || $currentRedirection < $maximumRedirections)
        {
          return self::getUrlContents($match[1][0], $maximumRedirections, ++$currentRedirection);
        }

        $result = false;
      }
      else
      {
        $result = $contents;
      }
    }

    return $contents;
  }

  public function getMonthNames()
  {
    return array(1 => 'Styczeń', 2 => 'Luty', 3 => 'Marzec', 4 => 'Kwiecień', 5 => 'Maj', 6 => 'Czerwiec', 7 => 'Lipiec', 8 => 'Sierpień', 9 => 'Wrzesień', 10 => 'Październik', 11 => 'Listopad', 12 => 'Grudzień');
  }

  function getAddresses($domain)
  {
    $records = dns_get_record($domain);
    $res = array();
    foreach ($records as $r)
    {
      if ($r['host'] != $domain) continue; // glue entry
      if (!isset($r['type'])) continue; // DNSSec

      if ($r['type'] == 'A') $res[] = $r['ip'];
      if ($r['type'] == 'AAAA') $res[] = $r['ipv6'];
    }
    return $res;
  }

  public static function number($value)
  {
    return number_format($value, 2, '.', '');
  }

  public function number_display($value)
  {
    return number_format($value, 2, ',', ' ') . ' zł';
  }

  public function downloadFile($file)
  {
    if (file_exists($file) && is_readable($file))
    {
      $name = str_replace('temp/', '', $file);
      $name = str_replace('temp_t/', '', $name);
      header('Content-type: application/pdf');
      header("Content-Disposition: attachment; filename=\"" . $name . "\"");
      readfile($file);
    }
    exit;
  }

  function d2w($digits)
  {
    if ($digits * 1 == 0)
    {
      return "zero";
    }

    $jednosci     = array('zero', 'jeden', 'dwa', 'trzy', 'cztery', 'pięć', 'sześć', 'siedem', 'osiem', 'dziewięć');
    $dziesiatki   = array('', 'dziesięć', 'dwadzieścia', 'trzydzieści', 'czterdzieści', 'piećdziesiąt', 'sześćdziesiąt', 'siedemdziesiąt', 'osiemdziesiąt', 'dziewiećdziesiąt');
    $setki        = array('', 'sto', 'dwieście', 'trzysta', 'czterysta', 'pięćset', 'sześćset', 'siedemset', 'osiemset', 'dziewięćset');
    $nastki       = array('dziesięć', 'jedenaście', 'dwanaście', 'trzynaście', 'czternaście', 'piętnaście', 'szesnaście', 'siedemnaście', 'osiemnaście', 'dzięwietnaście');
    $tysiace      = array('tysiąc', 'tysiące', 'tysięcy');

    $digits = (string) $digits;
    $digits = strrev($digits);
    $i      = strlen($digits);
    $string = '';

    if ($i > 5 && $digits[5] > 0)
    {
      $string .= $setki[$digits[5]] . ' ';
    }
    if ($i > 4 && $digits[4] > 1)
    {
      $string .= $dziesiatki[$digits[4]] . ' ';
    }
    else if ($i > 3 && $digits[4] == 1)
    {
      $string .= $nastki[$digits[3]] . ' ';
    }
    if ($i > 3 && $digits[3] > 0 && $digits[4] != 1)
    {
      $string .= $jednosci[$digits[3]] . ' ';
    }
    $tmpStr = substr(strrev($digits), 0, -3);
    if (strlen($tmpStr) > 0)
    {
      $tmpInt = (int) $tmpStr;
      if ($tmpInt == 1)
      {
        $string .= $tysiace[0] . ' ';
      }
      elseif (($tmpInt % 10 > 1 && $tmpInt % 10 < 5) && ($tmpInt < 10 || $tmpInt > 20))
      {
        $string .= $tysiace[1] . ' ';
      }
      else
      {
        $string .= $tysiace[2] . ' ';
      }
    }
    if ($i > 2 && $digits[2] > 0)
    {
      $string .= $setki[$digits[2]] . ' ';
    }
    if ($i > 1 && $digits[1] > 1)
    {
      $string .= $dziesiatki[$digits[1]] . ' ';
    }
    elseif ($i > 0 && $digits[1] == 1)
    {
      $string .= $nastki[$digits[0]] . ' ';
    }
    if ($digits[0] > 0 && $digits[1] != 1)
    {
      $string .= $jednosci[$digits[0]] . ' ';
    }
    return $string;
  }

  function slownie($a, $j1, $j2, $j3)
  {
    $out   = self::d2w($a);
    $i    = strlen($a);
    $l     = substr($a, $i - 1);
    if ($l == 1)
    {
      $out .= " $j1";
    }
    else if ($l == 2 || $l == 3 || $l == 4)
    {
      $out .= " $j2";
    }
    else
    {
      $out .= " $j3";
    }
    return $out;
  }

  function SC($a)
  {
    $a = round($a, 2);
    $c = floor($a);
    $u = $a - $c;
    $us = self::slownie(round($u * 100, 2), "grosz", "grosze", "groszy");
    $cs = self::slownie($c, "złoty", "złote", "złotych");
    return "$cs, $us";
  }

  public function sendEmail($email, $temat, $tresc, $replay = '', $file = '')
  {
    include_once 'resources/phpmailer/class.phpmailer.php';
    include_once 'resources/phpmailer/class.smtp.php';

    if (isset($email) && isset($temat) && isset($tresc))
    {
      $admin_mail         = 'biuro@project-pro.pl';
      $mail               = new PHPMailer();
      $mail->IsSMTP();
      $mail->SMTPAuth   = true;
      $mail->Host       = 'mail.project-pro.pl';
      $mail->Port       = 465;
      $mail->Username   = 'biuro@project-pro.pl';
      $mail->Password   = 'Legia1916Warszawa';
      $mail->CharSet    = "UTF-8";
      $mail->SMTPSecure = 'ssl';
      $mail->SMTPOptions = [
        'ssl' => [
          'verify_peer' => false,
          'verify_peer_name' => false,
          'allow_self_signed' => true
        ]
      ];
      if ($replay == "")
      {
        $mail->AddReplyTo($admin_mail, 'Project-Pro Pyziak Jacek');
        $mail->SetFrom($admin_mail, 'Project-Pro Pyziak Jacek');
      }
      else
      {
        $mail->AddReplyTo($replay, 'Project-Pro Pyziak Jacek');
        $mail->SetFrom($replay, 'Project-Pro Pyziak Jacek');
      }
      $mail->AddAddress($email, '');
      $mail->Subject = $temat;
      $mail->setLanguage('pl');
      $mail->Body = str_replace('<br>', chr(13) . chr(10), $tresc);
      if (is_array($file))
      {
        foreach ($file as $f)
          $mail->AddAttachment($f);
      }
      else if ($file)
        $mail->AddAttachment($file);
      $mail->IsHTML(true);
      return $mail->Send();
    }
    return false;
  }

  function curl_redir_exec($ch, $proxy = "")
  {
    static $curl_loops = 0;
    static $curl_max_loops = 20;

    if ($curl_loops++ >= $curl_max_loops)
    {
      $curl_loops = 0;
      return FALSE;
    }
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    if ($proxy)
    {
      curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, true);
      curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
      curl_setopt($ch, CURLOPT_TIMEOUT, 15);
      curl_setopt($ch, CURLOPT_PROXY, $proxy);
    }
    $data = curl_exec($ch);
    $debbbb = $data;
    @list($header, $data) = explode("\n\n", $data, 2);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($http_code == 301 || $http_code == 302)
    {
      $matches = array();
      preg_match('/Location:(.*?)\n/', $header, $matches);
      $url = @parse_url(trim(array_pop($matches)));
      if (!$url)
      {
        $curl_loops = 0;
        return $data;
      }
      $last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
      if (!isset($url['query']))
        $url['query'] = '';
      if (!isset($url['scheme']))
        $url['scheme'] = '';
      $new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query'] ? '?' . $url['query'] : '');
      curl_setopt($ch, CURLOPT_URL, $new_url);
      return self::curl_redir_exec($ch);
    }
    else
    {
      $curl_loops = 0;
      return $debbbb;
    }
  }

  public function info($text, $print = false)
  {
    $info = '<p style="font-size: 11px; font-family: Verdana; background: #f6f6f6; border: 1px solid #dddddd; line-height: 30px; padding: 5px 20px;">' . $text . '</p>';

    if ($print)
      echo $info;

    return $info;
  }

  public function my_array_diff($a, $b)
  {
    $map = $out = array();
    if (is_array($a)) foreach ($a as $val) $map[trim($val)] = 1;
    if (is_array($b)) foreach ($b as $val) unset($map[trim($val)]);
    return array_keys($map);
  }

  public function pre($data, $type = '')
  {
    $data = str_replace('Array
(', '', $data);
    $data = str_replace(')', '', $data);

    echo '<pre';
    if ($type == 'error')
      echo ' style="color: #cc0000;" ';
    else if ($type == 'info')
      echo ' style="color: #2c539e;" ';
    else
      echo ' style="color: #8fc400;" ';
    echo '>' . print_r($data, true) . '</pre>';
  }

  public function deleteSessionVar($var)
  {
    unset($_SESSION[$var]);
  }

  public function deleteCache($str = '../temp/')
  {
    if (is_file($str))
    {
      return @unlink($str);
    }
    else if (is_dir($str))
    {
      $scan = glob(rtrim($str, '/') . '/*');
      if (is_array($scan)) foreach ($scan as $index => $path)
      {
        \S::deleteCache($path);
      }
      if ($str != '../temp/' && $str != 'temp/')
        return @rmdir($str);
    }
  }

  public function saveString($val, $tolower = false)
  {
    if ($tolower)
      $val = strtolower($val);
    return trim(strip_tags($val));
  }

  public function deleteCacheAdmin($str = 'temp/')
  {
    if (is_file($str))
    {
      return @unlink($str);
    }
    else if (is_dir($str))
    {
      $scan = glob(rtrim($str, '/') . '/*');

      if (is_array($scan)) foreach ($scan as $index => $path)
        self::deleteCache($path);

      if ($str != 'temp/' && $str != 'admin/temp/')
        return @rmdir($str);
    }
  }

  public function getHash($val)
  {
    $val = base64_encode($val);
    $val = \S::get($val);
    return base64_decode($val);
  }

  public function deleteAction()
  {
    $akcja = "function mycallbackform(v,m,f){
                if( v == true )
                  document.location.href='./?rw=del&amp;id=[param]';
              }";
    $akcja .= "$.prompt('Potwierdz usunięcie',{ callback: mycallbackform, buttons: { tak: true, nie: false }, focus: 1 })";
    $akcja = 'onClick="' . $akcja . '"';

    return  $akcja;
  }

  public function seo($val, $nopl = true)
  {
    $array_rep1 = array('*', '_', ' ', '/', '+', '.', '"', "'", '?', '-', ',', '!', '~', '<', '>', '@', '#', '$', '%', '^', '&', '*' . '(', ')' . '-', '=', '\\', '|', '[', ']', '/', ':');
    $array_rep2 = array('-', '-', '-', '-', '-', '-', '',  '',  '',  '-', '-', '',  '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '',  '-', '-',  '=', '-', '-', '-', '-');

    if ($nopl)
      $val = self::noPl($val);

    $val = str_replace($array_rep1, $array_rep2, $val);

    return strtolower(trim($val));
  }

  public function noPL($val)
  {
    $table = array(
      //WIN
      "\xb9" => "a", "\xa5" => "A", "\xe6" => "c", "\xc6" => "C",
      "\xea" => "e", "\xca" => "E", "\xb3" => "l", "\xa3" => "L",
      "\xf3" => "o", "\xd3" => "O", "\x9c" => "s", "\x8c" => "S",
      "\x9f" => "z", "\xaf" => "Z", "\xbf" => "z", "\xac" => "Z",
      "\xf1" => "n", "\xd1" => "N",
      //UTF
      "\xc4\x85" => "a", "\xc4\x84" => "A", "\xc4\x87" => "c", "\xc4\x86" => "C",
      "\xc4\x99" => "e", "\xc4\x98" => "E", "\xc5\x82" => "l", "\xc5\x81" => "L",
      "\xc3\xb3" => "o", "\xc3\x93" => "O", "\xc5\x9b" => "s", "\xc5\x9a" => "S",
      "\xc5\xbc" => "z", "\xc5\xbb" => "Z", "\xc5\xba" => "z", "\xc5\xb9" => "Z",
      "\xc5\x84" => "n", "\xc5\x83" => "N",
      //ISO
      "\xb1" => "a", "\xa1" => "A", "\xe6" => "c", "\xc6" => "C",
      "\xea" => "e", "\xca" => "E", "\xb3" => "l", "\xa3" => "L",
      "\xf3" => "o", "\xd3" => "O", "\xb6" => "s", "\xa6" => "S",
      "\xbc" => "z", "\xac" => "Z", "\xbf" => "z", "\xaf" => "Z",
      "\xf1" => "n", "\xd1" => "N"
    );

    $array_de    = array('Ü');
    $array_de_pl = array('U');

    $val = str_replace($array_de, $array_de_pl, $val);

    $array_uk    = array('А', 'а', 'Б', 'б', 'В', 'в', 'Г', 'г', 'ґ', 'Д', 'д', 'Е', 'е', 'Є', 'є', 'Ж', 'ж', 'З' . 'з', 'И', 'и', 'І', 'і', 'Ї', 'ї', 'Й', 'й', 'К', 'к', 'Л', 'л', 'М', 'м', 'Н', 'н', 'О', 'о', 'П', 'п', 'Р', 'р', 'С', 'с', 'Т', 'т', 'У', 'у', 'Ф', 'ф', 'Х', 'х', 'Ц' - 'ц', 'Ч', 'ч', 'Ш', 'ш', 'Щ', 'щ', 'Ю', 'ю', 'Я', 'я', 'ь');
    $array_uk_pl = array('А', 'a', 'B', 'b', 'V', 'v', 'Gg', 'gh', 'Gg', 'D', 'd', 'E', 'e', 'Ye', 'yr', 'Zh', 'zh', 'Z', 'z', 'Y', 'y', 'I', 'i', 'Yi', 'yi', 'J', 'j', 'K', 'k', 'L', 'l', 'M', 'm', 'N', 'n', 'O', 'o', 'P', 'p', 'R', 'r', 'S', 's', 'T', 't', 'U', 'u', 'F', 'f', 'Kh', 'kh', 'Ts', 'ts', 'Ch', 'ch', 'Sh', 'sh', 'Shch', 'shch', 'Yu', 'yu', 'Ya', 'ya', '');

    $val = str_replace($array_uk, $array_uk_pl, $val);

    return strtr($val, $table);
  }

  public function getDateDiff($data1, $data2, $rodz = '60')
  {
    $d1_t   = explode(' ', $data1);
    $d1_tt   = explode('-', $d1_t[0]);
    $rok1   = $d1_tt[0];
    $mc1    = $d1_tt[1];
    $d1     = $d1_tt[2];
    $d1_tt   = explode(':', $d1_t[1]);
    $g1     = $d1_tt[0];
    $m1     = $d1_tt[1];
    $s1     = $d1_tt[2];

    $d2_t   = explode(' ', $data2);
    $d2_tt   = explode('-', $d2_t[0]);
    $rok2   = $d2_tt[0];
    $mc2    = $d2_tt[1];
    $d2     = $d2_tt[2];
    $d2_tt   = explode(':', $d2_t[1]);
    $g2     = $d2_tt[0];
    $m2     = $d2_tt[1];
    $s2     = $d2_tt[2];

    $lt   = mktime($g2, $m2, $s2, $mc2, $d2, $rok2);
    $st   = mktime($g1, $m1, $s1, $mc1, $d1, $rok1);

    return round(($lt - $st) / $rodz);
  }

  public function parseRSS($xml, $cat_id)
  {
    $cnt = count($xml->channel->item);
    for ($i = 0; $i < $cnt; $i++)
    {
      $row['link']    = $xml->channel->item[$i]->link;
      $row['date']    = $xml->channel->item[$i]->pubDate;
      $row['title']   = $xml->channel->item[$i]->title;
      $row['cat_id']  = $cat_id;
      $links[] = $row;
    }

    return $links;
  }
  public function synonyms($word)
  {
    global $db, $cache, $config;

    if (!$word)
      return $word;

    $key = 'synonyms:' . $word;

    if (!$synonim = $cache->fetch($key, 'temp_t'))
    {
      $query = $db->prepare('SELECT synonim FROM pro_thesaurus WHERE synonim LIKE "%;' . addslashes($word) . ';%" ORDER BY LENGTH(synonim) DESC LIMIT 1');
      $query->execute();
      if ($query->rowCount())
      {
        while ($row = $query->fetch())
          $synonim = $row['synonim'];
        $synonim = substr($synonim, 1);
        $synonim = substr($synonim, 0, -1);
      }
      else
        $synonim = $word;
      $query->closeCursor();

      if (strpos($synonim, ';') !== false)
        $synonim = '{' . str_replace(';', '|', $synonim) . '}';

      $cache->store($key, $synonim, $config['cxll'], 'temp_t');
    }

    return $synonim;
  }

  public function getHost($page, $www = false)
  {
    $page = str_replace('https://', 'http://', $page);
    preg_match('@^(?:http://)?([^/]+)@i', $page, $matches);
    if (!$www)
      $matches[1] = str_replace("www.", "", $matches[1]);
    return $matches[1];
  }

  public function preparRequest($query)
  {
    if (is_array($query) && !empty($query))
    {
      foreach ($query as $key => $value)
        $query[$key] = urlencode($key) . '=' . urlencode($value);
      return implode('&', $query);
    }
    else
      return false;
  }

  public function getDate()
  {
    return date('Y-m-d H:i:s');
  }

  public function getComboYesNo()
  {
    global $lang;

    $tab[0] = 'nie';
    $tab[1] = 'tak';

    return $tab;
  }

  public function getPagingVar($var, $bs, $ls)
  {
    if ($var == 'a')
    {
      if ($bs == 1)
        return 6;
      else if ($bs == 2)
        return 5;
      else if ($bs == 3)
        return 4;
      else
        return 3;
    }
    else if ($var == 'b')
    {
      if ($bs == $ls)
        return 6;
      else if ($bs == $ls - 1)
        return 5;
      else if ($bs == $ls - 2)
        return 4;
      else
        return 3;
    }
  }

  public static function alert($val)
  {
    \S::set_session('alert', $val);
  }

  public static function get($var)
  {
    if (isset($_POST[$var]))
    {
      if (is_string($_POST[$var]))
        return trim($_POST[$var]);
      else
        return $_POST[$var];
    }
    else
    {
      if (isset($_GET[$var]))
      {
        if (is_string($_GET[$var]))
          return trim($_GET[$var]);
        else
          return $_GET[$var];
      }
    }
  }

  public static function set_session($var, $val)
  {
    $_SESSION[$var] = $val;
  }

  public static function get_session($var)
  {
    return $_SESSION[$var];
  }
}