<?php

class System
{
	public function getLastUpdate()
  {
    if ( file_exists( 'files/.update' ) )
      $date = file_get_contents( 'files/.update' );
    else
      $date = '2012-01-01 00:00:00';

    return $date;
  }

  public function getLayout( $id )
  {
    global $db, $config, $cache;

    $key = 'getLayout:' . $id;
    if ( !$layout = $cache -> fetch() )
    {
      $query = $db -> prepare( 'SELECT * FROM pcms_layout WHERE id = :id' );
      $query -> bindValue( ':id', $id, \PDO::PARAM_INT );
      $query -> execute();
      if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
        $layout = $row;
      $query -> closeCursor();
    }
    return $layout;
  }

  public function getLayouts()
  {
    global $db;

    $query = $db -> query( 'SELECT id, name FROM pcms_layout' );
    if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
      $layouts[] = $row;
    $query -> closeCursor();

    return $layouts;
  }

  public function getUserSurname( $id )
  {
    global $db , $config , $cache;

    $key = 'getUserSurname:' . $id;

    if ( !$surname = $cache -> fetch( $key ) )
    {
      $query = $db -> prepare( 'SELECT surname FROM pcms_user WHERE id = :id' );
      $query -> bindValue( ':id' , $id , \PDO::PARAM_INT );
      $query -> execute();
      if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
        $name = $row['surname'];
      $query -> closeCursor();
      $cache -> store( $key , $surname , $config['cache_expire_long'] );
    }
    return $name;
  }

  public function getUserName( $id )
  {
    global $db , $config , $cache;

    $key = 'getUserName:' . $id;

    if ( !$name = $cache -> fetch( $key ) )
    {
      $query = $db -> prepare( 'SELECT name FROM pcms_user WHERE id = :id' );
      $query -> bindValue( ':id' , $id , \PDO::PARAM_INT );
      $query -> execute();
      if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
        $name = $row['name'];
      $query -> closeCursor();
      $cache -> store( $key , $name , $config['cache_expire_long'] );
    }
    return $name;
  }

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

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

  public function checkLoginRegister( $login )
  {
    if ( strlen( $login ) < 5 || preg_match( "/[^A-z0-9_-]/" , $login ) )
      return 1;
    else
    {
      if ( self::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 = '';
      }
    }
  }

  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;
  }

  function getNameDay()
  {
    global $sys;
    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 function setSessionVar( $var , $val , $admin = false )
  {
    if ( !$admin )
      $_SESSION[ $var ] = $val;
    else
      $_SESSION[ 'admin_' . $var ] = $val;
  }

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

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

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

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

  public 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 function formGetInt( $var )
  {
    return (int)self::formGet( $var );
  }

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

  public function getAlert()
  {
    $tpl = new \Savant3;
    $tpl -> _alert = self::getSessionVar( 'alert' );
    return $tpl -> fetch( 'templates/site-alert.php' );
  }

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

    $key = 'getLangs';

    if ( !$langs = $cache -> fetch( $key ) )
    {
      $query = $db -> prepare( 'SELECT id , name FROM pcms_lang WHERE enabled=:enabled' );
      $query -> bindValue( ':enabled' , 1 , PDO::PARAM_STR );
      $query -> execute();
      if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
      {
        $lg['id']   = $row['id'];
        $lg['name'] = $row['name'];
        $langs[]    = $lg;
      }
      $query -> closeCursor();
      $cache -> store( $key , $langs , $config['cache_expire_long' ] );
    }
    return $langs;
  }

  public function getComboYesNo()
  {
    global $lang;

    $tab[0] = $lang -> getTrans( 'T_NIE' );
    $tab[1] = $lang -> getTrans( 'T_TAK' );

    return $tab;
  }

  public function deleteAction()
  {
    global $lang;

    $akcja = "function mycallbackform(v,m,f){
                if( v == true )
                  document.location.href='index.php?rw=del&id=[param]';
              }";
    $akcja .= "$.prompt('" . $lang -> getTrans( 'T_POTWIERDZ_USUNIECIE' ) . "',{ callback: mycallbackform, buttons: { " . $lang -> getTrans( 'T_TAK' ) . ": true, " . $lang -> getTrans( 'T_NIE' ) . ": false }, focus: 1 })";
    $akcja = 'onClick="' . $akcja . '"';

    return  $akcja;
  }

  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 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 function getPagesTitle()
  {
    global $cache , $config , $db;

    $key = 'getPagesTitle:all';

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

    return $pages;
  }

  public function getPageTitle ( $id , $language = 'pl' )
  {
    global $db , $cache , $config;

    $key = 'pageTitle:' . $id . ':' . $language;

    if ( !$title = $cache -> fetch( $key ) )
    {
      $query = $db -> prepare( 'SELECT title FROM pcms_page_translation WHERE page_id = :page_id AND lang_id = :lang_id' );
      $query -> bindValue( ':page_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();
      $cache -> store( $key , $title , $config['cache_expire_long' ] );
    }
    if ( $title == '' )
    {
      $key = 'pageTitleRandom:' . $id;
      if ( !$title = $cache -> fetch( $key ) )
      {
        $query = $db -> prepare( 'SELECT title FROM pcms_page_translation WHERE page_id = :page_id AND title != "" LIMIT 1' );
        $query -> bindValue( ':page_id'   , $id , PDO::PARAM_STR );
        $query -> execute();
        if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
          $title = $row['title'];
        $query -> closeCursor();
        $cache -> store( $key , $title , $config['cache_expire_long' ] );
      }
    }

    return $title;
  }

  public 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 pcms_lang WHERE enabled = :enabled' );
    $query -> bindValue( ':enabled' , 1 , \PDO::PARAM_STR );
    $query -> execute();
    if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
    {
      $query2 = $db -> prepare( 'SELECT title, seo_link, page_id FROM pcms_page_translation 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 ) . 'RewriteRule ^' . $row2['seo_link'] . '$ index.php?rw=change_site&id=' . $row2['page_id'] . ' [L]';
      }

      $query2 = $db -> prepare( 'SELECT title, article_id, seo_link FROM pcms_article_translation 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 ) . 'RewriteRule ^' . $row2['seo_link'] . '$ index.php?art=$1' . $row2['article_id'] . ' [L]';
      }
      $query2->closeCursor();

      $query2 = $db -> prepare( 'SELECT title, article_id, text, seo_link FROM pcms_article_translation 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;
      }
      $query -> 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>' . self::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 © ' . self::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 function getMainPage()
  {
        global $db , $cache , $config;

    $key = 'mainPage';

    if ( !$main_page = $cache -> fetch( $key ) )
    {
      $query = $db -> prepare( 'SELECT id FROM pcms_page WHERE enabled = :enabled ORDER BY o ASC LIMIT 1' );
      $query -> bindValue( ':enabled' , 1 , \PDO::PARAM_STR );
      $query -> execute();
      if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
      {
        $main_page  = 's,' . $row['id'] . ',' . self::seo( self::getPageTitle ( $row[ 'id' ] ) );
      }
      $query -> closeCursor();
      $cache -> store( $key , $main_page , $config['cache_expire'] );
    }

      return $main_page;
  }

  public 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 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 getDate()
  {
    return date( 'Y-m-d H:i:s' );
  }

  public function getSystemSettings( $param )
  {
    global $db , $cache , $config , $lang;

    $key = 'systemSettings:' . $param;

    if ( !$out = $cache -> fetch( $key ) )
    {
      $query = $db -> prepare( 'SELECT value FROM pcms_settings WHERE param = :param' );
      $query -> bindValue( ':param' , $param , \PDO::PARAM_STR );
      $query -> execute();
      if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
        $out = stripslashes( $row['value'] );
      else
        die( $lang -> getTrans( 'T_BRAK_PODANEGO_PARAMETRU' ) );
      $query -> closeCursor();
      $cache -> store( $key , $out , $config['cache_expire_short'] );
    }

    return $out;
  }

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

    $key = 'articlestitle:all';

    if ( !$articles = $cache -> fetch( $key ) )
    {
      $query = $db -> prepare( 'SELECT id FROM pcms_article' );
      $query -> execute();
      if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
        $articles[ $row['id'] ] = \System::getArticleTitle( $row['id'] );
      $query -> closeCursor();
      $cache -> store( $key , $articles , $config['cache_expire_short'] );
    }

    return $articles;
  }

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

    $query = $db -> prepare( 'SELECT title FROM pcms_article_translation 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 pcms_article_translation 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 function getMenuList()
  {
    global $db;

    $menu = array();

    $query = $db -> prepare( 'SELECT id , name FROM pcms_menu' );
    $query -> execute();
    if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
    {
      $mn['id']   = $row['id'];
      $mn['name'] = $row['name'];
      $menu[]     = $mn;
    }
    $query -> closeCursor();

    return $menu;
  }

  public function getPageTypes()
  {
    global $db , $lang;

    $pages = array();

    $query = $db -> prepare( 'SELECT id , name FROM pcms_page_type WHERE enabled = :enabled ORDER BY name ASC' );
    $query -> bindValue( ':enabled' , 1 , \PDO::PARAM_STR );
    $query -> execute();
    if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
    {
      $pg['id']   = $row['id'];
      $pg['name'] = $lang -> getTrans( $row['name'] );
      $pages[]    = $pg;
    }
    $query -> closeCursor();

    return $pages;
  }

  public function getSortTypes()
  {
    global $db , $lang;

    $sort = array();

    $query = $db -> prepare( 'SELECT id , name FROM pcms_page_sort_type ORDER BY name ASC' );
    $query -> execute();
    if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
    {
      $st['id']   = $row['id'];
      $st['name'] = $lang -> getTrans( $row['name'] );
      $sort[]     = $st;
    }
    $query -> closeCursor();

    return $sort;
  }

  public function getCountPages( $menu_id )
  {
    global $db;

    $query = $db -> prepare( 'SELECT count(id) FROM pcms_page WHERE id_menu=:id' );
    $query -> bindValue( ':id' , $menu_id , \PDO::PARAM_INT );
    $query -> execute();
    if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
      return $row[0];
  }

  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::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 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 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         = self::getSystemSettings( 'admin_email');
      $mail = new PHPMailer();
      $mail -> IsSMTP();
      $mail -> SMTPAuth   = true;
      $mail -> Host       = self::getSystemSettings( 'email_host' );
      $mail -> Port       = self::getSystemSettings( 'email_port' );
      $mail -> Username   = self::getSystemSettings( 'email_login' );
      $mail -> Password   = self::getSystemSettings( 'email_password' );
      $mail -> CharSet  = "UTF-8";
      if ( $replay == "" )
      {
        $mail -> AddReplyTo( $admin_mail, $admin_mail );
        $mail -> SetFrom( $admin_mail, $admin_mail );
      }
      else
      {
        $mail -> AddReplyTo( $replay, '' );
        $mail -> SetFrom( $admin_mail, '' );
      }
      $mail -> AddAddress( $email , '' );
      $mail -> Subject = $temat;
      $mail -> Body = str_replace( '<br>' , chr(13).chr(10) , $tresc );
      if ( $file )
        $mail -> AddAttachment($file);
      $mail -> IsHTML(true);
      $mail -> Send();
    }
  }

  public function getCountBanners()
  {
    global $db;

    $query = $db -> prepare( 'SELECT count(id) FROM pcms_banner' );
    $query -> execute();
    if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
      return $row[0];
  }

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

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

  public function isBannedEmail( $email )
  {
    global $db;

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

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

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

  public function isBannedLogin( $login )
  {
    global $db;

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

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

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

  public function updateVisitCounter() {
    global $db;

    $query = $db -> prepare( 'UPDATE pcms_settings SET value = value + 1 WHERE param = :param' );
    $query -> bindValue( ':param' , 'visit_count' , \PDO::PARAM_STR );
    $query -> execute();
    $query -> closeCursor();

    self::setSessionVar( 'visit_counter' , true );
  }

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

    $sKey = 'getBanners';
    if ( !$aBanners = $cache -> fetch($sKey) )
    {
      $query = $db -> prepare('SELECT title, link, image FROM pcms_banner WHERE enabled = :enabled ORDER BY o');
      $query -> bindValue(':enabled', 1 , \PDO::PARAM_STR);
      $query -> execute();
      if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
        $aBanners[] = $row;
      $query -> closeCursor();
      $cache -> store($sKey, $aBanners, $config['cache_expire']);
    }
    return $aBanners;
  }

  public function getIp()
  {
    if ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
      $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else
      $ip = $_SERVER['REMOTE_ADDR'];

    return $ip;
  }

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

  public function getRandomKeyWord( $keywords )
  {
    $keywords = explode( ',' , $keywords );
    if ( is_array( $keywords ) )
      return $keywords[ rand( 0 , count( $keywords ) -1 ) ];
  }

  public 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;
      }
    }
  }
}
?>