Jelajahi Sumber

#5488 File cache: fix issue with broken cache files sometimes

Aleksandr Trofimov 5 bulan lalu
induk
melakukan
4e0bc0918c
2 mengubah file dengan 18 tambahan dan 15 penghapusan
  1. 9 7
      inc/classes/BxDolCacheFile.php
  2. 9 8
      inc/classes/BxDolCacheFileHtml.php

+ 9 - 7
inc/classes/BxDolCacheFile.php

@@ -52,17 +52,19 @@ class BxDolCacheFile extends BxDolCache
      */
     function setData($sKey, $mixedData, $iTTL = false)
     {
-        if(file_exists($this->sPath . $sKey) && !is_writable($this->sPath . $sKey))
-           return false;
+        $sFileName = $this->sPath . $sKey;
+        $sFileNameTmp = $this->sPath . '.' . uniqid('', true) . '.tmp';
 
-        if(!($rHandler = fopen($this->sPath . $sKey, 'w')))
+        if(file_exists($sFileName) && !is_writable($sFileName))
            return false;
 
-        fwrite($rHandler, '<?php $mixedData=' . var_export($mixedData, true) . '; ?>');
-        fclose($rHandler);
-        @chmod($this->sPath . $sKey, 0666);
+        $content = '<?php $mixedData=' . var_export($mixedData, true) . '; ?>';
+        if (false === file_put_contents($sFileNameTmp, $content))
+            return false;
+        rename($sFileNameTmp, $sFileName);
+        @chmod($sFileName, 0666);
 
-        if (function_exists('opcache_invalidate')) opcache_invalidate($this->sPath . $sKey);
+        if (function_exists('opcache_invalidate')) opcache_invalidate($sFileName, true);
 
         return true;
     }

+ 9 - 8
inc/classes/BxDolCacheFileHtml.php

@@ -51,18 +51,19 @@ class BxDolCacheFileHtml extends BxDolCacheFile
      */
     function setData($sKey, $mixedData, $iTTL = false)
     {
-        if(file_exists($this->sPath . $sKey) && !is_writable($this->sPath . $sKey))
-           return false;
+        $sFileName = $this->sPath . $sKey;
+        $sFileNameTmp = $this->sPath . '.' . uniqid('', true) . '.tmp';
 
-        if(!($rHandler = fopen($this->sPath . $sKey, 'w')))
+        if(file_exists($sFileName) && !is_writable($sFileName))
            return false;
 
-        fwrite($rHandler, $mixedData);
-        fclose($rHandler);
-        @chmod($this->sPath . $sKey, 0666);
+        if (false === file_put_contents($sFileNameTmp, $mixedData))
+            return false;
+        rename($sFileNameTmp, $sFileName);
+        @chmod($sFileName, 0666);
+
+        if (function_exists('opcache_invalidate')) opcache_invalidate($sFileName, true);
 
-        if (function_exists('opcache_invalidate')) opcache_invalidate($this->sPath . $sKey);
-        
         return true;
     }
 }