Passed
Push — master ( 40a760...c02299 )
by Chris
17:18 queued 13:08
created

CMB2::save_group_field()   F

Complexity

Conditions 17
Paths 389

Size

Total Lines 79
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 17
eloc 41
c 1
b 0
f 0
nc 389
nop 1
dl 0
loc 79
rs 2.0208

How to fix   Long Method    Complexity   

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
2
/**
3
 * CMB2 - The core metabox object
4
 *
5
 * @category  WordPress_Plugin
6
 * @package   CMB2
7
 * @author    CMB2 team
8
 * @license   GPL-2.0+
9
 * @link      https://cmb2.io
10
 *
11
 * @property-read string $cmb_id
12
 * @property-read array $meta_box
13
 * @property-read array $updated
14
 * @property-read bool  $has_columns
15
 * @property-read array $tax_metaboxes_to_remove
16
 */
17
18
/**
19
 * The main CMB2 object for storing box data/properties.
20
 */
21
class CMB2 extends CMB2_Base {
22
23
	/**
24
	 * The object properties name.
25
	 *
26
	 * @var   string
27
	 * @since 2.2.3
28
	 */
29
	protected $properties_name = 'meta_box';
30
31
	/**
32
	 * Metabox Config array
33
	 *
34
	 * @var   array
35
	 * @since 0.9.0
36
	 */
37
	protected $meta_box = array();
38
39
	/**
40
	 * Type of object registered for metabox. (e.g., post, user, or comment)
41
	 *
42
	 * @var   string
43
	 * @since 1.0.0
44
	 */
45
	protected $mb_object_type = null;
46
47
	/**
48
	 * List of fields that are changed/updated on save
49
	 *
50
	 * @var   array
51
	 * @since 1.1.0
52
	 */
53
	protected $updated = array();
54
55
	/**
56
	 * Metabox Defaults
57
	 *
58
	 * @var   array
59
	 * @since 1.0.1
60
	 */
61
	protected $mb_defaults = array(
62
		'id'                      => '',
63
		'title'                   => '',
64
		// Post type slug, or 'user', 'term', 'comment', or 'options-page'.
65
		'object_types'            => array(),
66
67
		/**
68
		 * The context within the screen where the boxes should display. Available contexts vary
69
		 * from screen to screen. Post edit screen contexts include 'normal', 'side', and 'advanced'.
70
		 *
71
		 * For placement in locations outside of a metabox, other options include:
72
		 * 'form_top', 'before_permalink', 'after_title', 'after_editor'
73
		 *
74
		 * Comments screen contexts include 'normal' and 'side'. Default is 'normal'.
75
		 */
76
		'context'                 => 'normal',
77
		'priority'                => 'high',
78
		'show_names'              => true, // Show field names on the left.
79
		'show_on_cb'              => null, // Callback to determine if metabox should display.
80
		'show_on'                 => array(), // Post IDs or page templates to display this metabox. overrides 'show_on_cb'.
81
		'cmb_styles'              => true, // Include CMB2 stylesheet.
82
		'enqueue_js'              => true, // Include CMB2 JS.
83
		'fields'                  => array(),
84
85
		/**
86
		 * Handles hooking CMB2 forms/metaboxes into the post/attachement/user/options-page screens
87
		 * and handles hooking in and saving those fields.
88
		 */
89
		'hookup'                  => true,
90
		'save_fields'             => true, // Will not save during hookup if false.
91
		'closed'                  => false, // Default metabox to being closed.
92
		'taxonomies'              => array(),
93
		'new_user_section'        => 'add-new-user', // or 'add-existing-user'.
94
		'new_term_section'        => true,
95
		'show_in_rest'            => false,
96
		'classes'                 => null, // Optionally add classes to the CMB2 wrapper.
97
		'classes_cb'              => '', // Optionally add classes to the CMB2 wrapper (via a callback).
98
99
		/*
100
		 * The following parameter is for post alternate-context metaboxes only.
101
		 *
102
		 * To output the fields 'naked' (without a postbox wrapper/style), then
103
		 * add a `'remove_box_wrap' => true` to your metabox registration array.
104
		 */
105
		'remove_box_wrap'         => false,
106
107
		/*
108
		 * The following parameter is any additional arguments passed as $callback_args
109
		 * to add_meta_box, if/when applicable.
110
		 *
111
		 * CMB2 does not use these arguments in the add_meta_box callback, however, these args
112
		 * are parsed for certain special properties, like determining Gutenberg/block-editor
113
		 * compatibility.
114
		 *
115
		 * Examples:
116
		 *
117
		 * - Make sure default editor is used as metabox is not compatible with block editor
118
		 *      [ '__block_editor_compatible_meta_box' => false/true ]
119
		 *
120
		 * - Or declare this box exists for backwards compatibility
121
		 *      [ '__back_compat_meta_box' => false ]
122
		 *
123
		 * More: https://wordpress.org/gutenberg/handbook/extensibility/meta-box/
124
		 */
125
		'mb_callback_args'        => null,
126
127
		/*
128
		 * The following parameters are for options-page metaboxes,
129
		 * and several are passed along to add_menu_page()/add_submenu_page()
130
		 */
131
132
		// 'menu_title'           => null, // Falls back to 'title' (above). Do not define here so we can set a fallback.
133
		'message_cb'              => '', // Optionally define the options-save message (via a callback).
134
		'option_key'              => '', // The actual option key and admin menu page slug.
135
		'parent_slug'             => '', // Used as first param in add_submenu_page().
136
		'capability'              => 'manage_options', // Cap required to view options-page.
137
		'icon_url'                => '', // Menu icon. Only applicable if 'parent_slug' is left empty.
138
		'position'                => null, // Menu position. Only applicable if 'parent_slug' is left empty.
139
140
		'admin_menu_hook'         => 'admin_menu', // Alternately 'network_admin_menu' to add network-level options page.
141
		'display_cb'              => false, // Override the options-page form output (CMB2_Hookup::options_page_output()).
142
		'save_button'             => '', // The text for the options-page save button. Defaults to 'Save'.
143
		'disable_settings_errors' => false, // On settings pages (not options-general.php sub-pages), allows disabling.
144
		'tab_group'               => '', // Tab-group identifier, enables options page tab navigation.
145
		// 'tab_title'            => null, // Falls back to 'title' (above). Do not define here so we can set a fallback.
146
		// 'autoload'             => true, // Defaults to true, the options-page option will be autloaded.
147
	);
148
149
	/**
150
	 * Metabox field objects
151
	 *
152
	 * @var   array
153
	 * @since 2.0.3
154
	 */
155
	protected $fields = array();
156
157
	/**
158
	 * An array of hidden fields to output at the end of the form
159
	 *
160
	 * @var   array
161
	 * @since 2.0.0
162
	 */
163
	protected $hidden_fields = array();
164
165
	/**
166
	 * Array of key => value data for saving. Likely $_POST data.
167
	 *
168
	 * @var   string
169
	 * @since 2.0.0
170
	 */
171
	protected $generated_nonce = '';
172
173
	/**
174
	 * Whether there are fields to be shown in columns. Set in CMB2::add_field().
175
	 *
176
	 * @var   bool
177
	 * @since 2.2.2
178
	 */
179
	protected $has_columns = false;
180
181
	/**
182
	 * If taxonomy field is requesting to remove_default, we store the taxonomy here.
183
	 *
184
	 * @var   array
185
	 * @since 2.2.3
186
	 */
187
	protected $tax_metaboxes_to_remove = array();
188
189
	/**
190
	 * Get started
191
	 *
192
	 * @since 0.4.0
193
	 * @param array   $config    Metabox config array.
194
	 * @param integer $object_id Optional object id.
195
	 */
196
	public function __construct( $config, $object_id = 0 ) {
197
198
		if ( empty( $config['id'] ) ) {
199
			wp_die( esc_html__( 'Metabox configuration is required to have an ID parameter.', 'cmb2' ) );
200
		}
201
202
		$this->cmb_id = $config['id'];
203
		$this->meta_box = wp_parse_args( $config, $this->mb_defaults );
204
		$this->meta_box['fields'] = array();
205
206
		// Ensures object_types is an array.
207
		$this->set_prop( 'object_types', $this->box_types() );
208
		$this->object_id( $object_id );
209
210
		if ( $this->is_options_page_mb() ) {
211
			$this->init_options_mb();
212
		}
213
214
		$this->mb_object_type();
215
216
		if ( ! empty( $config['fields'] ) && is_array( $config['fields'] ) ) {
217
			$this->add_fields( $config['fields'] );
218
		}
219
220
		CMB2_Boxes::add( $this );
221
222
		/**
223
		 * Hook during initiation of CMB2 object
224
		 *
225
		 * The dynamic portion of the hook name, $this->cmb_id, is this meta_box id.
226
		 *
227
		 * @param array $cmb This CMB2 object
228
		 */
229
		do_action( "cmb2_init_{$this->cmb_id}", $this );
230
231
		// Hook in the hookup... how meta.
232
		add_action( "cmb2_init_hookup_{$this->cmb_id}", array( 'CMB2_Hookup', 'maybe_init_and_hookup' ) );
233
234
		// Hook in the rest api functionality.
235
		add_action( "cmb2_init_hookup_{$this->cmb_id}", array( 'CMB2_REST', 'maybe_init_and_hookup' ) );
236
	}
237
238
	/**
239
	 * Loops through and displays fields
240
	 *
241
	 * @since 1.0.0
242
	 * @param int    $object_id   Object ID.
243
	 * @param string $object_type Type of object being saved. (e.g., post, user, or comment).
244
	 *
245
	 * @return CMB2
246
	 */
247
	public function show_form( $object_id = 0, $object_type = '' ) {
248
		$this->render_form_open( $object_id, $object_type );
249
250
		foreach ( $this->prop( 'fields' ) as $field_args ) {
251
			$this->render_field( $field_args );
252
		}
253
254
		return $this->render_form_close( $object_id, $object_type );
255
	}
256
257
	/**
258
	 * Outputs the opening form markup and runs corresponding hooks:
259
	 * 'cmb2_before_form' and "cmb2_before_{$object_type}_form_{$this->cmb_id}"
260
	 *
261
	 * @since  2.2.0
262
	 * @param  integer $object_id   Object ID.
263
	 * @param  string  $object_type Object type.
264
	 *
265
	 * @return CMB2
266
	 */
267
	public function render_form_open( $object_id = 0, $object_type = '' ) {
268
		$object_type = $this->object_type( $object_type );
269
		$object_id = $this->object_id( $object_id );
270
271
		echo "\n<!-- Begin CMB2 Fields -->\n";
272
273
		$this->nonce_field();
274
275
		/**
276
		 * Hook before form table begins
277
		 *
278
		 * @param array  $cmb_id      The current box ID.
279
		 * @param int    $object_id   The ID of the current object.
280
		 * @param string $object_type The type of object you are working with.
281
		 *                            Usually `post` (this applies to all post-types).
282
		 *                            Could also be `comment`, `user` or `options-page`.
283
		 * @param array  $cmb         This CMB2 object.
284
		 */
285
		do_action( 'cmb2_before_form', $this->cmb_id, $object_id, $object_type, $this );
286
287
		/**
288
		 * Hook before form table begins
289
		 *
290
		 * The first dynamic portion of the hook name, $object_type, is the type of object
291
		 * you are working with. Usually `post` (this applies to all post-types).
292
		 * Could also be `comment`, `user` or `options-page`.
293
		 *
294
		 * The second dynamic portion of the hook name, $this->cmb_id, is the meta_box id.
295
		 *
296
		 * @param array  $cmb_id      The current box ID
297
		 * @param int    $object_id   The ID of the current object
298
		 * @param array  $cmb         This CMB2 object
299
		 */
300
		do_action( "cmb2_before_{$object_type}_form_{$this->cmb_id}", $object_id, $this );
301
302
		echo '<div class="', esc_attr( $this->box_classes() ), '"><div id="cmb2-metabox-', sanitize_html_class( $this->cmb_id ), '" class="cmb2-metabox cmb-field-list">';
303
304
		return $this;
305
	}
306
307
	/**
308
	 * Defines the classes for the CMB2 form/wrap.
309
	 *
310
	 * @since  2.0.0
311
	 * @return string Space concatenated list of classes
312
	 */
313
	public function box_classes() {
314
315
		$classes = array( 'cmb2-wrap', 'form-table' );
316
317
		// Use the callback to fetch classes.
318
		if ( $added_classes = $this->get_param_callback_result( 'classes_cb' ) ) {
319
			$added_classes = is_array( $added_classes ) ? $added_classes : array( $added_classes );
320
			$classes = array_merge( $classes, $added_classes );
321
		}
322
323
		if ( $added_classes = $this->prop( 'classes' ) ) {
324
			$added_classes = is_array( $added_classes ) ? $added_classes : array( $added_classes );
325
			$classes = array_merge( $classes, $added_classes );
326
		}
327
328
		/**
329
		 * Add our context classes for non-standard metaboxes.
330
		 *
331
		 * @since 2.2.4
332
		 */
333
		if ( $this->is_alternate_context_box() ) {
334
			$context = array();
335
336
			// Include custom class if requesting no title.
337
			if ( ! $this->prop( 'title' ) && ! $this->prop( 'remove_box_wrap' ) ) {
338
				$context[] = 'cmb2-context-wrap-no-title';
339
			}
340
341
			// Include a generic context wrapper.
342
			$context[] = 'cmb2-context-wrap';
343
344
			// Include a context-type based context wrapper.
345
			$context[] = 'cmb2-context-wrap-' . $this->prop( 'context' );
346
347
			// Include an ID based context wrapper as well.
348
			$context[] = 'cmb2-context-wrap-' . $this->prop( 'id' );
349
350
			// And merge all the classes back into the array.
351
			$classes = array_merge( $classes, $context );
352
		}
353
354
		/**
355
		 * Globally filter box wrap classes
356
		 *
357
		 * @since 2.2.2
358
		 *
359
		 * @param string $classes Array of classes for the cmb2-wrap.
360
		 * @param CMB2   $cmb     This CMB2 object.
361
		 */
362
		$classes = apply_filters( 'cmb2_wrap_classes', $classes, $this );
363
364
		$split = array();
365
		foreach ( array_filter( $classes ) as $class ) {
366
			foreach ( explode( ' ', $class ) as $_class ) {
367
				// Clean up & sanitize.
368
				$split[] = sanitize_html_class( strip_tags( $_class ) );
369
			}
370
		}
371
		$classes = $split;
372
373
		// Remove any duplicates.
374
		$classes = array_unique( $classes );
375
376
		// Make it a string.
377
		return implode( ' ', $classes );
378
	}
379
380
	/**
381
	 * Outputs the closing form markup and runs corresponding hooks:
382
	 * 'cmb2_after_form' and "cmb2_after_{$object_type}_form_{$this->cmb_id}"
383
	 *
384
	 * @since  2.2.0
385
	 * @param  integer $object_id   Object ID.
386
	 * @param  string  $object_type Object type.
387
	 *
388
	 * @return CMB2
389
	 */
390
	public function render_form_close( $object_id = 0, $object_type = '' ) {
391
		$object_type = $this->object_type( $object_type );
392
		$object_id = $this->object_id( $object_id );
393
394
		echo '</div></div>';
395
396
		$this->render_hidden_fields();
397
398
		/**
399
		 * Hook after form form has been rendered
400
		 *
401
		 * The dynamic portion of the hook name, $this->cmb_id, is the meta_box id.
402
		 *
403
		 * The first dynamic portion of the hook name, $object_type, is the type of object
404
		 * you are working with. Usually `post` (this applies to all post-types).
405
		 * Could also be `comment`, `user` or `options-page`.
406
		 *
407
		 * @param int    $object_id   The ID of the current object
408
		 * @param array  $cmb         This CMB2 object
409
		 */
410
		do_action( "cmb2_after_{$object_type}_form_{$this->cmb_id}", $object_id, $this );
411
412
		/**
413
		 * Hook after form form has been rendered
414
		 *
415
		 * @param array  $cmb_id      The current box ID.
416
		 * @param int    $object_id   The ID of the current object.
417
		 * @param string $object_type The type of object you are working with.
418
		 *                            Usually `post` (this applies to all post-types).
419
		 *                            Could also be `comment`, `user` or `options-page`.
420
		 * @param array  $cmb         This CMB2 object.
421
		 */
422
		do_action( 'cmb2_after_form', $this->cmb_id, $object_id, $object_type, $this );
423
424
		echo "\n<!-- End CMB2 Fields -->\n";
425
426
		return $this;
427
	}
428
429
	/**
430
	 * Renders a field based on the field type
431
	 *
432
	 * @since  2.2.0
433
	 * @param  array $field_args A field configuration array.
434
	 * @return mixed CMB2_Field object if successful.
435
	 */
436
	public function render_field( $field_args ) {
437
		$field_args['context'] = $this->prop( 'context' );
438
439
		if ( 'group' === $field_args['type'] ) {
440
441
			if ( ! isset( $field_args['show_names'] ) ) {
442
				$field_args['show_names'] = $this->prop( 'show_names' );
443
			}
444
			$field = $this->render_group( $field_args );
445
446
		} elseif ( 'hidden' === $field_args['type'] && $this->get_field( $field_args )->should_show() ) {
447
			// Save rendering for after the metabox.
448
			$field = $this->add_hidden_field( $field_args );
449
450
		} else {
451
452
			$field_args['show_names'] = $this->prop( 'show_names' );
453
454
			// Render default fields.
455
			$field = $this->get_field( $field_args )->render_field();
456
		}
457
458
		return $field;
459
	}
460
461
	/**
462
	 * Render a group of fields.
463
	 *
464
	 * @param array|CMB2_Field $args Array of field arguments for a group field parent or the group parent field.
465
	 * @return CMB2_Field|null Group field object.
466
	 */
467
	public function render_group( $args ) {
468
		$field_group = false;
469
470
		if ( $args instanceof CMB2_Field ) {
471
			$field_group = 'group' === $args->type() ? $args : false;
472
		} elseif ( isset( $args['id'], $args['fields'] ) && is_array( $args['fields'] ) ) {
473
			$field_group = $this->get_field( $args );
474
		}
475
476
		if ( ! $field_group ) {
477
			return;
478
		}
479
480
		$field_group->render_context = 'edit';
481
		$field_group->peform_param_callback( 'render_row_cb' );
482
483
		return $field_group;
484
	}
485
486
	/**
487
	 * The default callback to render a group of fields.
488
	 *
489
	 * @since  2.2.6
490
	 *
491
	 * @param  array      $field_args  Array of field arguments for the group field parent.
492
	 * @param  CMB2_Field $field_group The CMB2_Field group object.
493
	 *
494
	 * @return CMB2_Field|null Group field object.
495
	 */
496
	public function render_group_callback( $field_args, $field_group ) {
497
498
		// If field is requesting to be conditionally shown.
499
		if ( ! $field_group || ! $field_group->should_show() ) {
500
			return;
501
		}
502
503
		$field_group->index = 0;
504
505
		$field_group->peform_param_callback( 'before_group' );
506
507
		$desc      = $field_group->args( 'description' );
508
		$label     = $field_group->args( 'name' );
509
		$group_val = (array) $field_group->value();
510
511
		echo '<div class="cmb-row cmb-repeat-group-wrap ', esc_attr( $field_group->row_classes() ), '" data-fieldtype="group"><div class="cmb-td"><div data-groupid="', esc_attr( $field_group->id() ), '" id="', esc_attr( $field_group->id() ), '_repeat" ', $this->group_wrap_attributes( $field_group ), '>';
512
513
		if ( $desc || $label ) {
514
			$class = $desc ? ' cmb-group-description' : '';
515
			echo '<div class="cmb-row', $class, '"><div class="cmb-th">';
516
			if ( $label ) {
517
				echo '<h2 class="cmb-group-name">', $label, '</h2>';
518
			}
519
			if ( $desc ) {
520
				echo '<p class="cmb2-metabox-description">', $desc, '</p>';
521
			}
522
			echo '</div></div>';
523
		}
524
525
		if ( ! empty( $group_val ) ) {
526
			foreach ( $group_val as $group_key => $field_id ) {
527
				$this->render_group_row( $field_group );
528
				$field_group->index++;
529
			}
530
		} else {
531
			$this->render_group_row( $field_group );
532
		}
533
534
		if ( $field_group->args( 'repeatable' ) ) {
535
			echo '<div class="cmb-row"><div class="cmb-td"><p class="cmb-add-row"><button type="button" data-selector="', esc_attr( $field_group->id() ), '_repeat" data-grouptitle="', esc_attr( $field_group->options( 'group_title' ) ), '" class="cmb-add-group-row button-secondary">', $field_group->options( 'add_button' ), '</button></p></div></div>';
536
		}
537
538
		echo '</div></div></div>';
539
540
		$field_group->peform_param_callback( 'after_group' );
541
542
		return $field_group;
543
	}
544
545
	/**
546
	 * Get the group wrap attributes, which are passed through a filter.
547
	 *
548
	 * @since  2.2.3
549
	 * @param  CMB2_Field $field_group The group CMB2_Field object.
550
	 * @return string                  The attributes string.
551
	 */
552
	public function group_wrap_attributes( $field_group ) {
553
		$classes = 'cmb-nested cmb-field-list cmb-repeatable-group';
554
		$classes .= $field_group->options( 'sortable' ) ? ' sortable' : ' non-sortable';
555
		$classes .= $field_group->args( 'repeatable' ) ? ' repeatable' : ' non-repeatable';
556
557
		$group_wrap_attributes = array(
558
			'class' => $classes,
559
			'style' => 'width:100%;',
560
		);
561
562
		/**
563
		 * Allow for adding additional HTML attributes to a group wrapper.
564
		 *
565
		 * The attributes will be an array of key => value pairs for each attribute.
566
		 *
567
		 * @since 2.2.2
568
		 *
569
		 * @param string     $group_wrap_attributes Current attributes array.
570
		 * @param CMB2_Field $field_group           The group CMB2_Field object.
571
		 */
572
		$group_wrap_attributes = apply_filters( 'cmb2_group_wrap_attributes', $group_wrap_attributes, $field_group );
573
574
		$atts = array();
575
		foreach ( $group_wrap_attributes as $att => $att_value ) {
576
			if ( ! CMB2_Utils::is_data_attribute( $att ) ) {
577
				$att_value = htmlspecialchars( $att_value );
578
			}
579
580
			$atts[ sanitize_html_class( $att ) ] = sanitize_text_field( $att_value );
581
		}
582
583
		return CMB2_Utils::concat_attrs( $atts );
584
	}
585
586
	/**
587
	 * Render a repeatable group row
588
	 *
589
	 * @since  1.0.2
590
	 * @param  CMB2_Field $field_group     CMB2_Field group field object.
591
	 *
592
	 * @return CMB2
593
	 */
594
	public function render_group_row( $field_group ) {
595
596
		$field_group->peform_param_callback( 'before_group_row' );
597
		$closed_class     = $field_group->options( 'closed' ) ? ' closed' : '';
598
		$confirm_deletion = $field_group->options( 'remove_confirm' );
599
		$confirm_deletion = ! empty( $confirm_deletion ) ? $confirm_deletion : '';
600
601
		echo '
602
		<div id="cmb-group-', $field_group->id(), '-', $field_group->index, '" class="postbox cmb-row cmb-repeatable-grouping', $closed_class, '" data-iterator="', $field_group->index, '">';
603
604
		if ( $field_group->args( 'repeatable' ) ) {
605
			echo '<button type="button" data-selector="', $field_group->id(), '_repeat" data-confirm="', esc_attr( $confirm_deletion ), '" class="dashicons-before dashicons-no-alt cmb-remove-group-row" title="', esc_attr( $field_group->options( 'remove_button' ) ), '"></button>';
606
		}
607
608
			echo '
609
			<div class="cmbhandle" title="' , esc_attr__( 'Click to toggle', 'cmb2' ), '"><br></div>
610
			<h3 class="cmb-group-title cmbhandle-title"><span>', $field_group->replace_hash( $field_group->options( 'group_title' ) ), '</span></h3>
611
612
			<div class="inside cmb-td cmb-nested cmb-field-list">';
613
				// Loop and render repeatable group fields.
614
		foreach ( array_values( $field_group->args( 'fields' ) ) as $field_args ) {
615
			if ( 'hidden' === $field_args['type'] ) {
616
617
				// Save rendering for after the metabox.
618
				$this->add_hidden_field( $field_args, $field_group );
619
620
			} else {
621
622
				$field_args['show_names'] = $field_group->args( 'show_names' );
623
				$field_args['context']    = $field_group->args( 'context' );
624
625
				$this->get_field( $field_args, $field_group )->render_field();
626
			}
627
		}
628
629
		if ( $field_group->args( 'repeatable' ) ) {
630
			echo '
631
					<div class="cmb-row cmb-remove-field-row">
632
						<div class="cmb-remove-row">
633
							<button type="button" data-selector="', $field_group->id(), '_repeat" data-confirm="', esc_attr( $confirm_deletion ), '" class="cmb-remove-group-row cmb-remove-group-row-button alignright button-secondary">', $field_group->options( 'remove_button' ), '</button>
634
						</div>
635
					</div>
636
					';
637
		}
638
			echo '
639
			</div>
640
		</div>
641
		';
642
643
		$field_group->peform_param_callback( 'after_group_row' );
644
645
		return $this;
646
	}
647
648
	/**
649
	 * Add a hidden field to the list of hidden fields to be rendered later.
650
	 *
651
	 * @since 2.0.0
652
	 *
653
	 * @param array           $field_args  Array of field arguments to be passed to CMB2_Field.
654
	 * @param CMB2_Field|null $field_group CMB2_Field group field object.
655
	 * @return CMB2_Field
656
	 */
657
	public function add_hidden_field( $field_args, $field_group = null ) {
658
		if ( isset( $field_args['field_args'] ) ) {
659
			// For back-compatibility.
660
			$field = new CMB2_Field( $field_args );
661
		} else {
662
			$field = $this->get_new_field( $field_args, $field_group );
663
		}
664
665
		$types = new CMB2_Types( $field );
666
667
		if ( $field_group ) {
668
			$types->iterator = $field_group->index;
669
		}
670
671
		$this->hidden_fields[] = $types;
672
673
		return $field;
674
	}
675
676
	/**
677
	 * Loop through and output hidden fields
678
	 *
679
	 * @since  2.0.0
680
	 *
681
	 * @return CMB2
682
	 */
683
	public function render_hidden_fields() {
684
		if ( ! empty( $this->hidden_fields ) ) {
685
			foreach ( $this->hidden_fields as $hidden ) {
686
				$hidden->render();
687
			}
688
		}
689
690
		return $this;
691
	}
692
693
	/**
694
	 * Returns array of sanitized field values (without saving them)
695
	 *
696
	 * @since  2.0.3
697
	 * @param  array $data_to_sanitize Array of field_id => value data for sanitizing (likely $_POST data).
698
	 * @return mixed
699
	 */
700
	public function get_sanitized_values( array $data_to_sanitize ) {
701
		$this->data_to_save = $data_to_sanitize;
702
		$stored_id          = $this->object_id();
703
704
		// We do this So CMB will sanitize our data for us, but not save it.
705
		$this->object_id( '_' );
706
707
		// Ensure temp. data store is empty.
708
		cmb2_options( 0 )->set();
709
710
		// We want to get any taxonomy values back.
711
		add_filter( "cmb2_return_taxonomy_values_{$this->cmb_id}", '__return_true' );
712
713
		// Process/save fields.
714
		$this->process_fields();
715
716
		// Put things back the way they were.
717
		remove_filter( "cmb2_return_taxonomy_values_{$this->cmb_id}", '__return_true' );
718
719
		// Get data from temp. data store.
720
		$sanitized_values = cmb2_options( 0 )->get_options();
721
722
		// Empty out temp. data store again.
723
		cmb2_options( 0 )->set();
724
725
		// Reset the object id.
726
		$this->object_id( $stored_id );
727
728
		return $sanitized_values;
729
	}
730
731
	/**
732
	 * Loops through and saves field data
733
	 *
734
	 * @since  1.0.0
735
	 * @param  int    $object_id    Object ID.
736
	 * @param  string $object_type  Type of object being saved. (e.g., post, user, or comment).
737
	 * @param  array  $data_to_save Array of key => value data for saving. Likely $_POST data.
738
	 *
739
	 * @return CMB2
740
	 */
741
	public function save_fields( $object_id = 0, $object_type = '', $data_to_save = array() ) {
742
743
		// Fall-back to $_POST data.
744
		$this->data_to_save = ! empty( $data_to_save ) ? $data_to_save : $_POST;
745
		$object_id = $this->object_id( $object_id );
746
		$object_type = $this->object_type( $object_type );
747
748
		$this->process_fields();
749
750
		// If options page, save the updated options.
751
		if ( 'options-page' === $object_type ) {
752
			cmb2_options( $object_id )->set();
753
		}
754
755
		return $this->after_save();
756
	}
757
758
	/**
759
	 * Process and save form fields
760
	 *
761
	 * @since  2.0.0
762
	 *
763
	 * @return CMB2
764
	 */
765
	public function process_fields() {
766
767
		$this->pre_process();
768
769
		// Remove the show_on properties so saving works.
770
		$this->prop( 'show_on', array() );
771
772
		// save field ids of those that are updated.
773
		$this->updated = array();
774
775
		foreach ( $this->prop( 'fields' ) as $field_args ) {
776
			$this->process_field( $field_args );
777
		}
778
779
		return $this;
780
	}
781
782
	/**
783
	 * Process and save a field
784
	 *
785
	 * @since  2.0.0
786
	 * @param  array $field_args Array of field arguments.
787
	 *
788
	 * @return CMB2
789
	 */
790
	public function process_field( $field_args ) {
791
792
		switch ( $field_args['type'] ) {
793
794
			case 'group':
795
				if ( $this->save_group( $field_args ) ) {
796
					$this->updated[] = $field_args['id'];
797
				}
798
799
				break;
800
801
			case 'title':
802
				// Don't process title fields.
803
				break;
804
805
			default:
806
				$field = $this->get_new_field( $field_args );
807
808
				if ( $field->save_field_from_data( $this->data_to_save ) ) {
809
					$this->updated[] = $field->id();
810
				}
811
812
				break;
813
		}
814
815
		return $this;
816
	}
817
818
	/**
819
	 * Fires the "cmb2_{$object_type}_process_fields_{$cmb_id}" action hook.
820
	 *
821
	 * @since 2.2.2
822
	 *
823
	 * @return CMB2
824
	 */
825
	public function pre_process() {
826
		$object_type = $this->object_type();
827
828
		/**
829
		 * Fires before fields have been processed/saved.
830
		 *
831
		 * The dynamic portion of the hook name, $object_type, refers to the
832
		 * metabox/form's object type
833
		 *    Usually `post` (this applies to all post-types).
834
		 *    Could also be `comment`, `user` or `options-page`.
835
		 *
836
		 * The dynamic portion of the hook name, $this->cmb_id, is the meta_box id.
837
		 *
838
		 * @param array $cmb       This CMB2 object
839
		 * @param int   $object_id The ID of the current object
840
		 */
841
		do_action( "cmb2_{$object_type}_process_fields_{$this->cmb_id}", $this, $this->object_id() );
842
843
		return $this;
844
	}
845
846
	/**
847
	 * Fires the "cmb2_save_{$object_type}_fields" and
848
	 * "cmb2_save_{$object_type}_fields_{$cmb_id}" action hooks.
849
	 *
850
	 * @since  2.x.x
851
	 *
852
	 * @return CMB2
853
	 */
854
	public function after_save() {
855
		$object_type = $this->object_type();
856
		$object_id   = $this->object_id();
857
858
		/**
859
		 * Fires after all fields have been saved.
860
		 *
861
		 * The dynamic portion of the hook name, $object_type, refers to the metabox/form's object type
862
		 * Usually `post` (this applies to all post-types).
863
		 * Could also be `comment`, `user` or `options-page`.
864
		 *
865
		 * @param int    $object_id   The ID of the current object
866
		 * @param array  $cmb_id      The current box ID
867
		 * @param string $updated     Array of field ids that were updated.
868
		 *                            Will only include field ids that had values change.
869
		 * @param array  $cmb         This CMB2 object
870
		 */
871
		do_action( "cmb2_save_{$object_type}_fields", $object_id, $this->cmb_id, $this->updated, $this );
872
873
		/**
874
		 * Fires after all fields have been saved.
875
		 *
876
		 * The dynamic portion of the hook name, $this->cmb_id, is the meta_box id.
877
		 *
878
		 * The dynamic portion of the hook name, $object_type, refers to the metabox/form's object type
879
		 * Usually `post` (this applies to all post-types).
880
		 * Could also be `comment`, `user` or `options-page`.
881
		 *
882
		 * @param int    $object_id   The ID of the current object
883
		 * @param string $updated     Array of field ids that were updated.
884
		 *                            Will only include field ids that had values change.
885
		 * @param array  $cmb         This CMB2 object
886
		 */
887
		do_action( "cmb2_save_{$object_type}_fields_{$this->cmb_id}", $object_id, $this->updated, $this );
888
889
		return $this;
890
	}
891
892
	/**
893
	 * Save a repeatable group
894
	 *
895
	 * @since  1.x.x
896
	 * @param  array $args Field arguments array.
897
	 * @return mixed        Return of CMB2_Field::update_data().
898
	 */
899
	public function save_group( $args ) {
900
		if ( ! isset( $args['id'], $args['fields'] ) || ! is_array( $args['fields'] ) ) {
901
			return;
902
		}
903
904
		return $this->save_group_field( $this->get_new_field( $args ) );
905
	}
906
907
	/**
908
	 * Save a repeatable group
909
	 *
910
	 * @since  1.x.x
911
	 * @param  CMB2_Field $field_group CMB2_Field group field object.
912
	 * @return mixed                   Return of CMB2_Field::update_data().
913
	 */
914
	public function save_group_field( $field_group ) {
915
		$base_id = $field_group->id();
916
917
		if ( ! isset( $this->data_to_save[ $base_id ] ) ) {
918
			return;
919
		}
920
921
		$old        = $field_group->get_data();
922
		// Check if group field has sanitization_cb.
923
		$group_vals = $field_group->sanitization_cb( $this->data_to_save[ $base_id ] );
924
		$saved      = array();
925
926
		$field_group->index = 0;
927
		$field_group->data_to_save = $this->data_to_save;
928
929
		foreach ( array_values( $field_group->fields() ) as $field_args ) {
930
			if ( 'title' === $field_args['type'] ) {
931
				// Don't process title fields.
932
				continue;
933
			}
934
935
			$field  = $this->get_new_field( $field_args, $field_group );
936
			$sub_id = $field->id( true );
937
			if ( empty( $saved[ $field_group->index ] ) ) {
938
				$saved[ $field_group->index ] = array();
939
			}
940
941
			foreach ( (array) $group_vals as $field_group->index => $post_vals ) {
942
943
				// Get value.
944
				$new_val = isset( $group_vals[ $field_group->index ][ $sub_id ] )
945
					? $group_vals[ $field_group->index ][ $sub_id ]
946
					: false;
947
948
				// Sanitize.
949
				$new_val = $field->sanitization_cb( $new_val );
950
951
				if ( is_array( $new_val ) && $field->args( 'has_supporting_data' ) ) {
952
					if ( $field->args( 'repeatable' ) ) {
953
						$_new_val = array();
954
						foreach ( $new_val as $group_index => $grouped_data ) {
955
							// Add the supporting data to the $saved array stack.
956
							$saved[ $field_group->index ][ $grouped_data['supporting_field_id'] ][] = $grouped_data['supporting_field_value'];
957
							// Reset var to the actual value.
958
							$_new_val[ $group_index ] = $grouped_data['value'];
959
						}
960
						$new_val = $_new_val;
961
					} else {
962
						// Add the supporting data to the $saved array stack.
963
						$saved[ $field_group->index ][ $new_val['supporting_field_id'] ] = $new_val['supporting_field_value'];
964
						// Reset var to the actual value.
965
						$new_val = $new_val['value'];
966
					}
967
				}
968
969
				// Get old value.
970
				$old_val = is_array( $old ) && isset( $old[ $field_group->index ][ $sub_id ] )
971
					? $old[ $field_group->index ][ $sub_id ]
972
					: false;
973
974
				$is_updated = ( ! CMB2_Utils::isempty( $new_val ) && $new_val !== $old_val );
975
				$is_removed = ( CMB2_Utils::isempty( $new_val ) && ! CMB2_Utils::isempty( $old_val ) );
976
977
				// Compare values and add to `$updated` array.
978
				if ( $is_updated || $is_removed ) {
979
					$this->updated[] = $base_id . '::' . $field_group->index . '::' . $sub_id;
980
				}
981
982
				// Add to `$saved` array.
983
				$saved[ $field_group->index ][ $sub_id ] = $new_val;
984
985
			}// End foreach.
986
987
			$saved[ $field_group->index ] = CMB2_Utils::filter_empty( $saved[ $field_group->index ] );
988
		}// End foreach.
989
990
		$saved = CMB2_Utils::filter_empty( $saved );
991
992
		return $field_group->update_data( $saved, true );
993
	}
994
995
	/**
996
	 * Get object id from global space if no id is provided
997
	 *
998
	 * @since  1.0.0
999
	 * @param  integer|string $object_id Object ID.
1000
	 * @return integer|string $object_id Object ID.
1001
	 */
1002
	public function object_id( $object_id = 0 ) {
1003
		global $pagenow;
1004
1005
		if ( $object_id ) {
1006
			$this->object_id = $object_id;
1007
			return $this->object_id;
1008
		}
1009
1010
		if ( $this->object_id ) {
1011
			return $this->object_id;
1012
		}
1013
1014
		// Try to get our object ID from the global space.
1015
		switch ( $this->object_type() ) {
1016
			case 'user':
1017
				$object_id = isset( $_REQUEST['user_id'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['user_id'] ) ) : $object_id;
1018
				$object_id = ! $object_id && 'user-new.php' !== $pagenow && isset( $GLOBALS['user_ID'] ) ? $GLOBALS['user_ID'] : $object_id;
1019
				break;
1020
1021
			case 'comment':
1022
				$object_id = isset( $_REQUEST['c'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['c'] ) ) : $object_id;
1023
				$object_id = ! $object_id && isset( $GLOBALS['comments']->comment_ID ) ? $GLOBALS['comments']->comment_ID : $object_id;
1024
				break;
1025
1026
			case 'term':
1027
				$object_id = isset( $_REQUEST['tag_ID'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['tag_ID'] ) ) : $object_id;
1028
				break;
1029
1030
			case 'options-page':
1031
				$key = $this->doing_options_page();
1032
				if ( ! empty( $key ) ) {
1033
					$object_id = $key;
1034
				}
1035
				break;
1036
1037
			default:
1038
				$object_id = isset( $GLOBALS['post']->ID ) ? $GLOBALS['post']->ID : $object_id;
1039
				$object_id = isset( $_REQUEST['post'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['post'] ) ) : $object_id;
1040
				break;
1041
		}
1042
1043
		// reset to id or 0.
1044
		$this->object_id = $object_id ? $object_id : 0;
1045
1046
		return $this->object_id;
1047
	}
1048
1049
	/**
1050
	 * Sets the $object_type based on metabox settings
1051
	 *
1052
	 * @since  1.0.0
1053
	 * @return string Object type.
1054
	 */
1055
	public function mb_object_type() {
1056
		if ( null !== $this->mb_object_type ) {
1057
			return $this->mb_object_type;
1058
		}
1059
1060
		if ( $this->is_options_page_mb() ) {
1061
			$this->mb_object_type = 'options-page';
1062
			return $this->mb_object_type;
1063
		}
1064
1065
		$registered_types = $this->box_types();
1066
1067
		$type = '';
1068
1069
		// if it's an array of one, extract it.
1070
		if ( 1 === count( $registered_types ) ) {
1071
			$last = end( $registered_types );
1072
			if ( is_string( $last ) ) {
1073
				$type = $last;
1074
			}
1075
		} elseif ( ( $curr_type = $this->current_object_type() ) && in_array( $curr_type, $registered_types, true ) ) {
1076
			$type = $curr_type;
1077
		}
1078
1079
		// Get our object type.
1080
		switch ( $type ) {
1081
1082
			case 'user':
1083
			case 'comment':
1084
			case 'term':
1085
				$this->mb_object_type = $type;
1086
				break;
1087
1088
			default:
1089
				$this->mb_object_type = 'post';
1090
				break;
1091
		}
1092
1093
		return $this->mb_object_type;
1094
	}
1095
1096
	/**
1097
	 * Gets the box 'object_types' array based on box settings.
1098
	 *
1099
	 * @since  2.2.3
1100
	 * @param  array $fallback Fallback value.
1101
	 *
1102
	 * @return array Object types.
1103
	 */
1104
	public function box_types( $fallback = array() ) {
1105
		return CMB2_Utils::ensure_array( $this->prop( 'object_types' ), $fallback );
1106
	}
1107
1108
	/**
1109
	 * Check if given object_type(s) matches any of the registered object types or
1110
	 * taxonomies for this box.
1111
	 *
1112
	 * @since  2.7.0
1113
	 * @param  string|array $object_types The object type(s) to check.
1114
	 * @param  array        $fallback     Fallback object_types value.
1115
	 *
1116
	 * @return bool Whether given object type(s) are registered to this box.
1117
	 */
1118
	public function is_box_type( $object_types = array(), $fallback = array() ) {
1119
		$object_types = (array) $object_types;
1120
		$box_types    = $this->box_types( $fallback );
1121
1122
		if ( in_array( 'term', $box_types, true ) ) {
1123
			$taxonomies = CMB2_Utils::ensure_array( $this->prop( 'taxonomies' ) );
1124
			$box_types = array_merge( $box_types, $taxonomies );
1125
		}
1126
1127
		$found = array_intersect( $object_types, $box_types );
1128
1129
		return ! empty( $found );
1130
	}
1131
1132
	/**
1133
	 * Initates the object types and option key for an options page metabox.
1134
	 *
1135
	 * @since  2.2.5
1136
	 *
1137
	 * @return void
1138
	 */
1139
	public function init_options_mb() {
1140
		$keys  = $this->options_page_keys();
1141
		$types = $this->box_types();
1142
1143
		if ( empty( $keys ) ) {
1144
			$keys = '';
1145
			$types = $this->deinit_options_mb( $types );
1146
		} else {
1147
1148
			// Make sure 'options-page' is one of the object types.
1149
			$types[] = 'options-page';
1150
		}
1151
1152
		// Set/Reset the option_key property.
1153
		$this->set_prop( 'option_key', $keys );
1154
1155
		// Reset the object types.
1156
		$this->set_prop( 'object_types', array_unique( $types ) );
1157
	}
1158
1159
	/**
1160
	 * If object-page initiation failed, remove traces options page setup.
1161
	 *
1162
	 * @since  2.2.5
1163
	 *
1164
	 * @param array $types Array of types.
1165
	 * @return array
1166
	 */
1167
	protected function deinit_options_mb( $types ) {
1168
		if ( isset( $this->meta_box['show_on']['key'] ) && 'options-page' === $this->meta_box['show_on']['key'] ) {
1169
			unset( $this->meta_box['show_on']['key'] );
1170
		}
1171
1172
		if ( array_key_exists( 'options-page', $this->meta_box['show_on'] ) ) {
1173
			unset( $this->meta_box['show_on']['options-page'] );
1174
		}
1175
1176
		$index = array_search( 'options-page', $types );
1177
1178
		if ( false !== $index ) {
1179
			unset( $types[ $index ] );
1180
		}
1181
1182
		return $types;
1183
	}
1184
1185
	/**
1186
	 * Determines if metabox is for an options page
1187
	 *
1188
	 * @since  1.0.1
1189
	 * @return boolean True/False.
1190
	 */
1191
	public function is_options_page_mb() {
1192
		return (
1193
			// 'show_on' values checked for back-compatibility.
1194
			$this->is_old_school_options_page_mb()
1195
			|| in_array( 'options-page', $this->box_types() )
1196
		);
1197
	}
1198
1199
	/**
1200
	 * Determines if metabox uses old-schoold options page config.
1201
	 *
1202
	 * @since  2.2.5
1203
	 * @return boolean True/False.
1204
	 */
1205
	public function is_old_school_options_page_mb() {
1206
		return (
1207
			// 'show_on' values checked for back-compatibility.
1208
			isset( $this->meta_box['show_on']['key'] ) && 'options-page' === $this->meta_box['show_on']['key']
1209
			|| array_key_exists( 'options-page', $this->meta_box['show_on'] )
1210
		);
1211
	}
1212
1213
	/**
1214
	 * Determine if we are on an options page (or saving the options page).
1215
	 *
1216
	 * @since  2.2.5
1217
	 *
1218
	 * @return bool
1219
	 */
1220
	public function doing_options_page() {
1221
		$found_key = false;
1222
		$keys = $this->options_page_keys();
1223
1224
		if ( empty( $keys ) ) {
1225
			return $found_key;
1226
		}
1227
1228
		if ( ! empty( $_GET['page'] ) && in_array( $_GET['page'], $keys ) ) {
1229
			$found_key = $_GET['page'];
1230
		}
1231
1232
		if ( ! empty( $_POST['action'] ) && in_array( $_POST['action'], $keys ) ) {
1233
			$found_key = $_POST['action'];
1234
		}
1235
1236
		return $found_key ? $found_key : false;
1237
	}
1238
1239
	/**
1240
	 * Get the options page key.
1241
	 *
1242
	 * @since  2.2.5
1243
	 * @return string|array
1244
	 */
1245
	public function options_page_keys() {
1246
		$key = '';
1247
		if ( ! $this->is_options_page_mb() ) {
1248
			return $key;
1249
		}
1250
1251
		$values = null;
1252
		if ( ! empty( $this->meta_box['show_on']['value'] ) ) {
1253
			$values = $this->meta_box['show_on']['value'];
1254
		} elseif ( ! empty( $this->meta_box['show_on']['options-page'] ) ) {
1255
			$values = $this->meta_box['show_on']['options-page'];
1256
		} elseif ( $this->prop( 'option_key' ) ) {
1257
			$values = $this->prop( 'option_key' );
1258
		}
1259
1260
		if ( $values ) {
1261
			$key = $values;
1262
		}
1263
1264
		if ( ! is_array( $key ) ) {
1265
			$key = array( $key );
1266
		}
1267
1268
		return $key;
1269
	}
1270
1271
	/**
1272
	 * Returns the object type
1273
	 *
1274
	 * @since  1.0.0
1275
	 * @param string $object_type Type of object being saved. (e.g., post, user, or comment). Optional.
1276
	 * @return string Object type.
1277
	 */
1278
	public function object_type( $object_type = '' ) {
1279
		if ( $object_type ) {
1280
			$this->object_type = $object_type;
1281
			return $this->object_type;
1282
		}
1283
1284
		if ( $this->object_type ) {
1285
			return $this->object_type;
1286
		}
1287
1288
		$this->object_type = $this->current_object_type();
1289
1290
		return $this->object_type;
1291
	}
1292
1293
	/**
1294
	 * Get the object type for the current page, based on the $pagenow global.
1295
	 *
1296
	 * @since  2.2.2
1297
	 * @return string  Page object type name.
1298
	 */
1299
	public function current_object_type() {
1300
		global $pagenow;
1301
		$type = 'post';
1302
1303
		if ( in_array( $pagenow, array( 'user-edit.php', 'profile.php', 'user-new.php' ), true ) ) {
1304
			$type = 'user';
1305
		}
1306
1307
		if ( in_array( $pagenow, array( 'edit-comments.php', 'comment.php' ), true ) ) {
1308
			$type = 'comment';
1309
		}
1310
1311
		if ( in_array( $pagenow, array( 'edit-tags.php', 'term.php' ), true ) ) {
1312
			$type = 'term';
1313
		}
1314
1315
		if ( defined( 'DOING_AJAX' ) && isset( $_POST['action'] ) && 'add-tag' === $_POST['action'] ) {
1316
			$type = 'term';
1317
		}
1318
1319
		if (
1320
			in_array( $pagenow, array( 'admin.php', 'admin-post.php' ), true )
1321
			&& $this->doing_options_page()
1322
		) {
1323
			$type = 'options-page';
1324
		}
1325
1326
		return $type;
1327
	}
1328
1329
	/**
1330
	 * Set metabox property.
1331
	 *
1332
	 * @since  2.2.2
1333
	 * @param  string $property Metabox config property to retrieve.
1334
	 * @param  mixed  $value    Value to set if no value found.
1335
	 * @return mixed            Metabox config property value or false.
1336
	 */
1337
	public function set_prop( $property, $value ) {
1338
		$this->meta_box[ $property ] = $value;
1339
1340
		return $this->prop( $property );
1341
	}
1342
1343
	/**
1344
	 * Get metabox property and optionally set a fallback
1345
	 *
1346
	 * @since  2.0.0
1347
	 * @param  string $property Metabox config property to retrieve.
1348
	 * @param  mixed  $fallback Fallback value to set if no value found.
1349
	 * @return mixed            Metabox config property value or false.
1350
	 */
1351
	public function prop( $property, $fallback = null ) {
1352
		if ( array_key_exists( $property, $this->meta_box ) ) {
1353
			return $this->meta_box[ $property ];
1354
		} elseif ( $fallback ) {
1355
			return $this->meta_box[ $property ] = $fallback;
1356
		}
1357
	}
1358
1359
	/**
1360
	 * Get a field object
1361
	 *
1362
	 * @since  2.0.3
1363
	 * @param  string|array|CMB2_Field $field        Metabox field id or field config array or CMB2_Field object.
1364
	 * @param  CMB2_Field|null         $field_group  (optional) CMB2_Field object (group parent).
1365
	 * @param  bool                    $reset_cached (optional) Reset the internal cache for this field object.
1366
	 *                                               Use sparingly.
1367
	 *
1368
	 * @return CMB2_Field|false                     CMB2_Field object (or false).
1369
	 */
1370
	public function get_field( $field, $field_group = null, $reset_cached = false ) {
1371
		if ( $field instanceof CMB2_Field ) {
1372
			return $field;
1373
		}
1374
1375
		$field_id = is_string( $field ) ? $field : $field['id'];
1376
1377
		$parent_field_id = ! empty( $field_group ) ? $field_group->id() : '';
1378
		$ids = $this->get_field_ids( $field_id, $parent_field_id );
1379
1380
		if ( ! $ids ) {
1381
			return false;
1382
		}
1383
1384
		list( $field_id, $sub_field_id ) = $ids;
1385
1386
		$index = implode( '', $ids ) . ( $field_group ? $field_group->index : '' );
1387
1388
		if ( array_key_exists( $index, $this->fields ) && ! $reset_cached ) {
1389
			return $this->fields[ $index ];
1390
		}
1391
1392
		$this->fields[ $index ] = new CMB2_Field( $this->get_field_args( $field_id, $field, $sub_field_id, $field_group ) );
1393
1394
		return $this->fields[ $index ];
1395
	}
1396
1397
	/**
1398
	 * Handles determining which type of arguments to pass to CMB2_Field
1399
	 *
1400
	 * @since  2.0.7
1401
	 * @param  mixed           $field_id     Field (or group field) ID.
1402
	 * @param  mixed           $field_args   Array of field arguments.
1403
	 * @param  mixed           $sub_field_id Sub field ID (if field_group exists).
1404
	 * @param  CMB2_Field|null $field_group  If a sub-field, will be the parent group CMB2_Field object.
1405
	 * @return array                         Array of CMB2_Field arguments.
1406
	 */
1407
	public function get_field_args( $field_id, $field_args, $sub_field_id, $field_group ) {
1408
1409
		// Check if group is passed and if fields were added in the old-school fields array.
1410
		if ( $field_group && ( $sub_field_id || 0 === $sub_field_id ) ) {
1411
1412
			// Update the fields array w/ any modified properties inherited from the group field.
1413
			$this->meta_box['fields'][ $field_id ]['fields'][ $sub_field_id ] = $field_args;
1414
1415
			return $this->get_default_args( $field_args, $field_group );
1416
		}
1417
1418
		if ( is_array( $field_args ) ) {
1419
			$this->meta_box['fields'][ $field_id ] = array_merge( $field_args, $this->meta_box['fields'][ $field_id ] );
1420
		}
1421
1422
		return $this->get_default_args( $this->meta_box['fields'][ $field_id ] );
1423
	}
1424
1425
	/**
1426
	 * Get default field arguments specific to this CMB2 object.
1427
	 *
1428
	 * @since  2.2.0
1429
	 * @param  array      $field_args  Metabox field config array.
1430
	 * @param  CMB2_Field $field_group (optional) CMB2_Field object (group parent).
1431
	 * @return array                   Array of field arguments.
1432
	 */
1433
	protected function get_default_args( $field_args, $field_group = null ) {
1434
		if ( $field_group ) {
1435
			$args = array(
1436
				'field_args'  => $field_args,
1437
				'group_field' => $field_group,
1438
			);
1439
		} else {
1440
			$args = array(
1441
				'field_args'  => $field_args,
1442
				'object_type' => $this->object_type(),
1443
				'object_id'   => $this->object_id(),
1444
				'cmb_id'      => $this->cmb_id,
1445
			);
1446
		}
1447
1448
		return $args;
1449
	}
1450
1451
	/**
1452
	 * When fields are added in the old-school way, intitate them as they should be
1453
	 *
1454
	 * @since 2.1.0
1455
	 * @param array $fields          Array of fields to add.
1456
	 * @param mixed $parent_field_id Parent field id or null.
1457
	 *
1458
	 * @return CMB2
1459
	 */
1460
	protected function add_fields( $fields, $parent_field_id = null ) {
1461
		foreach ( $fields as $field ) {
1462
1463
			$sub_fields = false;
1464
			if ( array_key_exists( 'fields', $field ) ) {
1465
				$sub_fields = $field['fields'];
1466
				unset( $field['fields'] );
1467
			}
1468
1469
			$field_id = $parent_field_id
1470
				? $this->add_group_field( $parent_field_id, $field )
1471
				: $this->add_field( $field );
1472
1473
			if ( $sub_fields ) {
1474
				$this->add_fields( $sub_fields, $field_id );
1475
			}
1476
		}
1477
1478
		return $this;
1479
	}
1480
1481
	/**
1482
	 * Add a field to the metabox
1483
	 *
1484
	 * @since  2.0.0
1485
	 * @param  array $field    Metabox field config array.
1486
	 * @param  int   $position (optional) Position of metabox. 1 for first, etc.
1487
	 * @return string|false    Field id or false.
1488
	 */
1489
	public function add_field( array $field, $position = 0 ) {
1490
		if ( ! array_key_exists( 'id', $field ) ) {
1491
			return false;
1492
		}
1493
1494
		$this->_add_field_to_array(
1495
			$field,
1496
			$this->meta_box['fields'],
1497
			$position
1498
		);
1499
1500
		return $field['id'];
1501
	}
1502
1503
	/**
1504
	 * Add a field to a group
1505
	 *
1506
	 * @since  2.0.0
1507
	 * @param  string $parent_field_id The field id of the group field to add the field.
1508
	 * @param  array  $field           Metabox field config array.
1509
	 * @param  int    $position        (optional) Position of metabox. 1 for first, etc.
1510
	 * @return mixed                   Array of parent/field ids or false.
1511
	 */
1512
	public function add_group_field( $parent_field_id, array $field, $position = 0 ) {
1513
		if ( ! array_key_exists( $parent_field_id, $this->meta_box['fields'] ) ) {
1514
			return false;
1515
		}
1516
1517
		$parent_field = $this->meta_box['fields'][ $parent_field_id ];
1518
1519
		if ( 'group' !== $parent_field['type'] ) {
1520
			return false;
1521
		}
1522
1523
		if ( ! isset( $parent_field['fields'] ) ) {
1524
			$this->meta_box['fields'][ $parent_field_id ]['fields'] = array();
1525
		}
1526
1527
		$this->_add_field_to_array(
1528
			$field,
1529
			$this->meta_box['fields'][ $parent_field_id ]['fields'],
1530
			$position
1531
		);
1532
1533
		return array( $parent_field_id, $field['id'] );
1534
	}
1535
1536
	/**
1537
	 * Perform some field-type-specific initiation actions.
1538
	 *
1539
	 * @since  2.7.0
1540
	 * @param  array $field Metabox field config array.
1541
	 * @return void
1542
	 */
1543
	protected function field_actions( $field ) {
1544
		switch ( $field['type'] ) {
1545
			case 'file':
1546
			case 'file_list':
1547
1548
				// Initiate attachment JS hooks.
1549
				add_filter( 'wp_prepare_attachment_for_js', array( 'CMB2_Type_File_Base', 'prepare_image_sizes_for_js' ), 10, 3 );
1550
				break;
1551
1552
			case 'oembed':
1553
				// Initiate oembed Ajax hooks.
1554
				cmb2_ajax();
1555
				break;
1556
1557
			case 'group':
1558
				if ( empty( $field['render_row_cb'] ) ) {
1559
					$field['render_row_cb'] = array( $this, 'render_group_callback' );
1560
				}
1561
				break;
1562
			case 'colorpicker':
1563
1564
				// https://github.com/JayWood/CMB2_RGBa_Picker
1565
				// Dequeue the rgba_colorpicker custom field script if it is used,
1566
				// since we now enqueue our own more current version.
1567
				add_action( 'admin_enqueue_scripts', array( 'CMB2_Type_Colorpicker', 'dequeue_rgba_colorpicker_script' ), 99 );
1568
				break;
1569
		}
1570
1571
		if ( isset( $field['column'] ) && false !== $field['column'] ) {
1572
			$field = $this->define_field_column( $field );
1573
		}
1574
1575
		if ( isset( $field['taxonomy'] ) && ! empty( $field['remove_default'] ) ) {
1576
			$this->tax_metaboxes_to_remove[ $field['taxonomy'] ] = $field['taxonomy'];
1577
		}
1578
1579
		return $field;
1580
	}
1581
1582
	/**
1583
	 * Defines a field's column if requesting to be show in admin columns.
1584
	 *
1585
	 * @since  2.2.3
1586
	 * @param  array $field Metabox field config array.
1587
	 * @return array         Modified metabox field config array.
1588
	 */
1589
	protected function define_field_column( array $field ) {
1590
		$this->has_columns = true;
1591
1592
		$column = is_array( $field['column'] ) ? $field['column'] : array();
1593
1594
		$field['column'] = wp_parse_args( $column, array(
1595
			'name'     => isset( $field['name'] ) ? $field['name'] : '',
1596
			'position' => false,
1597
		) );
1598
1599
		return $field;
1600
	}
1601
1602
	/**
1603
	 * Add a field array to a fields array in desired position
1604
	 *
1605
	 * @since 2.0.2
1606
	 * @param array   $field    Metabox field config array.
1607
	 * @param array   $fields   Array (passed by reference) to append the field (array) to.
1608
	 * @param integer $position Optionally specify a position in the array to be inserted.
1609
	 */
1610
	protected function _add_field_to_array( $field, &$fields, $position = 0 ) {
1611
		$field = $this->field_actions( $field );
1612
1613
		if ( $position ) {
1614
			CMB2_Utils::array_insert( $fields, array( $field['id'] => $field ), $position );
1615
		} else {
1616
			$fields[ $field['id'] ] = $field;
1617
		}
1618
	}
1619
1620
	/**
1621
	 * Remove a field from the metabox
1622
	 *
1623
	 * @since 2.0.0
1624
	 * @param  string $field_id        The field id of the field to remove.
1625
	 * @param  string $parent_field_id (optional) The field id of the group field to remove field from.
1626
	 * @return bool                    True if field was removed.
1627
	 */
1628
	public function remove_field( $field_id, $parent_field_id = '' ) {
1629
		$ids = $this->get_field_ids( $field_id, $parent_field_id );
1630
1631
		if ( ! $ids ) {
1632
			return false;
1633
		}
1634
1635
		list( $field_id, $sub_field_id ) = $ids;
1636
1637
		unset( $this->fields[ implode( '', $ids ) ] );
1638
1639
		if ( ! $sub_field_id ) {
1640
			unset( $this->meta_box['fields'][ $field_id ] );
1641
			return true;
1642
		}
1643
1644
		if ( isset( $this->fields[ $field_id ]->args['fields'][ $sub_field_id ] ) ) {
1645
			unset( $this->fields[ $field_id ]->args['fields'][ $sub_field_id ] );
1646
		}
1647
		if ( isset( $this->meta_box['fields'][ $field_id ]['fields'][ $sub_field_id ] ) ) {
1648
			unset( $this->meta_box['fields'][ $field_id ]['fields'][ $sub_field_id ] );
1649
		}
1650
1651
		return true;
1652
	}
1653
1654
	/**
1655
	 * Update or add a property to a field
1656
	 *
1657
	 * @since  2.0.0
1658
	 * @param  string $field_id        Field id.
1659
	 * @param  string $property        Field property to set/update.
1660
	 * @param  mixed  $value           Value to set the field property.
1661
	 * @param  string $parent_field_id (optional) The field id of the group field to remove field from.
1662
	 * @return mixed                   Field id. Strict compare to false, as success can return a falsey value (like 0).
1663
	 */
1664
	public function update_field_property( $field_id, $property, $value, $parent_field_id = '' ) {
1665
		$ids = $this->get_field_ids( $field_id, $parent_field_id );
1666
1667
		if ( ! $ids ) {
1668
			return false;
1669
		}
1670
1671
		list( $field_id, $sub_field_id ) = $ids;
1672
1673
		if ( ! $sub_field_id ) {
1674
			$this->meta_box['fields'][ $field_id ][ $property ] = $value;
1675
			return $field_id;
1676
		}
1677
1678
		$this->meta_box['fields'][ $field_id ]['fields'][ $sub_field_id ][ $property ] = $value;
1679
		return $field_id;
1680
	}
1681
1682
	/**
1683
	 * Check if field ids match a field and return the index/field id
1684
	 *
1685
	 * @since  2.0.2
1686
	 * @param  string $field_id        Field id.
1687
	 * @param  string $parent_field_id (optional) Parent field id.
1688
	 * @return mixed                    Array of field/parent ids, or false.
1689
	 */
1690
	public function get_field_ids( $field_id, $parent_field_id = '' ) {
1691
		$sub_field_id = $parent_field_id ? $field_id : '';
1692
		$field_id     = $parent_field_id ? $parent_field_id : $field_id;
1693
		$fields       =& $this->meta_box['fields'];
1694
1695
		if ( ! array_key_exists( $field_id, $fields ) ) {
1696
			$field_id = $this->search_old_school_array( $field_id, $fields );
1697
		}
1698
1699
		if ( false === $field_id ) {
1700
			return false;
1701
		}
1702
1703
		if ( ! $sub_field_id ) {
1704
			return array( $field_id, $sub_field_id );
1705
		}
1706
1707
		if ( 'group' !== $fields[ $field_id ]['type'] ) {
1708
			return false;
1709
		}
1710
1711
		if ( ! array_key_exists( $sub_field_id, $fields[ $field_id ]['fields'] ) ) {
1712
			$sub_field_id = $this->search_old_school_array( $sub_field_id, $fields[ $field_id ]['fields'] );
1713
		}
1714
1715
		return false === $sub_field_id ? false : array( $field_id, $sub_field_id );
1716
	}
1717
1718
	/**
1719
	 * When using the old array filter, it is unlikely field array indexes will be the field id.
1720
	 *
1721
	 * @since  2.0.2
1722
	 * @param  string $field_id The field id.
1723
	 * @param  array  $fields   Array of fields to search.
1724
	 * @return mixed            Field index or false.
1725
	 */
1726
	public function search_old_school_array( $field_id, $fields ) {
1727
		$ids = wp_list_pluck( $fields, 'id' );
1728
		$index = array_search( $field_id, $ids );
1729
		return false !== $index ? $index : false;
1730
	}
1731
1732
	/**
1733
	 * Handles metabox property callbacks, and passes this $cmb object as property.
1734
	 *
1735
	 * @since 2.2.3
1736
	 * @param  callable $cb                The callback method/function/closure.
1737
	 * @param  mixed    $additional_params Any additoinal parameters which should be passed to the callback.
1738
	 * @return mixed                       Return of the callback function.
1739
	 */
1740
	public function do_callback( $cb, $additional_params = null ) {
1741
		return call_user_func( $cb, $this, $additional_params );
1742
	}
1743
1744
	/**
1745
	 * Generate a unique nonce field for each registered meta_box
1746
	 *
1747
	 * @since  2.0.0
1748
	 * @return void
1749
	 */
1750
	public function nonce_field() {
1751
		wp_nonce_field( $this->nonce(), $this->nonce(), false, true );
1752
	}
1753
1754
	/**
1755
	 * Generate a unique nonce for each registered meta_box
1756
	 *
1757
	 * @since  2.0.0
1758
	 * @return string unique nonce string.
1759
	 */
1760
	public function nonce() {
1761
		if ( ! $this->generated_nonce ) {
1762
			$this->generated_nonce = sanitize_html_class( 'nonce_' . basename( __FILE__ ) . $this->cmb_id );
1763
		}
1764
1765
		return $this->generated_nonce;
1766
	}
1767
1768
	/**
1769
	 * Checks if field-saving updated any fields.
1770
	 *
1771
	 * @since  2.2.5
1772
	 *
1773
	 * @return bool
1774
	 */
1775
	public function was_updated() {
1776
		return ! empty( $this->updated );
1777
	}
1778
1779
	/**
1780
	 * Whether this box is an "alternate context" box. This means the box has a 'context' property defined as:
1781
	 * 'form_top', 'before_permalink', 'after_title', or 'after_editor'.
1782
	 *
1783
	 * @since  2.2.4
1784
	 * @return bool
1785
	 */
1786
	public function is_alternate_context_box() {
1787
		return $this->prop( 'context' ) && in_array( $this->prop( 'context' ), array( 'form_top', 'before_permalink', 'after_title', 'after_editor' ), true );
1788
	}
1789
1790
	/**
1791
	 * Magic getter for our object.
1792
	 *
1793
	 * @param  string $property Object property.
1794
	 * @throws Exception Throws an exception if the field is invalid.
1795
	 * @return mixed
1796
	 */
1797
	public function __get( $property ) {
1798
		switch ( $property ) {
1799
			case 'updated':
1800
			case 'has_columns':
1801
			case 'tax_metaboxes_to_remove':
1802
				return $this->{$property};
1803
			default:
1804
				return parent::__get( $property );
1805
		}
1806
	}
1807
1808
}
1809