<?php
class DataBase
{
  public function SaveData( $db_edit_table , $db_edit_key , $db_edit_val , $db_edit_pols , $db_edit_pass , $db_edit_pols_t )
  {
    global $sys , $lang , $db;

    $sql = '';

    if ( is_array( $db_edit_pols ) ) foreach ( $db_edit_pols as $val )
    {
      if ( $sql && $val != 'image' )
        $sql .= ',';
      if ( $val != 'image' )
        $sql .= $val . "='" . addslashes( $sys -> saveString( $sys -> formGet( $val ) ) ) . "'";
    }

    if ( $db_edit_pass )
    {
      $name   = $db_edit_pass['nazwa1'];
      $pass1  = $sys -> saveString( $sys -> formGet( $name ) );
      $pass2  = $sys -> saveString( $sys -> formGet( $name . '_repeat' ) );
      if ( $pass1 != $pass2 )
        $sys -> setAlert( $lang -> getTrans( 'T_HASLA_ROZNE' ) );
      else
      {
        if ( strlen($pass1) >= 5 )
        {
          if ( $sql )
            $sql .= ',';
          $sql .= $name . "='" . md5($pass1) . "'";
        }
        else
        {
          if ( strlen( $pass1 ) < 5 )
            $sys -> setAlert( $lang -> getTrans( 'T_HASLA_ZA_KROTKIE' ) );
        }
      }
    }

    if ( $db_edit_table && $db_edit_key && $db_edit_val && $db_edit_pols )
    {
      $db_edit_table  = $sys -> saveString( $db_edit_table );
      $db_edit_key    = $sys -> saveString( $db_edit_key );
      $db_edit_val    = $sys -> saveString( $db_edit_val );

      $query = $db -> query( "UPDATE " . $db_edit_table . " SET " . $sql . " WHERE " . $db_edit_key . "='" . $db_edit_val . "'" );

      for ( $i = 0; $i < count( $db_edit_pols_t ); $i++ )
      {
        if ( $db_edit_pols_t[$i] == 'file' && is_array( $_FILES[$db_edit_pols[$i]] ) )
        {
          $file   = $_FILES[$db_edit_pols[$i]];
          if ( $file['name'] )
            $name   = explode( '.' , $file['name'] );
          if ( isset( $name ) && is_array( $name ) )
            $patch  = '../' . $sys -> formGet( 'image_folder' ) . $sys -> seo( $name[0]) . '.' . $name[1];

          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 ) or $x[0] < 2)
              {
                $query = $db -> prepare( "SELECT " . $db_edit_pols[$i] . " FROM " . $db_edit_table . " WHERE " . $db_edit_key . "='" . $db_edit_val . "'" );
                $query -> execute();
                if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
                {
                  $plik = '../' . $row[0];
                  if ( file_exists( $plik ) && $row[0] )
                  unlink( $plik );
                }
                $query -> closeCursor();

                if ( file_exists( $patch ) )
                unlink( $patch );

                rename( $file['tmp_name'] , $patch );
                chmod( $patch , 0755 );
                $patch = str_replace( '../' , '' , $patch );
                $query = $db -> query( "UPDATE " . $db_edit_table . " SET " . $db_edit_pols[$i] ."='" . $patch . "' WHERE " . $db_edit_key . "='" . $db_edit_val . "'" );
              }
            }
          }
        }
      }
      $sys -> setAlert( $lang -> getTrans( 'T_ZAKTUALIZOWANO_ELEMENT' ) );
    }
    $saveFlag = true;
    $sys -> deleteCacheAdmin();
    $sys -> deleteCache();
  }

  public function addData( $db_edit_table , $db_edit_pols , $db_edit_pols_hidden , $db_edit_pols_t , $time , $db_edit_pass = '' )
  {
    global $lang , $db;

    $flag   = true;
    $idk    = '';
    $key    = '';
    $val    = '';
    $value  = '';

    if ( $time == \System::getSessionVar( 'dbedit_add_time' ) ) return false;

    if ( is_array( $db_edit_pols ) ) foreach ( $db_edit_pols as $val )
    {
      if ( !$idk )
        $idk = $val;
      if ( $key )
        $key .= ',';
      if ( $value )
        $value .= ',';
      $key .= $val;
      $value .= "'" . \System::saveString( \System::formGet( $val ) ) . "'";
    }

    if ( is_array( $db_edit_pols_hidden ) ) foreach ( $db_edit_pols_hidden as $val )
    {
      if ( $key )
        $key .= ',';
      if ( $value )
        $value .= ',';
      $key .= $val;
      $value .= "'" . \System::saveString( \System::formGet( $val ) ) . "'";
    }

    if ( $db_edit_pass )
    {
      $name   = $db_edit_pass['nazwa1'];
      $pass1  = \System::saveString( \System::formGet( $name ) );
      $pass2  = \System::saveString( \System::formGet( $name . '_repeat' ) );
      if ( $pass1 != $pass2 )
      {
        \System::setAlert( $lang -> getTrans( 'T_HASLA_ROZNE' ) );
        $flag = false;
      }
      else
      {
        if ( strlen($pass1) >= 5 )
        {
          if ( $key )
            $key .= ',';
          $key .= $name;
          if ( $value )
            $value .= ',';
          $value .= "'" . md5( $pass1 ) . "'";
        }
        else
        {
          if ( $pass1 )
          {
            $flag = false;
            \System::setAlert( $lang -> getTrans( 'T_HASLA_ZA_KROTKIE' ) );
          }
        }
      }
    }

    if ( $db_edit_table && $db_edit_pols && $flag )
    {
    $check = true;
    $db_edit_table  = \System::saveString( $db_edit_table );
    try
    {
      $query = $db -> prepare( "INSERT INTO " . $db_edit_table . " (" . $key . ") VALUES (" . $value . ")");
      $query -> execute();
    }
    catch(PDOException $e)
    {
      $check = false;
    }

    $id = $db -> lastInsertId();
    $query -> closeCursor();

    for ( $i = 0; $i < count( $db_edit_pols_t ); $i++ )
    {
      if ( $db_edit_pols_t[$i] == 'file' && is_array($_FILES[$db_edit_pols[$i]]) )
      {
        $file   = $_FILES[$db_edit_pols[$i]];
        $name   = explode( '.' , $file['name'] );
        $patch  = '../' . \System::formGet( 'image_folder' ) . md5( mktime() ) . '.' . strtolower( $name[count( $name ) - 1] );

        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 )
          {
            if ( !is_dir( '../' . \System::formGet( 'image_folder' ) ) ) mkdir( '../' . \System::formGet( 'image_folder' ), 0775, true);
            $x = getimagesize( $file['tmp_name'] );
            if ( is_array( $x ) or $x[0] < 2)
            {
              if ( file_exists( $patch ) )
                unlink( $patch );

              @rename( $file['tmp_name'] , $patch );
              chmod( $patch , 0755 );
              $patch = str_replace( '../' , '' , $patch );

              $query = $db -> prepare( "UPDATE " . $db_edit_table . " SET " . $db_edit_pols[$i] . "='" . $patch . "' WHERE id='" . $id . "'" );
              $query -> execute();
              $query -> closeCursor();
            }
          }
        }
      }
    }
    if ( $check )
      \System::setAlert( $lang -> getTrans( 'T_DODANO_NOWY_ELEMENT' ) );
    else
      \System::setAlert( $lang -> getTrans( 'T_NIEPRAWIDLOWE_DANE' ) );
    $addFlag = true;
    }
    else
      \System::setAlert( $lang -> getTrans( 'T_NIEPRAWIDLOWE_DANE' ) );

    \System::setSessionVar( 'dbedit_add_time' , $time );
    \System::deleteCacheAdmin();
    \System::deleteCache();
  }
  
  public function updateSWL()
  {
    $db_t = \opdClass::create(
                        array(
                            'dsn' => 'mysql:host=22275.m.tld.pl;dbname=baza75_preselpro',
                            'user' => 'admin75_preselpro',
                            'password' => 'Legia1916',
                            'cache' => 'Temp/' ,
                            'debugConsole' => false
                            )
                      );
    $db_t -> query('SET NAMES utf8'); 
    
    $data   = base64_decode( file_get_contents( 'files/links.php' ) );
    $data   = @unserialize( $data );
    $delete = false;
    
    $query = $db_t -> prepare( 'SELECT 
                                  pad.id
                                FROM 
                                  pro_articles_downloads AS pad, pro_articles AS pa, pro_articles_groups AS pag 
                                WHERE 
                                  pa.group_id = pag.id AND pad.article_id = pa.id 
                                AND 
                                  ( ( swl_only_nonindexed = 1 AND indexed = 1 ) OR deleted = 1 ) 
                                AND 
                                  swl_link_count > 0' );
    $query -> execute();
    if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
    {
      $query2 = $db_t -> prepare( 'SELECT * FROM pro_articles_downloads_swl WHERE article_download_id = :article_download_id' );
      $query2 -> bindValue( ':article_download_id', $row['id'], \PDO::PARAM_INT );
      $query2 -> execute();
      if ( $query2 -> rowCount() ) while ( $row2 = $query2 -> fetch() )
      {
        if ( is_array( $data ) ) foreach ( $data as $key => $val )
        {
          if ( $key == $row2['link'] )
          {
            $query3 = $db_t -> prepare( 'DELETE FROM pro_articles_downloads_swl WHERE article_download_id = :article_download_id AND link = :link' );
            $query3 -> bindValue( ':article_download_id', $row['id'],     \PDO::PARAM_INT );
            $query3 -> bindValue( ':link',                $row2['link'],  \PDO::PARAM_STR );
            $query3 -> execute();
            $query3 -> closeCursor();
            
            $query3 = $db_t -> prepare( 'UPDATE pro_articles_downloads SET swl_link_count = swl_link_count - 1 WHERE id = :id' );
            $query3 -> bindValue( ':id', $row['id'], \PDO::PARAM_INT );
            $query3 -> execute();
            $query3 -> closeCursor(); print_r( $query3 -> errorInfo() );
            
            unset( $data[ $row2['link']] );
            $delete = true;
          }
        }
      }
      $query2 -> closeCursor();      
    }
    $query -> closeCursor();
    
    if ( $delete )
    { 
      $data = base64_encode( serialize( $data ) );
      $h    = fopen( 'files/links.php' , 'w' );
      if ( fwrite( $h , $data ) === false )
        throw new \Exception( 'Could not write to cache' );
      fclose( $h );
    }
    
    return false;
  }
}
?>