Merge pull request #14127 from civicrm/5.13
[civicrm-core.git] / CRM / Utils / VersionCheck.php
index ce14ef4a121f63dbc73f929a7844e197cec001c5..eb72bd94518a904b816b8c3d11311746722e40ea 100644 (file)
@@ -1,9 +1,9 @@
 <?php
 /*
  +--------------------------------------------------------------------+
- | CiviCRM version 4.7                                                |
+ | CiviCRM version 5                                                  |
  +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2018                                |
+ | Copyright CiviCRM LLC (c) 2004-2019                                |
  +--------------------------------------------------------------------+
  | This file is a part of CiviCRM.                                    |
  |                                                                    |
 /**
  *
  * @package CRM
- * @copyright CiviCRM LLC (c) 2004-2018
+ * @copyright CiviCRM LLC (c) 2004-2019
  */
 class CRM_Utils_VersionCheck {
   const
-    CACHEFILE_NAME = 'version-info-cache.json',
-    // After which length of time we expire the cached version info (7+ days).
-    CACHEFILE_EXPIRE = 605000;
+    CACHEFILE_NAME = 'version-msgs-cache.json',
+    // After which length of time we expire the cached version info (3 days).
+    CACHEFILE_EXPIRE = 259200;
 
   /**
    * The version of the current (local) installation
@@ -43,19 +43,12 @@ class CRM_Utils_VersionCheck {
    */
   public $localVersion = NULL;
 
-  /**
-   * The major version (branch name) of the local version
-   *
-   * @var string
-   */
-  public $localMajorVersion;
-
   /**
    * Info about available versions
    *
    * @var array
    */
-  public $versionInfo = array();
+  public $versionInfo = [];
 
   /**
    * @var bool
@@ -65,19 +58,19 @@ class CRM_Utils_VersionCheck {
   /**
    * @var array
    */
-  public $cronJob = array();
+  public $cronJob = [];
 
   /**
    * @var string
    */
-  public $pingbackUrl = 'https://latest.civicrm.org/stable.php?format=json';
+  public $pingbackUrl = 'https://latest.civicrm.org/stable.php?format=summary';
 
   /**
    * Pingback params
    *
    * @var array
    */
-  protected $stats = array();
+  protected $stats = [];
 
   /**
    * Path to cache file
@@ -91,7 +84,6 @@ class CRM_Utils_VersionCheck {
    */
   public function __construct() {
     $this->localVersion = CRM_Utils_System::version();
-    $this->localMajorVersion = $this->getMajorVersion($this->localVersion);
     $this->cacheFile = CRM_Core_Config::singleton()->uploadDir . self::CACHEFILE_NAME;
   }
 
@@ -126,113 +118,19 @@ class CRM_Utils_VersionCheck {
    *
    * @param $info
    */
-  public function setVersionInfo($info) {
-    $this->versionInfo = (array) $info;
-    // Sort version info in ascending order for easier comparisons
-    ksort($this->versionInfo, SORT_NUMERIC);
-  }
-
-  /**
-   * Finds the release info for a minor version.
-   * @param string $version
-   * @return array|null
-   */
-  public function getReleaseInfo($version) {
-    $majorVersion = $this->getMajorVersion($version);
-    if (isset($this->versionInfo[$majorVersion])) {
-      foreach ($this->versionInfo[$majorVersion]['releases'] as $info) {
-        if ($info['version'] == $version) {
-          return $info;
-        }
-      }
-    }
-    return NULL;
-  }
-
-  /**
-   * @param $minorVersion
-   * @return string
-   */
-  public function getMajorVersion($minorVersion) {
-    if (!$minorVersion) {
-      return NULL;
-    }
-    list($a, $b) = explode('.', $minorVersion);
-    return "$a.$b";
+  protected function setVersionInfo($info) {
+    $this->versionInfo = $info;
   }
 
-
   /**
-   * Get the latest version number if it's newer than the local one
-   *
-   * @return array
-   *   Returns version number of the latest release if it is greater than the local version,
-   *   along with the type of upgrade (regular/security) needed and the status of the major
-   *   version
+   * @return array|NULL
+   *   message: string
+   *   title: string
+   *   severity: string
+   *     Ex: 'info', 'notice', 'warning', 'critical'.
    */
-  public function isNewerVersionAvailable() {
-    $return = array(
-      'version' => NULL,
-      'upgrade' => NULL,
-      'status' => NULL,
-    );
-
-    if ($this->versionInfo && $this->localVersion) {
-      if (isset($this->versionInfo[$this->localMajorVersion])) {
-        switch (CRM_Utils_Array::value('status', $this->versionInfo[$this->localMajorVersion])) {
-          case 'stable':
-          case 'lts':
-          case 'testing':
-            // look for latest version in this major version
-            $releases = $this->checkBranchForNewVersion($this->versionInfo[$this->localMajorVersion]);
-            if ($releases['newest']) {
-              $return['version'] = $releases['newest'];
-
-              // check for intervening security releases
-              $return['upgrade'] = ($releases['security']) ? 'security' : 'regular';
-            }
-            break;
-
-          case 'eol':
-          default:
-            // look for latest version ever
-            foreach ($this->versionInfo as $majorVersionNumber => $majorVersion) {
-              if ($majorVersionNumber < $this->localMajorVersion || $majorVersion['status'] == 'testing') {
-                continue;
-              }
-              $releases = $this->checkBranchForNewVersion($this->versionInfo[$majorVersionNumber]);
-
-              if ($releases['newest']) {
-                $return['version'] = $releases['newest'];
-
-                // check for intervening security releases
-                $return['upgrade'] = ($releases['security'] || $return['upgrade'] == 'security') ? 'security' : 'regular';
-              }
-            }
-        }
-        $return['status'] = $this->versionInfo[$this->localMajorVersion]['status'];
-      }
-      else {
-        // Figure if the version is really old or really new
-        $wayOld = TRUE;
-
-        foreach ($this->versionInfo as $majorVersionNumber => $majorVersion) {
-          $wayOld = ($this->localMajorVersion < $majorVersionNumber);
-        }
-
-        if ($wayOld) {
-          $releases = $this->checkBranchForNewVersion($majorVersion);
-
-          $return = array(
-            'version' => $releases['newest'],
-            'upgrade' => 'security',
-            'status' => 'eol',
-          );
-        }
-      }
-    }
-
-    return $return;
+  public function getVersionMessages() {
+    return $this->isInfoAvailable ? $this->versionInfo : NULL;
   }
 
   /**
@@ -243,28 +141,6 @@ class CRM_Utils_VersionCheck {
     $this->pingBack();
   }
 
-  /**
-   * @param $majorVersion
-   * @return null|string
-   */
-  private function checkBranchForNewVersion($majorVersion) {
-    $newerVersion = array(
-      'newest' => NULL,
-      'security' => NULL,
-    );
-    if (!empty($majorVersion['releases'])) {
-      foreach ($majorVersion['releases'] as $release) {
-        if (version_compare($this->localVersion, $release['version']) < 0) {
-          $newerVersion['newest'] = $release['version'];
-          if (CRM_Utils_Array::value('security', $release)) {
-            $newerVersion['security'] = $release['version'];
-          }
-        }
-      }
-    }
-    return $newerVersion;
-  }
-
   /**
    * Collect info about the site to be sent as pingback data.
    */
@@ -273,11 +149,11 @@ class CRM_Utils_VersionCheck {
     $siteKey = md5(defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY : '');
 
     // Calorie-free pingback for alphas
-    $this->stats = array('version' => $this->localVersion);
+    $this->stats = ['version' => $this->localVersion];
 
     // Non-alpha versions get the full treatment
     if ($this->localVersion && !strpos($this->localVersion, 'alpha')) {
-      $this->stats += array(
+      $this->stats += [
         'hash' => md5($siteKey . $config->userFrameworkBaseURL),
         'uf' => $config->userFramework,
         'lang' => $config->lcMessages,
@@ -286,7 +162,7 @@ class CRM_Utils_VersionCheck {
         'PHP' => phpversion(),
         'MySQL' => CRM_CORE_DAO::singleValueQuery('SELECT VERSION()'),
         'communityMessagesUrl' => Civi::settings()->get('communityMessagesUrl'),
-      );
+      ];
       $this->getDomainStats();
       $this->getPayProcStats();
       $this->getEntityStats();
@@ -301,13 +177,12 @@ class CRM_Utils_VersionCheck {
     $dao = new CRM_Financial_DAO_PaymentProcessor();
     $dao->is_active = 1;
     $dao->find();
-    $ppTypes = array();
-
-    // Get title and id for all processor types
-    $ppTypeNames = CRM_Core_PseudoConstant::paymentProcessorType();
+    $ppTypes = [];
 
+    // Get title for all processor types
+    // FIXME: This should probably be getName, but it has always returned translated label so we stick with that for now as it would affect stats
     while ($dao->fetch()) {
-      $ppTypes[] = $ppTypeNames[$dao->payment_processor_type_id];
+      $ppTypes[] = CRM_Core_PseudoConstant::getLabel('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', $dao->payment_processor_type_id);
     }
     // add the .-separated list of the processor types
     $this->stats['PPTypes'] = implode(',', array_unique($ppTypes));
@@ -318,7 +193,7 @@ class CRM_Utils_VersionCheck {
    * Add info to the 'entities' array
    */
   private function getEntityStats() {
-    $tables = array(
+    $tables = [
       'CRM_Activity_DAO_Activity' => 'is_test = 0',
       'CRM_Case_DAO_Case' => 'is_deleted = 0',
       'CRM_Contact_DAO_Contact' => 'is_deleted = 0',
@@ -341,17 +216,17 @@ class CRM_Utils_VersionCheck {
       'CRM_Pledge_DAO_Pledge' => 'is_test = 0',
       'CRM_Pledge_DAO_PledgeBlock' => NULL,
       'CRM_Mailing_Event_DAO_Delivered' => NULL,
-    );
+    ];
     foreach ($tables as $daoName => $where) {
       $dao = new $daoName();
       if ($where) {
         $dao->whereAdd($where);
       }
       $short_name = substr($daoName, strrpos($daoName, '_') + 1);
-      $this->stats['entities'][] = array(
+      $this->stats['entities'][] = [
         'name' => $short_name,
         'size' => $dao->count(),
-      );
+      ];
     }
   }
 
@@ -363,11 +238,11 @@ class CRM_Utils_VersionCheck {
     // Core components
     $config = CRM_Core_Config::singleton();
     foreach ($config->enableComponents as $comp) {
-      $this->stats['extensions'][] = array(
+      $this->stats['extensions'][] = [
         'name' => 'org.civicrm.component.' . strtolower($comp),
         'enabled' => 1,
         'version' => $this->stats['version'],
-      );
+      ];
     }
     // Contrib extensions
     $mapper = CRM_Extension_System::singleton()->getMapper();
@@ -375,11 +250,11 @@ class CRM_Utils_VersionCheck {
     $dao->find();
     while ($dao->fetch()) {
       $info = $mapper->keyToInfo($dao->full_name);
-      $this->stats['extensions'][] = array(
+      $this->stats['extensions'][] = [
         'name' => $dao->full_name,
         'enabled' => $dao->is_active,
         'version' => isset($info->version) ? $info->version : NULL,
-      );
+      ];
     }
   }
 
@@ -390,21 +265,21 @@ class CRM_Utils_VersionCheck {
     // Start with default value NULL, then check to see if there's a better
     // value to be had.
     $this->stats['domain_isoCode'] = NULL;
-    $params = array(
+    $params = [
       'id' => CRM_Core_Config::domainID(),
-    );
+    ];
     $domain_result = civicrm_api3('domain', 'getsingle', $params);
     if (!empty($domain_result['contact_id'])) {
-      $address_params = array(
+      $address_params = [
         'contact_id' => $domain_result['contact_id'],
         'is_primary' => 1,
         'sequential' => 1,
-      );
+      ];
       $address_result = civicrm_api3('address', 'get', $address_params);
       if ($address_result['count'] == 1 && !empty($address_result['values'][0]['country_id'])) {
-        $country_params = array(
+        $country_params = [
           'id' => $address_result['values'][0]['country_id'],
-        );
+        ];
         $country_result = civicrm_api3('country', 'getsingle', $country_params);
         if (!empty($country_result['iso_code'])) {
           $this->stats['domain_isoCode'] = $country_result['iso_code'];
@@ -418,13 +293,13 @@ class CRM_Utils_VersionCheck {
    * Store results in the cache file
    */
   private function pingBack() {
-    $params = array(
-      'http' => array(
+    $params = [
+      'http' => [
         'method' => 'POST',
         'header' => 'Content-type: application/x-www-form-urlencoded',
         'content' => http_build_query($this->stats),
-      ),
-    );
+      ],
+    ];
     $ctx = stream_context_create($params);
     $rawJson = file_get_contents($this->pingbackUrl, FALSE, $ctx);
     $versionInfo = $rawJson ? json_decode($rawJson, TRUE) : NULL;
@@ -460,16 +335,25 @@ class CRM_Utils_VersionCheck {
     }
   }
 
+  /**
+   * Removes cached version info.
+   */
+  public function flushCache() {
+    if (file_exists($this->cacheFile)) {
+      unlink($this->cacheFile);
+    }
+  }
+
   /**
    * Lookup version_check scheduled job
    */
   private function getJob() {
-    $jobs = civicrm_api3('Job', 'get', array(
+    $jobs = civicrm_api3('Job', 'get', [
       'sequential' => 1,
       'api_action' => "version_check",
       'api_entity' => "job",
-    ));
-    $this->cronJob = CRM_Utils_Array::value(0, $jobs['values'], array());
+    ]);
+    $this->cronJob = CRM_Utils_Array::value(0, $jobs['values'], []);
   }
 
 }