<?php
#-------------------------------------------------------------------------
# Module: Captcha - Enables CAPTCHA support for use in other modules.
#-------------------------------------------------------------------------
# Version 1.0
# maintained by Fernando Morgado AKA Jo Morg since 2017
#-------------------------------------------------------------------------
# Original Author: Dick Ittmann
#-------------------------------------------------------------------------
#
# Captcha is a CMS Made Simple module that enables the web developer to create
# multiple lists throughout a site. It can be duplicated and given friendly
# names for easier client maintenance.
#
#-------------------------------------------------------------------------
# BEGIN_LICENSE
#-------------------------------------------------------------------------
#
# This file is part of Captcha
# Captcha program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Captcha program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Or read it online: http://www.gnu.org/licenses/licenses.html#GPL
#
#-------------------------------------------------------------------------
# END_LICENSE
#-------------------------------------------------------------------------
namespace Captcha;
	
class utils
{
  private static $_initialized = FALSE;
  private static $_cm;
  private static $_config;
  private static $_gd_errors = array();
  
  private static function _initialise()
  {
    if(!self::$_initialized) 
    {
      self::$_cm = \cmsms()->GetModuleInstance('Captcha');
      self::$_config = config::GetInstance();
      self::$_initialized = TRUE;
    }
  }
  
private static function _delete_files( $filelist = array() )
  {
    $ret = array();
    $modulepath = dirname( dirname(__FILE__) );
        
    foreach($filelist as $file => $path)
    {
      $fullqualfilename = realpath( cms_join_path(
                                                   $modulepath,
                                                   $path,
                                                   $file 
                                                  )
                                  );
                       
      if(is_readable($fullqualfilename))
      {
        self::_recursive_remove_directory($fullqualfilename);                    
      }                                
    }
  }
  
  /**
  * If 2del.dat exists in the module's data folder and has a list of files to delete
  * then do some house cleaning
  */
  private static function _delete_files_from_file_list($version = '')
  {
    if( empty($version) ) return;
    $modulepath = dirname( dirname(__FILE__) );
    
    $file_list = cms_join_path(
                                 $modulepath,
                                'data',
                                '2del.dat'
                              );
                              
    if( is_readable($file_list) )
    {
      include_once($file_list);
      
      if( isset($file2del[$version]) )
      {
        return self::_delete_files($file2del[$version]);
      }
    }
    
  }
  
  /**
  * Deletes a dir and everything inside recursivly
  * 
  * @param string $directory: a valid dir
  */
  private static function _recursive_remove_directory($directory)
  {
    
    $files = array();
    
    if( is_dir($directory) ) 
    {
      $files = array_diff( scandir($directory), array('.','..') );
    }
    else
    {
      unlink($directory);
    }
    
    $ret = array();

    foreach ($files as $file) 
    {
      $fn = cms_join_path($directory, $file);
      
      if( is_dir($fn) )
      {
        self::_recursive_remove_directory($fn);  
      }
      else
      {
        unlink($fn);
      }
    }
    
    if( !@rmdir($directory) )
    {
      $ret[] = 'error deleting directory: ' . $directory;
    }
    
    return $ret;
  }
  
  /**
  * If 2ren.dat exists in the module's data folder and has a list of files to rename
  * then do some house cleaning
  */
  private static function _rename_files_from_file_list($version = '')
  {
    self::_initialise();
    
    $file_list = cms_join_path(
                                 self::$_cm->GetModulePath(),
                                'data',
                                '2ren.dat'
                              );
                              
    if( is_readable($file_list) )
    {
      include_once($file_list);
      
      if( isset($file2ren[$version]) )
      {
        return self::_rename_files($file2ren[$version]);
      }
    }
  }
  
  /**
  * Renames a list of files
  * 
  * @param array $filelist
  */
  private static function _rename_files($filelist = array() )
  {
    self::_initialise();
    $ret = array();
    
    foreach($filelist as $oldfilename => $newfilename)
    {
      $oldfilename = str_replace('::', DIRECTORY_SEPARATOR, $oldfilename);
      $newfilename = str_replace('::', DIRECTORY_SEPARATOR, $newfilename);
      
      $fullqualoldfilename = realpath( cms_join_path(
                                                       self::$_cm->GetModulePath(),
                                                       $oldfilename
                                                      )
                                  );      
                                  
      $fullqualnewfilename = str_replace($oldfilename, $newfilename, $fullqualoldfilename);
      
      if( is_readable($fullqualoldfilename) )
      {
        $ret = $ret + array( self::_rename_file($fullqualoldfilename, $fullqualnewfilename) ); 
      }
                                                                        
    }
    
    return $ret;
  }
  
  /**
  * Renames a file or directory
  * 
  * @param string $oldfilename
  * @param string $newfilename
  */
  private static function _rename_file($oldfilename, $newfilename)
  {
    return rename($oldfilename, $newfilename) ? array() : 'Error renaming ' . $oldfilename . ' to ' . $newfilename;
  }
  
  /**
  * @return bool
  */
  public static function isImageFilename($name)
  {
    if (strlen($name) < 4)
    {
      return FALSE;
    }
    
    $image_extensions = array('.jpg', '.gif', '.png');
    $name_length      = strlen($name);
    $file_extension   = substr($name, strlen($name) - 4);
    
    return in_array($file_extension, $image_extensions);
  }
  
  public static function get_GD_errors()
  {
    self::_initialise();
    
    if( empty(self::$_gd_errors) )
    {
      // GD checks
      switch( function_exists('gd_info') )
      {
        case false:
          self::$_gd_errors[] = self::$_cm->Lang('err_no_gd_support');
          break;
        case true:
          $gd_info = gd_info();
          if ( (!isset($gd_info['JPG Support']) || !$gd_info['JPG Support']) &&
               (!isset($gd_info['JPEG Support']) || !$gd_info['JPEG Support']) )
          {
            self::$_gd_errors[] = self::$_cm->Lang('err_no_jpg_support');
          }
          if (! isset($gd_info['FreeType Support']) || ! $gd_info['FreeType Support'])
          {
            self::$_gd_errors[] = self::$_cm->Lang('err_no_freetype_support');
          }
      }
    }
    
    return self::$_gd_errors;
  }
  
  /**
  * returns true if we are in cmsms 2+ otherwise false
  * @since 0.5.3
  */
  public static function is_CMS2()
  {
    return version_compare('1.999.999.999', CMS_VERSION, '<');
  }
  
  public static function friendly_from_class_name($name)
  {
    return ucwords(str_replace('_', ' ', trim($name) ) );
  }
  
  public static function build_plugins_dropdown_array($full= FALSE)
  {
    plugins_ops::load($full);
    $tmp = plugins_ops::get_loaded();
    $ret = array();
    
    foreach($tmp as $k => $v)
    {
      $ret[$k] = $v->getFriendlyName();
    }
    
    return $ret;
  }
  
  public static function get_available_fonts_list()
  {
    self::_initialise();
    
    $fonts = array();
    if ($handle = opendir(self::$_cm->GetModulePath() . '/fonts')) 
    {
      while (false !== ($file = readdir($handle))) 
      {
        if ($file != '.' && $file != '..' && substr($file,strlen($file) - 4, 4) == '.ttf') 
        {
          $fontfile = cms_join_path(self::$_cm->GetModulePath(), 'fonts', $file);
          if(is_readable($fontfile))
          {
            $fonts[] = substr($file, 0, strlen($file)-4);
          }
        }
      }
      closedir($handle);
    }
    
    return $fonts;
  }
  
  static public function DeleteFilesFromFileList($version = '')
  {
    self::_delete_files_from_file_list($version);
  }
}
?>