<?php
namespace front\controls;
class Articles
{
  public static function pixieset_save_favorite_images( $hash )
  {
    return \front\factory\Articles::pixieset_save_favorite_images( $hash );
  }
  
  public static function pixieset_image_favorite( $image_id, $hash )
  {
    return \front\factory\Articles::pixieset_image_favorite( $image_id, $hash );
  }
  
  public static function images_download( $hash )
  {
    global $mdb;
    
    $results = $mdb -> query( 'SELECT * FROM ('
                                  . 'SELECT id, MD5( CONCAT( id, date_add ) ) AS hash FROM pp_articles ) AS q1'
                                . ' WHERE hash = \'' . $hash . '\'' ) -> fetchAll( \PDO::FETCH_ASSOC );
    if ( is_array( $results ) and count( $results ) ) foreach ( $results as $row )
    {
      $zip = new \ZipArchive;
      $tmp_file = 'temp/' . $hash . '.zip';
      
      if ( file_exists( $tmp_file ) )
        return $tmp_file;
      
      if ( $zip -> open( $tmp_file, \ZipArchive::CREATE ) ) 
      {
        $results2 = $mdb -> select( 'pp_articles_images', 'src', [ 'article_id' => $row['id'] ] );
        if ( is_array( $results2 ) and count( $results2 ) ) foreach ( $results2 as $row2 ) 
        {
          $file = substr( $row2, 1, strlen( $row2 ) );
          $zip -> addFile( $file, basename( $file ) );
        }
        
        $zip -> close();
        
        return $tmp_file;
      }
    }
  }
  
  public static function image()
  {
    global $mdb;
    
    $results = $mdb -> query( 'SELECT * FROM ('
                                  . 'SELECT id, src, MD5( CONCAT( id, src ) ) AS hash FROM pp_articles_images ) AS q1'
                                . ' WHERE hash = \'' . \S::get( 'hash' ) . '\'' ) -> fetchAll( \PDO::FETCH_ASSOC );
    if ( is_array( $results ) and count( $results ) )
    {
      $file = substr( $results[0]['src'], 1, strlen( $results[0]['src'] ) );
      
      header('Content-Description: File Transfer');
      header('Content-Type: application/octet-stream');
      header('Content-Disposition: attachment; filename="' . basename( $file ) . '"');
      header('Expires: 0');
      header('Cache-Control: must-revalidate');
      header('Pragma: public');
      header('Content-Length: ' . filesize( $file ) );
      flush();
      readfile($file);
      exit;
    }
    exit;
  }
  
  public static function article_unlock( $password, $article_id )
  {
    if ( $password == \front\factory\Articles::article_password( $article_id ) )
      \S::set_session( 'article-' . $article_id . '-' . $password, true );
  }
}
