home *** CD-ROM | disk | FTP | other *** search
/ HTML Examples / WP.iso / wordpress / wp-includes / rest-api / fields / class-wp-rest-meta-fields.php < prev    next >
Encoding:
PHP Script  |  2017-07-26  |  12.9 KB  |  458 lines

  1. <?php
  2. /**
  3.  * REST API: WP_REST_Meta_Fields class
  4.  *
  5.  * @package WordPress
  6.  * @subpackage REST_API
  7.  * @since 4.7.0
  8.  */
  9.  
  10. /**
  11.  * Core class to manage meta values for an object via the REST API.
  12.  *
  13.  * @since 4.7.0
  14.  */
  15. abstract class WP_REST_Meta_Fields {
  16.  
  17.     /**
  18.      * Retrieves the object meta type.
  19.      *
  20.      * @since 4.7.0
  21.      *
  22.      * @return string One of 'post', 'comment', 'term', 'user', or anything
  23.      *                else supported by `_get_meta_table()`.
  24.      */
  25.     abstract protected function get_meta_type();
  26.  
  27.     /**
  28.      * Retrieves the object type for register_rest_field().
  29.      *
  30.      * @since 4.7.0
  31.      *
  32.      * @return string The REST field type, such as post type name, taxonomy name, 'comment', or `user`.
  33.      */
  34.     abstract protected function get_rest_field_type();
  35.  
  36.     /**
  37.      * Registers the meta field.
  38.      *
  39.      * @since 4.7.0
  40.      *
  41.      * @see register_rest_field()
  42.      */
  43.     public function register_field() {
  44.         register_rest_field( $this->get_rest_field_type(), 'meta', array(
  45.             'get_callback'    => array( $this, 'get_value' ),
  46.             'update_callback' => array( $this, 'update_value' ),
  47.             'schema'          => $this->get_field_schema(),
  48.         ));
  49.     }
  50.  
  51.     /**
  52.      * Retrieves the meta field value.
  53.      *
  54.      * @since 4.7.0
  55.      *
  56.      * @param int             $object_id Object ID to fetch meta for.
  57.      * @param WP_REST_Request $request   Full details about the request.
  58.      * @return WP_Error|object Object containing the meta values by name, otherwise WP_Error object.
  59.      */
  60.     public function get_value( $object_id, $request ) {
  61.         $fields   = $this->get_registered_fields();
  62.         $response = array();
  63.  
  64.         foreach ( $fields as $meta_key => $args ) {
  65.             $name = $args['name'];
  66.             $all_values = get_metadata( $this->get_meta_type(), $object_id, $meta_key, false );
  67.             if ( $args['single'] ) {
  68.                 if ( empty( $all_values ) ) {
  69.                     $value = $args['schema']['default'];
  70.                 } else {
  71.                     $value = $all_values[0];
  72.                 }
  73.                 $value = $this->prepare_value_for_response( $value, $request, $args );
  74.             } else {
  75.                 $value = array();
  76.                 foreach ( $all_values as $row ) {
  77.                     $value[] = $this->prepare_value_for_response( $row, $request, $args );
  78.                 }
  79.             }
  80.  
  81.             $response[ $name ] = $value;
  82.         }
  83.  
  84.         return $response;
  85.     }
  86.  
  87.     /**
  88.      * Prepares a meta value for a response.
  89.      *
  90.      * This is required because some native types cannot be stored correctly
  91.      * in the database, such as booleans. We need to cast back to the relevant
  92.      * type before passing back to JSON.
  93.      *
  94.      * @since 4.7.0
  95.      *
  96.      * @param mixed           $value   Meta value to prepare.
  97.      * @param WP_REST_Request $request Current request object.
  98.      * @param array           $args    Options for the field.
  99.      * @return mixed Prepared value.
  100.      */
  101.     protected function prepare_value_for_response( $value, $request, $args ) {
  102.         if ( ! empty( $args['prepare_callback'] ) ) {
  103.             $value = call_user_func( $args['prepare_callback'], $value, $request, $args );
  104.         }
  105.  
  106.         return $value;
  107.     }
  108.  
  109.     /**
  110.      * Updates meta values.
  111.      *
  112.      * @since 4.7.0
  113.      *
  114.      * @param array           $meta      Array of meta parsed from the request.
  115.      * @param int             $object_id Object ID to fetch meta for.
  116.      * @return WP_Error|null WP_Error if one occurs, null on success.
  117.      */
  118.     public function update_value( $meta, $object_id ) {
  119.         $fields = $this->get_registered_fields();
  120.         foreach ( $fields as $meta_key => $args ) {
  121.             $name = $args['name'];
  122.             if ( ! array_key_exists( $name, $meta ) ) {
  123.                 continue;
  124.             }
  125.  
  126.             /*
  127.              * A null value means reset the field, which is essentially deleting it
  128.              * from the database and then relying on the default value.
  129.              */
  130.             if ( is_null( $meta[ $name ] ) ) {
  131.                 $result = $this->delete_meta_value( $object_id, $meta_key, $name );
  132.                 if ( is_wp_error( $result ) ) {
  133.                     return $result;
  134.                 }
  135.                 continue;
  136.             }
  137.  
  138.             $is_valid = rest_validate_value_from_schema( $meta[ $name ], $args['schema'], 'meta.' . $name );
  139.             if ( is_wp_error( $is_valid ) ) {
  140.                 $is_valid->add_data( array( 'status' => 400 ) );
  141.                 return $is_valid;
  142.             }
  143.  
  144.             $value = rest_sanitize_value_from_schema( $meta[ $name ], $args['schema'] );
  145.  
  146.             if ( $args['single'] ) {
  147.                 $result = $this->update_meta_value( $object_id, $meta_key, $name, $value );
  148.             } else {
  149.                 $result = $this->update_multi_meta_value( $object_id, $meta_key, $name, $value );
  150.             }
  151.  
  152.             if ( is_wp_error( $result ) ) {
  153.                 return $result;
  154.             }
  155.         }
  156.  
  157.         return null;
  158.     }
  159.  
  160.     /**
  161.      * Deletes a meta value for an object.
  162.      *
  163.      * @since 4.7.0
  164.      *
  165.      * @param int    $object_id Object ID the field belongs to.
  166.      * @param string $meta_key  Key for the field.
  167.      * @param string $name      Name for the field that is exposed in the REST API.
  168.      * @return bool|WP_Error True if meta field is deleted, WP_Error otherwise.
  169.      */
  170.     protected function delete_meta_value( $object_id, $meta_key, $name ) {
  171.         $meta_type = $this->get_meta_type();
  172.         if ( ! current_user_can( "delete_{$meta_type}_meta", $object_id, $meta_key ) ) {
  173.             return new WP_Error(
  174.                 'rest_cannot_delete',
  175.                 /* translators: %s: custom field key */
  176.                 sprintf( __( 'Sorry, you are not allowed to edit the %s custom field.' ), $name ),
  177.                 array( 'key' => $name, 'status' => rest_authorization_required_code() )
  178.             );
  179.         }
  180.  
  181.         if ( ! delete_metadata( $meta_type, $object_id, wp_slash( $meta_key ) ) ) {
  182.             return new WP_Error(
  183.                 'rest_meta_database_error',
  184.                 __( 'Could not delete meta value from database.' ),
  185.                 array( 'key' => $name, 'status' => WP_Http::INTERNAL_SERVER_ERROR )
  186.             );
  187.         }
  188.  
  189.         return true;
  190.     }
  191.  
  192.     /**
  193.      * Updates multiple meta values for an object.
  194.      *
  195.      * Alters the list of values in the database to match the list of provided values.
  196.      *
  197.      * @since 4.7.0
  198.      *
  199.      * @param int    $object_id Object ID to update.
  200.      * @param string $meta_key  Key for the custom field.
  201.      * @param string $name      Name for the field that is exposed in the REST API.
  202.      * @param array  $values    List of values to update to.
  203.      * @return bool|WP_Error True if meta fields are updated, WP_Error otherwise.
  204.      */
  205.     protected function update_multi_meta_value( $object_id, $meta_key, $name, $values ) {
  206.         $meta_type = $this->get_meta_type();
  207.         if ( ! current_user_can( "edit_{$meta_type}_meta", $object_id, $meta_key ) ) {
  208.             return new WP_Error(
  209.                 'rest_cannot_update',
  210.                 /* translators: %s: custom field key */
  211.                 sprintf( __( 'Sorry, you are not allowed to edit the %s custom field.' ), $name ),
  212.                 array( 'key' => $name, 'status' => rest_authorization_required_code() )
  213.             );
  214.         }
  215.  
  216.         $current = get_metadata( $meta_type, $object_id, $meta_key, false );
  217.  
  218.         $to_remove = $current;
  219.         $to_add    = $values;
  220.  
  221.         foreach ( $to_add as $add_key => $value ) {
  222.             $remove_keys = array_keys( $to_remove, $value, true );
  223.  
  224.             if ( empty( $remove_keys ) ) {
  225.                 continue;
  226.             }
  227.  
  228.             if ( count( $remove_keys ) > 1 ) {
  229.                 // To remove, we need to remove first, then add, so don't touch.
  230.                 continue;
  231.             }
  232.  
  233.             $remove_key = $remove_keys[0];
  234.  
  235.             unset( $to_remove[ $remove_key ] );
  236.             unset( $to_add[ $add_key ] );
  237.         }
  238.  
  239.         // `delete_metadata` removes _all_ instances of the value, so only call once.
  240.         $to_remove = array_unique( $to_remove );
  241.  
  242.         foreach ( $to_remove as $value ) {
  243.             if ( ! delete_metadata( $meta_type, $object_id, wp_slash( $meta_key ), wp_slash( $value ) ) ) {
  244.                 return new WP_Error(
  245.                     'rest_meta_database_error',
  246.                     __( 'Could not update meta value in database.' ),
  247.                     array( 'key' => $name, 'status' => WP_Http::INTERNAL_SERVER_ERROR )
  248.                 );
  249.             }
  250.         }
  251.  
  252.         foreach ( $to_add as $value ) {
  253.             if ( ! add_metadata( $meta_type, $object_id, wp_slash( $meta_key ), wp_slash( $value ) ) ) {
  254.                 return new WP_Error(
  255.                     'rest_meta_database_error',
  256.                     __( 'Could not update meta value in database.' ),
  257.                     array( 'key' => $name, 'status' => WP_Http::INTERNAL_SERVER_ERROR )
  258.                 );
  259.             }
  260.         }
  261.  
  262.         return true;
  263.     }
  264.  
  265.     /**
  266.      * Updates a meta value for an object.
  267.      *
  268.      * @since 4.7.0
  269.      *
  270.      * @param int    $object_id Object ID to update.
  271.      * @param string $meta_key  Key for the custom field.
  272.      * @param string $name      Name for the field that is exposed in the REST API.
  273.      * @param mixed  $value     Updated value.
  274.      * @return bool|WP_Error True if the meta field was updated, WP_Error otherwise.
  275.      */
  276.     protected function update_meta_value( $object_id, $meta_key, $name, $value ) {
  277.         $meta_type = $this->get_meta_type();
  278.         if ( ! current_user_can(  "edit_{$meta_type}_meta", $object_id, $meta_key ) ) {
  279.             return new WP_Error(
  280.                 'rest_cannot_update',
  281.                 /* translators: %s: custom field key */
  282.                 sprintf( __( 'Sorry, you are not allowed to edit the %s custom field.' ), $name ),
  283.                 array( 'key' => $name, 'status' => rest_authorization_required_code() )
  284.             );
  285.         }
  286.  
  287.         $meta_key   = wp_slash( $meta_key );
  288.         $meta_value = wp_slash( $value );
  289.  
  290.         // Do the exact same check for a duplicate value as in update_metadata() to avoid update_metadata() returning false.
  291.         $old_value = get_metadata( $meta_type, $object_id, $meta_key );
  292.  
  293.         if ( 1 === count( $old_value ) ) {
  294.             if ( $old_value[0] === $meta_value ) {
  295.                 return true;
  296.             }
  297.         }
  298.  
  299.         if ( ! update_metadata( $meta_type, $object_id, $meta_key, $meta_value ) ) {
  300.             return new WP_Error(
  301.                 'rest_meta_database_error',
  302.                 __( 'Could not update meta value in database.' ),
  303.                 array( 'key' => $name, 'status' => WP_Http::INTERNAL_SERVER_ERROR )
  304.             );
  305.         }
  306.  
  307.         return true;
  308.     }
  309.  
  310.     /**
  311.      * Retrieves all the registered meta fields.
  312.      *
  313.      * @since 4.7.0
  314.      *
  315.      * @return array Registered fields.
  316.      */
  317.     protected function get_registered_fields() {
  318.         $registered = array();
  319.  
  320.         foreach ( get_registered_meta_keys( $this->get_meta_type() ) as $name => $args ) {
  321.             if ( empty( $args['show_in_rest'] ) ) {
  322.                 continue;
  323.             }
  324.  
  325.             $rest_args = array();
  326.  
  327.             if ( is_array( $args['show_in_rest'] ) ) {
  328.                 $rest_args = $args['show_in_rest'];
  329.             }
  330.  
  331.             $default_args = array(
  332.                 'name'             => $name,
  333.                 'single'           => $args['single'],
  334.                 'type'             => ! empty( $args['type'] ) ? $args['type'] : null,
  335.                 'schema'           => array(),
  336.                 'prepare_callback' => array( $this, 'prepare_value' ),
  337.             );
  338.  
  339.             $default_schema = array(
  340.                 'type'        => $default_args['type'],
  341.                 'description' => empty( $args['description'] ) ? '' : $args['description'],
  342.                 'default'     => isset( $args['default'] ) ? $args['default'] : null,
  343.             );
  344.  
  345.             $rest_args = array_merge( $default_args, $rest_args );
  346.             $rest_args['schema'] = array_merge( $default_schema, $rest_args['schema'] );
  347.  
  348.             $type = ! empty( $rest_args['type'] ) ? $rest_args['type'] : null;
  349.             $type = ! empty( $rest_args['schema']['type'] ) ? $rest_args['schema']['type'] : $type;
  350.  
  351.             if ( ! in_array( $type, array( 'string', 'boolean', 'integer', 'number' ) ) ) {
  352.                 continue;
  353.             }
  354.  
  355.             if ( empty( $rest_args['single'] ) ) {
  356.                 $rest_args['schema']['items'] = array(
  357.                     'type' => $rest_args['type'],
  358.                 );
  359.                 $rest_args['schema']['type'] = 'array';
  360.             }
  361.  
  362.             $registered[ $name ] = $rest_args;
  363.         }
  364.  
  365.         return $registered;
  366.     }
  367.  
  368.     /**
  369.      * Retrieves the object's meta schema, conforming to JSON Schema.
  370.      *
  371.      * @since 4.7.0
  372.      *
  373.      * @return array Field schema data.
  374.      */
  375.     public function get_field_schema() {
  376.         $fields = $this->get_registered_fields();
  377.  
  378.         $schema = array(
  379.             'description' => __( 'Meta fields.' ),
  380.             'type'        => 'object',
  381.             'context'     => array( 'view', 'edit' ),
  382.             'properties'  => array(),
  383.             'arg_options' => array(
  384.                 'sanitize_callback' => null,
  385.                 'validate_callback' => array( $this, 'check_meta_is_array' ),
  386.             ),
  387.         );
  388.  
  389.         foreach ( $fields as $args ) {
  390.             $schema['properties'][ $args['name'] ] = $args['schema'];
  391.         }
  392.  
  393.         return $schema;
  394.     }
  395.  
  396.     /**
  397.      * Prepares a meta value for output.
  398.      *
  399.      * Default preparation for meta fields. Override by passing the
  400.      * `prepare_callback` in your `show_in_rest` options.
  401.      *
  402.      * @since 4.7.0
  403.      *
  404.      * @param mixed           $value   Meta value from the database.
  405.      * @param WP_REST_Request $request Request object.
  406.      * @param array           $args    REST-specific options for the meta key.
  407.      * @return mixed Value prepared for output. If a non-JsonSerializable object, null.
  408.      */
  409.     public static function prepare_value( $value, $request, $args ) {
  410.         $type = $args['schema']['type'];
  411.  
  412.         // For multi-value fields, check the item type instead.
  413.         if ( 'array' === $type && ! empty( $args['schema']['items']['type'] ) ) {
  414.             $type = $args['schema']['items']['type'];
  415.         }
  416.  
  417.         switch ( $type ) {
  418.             case 'string':
  419.                 $value = (string) $value;
  420.                 break;
  421.             case 'integer':
  422.                 $value = (int) $value;
  423.                 break;
  424.             case 'number':
  425.                 $value = (float) $value;
  426.                 break;
  427.             case 'boolean':
  428.                 $value = (bool) $value;
  429.                 break;
  430.         }
  431.  
  432.         // Don't allow objects to be output.
  433.         if ( is_object( $value ) && ! ( $value instanceof JsonSerializable ) ) {
  434.             return null;
  435.         }
  436.  
  437.         return $value;
  438.     }
  439.  
  440.     /**
  441.      * Check the 'meta' value of a request is an associative array.
  442.      *
  443.      * @since 4.7.0
  444.      *
  445.      * @param  mixed           $value   The meta value submitted in the request.
  446.      * @param  WP_REST_Request $request Full details about the request.
  447.      * @param  string          $param   The parameter name.
  448.      * @return WP_Error|string The meta array, if valid, otherwise an error.
  449.      */
  450.     public function check_meta_is_array( $value, $request, $param ) {
  451.         if ( ! is_array( $value ) ) {
  452.             return false;
  453.         }
  454.  
  455.         return $value;
  456.     }
  457. }
  458.