Completed
Push — trunk ( c5913a...941a5a )
by Justin
04:33
created

CMB2_Ajax::hooks()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 11
ccs 9
cts 9
cp 1
rs 9.4285
cc 2
eloc 7
nc 2
nop 1
crap 2
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
	 * Constructor
25
	 * @since 2.2.0
26
	 */
27 1
	public function __construct() {
28 1
		self::hooks( $this );
29 1
	}
30
31
	/**
32
	 * Hook in the oembed ajax handlers
33
	 * @since  2.2.0
34
	 * @param  CMB2_Ajax  $self This object (for hooking)
35
	 */
36 1
	public static function hooks( $self ) {
37 1
		static $hooked = false;
38
39 1
		if ( ! $hooked ) {
40 1
			add_action( 'wp_ajax_cmb2_oembed_handler', array( $self, 'oembed_handler' ) );
41 1
			add_action( 'wp_ajax_nopriv_cmb2_oembed_handler', array( $self, 'oembed_handler' ) );
42
			// Need to occasionally clean stale oembed cache data from the option value.
43 1
			add_action( 'cmb2_save_options-page_fields', array( __CLASS__, 'clean_stale_options_page_oembeds' ) );
44 1
			$hooked = true;
45 1
		}
46 1
	}
47
48
	/**
49
	 * Handles our oEmbed ajax request
50
	 * @since  0.9.5
51
	 * @return object oEmbed embed code | fallback | error message
52
	 */
53
	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...
54
55
		// Verify our nonce
56
		if ( ! ( isset( $_REQUEST['cmb2_ajax_nonce'], $_REQUEST['oembed_url'] ) && wp_verify_nonce( $_REQUEST['cmb2_ajax_nonce'], 'ajax_nonce' ) ) ) {
57
			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...
58
		}
59
60
		// Sanitize our search string
61
		$oembed_string = sanitize_text_field( $_REQUEST['oembed_url'] );
62
63
		// Send back error if empty
64
		if ( empty( $oembed_string ) ) {
65
			wp_send_json_error( '<p class="ui-state-error-text">' . __( 'Please Try Again', 'cmb2' ) . '</p>' );
66
		}
67
68
		// Set width of embed
69
		$embed_width = isset( $_REQUEST['oembed_width'] ) && intval( $_REQUEST['oembed_width'] ) < 640 ? intval( $_REQUEST['oembed_width'] ) : '640';
70
71
		// Set url
72
		$oembed_url = esc_url( $oembed_string );
73
74
		// Set args
75
		$embed_args = array( 'width' => $embed_width );
76
77
		$this->ajax_update = true;
78
79
		// Get embed code (or fallback link)
80
		$html = $this->get_oembed( array(
81
			'url'         => $oembed_url,
82
			'object_id'   => $_REQUEST['object_id'],
83
			'object_type' => isset( $_REQUEST['object_type'] ) ? $_REQUEST['object_type'] : 'post',
84
			'oembed_args' => $embed_args,
85
			'field_id'    => $_REQUEST['field_id'],
86
		) );
87
88
		wp_send_json_success( $html );
89
	}
90
91
	/**
92
	 * Retrieves oEmbed from url/object ID
93
	 * @since  0.9.5
94
	 * @param  array  $args      Arguments for method
95
	 * @return string            html markup with embed or fallback
96
	 */
97 2
	public function get_oembed( $args ) {
98
99 2
		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...
100
101 2
		$oembed_url = esc_url( $args['url'] );
102
103
		// Sanitize object_id
104 2
		$this->object_id = is_numeric( $args['object_id'] ) ? absint( $args['object_id'] ) : sanitize_text_field( $args['object_id'] );
105
106 2
		$args = wp_parse_args( $args, array(
107 2
			'object_type' => 'post',
108 2
			'oembed_args' => $this->embed_args,
109 2
			'field_id'    => false,
110 2
		) );
111
112 2
		$this->embed_args =& $args;
113
114
		/**
115
		 * Set the post_ID so oEmbed won't fail
116
		 * wp-includes/class-wp-embed.php, WP_Embed::shortcode()
117
		 */
118 2
		$wp_embed->post_ID = $this->object_id;
119
120
		// Special scenario if NOT a post object
121 2
		if ( isset( $args['object_type'] ) && 'post' != $args['object_type'] ) {
122
123 1
			if ( 'options-page' == $args['object_type'] ) {
124
125
				// Bogus id to pass some numeric checks. Issue with a VERY large WP install?
126 1
				$wp_embed->post_ID = 1987645321;
127 1
			}
128
129
			// Ok, we need to hijack the oembed cache system
130 1
			$this->hijack = true;
131 1
			$this->object_type = $args['object_type'];
132
133
			// Gets ombed cache from our object's meta (vs postmeta)
134 1
			add_filter( 'get_post_metadata', array( $this, 'hijack_oembed_cache_get' ), 10, 3 );
135
136
			// Sets ombed cache in our object's meta (vs postmeta)
137 1
			add_filter( 'update_post_metadata', array( $this, 'hijack_oembed_cache_set' ), 10, 4 );
138
139 1
		}
140
141 2
		$embed_args = '';
142
143 2
		foreach ( $args['oembed_args'] as $key => $val ) {
144 2
			$embed_args .= " $key=\"$val\"";
145 2
		}
146
147
		// Ping WordPress for an embed
148 2
		$check_embed = $wp_embed->run_shortcode( '[embed' . $embed_args . ']' . $oembed_url . '[/embed]' );
149
150
		// Fallback that WordPress creates when no oEmbed was found
151 2
		$fallback = $wp_embed->maybe_make_link( $oembed_url );
152
153
		// Send back our embed
154 2
		if ( $check_embed && $check_embed != $fallback ) {
155 2
			return '<div class="embed-status">' . $check_embed . '<p class="cmb2-remove-wrapper"><a href="#" class="cmb2-remove-file-button" rel="' . $args['field_id'] . '">' . __( 'Remove Embed', 'cmb2' ) . '</a></p></div>';
156
		}
157
158
		// Otherwise, send back error info that no oEmbeds were found
159 1
		return '<p class="ui-state-error-text">' . sprintf( __( 'No oEmbed Results Found for %s. View more info at', 'cmb2' ), $fallback ) . ' <a href="http://codex.wordpress.org/Embeds" target="_blank">codex.wordpress.org/Embeds</a>.</p>';
160
161
	}
162
163
	/**
164
	 * Hijacks retrieving of cached oEmbed.
165
	 * Returns cached data from relevant object metadata (vs postmeta)
166
	 *
167
	 * @since  0.9.5
168
	 * @param  boolean $check     Whether to retrieve postmeta or override
169
	 * @param  int     $object_id Object ID
170
	 * @param  string  $meta_key  Object metakey
171
	 * @return mixed              Object's oEmbed cached data
172
	 */
173 68
	public function hijack_oembed_cache_get( $check, $object_id, $meta_key ) {
174 68
		if ( ! $this->hijack || ( $this->object_id != $object_id && 1987645321 !== $object_id ) ) {
175 67
			return $check;
176
		}
177
178 2
		if ( $this->ajax_update ) {
179
			return false;
180
		}
181
182 2
		return $this->cache_action( $meta_key );
183
	}
184
185
	/**
186
	 * Hijacks saving of cached oEmbed.
187
	 * Saves cached data to relevant object metadata (vs postmeta)
188
	 *
189
	 * @since  0.9.5
190
	 * @param  boolean $check      Whether to continue setting postmeta
191
	 * @param  int     $object_id  Object ID to get postmeta from
192
	 * @param  string  $meta_key   Postmeta's key
193
	 * @param  mixed   $meta_value Value of the postmeta to be saved
194
	 * @return boolean             Whether to continue setting
195
	 */
196 52
	public function hijack_oembed_cache_set( $check, $object_id, $meta_key, $meta_value ) {
197
198
		if (
199 52
			! $this->hijack
200 52
			|| ( $this->object_id != $object_id && 1987645321 !== $object_id )
201
			// only want to hijack oembed meta values
202 52
			|| 0 !== strpos( $meta_key, '_oembed_' )
203 52
		) {
204 51
			return $check;
205
		}
206
207 2
		$this->cache_action( $meta_key, $meta_value );
208
209
		// Anything other than `null` to cancel saving to postmeta
210 2
		return true;
211
	}
212
213
	/**
214
	 * Gets/updates the cached oEmbed value from/to relevant object metadata (vs postmeta)
215
	 *
216
	 * @since  1.3.0
217
	 * @param  string  $meta_key   Postmeta's key
218
	 * @param  mixed   $meta_value (Optional) value of the postmeta to be saved
0 ignored issues
show
Bug introduced by
There is no parameter named $meta_value. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
219
	 */
220 2
	protected function cache_action( $meta_key ) {
221 2
		$func_args = func_get_args();
222 2
		$action    = isset( $func_args[1] ) ? 'update' : 'get';
223
224 2
		if ( 'options-page' === $this->object_type ) {
225
226 2
			$args = array( $meta_key );
227
228 2
			if ( 'update' === $action ) {
229 2
				$args[] = $func_args[1];
230 2
				$args[] = true;
231 2
			}
232
233
			// Cache the result to our options
234 2
			$status = call_user_func_array( array( cmb2_options( $this->object_id ), $action ), $args );
235 2
		} else {
236
237
			$args = array( $this->object_type, $this->object_id, $meta_key );
238
			$args[] = 'update' === $action ? $func_args : true;
239
240
			// Cache the result to our metadata
241
			$status = call_user_func_array( $action . '_metadata', $args );
242
		}
243
244 2
		return $status;
245
	}
246
247
	/**
248
	 * Hooks in when options-page data is saved to clean stale
249
	 * oembed cache data from the option value.
250
	 * @since  2.2.0
251
	 * @param  string  $option_key The options-page option key
252
	 * @return void
253
	 */
254 1
	public static function clean_stale_options_page_oembeds( $option_key ) {
255 1
		$options = cmb2_options( $option_key )->get_options();
256 1
		if ( is_array( $options ) ) {
257
258 1
			$ttl = apply_filters( 'oembed_ttl', DAY_IN_SECONDS, '', array(), 0 );
259 1
			$now = time();
260 1
			$modified = false;
261
262 1
			foreach ( $options as $key => $value ) {
263
				// Check for cached oembed data
264 1
				if ( 0 === strpos( $key, '_oembed_time_' ) ) {
265
					$cached_recently = ( $now - $value ) < $ttl;
266
267
					if ( ! $cached_recently ) {
268
						$modified = true;
269
						// Remove the the cached ttl expiration, and the cached oembed value.
270
						unset( $options[ $key ] );
271
						unset( $options[ str_replace( '_oembed_time_', '_oembed_', $key ) ] );
272
					}
273
				}
274
				// Remove the cached unknown values
275 1
				elseif ( '{{unknown}}' === $value ) {
276 1
					$modified = true;
277 1
					unset( $options[ $key ] );
278 1
				}
279 1
			}
280 1
		}
281
		// Update the option and remove stale cache data
282 1
		if ( $modified ) {
0 ignored issues
show
Bug introduced by
The variable $modified does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
283 1
			$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...
284 1
		}
285 1
	}
286
287
}
288