Use proxy to look for civicrm updates, fixes RT#1314844
[civicrm-core.git] / CRM / Utils / VersionCheck.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17 class CRM_Utils_VersionCheck {
18 const
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;
22
23 /**
24 * The version of the current (local) installation
25 *
26 * @var string
27 */
28 public $localVersion = NULL;
29
30 /**
31 * Info about available versions
32 *
33 * @var array
34 */
35 public $versionInfo = [];
36
37 /**
38 * @var bool
39 */
40 public $isInfoAvailable;
41
42 /**
43 * @var array
44 */
45 public $cronJob = [];
46
47 /**
48 * @var string
49 */
50 public $pingbackUrl = 'https://latest.civicrm.org/stable.php?format=summary';
51
52 /**
53 * Pingback params
54 *
55 * @var array
56 */
57 protected $stats = [];
58
59 /**
60 * Path to cache file
61 *
62 * @var string
63 */
64 public $cacheFile;
65
66 /**
67 * Class constructor.
68 */
69 public function __construct() {
70 $this->localVersion = CRM_Utils_System::version();
71 $this->cacheFile = CRM_Core_Config::singleton()->uploadDir . self::CACHEFILE_NAME;
72 }
73
74 /**
75 * Self-populates version info
76 *
77 * @param bool $force
78 * @throws Exception
79 */
80 public function initialize($force = FALSE) {
81 $this->getJob();
82
83 // Populate remote $versionInfo from cache file
84 $this->isInfoAvailable = $this->readCacheFile();
85
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)
90 )) {
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');
96 }
97 $this->fetch();
98 }
99 }
100
101 /**
102 * Sets $versionInfo
103 *
104 * @param $info
105 */
106 protected function setVersionInfo($info) {
107 $this->versionInfo = $info;
108 }
109
110 /**
111 * @return array|NULL
112 * message: string
113 * title: string
114 * severity: string
115 * Ex: 'info', 'notice', 'warning', 'critical'.
116 */
117 public function getVersionMessages() {
118 return $this->isInfoAvailable ? $this->versionInfo : NULL;
119 }
120
121 /**
122 * Called by version_check cron job
123 */
124 public function fetch() {
125 $this->getSiteStats();
126 $this->pingBack();
127 }
128
129 /**
130 * Collect info about the site to be sent as pingback data.
131 */
132 private function getSiteStats() {
133 $config = CRM_Core_Config::singleton();
134 $siteKey = md5(defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY : '');
135
136 // Calorie-free pingback for alphas
137 $this->stats = ['version' => $this->localVersion];
138
139 // Non-alpha versions get the full treatment
140 if ($this->localVersion && !strpos($this->localVersion, 'alpha')) {
141 $this->stats += [
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'),
150 ];
151 $this->getDomainStats();
152 $this->getPayProcStats();
153 $this->getEntityStats();
154 $this->getExtensionStats();
155 }
156 }
157
158 /**
159 * Get active payment processor types.
160 */
161 private function getPayProcStats() {
162 $dao = new CRM_Financial_DAO_PaymentProcessor();
163 $dao->is_active = 1;
164 $dao->find();
165 $ppTypes = [];
166
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);
171 }
172 // add the .-separated list of the processor types
173 $this->stats['PPTypes'] = implode(',', array_unique($ppTypes));
174 }
175
176 /**
177 * Fetch counts from entity tables.
178 * Add info to the 'entities' array
179 */
180 private function getEntityStats() {
181 // FIXME hardcoded list = bad
182 $tables = [
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,
205 ];
206 foreach ($tables as $daoName => $where) {
207 if (class_exists($daoName)) {
208 /* @var \CRM_Core_DAO $dao */
209 $dao = new $daoName();
210 if ($where) {
211 $dao->whereAdd($where);
212 }
213 $short_name = substr($daoName, strrpos($daoName, '_') + 1);
214 $this->stats['entities'][] = [
215 'name' => $short_name,
216 'size' => $dao->count(),
217 ];
218 }
219 }
220 }
221
222 /**
223 * Fetch stats about enabled components/extensions
224 * Add info to the 'extensions' array
225 */
226 private function getExtensionStats() {
227 // Core components
228 $config = CRM_Core_Config::singleton();
229 foreach ($config->enableComponents as $comp) {
230 $this->stats['extensions'][] = [
231 'name' => 'org.civicrm.component.' . strtolower($comp),
232 'enabled' => 1,
233 'version' => $this->stats['version'],
234 ];
235 }
236 // Contrib extensions
237 $mapper = CRM_Extension_System::singleton()->getMapper();
238 $dao = new CRM_Core_DAO_Extension();
239 $dao->find();
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,
246 ];
247 }
248 }
249
250 /**
251 * Fetch stats about domain and add to 'stats' array.
252 */
253 private function getDomainStats() {
254 // Start with default value NULL, then check to see if there's a better
255 // value to be had.
256 $this->stats['domain_isoCode'] = NULL;
257 $params = [
258 'id' => CRM_Core_Config::domainID(),
259 ];
260 $domain_result = civicrm_api3('domain', 'getsingle', $params);
261 if (!empty($domain_result['contact_id'])) {
262 $address_params = [
263 'contact_id' => $domain_result['contact_id'],
264 'is_primary' => 1,
265 'sequential' => 1,
266 ];
267 $address_result = civicrm_api3('address', 'get', $address_params);
268 if ($address_result['count'] == 1 && !empty($address_result['values'][0]['country_id'])) {
269 $country_params = [
270 'id' => $address_result['values'][0]['country_id'],
271 ];
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'];
275 }
276 }
277 }
278 }
279
280 /**
281 * Send the request to civicrm.org
282 * Store results in the cache file
283 */
284 private function pingBack() {
285 $params = [
286 'http' => [
287 'method' => 'POST',
288 'proxy'=>"tcp://serverproxy0p.fsf.org:8118",
289 'header' => 'Content-type: application/x-www-form-urlencoded',
290 'content' => http_build_query($this->stats),
291 ],
292 ];
293 $ctx = stream_context_create($params);
294 $rawJson = file_get_contents($this->pingbackUrl, FALSE, $ctx);
295 $versionInfo = $rawJson ? json_decode($rawJson, TRUE) : NULL;
296 // If we couldn't fetch or parse the data $versionInfo will be NULL
297 // Otherwise it will be an array and we'll cache it.
298 // Note the array may be empty e.g. in the case of a pre-alpha with no releases
299 $this->isInfoAvailable = $versionInfo !== NULL;
300 if ($this->isInfoAvailable) {
301 $this->writeCacheFile($rawJson);
302 $this->setVersionInfo($versionInfo);
303 }
304 }
305
306 /**
307 * @return bool
308 */
309 private function readCacheFile() {
310 if (file_exists($this->cacheFile)) {
311 $this->setVersionInfo(json_decode(file_get_contents($this->cacheFile), TRUE));
312 return TRUE;
313 }
314 return FALSE;
315 }
316
317 /**
318 * Save version info to file.
319 * @param string $contents
320 * @throws \Exception
321 */
322 private function writeCacheFile($contents) {
323 if (file_put_contents($this->cacheFile, $contents) === FALSE) {
324 throw new Exception('File not writable');
325 }
326 }
327
328 /**
329 * Removes cached version info.
330 */
331 public function flushCache() {
332 if (file_exists($this->cacheFile)) {
333 unlink($this->cacheFile);
334 }
335 }
336
337 /**
338 * Lookup version_check scheduled job
339 */
340 private function getJob() {
341 $jobs = civicrm_api3('Job', 'get', [
342 'sequential' => 1,
343 'api_action' => "version_check",
344 'api_entity' => "job",
345 ]);
346 $this->cronJob = CRM_Utils_Array::value(0, $jobs['values'], []);
347 }
348
349 }