Merge pull request #19554 from colemanw/searchFields
[civicrm-core.git] / CRM / Utils / Network.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 * @package CRM
14 * @copyright CiviCRM LLC https://civicrm.org/licensing
15 */
16
17 /**
18 * Simple static helpers for network operations
19 */
20 class CRM_Utils_Network {
21
22 /**
23 * Try connecting to a TCP service; if it fails, retry. Repeat until serverStartupTimeOut elapses.
24 *
25 * @param $host
26 * @param $port
27 * @param int $serverStartupTimeOut
28 * Seconds.
29 * @param float $interval
30 * Seconds to wait in between pollings.
31 *
32 * @return bool
33 * TRUE if service is online
34 */
35 public static function waitForServiceStartup($host, $port, $serverStartupTimeOut, $interval = 0.333) {
36 $start = time();
37 $end = $start + $serverStartupTimeOut;
38 $found = FALSE;
39 $interval_usec = (int) 1000000 * $interval;
40
41 while (!$found && $end >= time()) {
42 $found = self::checkService($host, $port, $end - time());
43 if ($found) {
44 return TRUE;
45 }
46 usleep($interval_usec);
47 }
48 return FALSE;
49 }
50
51 /**
52 * Check whether a TCP service is available on $host and $port.
53 *
54 * @param string $host
55 * @param string $port
56 * @param string $serverConnectionTimeOut
57 *
58 * @return bool
59 */
60 public static function checkService($host, $port, $serverConnectionTimeOut) {
61 $old_error_reporting = error_reporting();
62 error_reporting($old_error_reporting & ~E_WARNING);
63 try {
64 $fh = fsockopen($host, $port, $errno, $errstr, $serverConnectionTimeOut);
65 if ($fh) {
66 fclose($fh);
67 error_reporting($old_error_reporting);
68 return TRUE;
69 }
70 }
71 catch (Exception $e) {
72 }
73 error_reporting($old_error_reporting);
74 return FALSE;
75 }
76
77 }