Flush versionCheck cache when upgrading
[civicrm-core.git] / CRM / Utils / VersionCheck.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2018
32 */
33 class CRM_Utils_VersionCheck {
34 const
35 CACHEFILE_NAME = 'version-msgs-cache.json',
36 // After which length of time we expire the cached version info (3 days).
37 CACHEFILE_EXPIRE = 259200;
38
39 /**
40 * The version of the current (local) installation
41 *
42 * @var string
43 */
44 public $localVersion = NULL;
45
46 /**
47 * Info about available versions
48 *
49 * @var array
50 */
51 public $versionInfo = array();
52
53 /**
54 * @var bool
55 */
56 public $isInfoAvailable;
57
58 /**
59 * @var array
60 */
61 public $cronJob = array();
62
63 /**
64 * @var string
65 */
66 public $pingbackUrl = 'https://latest.civicrm.org/stable.php?format=summary';
67
68 /**
69 * Pingback params
70 *
71 * @var array
72 */
73 protected $stats = array();
74
75 /**
76 * Path to cache file
77 *
78 * @var string
79 */
80 public $cacheFile;
81
82 /**
83 * Class constructor.
84 */
85 public function __construct() {
86 $this->localVersion = CRM_Utils_System::version();
87 $this->cacheFile = CRM_Core_Config::singleton()->uploadDir . self::CACHEFILE_NAME;
88 }
89
90 /**
91 * Self-populates version info
92 *
93 * @throws \Exception
94 */
95 public function initialize() {
96 $this->getJob();
97
98 // Populate remote $versionInfo from cache file
99 $this->isInfoAvailable = $this->readCacheFile();
100
101 // Fallback if scheduled job is enabled but has failed to run.
102 $expiryTime = time() - self::CACHEFILE_EXPIRE;
103 if (!empty($this->cronJob['is_active']) &&
104 (!$this->isInfoAvailable || filemtime($this->cacheFile) < $expiryTime)
105 ) {
106 // First try updating the files modification time, for 2 reasons:
107 // - if the file is not writeable, this saves the trouble of pinging back
108 // - if the remote server is down, this will prevent an immediate retry
109 if (touch($this->cacheFile) === FALSE) {
110 throw new Exception('File not writable');
111 }
112 $this->fetch();
113 }
114 }
115
116 /**
117 * Sets $versionInfo
118 *
119 * @param $info
120 */
121 protected function setVersionInfo($info) {
122 $this->versionInfo = $info;
123 }
124
125 /**
126 * @return array|NULL
127 * message: string
128 * title: string
129 * severity: string
130 * Ex: 'info', 'notice', 'warning', 'critical'.
131 */
132 public function getVersionMessages() {
133 return $this->isInfoAvailable ? $this->versionInfo : NULL;
134 }
135
136 /**
137 * Called by version_check cron job
138 */
139 public function fetch() {
140 $this->getSiteStats();
141 $this->pingBack();
142 }
143
144 /**
145 * Collect info about the site to be sent as pingback data.
146 */
147 private function getSiteStats() {
148 $config = CRM_Core_Config::singleton();
149 $siteKey = md5(defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY : '');
150
151 // Calorie-free pingback for alphas
152 $this->stats = array('version' => $this->localVersion);
153
154 // Non-alpha versions get the full treatment
155 if ($this->localVersion && !strpos($this->localVersion, 'alpha')) {
156 $this->stats += array(
157 'hash' => md5($siteKey . $config->userFrameworkBaseURL),
158 'uf' => $config->userFramework,
159 'lang' => $config->lcMessages,
160 'co' => $config->defaultContactCountry,
161 'ufv' => $config->userSystem->getVersion(),
162 'PHP' => phpversion(),
163 'MySQL' => CRM_CORE_DAO::singleValueQuery('SELECT VERSION()'),
164 'communityMessagesUrl' => Civi::settings()->get('communityMessagesUrl'),
165 );
166 $this->getDomainStats();
167 $this->getPayProcStats();
168 $this->getEntityStats();
169 $this->getExtensionStats();
170 }
171 }
172
173 /**
174 * Get active payment processor types.
175 */
176 private function getPayProcStats() {
177 $dao = new CRM_Financial_DAO_PaymentProcessor();
178 $dao->is_active = 1;
179 $dao->find();
180 $ppTypes = array();
181
182 // Get title and id for all processor types
183 $ppTypeNames = CRM_Core_PseudoConstant::paymentProcessorType();
184
185 while ($dao->fetch()) {
186 $ppTypes[] = $ppTypeNames[$dao->payment_processor_type_id];
187 }
188 // add the .-separated list of the processor types
189 $this->stats['PPTypes'] = implode(',', array_unique($ppTypes));
190 }
191
192 /**
193 * Fetch counts from entity tables.
194 * Add info to the 'entities' array
195 */
196 private function getEntityStats() {
197 $tables = array(
198 'CRM_Activity_DAO_Activity' => 'is_test = 0',
199 'CRM_Case_DAO_Case' => 'is_deleted = 0',
200 'CRM_Contact_DAO_Contact' => 'is_deleted = 0',
201 'CRM_Contact_DAO_Relationship' => NULL,
202 'CRM_Campaign_DAO_Campaign' => NULL,
203 'CRM_Contribute_DAO_Contribution' => 'is_test = 0',
204 'CRM_Contribute_DAO_ContributionPage' => 'is_active = 1',
205 'CRM_Contribute_DAO_ContributionProduct' => NULL,
206 'CRM_Contribute_DAO_Widget' => 'is_active = 1',
207 'CRM_Core_DAO_Discount' => NULL,
208 'CRM_Price_DAO_PriceSetEntity' => NULL,
209 'CRM_Core_DAO_UFGroup' => 'is_active = 1',
210 'CRM_Event_DAO_Event' => 'is_active = 1',
211 'CRM_Event_DAO_Participant' => 'is_test = 0',
212 'CRM_Friend_DAO_Friend' => 'is_active = 1',
213 'CRM_Grant_DAO_Grant' => NULL,
214 'CRM_Mailing_DAO_Mailing' => 'is_completed = 1',
215 'CRM_Member_DAO_Membership' => 'is_test = 0',
216 'CRM_Member_DAO_MembershipBlock' => 'is_active = 1',
217 'CRM_Pledge_DAO_Pledge' => 'is_test = 0',
218 'CRM_Pledge_DAO_PledgeBlock' => NULL,
219 'CRM_Mailing_Event_DAO_Delivered' => NULL,
220 );
221 foreach ($tables as $daoName => $where) {
222 $dao = new $daoName();
223 if ($where) {
224 $dao->whereAdd($where);
225 }
226 $short_name = substr($daoName, strrpos($daoName, '_') + 1);
227 $this->stats['entities'][] = array(
228 'name' => $short_name,
229 'size' => $dao->count(),
230 );
231 }
232 }
233
234 /**
235 * Fetch stats about enabled components/extensions
236 * Add info to the 'extensions' array
237 */
238 private function getExtensionStats() {
239 // Core components
240 $config = CRM_Core_Config::singleton();
241 foreach ($config->enableComponents as $comp) {
242 $this->stats['extensions'][] = array(
243 'name' => 'org.civicrm.component.' . strtolower($comp),
244 'enabled' => 1,
245 'version' => $this->stats['version'],
246 );
247 }
248 // Contrib extensions
249 $mapper = CRM_Extension_System::singleton()->getMapper();
250 $dao = new CRM_Core_DAO_Extension();
251 $dao->find();
252 while ($dao->fetch()) {
253 $info = $mapper->keyToInfo($dao->full_name);
254 $this->stats['extensions'][] = array(
255 'name' => $dao->full_name,
256 'enabled' => $dao->is_active,
257 'version' => isset($info->version) ? $info->version : NULL,
258 );
259 }
260 }
261
262 /**
263 * Fetch stats about domain and add to 'stats' array.
264 */
265 private function getDomainStats() {
266 // Start with default value NULL, then check to see if there's a better
267 // value to be had.
268 $this->stats['domain_isoCode'] = NULL;
269 $params = array(
270 'id' => CRM_Core_Config::domainID(),
271 );
272 $domain_result = civicrm_api3('domain', 'getsingle', $params);
273 if (!empty($domain_result['contact_id'])) {
274 $address_params = array(
275 'contact_id' => $domain_result['contact_id'],
276 'is_primary' => 1,
277 'sequential' => 1,
278 );
279 $address_result = civicrm_api3('address', 'get', $address_params);
280 if ($address_result['count'] == 1 && !empty($address_result['values'][0]['country_id'])) {
281 $country_params = array(
282 'id' => $address_result['values'][0]['country_id'],
283 );
284 $country_result = civicrm_api3('country', 'getsingle', $country_params);
285 if (!empty($country_result['iso_code'])) {
286 $this->stats['domain_isoCode'] = $country_result['iso_code'];
287 }
288 }
289 }
290 }
291
292 /**
293 * Send the request to civicrm.org
294 * Store results in the cache file
295 */
296 private function pingBack() {
297 $params = array(
298 'http' => array(
299 'method' => 'POST',
300 'header' => 'Content-type: application/x-www-form-urlencoded',
301 'content' => http_build_query($this->stats),
302 ),
303 );
304 $ctx = stream_context_create($params);
305 $rawJson = file_get_contents($this->pingbackUrl, FALSE, $ctx);
306 $versionInfo = $rawJson ? json_decode($rawJson, TRUE) : NULL;
307 // If we couldn't fetch or parse the data $versionInfo will be NULL
308 // Otherwise it will be an array and we'll cache it.
309 // Note the array may be empty e.g. in the case of a pre-alpha with no releases
310 $this->isInfoAvailable = $versionInfo !== NULL;
311 if ($this->isInfoAvailable) {
312 $this->writeCacheFile($rawJson);
313 $this->setVersionInfo($versionInfo);
314 }
315 }
316
317 /**
318 * @return bool
319 */
320 private function readCacheFile() {
321 if (file_exists($this->cacheFile)) {
322 $this->setVersionInfo(json_decode(file_get_contents($this->cacheFile), TRUE));
323 return TRUE;
324 }
325 return FALSE;
326 }
327
328 /**
329 * Save version info to file.
330 * @param string $contents
331 * @throws \Exception
332 */
333 private function writeCacheFile($contents) {
334 if (file_put_contents($this->cacheFile, $contents) === FALSE) {
335 throw new Exception('File not writable');
336 }
337 }
338
339 /**
340 * Removes cached version info.
341 */
342 public function flushCache() {
343 if (file_exists($this->cacheFile)) {
344 unlink($this->cacheFile);
345 }
346 }
347
348 /**
349 * Lookup version_check scheduled job
350 */
351 private function getJob() {
352 $jobs = civicrm_api3('Job', 'get', array(
353 'sequential' => 1,
354 'api_action' => "version_check",
355 'api_entity' => "job",
356 ));
357 $this->cronJob = CRM_Utils_Array::value(0, $jobs['values'], array());
358 }
359
360 }