3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Utils_VersionCheck
{
19 CACHEFILE_NAME
= 'version-msgs-cache.json',
20 // After which length of time we expire the cached version info (3 days).
21 CACHEFILE_EXPIRE
= 259200;
24 * The version of the current (local) installation
28 public $localVersion = NULL;
31 * Info about available versions
35 public $versionInfo = [];
40 public $isInfoAvailable;
50 public $pingbackUrl = 'https://latest.civicrm.org/stable.php?format=summary';
57 protected $stats = [];
69 public function __construct() {
70 $this->localVersion
= CRM_Utils_System
::version();
71 $this->cacheFile
= CRM_Core_Config
::singleton()->uploadDir
. self
::CACHEFILE_NAME
;
75 * Self-populates version info
80 public function initialize($force = FALSE) {
83 // Populate remote $versionInfo from cache file
84 $this->isInfoAvailable
= $this->readCacheFile();
86 // Fallback if scheduled job is enabled but has failed to run.
87 $expiryTime = time() - self
::CACHEFILE_EXPIRE
;
88 if ($force ||
(!empty($this->cronJob
['is_active']) &&
89 (!$this->isInfoAvailable ||
filemtime($this->cacheFile
) < $expiryTime)
91 // First try updating the files modification time, for 2 reasons:
92 // - if the file is not writeable, this saves the trouble of pinging back
93 // - if the remote server is down, this will prevent an immediate retry
94 if (touch($this->cacheFile
) === FALSE) {
95 throw new Exception('File not writable');
106 protected function setVersionInfo($info) {
107 $this->versionInfo
= $info;
115 * Ex: 'info', 'notice', 'warning', 'critical'.
117 public function getVersionMessages() {
118 return $this->isInfoAvailable ?
$this->versionInfo
: NULL;
122 * Called by version_check cron job
124 public function fetch() {
125 $this->getSiteStats();
130 * Collect info about the site to be sent as pingback data.
132 private function getSiteStats() {
133 $config = CRM_Core_Config
::singleton();
134 $siteKey = md5(defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY
: '');
136 // Calorie-free pingback for alphas
137 $this->stats
= ['version' => $this->localVersion
];
139 // Non-alpha versions get the full treatment
140 if ($this->localVersion
&& !strpos($this->localVersion
, 'alpha')) {
142 'hash' => md5($siteKey . $config->userFrameworkBaseURL
),
143 'uf' => $config->userFramework
,
144 'lang' => $config->lcMessages
,
145 'co' => $config->defaultContactCountry
,
146 'ufv' => $config->userSystem
->getVersion(),
147 'PHP' => phpversion(),
148 'MySQL' => CRM_Core_DAO
::singleValueQuery('SELECT VERSION()'),
149 'communityMessagesUrl' => Civi
::settings()->get('communityMessagesUrl'),
151 $this->getDomainStats();
152 $this->getPayProcStats();
153 $this->getEntityStats();
154 $this->getExtensionStats();
159 * Get active payment processor types.
161 private function getPayProcStats() {
162 $dao = new CRM_Financial_DAO_PaymentProcessor();
167 // Get title for all processor types
168 // 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
169 while ($dao->fetch()) {
170 $ppTypes[] = CRM_Core_PseudoConstant
::getLabel('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', $dao->payment_processor_type_id
);
172 // add the .-separated list of the processor types
173 $this->stats
['PPTypes'] = implode(',', array_unique($ppTypes));
177 * Fetch counts from entity tables.
178 * Add info to the 'entities' array
180 private function getEntityStats() {
181 // FIXME hardcoded list = bad
183 'CRM_Activity_DAO_Activity' => 'is_test = 0',
184 'CRM_Case_DAO_Case' => 'is_deleted = 0',
185 'CRM_Contact_DAO_Contact' => 'is_deleted = 0',
186 'CRM_Contact_DAO_Relationship' => NULL,
187 'CRM_Campaign_DAO_Campaign' => NULL,
188 'CRM_Contribute_DAO_Contribution' => 'is_test = 0',
189 'CRM_Contribute_DAO_ContributionPage' => 'is_active = 1',
190 'CRM_Contribute_DAO_ContributionProduct' => NULL,
191 'CRM_Contribute_DAO_Widget' => 'is_active = 1',
192 'CRM_Core_DAO_Discount' => NULL,
193 'CRM_Price_DAO_PriceSetEntity' => NULL,
194 'CRM_Core_DAO_UFGroup' => 'is_active = 1',
195 'CRM_Event_DAO_Event' => 'is_active = 1',
196 'CRM_Event_DAO_Participant' => 'is_test = 0',
197 'CRM_Friend_DAO_Friend' => 'is_active = 1',
198 'CRM_Grant_DAO_Grant' => NULL,
199 'CRM_Mailing_DAO_Mailing' => 'is_completed = 1',
200 'CRM_Member_DAO_Membership' => 'is_test = 0',
201 'CRM_Member_DAO_MembershipBlock' => 'is_active = 1',
202 'CRM_Pledge_DAO_Pledge' => 'is_test = 0',
203 'CRM_Pledge_DAO_PledgeBlock' => NULL,
204 'CRM_Mailing_Event_DAO_Delivered' => NULL,
206 foreach ($tables as $daoName => $where) {
207 if (class_exists($daoName)) {
208 /* @var \CRM_Core_DAO $dao */
209 $dao = new $daoName();
211 $dao->whereAdd($where);
213 $short_name = substr($daoName, strrpos($daoName, '_') +
1);
214 $this->stats
['entities'][] = [
215 'name' => $short_name,
216 'size' => $dao->count(),
223 * Fetch stats about enabled components/extensions
224 * Add info to the 'extensions' array
226 private function getExtensionStats() {
228 $config = CRM_Core_Config
::singleton();
229 foreach ($config->enableComponents
as $comp) {
230 $this->stats
['extensions'][] = [
231 'name' => 'org.civicrm.component.' . strtolower($comp),
233 'version' => $this->stats
['version'],
236 // Contrib extensions
237 $mapper = CRM_Extension_System
::singleton()->getMapper();
238 $dao = new CRM_Core_DAO_Extension();
240 while ($dao->fetch()) {
241 $info = $mapper->keyToInfo($dao->full_name
);
242 $this->stats
['extensions'][] = [
243 'name' => $dao->full_name
,
244 'enabled' => $dao->is_active
,
245 'version' => $info->version ??
NULL,
251 * Fetch stats about domain and add to 'stats' array.
253 private function getDomainStats() {
254 // Start with default value NULL, then check to see if there's a better
256 $this->stats
['domain_isoCode'] = NULL;
258 'id' => CRM_Core_Config
::domainID(),
260 $domain_result = civicrm_api3('domain', 'getsingle', $params);
261 if (!empty($domain_result['contact_id'])) {
263 'contact_id' => $domain_result['contact_id'],
267 $address_result = civicrm_api3('address', 'get', $address_params);
268 if ($address_result['count'] == 1 && !empty($address_result['values'][0]['country_id'])) {
270 'id' => $address_result['values'][0]['country_id'],
272 $country_result = civicrm_api3('country', 'getsingle', $country_params);
273 if (!empty($country_result['iso_code'])) {
274 $this->stats
['domain_isoCode'] = $country_result['iso_code'];
281 * Send the request to civicrm.org
282 * Store results in the cache file
284 private function pingBack() {
288 'header' => 'Content-type: application/x-www-form-urlencoded',
289 'content' => http_build_query($this->stats
),
292 $ctx = stream_context_create($params);
293 $rawJson = file_get_contents($this->pingbackUrl
, FALSE, $ctx);
294 $versionInfo = $rawJson ?
json_decode($rawJson, TRUE) : NULL;
295 // If we couldn't fetch or parse the data $versionInfo will be NULL
296 // Otherwise it will be an array and we'll cache it.
297 // Note the array may be empty e.g. in the case of a pre-alpha with no releases
298 $this->isInfoAvailable
= $versionInfo !== NULL;
299 if ($this->isInfoAvailable
) {
300 $this->writeCacheFile($rawJson);
301 $this->setVersionInfo($versionInfo);
308 private function readCacheFile() {
309 if (file_exists($this->cacheFile
)) {
310 $this->setVersionInfo(json_decode(file_get_contents($this->cacheFile
), TRUE));
317 * Save version info to file.
318 * @param string $contents
321 private function writeCacheFile($contents) {
322 if (file_put_contents($this->cacheFile
, $contents) === FALSE) {
323 throw new Exception('File not writable');
328 * Removes cached version info.
330 public function flushCache() {
331 if (file_exists($this->cacheFile
)) {
332 unlink($this->cacheFile
);
337 * Lookup version_check scheduled job
339 private function getJob() {
340 $jobs = civicrm_api3('Job', 'get', [
342 'api_action' => "version_check",
343 'api_entity' => "job",
345 $this->cronJob
= CRM_Utils_Array
::value(0, $jobs['values'], []);