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
79 public function initialize() {
82 // Populate remote $versionInfo from cache file
83 $this->isInfoAvailable
= $this->readCacheFile();
85 // Fallback if scheduled job is enabled but has failed to run.
86 $expiryTime = time() - self
::CACHEFILE_EXPIRE
;
87 if (!empty($this->cronJob
['is_active']) &&
88 (!$this->isInfoAvailable ||
filemtime($this->cacheFile
) < $expiryTime)
90 // First try updating the files modification time, for 2 reasons:
91 // - if the file is not writeable, this saves the trouble of pinging back
92 // - if the remote server is down, this will prevent an immediate retry
93 if (touch($this->cacheFile
) === FALSE) {
94 throw new Exception('File not writable');
105 protected function setVersionInfo($info) {
106 $this->versionInfo
= $info;
114 * Ex: 'info', 'notice', 'warning', 'critical'.
116 public function getVersionMessages() {
117 return $this->isInfoAvailable ?
$this->versionInfo
: NULL;
121 * Called by version_check cron job
123 public function fetch() {
124 $this->getSiteStats();
129 * Collect info about the site to be sent as pingback data.
131 private function getSiteStats() {
132 $config = CRM_Core_Config
::singleton();
133 $siteKey = md5(defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY
: '');
135 // Calorie-free pingback for alphas
136 $this->stats
= ['version' => $this->localVersion
];
138 // Non-alpha versions get the full treatment
139 if ($this->localVersion
&& !strpos($this->localVersion
, 'alpha')) {
141 'hash' => md5($siteKey . $config->userFrameworkBaseURL
),
142 'uf' => $config->userFramework
,
143 'lang' => $config->lcMessages
,
144 'co' => $config->defaultContactCountry
,
145 'ufv' => $config->userSystem
->getVersion(),
146 'PHP' => phpversion(),
147 'MySQL' => CRM_Core_DAO
::singleValueQuery('SELECT VERSION()'),
148 'communityMessagesUrl' => Civi
::settings()->get('communityMessagesUrl'),
150 $this->getDomainStats();
151 $this->getPayProcStats();
152 $this->getEntityStats();
153 $this->getExtensionStats();
158 * Get active payment processor types.
160 private function getPayProcStats() {
161 $dao = new CRM_Financial_DAO_PaymentProcessor();
166 // Get title for all processor types
167 // 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
168 while ($dao->fetch()) {
169 $ppTypes[] = CRM_Core_PseudoConstant
::getLabel('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', $dao->payment_processor_type_id
);
171 // add the .-separated list of the processor types
172 $this->stats
['PPTypes'] = implode(',', array_unique($ppTypes));
176 * Fetch counts from entity tables.
177 * Add info to the 'entities' array
179 private function getEntityStats() {
181 'CRM_Activity_DAO_Activity' => 'is_test = 0',
182 'CRM_Case_DAO_Case' => 'is_deleted = 0',
183 'CRM_Contact_DAO_Contact' => 'is_deleted = 0',
184 'CRM_Contact_DAO_Relationship' => NULL,
185 'CRM_Campaign_DAO_Campaign' => NULL,
186 'CRM_Contribute_DAO_Contribution' => 'is_test = 0',
187 'CRM_Contribute_DAO_ContributionPage' => 'is_active = 1',
188 'CRM_Contribute_DAO_ContributionProduct' => NULL,
189 'CRM_Contribute_DAO_Widget' => 'is_active = 1',
190 'CRM_Core_DAO_Discount' => NULL,
191 'CRM_Price_DAO_PriceSetEntity' => NULL,
192 'CRM_Core_DAO_UFGroup' => 'is_active = 1',
193 'CRM_Event_DAO_Event' => 'is_active = 1',
194 'CRM_Event_DAO_Participant' => 'is_test = 0',
195 'CRM_Friend_DAO_Friend' => 'is_active = 1',
196 'CRM_Grant_DAO_Grant' => NULL,
197 'CRM_Mailing_DAO_Mailing' => 'is_completed = 1',
198 'CRM_Member_DAO_Membership' => 'is_test = 0',
199 'CRM_Member_DAO_MembershipBlock' => 'is_active = 1',
200 'CRM_Pledge_DAO_Pledge' => 'is_test = 0',
201 'CRM_Pledge_DAO_PledgeBlock' => NULL,
202 'CRM_Mailing_Event_DAO_Delivered' => NULL,
204 foreach ($tables as $daoName => $where) {
205 $dao = new $daoName();
207 $dao->whereAdd($where);
209 $short_name = substr($daoName, strrpos($daoName, '_') +
1);
210 $this->stats
['entities'][] = [
211 'name' => $short_name,
212 'size' => $dao->count(),
218 * Fetch stats about enabled components/extensions
219 * Add info to the 'extensions' array
221 private function getExtensionStats() {
223 $config = CRM_Core_Config
::singleton();
224 foreach ($config->enableComponents
as $comp) {
225 $this->stats
['extensions'][] = [
226 'name' => 'org.civicrm.component.' . strtolower($comp),
228 'version' => $this->stats
['version'],
231 // Contrib extensions
232 $mapper = CRM_Extension_System
::singleton()->getMapper();
233 $dao = new CRM_Core_DAO_Extension();
235 while ($dao->fetch()) {
236 $info = $mapper->keyToInfo($dao->full_name
);
237 $this->stats
['extensions'][] = [
238 'name' => $dao->full_name
,
239 'enabled' => $dao->is_active
,
240 'version' => $info->version ??
NULL,
246 * Fetch stats about domain and add to 'stats' array.
248 private function getDomainStats() {
249 // Start with default value NULL, then check to see if there's a better
251 $this->stats
['domain_isoCode'] = NULL;
253 'id' => CRM_Core_Config
::domainID(),
255 $domain_result = civicrm_api3('domain', 'getsingle', $params);
256 if (!empty($domain_result['contact_id'])) {
258 'contact_id' => $domain_result['contact_id'],
262 $address_result = civicrm_api3('address', 'get', $address_params);
263 if ($address_result['count'] == 1 && !empty($address_result['values'][0]['country_id'])) {
265 'id' => $address_result['values'][0]['country_id'],
267 $country_result = civicrm_api3('country', 'getsingle', $country_params);
268 if (!empty($country_result['iso_code'])) {
269 $this->stats
['domain_isoCode'] = $country_result['iso_code'];
276 * Send the request to civicrm.org
277 * Store results in the cache file
279 private function pingBack() {
283 'header' => 'Content-type: application/x-www-form-urlencoded',
284 'content' => http_build_query($this->stats
),
287 $ctx = stream_context_create($params);
288 $rawJson = file_get_contents($this->pingbackUrl
, FALSE, $ctx);
289 $versionInfo = $rawJson ?
json_decode($rawJson, TRUE) : NULL;
290 // If we couldn't fetch or parse the data $versionInfo will be NULL
291 // Otherwise it will be an array and we'll cache it.
292 // Note the array may be empty e.g. in the case of a pre-alpha with no releases
293 $this->isInfoAvailable
= $versionInfo !== NULL;
294 if ($this->isInfoAvailable
) {
295 $this->writeCacheFile($rawJson);
296 $this->setVersionInfo($versionInfo);
303 private function readCacheFile() {
304 if (file_exists($this->cacheFile
)) {
305 $this->setVersionInfo(json_decode(file_get_contents($this->cacheFile
), TRUE));
312 * Save version info to file.
313 * @param string $contents
316 private function writeCacheFile($contents) {
317 if (file_put_contents($this->cacheFile
, $contents) === FALSE) {
318 throw new Exception('File not writable');
323 * Removes cached version info.
325 public function flushCache() {
326 if (file_exists($this->cacheFile
)) {
327 unlink($this->cacheFile
);
332 * Lookup version_check scheduled job
334 private function getJob() {
335 $jobs = civicrm_api3('Job', 'get', [
337 'api_action' => "version_check",
338 'api_entity' => "job",
340 $this->cronJob
= CRM_Utils_Array
::value(0, $jobs['values'], []);