<?php
namespace article;

class Article
{
  public $_values;
  
  public function __construct( $id )
  {    
    global $db;

    $query = $db -> prepare( 'SELECT * FROM pp_articles WHERE id = :id' );
    $query -> bindValue( ':id', $id, \PDO::PARAM_INT );
    $query -> execute();
    if ( $query -> rowCount() ) while ( $row = $query -> fetch( \PDO::FETCH_ASSOC ) )
    {
      foreach ( $row as $key => $val )
        $this -> _values[$key] = $val;
    }
    $query -> closeCursor();    

    $query = $db -> prepare( 'SELECT title, text, meta_description, meta_keywords, seo_link 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',    \System::getSessionVar( 'current_lang' ), \PDO::PARAM_STR );
    $query -> execute();
    if ( $query -> rowCount() ) while ( $row = $query -> fetch( \PDO::FETCH_ASSOC ) )
    {
      foreach ( $row as $key => $val )
        $this -> _values[$key] = $val;
    }
    $query -> closeCursor(); 

    $query = $db -> prepare( 'SELECT * FROM pp_articles_img WHERE id_article = :id_article' );
    $query -> bindValue( ':id_article', $id, \PDO::PARAM_INT );
    $query -> execute();
    if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
      $images[] = $row;
    $query -> closeCursor();
    
    $this -> _values['images'] = $images;

    $query = $db -> prepare( 'SELECT * FROM pp_articles_file WHERE id_article = :id_article' );
    $query -> bindValue( ':id_article', $id, \PDO::PARAM_INT );
    $query -> execute();
    if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
      $files[] = $row;
    $query -> closeCursor();
    
    $this -> _values['files'] = $files;

    $query = $db -> prepare( 'SELECT * FROM pp_articles_comments WHERE article_id = :article_id ORDER BY date_add ASC' );
    $query -> bindValue( ':article_id', $id, \PDO::PARAM_INT );
    $query -> execute();
    if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
      $comments[] = $row;
    $query -> closeCursor();
    
    $this -> _values['comments'] = $comments;
    
    return true;
  }

  public function getImg()
  {
    global $db;
    
    $src = '';
    
    if ( $this -> _values['thumbnail'] )
      return $this -> _values['thumbnail'];

    $regex_img = "|<[\s\v]*img[\s\v]([^>]*[^>]*)>|Ui";
    preg_match_all( $regex_img, $this -> _values['text'], $matches_img );
    $count_img = count($matches_img[0]);
    if ( $count_img )
    {
      if ( @$matches_img[1][0] )
      {
        $inline_params = $matches_img[1][0];
        $asrc = array();
        preg_match( "#src=\"(.*?)\"#s", $inline_params, $asrc );
        if ( isset($asrc[1]) )
          $src = trim($asrc[1]);
        else
        $src = "";
        $syn = substr($src,0,1);
        if ( $syn === "/" or $syn === "\\" )
          $src = substr($src,1,99999);
        $syn = substr($src,0,3);
        if ( $syn == "../" )
          $src = substr($src,3,99999);
        $syn = substr($src,0,7);
        if ( $syn == "example" )
          $src = substr($src,8,99999);
      }
    }
  
    if ( !$src )
    {
      $image = false;
      if ( strpos( $this -> _values['text'], "{galeria}" ) !== false )
      {
        $text = explode( "{galeria}", $this -> _values['text'] );
        for ( $i = 1; $i < count( $text ); $i++ )
        {
          $temp = explode( "{/galeria}", $text[$i] );
          $path = $temp[0];
          if ( $path != "" && is_dir( $path )  )
          {
            @$fh = opendir($path);
            while ( false !== ( $filename = @readdir($fh) ) && !$image )
            {
              if ( $filename == "." || $filename == ".." ) continue;
              if ( file_exists($path.$filename) )
              {
                $src = $path.$filename;
                $image = true;
              }
            }
          }
        }
      }
    }
    
    if ( !$src )
    {
      $query = $db -> prepare( 'SELECT src FROM pp_articles_img WHERE id_article = :id_article ORDER BY id ASC LIMIT 1' );
      $query -> bindValue( ':id_article', $this -> _values['id'], \PDO::PARAM_INT );
      $query -> execute();
      if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
        $src = $row['src'];
      $query -> closeCursor();
    }
    
    return $src;
  }

  public function getModifyText( $entry = false ) 
  {
    if ( $entry )
      $this -> removeImages();
    if ( !$entry ) 
    {
      $this -> drawGallery();
      $this -> drawShadowBox();
    }
    $this -> includePHP( $entry );
    $this -> drawSlider( $entry );
    $this -> getMap();
    return $this -> _values['text'];
  }

  public function getMap()
  {
    $out = '';
    if ( strpos( $this -> _values['text'], "{mapa}" ) !== false )
    {
      $text = explode( "{mapa}", $this -> _values['text'] );
      $before = $text[0];

      for ( $i = 1; $i < count( $text ); $i++ )
      {
        $temp = explode( "{/mapa}", $text[$i] );
        $settings_temp = $temp[0];

        $settings = explode("|",$settings_temp);
        for ( $j = 0; $j < count( $settings ); $j++ )
        {
          $params = explode(":",$settings[$j]);
          if ( trim($params[0]) == "adres" )
            $adress = $params[1];
          else if ( trim($params[0]) == "szerokosc" )
            $width = $params[1];
          else if ( trim($params[0]) == "wysokosc" )
            $height = $params[1];
          else if ( trim($params[0]) == "x_coord" )
            $x_coord = \System::saveString($params[1]);
          else if ( trim($params[0]) == "y_coord" )
            $y_coord = \System::saveString($params[1]);
          else if ( trim($params[0]) == "zoom" )
            $zoom = (int)$params[1];
        }

        $id = rand(0,10000000000000);

        if ( !isset( $zoom ) || !$zoom )
          $zoom = 13;

        if ( $adress != "" && $adress != " " )
        {
          if ( $width == "" )
            $width = 400;
          if ( $height == "" )
            $height = 250;

            $tpl = new \Savant3;
            $tpl -> _google_map_key = \admin\factory\Settings::getSystemSettings( 'google_map_key' );
            $tpl -> _adress         = trim( strip_tags( $adress ) );
            $tpl -> _zoom           = (int)$zoom;
            $tpl -> _width          = (int)$width;
            $tpl -> _height         = (int)$height;
            $tpl -> _id             = $id;
            $out .= $tpl -> fetch( 'articles/article-map' );
          }
          else if ( $x_coord && $y_coord )
          {
            $tpl = new \Savant3;
            $tpl -> _google_map_key = \admin\factory\Settings::getSystemSettings( 'google_map_key' );
            $tpl -> _x_coord        = $x_coord;
            $tpl -> _y_coord        = $y_coord;
            $tpl -> _zoom           = (int)$zoom;
            $tpl -> _width          = (int)$width;
            $tpl -> _height         = (int)$height;
            $tpl -> _id             = $id;
            $out .= $tpl -> fetch( 'articles/article-map' );
          }
        $out .= $temp[1];
      }
      $this -> _values['text'] = $before . $out;
    }
  }

  public function drawSlider( $entry ) 
  {
    $out = '';

    if ( strpos( $this -> _values['text'] , '{slider}' ) !== false )
    {
      $text = explode( '{slider}' , $this -> _values['text'] );
      $before = $text[0];
      for ( $i = 1; $i < count( $text ); $i++ ) 
      {
        $temp   = explode( '{/slider}' , $text[$i] );
        $path   = $temp[0];
        if ( $path && !$entry && is_dir( $path ) ) 
        {
          $fh = @opendir($path);
          while ( false !== ( $filename = @readdir($fh) ) ) 
          {
            if ( $filename == "." || $filename == ".." ) continue;
            if ( file_exists($path.$filename) ) 
            {
              $nazwa = pathinfo( $path  . $filename );
              $pliki[$nazwa['basename']] = $nazwa['extension'];
            }
          }
          if ( is_array( $pliki ) ) ksort($pliki);
          if ( is_array( $pliki ) ) foreach ( $pliki as $key => $val ) 
          {
            $img['src'] = $path . $key;
            $images[] = $img;
          }
          $out .= \article\VArticle::drawSlider( $this -> _id , $images );
        }
        $out .= $temp[1];
      }
      $this -> _values['text'] = $before . $out;
    }
  }

  public function includePHP( $entry ) 
  {
    $out = '';

    if ( strpos( $this -> _values['text'] , '{include_php}' ) !== false ) 
    {
      $text = explode( '{include_php}' , $this -> _values['text'] );
      $before = $text[0];
      for ( $i = 1; $i < count( $text ); $i++ ) 
      {
        $temp   = explode( '{/include_php}' , $text[$i] );
        $path   = $temp[0];
        if ( $path && !$entry ) 
        {
          if ( file_exists( $path ) ) 
          {
            ob_start();
            include( $path );
            $out .= ob_get_contents();
            ob_end_clean();
          }
        }
        $out .= $temp[1];
      }
      $this -> _values['text'] = $before . $out;
    }
  }

  public function drawGallery() 
  {
    $out = '';

    if ( strpos( $this -> _values['text'] , '{galeria}' ) !== false ) 
    {
      $text = explode( '{galeria}' , $this -> _values['text'] );
      $before = $text[0];
      for ( $i = 1; $i < count( $text ); $i++ ) 
      {
        if ( trim( strip_tags( $text[$i] ) ) != '' ) 
        {
          $images = '';
          $temp   = explode( '{/galeria}' , $text[$i] );
          $path   = strip_tags( $temp[0] );

          if ( isset( $path ) && is_dir( $path ) && $path != '' ) 
          {
            $fh = @opendir($path);
            while ( false !== ( $filename = @readdir($fh) ) ) 
            {
              if ( $filename == "." || $filename == ".." ) continue;
              if ( file_exists($path.$filename) ) 
              {
                $nazwa = pathinfo( $path . $filename );
                $pliki[$nazwa['basename']] = $nazwa['extension'];
              }
            }
          }
          if ( isset( $pliki ) && is_array( $pliki ) )
            ksort($pliki);
          if ( isset( $pliki ) && is_array( $pliki ) ) foreach ( $pliki as $key => $val )
          {
            $img['src'] = $path . $key;
            $images[] = $img;
          }
          $out .= \article\VArticle::drawGallery( $this -> _values['id'] , $images );
          if ( isset( $temp[1] ) )
            $out .= $temp[1];
        }
      }
      $this -> _values['text'] = $before . $out;
    }
  }

  public function removeImages()
  {
    $out        = '';
    $regex_img  = "|<[\s\v]*img[\s\v]([^>]*[^>]*)>|Ui";

    preg_match_all( $regex_img, $this -> _values['text'], $matches_img );
    $count_img = count( $matches_img[0] );
    if ( $count_img )
    {
      for ( $i = 0; $i < $count_img; $i++ )
      {
        if ( @$matches_img[1][$i] )
        {
          $this -> _values['text'] = str_replace( $matches_img[0][$i] , '' , $this -> _values['text'] );
        }
      }
    }

    if ( strpos( $this -> _values['text'] , '{galeria}' ) !== false )
    {
      $text   = explode( '{galeria}' , $this -> _values['text'] );
      $before = $text[0];
      for ( $i = 1; $i < count( $text ); $i++ )
      {
        $temp = explode( '{/galeria}' , $text[$i] );
        $out  .= $temp[1];
      }
      $this -> _values['text'] = $before . $out;
    }
  }

  public function drawShadowBox()
  {
    $regex_img = "|<[\s\v]*img[\s\v]([^>]*[^>]*)>|Ui";
    preg_match_all( $regex_img, $this -> _values['text'], $matches_img);
    $count_img = count( $matches_img[0] );
    if ( $count_img )
    {
      for ( $i=0; $i < $count_img; $i++ )
      {
        if (@$matches_img[1][$i])
        {
          $inline_params = $matches_img[1][$i];
          $aclass = array();
          preg_match( "#class=\"(.*?)\"#s", $inline_params, $aclass );
          if ( isset($aclass[1]) )
            $individ_class = trim($aclass[1]);
          else
              $individ_class="";
          $awidth = array();
          preg_match( "#width:(.*?);#s", $inline_params, $awidth );
          if ( isset($awidth[1]) )
            $individ_width = trim($awidth[1]);
          else
            $individ_width="";
          $aheight = array();
          preg_match( "#height:(.*?);#s", $inline_params, $aheight );
          if ( isset($aheight[1]) )
            $individ_height = trim($aheight[1]);
          else
            $individ_height="";
          $aborder = array();
          preg_match( "#border:(.*?);#s", $inline_params, $aborder );
          if ( isset($aborder[0]) )
            $individ_border = trim($aborder[0]);
          else
            $individ_border ="";
          $amagin = array();
          preg_match( "#margin:(.*?);#s", $inline_params, $amagin );
          if ( isset($amagin[0]) )
            $individ_margin = trim($amagin[0]);
          else
            $individ_margin ="";
          $amaginl = array();
          preg_match( "#margin-left:(.*?);#s", $inline_params, $amaginl );
          if ( isset($amaginl[0]) )
            $individ_marginl = trim($amaginl[0]);
          else
            $individ_marginl ="";
          $amaginr = array();
          preg_match( "#margin-right:(.*?);#s", $inline_params, $amaginr );
          if ( isset($amaginr[0]) )
            $individ_marginr = trim($amaginr[0]);
          else
            $individ_marginr ="";
          $amagint = array();
          preg_match( "#margin-top:(.*?);#s", $inline_params, $amagint );
          if ( isset($amagint[0]) )
            $individ_margint = trim($amagint[0]);
          else
            $individ_margint ="";
          $amaginb = array();
          preg_match( "#margin-bottom:(.*?);#s", $inline_params, $amaginb );
          if ( isset($amaginb[0]) )
            $individ_marginb = trim($amaginb[0]);
          else
            $individ_marginb ="";
          $afloat = array();
          preg_match( "#float:(.*?);#s", $inline_params, $afloat );
          if ( isset($afloat[0]) )
            $individ_afloat = trim($afloat[0]);
          else
            $individ_afloat ="";
          $asrc = array();
          preg_match( "#src=\"(.*?)\"#s", $inline_params, $asrc );
          if ( isset($asrc[1]) )
            $src = trim($asrc[1]);
          else
            $src = "";
          $syn = substr($src,0,1);
          if ( $syn === "/" or $syn === "\\" )
            $src = substr($src,1,99999);
          $syn = substr($src,0,3);
          if ( $syn == "../" )
            $src = substr($src,3,99999);
          $syn = substr($src,0,7);
          if ( $syn == "example" )
            $src = substr($src,8,99999);

          if ( file_exists($src) )
          {
            $check = GetImageSize($src);
            $width = $check[0];
            $height = $check[1];
            if ( ( $width != (int)$individ_width || $height != (int)$individ_height ) && $individ_class != 'noshadow' )
            {
              $out = "<a href='" . $src . "' class='fancybox-buttons' rel='" . $this -> _values['id'] . "'>";
              $out .= "<img class='" . $individ_class . "' src='" . $src . "'
                  style='
                    width:" . $individ_width . ";
                    height:" . $individ_height . ";
                    " . $individ_border . "
                    " . $individ_margin . "
                    " . $individ_marginr . "
                    " . $individ_marginl . "
                    " . $individ_margint . "
                    " . $individ_marginb . "
                    " . $individ_afloat . "'>";
              $out .= "</a>";
              $this -> _values['text'] = str_replace( $matches_img[0][$i], $out , $this -> _values['text'] );
            }
          }
        }
      }
    }
  }

  public function drawPrint()
  {
    $out = $this -> _values['title'] . ", " . date( "d/m/Y H:i", strtotime( $this -> _values['date_modify'] ) );
    $out .= $this -> getModifyText( false );
    return $out;
  }
}
?>