Merge pull request #5097 from PalanteJon/CRM-15917
[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 */
53 static private $_singleton = NULL;
54
55 /**
56 * The version of the current (local) installation
57 *
58 * @var string
59 */
60 public $localVersion = NULL;
61
62 /**
63 * The major version (branch name) of the local version
64 *
65 * @var string
66 */
67 public $localMajorVersion;
68
69 /**
70 * User setting to skip updates prior to a certain date
71 *
72 * @var string
73 */
74 public $ignoreDate;
75
76 /**
77 * Info about available versions
78 *
79 * @var array
80 */
81 public $versionInfo = array();
82
83 /**
84 * Pingback params
85 *
86 * @var array
87 */
88 protected $stats = array();
89
90 /**
91 * Path to cache file
92 *
93 * @var string
94 */
95 protected $cacheFile;
96
97 /**
98 * Class constructor.
99 */
100 public function __construct() {
101 global $civicrm_root;
102 $config = CRM_Core_Config::singleton();
103
104 $localFile = $civicrm_root . DIRECTORY_SEPARATOR . self::LOCALFILE_NAME;
105 $this->cacheFile = $config->uploadDir . self::CACHEFILE_NAME;
106
107 if (file_exists($localFile)) {
108 require_once $localFile;
109 }
110 if (function_exists('civicrmVersion')) {
111 $info = civicrmVersion();
112 $this->localVersion = trim($info['version']);
113 $this->localMajorVersion = $this->getMajorVersion($this->localVersion);
114 }
115 // Populate $versionInfo
116 if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'versionCheck', NULL, 1)) {
117 // Use cached data if available and not stale
118 if (!$this->readCacheFile()) {
119 // Collect stats for pingback
120 $this->getSiteStats();
121
122 // Get the latest version and send site info
123 $this->pingBack();
124 }
125 $this->ignoreDate = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'versionCheckIgnoreDate');
126
127 // Sort version info in ascending order for easier comparisons
128 ksort($this->versionInfo, SORT_NUMERIC);
129 }
130 }
131
132 /**
133 * Static instance provider.
134 *
135 * Method providing static instance of CRM_Utils_VersionCheck,
136 * as in Singleton pattern
137 *
138 * @return CRM_Utils_VersionCheck
139 */
140 public static function &singleton() {
141 if (!isset(self::$_singleton)) {
142 self::$_singleton = new CRM_Utils_VersionCheck();
143 }
144 return self::$_singleton;
145 }
146
147 /**
148 * Finds the release info for a minor version.
149 * @param string $version
150 * @return array|null
151 */
152 public function getReleaseInfo($version) {
153 $majorVersion = $this->getMajorVersion($version);
154 if (isset($this->versionInfo[$majorVersion])) {
155 foreach ($this->versionInfo[$majorVersion]['releases'] as $info) {
156 if ($info['version'] == $version) {
157 return $info;
158 }
159 }
160 }
161 return NULL;
162 }
163
164 /**
165 * @param $minorVersion
166 * @return string
167 */
168 public function getMajorVersion($minorVersion) {
169 if (!$minorVersion) {
170 return NULL;
171 }
172 list($a, $b) = explode('.', $minorVersion);
173 return "$a.$b";
174 }
175
176 /**
177 * @return bool
178 */
179 public function isSecurityUpdateAvailable() {
180 $thisVersion = $this->getReleaseInfo($this->localVersion);
181 $localVersionDate = CRM_Utils_Array::value('date', $thisVersion, 0);
182 foreach ($this->versionInfo as $majorVersion) {
183 foreach ($majorVersion['releases'] as $release) {
184 if (!empty($release['security']) && $release['date'] > $localVersionDate
185 && version_compare($this->localVersion, $release['version']) < 0
186 ) {
187 if (!$this->ignoreDate || $this->ignoreDate < $release['date']) {
188 return TRUE;
189 }
190 }
191 }
192 }
193 }
194
195 /**
196 * Get the latest version number if it's newer than the local one
197 *
198 * @return string|null
199 * Returns version number of the latest release if it is greater than the local version
200 */
201 public function isNewerVersionAvailable() {
202 $newerVersion = NULL;
203 if ($this->versionInfo && $this->localVersion) {
204 foreach ($this->versionInfo as $majorVersionNumber => $majorVersion) {
205 $release = $this->checkBranchForNewVersion($majorVersion);
206 if ($release) {
207 // If we have a release with the same majorVersion as local, return it
208 if ($majorVersionNumber == $this->localMajorVersion) {
209 return $release;
210 }
211 // Search outside the local majorVersion (excluding non-stable)
212 elseif ($majorVersion['status'] != 'testing') {
213 // We found a new release but don't return yet, keep searching newer majorVersions
214 $newerVersion = $release;
215 }
216 }
217 }
218 }
219 return $newerVersion;
220 }
221
222 /**
223 * @param $majorVersion
224 * @return null|string
225 */
226 private function checkBranchForNewVersion($majorVersion) {
227 $newerVersion = NULL;
228 if (!empty($majorVersion['releases'])) {
229 foreach ($majorVersion['releases'] as $release) {
230 if (version_compare($this->localVersion, $release['version']) < 0) {
231 if (!$this->ignoreDate || $this->ignoreDate < $release['date']) {
232 $newerVersion = $release['version'];
233 }
234 }
235 }
236 }
237 return $newerVersion;
238 }
239
240 /**
241 * Alert the site admin of new versions of CiviCRM.
242 * Show the message once a day
243 */
244 public function versionAlert() {
245 $versionAlertSetting = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'versionAlert', NULL, 1);
246 $securityAlertSetting = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'securityUpdateAlert', NULL, 3);
247 $settingsUrl = CRM_Utils_System::url('civicrm/admin/setting/misc', 'reset=1', FALSE, NULL, FALSE, FALSE, TRUE);
248 if (CRM_Core_Permission::check('administer CiviCRM') && $securityAlertSetting > 1 && $this->isSecurityUpdateAvailable()) {
249 $session = CRM_Core_Session::singleton();
250 if ($session->timer('version_alert', 24 * 60 * 60)) {
251 $msg = ts('This version of CiviCRM requires a security update.') .
252 '<ul>
253 <li><a href="https://civicrm.org/advisory">' . ts('Read advisory') . '</a></li>
254 <li><a href="https://civicrm.org/download">' . ts('Download now') . '</a></li>
255 <li><a class="crm-setVersionCheckIgnoreDate" href="' . $settingsUrl . '">' . ts('Suppress this message') . '</a></li>
256 </ul>';
257 $session->setStatus($msg, ts('Security Alert'), 'alert');
258 CRM_Core_Resources::singleton()
259 ->addScriptFile('civicrm', 'templates/CRM/Admin/Form/Setting/versionCheckOptions.js');
260 }
261 }
262 elseif (CRM_Core_Permission::check('administer CiviCRM') && $versionAlertSetting > 1) {
263 $newerVersion = $this->isNewerVersionAvailable();
264 if ($newerVersion) {
265 $session = CRM_Core_Session::singleton();
266 if ($session->timer('version_alert', 24 * 60 * 60)) {
267 $msg = ts('A newer version of CiviCRM is available: %1', array(1 => $newerVersion)) .
268 '<ul>
269 <li><a href="https://civicrm.org/download">' . ts('Download now') . '</a></li>
270 <li><a class="crm-setVersionCheckIgnoreDate" href="' . $settingsUrl . '">' . ts('Suppress this message') . '</a></li>
271 </ul>';
272 $session->setStatus($msg, ts('Update Available'), 'info');
273 CRM_Core_Resources::singleton()
274 ->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 }