phpcs - Fix error, "Visibility must be declared on method"
[civicrm-core.git] / CRM / Utils / VersionCheck.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
32 * $Id: $
33 *
34 */
35 class CRM_Utils_VersionCheck {
36 const
37 PINGBACK_URL = 'http://latest.civicrm.org/stable.php?format=json',
38 // timeout for when the connection or the server is slow
39 CHECK_TIMEOUT = 5,
40 // relative to $civicrm_root
41 LOCALFILE_NAME = 'civicrm-version.php',
42 // relative to $config->uploadDir
43 CACHEFILE_NAME = 'version-info-cache.json',
44 // cachefile expiry time (in seconds) - one day
45 CACHEFILE_EXPIRE = 86400;
46
47 /**
48 * We only need one instance of this object, so we use the
49 * singleton pattern and cache the instance in this variable
50 *
51 * @var object
52 * @static
53 */
54 static private $_singleton = NULL;
55
56 /**
57 * The version of the current (local) installation
58 *
59 * @var string
60 */
61 public $localVersion = NULL;
62
63 /**
64 * The major version (branch name) of the local version
65 *
66 * @var string
67 */
68 public $localMajorVersion;
69
70 /**
71 * User setting to skip updates prior to a certain date
72 *
73 * @var string
74 */
75 public $ignoreDate;
76
77 /**
78 * Info about available versions
79 *
80 * @var array
81 */
82 public $versionInfo = array();
83
84 /**
85 * Pingback params
86 *
87 * @var array
88 */
89 protected $stats = array();
90
91 /**
92 * Path to cache file
93 *
94 * @var string
95 */
96 protected $cacheFile;
97
98 /**
99 * Class constructor
100 *
101 * @access private
102 */
103 public function __construct() {
104 global $civicrm_root;
105 $config = CRM_Core_Config::singleton();
106
107 $localFile = $civicrm_root . DIRECTORY_SEPARATOR . self::LOCALFILE_NAME;
108 $this->cacheFile = $config->uploadDir . self::CACHEFILE_NAME;
109
110 if (file_exists($localFile)) {
111 require_once ($localFile);
112 }
113 if (function_exists('civicrmVersion')) {
114 $info = civicrmVersion();
115 $this->localVersion = trim($info['version']);
116 $this->localMajorVersion = $this->getMajorVersion($this->localVersion);
117 }
118 // Populate $versionInfo
119 if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'versionCheck', NULL, 1)) {
120 // Use cached data if available and not stale
121 if (!$this->readCacheFile()) {
122 // Collect stats for pingback
123 $this->getSiteStats();
124
125 // Get the latest version and send site info
126 $this->pingBack();
127 }
128 $this->ignoreDate = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'versionCheckIgnoreDate');
129
130 // Sort version info in ascending order for easier comparisons
131 ksort($this->versionInfo, SORT_NUMERIC);
132 }
133 }
134
135 /**
136 * Static instance provider
137 *
138 * Method providing static instance of CRM_Utils_VersionCheck,
139 * as in Singleton pattern
140 *
141 * @return CRM_Utils_VersionCheck
142 */
143 public static function &singleton() {
144 if (!isset(self::$_singleton)) {
145 self::$_singleton = new CRM_Utils_VersionCheck();
146 }
147 return self::$_singleton;
148 }
149
150 /**
151 * Finds the release info for a minor version
152 * @param string $version
153 * @return array|null
154 */
155 public function getReleaseInfo($version) {
156 $majorVersion = $this->getMajorVersion($version);
157 if (isset($this->versionInfo[$majorVersion])) {
158 foreach ($this->versionInfo[$majorVersion]['releases'] as $info) {
159 if ($info['version'] == $version) {
160 return $info;
161 }
162 }
163 }
164 return NULL;
165 }
166
167 /**
168 * @param $minorVersion
169 * @return string
170 */
171 public function getMajorVersion($minorVersion) {
172 if (!$minorVersion) {
173 return NULL;
174 }
175 list($a, $b) = explode('.', $minorVersion);
176 return "$a.$b";
177 }
178
179 /**
180 * @return bool
181 */
182 public function isSecurityUpdateAvailable() {
183 $thisVersion = $this->getReleaseInfo($this->localVersion);
184 $localVersionDate = CRM_Utils_Array::value('date', $thisVersion, 0);
185 foreach ($this->versionInfo as $majorVersion) {
186 foreach ($majorVersion['releases'] as $release) {
187 if (!empty($release['security']) && $release['date'] > $localVersionDate
188 && version_compare($this->localVersion, $release['version']) < 0) {
189 if (!$this->ignoreDate || $this->ignoreDate < $release['date']) {
190 return TRUE;
191 }
192 }
193 }
194 }
195 }
196
197 /**
198 * Get the latest version number if it's newer than the local one
199 *
200 * @return string|null
201 * Returns version number of the latest release if it is greater than the local version
202 */
203 public function isNewerVersionAvailable() {
204 $newerVersion = NULL;
205 if ($this->versionInfo && $this->localVersion) {
206 foreach ($this->versionInfo as $majorVersionNumber => $majorVersion) {
207 $release = $this->checkBranchForNewVersion($majorVersion);
208 if ($release) {
209 // If we have a release with the same majorVersion as local, return it
210 if ($majorVersionNumber == $this->localMajorVersion) {
211 return $release;
212 }
213 // Search outside the local majorVersion (excluding non-stable)
214 elseif ($majorVersion['status'] != 'testing') {
215 // We found a new release but don't return yet, keep searching newer majorVersions
216 $newerVersion = $release;
217 }
218 }
219 }
220 }
221 return $newerVersion;
222 }
223
224 /**
225 * @param $majorVersion
226 * @return null|string
227 */
228 private function checkBranchForNewVersion($majorVersion) {
229 $newerVersion = NULL;
230 if (!empty($majorVersion['releases'])) {
231 foreach ($majorVersion['releases'] as $release) {
232 if (version_compare($this->localVersion, $release['version']) < 0) {
233 if (!$this->ignoreDate || $this->ignoreDate < $release['date']) {
234 $newerVersion = $release['version'];
235 }
236 }
237 }
238 }
239 return $newerVersion;
240 }
241
242 /**
243 * Alert the site admin of new versions of CiviCRM
244 * Show the message once a day
245 */
246 public function versionAlert() {
247 $versionAlertSetting = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'versionAlert', NULL, 1);
248 $securityAlertSetting = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'securityUpdateAlert', NULL, 3);
249 $settingsUrl = CRM_Utils_System::url('civicrm/admin/setting/misc', 'reset=1', FALSE, NULL, FALSE, FALSE, TRUE);
250 if (CRM_Core_Permission::check('administer CiviCRM') && $securityAlertSetting > 1 && $this->isSecurityUpdateAvailable()) {
251 $session = CRM_Core_Session::singleton();
252 if ($session->timer('version_alert', 24 * 60 * 60)) {
253 $msg = ts('This version of CiviCRM requires a security update.') .
254 '<ul>
255 <li><a href="https://civicrm.org/advisory">' . ts('Read advisory') . '</a></li>
256 <li><a href="https://civicrm.org/download">' . ts('Download now') . '</a></li>
257 <li><a class="crm-setVersionCheckIgnoreDate" href="' . $settingsUrl . '">' . ts('Suppress this message') . '</a></li>
258 </ul>';
259 $session->setStatus($msg, ts('Security Alert'), 'alert');
260 CRM_Core_Resources::singleton()->addScriptFile('civicrm', 'templates/CRM/Admin/Form/Setting/versionCheckOptions.js');
261 }
262 }
263 elseif (CRM_Core_Permission::check('administer CiviCRM') && $versionAlertSetting > 1) {
264 $newerVersion = $this->isNewerVersionAvailable();
265 if ($newerVersion) {
266 $session = CRM_Core_Session::singleton();
267 if ($session->timer('version_alert', 24 * 60 * 60)) {
268 $msg = ts('A newer version of CiviCRM is available: %1', array(1 => $newerVersion)) .
269 '<ul>
270 <li><a href="https://civicrm.org/download">' . ts('Download now') . '</a></li>
271 <li><a class="crm-setVersionCheckIgnoreDate" href="' . $settingsUrl . '">' . ts('Suppress this message') . '</a></li>
272 </ul>';
273 $session->setStatus($msg, ts('Update Available'), 'info');
274 CRM_Core_Resources::singleton()->addScriptFile('civicrm', 'templates/CRM/Admin/Form/Setting/versionCheckOptions.js');
275 }
276 }
277 }
278 }
279
280 /**
281 * Collect info about the site to be sent as pingback data
282 */
283 private function getSiteStats() {
284 $config = CRM_Core_Config::singleton();
285 $siteKey = md5(defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY : '');
286
287 // Calorie-free pingback for alphas
288 $this->stats = array('version' => $this->localVersion);
289
290 // Non-alpha versions get the full treatment
291 if ($this->localVersion && !strpos($this->localVersion, 'alpha')) {
292 $this->stats += array(
293 'hash' => md5($siteKey . $config->userFrameworkBaseURL),
294 'uf' => $config->userFramework,
295 'lang' => $config->lcMessages,
296 'co' => $config->defaultContactCountry,
297 'ufv' => $config->userFrameworkVersion,
298 'PHP' => phpversion(),
299 'MySQL' => CRM_CORE_DAO::singleValueQuery('SELECT VERSION()'),
300 'communityMessagesUrl' => CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'communityMessagesUrl', NULL, '*default*'),
301 );
302 $this->getPayProcStats();
303 $this->getEntityStats();
304 $this->getExtensionStats();
305 }
306 }
307
308 /**
309 * Get active payment processor types
310 */
311 private function getPayProcStats() {
312 $dao = new CRM_Financial_DAO_PaymentProcessor;
313 $dao->is_active = 1;
314 $dao->find();
315 $ppTypes = array();
316
317 // Get title and id for all processor types
318 $ppTypeNames = CRM_Core_PseudoConstant::paymentProcessorType();
319
320 while ($dao->fetch()) {
321 $ppTypes[] = $ppTypeNames[$dao->payment_processor_type_id];
322 }
323 // add the .-separated list of the processor types
324 $this->stats['PPTypes'] = implode(',', array_unique($ppTypes));
325 }
326
327 /**
328 * Fetch counts from entity tables
329 * Add info to the 'entities' array
330 */
331 private function getEntityStats() {
332 $tables = array(
333 'CRM_Activity_DAO_Activity' => 'is_test = 0',
334 'CRM_Case_DAO_Case' => 'is_deleted = 0',
335 'CRM_Contact_DAO_Contact' => 'is_deleted = 0',
336 'CRM_Contact_DAO_Relationship' => NULL,
337 'CRM_Campaign_DAO_Campaign' => NULL,
338 'CRM_Contribute_DAO_Contribution' => 'is_test = 0',
339 'CRM_Contribute_DAO_ContributionPage' => 'is_active = 1',
340 'CRM_Contribute_DAO_ContributionProduct' => NULL,
341 'CRM_Contribute_DAO_Widget' => 'is_active = 1',
342 'CRM_Core_DAO_Discount' => NULL,
343 'CRM_Price_DAO_PriceSetEntity' => NULL,
344 'CRM_Core_DAO_UFGroup' => 'is_active = 1',
345 'CRM_Event_DAO_Event' => 'is_active = 1',
346 'CRM_Event_DAO_Participant' => 'is_test = 0',
347 'CRM_Friend_DAO_Friend' => 'is_active = 1',
348 'CRM_Grant_DAO_Grant' => NULL,
349 'CRM_Mailing_DAO_Mailing' => 'is_completed = 1',
350 'CRM_Member_DAO_Membership' => 'is_test = 0',
351 'CRM_Member_DAO_MembershipBlock' => 'is_active = 1',
352 'CRM_Pledge_DAO_Pledge' => 'is_test = 0',
353 'CRM_Pledge_DAO_PledgeBlock' => NULL,
354 );
355 foreach ($tables as $daoName => $where) {
356 $dao = new $daoName;
357 if ($where) {
358 $dao->whereAdd($where);
359 }
360 $short_name = substr($daoName, strrpos($daoName, '_') + 1);
361 $this->stats['entities'][] = array(
362 'name' => $short_name,
363 'size' => $dao->count(),
364 );
365 }
366 }
367
368 /**
369 * Fetch stats about enabled components/extensions
370 * Add info to the 'extensions' array
371 */
372 private function getExtensionStats() {
373 // Core components
374 $config = CRM_Core_Config::singleton();
375 foreach ($config->enableComponents as $comp) {
376 $this->stats['extensions'][] = array(
377 'name' => 'org.civicrm.component.' . strtolower($comp),
378 'enabled' => 1,
379 'version' => $this->stats['version'],
380 );
381 }
382 // Contrib extensions
383 $mapper = CRM_Extension_System::singleton()->getMapper();
384 $dao = new CRM_Core_DAO_Extension();
385 $dao->find();
386 while ($dao->fetch()) {
387 $info = $mapper->keyToInfo($dao->full_name);
388 $this->stats['extensions'][] = array(
389 'name' => $dao->full_name,
390 'enabled' => $dao->is_active,
391 'version' => isset($info->version) ? $info->version : NULL,
392 );
393 }
394 }
395
396 /**
397 * Send the request to civicrm.org
398 * Set timeout and suppress errors
399 * Store results in the cache file
400 */
401 private function pingBack() {
402 ini_set('default_socket_timeout', self::CHECK_TIMEOUT);
403 $params = array(
404 'http' => array(
405 'method' => 'POST',
406 'header' => 'Content-type: application/x-www-form-urlencoded',
407 'content' => http_build_query($this->stats),
408 ),
409 );
410 $ctx = stream_context_create($params);
411 $rawJson = @file_get_contents(self::PINGBACK_URL, FALSE, $ctx);
412 $versionInfo = $rawJson ? json_decode($rawJson, TRUE) : NULL;
413 // If we couldn't fetch or parse the data $versionInfo will be NULL
414 // Otherwise it will be an array and we'll cache it.
415 // Note the array may be empty e.g. in the case of a pre-alpha with no releases
416 if ($versionInfo !== NULL) {
417 $this->writeCacheFile($rawJson);
418 $this->versionInfo = $versionInfo;
419 }
420 ini_restore('default_socket_timeout');
421 }
422
423 /**
424 * @return bool
425 */
426 private function readCacheFile() {
427 $expiryTime = time() - self::CACHEFILE_EXPIRE;
428
429 // if there's a cachefile and it's not stale, use it
430 if (file_exists($this->cacheFile) && (filemtime($this->cacheFile) > $expiryTime)) {
431 $this->versionInfo = (array) json_decode(file_get_contents($this->cacheFile), TRUE);
432 return TRUE;
433 }
434 return FALSE;
435 }
436
437 /**
438 * Save version info to file
439 * @param string $contents
440 */
441 private function writeCacheFile($contents) {
442 $fp = @fopen($this->cacheFile, 'w');
443 if (!$fp) {
444 if (CRM_Core_Permission::check('administer CiviCRM')) {
445 CRM_Core_Session::setStatus(
446 ts('Unable to write file') . ": $this->cacheFile<br />" . ts('Please check your system file permissions.'),
447 ts('File Error'), 'error');
448 }
449 return;
450 }
451 fwrite($fp, $contents);
452 fclose($fp);
453 }
454
455 }