class-wp-rest-comments-controller.php 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710
  1. <?php
  2. /**
  3. * REST API: WP_REST_Comments_Controller class
  4. *
  5. * @package WordPress
  6. * @subpackage REST_API
  7. * @since 4.7.0
  8. */
  9. /**
  10. * Core controller used to access comments via the REST API.
  11. *
  12. * @since 4.7.0
  13. *
  14. * @see WP_REST_Controller
  15. */
  16. class WP_REST_Comments_Controller extends WP_REST_Controller {
  17. /**
  18. * Instance of a comment meta fields object.
  19. *
  20. * @since 4.7.0
  21. * @var WP_REST_Comment_Meta_Fields
  22. */
  23. protected $meta;
  24. /**
  25. * Constructor.
  26. *
  27. * @since 4.7.0
  28. */
  29. public function __construct() {
  30. $this->namespace = 'wp/v2';
  31. $this->rest_base = 'comments';
  32. $this->meta = new WP_REST_Comment_Meta_Fields();
  33. }
  34. /**
  35. * Registers the routes for the objects of the controller.
  36. *
  37. * @since 4.7.0
  38. */
  39. public function register_routes() {
  40. register_rest_route(
  41. $this->namespace,
  42. '/' . $this->rest_base,
  43. array(
  44. array(
  45. 'methods' => WP_REST_Server::READABLE,
  46. 'callback' => array( $this, 'get_items' ),
  47. 'permission_callback' => array( $this, 'get_items_permissions_check' ),
  48. 'args' => $this->get_collection_params(),
  49. ),
  50. array(
  51. 'methods' => WP_REST_Server::CREATABLE,
  52. 'callback' => array( $this, 'create_item' ),
  53. 'permission_callback' => array( $this, 'create_item_permissions_check' ),
  54. 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ),
  55. ),
  56. 'schema' => array( $this, 'get_public_item_schema' ),
  57. )
  58. );
  59. register_rest_route(
  60. $this->namespace,
  61. '/' . $this->rest_base . '/(?P<id>[\d]+)',
  62. array(
  63. 'args' => array(
  64. 'id' => array(
  65. 'description' => __( 'Unique identifier for the object.' ),
  66. 'type' => 'integer',
  67. ),
  68. ),
  69. array(
  70. 'methods' => WP_REST_Server::READABLE,
  71. 'callback' => array( $this, 'get_item' ),
  72. 'permission_callback' => array( $this, 'get_item_permissions_check' ),
  73. 'args' => array(
  74. 'context' => $this->get_context_param( array( 'default' => 'view' ) ),
  75. 'password' => array(
  76. 'description' => __( 'The password for the parent post of the comment (if the post is password protected).' ),
  77. 'type' => 'string',
  78. ),
  79. ),
  80. ),
  81. array(
  82. 'methods' => WP_REST_Server::EDITABLE,
  83. 'callback' => array( $this, 'update_item' ),
  84. 'permission_callback' => array( $this, 'update_item_permissions_check' ),
  85. 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
  86. ),
  87. array(
  88. 'methods' => WP_REST_Server::DELETABLE,
  89. 'callback' => array( $this, 'delete_item' ),
  90. 'permission_callback' => array( $this, 'delete_item_permissions_check' ),
  91. 'args' => array(
  92. 'force' => array(
  93. 'type' => 'boolean',
  94. 'default' => false,
  95. 'description' => __( 'Whether to bypass trash and force deletion.' ),
  96. ),
  97. 'password' => array(
  98. 'description' => __( 'The password for the parent post of the comment (if the post is password protected).' ),
  99. 'type' => 'string',
  100. ),
  101. ),
  102. ),
  103. 'schema' => array( $this, 'get_public_item_schema' ),
  104. )
  105. );
  106. }
  107. /**
  108. * Checks if a given request has access to read comments.
  109. *
  110. * @since 4.7.0
  111. *
  112. * @param WP_REST_Request $request Full details about the request.
  113. * @return WP_Error|bool True if the request has read access, error object otherwise.
  114. */
  115. public function get_items_permissions_check( $request ) {
  116. if ( ! empty( $request['post'] ) ) {
  117. foreach ( (array) $request['post'] as $post_id ) {
  118. $post = get_post( $post_id );
  119. if ( ! empty( $post_id ) && $post && ! $this->check_read_post_permission( $post, $request ) ) {
  120. return new WP_Error( 'rest_cannot_read_post', __( 'Sorry, you are not allowed to read the post for this comment.' ), array( 'status' => rest_authorization_required_code() ) );
  121. } elseif ( 0 === $post_id && ! current_user_can( 'moderate_comments' ) ) {
  122. return new WP_Error( 'rest_cannot_read', __( 'Sorry, you are not allowed to read comments without a post.' ), array( 'status' => rest_authorization_required_code() ) );
  123. }
  124. }
  125. }
  126. if ( ! empty( $request['context'] ) && 'edit' === $request['context'] && ! current_user_can( 'moderate_comments' ) ) {
  127. return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to edit comments.' ), array( 'status' => rest_authorization_required_code() ) );
  128. }
  129. if ( ! current_user_can( 'edit_posts' ) ) {
  130. $protected_params = array( 'author', 'author_exclude', 'author_email', 'type', 'status' );
  131. $forbidden_params = array();
  132. foreach ( $protected_params as $param ) {
  133. if ( 'status' === $param ) {
  134. if ( 'approve' !== $request[ $param ] ) {
  135. $forbidden_params[] = $param;
  136. }
  137. } elseif ( 'type' === $param ) {
  138. if ( 'comment' !== $request[ $param ] ) {
  139. $forbidden_params[] = $param;
  140. }
  141. } elseif ( ! empty( $request[ $param ] ) ) {
  142. $forbidden_params[] = $param;
  143. }
  144. }
  145. if ( ! empty( $forbidden_params ) ) {
  146. return new WP_Error(
  147. 'rest_forbidden_param',
  148. /* translators: %s: List of forbidden parameters. */
  149. sprintf( __( 'Query parameter not permitted: %s' ), implode( ', ', $forbidden_params ) ),
  150. array( 'status' => rest_authorization_required_code() )
  151. );
  152. }
  153. }
  154. return true;
  155. }
  156. /**
  157. * Retrieves a list of comment items.
  158. *
  159. * @since 4.7.0
  160. *
  161. * @param WP_REST_Request $request Full details about the request.
  162. * @return WP_Error|WP_REST_Response Response object on success, or error object on failure.
  163. */
  164. public function get_items( $request ) {
  165. // Retrieve the list of registered collection query parameters.
  166. $registered = $this->get_collection_params();
  167. /*
  168. * This array defines mappings between public API query parameters whose
  169. * values are accepted as-passed, and their internal WP_Query parameter
  170. * name equivalents (some are the same). Only values which are also
  171. * present in $registered will be set.
  172. */
  173. $parameter_mappings = array(
  174. 'author' => 'author__in',
  175. 'author_email' => 'author_email',
  176. 'author_exclude' => 'author__not_in',
  177. 'exclude' => 'comment__not_in',
  178. 'include' => 'comment__in',
  179. 'offset' => 'offset',
  180. 'order' => 'order',
  181. 'parent' => 'parent__in',
  182. 'parent_exclude' => 'parent__not_in',
  183. 'per_page' => 'number',
  184. 'post' => 'post__in',
  185. 'search' => 'search',
  186. 'status' => 'status',
  187. 'type' => 'type',
  188. );
  189. $prepared_args = array();
  190. /*
  191. * For each known parameter which is both registered and present in the request,
  192. * set the parameter's value on the query $prepared_args.
  193. */
  194. foreach ( $parameter_mappings as $api_param => $wp_param ) {
  195. if ( isset( $registered[ $api_param ], $request[ $api_param ] ) ) {
  196. $prepared_args[ $wp_param ] = $request[ $api_param ];
  197. }
  198. }
  199. // Ensure certain parameter values default to empty strings.
  200. foreach ( array( 'author_email', 'search' ) as $param ) {
  201. if ( ! isset( $prepared_args[ $param ] ) ) {
  202. $prepared_args[ $param ] = '';
  203. }
  204. }
  205. if ( isset( $registered['orderby'] ) ) {
  206. $prepared_args['orderby'] = $this->normalize_query_param( $request['orderby'] );
  207. }
  208. $prepared_args['no_found_rows'] = false;
  209. $prepared_args['date_query'] = array();
  210. // Set before into date query. Date query must be specified as an array of an array.
  211. if ( isset( $registered['before'], $request['before'] ) ) {
  212. $prepared_args['date_query'][0]['before'] = $request['before'];
  213. }
  214. // Set after into date query. Date query must be specified as an array of an array.
  215. if ( isset( $registered['after'], $request['after'] ) ) {
  216. $prepared_args['date_query'][0]['after'] = $request['after'];
  217. }
  218. if ( isset( $registered['page'] ) && empty( $request['offset'] ) ) {
  219. $prepared_args['offset'] = $prepared_args['number'] * ( absint( $request['page'] ) - 1 );
  220. }
  221. /**
  222. * Filters arguments, before passing to WP_Comment_Query, when querying comments via the REST API.
  223. *
  224. * @since 4.7.0
  225. *
  226. * @link https://developer.wordpress.org/reference/classes/wp_comment_query/
  227. *
  228. * @param array $prepared_args Array of arguments for WP_Comment_Query.
  229. * @param WP_REST_Request $request The current request.
  230. */
  231. $prepared_args = apply_filters( 'rest_comment_query', $prepared_args, $request );
  232. $query = new WP_Comment_Query;
  233. $query_result = $query->query( $prepared_args );
  234. $comments = array();
  235. foreach ( $query_result as $comment ) {
  236. if ( ! $this->check_read_permission( $comment, $request ) ) {
  237. continue;
  238. }
  239. $data = $this->prepare_item_for_response( $comment, $request );
  240. $comments[] = $this->prepare_response_for_collection( $data );
  241. }
  242. $total_comments = (int) $query->found_comments;
  243. $max_pages = (int) $query->max_num_pages;
  244. if ( $total_comments < 1 ) {
  245. // Out-of-bounds, run the query again without LIMIT for total count.
  246. unset( $prepared_args['number'], $prepared_args['offset'] );
  247. $query = new WP_Comment_Query;
  248. $prepared_args['count'] = true;
  249. $total_comments = $query->query( $prepared_args );
  250. $max_pages = ceil( $total_comments / $request['per_page'] );
  251. }
  252. $response = rest_ensure_response( $comments );
  253. $response->header( 'X-WP-Total', $total_comments );
  254. $response->header( 'X-WP-TotalPages', $max_pages );
  255. $base = add_query_arg( urlencode_deep( $request->get_query_params() ), rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ) );
  256. if ( $request['page'] > 1 ) {
  257. $prev_page = $request['page'] - 1;
  258. if ( $prev_page > $max_pages ) {
  259. $prev_page = $max_pages;
  260. }
  261. $prev_link = add_query_arg( 'page', $prev_page, $base );
  262. $response->link_header( 'prev', $prev_link );
  263. }
  264. if ( $max_pages > $request['page'] ) {
  265. $next_page = $request['page'] + 1;
  266. $next_link = add_query_arg( 'page', $next_page, $base );
  267. $response->link_header( 'next', $next_link );
  268. }
  269. return $response;
  270. }
  271. /**
  272. * Get the comment, if the ID is valid.
  273. *
  274. * @since 4.7.2
  275. *
  276. * @param int $id Supplied ID.
  277. * @return WP_Comment|WP_Error Comment object if ID is valid, WP_Error otherwise.
  278. */
  279. protected function get_comment( $id ) {
  280. $error = new WP_Error( 'rest_comment_invalid_id', __( 'Invalid comment ID.' ), array( 'status' => 404 ) );
  281. if ( (int) $id <= 0 ) {
  282. return $error;
  283. }
  284. $id = (int) $id;
  285. $comment = get_comment( $id );
  286. if ( empty( $comment ) ) {
  287. return $error;
  288. }
  289. if ( ! empty( $comment->comment_post_ID ) ) {
  290. $post = get_post( (int) $comment->comment_post_ID );
  291. if ( empty( $post ) ) {
  292. return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
  293. }
  294. }
  295. return $comment;
  296. }
  297. /**
  298. * Checks if a given request has access to read the comment.
  299. *
  300. * @since 4.7.0
  301. *
  302. * @param WP_REST_Request $request Full details about the request.
  303. * @return WP_Error|bool True if the request has read access for the item, error object otherwise.
  304. */
  305. public function get_item_permissions_check( $request ) {
  306. $comment = $this->get_comment( $request['id'] );
  307. if ( is_wp_error( $comment ) ) {
  308. return $comment;
  309. }
  310. if ( ! empty( $request['context'] ) && 'edit' === $request['context'] && ! current_user_can( 'moderate_comments' ) ) {
  311. return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to edit comments.' ), array( 'status' => rest_authorization_required_code() ) );
  312. }
  313. $post = get_post( $comment->comment_post_ID );
  314. if ( ! $this->check_read_permission( $comment, $request ) ) {
  315. return new WP_Error( 'rest_cannot_read', __( 'Sorry, you are not allowed to read this comment.' ), array( 'status' => rest_authorization_required_code() ) );
  316. }
  317. if ( $post && ! $this->check_read_post_permission( $post, $request ) ) {
  318. return new WP_Error( 'rest_cannot_read_post', __( 'Sorry, you are not allowed to read the post for this comment.' ), array( 'status' => rest_authorization_required_code() ) );
  319. }
  320. return true;
  321. }
  322. /**
  323. * Retrieves a comment.
  324. *
  325. * @since 4.7.0
  326. *
  327. * @param WP_REST_Request $request Full details about the request.
  328. * @return WP_Error|WP_REST_Response Response object on success, or error object on failure.
  329. */
  330. public function get_item( $request ) {
  331. $comment = $this->get_comment( $request['id'] );
  332. if ( is_wp_error( $comment ) ) {
  333. return $comment;
  334. }
  335. $data = $this->prepare_item_for_response( $comment, $request );
  336. $response = rest_ensure_response( $data );
  337. return $response;
  338. }
  339. /**
  340. * Checks if a given request has access to create a comment.
  341. *
  342. * @since 4.7.0
  343. *
  344. * @param WP_REST_Request $request Full details about the request.
  345. * @return WP_Error|bool True if the request has access to create items, error object otherwise.
  346. */
  347. public function create_item_permissions_check( $request ) {
  348. if ( ! is_user_logged_in() ) {
  349. if ( get_option( 'comment_registration' ) ) {
  350. return new WP_Error( 'rest_comment_login_required', __( 'Sorry, you must be logged in to comment.' ), array( 'status' => 401 ) );
  351. }
  352. /**
  353. * Filter whether comments can be created without authentication.
  354. *
  355. * Enables creating comments for anonymous users.
  356. *
  357. * @since 4.7.0
  358. *
  359. * @param bool $allow_anonymous Whether to allow anonymous comments to
  360. * be created. Default `false`.
  361. * @param WP_REST_Request $request Request used to generate the
  362. * response.
  363. */
  364. $allow_anonymous = apply_filters( 'rest_allow_anonymous_comments', false, $request );
  365. if ( ! $allow_anonymous ) {
  366. return new WP_Error( 'rest_comment_login_required', __( 'Sorry, you must be logged in to comment.' ), array( 'status' => 401 ) );
  367. }
  368. }
  369. // Limit who can set comment `author`, `author_ip` or `status` to anything other than the default.
  370. if ( isset( $request['author'] ) && get_current_user_id() !== $request['author'] && ! current_user_can( 'moderate_comments' ) ) {
  371. return new WP_Error(
  372. 'rest_comment_invalid_author',
  373. /* translators: %s: Request parameter. */
  374. sprintf( __( "Sorry, you are not allowed to edit '%s' for comments." ), 'author' ),
  375. array( 'status' => rest_authorization_required_code() )
  376. );
  377. }
  378. if ( isset( $request['author_ip'] ) && ! current_user_can( 'moderate_comments' ) ) {
  379. if ( empty( $_SERVER['REMOTE_ADDR'] ) || $request['author_ip'] !== $_SERVER['REMOTE_ADDR'] ) {
  380. return new WP_Error(
  381. 'rest_comment_invalid_author_ip',
  382. /* translators: %s: Request parameter. */
  383. sprintf( __( "Sorry, you are not allowed to edit '%s' for comments." ), 'author_ip' ),
  384. array( 'status' => rest_authorization_required_code() )
  385. );
  386. }
  387. }
  388. if ( isset( $request['status'] ) && ! current_user_can( 'moderate_comments' ) ) {
  389. return new WP_Error(
  390. 'rest_comment_invalid_status',
  391. /* translators: %s: Request parameter. */
  392. sprintf( __( "Sorry, you are not allowed to edit '%s' for comments." ), 'status' ),
  393. array( 'status' => rest_authorization_required_code() )
  394. );
  395. }
  396. if ( empty( $request['post'] ) ) {
  397. return new WP_Error( 'rest_comment_invalid_post_id', __( 'Sorry, you are not allowed to create this comment without a post.' ), array( 'status' => 403 ) );
  398. }
  399. $post = get_post( (int) $request['post'] );
  400. if ( ! $post ) {
  401. return new WP_Error( 'rest_comment_invalid_post_id', __( 'Sorry, you are not allowed to create this comment without a post.' ), array( 'status' => 403 ) );
  402. }
  403. if ( 'draft' === $post->post_status ) {
  404. return new WP_Error( 'rest_comment_draft_post', __( 'Sorry, you are not allowed to create a comment on this post.' ), array( 'status' => 403 ) );
  405. }
  406. if ( 'trash' === $post->post_status ) {
  407. return new WP_Error( 'rest_comment_trash_post', __( 'Sorry, you are not allowed to create a comment on this post.' ), array( 'status' => 403 ) );
  408. }
  409. if ( ! $this->check_read_post_permission( $post, $request ) ) {
  410. return new WP_Error( 'rest_cannot_read_post', __( 'Sorry, you are not allowed to read the post for this comment.' ), array( 'status' => rest_authorization_required_code() ) );
  411. }
  412. if ( ! comments_open( $post->ID ) ) {
  413. return new WP_Error( 'rest_comment_closed', __( 'Sorry, comments are closed for this item.' ), array( 'status' => 403 ) );
  414. }
  415. return true;
  416. }
  417. /**
  418. * Creates a comment.
  419. *
  420. * @since 4.7.0
  421. *
  422. * @param WP_REST_Request $request Full details about the request.
  423. * @return WP_Error|WP_REST_Response Response object on success, or error object on failure.
  424. */
  425. public function create_item( $request ) {
  426. if ( ! empty( $request['id'] ) ) {
  427. return new WP_Error( 'rest_comment_exists', __( 'Cannot create existing comment.' ), array( 'status' => 400 ) );
  428. }
  429. // Do not allow comments to be created with a non-default type.
  430. if ( ! empty( $request['type'] ) && 'comment' !== $request['type'] ) {
  431. return new WP_Error( 'rest_invalid_comment_type', __( 'Cannot create a comment with that type.' ), array( 'status' => 400 ) );
  432. }
  433. $prepared_comment = $this->prepare_item_for_database( $request );
  434. if ( is_wp_error( $prepared_comment ) ) {
  435. return $prepared_comment;
  436. }
  437. $prepared_comment['comment_type'] = '';
  438. /*
  439. * Do not allow a comment to be created with missing or empty
  440. * comment_content. See wp_handle_comment_submission().
  441. */
  442. if ( empty( $prepared_comment['comment_content'] ) ) {
  443. return new WP_Error( 'rest_comment_content_invalid', __( 'Invalid comment content.' ), array( 'status' => 400 ) );
  444. }
  445. // Setting remaining values before wp_insert_comment so we can use wp_allow_comment().
  446. if ( ! isset( $prepared_comment['comment_date_gmt'] ) ) {
  447. $prepared_comment['comment_date_gmt'] = current_time( 'mysql', true );
  448. }
  449. // Set author data if the user's logged in.
  450. $missing_author = empty( $prepared_comment['user_id'] )
  451. && empty( $prepared_comment['comment_author'] )
  452. && empty( $prepared_comment['comment_author_email'] )
  453. && empty( $prepared_comment['comment_author_url'] );
  454. if ( is_user_logged_in() && $missing_author ) {
  455. $user = wp_get_current_user();
  456. $prepared_comment['user_id'] = $user->ID;
  457. $prepared_comment['comment_author'] = $user->display_name;
  458. $prepared_comment['comment_author_email'] = $user->user_email;
  459. $prepared_comment['comment_author_url'] = $user->user_url;
  460. }
  461. // Honor the discussion setting that requires a name and email address of the comment author.
  462. if ( get_option( 'require_name_email' ) ) {
  463. if ( empty( $prepared_comment['comment_author'] ) || empty( $prepared_comment['comment_author_email'] ) ) {
  464. return new WP_Error( 'rest_comment_author_data_required', __( 'Creating a comment requires valid author name and email values.' ), array( 'status' => 400 ) );
  465. }
  466. }
  467. if ( ! isset( $prepared_comment['comment_author_email'] ) ) {
  468. $prepared_comment['comment_author_email'] = '';
  469. }
  470. if ( ! isset( $prepared_comment['comment_author_url'] ) ) {
  471. $prepared_comment['comment_author_url'] = '';
  472. }
  473. if ( ! isset( $prepared_comment['comment_agent'] ) ) {
  474. $prepared_comment['comment_agent'] = '';
  475. }
  476. $check_comment_lengths = wp_check_comment_data_max_lengths( $prepared_comment );
  477. if ( is_wp_error( $check_comment_lengths ) ) {
  478. $error_code = $check_comment_lengths->get_error_code();
  479. return new WP_Error( $error_code, __( 'Comment field exceeds maximum length allowed.' ), array( 'status' => 400 ) );
  480. }
  481. $prepared_comment['comment_approved'] = wp_allow_comment( $prepared_comment, true );
  482. if ( is_wp_error( $prepared_comment['comment_approved'] ) ) {
  483. $error_code = $prepared_comment['comment_approved']->get_error_code();
  484. $error_message = $prepared_comment['comment_approved']->get_error_message();
  485. if ( 'comment_duplicate' === $error_code ) {
  486. return new WP_Error( $error_code, $error_message, array( 'status' => 409 ) );
  487. }
  488. if ( 'comment_flood' === $error_code ) {
  489. return new WP_Error( $error_code, $error_message, array( 'status' => 400 ) );
  490. }
  491. return $prepared_comment['comment_approved'];
  492. }
  493. /**
  494. * Filters a comment before it is inserted via the REST API.
  495. *
  496. * Allows modification of the comment right before it is inserted via wp_insert_comment().
  497. * Returning a WP_Error value from the filter will shortcircuit insertion and allow
  498. * skipping further processing.
  499. *
  500. * @since 4.7.0
  501. * @since 4.8.0 `$prepared_comment` can now be a WP_Error to shortcircuit insertion.
  502. *
  503. * @param array|WP_Error $prepared_comment The prepared comment data for wp_insert_comment().
  504. * @param WP_REST_Request $request Request used to insert the comment.
  505. */
  506. $prepared_comment = apply_filters( 'rest_pre_insert_comment', $prepared_comment, $request );
  507. if ( is_wp_error( $prepared_comment ) ) {
  508. return $prepared_comment;
  509. }
  510. $comment_id = wp_insert_comment( wp_filter_comment( wp_slash( (array) $prepared_comment ) ) );
  511. if ( ! $comment_id ) {
  512. return new WP_Error( 'rest_comment_failed_create', __( 'Creating comment failed.' ), array( 'status' => 500 ) );
  513. }
  514. if ( isset( $request['status'] ) ) {
  515. $this->handle_status_param( $request['status'], $comment_id );
  516. }
  517. $comment = get_comment( $comment_id );
  518. /**
  519. * Fires after a comment is created or updated via the REST API.
  520. *
  521. * @since 4.7.0
  522. *
  523. * @param WP_Comment $comment Inserted or updated comment object.
  524. * @param WP_REST_Request $request Request object.
  525. * @param bool $creating True when creating a comment, false
  526. * when updating.
  527. */
  528. do_action( 'rest_insert_comment', $comment, $request, true );
  529. $schema = $this->get_item_schema();
  530. if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
  531. $meta_update = $this->meta->update_value( $request['meta'], $comment_id );
  532. if ( is_wp_error( $meta_update ) ) {
  533. return $meta_update;
  534. }
  535. }
  536. $fields_update = $this->update_additional_fields_for_object( $comment, $request );
  537. if ( is_wp_error( $fields_update ) ) {
  538. return $fields_update;
  539. }
  540. $context = current_user_can( 'moderate_comments' ) ? 'edit' : 'view';
  541. $request->set_param( 'context', $context );
  542. /**
  543. * Fires completely after a comment is created or updated via the REST API.
  544. *
  545. * @since 5.0.0
  546. *
  547. * @param WP_Comment $comment Inserted or updated comment object.
  548. * @param WP_REST_Request $request Request object.
  549. * @param bool $creating True when creating a comment, false
  550. * when updating.
  551. */
  552. do_action( 'rest_after_insert_comment', $comment, $request, true );
  553. $response = $this->prepare_item_for_response( $comment, $request );
  554. $response = rest_ensure_response( $response );
  555. $response->set_status( 201 );
  556. $response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment_id ) ) );
  557. return $response;
  558. }
  559. /**
  560. * Checks if a given REST request has access to update a comment.
  561. *
  562. * @since 4.7.0
  563. *
  564. * @param WP_REST_Request $request Full details about the request.
  565. * @return WP_Error|bool True if the request has access to update the item, error object otherwise.
  566. */
  567. public function update_item_permissions_check( $request ) {
  568. $comment = $this->get_comment( $request['id'] );
  569. if ( is_wp_error( $comment ) ) {
  570. return $comment;
  571. }
  572. if ( ! $this->check_edit_permission( $comment ) ) {
  573. return new WP_Error( 'rest_cannot_edit', __( 'Sorry, you are not allowed to edit this comment.' ), array( 'status' => rest_authorization_required_code() ) );
  574. }
  575. return true;
  576. }
  577. /**
  578. * Updates a comment.
  579. *
  580. * @since 4.7.0
  581. *
  582. * @param WP_REST_Request $request Full details about the request.
  583. * @return WP_Error|WP_REST_Response Response object on success, or error object on failure.
  584. */
  585. public function update_item( $request ) {
  586. $comment = $this->get_comment( $request['id'] );
  587. if ( is_wp_error( $comment ) ) {
  588. return $comment;
  589. }
  590. $id = $comment->comment_ID;
  591. if ( isset( $request['type'] ) && get_comment_type( $id ) !== $request['type'] ) {
  592. return new WP_Error( 'rest_comment_invalid_type', __( 'Sorry, you are not allowed to change the comment type.' ), array( 'status' => 404 ) );
  593. }
  594. $prepared_args = $this->prepare_item_for_database( $request );
  595. if ( is_wp_error( $prepared_args ) ) {
  596. return $prepared_args;
  597. }
  598. if ( ! empty( $prepared_args['comment_post_ID'] ) ) {
  599. $post = get_post( $prepared_args['comment_post_ID'] );
  600. if ( empty( $post ) ) {
  601. return new WP_Error( 'rest_comment_invalid_post_id', __( 'Invalid post ID.' ), array( 'status' => 403 ) );
  602. }
  603. }
  604. if ( empty( $prepared_args ) && isset( $request['status'] ) ) {
  605. // Only the comment status is being changed.
  606. $change = $this->handle_status_param( $request['status'], $id );
  607. if ( ! $change ) {
  608. return new WP_Error( 'rest_comment_failed_edit', __( 'Updating comment status failed.' ), array( 'status' => 500 ) );
  609. }
  610. } elseif ( ! empty( $prepared_args ) ) {
  611. if ( is_wp_error( $prepared_args ) ) {
  612. return $prepared_args;
  613. }
  614. if ( isset( $prepared_args['comment_content'] ) && empty( $prepared_args['comment_content'] ) ) {
  615. return new WP_Error( 'rest_comment_content_invalid', __( 'Invalid comment content.' ), array( 'status' => 400 ) );
  616. }
  617. $prepared_args['comment_ID'] = $id;
  618. $check_comment_lengths = wp_check_comment_data_max_lengths( $prepared_args );
  619. if ( is_wp_error( $check_comment_lengths ) ) {
  620. $error_code = $check_comment_lengths->get_error_code();
  621. return new WP_Error( $error_code, __( 'Comment field exceeds maximum length allowed.' ), array( 'status' => 400 ) );
  622. }
  623. $updated = wp_update_comment( wp_slash( (array) $prepared_args ) );
  624. if ( false === $updated ) {
  625. return new WP_Error( 'rest_comment_failed_edit', __( 'Updating comment failed.' ), array( 'status' => 500 ) );
  626. }
  627. if ( isset( $request['status'] ) ) {
  628. $this->handle_status_param( $request['status'], $id );
  629. }
  630. }
  631. $comment = get_comment( $id );
  632. /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php */
  633. do_action( 'rest_insert_comment', $comment, $request, false );
  634. $schema = $this->get_item_schema();
  635. if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
  636. $meta_update = $this->meta->update_value( $request['meta'], $id );
  637. if ( is_wp_error( $meta_update ) ) {
  638. return $meta_update;
  639. }
  640. }
  641. $fields_update = $this->update_additional_fields_for_object( $comment, $request );
  642. if ( is_wp_error( $fields_update ) ) {
  643. return $fields_update;
  644. }
  645. $request->set_param( 'context', 'edit' );
  646. /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php */
  647. do_action( 'rest_after_insert_comment', $comment, $request, false );
  648. $response = $this->prepare_item_for_response( $comment, $request );
  649. return rest_ensure_response( $response );
  650. }
  651. /**
  652. * Checks if a given request has access to delete a comment.
  653. *
  654. * @since 4.7.0
  655. *
  656. * @param WP_REST_Request $request Full details about the request.
  657. * @return WP_Error|bool True if the request has access to delete the item, error object otherwise.
  658. */
  659. public function delete_item_permissions_check( $request ) {
  660. $comment = $this->get_comment( $request['id'] );
  661. if ( is_wp_error( $comment ) ) {
  662. return $comment;
  663. }
  664. if ( ! $this->check_edit_permission( $comment ) ) {
  665. return new WP_Error( 'rest_cannot_delete', __( 'Sorry, you are not allowed to delete this comment.' ), array( 'status' => rest_authorization_required_code() ) );
  666. }
  667. return true;
  668. }
  669. /**
  670. * Deletes a comment.
  671. *
  672. * @since 4.7.0
  673. *
  674. * @param WP_REST_Request $request Full details about the request.
  675. * @return WP_Error|WP_REST_Response Response object on success, or error object on failure.
  676. */
  677. public function delete_item( $request ) {
  678. $comment = $this->get_comment( $request['id'] );
  679. if ( is_wp_error( $comment ) ) {
  680. return $comment;
  681. }
  682. $force = isset( $request['force'] ) ? (bool) $request['force'] : false;
  683. /**
  684. * Filters whether a comment can be trashed.
  685. *
  686. * Return false to disable trash support for the post.
  687. *
  688. * @since 4.7.0
  689. *
  690. * @param bool $supports_trash Whether the post type support trashing.
  691. * @param WP_Post $comment The comment object being considered for trashing support.
  692. */
  693. $supports_trash = apply_filters( 'rest_comment_trashable', ( EMPTY_TRASH_DAYS > 0 ), $comment );
  694. $request->set_param( 'context', 'edit' );
  695. if ( $force ) {
  696. $previous = $this->prepare_item_for_response( $comment, $request );
  697. $result = wp_delete_comment( $comment->comment_ID, true );
  698. $response = new WP_REST_Response();
  699. $response->set_data(
  700. array(
  701. 'deleted' => true,
  702. 'previous' => $previous->get_data(),
  703. )
  704. );
  705. } else {
  706. // If this type doesn't support trashing, error out.
  707. if ( ! $supports_trash ) {
  708. /* translators: %s: force=true */
  709. return new WP_Error( 'rest_trash_not_supported', sprintf( __( "The comment does not support trashing. Set '%s' to delete." ), 'force=true' ), array( 'status' => 501 ) );
  710. }
  711. if ( 'trash' === $comment->comment_approved ) {
  712. return new WP_Error( 'rest_already_trashed', __( 'The comment has already been trashed.' ), array( 'status' => 410 ) );
  713. }
  714. $result = wp_trash_comment( $comment->comment_ID );
  715. $comment = get_comment( $comment->comment_ID );
  716. $response = $this->prepare_item_for_response( $comment, $request );
  717. }
  718. if ( ! $result ) {
  719. return new WP_Error( 'rest_cannot_delete', __( 'The comment cannot be deleted.' ), array( 'status' => 500 ) );
  720. }
  721. /**
  722. * Fires after a comment is deleted via the REST API.
  723. *
  724. * @since 4.7.0
  725. *
  726. * @param WP_Comment $comment The deleted comment data.
  727. * @param WP_REST_Response $response The response returned from the API.
  728. * @param WP_REST_Request $request The request sent to the API.
  729. */
  730. do_action( 'rest_delete_comment', $comment, $response, $request );
  731. return $response;
  732. }
  733. /**
  734. * Prepares a single comment output for response.
  735. *
  736. * @since 4.7.0
  737. *
  738. * @param WP_Comment $comment Comment object.
  739. * @param WP_REST_Request $request Request object.
  740. * @return WP_REST_Response Response object.
  741. */
  742. public function prepare_item_for_response( $comment, $request ) {
  743. $fields = $this->get_fields_for_response( $request );
  744. $data = array();
  745. if ( in_array( 'id', $fields, true ) ) {
  746. $data['id'] = (int) $comment->comment_ID;
  747. }
  748. if ( in_array( 'post', $fields, true ) ) {
  749. $data['post'] = (int) $comment->comment_post_ID;
  750. }
  751. if ( in_array( 'parent', $fields, true ) ) {
  752. $data['parent'] = (int) $comment->comment_parent;
  753. }
  754. if ( in_array( 'author', $fields, true ) ) {
  755. $data['author'] = (int) $comment->user_id;
  756. }
  757. if ( in_array( 'author_name', $fields, true ) ) {
  758. $data['author_name'] = $comment->comment_author;
  759. }
  760. if ( in_array( 'author_email', $fields, true ) ) {
  761. $data['author_email'] = $comment->comment_author_email;
  762. }
  763. if ( in_array( 'author_url', $fields, true ) ) {
  764. $data['author_url'] = $comment->comment_author_url;
  765. }
  766. if ( in_array( 'author_ip', $fields, true ) ) {
  767. $data['author_ip'] = $comment->comment_author_IP;
  768. }
  769. if ( in_array( 'author_user_agent', $fields, true ) ) {
  770. $data['author_user_agent'] = $comment->comment_agent;
  771. }
  772. if ( in_array( 'date', $fields, true ) ) {
  773. $data['date'] = mysql_to_rfc3339( $comment->comment_date );
  774. }
  775. if ( in_array( 'date_gmt', $fields, true ) ) {
  776. $data['date_gmt'] = mysql_to_rfc3339( $comment->comment_date_gmt );
  777. }
  778. if ( in_array( 'content', $fields, true ) ) {
  779. $data['content'] = array(
  780. /** This filter is documented in wp-includes/comment-template.php */
  781. 'rendered' => apply_filters( 'comment_text', $comment->comment_content, $comment ),
  782. 'raw' => $comment->comment_content,
  783. );
  784. }
  785. if ( in_array( 'link', $fields, true ) ) {
  786. $data['link'] = get_comment_link( $comment );
  787. }
  788. if ( in_array( 'status', $fields, true ) ) {
  789. $data['status'] = $this->prepare_status_response( $comment->comment_approved );
  790. }
  791. if ( in_array( 'type', $fields, true ) ) {
  792. $data['type'] = get_comment_type( $comment->comment_ID );
  793. }
  794. if ( in_array( 'author_avatar_urls', $fields, true ) ) {
  795. $data['author_avatar_urls'] = rest_get_avatar_urls( $comment );
  796. }
  797. if ( in_array( 'meta', $fields, true ) ) {
  798. $data['meta'] = $this->meta->get_value( $comment->comment_ID, $request );
  799. }
  800. $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
  801. $data = $this->add_additional_fields_to_object( $data, $request );
  802. $data = $this->filter_response_by_context( $data, $context );
  803. // Wrap the data in a response object.
  804. $response = rest_ensure_response( $data );
  805. $response->add_links( $this->prepare_links( $comment ) );
  806. /**
  807. * Filters a comment returned from the API.
  808. *
  809. * Allows modification of the comment right before it is returned.
  810. *
  811. * @since 4.7.0
  812. *
  813. * @param WP_REST_Response $response The response object.
  814. * @param WP_Comment $comment The original comment object.
  815. * @param WP_REST_Request $request Request used to generate the response.
  816. */
  817. return apply_filters( 'rest_prepare_comment', $response, $comment, $request );
  818. }
  819. /**
  820. * Prepares links for the request.
  821. *
  822. * @since 4.7.0
  823. *
  824. * @param WP_Comment $comment Comment object.
  825. * @return array Links for the given comment.
  826. */
  827. protected function prepare_links( $comment ) {
  828. $links = array(
  829. 'self' => array(
  830. 'href' => rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment->comment_ID ) ),
  831. ),
  832. 'collection' => array(
  833. 'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ),
  834. ),
  835. );
  836. if ( 0 !== (int) $comment->user_id ) {
  837. $links['author'] = array(
  838. 'href' => rest_url( 'wp/v2/users/' . $comment->user_id ),
  839. 'embeddable' => true,
  840. );
  841. }
  842. if ( 0 !== (int) $comment->comment_post_ID ) {
  843. $post = get_post( $comment->comment_post_ID );
  844. if ( ! empty( $post->ID ) ) {
  845. $obj = get_post_type_object( $post->post_type );
  846. $base = ! empty( $obj->rest_base ) ? $obj->rest_base : $obj->name;
  847. $links['up'] = array(
  848. 'href' => rest_url( 'wp/v2/' . $base . '/' . $comment->comment_post_ID ),
  849. 'embeddable' => true,
  850. 'post_type' => $post->post_type,
  851. );
  852. }
  853. }
  854. if ( 0 !== (int) $comment->comment_parent ) {
  855. $links['in-reply-to'] = array(
  856. 'href' => rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment->comment_parent ) ),
  857. 'embeddable' => true,
  858. );
  859. }
  860. // Only grab one comment to verify the comment has children.
  861. $comment_children = $comment->get_children(
  862. array(
  863. 'number' => 1,
  864. 'count' => true,
  865. )
  866. );
  867. if ( ! empty( $comment_children ) ) {
  868. $args = array(
  869. 'parent' => $comment->comment_ID,
  870. );
  871. $rest_url = add_query_arg( $args, rest_url( $this->namespace . '/' . $this->rest_base ) );
  872. $links['children'] = array(
  873. 'href' => $rest_url,
  874. );
  875. }
  876. return $links;
  877. }
  878. /**
  879. * Prepends internal property prefix to query parameters to match our response fields.
  880. *
  881. * @since 4.7.0
  882. *
  883. * @param string $query_param Query parameter.
  884. * @return string The normalized query parameter.
  885. */
  886. protected function normalize_query_param( $query_param ) {
  887. $prefix = 'comment_';
  888. switch ( $query_param ) {
  889. case 'id':
  890. $normalized = $prefix . 'ID';
  891. break;
  892. case 'post':
  893. $normalized = $prefix . 'post_ID';
  894. break;
  895. case 'parent':
  896. $normalized = $prefix . 'parent';
  897. break;
  898. case 'include':
  899. $normalized = 'comment__in';
  900. break;
  901. default:
  902. $normalized = $prefix . $query_param;
  903. break;
  904. }
  905. return $normalized;
  906. }
  907. /**
  908. * Checks comment_approved to set comment status for single comment output.
  909. *
  910. * @since 4.7.0
  911. *
  912. * @param string|int $comment_approved comment status.
  913. * @return string Comment status.
  914. */
  915. protected function prepare_status_response( $comment_approved ) {
  916. switch ( $comment_approved ) {
  917. case 'hold':
  918. case '0':
  919. $status = 'hold';
  920. break;
  921. case 'approve':
  922. case '1':
  923. $status = 'approved';
  924. break;
  925. case 'spam':
  926. case 'trash':
  927. default:
  928. $status = $comment_approved;
  929. break;
  930. }
  931. return $status;
  932. }
  933. /**
  934. * Prepares a single comment to be inserted into the database.
  935. *
  936. * @since 4.7.0
  937. *
  938. * @param WP_REST_Request $request Request object.
  939. * @return array|WP_Error Prepared comment, otherwise WP_Error object.
  940. */
  941. protected function prepare_item_for_database( $request ) {
  942. $prepared_comment = array();
  943. /*
  944. * Allow the comment_content to be set via the 'content' or
  945. * the 'content.raw' properties of the Request object.
  946. */
  947. if ( isset( $request['content'] ) && is_string( $request['content'] ) ) {
  948. $prepared_comment['comment_content'] = $request['content'];
  949. } elseif ( isset( $request['content']['raw'] ) && is_string( $request['content']['raw'] ) ) {
  950. $prepared_comment['comment_content'] = $request['content']['raw'];
  951. }
  952. if ( isset( $request['post'] ) ) {
  953. $prepared_comment['comment_post_ID'] = (int) $request['post'];
  954. }
  955. if ( isset( $request['parent'] ) ) {
  956. $prepared_comment['comment_parent'] = $request['parent'];
  957. }
  958. if ( isset( $request['author'] ) ) {
  959. $user = new WP_User( $request['author'] );
  960. if ( $user->exists() ) {
  961. $prepared_comment['user_id'] = $user->ID;
  962. $prepared_comment['comment_author'] = $user->display_name;
  963. $prepared_comment['comment_author_email'] = $user->user_email;
  964. $prepared_comment['comment_author_url'] = $user->user_url;
  965. } else {
  966. return new WP_Error( 'rest_comment_author_invalid', __( 'Invalid comment author ID.' ), array( 'status' => 400 ) );
  967. }
  968. }
  969. if ( isset( $request['author_name'] ) ) {
  970. $prepared_comment['comment_author'] = $request['author_name'];
  971. }
  972. if ( isset( $request['author_email'] ) ) {
  973. $prepared_comment['comment_author_email'] = $request['author_email'];
  974. }
  975. if ( isset( $request['author_url'] ) ) {
  976. $prepared_comment['comment_author_url'] = $request['author_url'];
  977. }
  978. if ( isset( $request['author_ip'] ) && current_user_can( 'moderate_comments' ) ) {
  979. $prepared_comment['comment_author_IP'] = $request['author_ip'];
  980. } elseif ( ! empty( $_SERVER['REMOTE_ADDR'] ) && rest_is_ip_address( $_SERVER['REMOTE_ADDR'] ) ) {
  981. $prepared_comment['comment_author_IP'] = $_SERVER['REMOTE_ADDR'];
  982. } else {
  983. $prepared_comment['comment_author_IP'] = '127.0.0.1';
  984. }
  985. if ( ! empty( $request['author_user_agent'] ) ) {
  986. $prepared_comment['comment_agent'] = $request['author_user_agent'];
  987. } elseif ( $request->get_header( 'user_agent' ) ) {
  988. $prepared_comment['comment_agent'] = $request->get_header( 'user_agent' );
  989. }
  990. if ( ! empty( $request['date'] ) ) {
  991. $date_data = rest_get_date_with_gmt( $request['date'] );
  992. if ( ! empty( $date_data ) ) {
  993. list( $prepared_comment['comment_date'], $prepared_comment['comment_date_gmt'] ) = $date_data;
  994. }
  995. } elseif ( ! empty( $request['date_gmt'] ) ) {
  996. $date_data = rest_get_date_with_gmt( $request['date_gmt'], true );
  997. if ( ! empty( $date_data ) ) {
  998. list( $prepared_comment['comment_date'], $prepared_comment['comment_date_gmt'] ) = $date_data;
  999. }
  1000. }
  1001. /**
  1002. * Filters a comment after it is prepared for the database.
  1003. *
  1004. * Allows modification of the comment right after it is prepared for the database.
  1005. *
  1006. * @since 4.7.0
  1007. *
  1008. * @param array $prepared_comment The prepared comment data for `wp_insert_comment`.
  1009. * @param WP_REST_Request $request The current request.
  1010. */
  1011. return apply_filters( 'rest_preprocess_comment', $prepared_comment, $request );
  1012. }
  1013. /**
  1014. * Retrieves the comment's schema, conforming to JSON Schema.
  1015. *
  1016. * @since 4.7.0
  1017. *
  1018. * @return array
  1019. */
  1020. public function get_item_schema() {
  1021. if ( $this->schema ) {
  1022. return $this->add_additional_fields_schema( $this->schema );
  1023. }
  1024. $schema = array(
  1025. '$schema' => 'http://json-schema.org/draft-04/schema#',
  1026. 'title' => 'comment',
  1027. 'type' => 'object',
  1028. 'properties' => array(
  1029. 'id' => array(
  1030. 'description' => __( 'Unique identifier for the object.' ),
  1031. 'type' => 'integer',
  1032. 'context' => array( 'view', 'edit', 'embed' ),
  1033. 'readonly' => true,
  1034. ),
  1035. 'author' => array(
  1036. 'description' => __( 'The ID of the user object, if author was a user.' ),
  1037. 'type' => 'integer',
  1038. 'context' => array( 'view', 'edit', 'embed' ),
  1039. ),
  1040. 'author_email' => array(
  1041. 'description' => __( 'Email address for the object author.' ),
  1042. 'type' => 'string',
  1043. 'format' => 'email',
  1044. 'context' => array( 'edit' ),
  1045. 'arg_options' => array(
  1046. 'sanitize_callback' => array( $this, 'check_comment_author_email' ),
  1047. 'validate_callback' => null, // skip built-in validation of 'email'.
  1048. ),
  1049. ),
  1050. 'author_ip' => array(
  1051. 'description' => __( 'IP address for the object author.' ),
  1052. 'type' => 'string',
  1053. 'format' => 'ip',
  1054. 'context' => array( 'edit' ),
  1055. ),
  1056. 'author_name' => array(
  1057. 'description' => __( 'Display name for the object author.' ),
  1058. 'type' => 'string',
  1059. 'context' => array( 'view', 'edit', 'embed' ),
  1060. 'arg_options' => array(
  1061. 'sanitize_callback' => 'sanitize_text_field',
  1062. ),
  1063. ),
  1064. 'author_url' => array(
  1065. 'description' => __( 'URL for the object author.' ),
  1066. 'type' => 'string',
  1067. 'format' => 'uri',
  1068. 'context' => array( 'view', 'edit', 'embed' ),
  1069. ),
  1070. 'author_user_agent' => array(
  1071. 'description' => __( 'User agent for the object author.' ),
  1072. 'type' => 'string',
  1073. 'context' => array( 'edit' ),
  1074. 'arg_options' => array(
  1075. 'sanitize_callback' => 'sanitize_text_field',
  1076. ),
  1077. ),
  1078. 'content' => array(
  1079. 'description' => __( 'The content for the object.' ),
  1080. 'type' => 'object',
  1081. 'context' => array( 'view', 'edit', 'embed' ),
  1082. 'arg_options' => array(
  1083. 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
  1084. 'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database()
  1085. ),
  1086. 'properties' => array(
  1087. 'raw' => array(
  1088. 'description' => __( 'Content for the object, as it exists in the database.' ),
  1089. 'type' => 'string',
  1090. 'context' => array( 'edit' ),
  1091. ),
  1092. 'rendered' => array(
  1093. 'description' => __( 'HTML content for the object, transformed for display.' ),
  1094. 'type' => 'string',
  1095. 'context' => array( 'view', 'edit', 'embed' ),
  1096. 'readonly' => true,
  1097. ),
  1098. ),
  1099. ),
  1100. 'date' => array(
  1101. 'description' => __( "The date the object was published, in the site's timezone." ),
  1102. 'type' => 'string',
  1103. 'format' => 'date-time',
  1104. 'context' => array( 'view', 'edit', 'embed' ),
  1105. ),
  1106. 'date_gmt' => array(
  1107. 'description' => __( 'The date the object was published, as GMT.' ),
  1108. 'type' => 'string',
  1109. 'format' => 'date-time',
  1110. 'context' => array( 'view', 'edit' ),
  1111. ),
  1112. 'link' => array(
  1113. 'description' => __( 'URL to the object.' ),
  1114. 'type' => 'string',
  1115. 'format' => 'uri',
  1116. 'context' => array( 'view', 'edit', 'embed' ),
  1117. 'readonly' => true,
  1118. ),
  1119. 'parent' => array(
  1120. 'description' => __( 'The ID for the parent of the object.' ),
  1121. 'type' => 'integer',
  1122. 'context' => array( 'view', 'edit', 'embed' ),
  1123. 'default' => 0,
  1124. ),
  1125. 'post' => array(
  1126. 'description' => __( 'The ID of the associated post object.' ),
  1127. 'type' => 'integer',
  1128. 'context' => array( 'view', 'edit' ),
  1129. 'default' => 0,
  1130. ),
  1131. 'status' => array(
  1132. 'description' => __( 'State of the object.' ),
  1133. 'type' => 'string',
  1134. 'context' => array( 'view', 'edit' ),
  1135. 'arg_options' => array(
  1136. 'sanitize_callback' => 'sanitize_key',
  1137. ),
  1138. ),
  1139. 'type' => array(
  1140. 'description' => __( 'Type of Comment for the object.' ),
  1141. 'type' => 'string',
  1142. 'context' => array( 'view', 'edit', 'embed' ),
  1143. 'readonly' => true,
  1144. ),
  1145. ),
  1146. );
  1147. if ( get_option( 'show_avatars' ) ) {
  1148. $avatar_properties = array();
  1149. $avatar_sizes = rest_get_avatar_sizes();
  1150. foreach ( $avatar_sizes as $size ) {
  1151. $avatar_properties[ $size ] = array(
  1152. /* translators: %d: Avatar image size in pixels. */
  1153. 'description' => sprintf( __( 'Avatar URL with image size of %d pixels.' ), $size ),
  1154. 'type' => 'string',
  1155. 'format' => 'uri',
  1156. 'context' => array( 'embed', 'view', 'edit' ),
  1157. );
  1158. }
  1159. $schema['properties']['author_avatar_urls'] = array(
  1160. 'description' => __( 'Avatar URLs for the object author.' ),
  1161. 'type' => 'object',
  1162. 'context' => array( 'view', 'edit', 'embed' ),
  1163. 'readonly' => true,
  1164. 'properties' => $avatar_properties,
  1165. );
  1166. }
  1167. $schema['properties']['meta'] = $this->meta->get_field_schema();
  1168. $this->schema = $schema;
  1169. return $this->add_additional_fields_schema( $this->schema );
  1170. }
  1171. /**
  1172. * Retrieves the query params for collections.
  1173. *
  1174. * @since 4.7.0
  1175. *
  1176. * @return array Comments collection parameters.
  1177. */
  1178. public function get_collection_params() {
  1179. $query_params = parent::get_collection_params();
  1180. $query_params['context']['default'] = 'view';
  1181. $query_params['after'] = array(
  1182. 'description' => __( 'Limit response to comments published after a given ISO8601 compliant date.' ),
  1183. 'type' => 'string',
  1184. 'format' => 'date-time',
  1185. );
  1186. $query_params['author'] = array(
  1187. 'description' => __( 'Limit result set to comments assigned to specific user IDs. Requires authorization.' ),
  1188. 'type' => 'array',
  1189. 'items' => array(
  1190. 'type' => 'integer',
  1191. ),
  1192. );
  1193. $query_params['author_exclude'] = array(
  1194. 'description' => __( 'Ensure result set excludes comments assigned to specific user IDs. Requires authorization.' ),
  1195. 'type' => 'array',
  1196. 'items' => array(
  1197. 'type' => 'integer',
  1198. ),
  1199. );
  1200. $query_params['author_email'] = array(
  1201. 'default' => null,
  1202. 'description' => __( 'Limit result set to that from a specific author email. Requires authorization.' ),
  1203. 'format' => 'email',
  1204. 'type' => 'string',
  1205. );
  1206. $query_params['before'] = array(
  1207. 'description' => __( 'Limit response to comments published before a given ISO8601 compliant date.' ),
  1208. 'type' => 'string',
  1209. 'format' => 'date-time',
  1210. );
  1211. $query_params['exclude'] = array(
  1212. 'description' => __( 'Ensure result set excludes specific IDs.' ),
  1213. 'type' => 'array',
  1214. 'items' => array(
  1215. 'type' => 'integer',
  1216. ),
  1217. 'default' => array(),
  1218. );
  1219. $query_params['include'] = array(
  1220. 'description' => __( 'Limit result set to specific IDs.' ),
  1221. 'type' => 'array',
  1222. 'items' => array(
  1223. 'type' => 'integer',
  1224. ),
  1225. 'default' => array(),
  1226. );
  1227. $query_params['offset'] = array(
  1228. 'description' => __( 'Offset the result set by a specific number of items.' ),
  1229. 'type' => 'integer',
  1230. );
  1231. $query_params['order'] = array(
  1232. 'description' => __( 'Order sort attribute ascending or descending.' ),
  1233. 'type' => 'string',
  1234. 'default' => 'desc',
  1235. 'enum' => array(
  1236. 'asc',
  1237. 'desc',
  1238. ),
  1239. );
  1240. $query_params['orderby'] = array(
  1241. 'description' => __( 'Sort collection by object attribute.' ),
  1242. 'type' => 'string',
  1243. 'default' => 'date_gmt',
  1244. 'enum' => array(
  1245. 'date',
  1246. 'date_gmt',
  1247. 'id',
  1248. 'include',
  1249. 'post',
  1250. 'parent',
  1251. 'type',
  1252. ),
  1253. );
  1254. $query_params['parent'] = array(
  1255. 'default' => array(),
  1256. 'description' => __( 'Limit result set to comments of specific parent IDs.' ),
  1257. 'type' => 'array',
  1258. 'items' => array(
  1259. 'type' => 'integer',
  1260. ),
  1261. );
  1262. $query_params['parent_exclude'] = array(
  1263. 'default' => array(),
  1264. 'description' => __( 'Ensure result set excludes specific parent IDs.' ),
  1265. 'type' => 'array',
  1266. 'items' => array(
  1267. 'type' => 'integer',
  1268. ),
  1269. );
  1270. $query_params['post'] = array(
  1271. 'default' => array(),
  1272. 'description' => __( 'Limit result set to comments assigned to specific post IDs.' ),
  1273. 'type' => 'array',
  1274. 'items' => array(
  1275. 'type' => 'integer',
  1276. ),
  1277. );
  1278. $query_params['status'] = array(
  1279. 'default' => 'approve',
  1280. 'description' => __( 'Limit result set to comments assigned a specific status. Requires authorization.' ),
  1281. 'sanitize_callback' => 'sanitize_key',
  1282. 'type' => 'string',
  1283. 'validate_callback' => 'rest_validate_request_arg',
  1284. );
  1285. $query_params['type'] = array(
  1286. 'default' => 'comment',
  1287. 'description' => __( 'Limit result set to comments assigned a specific type. Requires authorization.' ),
  1288. 'sanitize_callback' => 'sanitize_key',
  1289. 'type' => 'string',
  1290. 'validate_callback' => 'rest_validate_request_arg',
  1291. );
  1292. $query_params['password'] = array(
  1293. 'description' => __( 'The password for the post if it is password protected.' ),
  1294. 'type' => 'string',
  1295. );
  1296. /**
  1297. * Filter collection parameters for the comments controller.
  1298. *
  1299. * This filter registers the collection parameter, but does not map the
  1300. * collection parameter to an internal WP_Comment_Query parameter. Use the
  1301. * `rest_comment_query` filter to set WP_Comment_Query parameters.
  1302. *
  1303. * @since 4.7.0
  1304. *
  1305. * @param array $query_params JSON Schema-formatted collection parameters.
  1306. */
  1307. return apply_filters( 'rest_comment_collection_params', $query_params );
  1308. }
  1309. /**
  1310. * Sets the comment_status of a given comment object when creating or updating a comment.
  1311. *
  1312. * @since 4.7.0
  1313. *
  1314. * @param string|int $new_status New comment status.
  1315. * @param int $comment_id Comment ID.
  1316. * @return bool Whether the status was changed.
  1317. */
  1318. protected function handle_status_param( $new_status, $comment_id ) {
  1319. $old_status = wp_get_comment_status( $comment_id );
  1320. if ( $new_status === $old_status ) {
  1321. return false;
  1322. }
  1323. switch ( $new_status ) {
  1324. case 'approved':
  1325. case 'approve':
  1326. case '1':
  1327. $changed = wp_set_comment_status( $comment_id, 'approve' );
  1328. break;
  1329. case 'hold':
  1330. case '0':
  1331. $changed = wp_set_comment_status( $comment_id, 'hold' );
  1332. break;
  1333. case 'spam':
  1334. $changed = wp_spam_comment( $comment_id );
  1335. break;
  1336. case 'unspam':
  1337. $changed = wp_unspam_comment( $comment_id );
  1338. break;
  1339. case 'trash':
  1340. $changed = wp_trash_comment( $comment_id );
  1341. break;
  1342. case 'untrash':
  1343. $changed = wp_untrash_comment( $comment_id );
  1344. break;
  1345. default:
  1346. $changed = false;
  1347. break;
  1348. }
  1349. return $changed;
  1350. }
  1351. /**
  1352. * Checks if the post can be read.
  1353. *
  1354. * Correctly handles posts with the inherit status.
  1355. *
  1356. * @since 4.7.0
  1357. *
  1358. * @param WP_Post $post Post object.
  1359. * @param WP_REST_Request $request Request data to check.
  1360. * @return bool Whether post can be read.
  1361. */
  1362. protected function check_read_post_permission( $post, $request ) {
  1363. $post_type = get_post_type_object( $post->post_type );
  1364. $posts_controller = $post_type->get_rest_controller();
  1365. // Ensure the posts controller is specifically a WP_REST_Posts_Controller instance
  1366. // before using methods specific to that controller.
  1367. if ( ! $posts_controller instanceof WP_REST_Posts_Controller ) {
  1368. $posts_controller = new WP_REST_Posts_Controller( $post->post_type );
  1369. }
  1370. $has_password_filter = false;
  1371. // Only check password if a specific post was queried for or a single comment
  1372. $requested_post = ! empty( $request['post'] ) && ( ! is_array( $request['post'] ) || 1 === count( $request['post'] ) );
  1373. $requested_comment = ! empty( $request['id'] );
  1374. if ( ( $requested_post || $requested_comment ) && $posts_controller->can_access_password_content( $post, $request ) ) {
  1375. add_filter( 'post_password_required', '__return_false' );
  1376. $has_password_filter = true;
  1377. }
  1378. if ( post_password_required( $post ) ) {
  1379. $result = current_user_can( $post_type->cap->edit_post, $post->ID );
  1380. } else {
  1381. $result = $posts_controller->check_read_permission( $post );
  1382. }
  1383. if ( $has_password_filter ) {
  1384. remove_filter( 'post_password_required', '__return_false' );
  1385. }
  1386. return $result;
  1387. }
  1388. /**
  1389. * Checks if the comment can be read.
  1390. *
  1391. * @since 4.7.0
  1392. *
  1393. * @param WP_Comment $comment Comment object.
  1394. * @param WP_REST_Request $request Request data to check.
  1395. * @return bool Whether the comment can be read.
  1396. */
  1397. protected function check_read_permission( $comment, $request ) {
  1398. if ( ! empty( $comment->comment_post_ID ) ) {
  1399. $post = get_post( $comment->comment_post_ID );
  1400. if ( $post ) {
  1401. if ( $this->check_read_post_permission( $post, $request ) && 1 === (int) $comment->comment_approved ) {
  1402. return true;
  1403. }
  1404. }
  1405. }
  1406. if ( 0 === get_current_user_id() ) {
  1407. return false;
  1408. }
  1409. if ( empty( $comment->comment_post_ID ) && ! current_user_can( 'moderate_comments' ) ) {
  1410. return false;
  1411. }
  1412. if ( ! empty( $comment->user_id ) && get_current_user_id() === (int) $comment->user_id ) {
  1413. return true;
  1414. }
  1415. return current_user_can( 'edit_comment', $comment->comment_ID );
  1416. }
  1417. /**
  1418. * Checks if a comment can be edited or deleted.
  1419. *
  1420. * @since 4.7.0
  1421. *
  1422. * @param object $comment Comment object.
  1423. * @return bool Whether the comment can be edited or deleted.
  1424. */
  1425. protected function check_edit_permission( $comment ) {
  1426. if ( 0 === (int) get_current_user_id() ) {
  1427. return false;
  1428. }
  1429. if ( current_user_can( 'moderate_comments' ) ) {
  1430. return true;
  1431. }
  1432. return current_user_can( 'edit_comment', $comment->comment_ID );
  1433. }
  1434. /**
  1435. * Checks a comment author email for validity.
  1436. *
  1437. * Accepts either a valid email address or empty string as a valid comment
  1438. * author email address. Setting the comment author email to an empty
  1439. * string is allowed when a comment is being updated.
  1440. *
  1441. * @since 4.7.0
  1442. *
  1443. * @param string $value Author email value submitted.
  1444. * @param WP_REST_Request $request Full details about the request.
  1445. * @param string $param The parameter name.
  1446. * @return WP_Error|string The sanitized email address, if valid,
  1447. * otherwise an error.
  1448. */
  1449. public function check_comment_author_email( $value, $request, $param ) {
  1450. $email = (string) $value;
  1451. if ( empty( $email ) ) {
  1452. return $email;
  1453. }
  1454. $check_email = rest_validate_request_arg( $email, $request, $param );
  1455. if ( is_wp_error( $check_email ) ) {
  1456. return $check_email;
  1457. }
  1458. return $email;
  1459. }
  1460. }