Merge pull request #7886 from sarehag/CRM-18114
[civicrm-core.git] / CRM / Utils / VersionCheck.php
index fd6ee3ce2b2b1b12afc1bef7f7c07f82da96e785..9b51ed6e948e0af234ddbf82a781ce3c91c97d06 100644 (file)
@@ -32,8 +32,7 @@
  */
 class CRM_Utils_VersionCheck {
   const
-    PINGBACK_URL = 'http://latest.civicrm.org/stable.php?format=json',
-    CACHEFILE_NAME = '[civicrm.files]/persist/version-info-cache.json',
+    CACHEFILE_NAME = 'version-info-cache.json',
     // after this length of time we fall back on poor-man's cron (7+ days)
     CACHEFILE_EXPIRE = 605000;
 
@@ -68,6 +67,11 @@ class CRM_Utils_VersionCheck {
    */
   public $cronJob = array();
 
+  /**
+   * @var string
+   */
+  public $pingbackUrl = 'http://latest.civicrm.org/stable.php?format=json';
+
   /**
    * Pingback params
    *
@@ -80,7 +84,7 @@ class CRM_Utils_VersionCheck {
    *
    * @var string
    */
-  protected $cacheFile;
+  public $cacheFile;
 
   /**
    * Class constructor.
@@ -88,11 +92,13 @@ class CRM_Utils_VersionCheck {
   public function __construct() {
     $this->localVersion = CRM_Utils_System::version();
     $this->localMajorVersion = $this->getMajorVersion($this->localVersion);
-    $this->cacheFile = Civi::paths()->getPath(self::CACHEFILE_NAME);
+    $this->cacheFile = CRM_Core_Config::singleton()->uploadDir . self::CACHEFILE_NAME;
   }
 
   /**
    * Self-populates version info
+   *
+   * @throws \Exception
    */
   public function initialize() {
     $this->getJob();
@@ -105,6 +111,12 @@ class CRM_Utils_VersionCheck {
     if (!empty($this->cronJob['is_active']) &&
       (!$this->isInfoAvailable || filemtime($this->cacheFile) < $expiryTime)
     ) {
+      // First try updating the files modification time, for 2 reasons:
+      //  - if the file is not writeable, this saves the trouble of pinging back
+      //  - if the remote server is down, this will prevent an immediate retry
+      if (touch($this->cacheFile) === FALSE) {
+        throw new Exception('File not writable');
+      }
       $this->fetch();
     }
   }
@@ -382,7 +394,7 @@ class CRM_Utils_VersionCheck {
       ),
     );
     $ctx = stream_context_create($params);
-    $rawJson = file_get_contents(self::PINGBACK_URL, FALSE, $ctx);
+    $rawJson = file_get_contents($this->pingbackUrl, FALSE, $ctx);
     $versionInfo = $rawJson ? json_decode($rawJson, TRUE) : NULL;
     // If we couldn't fetch or parse the data $versionInfo will be NULL
     // Otherwise it will be an array and we'll cache it.
@@ -408,11 +420,12 @@ class CRM_Utils_VersionCheck {
   /**
    * Save version info to file.
    * @param string $contents
+   * @throws \Exception
    */
   private function writeCacheFile($contents) {
-    $fp = fopen($this->cacheFile, 'w');
-    fwrite($fp, $contents);
-    fclose($fp);
+    if (file_put_contents($this->cacheFile, $contents) === FALSE) {
+      throw new Exception('File not writable');
+    }
   }
 
   /**