<?php
/*
 * khoaofgod@gmail.com
 * Website: http://www.phpfastcache.com
 * Example at our website, any bugs, problems, please visit http://faster.phpfastcache.com
 * Edited by Product Designer App
 */

if (!defined('ABSPATH'))
{
    exit;
}

class PDAPP_phpfastcache_files extends  PDAPP_BasePhpFastCache implements pdapp_phpfastcache_driver
{
    function pdapp_checkdriver()
    {
        global $wp_filesystem;
        if($wp_filesystem->is_writable($this->pdapp_get_path()))
        {
            return true;
        } else{}

        return false;
    }

    /*
     * Init Cache Path
     */
    function __construct($config = array())
    {
        $this->pdapp_setup($config);
        $this->pdapp_get_path();

        if(!$this->pdapp_checkdriver() && !isset($config['skipError']))
        {
            throw new Exception( esc_html("Can't use this driver for your website!") );
        }
    }
    
    private function pdapp_encode_filename($keyword)
    {
	    return trim(trim(preg_replace("/[^a-zA-Z0-9]+/","_",$keyword),"_"));
    }

    /*
     * Return $FILE FULL PATH
     */
    private function pdapp_get_file_path($keyword, $skip = false)
    {
        $path = $this->pdapp_get_path();
        
        $filename = $this->pdapp_encode_filename($keyword);
        $folder = '';
        $path = rtrim($path,"/")."/".$folder;
        /*
         * Skip Create Sub Folders;
         */
        global $wp_filesystem;
        if($skip == false)
        {
            if(!file_exists($path))
            {
                if(!wp_mkdir_p($path))
                {
                    throw new Exception( esc_html("PLEASE CHMOD ". $this->pdapp_get_path() ." - 0777 OR ANY WRITABLE PERMISSION!"), 92);
                }

            } elseif(!$wp_filesystem->is_writable($path))
            {
                if(!$wp_filesystem->chmod($path,$this->__pdapp_set_chmod_auto()))
                {
	                die(esc_html("PLEASE CHMOD ". $this->pdapp_get_path() ." - 0777 OR ANY WRITABLE PERMISSION! MAKE SURE PHP/Apache/WebServer have Write Permission"));
                }
            }
        }

        $file_path = $path."/".$filename.".txt";
        return $file_path;
    }
    
    function pdapp_driver_set($keyword, $value = "", $time = 300, $option = array())
    {
        $file_path = $this->pdapp_get_file_path($keyword);
        $data = $this->pdapp_encode($value);

        $toWrite = true;
        /*
         * Skip if Existing Caching in Options
         */
        if(isset($option['skipExisting']) && $option['skipExisting'] == true && file_exists($file_path))
        {
            $content = pdapp_read_file($file_path);
            $old = $this->pdapp_decode($content);
            $toWrite = false;
            if($this->pdapp_is_expired($old))
            {
                $toWrite = true;
            }
        }

        if($toWrite == true)
        {
            if(!pdapp_write_file($file_path, $data))
            {
                return false;
            } 
        }
    }

    function pdapp_driver_get($keyword, $option = array())
    {
        $file_path = $this->pdapp_get_file_path($keyword);
        if(!file_exists($file_path))
        {
            return null;
        }

        $content = pdapp_read_file($file_path);
        $object = $this->pdapp_decode($content);
        if($this->pdapp_is_expired($object))
        {
            pdapp_delete_file($file_path);
            $this->pdapp_auto_clean_expired();
            return null;
        }

        return $object;
    }

    function pdapp_driver_delete($keyword, $option = array())
    {
        $file_path = $this->pdapp_get_file_path($keyword,true);
        if(pdapp_delete_file($file_path))
        {
            return true;
        } else
        {
            return false;
        }
    }

    /*
     * Return total cache size + auto removed expired files
     */
    function pdapp_driver_stats($option = array())
    {
        $res = array(
            "info"  =>  "",
            "size"  =>  "",
            "data"  =>  "",
       );

        $path = $this->pdapp_get_path();
        $dir = @opendir($path);
        if(!$dir)
        {
            throw new Exception( esc_html("Can't read PATH:".$path), 94);
        }

        $total = 0;
        $removed = 0;
        while($file=readdir($dir))
        {
            if($file!="." && $file!=".." && is_dir($path."/".$file))
            {
                $subdir = @opendir($path."/".$file);
                if(!$subdir)
                {
                    throw new Exception(esc_html("Can't read path:".$path."/".$file), 93);
                }

                while($f = readdir($subdir))
                {
                    if($f!="." && $f!="..")
                    {
                        $file_path = $path."/".$file."/".$f;
                        $size = filesize($file_path);
                        $object = $this->pdapp_decode(pdapp_read_file($file_path));
                        if($this->pdapp_is_expired($object))
                        {
                            pdapp_delete_file($file_path);
                            $removed = $removed + $size;
                        }
                        $total = $total + $size;
                    }
                }
            }
       }

       $res['size']  = $total - $removed;
       $res['info'] = array(
            "Total" => $total,
            "Removed"   => $removed,
            "Current"   => $res['size'],
      );
       return $res;
    }

    function pdapp_auto_clean_expired()
    {
        $autoclean = $this->pdapp_get("keyword_clean_up_driver_files");
        if($autoclean == null)
        {
            $this->pdapp_set("keyword_clean_up_driver_files",3600*24);
            $res = $this->pdapp_stats();
        }
    }

    function pdapp_driver_clean($option = array())
    {
        $path = $this->pdapp_get_path();
        $dir = @opendir($path);
        if(!$dir)
        {
            throw new Exception(esc_html("Can't read PATH:".$path), 94);
        }

        while($file=readdir($dir))
        {
            if($file!="." && $file!=".." && is_dir($path."/".$file))
            {
                $subdir = @opendir($path."/".$file);
                if(!$subdir)
                {
                    throw new Exception(esc_html("Can't read path:".$path."/".$file), 93);
                }

                while($f = readdir($subdir))
                {
                    if($f!="." && $f!="..")
                    {
                        $file_path = $path."/".$file."/".$f;
                        pdapp_delete_file($file_path);
                    }
                }
            }
        }
    }
    
    function pdapp_driver_is_existing($keyword)
    {
        $file_path = $this->pdapp_get_file_path($keyword,true);
        if(!file_exists($file_path))
        {
            return false;
        } else
        {
            $value = $this->pdapp_get($keyword);
            if($value == null)
            {
                return false;
            } else
            {
                return true;
            }
        }
    }

    function pdapp_is_expired($object)
    {
        if(isset($object['expired_time']) && gmdate("U") >= $object['expired_time'])
        {
            return true;
        } else
        {
            return false;
        }
    }
}