Completed
Push — develop ( 40c91a...f78234 )
by Zack
17:38
created

GravityView_Support_Port::_localize_script()   C

Complexity

Conditions 8
Paths 30

Size

Total Lines 112

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 0
Metric Value
cc 8
nc 30
nop 0
dl 0
loc 112
ccs 0
cts 76
cp 0
crap 72
rs 6.7555
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 6 and the first side effect is on line 302.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
/**
4
 * @since 1.15
5
 */
6
class GravityView_Support_Port {
7
8
	/**
9
	 * @var string The name of the User Meta option used to store whether a user wants to see the Support Port
10
	 * @since 1.15
11
	 */
12
	const user_pref_name = 'gravityview_support_port';
13
14
	/**
15
	 * @var string The hash key used to generate secure message history
16
     * @since 2.2.5
17
	 */
18
	const beacon_key = 'lCXlwbQR707kipR+J0MCqcxrhGOHjGF0ldD6yNbGM0w=';
19
20
	public function __construct() {
21
		$this->add_hooks();
22
	}
23
24
	/**
25
	 * @since 1.15
26
	 */
27
	private function add_hooks() {
28
		add_action( 'personal_options', array( $this, 'user_field' ) );
29
		add_action( 'personal_options_update', array( $this, 'update_user_meta_value' ) );
30
		add_action( 'edit_user_profile_update', array( $this, 'update_user_meta_value' ) );
31
		add_action( 'admin_enqueue_scripts', array( $this, 'maybe_enqueue_script' ), 1000 );
32
	}
33
34
	/**
35
	 * Enqueue Support Port script if user has it enabled and we're on a GravityView plugin page
36
	 *
37
	 * @uses \GV\Admin_Request::is_admin()
38
	 * @uses wp_enqueue_script()
39
	 * @since 1.15
40
	 *
41
	 * @return void
42
	 */
43
	public static function maybe_enqueue_script( $hook ) {
44
		global $pagenow;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
45
46
		// Don't show if not GravityView page, or if we're on the Widgets page
47
		if ( ! gravityview()->request->is_admin( $hook ) || $pagenow === 'widgets.php' ) {
0 ignored issues
show
Unused Code introduced by
The call to Request::is_admin() has too many arguments starting with $hook.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
introduced by
Found "=== '". Use Yoda Condition checks, you must
Loading history...
48
			return;
49
		}
50
51
		/**
52
		 * @filter `gravityview/support_port/display` Whether to display Support Port
53
		 * @since 1.15
54
		 * @param boolean $display_beacon Default: `true`
55
		 */
56
		$display_support_port = apply_filters( 'gravityview/support_port/display', self::show_for_user() );
57
58
		if ( empty( $display_support_port ) ) {
59
			gravityview()->log->debug( 'Not showing Support Port' );
60
61
			return;
62
		}
63
64
		$script_debug = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
65
66
		wp_enqueue_script( 'gravityview-support', plugins_url( 'assets/js/support' . $script_debug . '.js', GRAVITYVIEW_FILE ), array(), \GV\Plugin::$version, true );
67
68
		self::_localize_script();
69
	}
70
71
	/**
72
	 * Localize the Support Port script
73
	 *
74
	 * @uses wp_localize_script()
75
	 * @since 1.15
76
	 * @return void
77
	 */
78
	private static function _localize_script() {
79
80
		$translation = array(
81
			'agentLabel'                => __( 'GravityView Support', 'gravityview' ),
82
			'searchLabel'               => __( 'Search GravityView Docs', 'gravityview' ),
83
			'docsSearchErrorText'          => __( 'Your search timed out. Please double-check your internet connection and try again.', 'gravityview' ),
84
			'noResultsLabel'            => _x( 'No results found for', 'a support form search has returned empty for the following word', 'gravityview' ),
85
			'contactLabel'              => __( 'Contact Support', 'gravityview' ),
86
			'attachAFile'               => __( 'Attach a screenshot or file', 'gravityview' ),
87
			'attachmentSizeErrorText'   => __( 'The maximum file size is 10 MB', 'gravityview' ),
88
			'nameLabel'                 => __( 'Your Name', 'gravityview' ),
89
			'nameError'                 => __( 'Please enter your name', 'gravityview' ),
90
			'emailLabel'                => __( 'Email address', 'gravityview' ),
91
			'emailValidationLabel'      => __( 'Please enter a valid email address', 'gravityview' ),
92
			'subjectLabel'              => __( 'Subject', 'gravityview' ),
93
			'subjectError'              => _x( 'Please enter a subject', 'Error shown when submitting support request and there is no subject provided', 'gravityview' ),
94
			'messageLabel'              => __( 'How can we help you?', 'gravityview' ),
95
			'messageError'              => _x( 'Please enter a message', 'Error shown when submitting support request and there is no message provided', 'gravityview' ),
96
			'weAreOnIt'                 => __( 'Message sent!', 'gravityview' ),
97
			'contactSuccessDescription' => __( 'Thanks for reaching out! Someone from the GravityView team will get back to you soon.', 'gravityview' ),
98
		);
99
100
		$response = gravityview()->plugin->settings->get( 'license_key_response' );
101
102
		$response = wp_parse_args( $response, array(
103
			'license'          => '',
104
			'message'          => '',
105
			'license_key'      => '',
106
			'license_limit'    => '',
107
			'expires'          => '',
108
			'activations_left' => '',
109
			'site_count'       => '',
110
			'payment_id'       => '',
111
			'customer_name'    => '',
112
			'customer_email'   => '',
113
            'price_id'         => '0',
114
		) );
115
116
		// This is just HTML we don't need.
117
		unset( $response['message'] );
118
119
		switch ( intval( $response['price_id'] ) ) {
120
			default:
121
			case 1:
122
				$package = 'Core';
123
				break;
124
			case 2:
125
				$package = 'Extensions';
126
				break;
127
			case 3:
128
				$package = 'All Access';
129
				break;
130
            case 4:
131
                $package = 'Lifetime';
132
                break;
133
		}
134
135
		$current_user = wp_get_current_user();
136
		$no_conflict_mode = gravityview()->plugin->settings->get( 'no-conflict-mode' );
137
138
		// Prevent any PHP warnings
139
		ob_start();
140
141
		$data = array(
142
			'email'                 => $current_user->user_email,
143
			'name'                  => mb_substr( $current_user->display_name, 0, 80 ),
144
			'signature'             => hash_hmac( 'sha256', $current_user->user_email, self::beacon_key ),
145
			'License Key'           => $response['license_key'] . ' (' . ucwords( $response['license'] ) . ')',
146
			'License Level'         => $package,
147
			'Alt Emails'            => sprintf( "Admin: %s, GV Support: %s", get_bloginfo( 'admin_email' ), gravityview()->plugin->settings->get( 'support-email' ) ),
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal Admin: %s, GV Support: %s does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
148
			'Payment Details'       => $response['customer_name'] . ' ' . $response['customer_email'],
149
			'WordPress Version'     => get_bloginfo( 'version', 'display' ),
150
			'PHP Version'           => phpversion() . ' on ' . esc_html( $_SERVER['SERVER_SOFTWARE'] ),
0 ignored issues
show
introduced by
Detected usage of a non-validated input variable: $_SERVER
Loading history...
151
			'No-Conflict Mode'      => empty( $no_conflict_mode ) ? 'Disabled' : 'Enabled',
152
			'GravityView Version'   => \GV\Plugin::$version,
153
			'Gravity Forms Version' => GFForms::$version,
154
		);
155
156
		// End prevent any PHP warnings
157
		ob_get_clean();
158
159
		// Help Scout length limit is 200 characters
160
		foreach( $data as $key => $value ) {
161
			if ( ! is_string( $value ) ) {
162
                continue;
163
			}
164
		    $data[ $key ] = mb_substr( $value, 0, 200 );
165
        }
166
167
		$localization_data = array(
168
			'contactEnabled' => (int)GVCommon::has_cap( 'gravityview_contact_support' ),
0 ignored issues
show
introduced by
No space after closing casting parenthesis is prohibited
Loading history...
169
			'data' => $data,
170
			'translation' => $translation,
171
            'suggest' => array(),
172
		);
173
174
		/**
175
         * @filter `gravityview/support_port/localization_data` Filter data passed to the Support Port, before localize_script is run
176
		 * @since 2.0
177
         * @param array $localization_data {
178
         *   @type int $contactEnabled Can the user contact support?
179
         *   @type array $data Support/license info
180
         *   @type array $translation i18n strings
181
         *   @type array $suggest Article IDs to recommend to the user (per page in the admin
182
         * }
183
		 */
184
		$localization_data = apply_filters( 'gravityview/support_port/localization_data', $localization_data );
185
186
		wp_localize_script( 'gravityview-support', 'gvSupport', $localization_data );
187
188
		unset( $localization_data, $data, $translation, $response, $package );
189
	}
190
191
	/**
192
	 * Check whether to show Support for a user
193
	 *
194
	 * If the user doesn't have the `gravityview_support_port` capability, returns false; then
195
	 * If global setting is "hide", returns false; then
196
     * If user preference is not set, return global setting; then
197
     * If user preference is set, return that setting.
198
	 *
199
	 * @since 1.15
200
     * @since 1.17.5 Changed behavior to respect global setting
201
	 *
202
	 * @param int $user Optional. ID of the user to check, defaults to 0 for current user.
203
	 *
204
	 * @return bool Whether to show GravityView support port
205
	 */
206
	static public function show_for_user( $user = 0 ) {
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
207
208
		if ( ! GVCommon::has_cap( 'gravityview_support_port' ) ) {
209
			return false;
210
		}
211
212
		$global_setting = gravityview()->plugin->settings->get( 'support_port' );
213
214
		if ( empty( $global_setting ) ) {
215
            return false;
216
		}
217
218
		// Get the per-user Support Port setting
219
		$user_pref = get_user_option( self::user_pref_name, $user );
220
221
		// Not configured; default to global setting (which is true at this point)
222
		if ( false === $user_pref ) {
223
			$user_pref = $global_setting;
224
		}
225
226
		return ! empty( $user_pref );
227
	}
228
229
230
	/**
231
	 * Update User Profile preferences for GravityView Support
232
	 *
233
	 * @since 1.5
234
	 *
235
	 * @param int $user_id
236
	 *
237
	 * @return void
238
	 */
239
	public function update_user_meta_value( $user_id ) {
240
		if ( current_user_can( 'edit_user', $user_id ) && isset( $_POST[ self::user_pref_name ] ) ) {
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
241
			update_user_meta( $user_id, self::user_pref_name, intval( $_POST[ self::user_pref_name ] ) );
0 ignored issues
show
introduced by
update_user_meta() usage is highly discouraged, check VIP documentation on "Working with wp_users"
Loading history...
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
242
		}
243
	}
244
245
	/**
246
	 * Modify User Profile
247
	 *
248
	 * Modifies the output of profile.php to add GravityView Support preference
249
	 *
250
	 * @since 1.15
251
     * @since 1.17.5 Only show if global setting is active
252
	 *
253
	 * @param WP_User $user Current user info
254
	 *
255
	 * @return void
256
	 */
257
	public function user_field( $user ) {
258
259
		$global_setting = gravityview()->plugin->settings->get( 'support_port' );
260
261
		if ( empty( $global_setting ) ) {
262
            return;
263
		}
264
265
		/**
266
		 * @filter `gravityview/support_port/show_profile_setting` Should the "GravityView Support Port" setting be shown on user profiles?
267
		 * @since 1.15
268
		 * @param boolean $allow_profile_setting Default: `true`, if the user has the `gravityview_support_port` capability, which defaults to true for Contributors and higher
269
		 * @param WP_User $user Current user object
270
		 */
271
		$allow_profile_setting = apply_filters( 'gravityview/support_port/show_profile_setting', GVCommon::has_cap( 'gravityview_support_port' ), $user );
272
273
		if ( $allow_profile_setting && current_user_can( 'edit_user', $user->ID ) ) {
274
			?>
275
			<table class="form-table">
276
				<tbody>
277
					<tr class="user-gravityview-support-button-wrap">
278
						<th scope="row"><?php
279
							/* translators: "Support Port" can be translated as "Support Portal" or "Support Window" */
280
							_e( 'GravityView Support Port', 'gravityview' );
281
						?></th>
282
						<td>
283
							<fieldset>
284
								<legend class="screen-reader-text"><span><?php
285
										/* translators: "Support Port" can be translated as "Support Portal" or "Support Window" */
286
										_e( 'GravityView Support Port', 'gravityview' );
287
								?></span></legend>
288
								<label>
289
									<input name="<?php echo esc_attr( self::user_pref_name ); ?>" type="hidden" value="0"/>
290
									<input name="<?php echo esc_attr( self::user_pref_name ); ?>" type="checkbox" value="1" <?php checked( self::show_for_user( $user->ID ) ); ?> />
291
									<?php esc_html_e( 'Show GravityView Support Port when on a GravityView-related page', 'gravityview' ); ?>
292
								</label>
293
							</fieldset>
294
						</td>
295
					</tr>
296
				</tbody>
297
			</table>
298
		<?php }
299
	}
300
}
301
302
new GravityView_Support_Port;