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

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