<?
$xajax = new xajax();
$xajax -> register( XAJAX_FUNCTION, 'sendContactForm' );
$xajax -> register( XAJAX_FUNCTION, 'sendGuestBookEntry' );
$xajax -> register( XAJAX_FUNCTION, 'changeLang');
$xajax -> register( XAJAX_FUNCTION, 'checkRegisterForm' );
$xajax -> register( XAJAX_FUNCTION, 'registerUser' );
$xajax -> register( XAJAX_FUNCTION, 'recoverPassword' );
$xajax -> register( XAJAX_FUNCTION, 'loginUser' );
$xajax -> register( XAJAX_FUNCTION, 'logout' );
$xajax -> register( XAJAX_FUNCTION, 'closeAdvert' );
$xajax -> register( XAJAX_FUNCTION, 'setCookieInf' );

if ( $user && $user -> _values['admin'] )
{
  $xajax -> register( XAJAX_FUNCTION, 'saveArticleTranslation' );
  $xajax -> register( XAJAX_FUNCTION, 'saveLayout' );
  $xajax -> register( XAJAX_FUNCTION, 'saveArticle' );
  $xajax -> register( XAJAX_FUNCTION, 'deleteArticleImg' );
  $xajax -> register( XAJAX_FUNCTION, 'moveArticlesToArchive' );
  $xajax -> register( XAJAX_FUNCTION, 'deleteArticles' );
  $xajax -> register( XAJAX_FUNCTION, 'articleFileInfo' );
  $xajax -> register( XAJAX_FUNCTION, 'saveArticleFileInfo' );
  $xajax -> register( XAJAX_FUNCTION, 'deleteArticleFile' );
  $xajax -> register( XAJAX_FUNCTION, 'savePageOrder' );
  $xajax -> register( XAJAX_FUNCTION, 'deleteTranslations' );
  $xajax -> register( XAJAX_FUNCTION, 'generateSeoLink' );
  $xajax -> register( XAJAX_FUNCTION, 'savePagesCookie' );
  $xajax -> register( XAJAX_FUNCTION, 'saveMenuCookie' );
}

if ( file_exists( '../functions/xajax-articles.php' ) )
  include '../functions/xajax-articles.php';

include 'xajax-newsletter.php';
include 'xajax-site.php';
include 'xajax-contact.php';
$xajax -> processRequest();
$xajax -> configure( 'javascript URI', '../resources/xajax/' );

function saveMenuCookie( $id )
{
  $array = unserialize( $_COOKIE[ 'menu_definition' ] );
  
  if ( $array[ $id ] == 0 )
    $array[ $id ] = 1;
  else
    $array[ $id ] = 0;
  
  $array = serialize( $array );
  
  setcookie( 'menu_definition', $array, time() + 3600 * 24 * 365 );
}

function savePagesCookie( $id )
{
  $array = unserialize( $_COOKIE[ 'pages_definition' ] );
  
  if ( $array[ $id ] == 0 )
    $array[ $id ] = 1;
  else
    $array[ $id ] = 0;
  
  $array = serialize( $array );
  
  setcookie( 'pages_definition', $array, time() + 3600 * 24 * 365 );
}

function generateSeoLink( $lang, $title )
{
  global $db;
  
  $seo_link = \System::seo( $title );
  
  while ( !$seo_link_check )
  {
    $query = $db -> prepare( 'SELECT id FROM pp_pages_langs WHERE seo_link = :seo_link' );
    $query -> bindValue( ':seo_link', $seo_link, \PDO::PARAM_STR );
    $query -> execute();
    if ( $query -> rowCount() )
      $seo_link = \System::seo( $title ) . '-' . ( ++$i );
    else
      $seo_link_check = true;
  }
  
  $seo_link_check = false;
  
  while ( !$seo_link_check )
  {
    $query = $db -> prepare( 'SELECT id FROM pp_articles_langs WHERE seo_link = :seo_link' );
    $query -> bindValue( ':seo_link', $seo_link, \PDO::PARAM_STR );
    $query -> execute();
    if ( $query -> rowCount() )
      $seo_link = \System::seo( $title ) . '-' . ( ++$i );
    else
      $seo_link_check = true;
  }
  
  $objResponse = new xajaxResponse();
  $objResponse -> script( '$( "#seo_link_' . $lang . '" ).val( "' . $seo_link . '" );' );
  return $objResponse;
}

function setCookieInf()
{
  setcookie( "cookie_information", "true", mktime( 0, 0, 0, 12, 31, 2115 ) );
}

function savePageOrder( $pages, $id_menu )
{
  global $db;
  
  if ( is_array( $pages ) )
  {    
    $query = $db -> prepare( 'UPDATE pp_pages SET o = 0 WHERE id_menu = :id_menu' );
    $query -> bindValue( ':id_menu', $id_menu, \PDO::PARAM_INT );
    $query -> execute();
    $query -> closeCursor();
        
    for ( $i = 0; $i < count( $pages ); $i++ )
    {
      if ( $pages[$i]['item_id'] )
      {
        $pages[$i]['parent_id'] ? $parent_id = $pages[$i]['parent_id'] : $parent_id = 0;
        
        if ( $pages[$i]['item_id'] && $pages[$i]['depth'] > 1 )
        {
          
          if ( $pages[$i]['depth'] == 2 )
            $parent_id = 0;
          
          $x++;
          
          $query = $db -> prepare( 'UPDATE pp_pages SET o = :o, parent_id = :parent_id WHERE id = :id' );
          $query -> bindValue( ':id',         $pages[$i]['item_id'],  \PDO::PARAM_INT );
          $query -> bindValue( ':parent_id',  $parent_id,             \PDO::PARAM_INT );
          $query -> bindValue( ':o',          $x,                     \PDO::PARAM_INT );
          $query -> execute();
          $query -> closeCursor();
        }
      }
    }
  }
  
  $objResponse = new xajaxResponse();
  $objResponse -> script( '$( ".jqibox" ).remove();;' );
  return $objResponse;
}

function deleteArticleFile( $id )
{
  global $db;
  
  $query = $db -> prepare( 'SELECT * 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'] ) )
      unlink(  "../" . $row['file'] );
  }
  $query -> closeCursor();

  $query = $db -> prepare( 'DELETE FROM pp_articles_file WHERE id = :id' );
  $query -> bindValue( ':id' , $id , \PDO::PARAM_INT );
  $query -> execute();
  $query -> closeCursor();  

  \System::deleteCacheAdmin();
  \System::deleteCache();

  $objResponse  = new xajaxResponse();
  $objResponse -> script( '$( "#file_li_' . $id . '").remove(); jQuery( "#file_edit_id").val( "" ); jQuery( "#name" ).val( "" ); jQuery( ".plik_bg, .plik_edycja" ).hide();' );
  return $objResponse;
}

function saveArticleFileInfo( $id, $name )
{
  global $db;
 
  $query = $db -> prepare( 'UPDATE pp_articles_file SET name = :name WHERE id = :id' );
  $query -> bindValue( ':id',    $id,     \PDO::PARAM_INT );
  $query -> bindValue( ':name',  $name,   \PDO::PARAM_STR );
  $query -> execute();
  $query -> closeCursor();  
    
  $objResponse  = new xajaxResponse();
  $objResponse -> script( 'jQuery( "#file_edit_id").val( "" ); jQuery( "#name" ).val( "" ); jQuery( ".plik_bg, .plik_edycja" ).hide();' );
  return $objResponse;
}

function articleFileInfo( $id )
{
  global $db;
  
  $query = $db -> prepare( 'SELECT * FROM pp_articles_file WHERE id = :id' );
  $query -> bindValue( ':id', $id, \PDO::PARAM_INT );
  $query -> execute();
  if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
    $file = $row;
  $query -> closeCursor();
    
  $objResponse  = new xajaxResponse();
  $objResponse -> script( 'jQuery( "#name" ).val( "' . $file['name'] . '" );' );
  return $objResponse;  
}

function deleteArticles( $articles )
{
  $articles = explode( ':', $articles );
  if ( is_array( $articles ) ) foreach ( $articles as $art )
   \admin\factory\Articles::deleteArticle( $art );

  $objResponse  = new xajaxResponse();
  $objResponse -> script( 'document.location.href="./";' );
  return $objResponse;
}

function deleteTranslations( $translations )
{
  $translations = explode( ':', $translations );
  if ( is_array( $translations ) ) foreach ( $translations as $translation )
   \admin\factory\Languages::deleteTranslation( $translation );

  $objResponse  = new xajaxResponse();
  $objResponse -> script( 'document.location.href="./";' );
  return $objResponse;
}

function moveArticlesToArchive( $articles )
{
  $articles = explode( ':', $articles );
  if ( is_array( $articles ) ) foreach ( $articles as $art )
   \admin\factory\Articles::setAsArchive( $art );   

  $objResponse  = new xajaxResponse();
  $objResponse -> script( 'document.location.href="./";' );
  return $objResponse;
}

function closeAdvert()
{
  \System::setSessionVar( 'advert_close' , true );
}

function deleteArticleImg( $id )
{
  global $db;
  
  $query = $db -> prepare( 'SELECT * FROM pp_articles_img WHERE id = :id' );
  $query -> bindValue( ':id' , $id , \PDO::PARAM_INT );
  $query -> execute();
  if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
  {
    if ( file_exists( "../" . $row['src'] ) )
      unlink(  "../" . $row['src'] );
  }
  $query -> closeCursor();

  $query = $db -> prepare( 'DELETE FROM pp_articles_img WHERE id = :id' );
  $query -> bindValue( ':id' , $id , \PDO::PARAM_INT );
  $query -> execute();
  $query -> closeCursor();  

  $objResponse  = new xajaxResponse();
  $objResponse -> script( '$( "#li_' . $id . '").remove();' );
  return $objResponse;
}

function logout()
{
  \System::deleteSessionVar( 'user' );
  $objResponse  = new xajaxResponse();
  $message      = 'document.location.href="' . \System::getMainPage() . '";';
  $objResponse -> script( $message );
  return $objResponse;
}

function loginUser( $login, $password ) 
{
  global $db, $lang;

  $objResponse  = new xajaxResponse();
  $login        = \System::saveString( $login, true );
  $password     = \System::saveString( $password, true );
  
  $query = $db -> prepare( 'SELECT * FROM pp_users WHERE login = :login AND password = :password AND enabled = "1"' );
  $query -> bindValue( ':login',    $login,            \PDO::PARAM_STR );
  $query -> bindValue( ':password', md5( $password ),  \PDO::PARAM_STR );
  $query -> execute();
  if ( $query -> rowCount() )
  {
    $user = \user\FUser::login( $login, $password );
    \System::setSessionVar( 'user' , $user );
    $message = 'location.reload();';
  } 
  else 
  {
    $message = '$( ".jqibox" ).remove();;';
    $message .= "$.prompt('" . $lang -> getTrans( 'T_BRAK_UZYTKOWNIKA_KONTO_NIEAKTYWNE' ) . "',{ buttons: { " . $lang -> getTrans( 'T_ZAMKNIJ' ) . ": true }, focus: 1 });";
    $message .= 'setTimeout(function(){$( ".jqibox" ).remove();;},3000);';
  }
  $query -> closeCursor();
  
  $objResponse -> script( $message );

  return $objResponse;
}

function recoverPassword( $email )
{
  global $db , $lang;

  $objResponse  = new xajaxResponse();
  $message      = '';
  $hash         = \System::gen_hash( 16 );
  $email        = \System::saveString( $email , true );

  if ( !\System::checkEmail( $email ) )
  {
    $message = '$( ".jqibox" ).remove();;';
    $message .= "$.prompt('" . $lang -> getTrans( 'T_NIEPRAWIDLOWY_EMAIL_REJESTRACJA' ) . "',{ buttons: { " . $lang -> getTrans( 'T_ZAMKNIJ' ) . ": true }, focus: 1 });";
    $message .= 'setTimeout(function(){$( ".jqibox" ).remove();;},3000);';
  }
  else
  {
    if ( !System::isEmailFree( $email ) )
    {
      $query = $db -> prepare( 'UPDATE pp_users SET recover = :recover WHERE email = :email' );
      $query -> bindValue( ':recover' , $hash   , \PDO::PARAM_STR );
      $query -> bindValue( ':email'   , $email  , \PDO::PARAM_STR );
      $query -> execute();
      $query -> closeCursor();

      $query = $db -> prepare( 'SELECT id FROM pp_users WHERE email = :email' );
      $query -> bindValue( ':email' , $email , \PDO::PARAM_STR );
      $query -> execute();
      if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
        $user_id = $row['id'];
      $query -> closeCursor();

      $link = "<a href='http://" . $_SERVER['SERVER_NAME'] . "/index.php?recover_password=" . $hash . "&value=" . $user_id . "'>" . $lang -> getTrans( 'T_RESETUJ' ) . "</a>";

      $tresc = str_replace( '{LINK}'    , $link                                     , $lang -> getTrans( 'T_ODZYSKIWANIE_TRESC_UZYTKOWNIK' ) );
      $tresc = str_replace( '{SERWER}'  , \System::getSystemSettings( 'firm_name' ) , $tresc );

      \System::sendEmail(
              $email ,
              str_replace( '{SERWER}' , \System::getSystemSettings( 'firm_name' ) , $lang -> getTrans( 'T_ODZYSKIWANIE_HASLA' ) ),
              $tresc
            );

      $message = '$( ".jqibox" ).remove();;';
      $message .= "$.prompt('" . $lang -> getTrans( 'T_ODZYSKIWANIE_HASLA_ALERT' ) . "',{ buttons: { " . $lang -> getTrans( 'T_ZAMKNIJ' ) . ": true }, focus: 1 });";
      $message .= 'setTimeout(function(){$( ".jqibox" ).remove();;},3000);';
    }
    else
    {
      $message = '$( ".jqibox" ).remove();;';
      $message .= "$.prompt('" . $lang -> getTrans( 'T_BRAK_EMAILA_W_BAZIE' ) . "',{ buttons: { " . $lang -> getTrans( 'T_ZAMKNIJ' ) . ": true }, focus: 1 });";
      $message .= 'setTimeout(function(){$( ".jqibox" ).remove();;},3000);';
    }
  }
  $objResponse -> script( $message );

  return $objResponse;
}

function registerUser( $login , $password , $email )
{
  global $db , $lang;

  $login    = \System::saveString( $login , true );
  $password = \System::saveString( $password , true );
  $email    = \System::saveString( $email , true );
  $hash     = \System::gen_hash( 16 );

  $c_login    = \System::checkLoginRegister( $login );
  $c_password = \System::checkPasswordRegister( $password , $password );
  $c_email    = \System::checkEmailRegister( $email );

  $objResponse = new xajaxResponse();

  if ( $c_login == 0 && $c_password == 0 && $c_email == 0 && \System::getSystemSettings( 'register' ) != 0 )
  {
    $query = $db -> prepare( 'INSERT INTO pp_users ( login , password , email , registered , hash ) VALUES ( :login , :password , :email , :registered , :hash )' );
    $query -> bindValue( ':login'       , $login              , \PDO::PARAM_STR );
    $query -> bindValue( ':password'    , md5( $password )    , \PDO::PARAM_STR );
    $query -> bindValue( ':email'       , $email              , \PDO::PARAM_STR );
    $query -> bindValue( ':registered'  , \System::getDate()  , \PDO::PARAM_STR );
    $query -> bindValue( ':hash'        , $hash               , \PDO::PARAM_STR );
    $query -> execute();
    $query -> closeCursor();

    $user_id = $db -> lastInsertId();

    if ( \System::getSystemSettings( 'register' ) == 1 )
    {

      \System::sendEmail(
              \System::getSystemSettings( 'admin_email' ) ,
              str_replace( '{SERWER}' , \System::getSystemSettings( 'firm_name' ) , $lang -> getTrans( 'T_REJESTRACJA_UZYTKOWNIKA' ) ),
              str_replace( '{LOGIN}'  , $login                                    , $lang -> getTrans( 'T_REJESTRACJA_TRESC_ADMIN' ) )
            );

      $tresc = str_replace( '{LOGIN}'   , $login                                    , $lang -> getTrans( 'T_REJESTRACJA_TRESC_UZYTKOWNIK' ) );
      $tresc = str_replace( '{SERWER}'  , \System::getSystemSettings( 'firm_name' ) , $tresc );
      $tresc = str_replace( '{HASLO}'   , $password                                 , $tresc );

      \System::sendEmail(
              $email ,
              str_replace( '{SERWER}' , \System::getSystemSettings( 'firm_name' ) , $lang -> getTrans( 'T_REJESTRACJA_UZYTKOWNIKA' ) ),
              $tresc
            );
    }
    else if ( \System::getSystemSettings( 'register' ) == 2 )
    {

      $link = "<a href='http://" . $_SERVER['SERVER_NAME'] . "/index.php?account_activation=" . $hash . "&value=" . $user_id . "'>" . $lang -> getTrans( 'T_AKTYWUJ' ) . "</a>";

      $tresc = str_replace( '{LOGIN}'   , $login                                    , $lang -> getTrans( 'T_REJESTRACJA_TRESC_UZYTKOWNIK_AKTYWACJA' ) );
      $tresc = str_replace( '{SERWER}'  , \System::getSystemSettings( 'firm_name' ) , $tresc );
      $tresc = str_replace( '{HASLO}'   , $password                                 , $tresc );
      $tresc = str_replace( '{LINK}'    , $link                                     , $tresc );

      \System::sendEmail(
              $email ,
              str_replace( '{SERWER}' , \System::getSystemSettings( 'firm_name' ) , $lang -> getTrans( 'T_REJESTRACJA_UZYTKOWNIKA' ) ),
              $tresc
            );
    }

    $message = '$( ".jqibox" ).remove();;';
    $message .= "$.prompt('" . $lang -> getTrans( 'T_REJESTRACJA_SUKCES' ) . "',{ buttons: { " . $lang -> getTrans( 'T_ZAMKNIJ' ) . ": true }, focus: 1 });";
    $message .= 'setTimeout(function(){$( ".jqibox" ).remove();;},3000);';
  }
  else
  {
    $message = '$( ".jqibox" ).remove();;';
    $message .= "$.prompt('" . $lang -> getTrans( 'T_BLEDY_REJESTRACJA_FORMULARZ' ) . "',{ buttons: { " . $lang -> getTrans( 'T_ZAMKNIJ' ) . ": true }, focus: 1 });";
    $message .= 'setTimeout(function(){$( ".jqibox" ).remove();;},3000);';
  }
  $objResponse -> script( $message );

  return $objResponse;
}

function checkRegisterForm( $param , $value , $value2 = '' )
{
  global $lang;

  $value  = \System::saveString( $value   , true );
  $value2 = \System::saveString( $value2  , true );

  if ( $param == 'login' )
  {
    $r_login = false;
    $c_login = \System::checkLoginRegister( $value );

    if ( $c_login == 1 )
      $out = '<div class="alert">' . $lang -> getTrans( 'T_NIEPRAWIDLOWY_LOGIN_REJESTRACJA' ) . '</div>';
    else if ( $c_login == 2 )
      $out = '<div class="alert">' . $lang -> getTrans( 'T_LOGIN_ZAJETY' ) . '</div>';
    else if ( $c_login == 0 )
      $r_login = true;
    else
      $out = '<div class="alert">' . $lang -> getTrans( 'T_NIEPRAWIDLOWY_LOGIN_REJESTRACJA' ) . '</div>';
  }

  if ( $param == 'password' )
  {
    $r_password = false;
    $c_password = \System::checkPasswordRegister( $value , $value2 );

    if ( $c_password == 1 )
      $out = '<div class="alert">' . $lang -> getTrans( 'T_NIEPRAWIDLOWE_HASLO_REJESTRACJA' ) . '</div>';
    else if ( $c_password == 2 )
      $out = '<div class="alert">' . $lang -> getTrans( 'T_HASLA_ROZNE' ) . '</div>';
    else if ( $c_password == 0 )
      $r_password = true;
    else
      $out = '<div class="alert">' . $lang -> getTrans( 'T_NIEPRAWIDLOWE_HASLO_REJESTRACJA' ) . '</div>';
  }

  if ( $param == 'email' )
  {
    $r_email    = false;
    $c_password = \System::checkEmailRegister( $value );

    if ( $c_password == 1 )
      $out .= '<div class="alert">' . $lang -> getTrans( 'T_NIEPRAWIDLOWY_EMAIL_REJESTRACJA' ) . '</div>';
    else if ( $c_password == 2 )
      $out = '<div class="alert">' . $lang -> getTrans( 'T_EMAIL_ZAJETY' ) . '</div>';
    else if ( $c_password == 0 )
      $r_email = true;
    else
      $out .= '<div class="alert">' . $lang -> getTrans( 'T_NIEPRAWIDLOWY_EMAIL_REJESTRACJA' ) . '</div>';
  }


  $objResponse = new xajaxResponse();
  $objResponse -> script( '$( ".jqibox" ).remove();;' );
  $objResponse -> assign( "r_" . $param . "_check" , 'innerHTML' , $out );
  if ( $param == "login" )
    $objResponse -> script( '$( "#r_login" ).val( "' . $value . '");' );

  if ( $param == 'login' && $r_login )
    $objResponse -> script( 'r_login = true; $( "#r_password" ).focus();' );
  else if ( $param == "login" )
    $objResponse -> script( 'r_login = false; $( "#r_login" ).focus();' );
  if ( $param == 'password' && $r_password )
    $objResponse -> script( 'r_password = true; $( "#r_email" ).focus();' );
  else if ( $param == "password" )
    $objResponse -> script( 'r_password = false; $( "#r_password" ).focus();' );
  if ( $param == 'email' && $r_email )
    $objResponse -> script( 'r_email = true' );
  else if ( $param == "email ")
    $objResponse -> script( 'r_email = false; $( "#r_email" ).focus();' );

  return $objResponse;
}

function changeLang( $lang_id )
{
  \System::deleteSessionVar('lang');
  $objResponse = new xajaxResponse();
  $lang = \language\FLanguage::loadLang($lang_id, true);
  \System::setSessionVar( 'lang' , $lang , true );

  $objResponse -> script( "document.location.href='index.php';" );
  return $objResponse;
}

function saveArticle( $id, $enabled, $comments_enabled, $print, $show_title, $show_date, $pages , $show_author , $keep_archive, $layout, $replace_menu )
{
  global $db, $user;
  
  $new = false;
  
  if ( $id )
  {
    $sql = 'UPDATE
                pp_articles
              SET
                show_title = :show_title, enabled = :enabled, print = :print, show_date = :show_date, date_modify = :date_modify, show_author = :show_author, keep_archive = :keep_archive,
                id_layout = :id_layout, replace_menu_title = :replace_menu, comments_enabled = :comments_enabled
              WHERE
                id = :id';
    $query = $db -> prepare( $sql );
    $query -> bindValue( ':show_title',       $show_title,          \PDO::PARAM_STR );
    $query -> bindValue( ':enabled',          $enabled,             \PDO::PARAM_STR );
    $query -> bindValue( ':print',            $print,               \PDO::PARAM_STR );
    $query -> bindValue( ':show_date',        $show_date,           \PDO::PARAM_STR );
    $query -> bindValue( ':show_author',      $show_author,         \PDO::PARAM_STR );
    $query -> bindValue( ':keep_archive',     $keep_archive,        \PDO::PARAM_STR );
    $query -> bindValue( ':id',               $id,                  \PDO::PARAM_INT );
    $query -> bindValue( ':id_layout',        $layout,              \PDO::PARAM_INT );
    $query -> bindValue( ':replace_menu',     $replace_menu,        \PDO::PARAM_INT );
    $query -> bindValue( ':comments_enabled', $comments_enabled,    \PDO::PARAM_INT );
    $query -> bindValue( ':date_modify',      \System::getDate(),   \PDO::PARAM_STR );
    $query -> execute();
    $query -> closeCursor();
  }
  else
  {
    $sql = 'INSERT INTO
                pp_articles
                  ( show_title , enabled , print , show_date , date_add , date_modify , show_author , author , keep_archive, id_layout, comments_enabled )
              VALUES
                  ( :show_title , :enabled , :print , :show_date , :date_add , :date_modify , :show_author , :author , :keep_archive, :id_layout, :comments_enabled )';
    $query = $db -> prepare( $sql );
    $query -> bindValue( ':show_title',       $show_title,            \PDO::PARAM_STR );
    $query -> bindValue( ':enabled',          $enabled,               \PDO::PARAM_STR );
    $query -> bindValue( ':print',            $print,                 \PDO::PARAM_STR );
    $query -> bindValue( ':show_date',        $show_date,             \PDO::PARAM_STR );
    $query -> bindValue( ':show_author',      $show_author,           \PDO::PARAM_STR );
    $query -> bindValue( ':author',           $user -> _values['id'], \PDO::PARAM_STR );
    $query -> bindValue( ':keep_archive',     $keep_archive,          \PDO::PARAM_STR );
    $query -> bindValue( ':id_layout',        $layout,                \PDO::PARAM_INT );
    $query -> bindValue( ':comments_enabled', $comments_enabled,      \PDO::PARAM_INT );
    $query -> bindValue( ':date_add',         \System::getDate(),     \PDO::PARAM_STR );
    $query -> bindValue( ':date_modify',      \System::getDate(),     \PDO::PARAM_STR );
    $query -> execute();
    $query -> closeCursor();

    $id   = $db -> lastInsertId();
    
    $query = $db -> query( 'SELECT * FROM pp_articles_img WHERE id_article = 0' );
    if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
    {
      $dir   = 'upload/galeries/article_' . $id  . '/';
      if ( !is_dir( "../ " . $dir ) )
        mkdir( "../" . $dir , 0755 , true );
      
      $file = explode( '/', $row['src'] );
      $file = $file[3];
      
      if ( file_exists( '../' . $row['src'] ) )
      {
        rename( '../' . $row['src'], '../' . $dir . $file );    
        $query2 = $db -> prepare( 'UPDATE pp_articles_img SET id_article = :id_article, src = :src WHERE id = :id' );
        $query2 -> bindValue( ':id_article', $id,          \PDO::PARAM_INT );
        $query2 -> bindValue( ':src',        $dir . $file, \PDO::PARAM_STR );
        $query2 -> bindValue( ':id',         $row['id'],   \PDO::PARAM_INT );
        $query2 -> execute();
        $query2 -> closeCursor();        
      }
    }
    $query -> closeCursor();
    
    $new  = true;
  }

  $pages  = explode(':', $pages);
  $not_in = '0';

  if ( is_array( $pages ) ) foreach ( $pages as $pag )
  {
    if ( $not_in )
      $not_in .= ',';
    $not_in .= $pag;
  }

  if ( $not_in != '' )
  {
    $query = $db -> prepare( 'DELETE FROM pp_articles_pages WHERE article_id = :article_id AND page_id NOT IN (' . $not_in . ')' );
    $query -> bindValue( ':article_id' , (int)$id , \PDO::PARAM_INT );
    $query -> execute();
    $query -> closeCursor();
  }

  $query = $db -> prepare( 'SELECT page_id FROM pp_articles_pages WHERE article_id = :article_id' );
  $query -> bindValue( ':article_id' , (int)$id , \PDO::PARAM_INT );
  $query -> execute();
  if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
    $tab_tmp[] = $row['page_id'];
  $query -> closeCursor();

  $query  = $db -> prepare( 'INSERT INTO pp_articles_pages ( page_id, article_id, o ) VALUES ( :page_id, :article_id, :o )' );
  foreach ( $pages as $pag )
  {
    if ( !is_array( $tab_tmp ) || !in_array( $pag , $tab_tmp ) )
    {
      $o = \admin\factory\Articles::getMaxArticleOrder( $pag ) + 1;
      $query -> bindValue( ':page_id'     , $pag     , \PDO::PARAM_INT );
      $query -> bindValue( ':article_id'  , (int)$id , \PDO::PARAM_INT );
      $query -> bindValue( ':o'           , $o       , \PDO::PARAM_INT );
      $query -> execute();
      $o++;
    }
  }
  $query -> closeCursor();

  \System::deleteCacheAdmin();

  $objResponse = new xajaxResponse();
  $objResponse -> script( '$( "#idk" ).val( ' . $id . ' ); saveArticleTranslation( ' . $new . ');' );
  return $objResponse;
}

function saveArticleTranslation( $lang_id , $id , $title , $meta_description , $meta_keywords , $text , $message , $keep_archive, $version, $seo_link, $new )
{
  global $db;
  
  if ( is_null( $version ) )
    $version = 1;

  $query = $db -> prepare( 'SELECT id, version FROM pp_articles_langs WHERE article_id = :article_id AND lang_id = :lang_id ORDER BY version DESC LIMIT 1' );
  $query -> bindValue( ':article_id'  , $id       , \PDO::PARAM_INT );
  $query -> bindValue( ':lang_id'     , $lang_id  , \PDO::PARAM_STR );
  $query -> execute();
  if ( $query -> rowCount() && !$keep_archive )
  {
    while ( $row = $query -> fetch() )
    {
      if ( $seo_link == 'link seo' )
        $seo_link = '';

      if ( $meta_description == 'meta description' )
        $meta_description = '';

      if ( $meta_keywords == 'meta keywords' )
        $meta_keywords = '';
      
      $sql = 'UPDATE
                pp_articles_langs
              SET
                text = :text, meta_description = :meta_description, meta_keywords = :meta_keywords, title = :title, seo_link = :seo_link
              WHERE
                article_id = :article_id AND lang_id = :lang_id AND version = :version';
      $query2 = $db -> prepare( $sql );
      $query2 -> bindValue( ':text'             , stripslashes( $text )             , \PDO::PARAM_STR );
      $query2 -> bindValue( ':meta_description' , stripslashes( $meta_description ) , \PDO::PARAM_STR );
      $query2 -> bindValue( ':meta_keywords'    , stripslashes( $meta_keywords )    , \PDO::PARAM_STR );
      $query2 -> bindValue( ':title'            , stripslashes( $title )            , \PDO::PARAM_STR );
      $query2 -> bindValue( ':lang_id'          , $lang_id                          , \PDO::PARAM_STR );
      $query2 -> bindValue( ':article_id'       , $id                               , \PDO::PARAM_INT );
      $query2 -> bindValue( ':version'          , $row['version']                   , \PDO::PARAM_INT );
      $query2 -> bindValue( ':seo_link'         , $seo_link                         , \PDO::PARAM_STR );
      $query2 -> execute();
      $query2 -> closeCursor();
    }
  }
  else
  {
    $sql = 'INSERT INTO
              pp_articles_langs
                ( text, meta_description, meta_keywords, title, article_id, lang_id, version, seo_link )
            VALUES
                ( :text, :meta_description, :meta_keywords, :title, :article_id, :lang_id, :version, :seo_link )';
    $query2 = $db -> prepare( $sql );
    $query2 -> bindValue( ':text'             , stripslashes( $text )             , \PDO::PARAM_STR );
    $query2 -> bindValue( ':meta_description' , stripslashes( $meta_description ) , \PDO::PARAM_STR );
    $query2 -> bindValue( ':meta_keywords'    , stripslashes( $meta_keywords )    , \PDO::PARAM_STR );
    $query2 -> bindValue( ':title'            , stripslashes( $title )            , \PDO::PARAM_STR );
    $query2 -> bindValue( ':seo_link'         , $seo_link         , \PDO::PARAM_STR );
    $query2 -> bindValue( ':lang_id'          , $lang_id          , \PDO::PARAM_STR );
    $query2 -> bindValue( ':article_id'       , $id               , \PDO::PARAM_INT );
    $query2 -> bindValue( ':version'          , $version          , \PDO::PARAM_INT );
    $query2 -> execute();
    $query2 -> closeCursor();
  }
  \System::rewriteHtacces();
  
  if ( $message )
  {
    $objResponse = new xajaxResponse();
    $objResponse -> script( '$( "#version" ).val(' . ( $version + 1 ) . ');' );
    $objResponse -> script( '$( ".jqibox" ).remove();;' );
    if ( $new )
      $objResponse -> script( 'document.location.href="./?rw=edit&id=' . $id . '";' );
    return $objResponse;
  }
}

function sendGuestBookEntry( $signature , $text , $code , $check , $val_check )
{
  global $lang , $securimage;

  if ( $val_check != \System::getSessionVar( 'token' ) )
    return false;

  $signature  = \System::saveString( $signature , true );
  $text       = \System::saveString( $text , true );

  if ( $signature && $text && $code )
  {
    $signature = '~' . $signature;

    if ( $check != \System::getSessionVar( 'guest_book_time' ) )
    {
      $date = \System::getSessionVar( 'guest_book_time' );
      if ( !$date )
        $date = "1980-00-00 00:00:00";
      if ( \System::getDateDiff( $date , date( 'Y-m-d H:i:s' ) ) > 1 )
      {
        if ( $securimage -> check( $code ) == false )
          $out = $lang -> getTrans( 'T_NIEPRAWIDLOWY_KOD' );
        else
        {
          \guestbook\FGuestBook::addEntry( $signature , $text );
          \System::setSessionVar( 'guest_book_time' , $check );
          \System::deleteCache();
          $out = $lang -> getTrans( 'T_DZIEKUJEMY_ZA_WPIS' );
        }
      }
      else
        $out = $lang -> getTrans( 'T_ZACZEKAJ_MIN_WPIS' );
    }
    else
      $out = $lang -> getTrans( 'T_TEN_WPIS_ZOSTAL_JUZ_DODANY' );
  }
  else
    $out = $lang -> getTrans( 'T_BRAK_WSZYSTKICH_DANYCH' );

  $objResponse  = new xajaxResponse();
  $message      = '$( ".jqibox" ).remove();;';
  $message      .= "$.prompt('" . $out . "',{ buttons: { " . $lang -> getTrans( 'T_ZAMKNIJ' ) . ": true }, focus: 1 });";
  $message      .= 'setTimeout(function(){$( ".jqibox" ).remove();;},3000);';
  $objResponse -> script( $message );
  return $objResponse;
}

function sendContactForm( $email, $subject, $text, $check )
{
  global $lang;

  $email = \System::saveString( $email, true );
  
  if ( \System::checkEmail( $email ) && $email && $subject && $text )
  {
    if ( \System::getSessionVar( 'check' ) != $check )
    {
      $admin_email = \admin\factory\Settings::getSystemSettings( 'admin_email' );
      \System::sendEmail( $admin_email, $subject, $text, $email );
      \System::setSessionVar( 'check' , $check );
      $out = $lang -> getTrans( 'T_ZAPYTANIE_ZOSTALO_WYSLANE' );
    }
    else
      $out = $lang -> getTrans( 'T_TEN_FORMULARZ_BYL_JUZ_WYSLANY' );
  }
  else
  {
    if ( \System::checkEmail( $email ) )
      $out = $lang -> getTrans( 'T_NIEPOPRAWNY_ADRES_EMAIL' );
    else
      $out = $lang -> getTrans( 'T_BRAK_WSZYSTKICH_DANYCH' );
  }

  $objResponse = new xajaxResponse();
  $message = '$(".jqibox").remove();';
  $message .= "$.prompt('" . $out . "',{ title: 'Komunikat', buttons: { " . $lang -> getTrans( 'T_ZAMKNIJ' ) . ": true }, focus: 1 });";
  $message .= 'setTimeout( function() { $( ".jqibox" ).remove() },3000 );';
  $objResponse -> script( $message );
  return $objResponse;
}

function saveLayout( $id, $name, $enabled, $html, $css, $js, $pages )
{
  global $db;
  
  $pages = explode( ':' , $pages );

  if ( $enabled )
  {
    $query = $db -> prepare( 'UPDATE pp_layouts SET enabled = :enabled' );
    $query -> bindValue( ':enabled', 0, \PDO::PARAM_STR );
    $query -> execute();
    $query -> closeCursor();
  }
  $html = addslashes( $html );

  $query = $db -> prepare( 'UPDATE pp_layouts SET name = :name , enabled = :enabled , html = :html , css = :css , javascript = :javascript WHERE id = :id' );
  $query -> bindValue( ':name',       $name,    \PDO::PARAM_STR );
  $query -> bindValue( ':enabled',    $enabled, \PDO::PARAM_STR );
  $query -> bindValue( ':html',       $html,    \PDO::PARAM_STR );
  $query -> bindValue( ':css',        $css,     \PDO::PARAM_STR );
  $query -> bindValue( ':javascript', $js,      \PDO::PARAM_STR );
  $query -> bindValue( ':id',         $id,      \PDO::PARAM_INT );
  $query -> execute();
  $query -> closeCursor();

  $query = $db -> prepare( 'DELETE FROM pp_layouts_pages WHERE layout_id = :layout_id' );
  $query -> bindValue( ':layout_id', $id, \PDO::PARAM_INT );
  $query -> execute();
  $query -> closeCursor();

  if ( is_array( $pages ) ) foreach ( $pages as $page )
  {
    $query = $db -> prepare( 'INSERT INTO pp_layouts_pages ( layout_id , page_id ) VALUES ( :layout_id , :page_id )' );
    $query -> bindValue( ':layout_id',  $id,    \PDO::PARAM_INT );
    $query -> bindValue( ':page_id',    $page,  \PDO::PARAM_INT );
    $query -> execute();
    $query -> closeCursor();
  }
    
  $objResponse = new xajaxResponse();
  $message = '$( ".jqibox" ).remove();;';
  $objResponse -> script( $message );

  \System::deleteCacheAdmin();
  return $objResponse;
}
?>