CMB2 Documentation
  • Package
  • Class
  • Tree
  • Deprecated
  • Todo
  • Hooks
  • Download Docs
  • Github

Packages

  • CMB2
  • Demo
    • CMB2
  • None
  • Tests
    • CMB2

Classes

  • CMB2
  • CMB2_Ajax
  • CMB2_Base
  • CMB2_Bootstrap_2101
  • CMB2_Boxes
  • CMB2_Display_Checkbox
  • CMB2_Display_Colorpicker
  • CMB2_Display_File
  • CMB2_Display_File_List
  • CMB2_Display_Multicheck
  • CMB2_Display_oEmbed
  • CMB2_Display_Select
  • CMB2_Display_Taxonomy_Multicheck
  • CMB2_Display_Taxonomy_Radio
  • CMB2_Display_Text_Date
  • CMB2_Display_Text_Date_Timezone
  • CMB2_Display_Text_Money
  • CMB2_Display_Text_Time
  • CMB2_Display_Text_Url
  • CMB2_Display_Textarea
  • CMB2_Display_Textarea_Code
  • CMB2_Field
  • CMB2_Field_Display
  • CMB2_Hookup
  • CMB2_Hookup_Base
  • CMB2_Integration_Box
  • CMB2_JS
  • CMB2_Option
  • CMB2_Options
  • CMB2_Options_Hookup
  • CMB2_REST
  • CMB2_REST_Controller
  • CMB2_REST_Controller_Boxes
  • CMB2_REST_Controller_Fields
  • CMB2_Sanitize
  • CMB2_Show_Filters
  • CMB2_Type_Base
  • CMB2_Type_Checkbox
  • CMB2_Type_Colorpicker
  • CMB2_Type_Counter_Base
  • CMB2_Type_File
  • CMB2_Type_File_Base
  • CMB2_Type_File_List
  • CMB2_Type_Multi_Base
  • CMB2_Type_Multicheck
  • CMB2_Type_Oembed
  • CMB2_Type_Picker_Base
  • CMB2_Type_Radio
  • CMB2_Type_Select
  • CMB2_Type_Select_Timezone
  • CMB2_Type_Taxonomy_Base
  • CMB2_Type_Taxonomy_Multicheck
  • CMB2_Type_Taxonomy_Multicheck_Hierarchical
  • CMB2_Type_Taxonomy_Radio
  • CMB2_Type_Taxonomy_Radio_Hierarchical
  • CMB2_Type_Taxonomy_Select
  • CMB2_Type_Taxonomy_Select_Hierarchical
  • CMB2_Type_Text
  • CMB2_Type_Text_Date
  • CMB2_Type_Text_Datetime_Timestamp
  • CMB2_Type_Text_Datetime_Timestamp_Timezone
  • CMB2_Type_Text_Time
  • CMB2_Type_Textarea
  • CMB2_Type_Textarea_Code
  • CMB2_Type_Title
  • CMB2_Type_Wysiwyg
  • CMB2_Types
  • CMB2_Utils

Hooks

  • Hook Reference
  1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 
<?php
/**
 * CMB2 objects/fields endpoint for WordPres REST API.
 * Allows access to fields registered to a specific box.
 *
 * @todo  Add better documentation.
 * @todo  Research proper schema.
 *
 * @since 2.2.3
 *
 * @category  WordPress_Plugin
 * @package   CMB2
 * @author    CMB2 team
 * @license   GPL-2.0+
 * @link      https://cmb2.io
 */
class CMB2_REST_Controller_Fields extends CMB2_REST_Controller_Boxes {

    /**
     * Register the routes for the objects of the controller.
     *
     * @since 2.2.3
     */
    public function register_routes() {
        $args = array(
            '_embed' => array(
                'description' => __( 'Includes the box object which the fields are registered to in the response.', 'cmb2' ),
            ),
            '_rendered' => array(
                'description' => __( 'When the \'_rendered\' argument is passed, the renderable field attributes will be returned fully rendered. By default, the names of the callback handers for the renderable attributes will be returned.', 'cmb2' ),
            ),
            'object_id' => array(
                'description' => __( 'To view or modify the field\'s value, the \'object_id\' and \'object_type\' arguments are required.', 'cmb2' ),
            ),
            'object_type' => array(
                'description' => __( 'To view or modify the field\'s value, the \'object_id\' and \'object_type\' arguments are required.', 'cmb2' ),
            ),
        );

        // Returns specific box's fields.
        register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<cmb_id>[\w-]+)/fields/', array(
            array(
                'methods'             => WP_REST_Server::READABLE,
                'permission_callback' => array( $this, 'get_items_permissions_check' ),
                'callback'            => array( $this, 'get_items' ),
                'args'                => $args,
            ),
            'schema' => array( $this, 'get_item_schema' ),
        ) );

        $delete_args = $args;
        $delete_args['object_id']['required'] = true;
        $delete_args['object_type']['required'] = true;

        // Returns specific field data.
        register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<cmb_id>[\w-]+)/fields/(?P<field_id>[\w-]+)', array(
            array(
                'methods'             => WP_REST_Server::READABLE,
                'permission_callback' => array( $this, 'get_item_permissions_check' ),
                'callback'            => array( $this, 'get_item' ),
                'args'                => $args,
            ),
            array(
                'methods'             => WP_REST_Server::EDITABLE,
                'permission_callback' => array( $this, 'update_item_permissions_check' ),
                'callback'            => array( $this, 'update_item' ),
                'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
                'args'                => $args,
            ),
            array(
                'methods'             => WP_REST_Server::DELETABLE,
                'permission_callback' => array( $this, 'delete_item_permissions_check' ),
                'callback'            => array( $this, 'delete_item' ),
                'args'                => $delete_args,
            ),
            'schema' => array( $this, 'get_item_schema' ),
        ) );
    }

    /**
     * Check if a given request has access to get fields.
     * By default, no special permissions needed, but filtering return value.
     *
     * @since 2.2.3
     *
     * @param  WP_REST_Request $request Full data about the request.
     * @return WP_Error|boolean
     */
    public function get_items_permissions_check( $request ) {
        $this->initiate_rest_read_box( $request, 'fields_read' );
        $can_access = true;

        /**
         * By default, no special permissions needed.
         *
         * @since 2.2.3
         *
         * @param bool   $can_access Whether this CMB2 endpoint can be accessed.
         * @param object $controller This CMB2_REST_Controller object.
         */
        return $this->maybe_hook_callback_and_apply_filters( 'cmb2_api_get_fields_permissions_check', $can_access );
    }

    /**
     * Get all public CMB2 box fields.
     *
     * @since 2.2.3
     *
     * @param  WP_REST_Request $request Full data about the request.
     * @return WP_Error|WP_REST_Response
     */
    public function get_items( $request ) {
        if ( ! $this->rest_box ) {
            $this->initiate_rest_read_box( $request, 'fields_read' );
        }

        if ( is_wp_error( $this->rest_box ) ) {
            return $this->rest_box;
        }

        $fields = array();
        foreach ( $this->rest_box->cmb->prop( 'fields', array() ) as $field ) {

            // Make sure this field can be read.
            $this->field = $this->rest_box->field_can_read( $field['id'], true );

            // And make sure current user can view this box.
            if ( $this->field && $this->get_item_permissions_check_filter() ) {
                $fields[ $field['id'] ] = $this->server->response_to_data(
                    $this->prepare_field_response(),
                    isset( $this->request['_embed'] )
                );
            }
        }

        return $this->prepare_item( $fields );
    }

    /**
     * Check if a given request has access to a field.
     * By default, no special permissions needed, but filtering return value.
     *
     * @since 2.2.3
     *
     * @param  WP_REST_Request $request Full details about the request.
     * @return WP_Error|boolean
     */
    public function get_item_permissions_check( $request ) {
        $this->initiate_rest_read_box( $request, 'field_read' );
        if ( ! is_wp_error( $this->rest_box ) ) {
            $this->field = $this->rest_box->field_can_read( $this->request->get_param( 'field_id' ), true );
        }

        return $this->get_item_permissions_check_filter();
    }

    /**
     * Check by filter if a given request has access to a field.
     * By default, no special permissions needed, but filtering return value.
     *
     * @since 2.2.3
     *
     * @param  bool $can_access Whether the current request has access to view the field by default.
     * @return WP_Error|boolean
     */
    public function get_item_permissions_check_filter( $can_access = true ) {
        /**
         * By default, no special permissions needed.
         *
         * @since 2.2.3
         *
         * @param bool   $can_access Whether this CMB2 endpoint can be accessed.
         * @param object $controller This CMB2_REST_Controller object.
         */
        return $this->maybe_hook_callback_and_apply_filters( 'cmb2_api_get_field_permissions_check', $can_access );
    }

    /**
     * Get one CMB2 field from the collection.
     *
     * @since 2.2.3
     *
     * @param  WP_REST_Request $request Full data about the request.
     * @return WP_Error|WP_REST_Response
     */
    public function get_item( $request ) {
        $this->initiate_rest_read_box( $request, 'field_read' );

        if ( is_wp_error( $this->rest_box ) ) {
            return $this->rest_box;
        }

        return $this->prepare_read_field( $this->request->get_param( 'field_id' ) );
    }

    /**
     * Check if a given request has access to update a field value.
     * By default, requires 'edit_others_posts' capability, but filtering return value.
     *
     * @since 2.2.3
     *
     * @param  WP_REST_Request $request Full details about the request.
     * @return WP_Error|boolean
     */
    public function update_item_permissions_check( $request ) {
        $this->initiate_rest_read_box( $request, 'field_value_update' );
        if ( ! is_wp_error( $this->rest_box ) ) {
            $this->field = $this->rest_box->field_can_edit( $this->request->get_param( 'field_id' ), true );
        }

        $can_update = current_user_can( 'edit_others_posts' );

        /**
         * By default, 'edit_others_posts' is required capability.
         *
         * @since 2.2.3
         *
         * @param bool   $can_update Whether this CMB2 endpoint can be accessed.
         * @param object $controller This CMB2_REST_Controller object.
         */
        return $this->maybe_hook_callback_and_apply_filters( 'cmb2_api_update_field_value_permissions_check', $can_update );
    }

    /**
     * Update CMB2 field value.
     *
     * @since 2.2.3
     *
     * @param  WP_REST_Request $request Full data about the request.
     * @return WP_Error|WP_REST_Response
     */
    public function update_item( $request ) {
        $this->initiate_rest_read_box( $request, 'field_value_update' );

        if ( ! $this->request['value'] ) {
            return new WP_Error( 'cmb2_rest_update_field_error', __( 'CMB2 Field value cannot be updated without the value parameter specified.', 'cmb2' ), array(
                'status' => 400,
            ) );
        }

        return $this->modify_field_value( 'updated' );
    }

    /**
     * Check if a given request has access to delete a field value.
     * By default, requires 'delete_others_posts' capability, but filtering return value.
     *
     * @since 2.2.3
     *
     * @param  WP_REST_Request $request Full details about the request.
     * @return WP_Error|boolean
     */
    public function delete_item_permissions_check( $request ) {
        $this->initiate_rest_read_box( $request, 'field_value_delete' );
        if ( ! is_wp_error( $this->rest_box ) ) {
            $this->field = $this->rest_box->field_can_edit( $this->request->get_param( 'field_id' ), true );
        }

        $can_delete = current_user_can( 'delete_others_posts' );

        /**
         * By default, 'delete_others_posts' is required capability.
         *
         * @since 2.2.3
         *
         * @param bool   $can_delete Whether this CMB2 endpoint can be accessed.
         * @param object $controller This CMB2_REST_Controller object.
         */
        return $this->maybe_hook_callback_and_apply_filters( 'cmb2_api_delete_field_value_permissions_check', $can_delete );
    }

    /**
     * Delete CMB2 field value.
     *
     * @since 2.2.3
     *
     * @param  WP_REST_Request $request Full data about the request.
     * @return WP_Error|WP_REST_Response
     */
    public function delete_item( $request ) {
        $this->initiate_rest_read_box( $request, 'field_value_delete' );

        return $this->modify_field_value( 'deleted' );
    }

    /**
     * Modify CMB2 field value.
     *
     * @since 2.2.3
     *
     * @param  string $activity The modification activity (updated or deleted).
     * @return WP_Error|WP_REST_Response
     */
    public function modify_field_value( $activity ) {

        if ( ! $this->request['object_id'] || ! $this->request['object_type'] ) {
            return new WP_Error( 'cmb2_rest_modify_field_value_error', __( 'CMB2 Field value cannot be modified without the object_id and object_type parameters specified.', 'cmb2' ), array(
                'status' => 400,
            ) );
        }

        if ( is_wp_error( $this->rest_box ) ) {
            return $this->rest_box;
        }

        $this->field = $this->rest_box->field_can_edit(
            $this->field ? $this->field : $this->request->get_param( 'field_id' ),
            true
        );

        if ( ! $this->field ) {
            return new WP_Error( 'cmb2_rest_no_field_by_id_error', __( 'No field found by that id.', 'cmb2' ), array(
                'status' => 403,
            ) );
        }

        $this->field->args[ "value_{$activity}" ] = (bool) 'deleted' === $activity
            ? $this->field->remove_data()
            : $this->field->save_field( $this->request['value'] );

        // If options page, save the $activity options
        if ( 'options-page' == $this->request['object_type'] ) {
            $this->field->args[ "value_{$activity}" ] = cmb2_options( $this->request['object_id'] )->set();
        }

        return $this->prepare_read_field( $this->field );
    }

    /**
     * Get a response object for a specific field ID.
     *
     * @since 2.2.3
     *
     * @param  string\CMB2_Field Field id or Field object.
     * @return WP_Error|WP_REST_Response
     */
    public function prepare_read_field( $field ) {
        $this->field = $this->rest_box->field_can_read( $field, true );

        if ( ! $this->field ) {
            return new WP_Error( 'cmb2_rest_no_field_by_id_error', __( 'No field found by that id.', 'cmb2' ), array(
                'status' => 403,
            ) );
        }

        return $this->prepare_item( $this->prepare_field_response() );
    }

    /**
     * Get a specific field response.
     *
     * @since 2.2.3
     *
     * @param  CMB2_Field Field object.
     * @return array      Response array.
     */
    public function prepare_field_response() {
        $field_data = $this->prepare_field_data( $this->field );
        $response = rest_ensure_response( $field_data );

        $response->add_links( $this->prepare_links( $this->field ) );

        return $response;
    }

    /**
     * Prepare the field data array for JSON.
     *
     * @since  2.2.3
     *
     * @param  CMB2_Field $field field object.
     *
     * @return array             Array of field data.
     */
    protected function prepare_field_data( CMB2_Field $field ) {
        $field_data = array();
        $params_to_ignore = array( 'show_in_rest', 'options' );
        $params_to_rename = array(
            'label_cb' => 'label',
            'options_cb' => 'options',
        );

        // Run this first so the js_dependencies arg is populated.
        $rendered = ( $cb = $field->maybe_callback( 'render_row_cb' ) )
            // Ok, callback is good, let's run it.
            ? $this->get_cb_results( $cb, $field->args(), $field )
            : false;

        $field_args = $field->args();

        foreach ( $field_args as $key => $value ) {
            if ( in_array( $key, $params_to_ignore, true ) ) {
                continue;
            }

            if ( 'options_cb' === $key ) {
                $value = $field->options();
            } elseif ( in_array( $key, CMB2_Field::$callable_fields, true ) ) {

                if ( isset( $this->request['_rendered'] ) ) {
                    $value = $key === 'render_row_cb' ? $rendered : $field->get_param_callback_result( $key );
                } elseif ( is_array( $value ) ) {
                    // We need to rewrite callbacks as string as they will cause
                    // JSON recursion errors.
                    $class = is_string( $value[0] ) ? $value[0] : get_class( $value[0] );
                    $value = $class . '::' . $value[1];
                }
            }

            $key = isset( $params_to_rename[ $key ] ) ? $params_to_rename[ $key ] : $key;

            if ( empty( $value ) || is_scalar( $value ) || is_array( $value ) ) {
                $field_data[ $key ] = $value;
            } else {
                $field_data[ $key ] = sprintf( __( 'Value Error for %s', 'cmb2' ), $key );
            }
        }

        if ( $field->args( 'has_supporting_data' ) ) {
            $field_data = $this->get_supporting_data( $field_data, $field );
        }

        if ( $this->request['object_id'] && $this->request['object_type'] ) {
            $field_data['value'] = $field->get_rest_value();
        }

        return $field_data;
    }

    /**
     * Gets field supporting data (field id and value).
     *
     * @since  2.7.0
     *
     * @param  CMB2_Field $field      Field object.
     * @param  array      $field_data Array of field data.
     *
     * @return array                  Array of field data.
     */
    public function get_supporting_data( $field_data, $field ) {

        // Reset placement of this property.
        unset( $field_data['has_supporting_data'] );
        $field_data['has_supporting_data'] = true;

        $field = $field->get_supporting_field();
        $field_data['supporting_data'] = array(
            'id' => $field->_id( '', false ),
        );

        if ( $this->request['object_id'] && $this->request['object_type'] ) {
            $field_data['supporting_data']['value'] = $field->get_rest_value();
        }

        return $field_data;
    }

    /**
     * Return an array of contextual links for field/fields.
     *
     * @since  2.2.3
     *
     * @param  CMB2_Field $field Field object to build links from.
     *
     * @return array             Array of links
     */
    protected function prepare_links( $field ) {
        $boxbase      = $this->namespace_base . '/' . $this->rest_box->cmb->cmb_id;
        $query_string = $this->get_query_string();

        $links = array(
            'self' => array(
                'href' => rest_url( trailingslashit( $boxbase ) . 'fields/' . $field->_id( '', false ) . $query_string ),
            ),
            'collection' => array(
                'href' => rest_url( trailingslashit( $boxbase ) . 'fields' . $query_string ),
            ),
            'up' => array(
                'embeddable' => true,
                'href' => rest_url( $boxbase . $query_string ),
            ),
        );

        return $links;
    }

    /**
     * Checks if the CMB2 box or field has any registered callback parameters for the given filter.
     *
     * The registered handlers will have a property name which matches the filter, except:
     * - The 'cmb2_api' prefix will be removed
     * - A '_cb' suffix will be added (to stay inline with other '*_cb' parameters).
     *
     * @since  2.2.3
     *
     * @param  string $filter      The filter name.
     * @param  bool   $default_val The default filter value.
     *
     * @return bool                The possibly-modified filter value (if the _cb param is a non-callable).
     */
    public function maybe_hook_registered_callback( $filter, $default_val ) {
        $default_val = parent::maybe_hook_registered_callback( $filter, $default_val );

        if ( $this->field ) {

            // Hook field specific filter callbacks.
            $val = $this->field->maybe_hook_parameter( $filter, $default_val );
            if ( null !== $val ) {
                $default_val = $val;
            }
        }

        return $default_val;
    }

    /**
     * Unhooks any CMB2 box or field registered callback parameters for the given filter.
     *
     * @since  2.2.3
     *
     * @param  string $filter The filter name.
     *
     * @return void
     */
    public function maybe_unhook_registered_callback( $filter ) {
        parent::maybe_unhook_registered_callback( $filter );

        if ( $this->field ) {
            // Unhook field specific filter callbacks.
            $this->field->maybe_hook_parameter( $filter, null, 'remove_filter' );
        }
    }

}
CMB2 Documentation API documentation generated by ApiGen