<?php
class ImagesAdmin extends Images{

  function &getInstance( ){  
    static $oInstance = null;
    if( !isset( $oInstance ) ){
      $oInstance = new ImagesAdmin( );  
    }  
    return $oInstance;  
  } // end function getInstance

  /**
  * Constructor
  * @return void
  */
  function ImagesAdmin( ){
    $this->generateCache( );
  } // end function ImagesAdmin

  /**
  * Return images list
  * @return string
  * @param string $sFile
  * @param int    $iList
  */
  function listImagesAdmin( $sFile, $iList = null ){
    global $config;

    if( isset( $this->aImages ) ){
      if( isset( $_GET['iPageImages'] ) && is_numeric( $_GET['iPageImages'] ) ){
        if( isset( $this->aImagesPages[$_GET['iPageImages']] ) )
          $aImages = $this->aImagesPages[$_GET['iPageImages']];
      }
      else{
        foreach( $this->aImages as $iImage => $aData ){
          $aImages[] = $iImage;
        } // end foreach
      }

      if( isset( $aImages ) ){

        $aComments = getCommetsQuantity( );
        $aVotes = getVotes( );

        if( isset( $_GET['sSort'] ) && !empty( $_GET['sSort'] ) && $_GET['sSort'] == 'id' ){
          $aImages = $this->sortImages( $aImages, $_GET['sSort'] );
        }

        $oTpl =& TplParser::getInstance( );
        $oPage =& PagesAdmin::getInstance( );
        $content = null;

        if( !isset( $iList ) ){
          $iList = $GLOBALS['config']['admin_list'];
        }

        $iCount = count( $aImages );
        $iImages = ceil( $iCount / $iList );
        $iPageNumber = isset( $_GET['iPage'] ) ? $_GET['iPage'] : 1;
        if( !isset( $iPageNumber ) || !is_numeric( $iPageNumber ) || $iPageNumber < 1 )
          $iPageNumber = 1;
        if( $iPageNumber > $iImages )
          $iPageNumber = $iImages;

        $iEnd   = $iPageNumber * $iList;
        $iStart = $iEnd - $iList;

        if( $iEnd > $iCount )
          $iEnd = $iCount;

        for( $i = $iStart; $i < $iEnd; $i++ ){
          $aData = $this->aImages[$aImages[$i]];
          $aData['iStyle'] = ( $i % 2 ) ? 0: 1;
          $aData['sStatusBox'] = ( $aData['iStatus'] == 1 ) ? ' checked="checked"' : null;
          $aData['sCommentsBox'] = ( $aData['iComments'] == 1 ) ? ' checked="checked"' : null;
          $aData['sVotesBox'] = ( $aData['iVotes'] == 1 ) ? ' checked="checked"' : null;
          $aData['sPageName'] = isset( $oPage->aPages[$aData['iPage']] ) ? $oPage->aPages[$aData['iPage']]['sName'] : null;
          $aData['iCommentsQuantity'] = isset( $aComments[$aData['iImage']] ) ? $aComments[$aData['iImage']] : 0;
          $aData['iVotesCount'] = isset( $aVotes[$aData['iImage']] ) ? $aVotes[$aData['iImage']]['iVotesCount'] : 0;
          $aData['fVotesAvarage'] = isset( $aVotes[$aData['iImage']] ) ? $aVotes[$aData['iImage']]['fVotesAvarage'] : 0;

          $oTpl->setVariables( 'aData', $aData );
          $content .= $oTpl->tbHtml( $sFile, 'LIST' );
        } // end for

        if( isset( $content ) ){
          $aData['sPages'] = countPagesClassic( $iCount, $iList, $iPageNumber, changeUri( $_SERVER['REQUEST_URI'] ) );
          $oTpl->setVariables( 'aData', $aData );
          return $oTpl->tbHtml( $sFile, 'HEAD' ).$content.$oTpl->tbHtml( $sFile, 'FOOT' );
        }
      }
    }
  } // end function listImagesAdmin

  /**
  * Delete image
  * @return void
  * @param int  $iImage
  */
  function deleteImage( $iImage ){
    if( !isset( $this->aImages[$iImage] ) )
      return null;

    $oFF =& FlatFiles::getInstance( );

    $this->deleteFilesFromDirs( $this->aImages[$iImage]['sFile'], $this->aImages[$iImage]['sDirectory'] );
    $oFF->deleteInFile( DB_IMAGES, $iImage, 'iImage' );
    $oFF->deleteInFile( DB_IMAGES_VOTES, $iImage, 'iImage' );
    $oFF->deleteInFile( DB_IMAGES_COMMENTS, $iImage, 'iImage' );
  } // end function deleteImage

  /**
  * Delete all images in selected page
  * @return void
  * @param array  $aData
  */
  function deleteImages( $aData ){
    $oFF =& FlatFiles::getInstance( );
    foreach( $aData as $iPage => $bValue ){
      if( isset( $this->aImagesPages[$iPage] ) ){
        foreach( $this->aImagesPages[$iPage] as $iKey => $iImage ){
          $this->deleteFilesFromDirs( $this->aImages[$iImage]['sFile'], $this->aImages[$iImage]['sDirectory'] );
          $oFF->deleteInFile( DB_IMAGES_VOTES, $iImage, 'iImage' );
          $oFF->deleteInFile( DB_IMAGES_COMMENTS, $iImage, 'iImage' );
        }
      }
    }

    $oFF->deleteInFile( DB_IMAGES, $aData, 'iPage' );
  } // end function deleteImages

  /**
  * Delete images from directories
  * @return void
  * @param string $sFileName
  * @param string $sDirectory
  */
  function deleteFilesFromDirs( $sFileName, $sDirectory ){

    $oDir = dir( DIR_IMAGES.$sDirectory );
    while( false !== ( $mDir = $oDir->read( ) ) ){
      if( is_numeric( $mDir ) && is_dir( DIR_IMAGES.$sDirectory.'/'.$mDir ) ){
        if( is_file( DIR_IMAGES.$sDirectory.'/'.$mDir.'/'.$sFileName ) )
          unlink( DIR_IMAGES.$sDirectory.'/'.$mDir.'/'.$sFileName );
      }
    }
    $oDir->close( );

    if( is_file( DIR_IMAGES.$sDirectory.'/'.$sFileName ) )
      unlink( DIR_IMAGES.$sDirectory.'/'.$sFileName );
  } // end function deleteFilesFromDirs

  /**
  * Save image data
  * @return int
  * @param array  $aForm
  */
  function saveImage( $aForm ){
    $oFF =& FlatFiles::getInstance( );

    if( isset( $aForm['iImage'] ) && is_numeric( $aForm['iImage'] ) && isset( $this->aImages[$aForm['iImage']] ) ){
      $sParam = 'iImage';
      $aForm['sDirectory'] = $this->aImages[$aForm['iImage']]['sDirectory'];
      $aForm['sFile'] = $this->aImages[$aForm['iImage']]['sFile'];

      if( $aForm['iSize1'] != $this->aImages[$aForm['iImage']]['iSize1'] || $aForm['iSize2'] != $this->aImages[$aForm['iImage']]['iSize2'] ){
        $this->generateThumbs( $aForm['sFile'], DIR_IMAGES.$aForm['sDirectory'].'/', $aForm['iSize1'], $aForm['iSize2'] );
      }
    }
    else{
      $sParam = null;
      $aForm['iImage'] = $oFF->throwLastId( DB_IMAGES, 'iImage' ) + 1;
    }
    
    if( !isset( $aForm['iPosition'] ) || !is_numeric( $aForm['iPosition'] ) || $aForm['iPosition'] < -999 || $aForm['iPosition'] > 9999 )
      $aForm['iPosition'] = 0;
    if( !isset( $aForm['iStatus'] ) )
      $aForm['iStatus'] = 0;
    if( !isset( $aForm['iComments'] ) )
      $aForm['iComments'] = 0;
    if( !isset( $aForm['iVotes'] ) )
      $aForm['iVotes'] = 0;

    $aForm = changeMassTxt( $aForm, '', Array( 'sDescription', 'Nds' ) );

    if( !empty( $aForm['sDirectoryNew'] ) && $aForm['sDirectory'] == '_newDirectory_' ){
      $aForm['sDirectoryNew'] = str_replace( '/', '', $aForm['sDirectoryNew'] );
      if( !is_dir( DIR_IMAGES.$aForm['sDirectoryNew'] ) ){
        mkdir( DIR_IMAGES.$aForm['sDirectoryNew'] );
        chmod( DIR_IMAGES.$aForm['sDirectoryNew'], 0777 );
      }
      $aForm['sDirectory'] = $aForm['sDirectoryNew'];
      $sDirectorySave = DIR_IMAGES.$aForm['sDirectoryNew'].'/';
    }
    else{
      $sDirectorySave = DIR_IMAGES.$aForm['sDirectory'].'/';
    }

    if( !empty( $_FILES['aNewFile']['name'] ) && $oFF->checkCorrectFile( $_FILES['aNewFile']['name'], 'gif|jpg|png|jpeg' ) == true ){
      $sFileName = $oFF->uploadFile( $_FILES['aNewFile'], $sDirectorySave );
      if( !empty( $sFileName ) ){
        $this->generateThumbs( $sFileName, $sDirectorySave, $aForm['iSize1'], $aForm['iSize2'] );
        $aForm['sFile'] = $sFileName;  
      }
    }

    $oFF->save( DB_IMAGES, $aForm, $sParam, 'sort' );

    if( isset( $aForm['iVotesDelete'] ) ){
      $oFF->deleteInFile( DB_IMAGES_VOTES, $aForm['iImage'], 'iImage' );
    }

    $this->generateCache( );
    return $aForm['iImage'];
  } // end function saveImage 


  /**
  * Save images data and upload
  * @return void
  * @param array  $aForm
  */
  function saveImagesUpload( $aForm ){
    $oFF =& FlatFiles::getInstance( );
    $iImage = $oFF->throwLastId( DB_IMAGES, 'iImage' ) + 1;

    foreach( $aForm['aNames'] as $iKey => $sName ){
      if( is_numeric( $aForm['aPages'][$iKey] ) && ( ( !empty( $aForm['aDirectories'][$iKey] ) && $aForm['aDirectories'][$iKey] != '_newDirectory_' ) || ( $aForm['aDirectories'][$iKey] == '_newDirectory_' ) && !empty( $aForm['aDirectoriesNew'][$iKey] ) ) && !empty( $_FILES['aFiles']['name'][$iKey] ) && $oFF->checkCorrectFile( $_FILES['aFiles']['name'][$iKey], 'gif|jpg|png|jpeg' ) == true ){
        $aKeys[] = $iKey;
      }
    }

    $iCount = count( $aKeys );
    for( $i = 0; $i < $iCount; $i++ ){
      $iKey = $aKeys[$i];

      if( !isset( $aForm['aPositions'][$iKey] ) || !is_numeric( $aForm['aPositions'][$iKey] ) || $aForm['aPositions'][$iKey] < -999 || $aForm['aPositions'][$iKey] > 9999 )
        $aSave['iPosition'] = 0;
      else
        $aSave['iPosition'] = $aForm['aPositions'][$iKey];

      $aSave['sName'] = changeTxt( $aForm['aNames'][$iKey], '' );
      $aSave['iStatus'] = !isset( $aForm['aStatus'][$iKey] ) ? 0 : 1;
      $aSave['iComments'] = 0;
      $aSave['iVotes'] = 0;
      $aSave['sDescription'] = '';
      $aSave['iPage'] = $aForm['aPages'][$iKey];
      $aSave['iSize1'] = $aForm['aSizes1'][$iKey];
      $aSave['iSize2'] = $aForm['aSizes2'][$iKey];

      if( !empty( $aForm['aDirectoriesNew'][$iKey] ) && $aForm['aDirectories'][$iKey] == '_newDirectory_' ){
        $aForm['aDirectoriesNew'][$iKey] = str_replace( '/', '', $aForm['aDirectoriesNew'][$iKey] );
        if( !is_dir( DIR_IMAGES.$aForm['aDirectoriesNew'][$iKey] ) ){
          mkdir( DIR_IMAGES.$aForm['aDirectoriesNew'][$iKey] );
          chmod( DIR_IMAGES.$aForm['aDirectoriesNew'][$iKey], 0777 );
        }
        $aSave['sDirectory'] = $aForm['aDirectoriesNew'][$iKey];
        $sDirectorySave = DIR_IMAGES.$aForm['aDirectoriesNew'][$iKey].'/';
      }
      else{
        $sDirectorySave = DIR_IMAGES.$aForm['aDirectories'][$iKey].'/';
        $aSave['sDirectory'] = $aForm['aDirectories'][$iKey];
      }
      
      $aUpload = Array( 'name' => $_FILES['aFiles']['name'][$iKey], 'type' => $_FILES['aFiles']['type'][$iKey], 'tmp_name' => $_FILES['aFiles']['tmp_name'][$iKey], 'error' => $_FILES['aFiles']['error'][$iKey], 'size' => $_FILES['aFiles']['size'][$iKey] );
      $sFileName = $oFF->uploadFile( $aUpload, $sDirectorySave );
      if( !empty( $sFileName ) ){
        $this->generateThumbs( $sFileName, $sDirectorySave, $aSave['iSize1'], $aSave['iSize2'] );
        $aSave['sFile'] = $sFileName;  
      }

      $aSave['iImage'] = $iImage;
      
      if( $i == $iCount - 1 ){
        $oFF->save( DB_IMAGES, $aSave, null, 'sort' );
      }
      else{
        $oFF->save( DB_IMAGES, $aSave );
      }

      $iImage++;
    } // end for

  } // end function saveImagesUpload

  /**
  * Save images position, status, comments, votes
  * @return void
  * @param array  $aForm
  */
  function saveImages( $aForm ){
    if( isset( $aForm['aPositions'] ) && is_array( $aForm['aPositions'] ) ){
      foreach( $this->aImages as $iImage => $aData ){
        if( isset( $aForm['aPositions'][$iImage] ) ){
          $aForm['aPositions'][$iImage] = trim( $aForm['aPositions'][$iImage] );
          if( is_numeric( $aForm['aPositions'][$iImage] ) ){
            $aChange[$iImage]['iPosition'] = $aForm['aPositions'][$iImage];
          }

          $aChange[$iImage]['sName'] = changeTxt( $aForm['aNames'][$iImage], '' );
          $aChange[$iImage]['iStatus'] = isset( $aForm['aStatus'][$iImage] ) ? 1 : 0;
          $aChange[$iImage]['iComments'] = isset( $aForm['aComments'][$iImage] ) ? 1 : 0;
          $aChange[$iImage]['iVotes'] = isset( $aForm['aVotes'][$iImage] ) ? 1 : 0;
        }
      } // end foreach

      if( isset( $aChange ) ){
        $this->saveImagesData( $aChange );
        $this->generateCache( );
      }
    }
  } // end function saveImages

  /**
  * Save images status, position etc.
  * @return void
  * @param array  $aChange
  */
  function saveImagesData( $aChange ){
    $oFF =& FlatFiles::getInstance( );
    $iCount = count( $aChange );
    $i = 1;

    foreach( $aChange as $iImage => $aData ){
      $aSave = array_merge( $this->aImages[$iImage], $aData );

      if( $i == $iCount )
        $oFF->save( DB_IMAGES, $aSave, 'iImage', 'sort' );
      else
        $oFF->save( DB_IMAGES, $aSave, 'iImage' );
      
      $i++;
    } // end foreach

  } // end function saveImagesData

  /**
  * Generate image thumbnails
  * @return void
  * @param string $sFileName
  * @param string $sDir
  * @param int    $iSize1
  * @param int    $iSize2
  */
  function generateThumbs( $sFileName, $sDir, $iSize1, $iSize2 ){
    $oFoto  =& FotoJobs::getInstance( );

    $aImgSize = $oFoto->throwImgSize( $sDir.$sFileName );
    if( defined( 'MAX_DIMENSION_OF_IMAGE' ) && ( $aImgSize['width'] > MAX_DIMENSION_OF_IMAGE || $aImgSize ['height'] > MAX_DIMENSION_OF_IMAGE ) ){
      if( $aImgSize['width'] < $oFoto->iMaxForThumbSize && $aImgSize['height'] < $oFoto->iMaxForThumbSize ){
        $oFoto->setThumbSize( MAX_DIMENSION_OF_IMAGE );
        $oFoto->createThumb( $sDir.$sFileName, $sDir, $sFileName );
      }
    }
    
    if( isset( $GLOBALS['config']['images_sizes'][$iSize1] ) )
      $iSize1 = $GLOBALS['config']['images_sizes'][$iSize1];
    else
      $iSize1 = $GLOBALS['config']['images_sizes'][0];

    if( isset( $GLOBALS['config']['images_sizes'][$iSize2] ) )
      $iSize2 = $GLOBALS['config']['images_sizes'][$iSize2];
    else
      $iSize2 = $GLOBALS['config']['images_sizes'][0];

    $sThumbsDir1 = $sDir.$iSize1.'/';
    $sThumbsDir2 = $sDir.$iSize2.'/';

    if( !is_dir( $sThumbsDir1 ) ){
      mkdir( $sThumbsDir1 );
      chmod( $sThumbsDir1, 0777 );
    }
    if( !is_dir( $sThumbsDir2 ) ){
      mkdir( $sThumbsDir2 );
      chmod( $sThumbsDir2, 0777 );
    }

    if( !is_file( $sThumbsDir1.$sFileName ) )
      $oFoto->createCustomThumb( $sDir.$sFileName, $sThumbsDir1, $iSize1, $sFileName, true );
    if( !is_file( $sThumbsDir2.$sFileName ) )
      $oFoto->createCustomThumb( $sDir.$sFileName, $sThumbsDir2, $iSize2, $sFileName, true );
  } // end function generateThumbs

};
?>