No Description

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

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