<?php
class System
{  
  function getImgFileTypes() 
  {
    $mime_types = array(
      'image/png',
      'image/jpeg',
      'image/jpeg',
      'image/jpeg',
      'image/gif',
      'image/bmp',
      'image/vnd.microsoft.icon',
      'image/tiff',
      'image/tiff',
      'image/svg+xml',
      'image/svg+xml',
      'application/pdf',
      'image/vnd.adobe.photoshop',
      'application/postscript',
      'application/postscript',
      'application/postscript'
    );
    return $mime_types;
  }
  
  public static function duplicateMysqlRow( $table, $id_field, $id, $leave = false ) 
  {
    global $db;
    
    $db -> query( "INSERT INTO " . $table . " (`" . $id_field . "`) VALUES (NULL)" );
    $newid = $db -> lastInsertId();
    
    $sql = "UPDATE " . $table . " SET ";
    
    $query = $db -> query( 'SELECT * FROM ' . $table . ' WHERE ' . $id_field . ' = ' . $id );
    if ( $query -> rowCount() ) while ( $row = $query -> fetch( PDO::FETCH_ASSOC ) )
    {
      foreach ( $row as $key => $value )
      {
        if ( $key != $id_field && @!in_array( $key, $leave ) )
          $sql .= '`' . $key . '` = "' . str_replace( '"', '\"', $value ) . '", ';
      }      
    }
    $query -> closeCursor();
    
    $sql = substr( $sql, 0, strlen( $sql ) - 2 );
    $sql .= " WHERE " . $id_field . " = " . $newid;
  
    $db -> query( $sql );
    
    return $newid;
  }

  public static function copy_file( $url, $filename )
  { 
    $file = fopen( $url, "rb" );
    if ( !$file ) return false; else 
    {
      $fc = fopen( $filename, "wb" );
      while ( !feof( $file ) ) 
      {
        $line = fread( $file, 1028 );
        fwrite( $fc, $line );
      }
      fclose( $fc );
      return true;
    }
  }
  
  public static 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;
	}
				
	public static 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;
	}
			
	public static 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 static function downloadFile( $id )
  {
    global $db;
    
    $query = $db -> prepare( 'SELECT file FROM pp_articles_file WHERE id = :id' );
    $query -> bindValue( ':id', $id, \PDO::PARAM_INT );
    $query -> execute();
    if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
    {
      if (file_exists( $row['file'] ) )
      {
        header( 'Content-Description: File Transfer');
        header( 'Content-Type: application/octet-stream');
        header( 'Content-Disposition: attachment; filename=' . basename( $row['file'] ) );
        header( 'Content-Transfer-Encoding: binary');
        header( 'Expires: 0');
        header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header( 'Pragma: public');
        header( 'Content-Length: ' . filesize( $row['file'] ) );
        ob_clean();
        flush();
        readfile( $row['file'] );
        exit;
      }
    }
    $query -> closeCursor();    
  }  
  
  public static function isBot( $user_agent = '' )
  {
    if ( !$user_agent )
      $user_agent = $_SERVER['HTTP_USER_AGENT'];
      
    $bots = array(  "Teoma", "alexa", "froogle", "Gigabot", "inktomi", "looksmart", "URL_Spider_SQL", "Firefly", "NationalDirectory", "Ask Jeeves", "TECNOSEEK", "InfoSeek", "WebFindBot", "girafabot",
                    "crawler", "www.galaxy.com", "Googlebot", "Scooter", "Slurp", "msnbot", "appie", "FAST", "WebBug", "Spade", "ZyBorg", "rabaz", "Baiduspider", "Feedfetcher-Google", "TechnoratiSnoop", "Rankivabot",
                    "Mediapartners-Google", "Sogou web spider", "WebAlta Crawler","TweetmemeBot", "Butterfly", "Twitturls", "Me.dium", "Twiceler");

    if ( is_array( $bots ) ) foreach ( $bots as $bot )
    {
      if ( strpos( $user_agent, $bot ) !== false )
        return true;
    }

    return false;
  }

  public static function otherDiffDate( $start, $end, $out_in_array = false )
  {
    $intervalo  = date_diff( date_create( $start ), date_create( $end ) );
    $out        = $intervalo -> format( "Years:%Y,Months:%M,Days:%d,Hours:%H,Minutes:%i,Seconds:%s" );
    if ( !$out_in_array )
      return $out;
    $a_out = array();
    array_walk( explode( ',', $out ),
    function($val,$key) use(&$a_out){
        $v=explode(':',$val);
        $a_out[$v[0]] = $v[1];
    });
    return $a_out;
  }
  
  public static function getHost( $page, $www = true ) 
  {
		preg_match('@^(?:http://)?([^/]+)@i', $page, $matches);
    if ( !$www )
      $matches[1] = str_replace("www.", "", $matches[1]);
		return $matches[1];
	}

  public static function checkEmailRegister( $email )
  {
    if ( !self::checkEmail( $email ) )
      return 1;
    else
    {
      if ( \admin\factory\Restriction::isBannedEmail( $email ) || !self::isEmailFree( $email ) )
        return 2;
      else
        return 0;
    }
  }

  public static function checkPasswordRegister( $password , $password2 )
  {
    if ( strlen( $password ) < 5 )
      return 1;
    else
    {
      if ( $password != $password2 )
        return 2;
      else
        return 0;
    }
  }

  public static function checkLoginRegister( $login )
  {
    if ( strlen( $login ) < 5 || preg_match( "/[^A-z0-9_-]/" , $login ) )
      return 1;
    else
    {
      if ( \admin\factory\Restriction::isBannedLogin( $login ) || !self::isLoginFree( $login ) )
        return 2;
      else
        return 0;
    }
  }

  function importDumpFile( $filePath )
  {
    global $db;

    if (!is_file($filePath))
      throw new Exception("Podany plik ($filePath) nie istniej!!");

    $lines = file( $filePath );
    $query = '';
    foreach ( $lines as $line )
    {
      if( strncmp($line,'--',2) == 0 )
        continue;
      if( strncmp($line,'/*',2) == 0 )
        continue;

      $line = ' '.trim($line);
      $query .= $line;

      if( $line[strlen($line) - 1] == ';' )
      {
        $db -> query( $query );
        $query = '';
      }
    }
  }

  public static function getFormatDate()
  {
      $date     = date("l, d-F-Y",  time());
      $date_ang = array('Monday', 'Tuesday', 'Wednesday',  'Thursday', 'Friday', 'Saturday', 'Sunday', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
      $date_pl  = array('Poniedziałek', 'Wtorek', 'Środa', 'Czwartek', 'Piątek', 'Sobota', 'Niedziela', 'Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj', 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 'Listopad', 'Grudzień');
      $data     = str_replace($date_ang, $date_pl, $date);
      $data     = str_replace('-',' ',$data);
      return $data;
  }

  public static function getNameDay()
  {
    if ( file_exists( 'resources/namedays.php' ) )
    {
      include 'resources/namedays.php';

      $days   = explode( "*" , $namedays );
      $today  = date('d m');
      for ( $x = 0; $x < sizeof( $days ); $x++ ) {
        $day = explode( "-" , $days[$x] );
        if ( $today == trim( $day[0] ) )
          $out = $day[1];
      }
      return $out;
    }
  }

  public static function setSessionVar( $var, $val, $admin = false )
  {
    if ( !$admin )
      $_SESSION[ $var ] = $val;
    else
      $_SESSION[ 'admin_' . $var ] = $val;
  }

  public static function getSessionVar( $var, $admin = false )
  {
    if ( !$admin ) 
    {
      if ( isset( $_SESSION[ $var ] ) )
        return $_SESSION[ $var ];
    } 
    else 
    {
      if ( isset( $_SESSION[ 'admin_' . $var ] ) )
        return $_SESSION[ 'admin_' . $var ];
    }
    return null;
  }

  public static function deleteSessionVar( $var, $admin = false )
  {
    if ( !$admin )
      unset( $_SESSION[ $var ] );
    else
      unset( $_SESSION[ 'admin_' . $var ] );
  }

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

  public static function formGetHash( $val )
  {
    $val = base64_encode( $val );
    $val = self::formGet( $val );
    return base64_decode( $val );
  }

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

  public static function formGetInt( $var )
  {
    return (int)self::formGet( $var );
  }

  public static function setAlert( $val )
  {
    self::setSessionVar( 'alert', $val );
  }

  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 getComboYesNo()
  {
    $tab[0] = 'nie';
    $tab[1] = 'tak';

    return $tab;
  }

  public static function deleteAction()
  {
    $akcja = "$.prompt( 'Na pewno chcesz usunąć wybrany element?', { title: 'Potwierdź?', submit: function(e,v,m,f) { if ( v == true ) document.location.href='index.php?rw=del&id=[param]'; }, buttons: { 'tak': true, 'nie': false }, focus: 1 } )";
    $akcja = 'onClick="' . $akcja . '"';

    return  $akcja;
  }

  public static 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 checkBrowseLimit( $limit )
  {
    switch ($limit)
    {
      case 5:
        return 5;
      break;
      case 10:
        return 10;
      break;
        case 25:
      return 25;
        break;
      case 50:
        return 50;
      break;
      case 100:
        return 100;
      break;
      default:
        return 25;
      break;
    }
  }

  public static function getPagesTitle()
  {
    global $cache , $config , $db;

    $key = 'getPagesTitle:all';

    if ( !$pages = $cache -> fetch( $key ) )
    {
      $query = $db -> prepare( 'SELECT id FROM pp_pages' );
      $query -> execute();
      if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
        $pages[ $row['id'] ] = \admin\factory\Pages::getPageTitle( $row['id'] );
      $query -> closeCursor();
      $cache -> store( $key , $pages , $config['cache_expire_short'] );
    }

    return $pages;
  }

  public static function rewriteHtacces()
  {
    global $db , $config;

    $link_base  = "http://" . $_SERVER['SERVER_NAME'] . "/";

    $nl       = chr( 13 ) . chr( 10 );
    $rss_tmp  = '';

    $site_map   = '<?xml version="1.0" encoding="UTF-8"?>' . $nl;
    $site_map   .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . $nl;
    $site_map   .= '<url>' . $nl;
      $site_map .= '<loc>' . $link_base . '</loc>' . $nl;
      $site_map .= '<lastmod>' . date( 'Y-m-d' ) . '</lastmod>' . $nl;
      $site_map .= '<changefreq>daily</changefreq>' . $nl;
      $site_map .= '<priority>1</priority>' . $nl;
    $site_map   .= '</url>' . $nl;

    $htaccess_data = file_get_contents( '../files/htaccess.conf' );
    $htaccess_data = str_replace( '{MAIN_PAGE}' , self::getMainPage()  , $htaccess_data );
    $htaccess_data = str_replace( '{PAGE}'      , $config['page']      , $htaccess_data );

    $query = $db -> prepare( 'SELECT id, name FROM pp_langs WHERE enabled = :enabled' );
    $query -> bindValue( ':enabled', 1, \PDO::PARAM_INT );
    $query -> execute();
    if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
    {
      $query2 = $db -> prepare( 'SELECT title, seo_link, page_id FROM pp_pages_langs WHERE lang_id = :lang_id' );
      $query2 -> bindValue( ':lang_id' , $row['id'] , \PDO::PARAM_STR );
      $query2 -> execute();
      if ( $query2 -> rowCount() ) while ( $row2 = $query2 -> fetch() )
      {
        $site_map .= '<url>' . $nl;
          if ( !$row2['seo_link'] )
            $site_map .= '<loc>' . $link_base . 's,' . $row2['page_id'] . ',' . self::seo( $row2['title'] ) . '</loc>' . $nl;
          else
            $site_map .= '<loc>' . $link_base . $row['seo_link'] . '</loc>' . $nl;            
          $site_map .= '<lastmod>' . date( 'Y-m-d' ) . '</lastmod>' . $nl;
          $site_map .= '<changefreq>daily</changefreq>' . $nl;
          $site_map .= '<priority>1</priority>' . $nl;
        $site_map .= '</url>' . $nl;
        
        if ( $row2['seo_link'] )
        {
          $htaccess_data .= chr( 13 ) . chr( 10 ) . 'RewriteCond %{QUERY_STRING} !=""';
          $htaccess_data .= chr( 13 ) . chr( 10 ) . 'RewriteCond %{REQUEST_METHOD} !=POST';
          $htaccess_data .= chr( 13 ) . chr( 10 ) . 'RewriteRule ' . \System::seo( $row2['seo_link'] ) . ' %{REQUEST_URI}? [R=301,L]';
          $htaccess_data .= chr( 13 ) . chr( 10 ) . 'RewriteRule ^' . \System::seo( $row2['seo_link'] ) . '$ index.php?rw=change_site&id=' . $row2['page_id'] . ' [L]';
        }
      }

      $query2 = $db -> prepare( 'SELECT title, article_id, seo_link FROM pp_articles_langs WHERE lang_id = :lang_id' );
      $query2 -> bindValue( ':lang_id' , $row['id'] , \PDO::PARAM_STR );
      $query2 -> execute();
      if ( $query2 -> rowCount() ) while ( $row2 = $query2 -> fetch() )
      {
        $site_map .= '<url>' . $nl;
          if ( !$row2['seo_link'] )
            $site_map .= '<loc>' . $link_base . 'a,' . $row2['article_id'] . ',' . self::seo( $row2['title'] ) . '</loc>' . $nl;
          else
            $site_map .= '<loc>' . $link_base . $row2['seo_link'] . '</loc>' . $nl;
          $site_map .= '<lastmod>' . date( 'Y-m-d' , strtotime( self::getDate() ) ) . '</lastmod>' . $nl;
          $site_map .= '<changefreq>daily</changefreq>' . $nl;
          $site_map .= '<priority>1</priority>' . $nl;
        $site_map .= '</url>' . $nl;
        
        if ( $row2['seo_link'] )
        {
          $htaccess_data .= chr( 13 ) . chr( 10 ) . 'RewriteCond %{QUERY_STRING} !=""';
          $htaccess_data .= chr( 13 ) . chr( 10 ) . 'RewriteCond %{REQUEST_METHOD} !=POST';
          $htaccess_data .= chr( 13 ) . chr( 10 ) . 'RewriteRule ' . \System::seo( $row2['seo_link'] ) . ' %{REQUEST_URI}? [R=301,L]';
          $htaccess_data .=  chr( 13 ).chr( 10 ) . 'RewriteRule ^' . \System::seo( $row2['seo_link'] ) . '$ index.php?art=$1' . $row2['article_id'] . ' [L]';
        }
      }
      $query2 -> closeCursor();

      $query2 = $db -> prepare( 'SELECT title, article_id, text, seo_link FROM pp_articles_langs WHERE lang_id = :lang_id ORDER BY article_id DESC LIMIT 30' );
      $query2 -> bindValue( ':lang_id' , $row['id'] , \PDO::PARAM_STR );
      $query2 -> execute();
      if ( $query2 -> rowCount() ) while ( $row2 = $query2 -> fetch() )
      {
        $rss_tmp .= '<item>' . $nl;
          $rss_tmp .= '<title>' . $row2['title'] . '</title>' . $nl;
          if ( !$row2['seo_link'] )
            $rss_tmp .= '<link>' . $link_base . 'a,' . $row2['article_id'] . ',' . self::seo( $row2['title'] ) . '</link>' . $nl;
          else
            $rss_tmp .= '<link>' . $link_base . $row2['seo_link'] . '</link>' . $nl;
          $text = str_replace( 'ó' , 'Ã³' , stripslashes( $row2['text'] ) );
          $text = str_replace( '&oacute;' , 'ó' , $text );
          $text = System::deleteHTML( $text );
          $text = mb_substr( $text , 0 , 150 , 'UTF-8' );
          $rss_tmp .= '<description>' . $text . '...</description>' . $nl;
          $rss_tmp .= '<pubDate>' . date( "d/m/Y H:i" , strtotime( self::getDate() ) ) . '</pubDate>' . $nl;
        $rss_tmp .= '</item>' . $nl;
      }
      $query2 -> closeCursor();
    }
    $query -> closeCursor();

    $site_map .= '</urlset>';

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

    $sitemap  = '../files/sitemap.xml';
    $fp     = fopen( $sitemap , 'w' );
    fwrite( $fp , $site_map );
    fclose( $fp );

    $rss_feed = '<?xml version="1.0" encoding="UTF-8"?>' . $nl;
    $rss_feed .= '<rss version="2.0">' . $nl;
    $rss_feed .= '<channel>' . $nl;
    $rss_feed .= '<title>' . \admin\factory\Settings::getSystemSettings( 'firm_name' ) . '</title>' . $nl;
    $rss_feed .= '<link>' . $link_base . '</link>' . $nl;
    $rss_feed .= '<description></description>' . $nl;
    $rss_feed .= '<language>pl</language>';
    $rss_feed .= '<copyright>Copyright © ' . \admin\factory\Settings::getSystemSettings('firm_name') . '</copyright>' . $nl;
    $rss_feed .= '<lastBuildDate>' . date( 'm/d/Y H:i' , strtotime( self::getDate() ) ) . '</lastBuildDate>' . $nl;
    $rss_feed .= $rss_tmp;
    $rss_feed .= '</channel>' . $nl;
    $rss_feed .= '</rss>' . $nl;


    $rssfeed  = '../files/rss.xml';
    $fp     = fopen( $rssfeed , 'w' );
    fwrite( $fp , $rss_feed );
    fclose( $fp );
  }

  function deleteHTML( $text )
  {
    $search = array ("'<script[^>]*?>.*?</script>'si",
                 "'<[/!]*?[^<>]*?>'si",
                 "'([rn])[s]+'",
                 "'&(quot|#34);'i",
                 "'&(amp|#38);'i",
                 "'&(lt|#60);'i",
                 "'&(gt|#62);'i",
                 "'&(nbsp|#160);'i",
                 "'&(iexcl|#161);'i",
                 "'&(cent|#162);'i",
                 "'&(pound|#163);'i",
                 "'&(copy|#169);'i",
                 "'&#(d+);'e");

    $replace = array ("",
                 "",
                 "\1",
                 "\"",
                 "&",
                 "<",
                 ">",
                 " ",
                 chr(161),
                 chr(162),
                 chr(163),
                 chr(169),
                 "chr(\1)");

    $text = preg_replace($search, $replace, $text);

    return $text;
  }

  public static function getMainPage()
  {
    global $db , $cache , $config, $lang;
    
    $key = 'mainPage:' . $lang -> get_language();

    if ( !$main_page = $cache -> fetch( $key . 'a' ) )
    {
      $query = $db -> prepare( 'SELECT pp.id, seo_link FROM pp_pages AS pp, pp_pages_langs AS ppt WHERE enabled = :enabled AND pp.id = ppt.page_id AND lang_id = :lang_id ORDER BY id_menu ASC, o ASC LIMIT 1' );
      $query -> bindValue( ':enabled', 1,                       \PDO::PARAM_STR );
      $query -> bindValue( ':lang_id', $lang -> get_language(), \PDO::PARAM_STR );
      $query -> execute();
      if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
      {
        if ( $row['seo_link'] )
          $main_page = $row['seo_link'];
        else
          $main_page  = 's,' . $row['id'] . ',' . self::seo( \admin\factory\Pages::getPageTitle ( $row[ 'id' ] ) );
      }
      $query -> closeCursor();
      $cache -> store( $key , $main_page , $config['cache_expire'] );
    }

    return $main_page;
  }

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

    $val = self::noPl( $val );
    $val = str_replace( $array_rep1 , $array_rep2 , $val );
    $val = strtolower( $val );
    $val = preg_replace( '/(-){2,}/', '-', $val );
    
    return $val;
  }

  public static 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");

     return strtr( $val , $table );
  }

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

  public static function getArticlesTitle()
  {
    global $db;

    $query = $db -> prepare( 'SELECT id FROM pp_articles' );
    $query -> execute();
    if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
      $articles[ $row['id'] ] = \System::getArticleTitle( $row['id'] );
    $query -> closeCursor();

    return $articles;
  }

  public static function getArticleTitle( $id , $language = 'pl' )
  {
    global $db;

    $query = $db -> prepare( 'SELECT title FROM pp_articles_langs WHERE article_id = :article_id AND lang_id = :lang_id' );
    $query -> bindValue( ':article_id'  , $id       , PDO::PARAM_INT );
    $query -> bindValue( ':lang_id'     , $language , PDO::PARAM_STR );
    $query -> execute();
    if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
      $title = $row['title'];
    $query -> closeCursor();

    if ( !$title )
    {
      $query2 = $db -> prepare( 'SELECT title FROM pp_articles_langs WHERE article_id = :article_id LIMIT 1' );
      $query2 -> bindValue( ':article_id' , $id , PDO::PARAM_STR );
      $query2 -> execute();
      if ( $query2 -> rowCount() ) while ( $row2 = $query2 -> fetch() )
        $title = $row2['title'];
      $query2 -> closeCursor();
    }
    return $title;
  }

  public static 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::deleteCacheAdmin( $path );
      if ( $str != 'temp/' && $str != 'admin/temp/' && is_dir( $str ) && self::isEmptyDir( $str ) )
        return @rmdir( $str );
    }
    self::deleteCache();
  }

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

  public static 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 )
        self::deleteCache( $path );
      if ( $str != '../temp/' && $str != 'temp/' && is_dir( $str ) && self::isEmptyDir( $str ) )
        return @rmdir( $str );
    }
  }

  public static function sendEmail( $email, $temat, $tresc, $replay = '', $file = '' )
  {
    if ( file_exists('resources/phpmailer/class.phpmailer.php') )
        require_once 'resources/phpmailer/class.phpmailer.php';
    if ( file_exists('../resources/phpmailer/class.phpmailer.php') )
        require_once'../resources/phpmailer/class.phpmailer.php';

    if ( isset($email) && isset($temat) && isset($tresc) )
    {
      $admin_mail         = \admin\factory\Settings::getSystemSettings( 'admin_email');
      $mail               = new PHPMailer();
      $mail -> SMTPAuth   = true;
      $mail -> Host       = \admin\factory\Settings::getSystemSettings( 'email_host' );
      $mail -> Port       = \admin\factory\Settings::getSystemSettings( 'email_port' );
      $mail -> Username   = \admin\factory\Settings::getSystemSettings( 'email_login' );
      $mail -> Password   = \admin\factory\Settings::getSystemSettings( 'email_password' );
      $mail -> CharSet  = "UTF-8";
      if ( $replay == "" )
      {
        $mail -> AddReplyTo( $admin_mail  , \admin\factory\Settings::getSystemSettings( 'firm_name' ) );
        $mail -> SetFrom( $admin_mail     , \admin\factory\Settings::getSystemSettings( 'firm_name' ) );
      }
      else
      {
        $mail -> AddReplyTo( $replay  , '' );
        $mail -> SetFrom( $replay   , '' );
      }
      $mail -> AddAddress( $email , '' );
      $mail -> Subject = $temat;
      $mail -> Body = str_replace( '<br>' , chr(13).chr(10) , $tresc );
      if ( file_exists( $file ) )
        $mail -> AddAttachment($file);
      $mail -> IsHTML(true);
      $mail -> Send();
    }
  }

  public static 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 static function checkEmail( $email )
  {
    if ( filter_var( $email , FILTER_VALIDATE_EMAIL ) )
      return true;
    else
      return false;
  }

  public static function gen_hash( $limit = 5 )
  {
    $out = '';
    for ( $i = 0; $i < $limit; $i++ )
      $out .= chr( rand( 97 , 122 ) );
    return $out . rand( 1000 , 9999 );
  }

  public static function isEmailFree( $email )
  {
    global $db;

    $query = $db -> prepare( 'SELECT id FROM pp_users WHERE email = :email' );
    $query -> bindValue( ':email', $email, \PDO::PARAM_STR );
    $query -> execute();
    if ( $query -> rowCount() )
      return false;
    $query -> closeCursor();
    return true;
  }

  public static function isLoginFree( $login )
  {
    global $db;

    $query = $db -> prepare( 'SELECT id FROM pp_users WHERE login = :login' );
    $query -> bindValue( ':login', $login, \PDO::PARAM_STR );
    $query -> execute();
    if ( $query -> rowCount() )
      return false;
    $query -> closeCursor();
    return true;
  }

  public static function getIp()
  {
    if ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
      return $_SERVER['HTTP_X_FORWARDED_FOR'];
    return $_SERVER['REMOTE_ADDR'];
  }

  public static function random_color()
  {
    mt_srand((double)microtime()*1000000);
    $c = '';
    while(strlen($c)<6)
      $c .= sprintf("%02X", mt_rand(0, 255));
    return $c;
  }

  public static function getRandomKeyWord( $keywords )
  {
    $out = '';
    
    $keywords = explode( ',' , $keywords );
    
    shuffle( $keywords );
    
    for ( $i = 0; $i <= 1; $i++ )
    {
      if ( $out && $keywords[$i] )
        $out .= ', ';
      
      $out .= $keywords[$i];
    }
    return $out;
  }

  public static function isImage( $file )
  {
    if ( $file['type'] == 'image/pjpeg' || $file['type'] == 'image/jpg' || $file['type'] == 'image/jpeg' || $file['type'] == 'image/gif' || $file['type'] == 'image/png' )
    {
      if ( $file['size'] < 500000 )
      {
        $x = getimagesize( $file['tmp_name'] );
        if ( is_array( $x ) && $x[0] > 0 && $x[1] > 0 )
          return true;
      }
    }
  }
}
?>