<?php
class S
{
  static public function strip_attributes_except_style($html) {
    return preg_replace_callback(
      '/<([a-z0-9]+)([^>]*)>/i',
      function ($matches) {
        $tag = $matches[1];
        $attrs = $matches[2];

        // Znajdź tylko atrybut "style"
        preg_match('/\sstyle\s*=\s*("[^"]*"|\'[^\']*\'|[^"\'>\s]+)/i', $attrs, $styleMatch);
        $style = isset($styleMatch[0]) ? ' ' . $styleMatch[0] : '';

        return "<$tag$style>";
      },
      $html
    );
  }

  static public function strip_attributes_except_style_and_clean_font($html) {
    return preg_replace_callback(
      '/<([a-z0-9]+)([^>]*)>/i',
      function ($matches) {
        $tag = $matches[1];
        $attrs = $matches[2];

        // Wyciągnij styl
        preg_match('/\sstyle\s*=\s*("[^"]*"|\'[^\']*\'|[^"\'>\s]+)/i', $attrs, $styleMatch);
        $style = '';

        if (isset($styleMatch[1])) {
          $rawStyle = trim($styleMatch[1], '\'"'); // bez cudzysłowów

          // usuń font-family (również z fallbackami np. Arial, sans-serif)
          $filtered = [];
          foreach (explode(';', $rawStyle) as $rule) {
            if (stripos(trim($rule), 'font-family') !== 0) {
              $filtered[] = trim($rule);
            }
          }

          if (!empty($filtered)) {
            $style = ' style="' . implode('; ', $filtered) . '"';
          }
        }

        return "<$tag$style>";
      },
      $html
    );
  }

  static public function clear_advert_text( $text )
  {
    $text = preg_replace('#<style[^>]*>.*?</style>#is', '', $text);
    $text = preg_replace('#<script[^>]*>.*?</script>#is', '', $text);
    $text = preg_replace('/on\w+="[^"]*"/i', '', $text);
    $text = preg_replace("/on\w+='[^']*'/i", '', $text);
    $text = preg_replace('/(href|src)\s*=\s*["\']\s*javascript:[^"\']*["\']/i', '', $text);
    $text = self::strip_attributes_except_style($text);
    $text = self::strip_attributes_except_style_and_clean_font($text);
    return $text;
  }

  static public function strpos_arr( $haystack, $needle )
  {
    if (!is_array($needle)) $needle = array($needle);
    foreach($needle as $what) {
        if(($pos = strpos($haystack, $what))!==false) return $pos;
    }
    return false;
  }

  static public function generate_webp_image($file, $compression_quality = 85)
  {
    if ( strpos( $file, 'thumb/' ) !== false )
    {
      $file_tmp = explode( '/', $file );

      $width = $file_tmp[1];
      if ( empty( $width ) and $width !== '0' )
        $width = 500;

      $height = $file_tmp[2];
      if ( empty( $height ) and $height !== '0' )
        $height = 500;

      for ( $i = 0; $i <= 2; $i++ )
        unset( $file_tmp[$i] );

      $img_src = implode( '/', $file_tmp );

      $crop_w   = $_GET['c_w'];
      $crop_h   = $_GET['c_h'];

      $img_md5    = md5( $img_src . $height . $width . $crop_h . $crop_w );
      $file  = 'thumbs/' . $img_md5[0] . '/' . $img_md5[1] . '/' . $img_md5[2] . '/' . $img_md5;
    }

    if (!file_exists($file))
      return false;

    $output_file = 'cache/' . $file . '.webp';
    if (file_exists($output_file))
      return $output_file;

    $file_type = mime_content_type( $file );

    if (function_exists('imagewebp'))
    {
      switch ($file_type)
      {
        case 'image/jpeg':
          $image = imagecreatefromjpeg($file);
          break;

        case 'image/png':
          $image = imagecreatefrompng($file);
          imagepalettetotruecolor($image);
          imagealphablending($image, true);
          imagesavealpha($image, true);
          break;

        case 'image/gif':
          $image = imagecreatefromgif($file);
          break;

        default:
          return false;
      }

      $dir = dirname($output_file);
      if (!is_dir($dir))
        mkdir($dir, 0755, true);

      $result = imagewebp($image, $output_file, $compression_quality);
      if (false === $result)
        return false;

      imagedestroy($image);

      return $output_file;
    }
    elseif (class_exists('Imagick'))
    {
      $dir = dirname($output_file);
      if (!is_dir($dir))
        mkdir($dir, 0755, true);

      $image = new \Imagick();
      $image->readImage($file);

      if ($file_type === 'png')
      {
        $image->setImageFormat('webp');
        $image->setImageCompressionQuality($compression_quality);
        $image->setOption('webp:lossless', 'true');
      }

      $image->writeImage($output_file);
      return $output_file;
    }

    return false;
  }

  static public function log( $user_id, $function, $data )
  {
    $file_name = 'logs/' . date( 'Y-m-d' ) . '.txt';
    $file_content = file_get_contents( $file_name );

    $file_content .= PHP_EOL . '-------------------------------------------------------------------------------------------------------------------';
    $file_content .= PHP_EOL . 'DATE: ' . date( 'Y-m-d H:i:s' );
    $file_content .= PHP_EOL . 'USER_ID: ' . $user_id;
    $file_content .= PHP_EOL . 'FUNCTION: ' . $function;
    $file_content .= PHP_EOL . 'DATA:';
    foreach ( $data[0] as $key => $val )
      $file_content .= PHP_EOL . "\t" . $key . ": " . print_r( $val, true );

    file_put_contents( $file_name, $file_content );
  }

  public static function alert_prompt( $alert )
  {
    $tpl = new \Tpl;
    $tpl -> alert = $alert;
    return $tpl -> render( 'site/alert-prompt' );
  }

  public static function set_alert_prompt( $title = 'Informacja', $message, $autoclose = '60' )
  {
    \S::set_session( 'alert-prompt', [
            'title' => $title,
            'message' => $message,
            'autoclose' => $autoclose
          ] );
    return false;
  }

  public static function log_db_error( $db_tmp, $debug )
  {
    global $settings;

    if ( $settings['mysql_debug'] )
    {
      $out .= date( 'Y-m-d H:i:s' ) . PHP_EOL;
      $out .= $db_tmp -> error()[2] . PHP_EOL;
      $out .= $db_tmp -> last() . PHP_EOL;
      $out .= $debug[0]['file'] . ' | ' . $debug[0]['line'] . PHP_EOL;
      $out .= '--------------------------------------------------------------------------------------------' . PHP_EOL;

      if ( !is_dir( 'logs' ) )
        mkdir( 'logs', 0755 , true );

      $content = file_get_contents( 'logs/' . date( 'Y-m-d' ) . '.txt' );
      $content = $out . $content;
      file_put_contents( 'logs/' . date( 'Y-m-d' ) . '.txt' , $content );
      die( 'Blad bazy danych.' );
    }
  }

  public static function lang( $text )
  {
    global $lang;
    return $lang[$text] ? $lang[$text] : 'LANG-' . $text;
  }

  public static function cache_read( $path )
  {
    $f      = fopen( $path, 'r' );
    $buffer = '';
    while ( !feof( $f ) )
    {
      $buffer .= fread( $f, 2048 );
    }
    fclose( $f );
    return $buffer;
  }

  public static function cache_write( $cache_url, $cache_file, $html )
  {
    $dir = md5( $cache_url );
    $dir = 'cache/' . $dir[0] . '/' . $dir[1] . '/';

    if ( !is_dir( $dir ) )
      mkdir( $dir , 0755 , true );

    $f      = fopen( $cache_file, 'w' );
    fwrite( $f, $html, strlen( $html ) );
    fclose( $f );
    return true;
  }

  public static function cache_file_url( $cache_url )
  {
    $cache = md5( $cache_url );
    return 'cache/' . $cache[1] . '/' . $cache[2] . '/' . $cache;
  }

  public static function date_diff( $data1, $data2, $rodz = '60' )
  {
    $data1 = date( 'Y-m-d H:i:s', strtotime( $data1 ) );
    $data2 = date( 'Y-m-d H:i:s', strtotime( $data2 ) );

		$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 static function is_token_valid( $token )
  {
    if ( !empty( $_SESSION['tokens'][$token] ) )
    {
      unset( $_SESSION['tokens'][$token] );
      return true;
    }
    return false;
  }

  public static function get_token()
  {
    $token = sha1( mt_rand() );
    if( !isset( $_SESSION['tokens'] ) )
      $_SESSION['tokens'] = [ $token => 1 ];
    else
      $_SESSION['tokens'][$token] = 1;
    return $token;
  }

  public static function get_domain( $url )
  {
    $parseUrl = parse_url( trim( $url ) );
    return trim( $parseUrl[host] ? str_replace( 'www.', '', $parseUrl[host] ) : str_replace( 'www.', '', array_shift( explode( '/', $parseUrl[path], 2 ) ) ) );
  }

  public static function get_domain_url( $url )
  {
    global $settings;

    $settings['link_version'] ? $www = 'www.' : $www = '';
    $settings['ssl'] == true ? $domain_prefix = 'https' : $domain_prefix = 'http';
    return $domain_prefix . '://' . $www . \S::get_domain( $url );
  }

  public static function max_db_value( $table, $column )
  {
    global $mdb;
    $results = $mdb -> query( 'SELECT MAX(' . $column . ') FROM ' . $table ) -> fetchAll();
    return $results[0][0];
  }

  public static function shuffle_assoc( $list )
  {
    if ( !is_array( $list ) )
      return $list;

    $keys         = array_keys( $list );
    shuffle( $keys );
    $random       = array();
    foreach ( $keys as $key )
      $random[$key] = $list[$key];
    return $random;
  }

  public static function escape( $value )
  {
    $return = '';
    for ( $i = 0; $i < strlen( $value ); ++$i )
    {
      $char   = $value[$i];
      $ord    = ord( $char );
      if ( $char !== "'" && $char !== "\"" && $char !== '\\' && $ord >= 32 && $ord <= 126 )
        $return .= $char;
      else
        $return .= '\\x' . dechex( $ord );
    }
    return $return;
  }

  public static function is_bot()
  {
    $bots  = [ "Slurp", "Scooter", "URL_Spider_SQL", "Googlebot", "Firefly", "WebBug", "WebFindBot", "crawler", "appie", "msnbot", "InfoSeek", "FAST", "Spade", "NationalDirectory" ];
    $agent = strtolower( $_SERVER['HTTP_USER_AGENT'] );
    foreach ( $bots as $bot )
      if ( stripos( $agent, $bot ) !== false )
        return true;
    return false;
  }

  public static function months()
  {
    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ń' );
  }

  public static function months_short()
  {
    return [ 1 => 'sty', 2 => 'lut', 3 => 'mar', 4 => 'kwi', 5 => 'maj', 6 => 'cze', 7 => 'lip', 8 => 'sie', 9 => 'wrz', 10 => 'paź', 11 => 'lis', 12 => 'gru' ];
  }

  public static function chmod_r( $path, $chmod = 0755 )
  {
    $dir = new DirectoryIterator( $path );
    foreach ( $dir as $item )
    {
      chmod( $item -> getPathname(), $chmod );
      if ( $item -> isDir() && !$item -> isDot() )
        self::chmod_r( $item -> getPathname() );
    }
  }

  public static function rrmdir( $dir )
  {
    if ( is_dir( $dir ) )
    {
      $files = scandir( $dir );
      foreach ( $files as $file )
        if ( $file != "." && $file != ".." )
          \S::rrmdir( "$dir/$file" );
      rmdir( $dir );
    }
    else if ( file_exists( $dir ) )
      unlink( $dir );
  }

  public static function rcopy( $src, $dst )
  {
    if ( is_dir( $src ) )
    {
      mkdir( $dst, 0755 );
      $files = scandir( $src );
      foreach ( $files as $file )
        if ( $file != "." && $file != ".." )
          \S::rcopy( "$src/$file", "$dst/$file" );
    }
    else if ( file_exists( $src ) )
      copy( $src, $dst );

    \S::rrmdir( $src );
  }

  public static function is_mobile()
  {
    $detect = new \Mobile_Detect;
    return $detect -> isMobile();
  }

  public static function get_new_version()
  {
    global $settings;

    if ( $version = \S::get_session( 'new-version' ) )
      return $version;

    $versions = file_get_contents( 'http://www.cmspro.project-dc.pl/updates/versions.php?key=' . $settings['update_key'] );
    $versions = explode( PHP_EOL, $versions );
    $version  = (float)max( $versions );

    \S::set_session( 'new-version', $version );

    return $version;
  }

  public static function get_version()
  {
    return (float) @file_get_contents( '../libraries/version.ini' );
  }

  public static 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 static function json_to_array( $json )
  {
    $values_tmp = json_decode( $json, true );

    if ( is_array( $values_tmp ) )
      foreach ( $values_tmp as $val )
      {
        if ( isset( $values[$val['name']] ) )
        {
          if ( is_array( $values[$val['name']] ) )
            $values[$val['name']][] = $val['value'];
          else
            $values[$val['name']]   = array( $values[$val['name']], $val['value'] );
        }
        else
          $values[$val['name']] = $val['value'];
      }
    return $values;
  }

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

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

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

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

  public static function set_message( $text )
  {
    self::set_session( 'message', $text );
  }

  public static function alert( $text, $class = 'alert-success' )
  {
    self::set_session( 'alert', $text );
    self::set_session( 'alert-class', $class );
  }

  public static function htacces( $dir = '../' )
  {
    global $mdb;

    $settings           = \front\factory\Settings::settings_details();
    $default_domain     = \admin\factory\Languages::default_domain();
    $available_domains  = \admin\factory\Languages::available_domains();

    $settings['link_version'] ? $www = 'www.' : $www = '';

    $settings['ssl'] == true ? $domain_prefix = 'https' : $domain_prefix = 'http';

    $default_domain ? $url = $default_domain : $url = preg_replace( '#^(http(s)?://)?w{3}\.#', '$1', $_SERVER['SERVER_NAME'] );

    $robots = 'User-agent: *' . PHP_EOL;
    $robots .= 'Allow: /' . PHP_EOL;

    unlink( '../sitemap.xml' );
    if ( is_array( $available_domains ) and !empty( $available_domains ) )
    {
      foreach ( $available_domains as $domain )
      {
        $site_map[ $domain['domain'] ] = '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;
        $site_map[ $domain['domain'] ] .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . PHP_EOL;
        $site_map[ $domain['domain'] ] .= '<url>' . PHP_EOL;
        $site_map[ $domain['domain'] ] .= '<loc>' . $domain_prefix . '://' . $www . $domain['domain'] . '</loc>' . PHP_EOL;
        $site_map[ $domain['domain'] ] .= '<lastmod>' . date( 'Y-m-d' ) . '</lastmod>' . PHP_EOL;
        $site_map[ $domain['domain'] ] .= '<changefreq>daily</changefreq>' . PHP_EOL;
        $site_map[ $domain['domain'] ] .= '<priority>1</priority>' . PHP_EOL;
        $site_map[ $domain['domain'] ] .= '</url>' . PHP_EOL;
      }
    }
    else
    {
      $site_map[ $url ] = '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;
      $site_map[ $url ] .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . PHP_EOL;
      $site_map[ $url ] .= '<url>' . PHP_EOL;
      $site_map[ $url ] .= '<loc>' . $domain_prefix . '://' . $www . $url . '</loc>' . PHP_EOL;
      $site_map[ $url ] .= '<lastmod>' . date( 'Y-m-d' ) . '</lastmod>' . PHP_EOL;
      $site_map[ $url ] .= '<changefreq>daily</changefreq>' . PHP_EOL;
      $site_map[ $url ] .= '<priority>1</priority>' . PHP_EOL;
      $site_map[ $url ] .= '</url>' . PHP_EOL;
    }

    $htaccess_data = file_get_contents( $dir . 'libraries/htaccess.conf' );

    /* cache */
    if ( $settings['htaccess_cache'] )
    {
      $htaccess_data = str_replace( '{HTACCESS_CACHE}',
              '<IfModule mod_deflate.c>' . PHP_EOL
              . 'AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml application/xhtml+xml text/css text/javascript application/javascript application/x-javascript' . PHP_EOL
              . '</IfModule>' . PHP_EOL
              . '<IfModule mod_expires.c>' . PHP_EOL
              . 'ExpiresActive on' . PHP_EOL
              . 'ExpiresDefault                                      "access plus 1 year"' . PHP_EOL
              . 'ExpiresByType text/css                              "access plus 1 year"' . PHP_EOL
              . 'ExpiresByType application/json                      "access plus 0 seconds"' . PHP_EOL
              . 'ExpiresByType application/xml                       "access plus 0 seconds"' . PHP_EOL
              . 'ExpiresByType text/xml                              "access plus 0 seconds"' . PHP_EOL
              . 'ExpiresByType image/x-icon                          "access plus 1 week"' . PHP_EOL
              . 'ExpiresByType text/x-component                      "access plus 1 year"' . PHP_EOL
              . 'ExpiresByType text/html                             "access plus 0 seconds"' . PHP_EOL
              . 'ExpiresByType application/javascript                "access plus 1 year"' . PHP_EOL
              . 'ExpiresByType application/x-web-app-manifest+json   "access plus 0 seconds"' . PHP_EOL
              . 'ExpiresByType text/cache-manifest                   "access plus 0 seconds"' . PHP_EOL
              . 'ExpiresByType audio/ogg                             "access plus 1 year"' . PHP_EOL
              . 'ExpiresByType image/gif                             "access plus 1 year"' . PHP_EOL
              . 'ExpiresByType image/jpeg                            "access plus 1 year"' . PHP_EOL
              . 'ExpiresByType image/webp                            "access plus 1 year"' . PHP_EOL
              . 'ExpiresByType image/png                             "access plus 1 year"' . PHP_EOL
              . 'ExpiresByType video/mp4                             "access plus 1 year"' . PHP_EOL
              . 'ExpiresByType video/ogg                             "access plus 1 year"' . PHP_EOL
              . 'ExpiresByType video/webm                            "access plus 1 year"' . PHP_EOL
              . 'ExpiresByType application/atom+xml                  "access plus 1 hour"' . PHP_EOL
              . 'ExpiresByType application/rss+xml                   "access plus 1 hour"' . PHP_EOL
              . 'ExpiresByType application/font-woff                 "access plus 1 year"' . PHP_EOL
              . 'ExpiresByType application/vnd.ms-fontobject         "access plus 1 year"' . PHP_EOL
              . 'ExpiresByType application/x-font-ttf                "access plus 1 year"' . PHP_EOL
              . 'ExpiresByType font/opentype                         "access plus 1 year"' . PHP_EOL
              . 'ExpiresByType image/svg+xml                         "access plus 1 year"' . PHP_EOL
              . '</IfModule>'
              , $htaccess_data );
    }
    else
    {
      $htaccess_data = str_replace( '{HTACCESS_CACHE}',
              '<IfModule mod_headers.c>' . PHP_EOL
              . 'Header set Cache-Control "no-cache, no-store, must-revalidate"' . PHP_EOL
              . 'Header set Pragma "no-cache"' . PHP_EOL
              . 'Header set Expires 0' . PHP_EOL
              . '</IfModule>',
            $htaccess_data );
    }

    /* języki w domenie głównej */
    $results = $mdb -> select( 'pp_langs', [ 'id' ], [ 'AND' => [ 'status' => 1, 'domain' => null ], 'ORDER' => [ 'o' => 'ASC' ] ] );
    if ( is_array( $results ) ) foreach ( $results as $row )
    {
      $htaccess_data .= PHP_EOL . 'RewriteCond %{HTTP_HOST} ^(www\.)?' . $url . '$';
      $htaccess_data .= PHP_EOL . 'RewriteRule ^' . $row['id'] . '/$ index.php?a=change_language&id=' . $row['id'] . ' [L]';
    }

    $htaccess_data .= PHP_EOL;

    $results = $mdb -> select( 'pp_langs', [ 'id', 'start', 'domain', 'main_domain' ], [ 'status' => 1, 'ORDER' => [ 'o' => 'ASC' ] ] );
    if ( is_array( $results ) ) foreach ( $results as $row )
    {
      $row['domain'] ? $url_tmp = $row['domain'] : $url_tmp = $url;

      !$row['start'] ? $language_link = $row['id'] . '/' : $language_link = '';

      $results2 = $mdb -> select( 'pp_pages_langs',
              [ '[><]pp_pages' => [ 'page_id' => 'id' ] ],
              [ 'seo_link', 'title', 'page_id', 'noindex', 'start', 'page_type' ],
              [ 'AND' => [ 'status' => 1, 'lang_id' => $row['id'], 'block_direct_access' => 0 ], 'ORDER' => [ 'start' => 'DESC', 'o' => 'ASC' ] ] );
      if ( is_array( $results2 ) ) foreach ( $results2 as $row2 )
      {
        if ( $row2['title'] )
        {
          /* sitemap.xml */
          if ( $row2['page_type'] != 3 and !$row2['noindex'] )
          {
            $site_map[ $url_tmp ] .= '<url>' . PHP_EOL;

            if ( $row2['seo_link'] )
            {
              if ( $settings['links_structure'] )
                $seo = \admin\factory\Pages::google_url_preview( $row2['page_id'], $row2['title'], $row[id], 0, 0, $row2['seo_link'], $language_link );
              else
                $seo = $language_link . \S::seo( $row2['seo_link'] );

              $site_map[ $url_tmp ] .= '<loc>' . $domain_prefix . '://' . $www . $url_tmp . '/' . $seo . '</loc>' . PHP_EOL;
            }
            else
            {
              if ( $settings['links_structure'] )
                $seo = \admin\factory\Pages::google_url_preview( $row2['page_id'], $row2['title'], $row['id'], 0, 0, $row2['seo_link'], $language_link );
              else
                $seo = $language_link . 's-' . $row2['page_id'] . '-' . \S::seo( $row2['title'] );

              $site_map[ $url_tmp ] .= '<loc>' . $domain_prefix . '://' . $www . $url_tmp . '/' . $seo . '</loc>' . PHP_EOL;
            }

            $site_map[ $url_tmp ] .= '<lastmod>' . date( 'Y-m-d' ) . '</lastmod>' . PHP_EOL;
            $site_map[ $url_tmp ] .= '<changefreq>daily</changefreq>' . PHP_EOL;

            $row['start'] ? $priority = 1 : $priority = 0.8;

            $site_map[ $url_tmp ] .= '<priority>' . $priority . '</priority>' . PHP_EOL;
            $site_map[ $url_tmp ] .= '</url>' . PHP_EOL;
          }

          /* robotx.txt */
          if ( $row2['noindex'] and $row2['page_type'] != 3 )
          {
            $robots .= 'User-agent: GoogleBot' . PHP_EOL;

            if ( $row2['seo_link'] )
            {
              if ( $settings['links_structure'] )
                $seo = \admin\factory\Pages::google_url_preview( $row2['page_id'], $row2['title'], $row[id], 0, 0, $row2['seo_link'], $language_link );
              else
                $seo = $language_link . \S::seo( $row2['seo_link'] );

              $robots .= 'Disallow: /' . $seo . '$' . PHP_EOL;
              $robots .= 'Disallow: /' . $seo . '-s-*' . PHP_EOL;
            }
            else
            {
              if ( $settings['links_structure'] )
                $seo = \admin\factory\Pages::google_url_preview( $row2['page_id'], $row2['title'], $row['id'], 0, 0, $row2['seo_link'], $language_link );
              else
                $seo = $language_link . 's-' . $row2['page_id'] . '-' . \S::seo( $row2['title'] );

              $robots .= 'Disallow: /' . $seo . '$' . PHP_EOL;
              $robots .= 'Disallow: /' . $seo . '-s-*$' . PHP_EOL;
            }
          }

          /* htaccess */
          if ( $row2['page_type'] != 3 )
          {
            if ( $row['start'] and $row2['start'] )
            {
              if ( $row2['seo_link'] )
              {
                $htaccess_data .= PHP_EOL . 'RewriteCond %{HTTP_HOST} ^(www\.)?' . $url_tmp . '$';
                $htaccess_data .= PHP_EOL . 'RewriteCond %{REQUEST_URI} ^/' . \S::seo( $row2['seo_link'] ) . '$';
                $htaccess_data .= PHP_EOL . 'RewriteRule ^(.*)$ ' . $domain_prefix . '://' . $www . $url_tmp . '/' . $language_link . ' [R=301,L]';

                $htaccess_data .= PHP_EOL . 'RewriteCond %{HTTP_HOST} ^(www\.)?' . $url_tmp . '$';
                $htaccess_data .= PHP_EOL . 'RewriteCond %{REQUEST_URI} ^/' . \S::seo( $row2['seo_link'] ) . '-s-1$';
                $htaccess_data .= PHP_EOL . 'RewriteRule ^(.*)$ ' . $domain_prefix . '://' . $www . $url_tmp . '/' . $language_link . ' [R=301,L]';
              }
              else
              {
                $htaccess_data .= PHP_EOL . 'RewriteCond %{HTTP_HOST} ^(www\.)?' . $url_tmp . '$';
                $htaccess_data .= PHP_EOL . 'RewriteCond %{REQUEST_URI} ^/s-' . $row2['page_id'] . '-' . \S::seo( $row2['title'] ) . '$';
                $htaccess_data .= PHP_EOL . 'RewriteRule ^(.*)$ ' . $domain_prefix . '://' . $www . $url_tmp . '/' . $language_link . ' [R=301,L]';

                $htaccess_data .= PHP_EOL . 'RewriteCond %{HTTP_HOST} ^(www\.)?' . $url_tmp . '$';
                $htaccess_data .= PHP_EOL . 'RewriteCond %{REQUEST_URI} ^/s-' . $row2['page_id'] . '-' . \S::seo( $row2['title'] ) . '-s-1$';
                $htaccess_data .= PHP_EOL . 'RewriteRule ^(.*)$ ' . $domain_prefix . '://' . $www . $url_tmp . '/' . $language_link . ' [R=301,L]';
              }

              $htaccess_data .= PHP_EOL . 'RewriteCond %{HTTP_HOST} ^(www\.)?' . $url_tmp . '$';
              $htaccess_data .= PHP_EOL . 'RewriteCond %{REQUEST_URI}  "^/$"';
              $htaccess_data .= PHP_EOL . 'RewriteRule ^$ index.php?a=page&id=' . $row2['page_id'] . '&lang=' . $row['id'] . ' [L]';

              $htaccess_data .= PHP_EOL;
            }

            if ( $row2['seo_link'] )
            {
              if ( $settings['links_structure'] )
                $seo = \admin\factory\Pages::google_url_preview( $row2['page_id'], $row2['title'], $row[id], 0, 0, $row2['seo_link'], $language_link );
              else
                $seo = $language_link . \S::seo( $row2['seo_link'] );

              $htaccess_data .= PHP_EOL . 'RewriteCond %{HTTP_HOST} ^(www\.)?' . $url_tmp . '$';
              $htaccess_data .= PHP_EOL . 'RewriteCond %{QUERY_STRING} ^(.*)(?:^|&)(utm_source|gclid)=[^&]+(&.*)?';
              $htaccess_data .= PHP_EOL . 'RewriteCond %{REQUEST_METHOD} !=POST';
              $htaccess_data .= PHP_EOL . 'RewriteRule ^' . $seo . '$ index.php?a=page&id=' . $row2['page_id'] . '&lang=' . $row['id'] . '&%{QUERY_STRING} [L]';

              $htaccess_data .= PHP_EOL . 'RewriteCond %{HTTP_HOST} ^(www\.)?' . $url_tmp . '$';
              $htaccess_data .= PHP_EOL . 'RewriteRule ^' . $seo . '-s-1$ ' . $seo . ' [R=301,L]';

              $htaccess_data .= PHP_EOL . 'RewriteCond %{HTTP_HOST} ^(www\.)?' . $url_tmp . '$';
              $htaccess_data .= PHP_EOL . 'RewriteCond %{QUERY_STRING} ^(.*)(?:^|&)(utm_source|gclid)=[^&]+(&.*)?';
              $htaccess_data .= PHP_EOL . 'RewriteCond %{REQUEST_METHOD} !=POST';
              $htaccess_data .= PHP_EOL . 'RewriteRule ^' . $seo . '-s-([0-9]+)$ index.php?a=page&id=' . $row2['page_id'] . '&lang=' . $row['id'] . '&bs=$1&%{QUERY_STRING} [L]';

              $htaccess_data .= PHP_EOL . 'RewriteCond %{HTTP_HOST} ^(www\.)?' . $url_tmp . '$';
              $htaccess_data .= PHP_EOL . 'RewriteCond %{QUERY_STRING} !=""';
              $htaccess_data .= PHP_EOL . 'RewriteCond %{REQUEST_METHOD} !=POST';
              $htaccess_data .= PHP_EOL . 'RewriteRule ' . $seo . ' %{REQUEST_URI}? [R=301,L]';

              $htaccess_data .= PHP_EOL . 'RewriteCond %{HTTP_HOST} ^(www\.)?' . $url_tmp . '$';
              $htaccess_data .= PHP_EOL . 'RewriteRule ^' . $seo . '$ index.php?a=page&id=' . $row2['page_id'] . '&lang=' . $row['id'] . ' [L]';

              $htaccess_data .= PHP_EOL . 'RewriteCond %{HTTP_HOST} ^(www\.)?' . $url_tmp . '$';
              $htaccess_data .= PHP_EOL . 'RewriteRule ^' . $seo . '-s-([0-9]+)$ index.php?a=page&id=' . $row2['page_id'] . '&lang=' . $row['id'] . '&bs=$1 [L]';
            }
            else
            {
              if ( $settings['links_structure'] )
                $seo = \admin\factory\Pages::google_url_preview( $row2['page_id'], $row2['title'], $row['id'], 0, 0, $row2['seo_link'], $language_link );
              else
                $seo = $language_link . 's-' . $row2['page_id'] . '-' . \S::seo( $row2['title'] );

              $htaccess_data .= PHP_EOL . 'RewriteCond %{HTTP_HOST} ^(www\.)?' . $url_tmp . '$';
              $htaccess_data .= PHP_EOL . 'RewriteCond %{QUERY_STRING} ^(.*)(?:^|&)(utm_source|gclid)=[^&]+(&.*)?';
              $htaccess_data .= PHP_EOL . 'RewriteCond %{REQUEST_METHOD} !=POST';
              $htaccess_data .= PHP_EOL . 'RewriteRule ^' . $seo . '$ index.php?a=page&id=' . $row2['page_id'] . '&lang=' . $row['id'] . '&%{QUERY_STRING} [L]';

              $htaccess_data .= PHP_EOL . 'RewriteCond %{HTTP_HOST} ^(www\.)?' . $url_tmp . '$';
              $htaccess_data .= PHP_EOL . 'RewriteRule ^' . $seo . '-s-1$ ' . $seo . ' [R=301,L]';

              $htaccess_data .= PHP_EOL . 'RewriteCond %{HTTP_HOST} ^(www\.)?' . $url_tmp . '$';
              $htaccess_data .= PHP_EOL . 'RewriteCond %{QUERY_STRING} ^(.*)(?:^|&)(utm_source|gclid)=[^&]+(&.*)?';
              $htaccess_data .= PHP_EOL . 'RewriteCond %{REQUEST_METHOD} !=POST';
              $htaccess_data .= PHP_EOL . 'RewriteRule ^' . $seo . '-s-([0-9]+)$ index.php?a=page&id=' . $row2['page_id'] . '&lang=' . $row['id'] . '&bs=$1&%{QUERY_STRING} [L]';

              $htaccess_data .= PHP_EOL . 'RewriteCond %{HTTP_HOST} ^(www\.)?' . $url_tmp . '$';
              $htaccess_data .= PHP_EOL . 'RewriteCond %{QUERY_STRING} !=""';
              $htaccess_data .= PHP_EOL . 'RewriteCond %{REQUEST_METHOD} !=POST';
              $htaccess_data .= PHP_EOL . 'RewriteRule ' . $seo . ' %{REQUEST_URI}? [R=301,L]';

              $htaccess_data .= PHP_EOL . 'RewriteCond %{HTTP_HOST} ^(www\.)?' . $url_tmp . '$';
              $htaccess_data .= PHP_EOL . 'RewriteRule ^' . $seo . '$ index.php?a=page&id=' . $row2['page_id'] . '&lang=' . $row['id'] . ' [L]';

              $htaccess_data .= PHP_EOL . 'RewriteCond %{HTTP_HOST} ^(www\.)?' . $url_tmp . '$';
              $htaccess_data .= PHP_EOL . 'RewriteRule ^' . $seo . '-s-([0-9]+)$ index.php?a=page&id=' . $row2['page_id'] . '&lang=' . $row['id'] . '&bs=$1 [L]';
            }
            $htaccess_data .= PHP_EOL;
          }
        }
      }

      $results2 = $mdb -> select( 'pp_articles_langs',
              [ '[><]pp_articles' => [ 'article_id' => 'id' ] ],
              [ 'seo_link', 'title', 'article_id', 'noindex', 'copy_from', 'block_direct_access' ],
              [ 'AND' => [ 'status' => 1, 'lang_id' => $row['id'] ] ] );
      if ( is_array( $results2 ) ) foreach ( $results2 as $row2 )
      {
        if ( $row2['copy_from'] != null )
        {
          $results_tmp = $mdb -> get( 'pp_articles_langs',
                            [
                              'seo_link',
                              'title'
                            ],
                            [
                              'AND' => [
                                'article_id' => $row2['article_id'],
                                'lang_id'    => $row2['copy_from']
                            ] ] );
          $row2['seo_link'] = $results_tmp['seo_link'];
          $row2['title']    = $results_tmp['title'];
        }

        /* sitemap */
        if ( !$row2['block_direct_access'] and $row2['title'] )
        {
          $site_map[ $url_tmp ] .= '<url>' . PHP_EOL;
          if ( $row2['seo_link'] )
            $site_map[ $url_tmp ] .= '<loc>' . $domain_prefix . '://' . $www . $url_tmp . '/' . $language_link . \S::seo( $row2['seo_link'] ) . '</loc>' . PHP_EOL;
          else
            $site_map[ $url_tmp ] .= '<loc>' . $domain_prefix . '://' . $www . $url_tmp . '/' . $language_link . 'a-' . $row2['article_id'] . '-' . self::seo( $row2['title'] ) . '</loc>' . PHP_EOL;
          $site_map[ $url_tmp ] .= '<lastmod>' . date( 'Y-m-d' ) . '</lastmod>' . PHP_EOL;
          $site_map[ $url_tmp ] .= '<changefreq>daily</changefreq>' . PHP_EOL;
          $site_map[ $url_tmp ] .= '<priority>0.6</priority>' . PHP_EOL;
          $site_map[ $url_tmp ] .= '</url>' . PHP_EOL;
        }

        /* robots.txt */
        if ( $row2['noindex'] )
        {
          $robots .= 'User-agent: GoogleBot' . PHP_EOL;
          if ( $row2['seo_link'] )
            $robots .= 'Disallow: /' . $row2['seo_link'] . '$' . PHP_EOL;
          else
            $robots .= 'Disallow: /a-' . $row2['article_id'] . '-' . self::seo( $row2['title'] ) . '$' . PHP_EOL;
        }

        if ( !$row2['block_direct_access'] )
        {
          if ( $row2['seo_link'] )
          {
            $htaccess_data .= PHP_EOL . 'RewriteCond %{HTTP_HOST} ^(www\.)?' . $url_tmp . '$';
            $htaccess_data .= PHP_EOL . 'RewriteCond %{QUERY_STRING} ^(.*)(?:^|&)(utm_source|gclid)=[^&]+(&.*)?';
            $htaccess_data .= PHP_EOL . 'RewriteCond %{REQUEST_METHOD} !=POST';
            $htaccess_data .= PHP_EOL . 'RewriteRule ^' . $language_link . \S::seo( $row2['seo_link'] ) . '$ index.php?article=' . $row2['article_id'] . '&lang=' . $row['id'] . '&%{QUERY_STRING} [L]';

            $htaccess_data .= PHP_EOL . 'RewriteCond %{HTTP_HOST} ^(www\.)?' . $url_tmp . '$';
            $htaccess_data .= PHP_EOL . 'RewriteCond %{QUERY_STRING} !=""';
            $htaccess_data .= PHP_EOL . 'RewriteCond %{REQUEST_METHOD} !=POST';
            $htaccess_data .= PHP_EOL . 'RewriteRule ^' . $language_link . \S::seo( $row2['seo_link'] ) . ' %{REQUEST_URI}? [R=301,L]';

            $htaccess_data .= PHP_EOL . 'RewriteCond %{HTTP_HOST} ^(www\.)?' . $url_tmp . '$';
            $htaccess_data .= PHP_EOL . 'RewriteRule ^' . $language_link . \S::seo( $row2['seo_link'] ) . '$ index.php?article=' . $row2['article_id'] . '&lang=' . $row['id'] . ' [L]';
          }
          else if ( $row2['title'] != null )
          {
            $htaccess_data .= PHP_EOL . 'RewriteCond %{HTTP_HOST} ^(www\.)?' . $url_tmp . '$';
            $htaccess_data .= PHP_EOL . 'RewriteCond %{QUERY_STRING} ^(.*)(?:^|&)(utm_source|gclid)=[^&]+(&.*)?';
            $htaccess_data .= PHP_EOL . 'RewriteCond %{REQUEST_METHOD} !=POST';
            $htaccess_data .= PHP_EOL . 'RewriteRule ^' . $language_link . 'a-' . $row2['article_id'] . '-' . \S::seo( $row2['title'] ) . '$ index.php?article=' . $row2['article_id'] . '&lang=' . $row['id'] . '&%{QUERY_STRING} [L]';

            $htaccess_data .= PHP_EOL . 'RewriteCond %{HTTP_HOST} ^(www\.)?' . $url_tmp . '$';
            $htaccess_data .= PHP_EOL . 'RewriteCond %{QUERY_STRING} !=""';
            $htaccess_data .= PHP_EOL . 'RewriteCond %{REQUEST_METHOD} !=POST';
            $htaccess_data .= PHP_EOL . 'RewriteRule ^' . $language_link . 'a-' . $row2['article_id'] . '-' . \S::seo( $row2['title'] ) . ' %{REQUEST_URI}? [R=301,L]';

            $htaccess_data .= PHP_EOL . 'RewriteCond %{HTTP_HOST} ^(www\.)?' . $url_tmp . '$';
            $htaccess_data .= PHP_EOL . 'RewriteRule ^' . $language_link . 'a-' . $row2['article_id'] . '-' . \S::seo( $row2['title'] ) . '$ index.php?article=' . $row2['article_id'] . '&lang=' . $row['id'] . ' [L]';
          }
          $htaccess_data .= PHP_EOL;
        }
      }
    }

    $results = $mdb -> query( 'SELECT '
                                . 'name, tag_id '
                              . 'FROM '
                                . 'pp_tags AS pt '
                              . 'INNER JOIN '
                                . 'pp_articles_tags AS pat ON pat.tag_id = pt.id '
                              . 'GROUP BY '
                                . 'tag_id' ) -> fetchAll();
    if ( is_array( $results ) and ! empty( $results ) ) foreach ( $results as $row )
    {
      $htaccess_data .= PHP_EOL . 'RewriteCond %{QUERY_STRING} !=""';
      $htaccess_data .= PHP_EOL . 'RewriteCond %{REQUEST_METHOD} !=POST';
      $htaccess_data .= PHP_EOL . 'RewriteRule tag,' . \S::seo( $row['name'] ) . ' %{REQUEST_URI}? [R=301,L]';
      $htaccess_data .= PHP_EOL . 'RewriteRule ^tag,' . \S::seo( $row['name'] ) . '$ index.php?tag=' . $row['tag_id'] . ' [L]';
    }

    $results = $mdb -> get( 'pp_settings', 'value', [ 'param' => 'htaccess' ] );
    if ( $results )
      $htaccess_data .= PHP_EOL . $results;

    if ( file_exists( '../libraries/htaccess.ini' ) )
      $htaccess_data .= PHP_EOL . file_get_contents( '../libraries/htaccess.ini' );

    $results = $mdb -> get( 'pp_settings', 'value', [ 'param' => 'robots' ] );
    if ( $results )
      $robots  .= PHP_EOL . $results;

    if ( is_array( $available_domains ) and !empty( $available_domains ) )
    {
      foreach ( $available_domains as $domain )
        $site_map[ $domain['domain'] ]  .= '</urlset>';
    }
    else
      $site_map[ $url ] .= '</urlset>';

    if ( $settings['ssl'] )
    {
      if ( $settings['link_version'] )
      {
        $htaccess_data = str_replace(
                '{REDIRECT}',
                'RewriteCond %{HTTP_HOST} !^www\.' . PHP_EOL
                . 'RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=permanent]' . PHP_EOL
                . 'RewriteCond %{SERVER_PORT} !=443' . PHP_EOL
                . 'RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=permanent]',
                $htaccess_data
        );
      }
      else
      {
        $htaccess_data = str_replace(
                '{REDIRECT}',
                'RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]' . PHP_EOL
                . 'RewriteRule ^(.*)$ https://%1/$1 [R=301,L]' . PHP_EOL
                . 'RewriteCond %{SERVER_PORT} !=443' . PHP_EOL
                . 'RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=permanent]',
                $htaccess_data
        );
      }
    }
    else
    {
      if ( $settings['link_version'] )
      {
        $htaccess_data = str_replace(
                '{REDIRECT}',
                'RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]' . PHP_EOL
                . 'RewriteRule ^(.*)$ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=permanent]' . PHP_EOL
                . 'RewriteCond %{SERVER_PORT} =443' . PHP_EOL
                . 'RewriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=permanent]',
                $htaccess_data
        );
      }
      else
      {
        $htaccess_data = str_replace(
                '{REDIRECT}',
                  'RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]' . PHP_EOL
                  . 'RewriteRule ^(.*)$ http://%1/$1 [R=301,L]' . PHP_EOL
                  . 'RewriteCond %{SERVER_PORT} =443' . PHP_EOL
                  . 'RewriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=permanent]',
                $htaccess_data );
      }
    }

    $additional_classes = file_get_contents( '../libraries/additional-classes.ini' );
    $additional_classes = explode( PHP_EOL, $additional_classes );
    $additional_classes = array_filter( $additional_classes );
    if ( is_array( $additional_classes ) and !empty( $additional_classes ) )
    {
      foreach ( $additional_classes as $class )
      {
        $classes .= 'RewriteCond %{REQUEST_URI}  ^/' . trim( $class ) . '/(.*) [NC]' . PHP_EOL;
        $classes .= 'RewriteRule ^([^/]*)/([^/]*)/(.*)$ index.php?module=$1&action=$2&$3 [L]' . PHP_EOL;
      }
    }
    $htaccess_data = str_replace( '{ADDITIONAL_CLASSES}', $classes, $htaccess_data );

    /* pozostałe linki */
    $htaccess_data .= PHP_EOL;
    $htaccess_data .= 'RewriteRule ^newsletter/signin/$ index.php?module=newsletter&action=signin [L]' . PHP_EOL;
    $htaccess_data .= 'RewriteRule ^newsletter/confirm/hash=(.*)$ index.php?module=newsletter&action=confirm&hash=$1 [L]' . PHP_EOL;
    $htaccess_data .= 'RewriteRule ^newsletter/unsubscribe/hash=(.*)$ index.php?module=newsletter&action=unsubscribe&hash=$1 [L]' . PHP_EOL;

    /* pixieset */
    $results = $mdb -> select( 'pp_articles', 'id', [ 'pixieset' => 1 ] );
    if ( is_array( $results ) and count( $results ) )
    {
      $pixieset = 'RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?' . $url_tmp. ' [NC]' . PHP_EOL;
      $pixieset .= 'RewriteCond %{REQUEST_URI} ^(';
      foreach ( $results as $row )
      {
        $pixieset .= '/upload/article_images/article_' . $row . '/';
        if ( $row != end( $results ) )
          $pixieset .= '|';
      }
      $pixieset .= ') [NC]' . PHP_EOL . 'RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]' . PHP_EOL;

      $htaccess_data = str_replace( '{PIXIESET]', $pixieset, $htaccess_data );
    }
    else
    {
      $htaccess_data = str_replace( '{PIXIESET]', '', $htaccess_data );
    }

    $fp = fopen( $dir . '.htaccess', 'w' );
    fwrite( $fp, $htaccess_data );
    fclose( $fp );

    $class  = '\admin\factory\Sitemap';
    $action = 'sitemap';

    if ( class_exists( $class ) and method_exists( new $class, $action ) )
      $site_map = call_user_func_array( array( $class, $action ), array( $site_map, $available_domains, $domain_prefix, $www, $url ) );

    if ( is_array( $available_domains ) and !empty( $available_domains ) )
    {
      foreach ( $available_domains as $domain )
      {
        $fp = fopen( $dir . 'sitemap_' . \S::seo( $domain['domain'] ) . '.xml', 'w' );
        fwrite( $fp, $site_map[ $domain['domain'] ] );
        fclose( $fp );
      }
    }
    else
    {
      $fp = fopen( $dir . 'sitemap.xml', 'w' );
      fwrite( $fp, $site_map[ $url ] );
      fclose( $fp );
    }

    $fp = fopen( $dir . 'robots.txt', 'w' );
    fwrite( $fp, $robots );
    fclose( $fp );
  }

  public static function seo($val, $delete_rhombs = false)
  {
      // Zamiana niełamiącej spacji na zwykłą
      $val = preg_replace('/\xc2\xa0/', ' ', $val);

      // Podstawowe zamiany znaków specjalnych
      $array_rep1 = array(
          '*', '_', ' ', '+', '"', "'", '?', '-', ',', '!', '~', '<', '>', '@', '#',
          '$', '%', '^', '&', '*', '(', ')', '-', '=', '\\', '|', '[', ']', ':', '(', ')',
          '–', '•', ' '
      );
      $array_rep2 = array(
          '-', '-', '-', '-', '', '', '', '-', '-', '', '-', '-', '-', '-', '-', '-',
          '-', '-', '-', '-', '-', '', '-', '-', '-', '-', '-', '-', '-', '-', '-', '', ''
      );

      // Usuwanie polskich znaków
      $val = \front\factory\Globelus::noPl($val);

      // Zamiana popularnych znaków na myślniki lub pusty ciąg
      $val = str_replace($array_rep1, $array_rep2, $val);

      // Opcjonalne usunięcie ukośników
      if ($delete_rhombs) {
          $val = str_replace('/', '', $val);
      }

      // Usunięcie wszystkich znaków poza literami, cyframi i myślnikami
      // (np. emotki, inne znaki Unicode, itd.)
      $val = preg_replace('/[^a-zA-Z0-9\-]/u', '', $val);

      // Konwersja na małe litery
      $val = strtolower($val);

      // Redukcja wielokrotnych myślników do jednego
      $val = preg_replace('/(-){2,}/', '-', $val);

      // Usunięcie myślników z początku i końca
      $val = ltrim($val, '-');
      $val = rtrim($val, '-');

      return $val;
  }

  public static function noPL( $val )
  {
    $table = array(
            "А" => "a", "Б" => "b", "В" => "v", "Г" => "g", "Д" => "d",
            "Е" => "e", "Ё" => "yo", "Ж" => "zh", "З" => "z", "И" => "i",
            "Й" => "j", "К" => "k", "Л" => "l", "М" => "m", "Н" => "n",
            "О" => "o", "П" => "p", "Р" => "r", "С" => "s", "Т" => "t",
            "У" => "u", "Ф" => "f", "Х" => "kh", "Ц" => "ts", "Ч" => "ch",
            "Ш" => "sh", "Щ" => "sch", "Ъ" => "", "Ы" => "y", "Ь" => "",
            "Э" => "e", "Ю" => "yu", "Я" => "ya", "а" => "a", "б" => "b",
            "в" => "v", "г" => "g", "д" => "d", "е" => "e", "ё" => "yo",
            "ж" => "zh", "з" => "z", "и" => "i", "й" => "j", "к" => "k",
            "л" => "l", "м" => "m", "н" => "n", "о" => "o", "п" => "p",
            "р" => "r", "с" => "s", "т" => "t", "у" => "u", "ф" => "f",
            "х" => "kh", "ц" => "ts", "ч" => "ch", "ш" => "sh", "щ" => "sch",
            "ъ" => "", "ы" => "y", "ь" => "", "э" => "e", "ю" => "yu",
            "я" => "ya", " " => "-", "." => "", "," => "",
            ":" => "", ";" => "", "—" => "", "–" => "-", "і" => "i", "ó" => "o"
    );

    $val = strtr( $val, $table );

    $val = iconv( 'UTF-8', 'ASCII//TRANSLIT',  $val );

    $table = Array(
            "\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"
    );

    $val = strtr( $val, $table );

    return $val;
  }

  public static function delete_cache()
  {
    \S::delete_dir( '../cache/' );
    \S::delete_dir( '../temp/' );
    \S::delete_dir( 'temp/' );
  }

  public static function delete_dir( $dir )
  {
    if ( is_file( $dir ) )
      return @unlink( $dir );

    else if ( is_dir( $dir ) )
    {
      $scan = glob( rtrim( $dir, '/' ) . '/*' );

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

      if ( is_dir( $dir ) && self::is_empty_dir( $dir ) and $dir != '../temp/' )
        return @rmdir( $dir );
    }
  }

  public static function is_empty_dir( $dir )
  {
    return ( ( $files = @scandir( $dir ) ) && count( $files ) <= 2 );
  }

  public static function email_check( $email )
  {
    return filter_var( $email, FILTER_VALIDATE_EMAIL );
  }

  public static function send_email( $email, $subject, $text, $replay = '', $file = '' )
  {
    global $settings;

    if ( file_exists( 'libraries/phpmailer/class.phpmailer.php' ) )
      require_once 'libraries/phpmailer/class.phpmailer.php';

    if ( file_exists( 'libraries/phpmailer/class.smtp.php' ) )
      require_once 'libraries/phpmailer/class.smtp.php';

    if ( file_exists( '../libraries/phpmailer/class.phpmailer.php' ) )
      require_once '../libraries/phpmailer/class.phpmailer.php';

    if ( file_exists( '../libraries/phpmailer/class.smtp.php' ) )
      require_once '../libraries/phpmailer/class.smtp.php';

    if ( self::email_check( $email ) and $subject )
    {
      $mail              = new PHPMailer();
      $mail -> IsSMTP();
      $mail -> SMTPAuth    = true;
      $mail -> Host        = $settings['email_host'];
      $mail -> Port        = $settings['email_port'];
      $mail -> Username    = $settings['email_login'];
      $mail -> Password    = $settings['email_password'];
      $mail -> CharSet     = "UTF-8";
      $mail -> SMTPOptions = array(
              'ssl' => array(
                      'verify_peer'       => false,
                      'verify_peer_name'  => false,
                      'allow_self_signed' => true
              )
      );

      if ( self::email_check( $replay ) )
      {
        $mail -> AddReplyTo( $replay, $replay );
        $mail -> SetFrom( $settings['contact_email'], $settings['contact_email'] );
      }
      else
      {
        $mail -> AddReplyTo( $settings['contact_email'], $settings['firm_name'] );
        $mail -> SetFrom( $settings['contact_email'], $settings['firm_name'] );
      }
      $mail -> AddAddress( $email, '' );
      $mail -> Subject = $subject;
      $mail -> Body    = $text;
      if ( is_array( $file ) )
      {
        foreach ( $file as $file_tmp )
        {
          if ( file_exists( $file_tmp ) )
            $mail -> AddAttachment( $file_tmp );
        }
      }
      else
      {
        if ( file_exists( $file ) )
          $mail -> AddAttachment( $file );
      }
      $mail -> IsHTML( true );
      return $mail -> Send();
    }
    return false;
  }
}
?>