1
0

InternetConnectivity.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\Settings\SetupChecks;
  8. use OCP\Http\Client\IClientService;
  9. use OCP\IConfig;
  10. use OCP\IL10N;
  11. use OCP\SetupCheck\ISetupCheck;
  12. use OCP\SetupCheck\SetupResult;
  13. use Psr\Log\LoggerInterface;
  14. /**
  15. * Checks if the server can connect to the internet using HTTPS and HTTP
  16. */
  17. class InternetConnectivity implements ISetupCheck {
  18. public function __construct(
  19. private IL10N $l10n,
  20. private IConfig $config,
  21. private IClientService $clientService,
  22. private LoggerInterface $logger,
  23. ) {
  24. }
  25. public function getCategory(): string {
  26. return 'network';
  27. }
  28. public function getName(): string {
  29. return $this->l10n->t('Internet connectivity');
  30. }
  31. public function run(): SetupResult {
  32. if ($this->config->getSystemValue('has_internet_connection', true) === false) {
  33. return SetupResult::success($this->l10n->t('Internet connectivity is disabled in configuration file.'));
  34. }
  35. $siteArray = $this->config->getSystemValue('connectivity_check_domains', [
  36. 'www.nextcloud.com', 'www.startpage.com', 'www.eff.org', 'www.edri.org'
  37. ]);
  38. foreach ($siteArray as $site) {
  39. if ($this->isSiteReachable($site)) {
  40. return SetupResult::success();
  41. }
  42. }
  43. return SetupResult::warning($this->l10n->t('This server has no working internet connection: Multiple endpoints could not be reached. This means that some of the features like mounting external storage, notifications about updates or installation of third-party apps will not work. Accessing files remotely and sending of notification emails might not work, either. Establish a connection from this server to the internet to enjoy all features.'));
  44. }
  45. /**
  46. * Checks if the Nextcloud server can connect to a specific URL
  47. * @param string $site site domain or full URL with http/https protocol
  48. */
  49. private function isSiteReachable(string $site): bool {
  50. try {
  51. $client = $this->clientService->newClient();
  52. // if there is no protocol, test http:// AND https://
  53. if (preg_match('/^https?:\/\//', $site) !== 1) {
  54. $httpSite = 'http://' . $site . '/';
  55. $client->get($httpSite);
  56. $httpsSite = 'https://' . $site . '/';
  57. $client->get($httpsSite);
  58. } else {
  59. $client->get($site);
  60. }
  61. } catch (\Exception $e) {
  62. $this->logger->error('Cannot connect to: ' . $site, [
  63. 'app' => 'internet_connection_check',
  64. 'exception' => $e,
  65. ]);
  66. return false;
  67. }
  68. return true;
  69. }
  70. }