Completed
Push — trunk ( 1199b1...89b293 )
by Justin
09:57
created

helper-functions.php ➔ cmb2_autoload_classes()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4.0312

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 7
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 13
ccs 7
cts 8
cp 0.875
crap 4.0312
rs 9.2
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 18 and the first side effect is on line 116.

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
 * CMB2 Helper Functions
4
 *
5
 * @category  WordPress_Plugin
6
 * @package   CMB2
7
 * @author    WebDevStudios
8
 * @license   GPL-2.0+
9
 * @link      http://webdevstudios.com
10
 */
11
12
/**
13
 * Helper function to provide directory path to CMB2
14
 * @since  2.0.0
15
 * @param  string  $path Path to append
16
 * @return string        Directory with optional path appended
17
 */
18
function cmb2_dir( $path = '' ) {
19 27
	return CMB2_DIR . $path;
20
}
21
22
/**
23
 * Autoloads files with CMB2 classes when needed
24
 * @since  1.0.0
25
 * @param  string $class_name Name of the class being requested
26
 */
27
function cmb2_autoload_classes( $class_name ) {
28 26
	if ( 0 !== strpos( $class_name, 'CMB2' ) ) {
29
		return;
30
	}
31
32 26
	$path = 'includes';
33
34 26
	if ( 'CMB2_Type' === $class_name || 0 === strpos( $class_name, 'CMB2_Type_' ) ) {
35 22
		$path .= '/types';
36 22
	}
37
38 26
	include_once( cmb2_dir( "$path/{$class_name}.php" ) );
39 26
}
40
41
/**
42
 * Get instance of the CMB2_Utils class
43
 * @since  2.0.0
44
 * @return CMB2_Utils object CMB2 utilities class
45
 */
46
function cmb2_utils() {
47 1
	static $cmb2_utils;
48 1
	$cmb2_utils = $cmb2_utils ? $cmb2_utils : new CMB2_Utils();
49 1
	return $cmb2_utils;
50
}
51
52
/**
53
 * Get instance of the CMB2_Ajax class
54
 * @since  2.0.0
55
 * @return CMB2_Ajax object CMB2 ajax class
56
 */
57
function cmb2_ajax() {
58 5
	return CMB2_Ajax::get_instance();
59
}
60
61
/**
62
 * Get instance of the CMB2_Option class for the passed metabox ID
63
 * @since  2.0.0
64
 * @return CMB2_Option object Options class for setting/getting options for metabox
65
 */
66
function cmb2_options( $key ) {
67 10
	return CMB2_Options::get( $key );
68
}
69
70
/**
71
 * Get a cmb oEmbed. Handles oEmbed getting for non-post objects
72
 * @since  2.0.0
73
 * @param  array   $args Arguments. Accepts:
74
 *
75
 *         'url'         - URL to retrieve the oEmbed from,
76
 *         'object_id'   - $post_id,
77
 *         'object_type' - 'post',
78
 *         'oembed_args' - $embed_args, // array containing 'width', etc
79
 *         'field_id'    - false,
80
 *         'cache_key'   - false,
81
 *         'wp_error'    - true/false, // To return a wp_error object if no embed found.
82
 *
83
 * @return string        oEmbed string
84
 */
85
function cmb2_get_oembed( $args = array() ) {
86 1
	$oembed = cmb2_ajax()->get_oembed_no_edit( $args );
87
88
	// Send back our embed
89 1
	if ( $oembed['embed'] && $oembed['embed'] != $oembed['fallback'] ) {
90 1
		return '<div class="cmb2-oembed">' . $oembed['embed'] . '</div>';
91
	}
92
93
	$error = sprintf(
94
		/* translators: 1: results for. 2: link to codex.wordpress.org/Embeds */
95
		esc_html__( 'No oEmbed Results Found for %1$s. View more info at %2$s.', 'cmb2' ),
96
		$oembed['fallback'],
97
		'<a href="https://codex.wordpress.org/Embeds" target="_blank">codex.wordpress.org/Embeds</a>'
98
	);
99
100
	if ( isset( $args['wp_error'] ) && $args['wp_error'] ) {
101
		return new WP_Error( 'cmb2_get_oembed_result', $wp_error, compact( 'oembed', 'args' ) );
0 ignored issues
show
Bug introduced by
The variable $wp_error does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
102
	}
103
104
	// Otherwise, send back error info that no oEmbeds were found
105
	return '<p class="ui-state-error-text">' . $error . '</p>';
106
}
107
108
/**
109
 * Outputs the return of cmb2_get_oembed.
110
 * @since  2.2.2
111
 * @see cmb2_get_oembed
112
 */
113
function cmb2_do_oembed( $args = array() ) {
114 1
	echo cmb2_get_oembed( $args );
115 1
}
116
add_action( 'cmb2_do_oembed', 'cmb2_do_oembed' );
117
118
/**
119
 * A helper function to get an option from a CMB2 options array
120
 * @since  1.0.1
121
 * @param  string  $option_key Option key
122
 * @param  string  $field_id   Option array field key
123
 * @param  mixed   $default    Optional default fallback value
124
 * @return array               Options array or specific field
125
 */
126
function cmb2_get_option( $option_key, $field_id = '', $default = false ) {
127 2
	return cmb2_options( $option_key )->get( $field_id, $default );
128
}
129
130
/**
131
 * A helper function to update an option in a CMB2 options array
132
 * @since  2.0.0
133
 * @param  string  $option_key Option key
134
 * @param  string  $field_id   Option array field key
135
 * @param  mixed   $value      Value to update data with
136
 * @param  boolean $single     Whether data should not be an array
137
 * @return boolean             Success/Failure
138
 */
139
function cmb2_update_option( $option_key, $field_id, $value, $single = true ) {
140 1
	if ( cmb2_options( $option_key )->update( $field_id, $value, false, $single ) ) {
141 1
		return cmb2_options( $option_key )->set();
142
	}
143
144
	return false;
145
}
146
147
/**
148
 * Get a CMB2 field object.
149
 * @since  1.1.0
150
 * @param  array  $meta_box    Metabox ID or Metabox config array
151
 * @param  array  $field_id    Field ID or all field arguments
152
 * @param  int    $object_id   Object ID
153
 * @param  string $object_type Type of object being saved. (e.g., post, user, comment, or options-page).
154
 *                             Defaults to metabox object type.
155
 * @return CMB2_Field|null     CMB2_Field object unless metabox config cannot be found
156
 */
157
function cmb2_get_field( $meta_box, $field_id, $object_id = 0, $object_type = '' ) {
158
159 10
	$object_id = $object_id ? $object_id : get_the_ID();
160 10
	$cmb = $meta_box instanceof CMB2 ? $meta_box : cmb2_get_metabox( $meta_box, $object_id );
161
162 10
	if ( ! $cmb ) {
163
		return;
164
	}
165
166 10
	$cmb->object_type( $object_type ? $object_type : $cmb->mb_object_type() );
0 ignored issues
show
Security Bug introduced by
It seems like $object_type ? $object_t... $cmb->mb_object_type() can also be of type false; however, CMB2::object_type() does only seem to accept string, did you maybe forget to handle an error condition?
Loading history...
167
168 10
	return $cmb->get_field( $field_id );
169
}
170
171
/**
172
 * Get a field's value.
173
 * @since  1.1.0
174
 * @param  array  $meta_box    Metabox ID or Metabox config array
175
 * @param  array  $field_id    Field ID or all field arguments
176
 * @param  int    $object_id   Object ID
177
 * @param  string $object_type Type of object being saved. (e.g., post, user, comment, or options-page).
178
 *                             Defaults to metabox object type.
179
 * @return mixed               Maybe escaped value
180
 */
181
function cmb2_get_field_value( $meta_box, $field_id, $object_id = 0, $object_type = '' ) {
182 1
	$field = cmb2_get_field( $meta_box, $field_id, $object_id, $object_type );
183 1
	return $field->escaped_value();
184
}
185
186
/**
187
 * Because OOP can be scary
188
 * @since  2.0.2
189
 * @param  array $meta_box_config Metabox Config array
190
 * @return CMB2 object            Instantiated CMB2 object
191
 */
192
function new_cmb2_box( array $meta_box_config ) {
193 2
	return cmb2_get_metabox( $meta_box_config );
194
}
195
196
/**
197
 * Retrieve a CMB2 instance by the metabox ID
198
 * @since  2.0.0
199
 * @param  mixed  $meta_box    Metabox ID or Metabox config array
200
 * @param  int    $object_id   Object ID
201
 * @param  string $object_type Type of object being saved. (e.g., post, user, comment, or options-page).
202
 *                             Defaults to metabox object type.
203
 * @return CMB2 object
204
 */
205
function cmb2_get_metabox( $meta_box, $object_id = 0, $object_type = '' ) {
206
207 32
	if ( $meta_box instanceof CMB2 ) {
208 1
		return $meta_box;
209
	}
210
211 32
	if ( is_string( $meta_box ) ) {
212 26
		$cmb = CMB2_Boxes::get( $meta_box );
213 26
	} else {
214
		// See if we already have an instance of this metabox
215 9
		$cmb = CMB2_Boxes::get( $meta_box['id'] );
216
		// If not, we'll initate a new metabox
217 9
		$cmb = $cmb ? $cmb : new CMB2( $meta_box, $object_id );
218
	}
219
220 32
	if ( $cmb && $object_id ) {
221 17
		$cmb->object_id( $object_id );
222 17
	}
223
224 32
	if ( $cmb && $object_type ) {
225 7
		$cmb->object_type( $object_type );
226 7
	}
227
228 32
	return $cmb;
229
}
230
231
/**
232
 * Returns array of sanitized field values from a metabox (without saving them)
233
 * @since  2.0.3
234
 * @param  mixed $meta_box         Metabox ID or Metabox config array
235
 * @param  array $data_to_sanitize Array of field_id => value data for sanitizing (likely $_POST data).
236
 * @return mixed                   Array of sanitized values or false if no CMB2 object found
237
 */
238
function cmb2_get_metabox_sanitized_values( $meta_box, array $data_to_sanitize ) {
239 1
	$cmb = cmb2_get_metabox( $meta_box );
240 1
	return $cmb ? $cmb->get_sanitized_values( $data_to_sanitize ) : false;
241
}
242
243
/**
244
 * Retrieve a metabox form
245
 * @since  2.0.0
246
 * @param  mixed   $meta_box  Metabox config array or Metabox ID
247
 * @param  int     $object_id Object ID
248
 * @param  array   $args      Optional arguments array
249
 * @return string             CMB2 html form markup
250
 */
251
function cmb2_get_metabox_form( $meta_box, $object_id = 0, $args = array() ) {
252
253 1
	$object_id = $object_id ? $object_id : get_the_ID();
254 1
	$cmb       = cmb2_get_metabox( $meta_box, $object_id );
255
256 1
	ob_start();
257
	// Get cmb form
258 1
	cmb2_print_metabox_form( $cmb, $object_id, $args );
259 1
	$form = ob_get_contents();
260 1
	ob_end_clean();
261
262 1
	return apply_filters( 'cmb2_get_metabox_form', $form, $object_id, $cmb );
263
}
264
265
/**
266
 * Display a metabox form & save it on submission
267
 * @since  1.0.0
268
 * @param  mixed   $meta_box  Metabox config array or Metabox ID
269
 * @param  int     $object_id Object ID
270
 * @param  array   $args      Optional arguments array
271
 */
272
function cmb2_print_metabox_form( $meta_box, $object_id = 0, $args = array() ) {
0 ignored issues
show
Coding Style introduced by
cmb2_print_metabox_form uses the super-global variable $_POST 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...
273
274 1
	$object_id = $object_id ? $object_id : get_the_ID();
275 1
	$cmb = cmb2_get_metabox( $meta_box, $object_id );
276
277
	// if passing a metabox ID, and that ID was not found
278 1
	if ( ! $cmb ) {
279
		return;
280
	}
281
282 1
	$args = wp_parse_args( $args, array(
283 1
		'form_format' => '<form class="cmb-form" method="post" id="%1$s" enctype="multipart/form-data" encoding="multipart/form-data"><input type="hidden" name="object_id" value="%2$s">%3$s<input type="submit" name="submit-cmb" value="%4$s" class="button-primary"></form>',
284 1
		'save_button' => esc_html__( 'Save', 'cmb2' ),
285 1
		'object_type' => $cmb->mb_object_type(),
286 1
		'cmb_styles'  => $cmb->prop( 'cmb_styles' ),
287 1
		'enqueue_js'  => $cmb->prop( 'enqueue_js' ),
288 1
	) );
289
290
	// Set object type explicitly (rather than trying to guess from context)
291 1
	$cmb->object_type( $args['object_type'] );
292
293
	// Save the metabox if it's been submitted
294
	// check permissions
295
	// @todo more hardening?
296
	if (
297 1
		$cmb->prop( 'save_fields' )
298
		// check nonce
299 1
		&& isset( $_POST['submit-cmb'], $_POST['object_id'], $_POST[ $cmb->nonce() ] )
300 1
		&& wp_verify_nonce( $_POST[ $cmb->nonce() ], $cmb->nonce() )
301 1
		&& $object_id && $_POST['object_id'] == $object_id
302 1
	) {
303
		$cmb->save_fields( $object_id, $cmb->object_type(), $_POST );
304
	}
305
306
	// Enqueue JS/CSS
307 1
	if ( $args['cmb_styles'] ) {
308 1
		CMB2_hookup::enqueue_cmb_css();
309 1
	}
310
311 1
	if ( $args['enqueue_js'] ) {
312 1
		CMB2_hookup::enqueue_cmb_js();
313 1
	}
314
315 1
	$form_format = apply_filters( 'cmb2_get_metabox_form_format', $args['form_format'], $object_id, $cmb );
316
317 1
	$format_parts = explode( '%3$s', $form_format );
318
319
	// Show cmb form
320 1
	printf( $format_parts[0], $cmb->cmb_id, $object_id );
321 1
	$cmb->show_form();
322
323 1
	if ( isset( $format_parts[1] ) && $format_parts[1] ) {
324 1
		printf( str_ireplace( '%4$s', '%1$s', $format_parts[1] ), $args['save_button'] );
325 1
	}
326
327 1
}
328
329
/**
330
 * Display a metabox form (or optionally return it) & save it on submission
331
 * @since  1.0.0
332
 * @param  mixed   $meta_box  Metabox config array or Metabox ID
333
 * @param  int     $object_id Object ID
334
 * @param  array   $args      Optional arguments array
335
 */
336
function cmb2_metabox_form( $meta_box, $object_id = 0, $args = array() ) {
337
	if ( ! isset( $args['echo'] ) || $args['echo'] ) {
338
		cmb2_print_metabox_form( $meta_box, $object_id, $args );
339
	} else {
340
		return cmb2_get_metabox_form( $meta_box, $object_id, $args );
341
	}
342
}
343
344
if ( ! function_exists( 'date_create_from_format' ) ) {
345
346
	/**
347
	 * Reimplementation of DateTime::createFromFormat for PHP < 5.3. :(
348
	 * Borrowed from http://stackoverflow.com/questions/5399075/php-datetimecreatefromformat-in-5-2
349
	 *
350
	 * @param $date_format
351
	 * @param $date_value
352
	 *
353
	 * @return DateTime
354
	 */
355
	function date_create_from_format( $date_format, $date_value ) {
356
357
		$schedule_format = str_replace(
358
			array( 'M', 'Y', 'm', 'd', 'H', 'i', 'a' ),
359
			array('%b', '%Y', '%m', '%d', '%H', '%M', '%p' ),
360
			$date_format
361
		);
362
363
		/*
364
		 * %Y, %m and %d correspond to date()'s Y m and d.
365
		 * %I corresponds to H, %M to i and %p to a
366
		 */
367
		$parsed_time = strptime( $date_value, $schedule_format );
368
369
		$ymd = sprintf(
370
			/*
371
			 * This is a format string that takes six total decimal
372
			 * arguments, then left-pads them with zeros to either
373
			 * 4 or 2 characters, as needed
374
			 */
375
			'%04d-%02d-%02d %02d:%02d:%02d',
376
			$parsed_time['tm_year'] + 1900,  // This will be "111", so we need to add 1900.
377
			$parsed_time['tm_mon'] + 1,      // This will be the month minus one, so we add one.
378
			$parsed_time['tm_mday'],
379
			$parsed_time['tm_hour'],
380
			$parsed_time['tm_min'],
381
			$parsed_time['tm_sec']
382
		);
383
384
		return new DateTime($ymd);
385
	}
386
}
387