/*!
\static
Stores the data of the cache with the key \a $key to a file.
\return false if the cache does not exist.
177655
static function storeCache( $key, $templateFilepath )
    {
        if ( !eZTemplateTreeCache::isCacheEnabled() )
            return false;
        $templateCache =& eZTemplateTreeCache::cacheTable();
        $key = eZTemplateTreeCache::internalKey( $key );
        if ( !isset( $templateCache[$key] ) )
        {
            eZDebug::writeDebug( "Template cache for key '$key' does not exist, cannot store cache", __METHOD__ );
            return;
        }
        $cacheFileName = eZTemplateTreeCache::treeCacheFilename( $key, $templateFilepath );

        $cache =& $templateCache[$key];

        $php = new eZPHPCreator( eZTemplateTreeCache::cacheDirectory(), $cacheFileName );
        $php->addVariable( 'eZTemplateTreeCacheCodeDate', eZTemplateTreeCache::CODE_DATE );
        $php->addSpace();
        $php->addVariable( 'TemplateInfo', $cache['info'] );
        $php->addSpace();
        $php->addVariable( 'TemplateRoot', $cache['root'] );
        $php->store( true );
    }
493390
public static function forever($key, $data)
    {
        if (is_callable($data)) {
            $content = $data();
        } else {
            $content = $data;
        }

        $meta['__bow_meta'] = ['expire_at' => '+'];

        $meta['content'] = $content;

        return (bool) file_put_contents(
            static::makeHashFilename($key, true),
            serialize($meta)
        );
    }
474754
public function exists($key) {

		$files = glob(Path :: get('cache-shared') . $this -> generateName($key));

		if(true === is_array($files) && count($files) > 0) {

			$file 		= new File($files[0]);
			$expiration = $this -> extractExpiration($file);

			if($expiration -> time >= time()) {
				return true;
			}

			$file -> delete();
		}

		return false;
	}
554843
public static function SaveCache($CacheName) {
      if ($CacheName != 'locale') return;
      
      if (!array_key_exists($CacheName,self::$Caches)) 
         return FALSE;
      
      $UseCache = (Gdn::Cache()->Type() == Gdn_Cache::CACHE_TYPE_MEMORY && Gdn::Cache()->ActiveEnabled());
      if ($UseCache) {
         $CacheKey = sprintf(Gdn_LibraryMap::CACHE_CACHE_NAME_FORMAT, $CacheName);
         $Stored = Gdn::Cache()->Store($CacheKey, self::$Caches[$CacheName]['cache']);
      } else {
         $FileName = self::$Caches[$CacheName]['ondisk'];
         $CacheContents = "";
         foreach (self::$Caches[$CacheName]['cache'] as $SectionTitle => $SectionData) {
            $CacheContents .= "[{$SectionTitle}]\n";
            foreach ($SectionData as $StoreKey => $StoreValue) {
               $CacheContents .= "{$StoreKey} = \"{$StoreValue}\"\n";
            }
         }
         try {
            Gdn_FileSystem::SaveFile(PATH_CACHE.DS.$FileName, $CacheContents, LOCK_EX);
         }
         catch (Exception $e) {}
      }
   }
1330307
public function store($key, $data, $expiration = 0) {
    $storeData = array(
      'time'   => time(),
      'expire' => $expiration,
      'data'   => serialize($data)
    );
    $dataArray = $this->_loadCache();
    if (true === is_array($dataArray)) {
      $dataArray[$key] = $storeData;
    } else {
      $dataArray = array($key => $storeData);
    }
    $cacheData = json_encode($dataArray);
    file_put_contents($this->getCacheDir(), $cacheData);
    return $this;
  }
1085407
public function isCached($key) {
        // The actual working horse. The method does not only check existence of the key. It retrieves the value and stores
        // it in the local reference pool, so following cache queries can use the local reference.

        // check local reference pool
        if ($this->getReferencePool()->isCached($key))
            return true;

        // query APC cache
        $data = apc_fetch($this->namespace.'::'.$key);
        if (!$data)                                     // cache miss
            return false;

        // cache hit
        $created = $data[0];                            // data: [created, expires, serialized([$value, $dependency])]
        $expires = $data[1];

        // check expiration
        if ($expires && $created+$expires < time()) {
            $this->drop($key);
            return false;
        }

        // unpack serialized value
        $data[2]    = unserialize($data[2]);
        $value      = $data[2][0];
        $dependency = $data[2][1];

        // check dependency
        if ($dependency) {
            $minValid = $dependency->getMinValidity();

            if ($minValid) {
                if (time() > $created+$minValid) {
                    if (!$dependency->isValid()) {
                        $this->drop($key);
                        return false;
                    }
                    // reset the creation time by writing back to the cache (resets $minValid period)
                    return $this->set($key, $value, $expires, $dependency);
                }
            }
            elseif (!$dependency->isValid()) {
                $this->drop($key);
                return false;
            }
        }

        // store the validated value in the local reference pool
        $this->getReferencePool()->set($key, $value, Cache::EXPIRES_NEVER, $dependency);
        return true;
    }
69219
function save($args)
    {
        $args = parent::save($args);

        $this->_load_drivers();

        $data = $args['path'] ? file_get_contents($args['path']) : $args['data'];

        $args['data'] = null;

        $key  = $this->_key($args);
        $data = base64_encode($data);

        $status = $this->cache->write($key, $data);

        if (!$status && $this->mem_cache) {
            $status = $this->mem_cache->write($key, $data);
        }

        if ($status) {
            $args['id'] = $key;
            $args['status'] = true;
        }

        return $args;
    }
1129211
public function do_get($key)
    {
        $file = $this->_getFileName($key);

        if (@filemtime($file) >= time()) {
            return file_get_contents($file);
        } else {
            return false;
        }
    }
391649
public function write( $key, $contents ) {
		$filename = $this->prepare_write( $key );

		if ( $filename ) {
			return file_put_contents( $filename, $contents ) && touch( $filename );
		}

		return false;
	}
1024320
public function has($key = '')
    {
        try {
            if ($this->cacheInstance !== NULL && is_object($this->cacheInstance)) {
                /**
                 * @var $cache object
                 */
                $cache = $this->cacheInstance->getItem($key);
                if (!$cache->isHit()) {
                    return FALSE;
                } else {
                    return TRUE;
                }
            } else {
                $this->debug->error(__FUNCTION__, 'Unavailable cacheInstance');

                return FALSE;
            }
        }
        catch (\Exception $e) {
            $message = 'Error File: ' . $e->getFile() . ' - Line: ' . $e->getLine() . ' - Code: ' . $e->getCode() . ' - Message: ' . $e->getMessage();
            $this->debug->error(__FUNCTION__, $message);

            return $message;
        }
    }
684981
public function hasFile($key)
    {
        if (! is_array($files = $this->file($key))) {
            $files = [$files];
        }

        foreach ($files as $file) {
            if ($this->isValidFile($file)) {
                return true;
            }
        }

        return false;
    }
249237
public function get($key)
    {
        $filePath = $this->getFilePathFromKey($key);

        if (!file_exists($filePath)) {
            return false;
        }

        if (!is_readable($filePath)) {
            return false;
        }

        $cacheFileData = file_get_contents($filePath);

        if ($this->config['gzipCompression']) {
            $cacheFileData = gzuncompress($cacheFileData);
        }

        $cacheObj = json_decode($cacheFileData);

        // Unable to decode JSON (could happen if compression was turned off while compressed caches still exist)
        if ($cacheObj === null) {
            return false;
        }

        if (!function_exists('sys_getloadavg')) {
            throw new Exception('Your PHP installation does not support `sys_getloadavg` (Windows?). Please set `unixLoadUpperThreshold` to `-1` in your RWFileCache config.');
        }

        if ($this->config['unixLoadUpperThreshold'] == -1) {
            $unixLoad = [0 => PHP_INT_MAX, 1 => PHP_INT_MAX, 2 => PHP_INT_MAX];
        } else {
            $unixLoad = sys_getloadavg();
        }

        if ($cacheObj->expiryTimestamp > time() || $unixLoad[0] >= $this->config['unixLoadUpperThreshold']) {
            // Cache item has not yet expired or system load is too high
            $content = $cacheObj->content;

            if (($unserializedContent = @unserialize($content)) !== false) {
                // Normal unserialization
                $content = $unserializedContent;
            } elseif ($content == serialize(false)) {
                // Edge case to handle boolean false being stored
                $content = false;
            }

            return $content;
        } else {
            // Cache item has expired
            return false;
        }
    }
117960
public function write($key, $data)
    {
        if ($data === '' || !$this->_init) {
            return false;
        }

        $key = $this->_key($key);

        if ($this->_setKey($key, true) === false) {
            return false;
        }

        $lineBreak = "\n";

        if ($this->_config['isWindows']) {
            $lineBreak = "\r\n";
        }

        if (!empty($this->_config['serialize'])) {
            if ($this->_config['isWindows']) {
                $data = str_replace('\\', '\\\\\\\\', serialize($data));
            } else {
                $data = serialize($data);
            }
        }

        $duration = $this->_config['duration'];
        $expires = time() + $duration;
        $contents = implode([$expires, $lineBreak, $data, $lineBreak]);

        if ($this->_config['lock']) {
            $this->_File->flock(LOCK_EX);
        }

        $this->_File->rewind();
        $success = $this->_File->ftruncate(0) &&
            $this->_File->fwrite($contents) &&
            $this->_File->fflush();

        if ($this->_config['lock']) {
            $this->_File->flock(LOCK_UN);
        }
        $this->_File = null;

        return $success;
    }
1189505
private function createCacheFile($key)
    {
        $cache_file = $this->path($key);
        if (!file_exists($cache_file)) {
            $directory = dirname($cache_file);
            if (!is_dir($directory)) {
                $make_dir_result = mkdir($directory, 0755, true);
                if ($make_dir_result === false) {
                    return false;
                }
            }
            $create_result = touch($cache_file);
            if ($create_result === false) {
                return false;
            }
        }

        return $cache_file;
    }
11042
public function has($key) {
		$this->refresh();
		$keys = explode('.', $key);
		$conf = $this->cache;
		foreach ($keys as $v) {
			if (isset($conf[$v])) {
				$conf = $conf[$v];
			} else {
				return false;
			}
		}
		return true;
	}
741522
public function save($key, $data, $force = false, $ttl = 1440) {
        $ttl = $ttl * 60; // Minutes to Seconds
        // Store result from last query for checking if cache is existing
        // This will avoid locked database error for sqlite3
        $cache_exists = $this->exists($key);

        if (!$cache_exists || $force) {
            // Build data into a array
            $data = [
                'date_created' => time(),
                'ttl' => $ttl,
                'data' => $data
            ];
            
            file_put_contents($this->_storage_path . $this->_encrypt($key), base64_encode(serialize($data)));
            
            return true;
        }
        
        return false;
    }
941791
static function storeCachedFile( $file, $content )
    {
        $dir = dirname( $file );
        if ( !is_dir( $dir ) )
        {
            eZDir::mkdir( $dir, false, true );
        }

        $oldumask = umask( 0 );

        $tmpFileName = $file . '.' . md5( $file. uniqid( "ezp". getmypid(), true ) );

        // Remove files, this might be necessary for Windows
        @unlink( $tmpFileName );

        // Write the new cache file with the data attached
        $fp = fopen( $tmpFileName, 'w' );
        if ( $fp )
        {
            $comment = ( eZINI::instance( 'staticcache.ini' )->variable( 'CacheSettings', 'AppendGeneratedTime' ) === 'true' ) ? "<!-- Generated: " . date( 'Y-m-d H:i:s' ). " -->\n\n" : null;

            fwrite( $fp, $content . $comment );
            fclose( $fp );
            eZFile::rename( $tmpFileName, $file, false, eZFile::CLEAN_ON_FAILURE | eZFile::APPEND_DEBUG_ON_FAILURE );

            $perm = eZINI::instance()->variable( 'FileSettings', 'StorageFilePermissions' );
            chmod( $file, octdec( $perm ) );
        }

        umask( $oldumask );
    }