Completed
Push — trunk ( 4bf362...177664 )
by
unknown
493:49 queued 491:11
created

CMB2_Ajax::get_instance()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 7
ccs 0
cts 3
cp 0
crap 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * CMB2 ajax methods
5
 * (i.e. a lot of work to get oEmbeds to work with non-post objects)
6
 *
7
 * @since  0.9.5
8
 *
9
 * @category  WordPress_Plugin
10
 * @package   CMB2
11
 * @author    WebDevStudios
12
 * @license   GPL-2.0+
13
 */
14
class CMB2_Ajax {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
15
16
	// Whether to hijack the oembed cache system
17
	protected $hijack      = false;
18
	protected $object_id   = 0;
19
	protected $embed_args  = array();
20
	protected $object_type = 'post';
21
	protected $ajax_update = false;
22
23
	/**
24
	 * Instance of this class
25
	 *
26
	 * @since 2.2.2
27
	 * @var object
28
	 */
29
	protected static $instance;
30
31
	/**
32
	 * Get the singleton instance of this class
33
	 *
34
	 * @since 2.2.2
35
	 * @return CMB2_Ajax
36
	 */
37
	public static function get_instance() {
38
		if ( ! ( self::$instance instanceof self ) ) {
39
			self::$instance = new self();
40
		}
41
42
		return self::$instance;
43
	}
44
45
	/**
46
	 * Constructor
47
	 *
48
	 * @since 2.2.0
49
	 */
50
	protected function __construct() {
51
		add_action( 'wp_ajax_cmb2_oembed_handler', array( $this, 'oembed_handler' ) );
52
		add_action( 'wp_ajax_nopriv_cmb2_oembed_handler', array( $this, 'oembed_handler' ) );
53
		// Need to occasionally clean stale oembed cache data from the option value.
54
		add_action( 'cmb2_save_options-page_fields', array( __CLASS__, 'clean_stale_options_page_oembeds' ) );
55
	}
56
57
	/**
58
	 * Handles our oEmbed ajax request
59
	 *
60
	 * @since  0.9.5
61
	 * @return object oEmbed embed code | fallback | error message
62
	 */
63
	public function oembed_handler() {
0 ignored issues
show
Coding Style introduced by
oembed_handler uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
64
65
		// Verify our nonce
66
		if ( ! ( isset( $_REQUEST['cmb2_ajax_nonce'], $_REQUEST['oembed_url'] ) && wp_verify_nonce( $_REQUEST['cmb2_ajax_nonce'], 'ajax_nonce' ) ) ) {
67
			die();
0 ignored issues
show
Coding Style Compatibility introduced by
The method oembed_handler() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
68
		}
69
70 1
		// Sanitize our search string
71
		$oembed_string = sanitize_text_field( $_REQUEST['oembed_url'] );
72 1
73
		// Send back error if empty
74 1
		if ( empty( $oembed_string ) ) {
75
			wp_send_json_error( '<p class="ui-state-error-text">' . esc_html__( 'Please Try Again', 'cmb2' ) . '</p>' );
76
		}
77 1
78
		// Set width of embed
79 1
		$embed_width = isset( $_REQUEST['oembed_width'] ) && intval( $_REQUEST['oembed_width'] ) < 640 ? intval( $_REQUEST['oembed_width'] ) : '640';
80 1
81 1
		// Set url
82 1
		$oembed_url = esc_url( $oembed_string );
83 1
84 1
		// Set args
85
		$embed_args = array( 'width' => $embed_width );
86 1
87
		$this->ajax_update = true;
88
89
		// Get embed code (or fallback link)
90
		$html = $this->get_oembed( array(
91
			'url'         => $oembed_url,
92
			'object_id'   => $_REQUEST['object_id'],
93 1
			'object_type' => isset( $_REQUEST['object_type'] ) ? $_REQUEST['object_type'] : 'post',
94
			'oembed_args' => $embed_args,
95
			'field_id'    => $_REQUEST['field_id'],
96 1
		) );
97
98
		wp_send_json_success( $html );
99
	}
100
101
	/**
102
	 * Retrieves oEmbed from url/object ID
103
	 *
104
	 * @since  0.9.5
105
	 * @param  array $args      Arguments for method
106
	 * @return string            html markup with embed or fallback
107
	 */
108
	public function get_oembed_no_edit( $args ) {
109
		global $wp_embed;
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...
110
111
		$oembed_url = esc_url( $args['url'] );
112
113
		// Sanitize object_id
114
		$this->object_id = is_numeric( $args['object_id'] ) ? absint( $args['object_id'] ) : sanitize_text_field( $args['object_id'] );
115
116
		$args = wp_parse_args( $args, array(
117
			'object_type' => 'post',
118
			'oembed_args' => $this->embed_args,
119 1
			'field_id'    => false,
120
			'wp_error'    => false,
121 1
		) );
122 1
123 1
		$this->embed_args =& $args;
124
125
		/**
126 1
		 * Set the post_ID so oEmbed won't fail
127
		 * wp-includes/class-wp-embed.php, WP_Embed::shortcode()
128
		 */
129 1
		$wp_embed->post_ID = $this->object_id;
130
131
		// Special scenario if NOT a post object
132 1
		if ( isset( $args['object_type'] ) && 'post' != $args['object_type'] ) {
133 1
134
			if ( 'options-page' == $args['object_type'] ) {
135
136
				// Bogus id to pass some numeric checks. Issue with a VERY large WP install?
137
				$wp_embed->post_ID = 1987645321;
138
			}
139
140
			// Ok, we need to hijack the oembed cache system
141
			$this->hijack = true;
142
			$this->object_type = $args['object_type'];
143
144
			// Gets ombed cache from our object's meta (vs postmeta)
145
			add_filter( 'get_post_metadata', array( $this, 'hijack_oembed_cache_get' ), 10, 3 );
146
147
			// Sets ombed cache in our object's meta (vs postmeta)
148
			add_filter( 'update_post_metadata', array( $this, 'hijack_oembed_cache_set' ), 10, 4 );
149
150
		}
151
152
		$embed_args = '';
153
154
		foreach ( $args['oembed_args'] as $key => $val ) {
155
			$embed_args .= " $key=\"$val\"";
156
		}
157
158
		// Ping WordPress for an embed
159
		$embed = $wp_embed->run_shortcode( '[embed' . $embed_args . ']' . $oembed_url . '[/embed]' );
160
161
		// Fallback that WordPress creates when no oEmbed was found
162
		$fallback = $wp_embed->maybe_make_link( $oembed_url );
163
164
		return compact( 'embed', 'fallback', 'args' );
165
	}
166
167
	/**
168
	 * Retrieves oEmbed from url/object ID
169
	 *
170
	 * @since  0.9.5
171
	 * @param  array $args      Arguments for method
172
	 * @return string            html markup with embed or fallback
173
	 */
174
	public function get_oembed( $args ) {
175
		$oembed = $this->get_oembed_no_edit( $args );
176
177
		// Send back our embed
178
		if ( $oembed['embed'] && $oembed['embed'] != $oembed['fallback'] ) {
179
			return '<div class="cmb2-oembed embed-status">' . $oembed['embed'] . '<p class="cmb2-remove-wrapper"><a href="#" class="cmb2-remove-file-button" rel="' . $oembed['args']['field_id'] . '">' . esc_html__( 'Remove Embed', 'cmb2' ) . '</a></p></div>';
180
		}
181
182
		// Otherwise, send back error info that no oEmbeds were found
183
		return sprintf(
184
			'<p class="ui-state-error-text">%s</p>',
185
			sprintf(
186
				/* translators: 1: results for. 2: link to codex.wordpress.org/Embeds */
187
				esc_html__( 'No oEmbed Results Found for %1$s. View more info at %2$s.', 'cmb2' ),
188
				$oembed['fallback'],
189
				'<a href="https://codex.wordpress.org/Embeds" target="_blank">codex.wordpress.org/Embeds</a>'
190
			)
191
		);
192
	}
193
194
	/**
195
	 * Hijacks retrieving of cached oEmbed.
196
	 * Returns cached data from relevant object metadata (vs postmeta)
197
	 *
198
	 * @since  0.9.5
199
	 * @param  boolean $check     Whether to retrieve postmeta or override
200
	 * @param  int     $object_id Object ID
201
	 * @param  string  $meta_key  Object metakey
202
	 * @return mixed              Object's oEmbed cached data
203
	 */
204
	public function hijack_oembed_cache_get( $check, $object_id, $meta_key ) {
205
		if ( ! $this->hijack || ( $this->object_id != $object_id && 1987645321 !== $object_id ) ) {
206
			return $check;
207
		}
208
209
		if ( $this->ajax_update ) {
210 1
			return false;
211
		}
212
213
		return $this->cache_action( $meta_key );
214
	}
215
216
	/**
217
	 * Hijacks saving of cached oEmbed.
218
	 * Saves cached data to relevant object metadata (vs postmeta)
219
	 *
220
	 * @since  0.9.5
221
	 * @param  boolean $check      Whether to continue setting postmeta
222
	 * @param  int     $object_id  Object ID to get postmeta from
223
	 * @param  string  $meta_key   Postmeta's key
224
	 * @param  mixed   $meta_value Value of the postmeta to be saved
225
	 * @return boolean             Whether to continue setting
226
	 */
227
	public function hijack_oembed_cache_set( $check, $object_id, $meta_key, $meta_value ) {
228
229
		if (
230
			! $this->hijack
231
			|| ( $this->object_id != $object_id && 1987645321 !== $object_id )
232
			// only want to hijack oembed meta values
233
			|| 0 !== strpos( $meta_key, '_oembed_' )
234
		) {
235
			return $check;
236
		}
237
238
		$this->cache_action( $meta_key, $meta_value );
239
240
		// Anything other than `null` to cancel saving to postmeta
241
		return true;
242
	}
243
244
	/**
245
	 * Gets/updates the cached oEmbed value from/to relevant object metadata (vs postmeta)
246
	 *
247
	 * @since 1.3.0
248
	 * @param string $meta_key Postmeta's key
249
	 */
250
	protected function cache_action( $meta_key ) {
251
		$func_args = func_get_args();
252
		$action    = isset( $func_args[1] ) ? 'update' : 'get';
253
254
		if ( 'options-page' === $this->object_type ) {
255
256
			$args = array( $meta_key );
257
258
			if ( 'update' === $action ) {
259
				$args[] = $func_args[1];
260
				$args[] = true;
261
			}
262
263
			// Cache the result to our options
264
			$status = call_user_func_array( array( cmb2_options( $this->object_id ), $action ), $args );
265
		} else {
266
267
			$args = array( $this->object_type, $this->object_id, $meta_key );
268
			$args[] = 'update' === $action ? $func_args : true;
269
270
			// Cache the result to our metadata
271
			$status = call_user_func_array( $action . '_metadata', $args );
272
		}
273
274
		return $status;
275
	}
276
277
	/**
278
	 * Hooks in when options-page data is saved to clean stale
279
	 * oembed cache data from the option value.
280
	 *
281
	 * @since  2.2.0
282
	 * @param  string $option_key The options-page option key
283
	 * @return void
284
	 */
285
	public static function clean_stale_options_page_oembeds( $option_key ) {
286
		$options = cmb2_options( $option_key )->get_options();
287
		$modified = false;
288
		if ( is_array( $options ) ) {
289
290
			$ttl = apply_filters( 'oembed_ttl', DAY_IN_SECONDS, '', array(), 0 );
291
			$now = time();
292
293
			foreach ( $options as $key => $value ) {
294
				// Check for cached oembed data
295
				if ( 0 === strpos( $key, '_oembed_time_' ) ) {
296
					$cached_recently = ( $now - $value ) < $ttl;
297
298
					if ( ! $cached_recently ) {
299
						$modified = true;
300
						// Remove the the cached ttl expiration, and the cached oembed value.
301
						unset( $options[ $key ] );
302
						unset( $options[ str_replace( '_oembed_time_', '_oembed_', $key ) ] );
303
					}
304
				} // Remove the cached unknown values
305
				elseif ( '{{unknown}}' === $value ) {
306
					$modified = true;
307
					unset( $options[ $key ] );
308
				}
309
			}
310
		}
311
312
		// Update the option and remove stale cache data
313
		if ( $modified ) {
314
			$updated = cmb2_options( $option_key )->set( $options );
0 ignored issues
show
Unused Code introduced by
$updated is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
315
		}
316
	}
317
318
}
319