Completed
Push — tmp/not-master ( 0b734a )
by
unknown
115:59 queued 109:41
created

Utils::update_user_token()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 4
nop 3
dl 0
loc 15
rs 9.7666
c 0
b 0
f 0
1
<?php
2
/**
3
 * The Jetpack Connection package Utils class file.
4
 *
5
 * @package automattic/jetpack-connection
6
 */
7
8
namespace Automattic\Jetpack\Connection;
9
10
use Automattic\Jetpack\Constants;
11
12
/**
13
 * Provides utility methods for the Connection package.
14
 */
15
class Utils {
16
17
	const DEFAULT_JETPACK__API_VERSION = 1;
18
	const DEFAULT_JETPACK__API_BASE    = 'https://jetpack.wordpress.com/jetpack.';
19
20
	/**
21
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requests.
22
	 * This method sets the URL scheme to HTTP when HTTPS requests can't be made.
23
	 *
24
	 * @param string $url The url.
25
	 * @return string The url with the required URL scheme.
26
	 */
27
	public static function fix_url_for_bad_hosts( $url ) {
28
		// If we receive an http url, return it.
29
		if ( 'http' === wp_parse_url( $url, PHP_URL_SCHEME ) ) {
30
			return $url;
31
		}
32
33
		// If the url should never be https, ensure it isn't https.
34
		if ( 'NEVER' === Constants::get_constant( 'JETPACK_CLIENT__HTTPS' ) ) {
35
			return set_url_scheme( $url, 'http' );
36
		}
37
38
		// Otherwise, return the https url.
39
		return $url;
40
	}
41
42
	/**
43
	 * Enters a user token into the user_tokens option
44
	 *
45
	 * @param int    $user_id The user id.
46
	 * @param string $token The user token.
47
	 * @param bool   $is_master_user Whether the user is the master user.
48
	 * @return bool
49
	 */
50
	public static function update_user_token( $user_id, $token, $is_master_user ) {
51
		// Not designed for concurrent updates.
52
		$user_tokens = \Jetpack_Options::get_option( 'user_tokens' );
53
		if ( ! is_array( $user_tokens ) ) {
54
			$user_tokens = array();
55
		}
56
		$user_tokens[ $user_id ] = $token;
57
		if ( $is_master_user ) {
58
			$master_user = $user_id;
59
			$options     = compact( 'user_tokens', 'master_user' );
60
		} else {
61
			$options = compact( 'user_tokens' );
62
		}
63
		return \Jetpack_Options::update_options( $options );
64
	}
65
66
	/**
67
	 * Filters the value of the api constant.
68
	 *
69
	 * @param String $constant_value The constant value.
70
	 * @param String $constant_name The constant name.
71
	 * @return mixed | null
72
	 */
73
	public static function jetpack_api_constant_filter( $constant_value, $constant_name ) {
74
		if ( ! is_null( $constant_value ) ) {
75
			// If the constant value was already set elsewhere, use that value.
76
			return $constant_value;
77
		}
78
79
		if ( defined( "self::DEFAULT_$constant_name" ) ) {
80
			return constant( "self::DEFAULT_$constant_name" );
81
		}
82
83
		return null;
84
	}
85
}
86