<?php
error_reporting( E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED & ~E_WARNING );
function __autoload_my_classes( $classname )
{
  $q = explode( '\\', $classname );
  $c = array_pop( $q );
  $f = 'autoload/' . implode( '/', $q ) . '/class.' . $c . '.php';

  if ( file_exists( $f ) )
    require_once( $f );
}
spl_autoload_register( '__autoload_my_classes' );
date_default_timezone_set( 'Europe/Warsaw' );

require_once 'config.php';
require_once 'libraries/medoo/medoo.php';

session_start();

if ( !isset( $_SESSION['check'] ) )
{
  session_regenerate_id();
  $_SESSION['check'] = true;
  $_SESSION['ip']    = $_SERVER['REMOTE_ADDR'];
}

if ( $_SESSION['ip'] !== $_SERVER['REMOTE_ADDR'] )
{
  session_destroy();
  header( 'Location: /' );
  exit;
}

$mdb = new medoo( [
        'database_type' => 'mysql',
        'database_name' => $database['name'],
        'server'        => $database['host'],
        'username'      => $database['user'],
        'password'      => $database['password'],
        'charset'       => 'utf8',
        'logging' => true
        ] );

\front\controls\Site::check_url_params();

if ( file_exists( 'plugins/special-actions.php' ) )
  include 'plugins/special-actions.php';

if ( !$lang_id = \S::get_session( 'current-lang' ) )
{
  $lang_id = \front\factory\Languages::default_language();
  \S::set_session( 'current-lang', $lang_id );
}

if ( \S::get('action') == 'htaccess' )
{
  \S::htacces( '' );
	unlink( 'install.php' );
	unlink( 'update.zip' );
  header('Location: /');
  exit;
}

if ( !$lang = \S::get_session( 'lang-' . $lang_id ) )
{
  $lang = \front\factory\Languages::lang_translations( $lang_id );
  \S::set_session( 'lang-' . $lang_id, $lang );
}

$settings = \front\factory\Settings::settings_details();

preg_match_all( \front\view\Site::language_pattern, $settings['additional_info'], $language_list );
if ( is_array( $language_list[0] ) ) foreach( $language_list[0] as $language_list_tmp )
{
  $language_list_tmp = explode( ':', $language_list_tmp );
  $settings['additional_info'] = str_replace( '[LANG:' . $language_list_tmp[1] . ']', $lang[ $language_list_tmp[1] ], $settings['additional_info'] );
}

if ( $settings['visit_counter'] and ! \S::get_session( 'visits' ) and ! \S::is_bot() )
{
  $visits = (int)\front\factory\Settings::visit_counter();
  $visits_new = $visits+1;
  if ( $visits_new > $visits )
  {
    if ( !$mdb -> count( 'pp_settings', [ 'param' => 'visits' ] ) )
      $mdb -> insert( 'pp_settings', [ 'value' => $visits_new, 'param' => 'visits' ] );
    else
      $mdb -> update( 'pp_settings', [ 'value' => $visits_new ], [ 'param' => 'visits' ] );
    \S::set_session( 'visits', $visits_new );
  }
}

if ( \S::get( 'a' ) == 'page' and \S::get( 'id' ) )
{
  $page = \front\factory\Pages::page_details( \S::get( 'id' ) );
  \S::set_session( 'page', $page );
}

if ( \S::get( 'devel' ) )
  $settings['devel'] = true;

if ( file_exists( 'plugins/special-actions-middle.php' ) )
  include 'plugins/special-actions-middle.php';

if ( $page['cache'] )
{
  $cache_url  = $_SERVER['REQUEST_URI'];
  $cache_file = \S::cache_file_url( $cache_url );
  if ( file_exists( $cache_file ) )
  {
    $timedif = ( time() - filemtime( $cache_file ));
    if ( $timedif < 3600 * 24 )
    {
      echo $html = \S::cache_read( $cache_file );
      exit;
    }
  }
}

$out = \front\view\Site::show();

if ( !isset( $_COOKIE["cookie_information"] ) )
  $out = strrev( implode( strrev( \front\view\Site::cookie_information() . '</body>' ), explode( strrev( '</body>' ), strrev( $out ), 2 ) ) );

if ( $settings['statistic_code'] )
  $out = strrev( implode( strrev( $settings['statistic_code'] . '</head>' ), explode( strrev( '</head>' ), strrev( $out ), 2 ) ) );

/* wysyłka newslettera w tle */
if ( !$settings['newsletter_cron'] )
  \front\factory\Newsletter::newsletter_send( 1 );

$dom = new DOMDocument('1.0', 'UTF-8');
$dom -> loadHTML( $out );
$stylesheet = $dom -> getElementsByTagName( 'link' );
$remove = [];
foreach ( $stylesheet as $item )
{
  if ( $item -> getAttribute( 'rel' ) == 'stylesheet' and ( strpos( $item -> getAttribute( 'class' ), 'footer' ) !== false or strpos( $item -> getAttribute( 'class' ), 'merge' ) !== false ) )
  {
    if ( strpos( $item -> getAttribute( 'class' ), 'merge' ) !== false )
    {
      $url = $item -> getAttribute( 'href' );
      if ( substr( $url, 0, 1 ) == '/' )
        $url = substr( $url, 1 );

      $css_buffer .= file_get_contents( $url );
    }

    $remove[] = $item;
  }
}

if ( $css_buffer )
  file_put_contents( 'temp/css_all.css', $css_buffer );

if ( $css_buffer ) {
  $element = $dom -> createElement( 'link' );
  $element -> setAttribute( 'href', '/temp/css_all.css' );
  $element -> setAttribute( 'rel', 'stylesheet' );
  $element -> setAttribute( 'type', 'text/css' );
  $body = $dom -> getElementsByTagName( 'body' ) -> item(0);
  $body -> appendChild( $element );
}

foreach ( $remove as $item )
{
  $item -> parentNode -> removeChild( $item );
  if ( strpos( $item -> getAttribute( 'class' ), 'footer' ) !== false and strpos( $item -> getAttribute( 'class' ), 'merge' ) === false  )
  {
    $body = $dom -> getElementsByTagName( 'body' ) -> item(0);
    $body -> appendChild( $item );
  }
}

$script = $dom -> getElementsByTagName( 'script' );
$remove = [];
foreach ( $script as $item )
{
  if ( $item -> getAttribute( 'class' ) == 'footer' )
    $remove[] = $item;
}

foreach ( $remove as $item )
{
  $item -> parentNode -> removeChild( $item );
  $body = $dom -> getElementsByTagName( 'body' ) -> item(0);
  $body -> appendChild( $item );
}

// webpimages
$images = $dom -> getElementsByTagName( 'img' );
foreach ( $images as $img )
{
  $img_src = $img -> getAttribute( 'src' );

  if ( $img_src != '' and strpos( $img -> getAttribute( 'class' ), 'nowebp' ) === false )
  {
    if ( strpos( $img_src, '/' ) === 0 )
      $img_src = substr( $img_src, 1, strlen( $img_src ) );

    $img_webp = \S::generate_webp_image( $img_src, 85 );
    if ( $img_webp !== false and file_exists( $img_webp ) )
    {
      $img -> setAttribute( 'src', '/' . $img_webp );
      $img -> setAttribute( 'src-nowebp', '/' . $img_src );
    }
  }
}

// lazy loading obrazków
$images = $dom -> getElementsByTagName( 'img' );
foreach ( $images as $img )
{
  if ( strpos( $img -> getAttribute( 'class' ), 'nolazy' ) === false )
  {
    $img -> setAttribute( 'data-src', $img -> getAttribute( 'src' ) );
    $img -> setAttribute( 'class', $img -> getAttribute( 'class' ) . ' lozad' );
    $img -> removeAttribute( 'src' );
  }
}

$html = $dom -> saveHTML();

if ( file_exists( 'plugins/special-actions-end.php' ) )
  include 'plugins/special-actions-end.php';

if ( $page['cache'] )
  \S::cache_write( $cache_url, $cache_file, $html );

echo $html;
?>