Bez popisu

class-wp-rest-posts-controller.php 92KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092
  1. <?php
  2. /**
  3. * REST API: WP_REST_Posts_Controller class
  4. *
  5. * @package WordPress
  6. * @subpackage REST_API
  7. * @since 4.7.0
  8. */
  9. /**
  10. * Core class to access posts via the REST API.
  11. *
  12. * @since 4.7.0
  13. *
  14. * @see WP_REST_Controller
  15. */
  16. class WP_REST_Posts_Controller extends WP_REST_Controller {
  17. /**
  18. * Post type.
  19. *
  20. * @since 4.7.0
  21. * @var string
  22. */
  23. protected $post_type;
  24. /**
  25. * Instance of a post meta fields object.
  26. *
  27. * @since 4.7.0
  28. * @var WP_REST_Post_Meta_Fields
  29. */
  30. protected $meta;
  31. /**
  32. * Passwordless post access permitted.
  33. *
  34. * @since 5.7.1
  35. * @var int[]
  36. */
  37. protected $password_check_passed = array();
  38. /**
  39. * Constructor.
  40. *
  41. * @since 4.7.0
  42. *
  43. * @param string $post_type Post type.
  44. */
  45. public function __construct( $post_type ) {
  46. $this->post_type = $post_type;
  47. $this->namespace = 'wp/v2';
  48. $obj = get_post_type_object( $post_type );
  49. $this->rest_base = ! empty( $obj->rest_base ) ? $obj->rest_base : $obj->name;
  50. $this->meta = new WP_REST_Post_Meta_Fields( $this->post_type );
  51. }
  52. /**
  53. * Registers the routes for posts.
  54. *
  55. * @since 4.7.0
  56. *
  57. * @see register_rest_route()
  58. */
  59. public function register_routes() {
  60. register_rest_route(
  61. $this->namespace,
  62. '/' . $this->rest_base,
  63. array(
  64. array(
  65. 'methods' => WP_REST_Server::READABLE,
  66. 'callback' => array( $this, 'get_items' ),
  67. 'permission_callback' => array( $this, 'get_items_permissions_check' ),
  68. 'args' => $this->get_collection_params(),
  69. ),
  70. array(
  71. 'methods' => WP_REST_Server::CREATABLE,
  72. 'callback' => array( $this, 'create_item' ),
  73. 'permission_callback' => array( $this, 'create_item_permissions_check' ),
  74. 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ),
  75. ),
  76. 'schema' => array( $this, 'get_public_item_schema' ),
  77. )
  78. );
  79. $schema = $this->get_item_schema();
  80. $get_item_args = array(
  81. 'context' => $this->get_context_param( array( 'default' => 'view' ) ),
  82. );
  83. if ( isset( $schema['properties']['password'] ) ) {
  84. $get_item_args['password'] = array(
  85. 'description' => __( 'The password for the post if it is password protected.' ),
  86. 'type' => 'string',
  87. );
  88. }
  89. register_rest_route(
  90. $this->namespace,
  91. '/' . $this->rest_base . '/(?P<id>[\d]+)',
  92. array(
  93. 'args' => array(
  94. 'id' => array(
  95. 'description' => __( 'Unique identifier for the post.' ),
  96. 'type' => 'integer',
  97. ),
  98. ),
  99. array(
  100. 'methods' => WP_REST_Server::READABLE,
  101. 'callback' => array( $this, 'get_item' ),
  102. 'permission_callback' => array( $this, 'get_item_permissions_check' ),
  103. 'args' => $get_item_args,
  104. ),
  105. array(
  106. 'methods' => WP_REST_Server::EDITABLE,
  107. 'callback' => array( $this, 'update_item' ),
  108. 'permission_callback' => array( $this, 'update_item_permissions_check' ),
  109. 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
  110. ),
  111. array(
  112. 'methods' => WP_REST_Server::DELETABLE,
  113. 'callback' => array( $this, 'delete_item' ),
  114. 'permission_callback' => array( $this, 'delete_item_permissions_check' ),
  115. 'args' => array(
  116. 'force' => array(
  117. 'type' => 'boolean',
  118. 'default' => false,
  119. 'description' => __( 'Whether to bypass Trash and force deletion.' ),
  120. ),
  121. ),
  122. ),
  123. 'schema' => array( $this, 'get_public_item_schema' ),
  124. )
  125. );
  126. }
  127. /**
  128. * Checks if a given request has access to read posts.
  129. *
  130. * @since 4.7.0
  131. *
  132. * @param WP_REST_Request $request Full details about the request.
  133. * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
  134. */
  135. public function get_items_permissions_check( $request ) {
  136. $post_type = get_post_type_object( $this->post_type );
  137. if ( 'edit' === $request['context'] && ! current_user_can( $post_type->cap->edit_posts ) ) {
  138. return new WP_Error(
  139. 'rest_forbidden_context',
  140. __( 'Sorry, you are not allowed to edit posts in this post type.' ),
  141. array( 'status' => rest_authorization_required_code() )
  142. );
  143. }
  144. return true;
  145. }
  146. /**
  147. * Override the result of the post password check for REST requested posts.
  148. *
  149. * Allow users to read the content of password protected posts if they have
  150. * previously passed a permission check or if they have the `edit_post` capability
  151. * for the post being checked.
  152. *
  153. * @since 5.7.1
  154. *
  155. * @param bool $required Whether the post requires a password check.
  156. * @param WP_Post $post The post been password checked.
  157. * @return bool Result of password check taking in to account REST API considerations.
  158. */
  159. public function check_password_required( $required, $post ) {
  160. if ( ! $required ) {
  161. return $required;
  162. }
  163. $post = get_post( $post );
  164. if ( ! $post ) {
  165. return $required;
  166. }
  167. if ( ! empty( $this->password_check_passed[ $post->ID ] ) ) {
  168. // Password previously checked and approved.
  169. return false;
  170. }
  171. return ! current_user_can( 'edit_post', $post->ID );
  172. }
  173. /**
  174. * Retrieves a collection of posts.
  175. *
  176. * @since 4.7.0
  177. *
  178. * @param WP_REST_Request $request Full details about the request.
  179. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  180. */
  181. public function get_items( $request ) {
  182. // Ensure a search string is set in case the orderby is set to 'relevance'.
  183. if ( ! empty( $request['orderby'] ) && 'relevance' === $request['orderby'] && empty( $request['search'] ) ) {
  184. return new WP_Error(
  185. 'rest_no_search_term_defined',
  186. __( 'You need to define a search term to order by relevance.' ),
  187. array( 'status' => 400 )
  188. );
  189. }
  190. // Ensure an include parameter is set in case the orderby is set to 'include'.
  191. if ( ! empty( $request['orderby'] ) && 'include' === $request['orderby'] && empty( $request['include'] ) ) {
  192. return new WP_Error(
  193. 'rest_orderby_include_missing_include',
  194. __( 'You need to define an include parameter to order by include.' ),
  195. array( 'status' => 400 )
  196. );
  197. }
  198. // Retrieve the list of registered collection query parameters.
  199. $registered = $this->get_collection_params();
  200. $args = array();
  201. /*
  202. * This array defines mappings between public API query parameters whose
  203. * values are accepted as-passed, and their internal WP_Query parameter
  204. * name equivalents (some are the same). Only values which are also
  205. * present in $registered will be set.
  206. */
  207. $parameter_mappings = array(
  208. 'author' => 'author__in',
  209. 'author_exclude' => 'author__not_in',
  210. 'exclude' => 'post__not_in',
  211. 'include' => 'post__in',
  212. 'menu_order' => 'menu_order',
  213. 'offset' => 'offset',
  214. 'order' => 'order',
  215. 'orderby' => 'orderby',
  216. 'page' => 'paged',
  217. 'parent' => 'post_parent__in',
  218. 'parent_exclude' => 'post_parent__not_in',
  219. 'search' => 's',
  220. 'slug' => 'post_name__in',
  221. 'status' => 'post_status',
  222. );
  223. /*
  224. * For each known parameter which is both registered and present in the request,
  225. * set the parameter's value on the query $args.
  226. */
  227. foreach ( $parameter_mappings as $api_param => $wp_param ) {
  228. if ( isset( $registered[ $api_param ], $request[ $api_param ] ) ) {
  229. $args[ $wp_param ] = $request[ $api_param ];
  230. }
  231. }
  232. // Check for & assign any parameters which require special handling or setting.
  233. $args['date_query'] = array();
  234. if ( isset( $registered['before'], $request['before'] ) ) {
  235. $args['date_query'][] = array(
  236. 'before' => $request['before'],
  237. 'column' => 'post_date',
  238. );
  239. }
  240. if ( isset( $registered['modified_before'], $request['modified_before'] ) ) {
  241. $args['date_query'][] = array(
  242. 'before' => $request['modified_before'],
  243. 'column' => 'post_modified',
  244. );
  245. }
  246. if ( isset( $registered['after'], $request['after'] ) ) {
  247. $args['date_query'][] = array(
  248. 'after' => $request['after'],
  249. 'column' => 'post_date',
  250. );
  251. }
  252. if ( isset( $registered['modified_after'], $request['modified_after'] ) ) {
  253. $args['date_query'][] = array(
  254. 'after' => $request['modified_after'],
  255. 'column' => 'post_modified',
  256. );
  257. }
  258. // Ensure our per_page parameter overrides any provided posts_per_page filter.
  259. if ( isset( $registered['per_page'] ) ) {
  260. $args['posts_per_page'] = $request['per_page'];
  261. }
  262. if ( isset( $registered['sticky'], $request['sticky'] ) ) {
  263. $sticky_posts = get_option( 'sticky_posts', array() );
  264. if ( ! is_array( $sticky_posts ) ) {
  265. $sticky_posts = array();
  266. }
  267. if ( $request['sticky'] ) {
  268. /*
  269. * As post__in will be used to only get sticky posts,
  270. * we have to support the case where post__in was already
  271. * specified.
  272. */
  273. $args['post__in'] = $args['post__in'] ? array_intersect( $sticky_posts, $args['post__in'] ) : $sticky_posts;
  274. /*
  275. * If we intersected, but there are no post IDs in common,
  276. * WP_Query won't return "no posts" for post__in = array()
  277. * so we have to fake it a bit.
  278. */
  279. if ( ! $args['post__in'] ) {
  280. $args['post__in'] = array( 0 );
  281. }
  282. } elseif ( $sticky_posts ) {
  283. /*
  284. * As post___not_in will be used to only get posts that
  285. * are not sticky, we have to support the case where post__not_in
  286. * was already specified.
  287. */
  288. $args['post__not_in'] = array_merge( $args['post__not_in'], $sticky_posts );
  289. }
  290. }
  291. $args = $this->prepare_tax_query( $args, $request );
  292. // Force the post_type argument, since it's not a user input variable.
  293. $args['post_type'] = $this->post_type;
  294. /**
  295. * Filters WP_Query arguments when querying posts via the REST API.
  296. *
  297. * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
  298. *
  299. * Possible hook names include:
  300. *
  301. * - `rest_post_query`
  302. * - `rest_page_query`
  303. * - `rest_attachment_query`
  304. *
  305. * Enables adding extra arguments or setting defaults for a post collection request.
  306. *
  307. * @since 4.7.0
  308. * @since 5.7.0 Moved after the `tax_query` query arg is generated.
  309. *
  310. * @link https://developer.wordpress.org/reference/classes/wp_query/
  311. *
  312. * @param array $args Array of arguments for WP_Query.
  313. * @param WP_REST_Request $request The REST API request.
  314. */
  315. $args = apply_filters( "rest_{$this->post_type}_query", $args, $request );
  316. $query_args = $this->prepare_items_query( $args, $request );
  317. $posts_query = new WP_Query();
  318. $query_result = $posts_query->query( $query_args );
  319. // Allow access to all password protected posts if the context is edit.
  320. if ( 'edit' === $request['context'] ) {
  321. add_filter( 'post_password_required', array( $this, 'check_password_required' ), 10, 2 );
  322. }
  323. $posts = array();
  324. foreach ( $query_result as $post ) {
  325. if ( ! $this->check_read_permission( $post ) ) {
  326. continue;
  327. }
  328. $data = $this->prepare_item_for_response( $post, $request );
  329. $posts[] = $this->prepare_response_for_collection( $data );
  330. }
  331. // Reset filter.
  332. if ( 'edit' === $request['context'] ) {
  333. remove_filter( 'post_password_required', array( $this, 'check_password_required' ) );
  334. }
  335. $page = (int) $query_args['paged'];
  336. $total_posts = $posts_query->found_posts;
  337. if ( $total_posts < 1 ) {
  338. // Out-of-bounds, run the query again without LIMIT for total count.
  339. unset( $query_args['paged'] );
  340. $count_query = new WP_Query();
  341. $count_query->query( $query_args );
  342. $total_posts = $count_query->found_posts;
  343. }
  344. $max_pages = ceil( $total_posts / (int) $posts_query->query_vars['posts_per_page'] );
  345. if ( $page > $max_pages && $total_posts > 0 ) {
  346. return new WP_Error(
  347. 'rest_post_invalid_page_number',
  348. __( 'The page number requested is larger than the number of pages available.' ),
  349. array( 'status' => 400 )
  350. );
  351. }
  352. $response = rest_ensure_response( $posts );
  353. $response->header( 'X-WP-Total', (int) $total_posts );
  354. $response->header( 'X-WP-TotalPages', (int) $max_pages );
  355. $request_params = $request->get_query_params();
  356. $base = add_query_arg( urlencode_deep( $request_params ), rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ) );
  357. if ( $page > 1 ) {
  358. $prev_page = $page - 1;
  359. if ( $prev_page > $max_pages ) {
  360. $prev_page = $max_pages;
  361. }
  362. $prev_link = add_query_arg( 'page', $prev_page, $base );
  363. $response->link_header( 'prev', $prev_link );
  364. }
  365. if ( $max_pages > $page ) {
  366. $next_page = $page + 1;
  367. $next_link = add_query_arg( 'page', $next_page, $base );
  368. $response->link_header( 'next', $next_link );
  369. }
  370. return $response;
  371. }
  372. /**
  373. * Get the post, if the ID is valid.
  374. *
  375. * @since 4.7.2
  376. *
  377. * @param int $id Supplied ID.
  378. * @return WP_Post|WP_Error Post object if ID is valid, WP_Error otherwise.
  379. */
  380. protected function get_post( $id ) {
  381. $error = new WP_Error(
  382. 'rest_post_invalid_id',
  383. __( 'Invalid post ID.' ),
  384. array( 'status' => 404 )
  385. );
  386. if ( (int) $id <= 0 ) {
  387. return $error;
  388. }
  389. $post = get_post( (int) $id );
  390. if ( empty( $post ) || empty( $post->ID ) || $this->post_type !== $post->post_type ) {
  391. return $error;
  392. }
  393. return $post;
  394. }
  395. /**
  396. * Checks if a given request has access to read a post.
  397. *
  398. * @since 4.7.0
  399. *
  400. * @param WP_REST_Request $request Full details about the request.
  401. * @return true|WP_Error True if the request has read access for the item, WP_Error object otherwise.
  402. */
  403. public function get_item_permissions_check( $request ) {
  404. $post = $this->get_post( $request['id'] );
  405. if ( is_wp_error( $post ) ) {
  406. return $post;
  407. }
  408. if ( 'edit' === $request['context'] && $post && ! $this->check_update_permission( $post ) ) {
  409. return new WP_Error(
  410. 'rest_forbidden_context',
  411. __( 'Sorry, you are not allowed to edit this post.' ),
  412. array( 'status' => rest_authorization_required_code() )
  413. );
  414. }
  415. if ( $post && ! empty( $request['password'] ) ) {
  416. // Check post password, and return error if invalid.
  417. if ( ! hash_equals( $post->post_password, $request['password'] ) ) {
  418. return new WP_Error(
  419. 'rest_post_incorrect_password',
  420. __( 'Incorrect post password.' ),
  421. array( 'status' => 403 )
  422. );
  423. }
  424. }
  425. // Allow access to all password protected posts if the context is edit.
  426. if ( 'edit' === $request['context'] ) {
  427. add_filter( 'post_password_required', array( $this, 'check_password_required' ), 10, 2 );
  428. }
  429. if ( $post ) {
  430. return $this->check_read_permission( $post );
  431. }
  432. return true;
  433. }
  434. /**
  435. * Checks if the user can access password-protected content.
  436. *
  437. * This method determines whether we need to override the regular password
  438. * check in core with a filter.
  439. *
  440. * @since 4.7.0
  441. *
  442. * @param WP_Post $post Post to check against.
  443. * @param WP_REST_Request $request Request data to check.
  444. * @return bool True if the user can access password-protected content, otherwise false.
  445. */
  446. public function can_access_password_content( $post, $request ) {
  447. if ( empty( $post->post_password ) ) {
  448. // No filter required.
  449. return false;
  450. }
  451. /*
  452. * Users always gets access to password protected content in the edit
  453. * context if they have the `edit_post` meta capability.
  454. */
  455. if (
  456. 'edit' === $request['context'] &&
  457. current_user_can( 'edit_post', $post->ID )
  458. ) {
  459. return true;
  460. }
  461. // No password, no auth.
  462. if ( empty( $request['password'] ) ) {
  463. return false;
  464. }
  465. // Double-check the request password.
  466. return hash_equals( $post->post_password, $request['password'] );
  467. }
  468. /**
  469. * Retrieves a single post.
  470. *
  471. * @since 4.7.0
  472. *
  473. * @param WP_REST_Request $request Full details about the request.
  474. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  475. */
  476. public function get_item( $request ) {
  477. $post = $this->get_post( $request['id'] );
  478. if ( is_wp_error( $post ) ) {
  479. return $post;
  480. }
  481. $data = $this->prepare_item_for_response( $post, $request );
  482. $response = rest_ensure_response( $data );
  483. if ( is_post_type_viewable( get_post_type_object( $post->post_type ) ) ) {
  484. $response->link_header( 'alternate', get_permalink( $post->ID ), array( 'type' => 'text/html' ) );
  485. }
  486. return $response;
  487. }
  488. /**
  489. * Checks if a given request has access to create a post.
  490. *
  491. * @since 4.7.0
  492. *
  493. * @param WP_REST_Request $request Full details about the request.
  494. * @return true|WP_Error True if the request has access to create items, WP_Error object otherwise.
  495. */
  496. public function create_item_permissions_check( $request ) {
  497. if ( ! empty( $request['id'] ) ) {
  498. return new WP_Error(
  499. 'rest_post_exists',
  500. __( 'Cannot create existing post.' ),
  501. array( 'status' => 400 )
  502. );
  503. }
  504. $post_type = get_post_type_object( $this->post_type );
  505. if ( ! empty( $request['author'] ) && get_current_user_id() !== $request['author'] && ! current_user_can( $post_type->cap->edit_others_posts ) ) {
  506. return new WP_Error(
  507. 'rest_cannot_edit_others',
  508. __( 'Sorry, you are not allowed to create posts as this user.' ),
  509. array( 'status' => rest_authorization_required_code() )
  510. );
  511. }
  512. if ( ! empty( $request['sticky'] ) && ! current_user_can( $post_type->cap->edit_others_posts ) && ! current_user_can( $post_type->cap->publish_posts ) ) {
  513. return new WP_Error(
  514. 'rest_cannot_assign_sticky',
  515. __( 'Sorry, you are not allowed to make posts sticky.' ),
  516. array( 'status' => rest_authorization_required_code() )
  517. );
  518. }
  519. if ( ! current_user_can( $post_type->cap->create_posts ) ) {
  520. return new WP_Error(
  521. 'rest_cannot_create',
  522. __( 'Sorry, you are not allowed to create posts as this user.' ),
  523. array( 'status' => rest_authorization_required_code() )
  524. );
  525. }
  526. if ( ! $this->check_assign_terms_permission( $request ) ) {
  527. return new WP_Error(
  528. 'rest_cannot_assign_term',
  529. __( 'Sorry, you are not allowed to assign the provided terms.' ),
  530. array( 'status' => rest_authorization_required_code() )
  531. );
  532. }
  533. return true;
  534. }
  535. /**
  536. * Creates a single post.
  537. *
  538. * @since 4.7.0
  539. *
  540. * @param WP_REST_Request $request Full details about the request.
  541. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  542. */
  543. public function create_item( $request ) {
  544. if ( ! empty( $request['id'] ) ) {
  545. return new WP_Error(
  546. 'rest_post_exists',
  547. __( 'Cannot create existing post.' ),
  548. array( 'status' => 400 )
  549. );
  550. }
  551. $prepared_post = $this->prepare_item_for_database( $request );
  552. if ( is_wp_error( $prepared_post ) ) {
  553. return $prepared_post;
  554. }
  555. $prepared_post->post_type = $this->post_type;
  556. $post_id = wp_insert_post( wp_slash( (array) $prepared_post ), true, false );
  557. if ( is_wp_error( $post_id ) ) {
  558. if ( 'db_insert_error' === $post_id->get_error_code() ) {
  559. $post_id->add_data( array( 'status' => 500 ) );
  560. } else {
  561. $post_id->add_data( array( 'status' => 400 ) );
  562. }
  563. return $post_id;
  564. }
  565. $post = get_post( $post_id );
  566. /**
  567. * Fires after a single post is created or updated via the REST API.
  568. *
  569. * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
  570. *
  571. * Possible hook names include:
  572. *
  573. * - `rest_insert_post`
  574. * - `rest_insert_page`
  575. * - `rest_insert_attachment`
  576. *
  577. * @since 4.7.0
  578. *
  579. * @param WP_Post $post Inserted or updated post object.
  580. * @param WP_REST_Request $request Request object.
  581. * @param bool $creating True when creating a post, false when updating.
  582. */
  583. do_action( "rest_insert_{$this->post_type}", $post, $request, true );
  584. $schema = $this->get_item_schema();
  585. if ( ! empty( $schema['properties']['sticky'] ) ) {
  586. if ( ! empty( $request['sticky'] ) ) {
  587. stick_post( $post_id );
  588. } else {
  589. unstick_post( $post_id );
  590. }
  591. }
  592. if ( ! empty( $schema['properties']['featured_media'] ) && isset( $request['featured_media'] ) ) {
  593. $this->handle_featured_media( $request['featured_media'], $post_id );
  594. }
  595. if ( ! empty( $schema['properties']['format'] ) && ! empty( $request['format'] ) ) {
  596. set_post_format( $post, $request['format'] );
  597. }
  598. if ( ! empty( $schema['properties']['template'] ) && isset( $request['template'] ) ) {
  599. $this->handle_template( $request['template'], $post_id, true );
  600. }
  601. $terms_update = $this->handle_terms( $post_id, $request );
  602. if ( is_wp_error( $terms_update ) ) {
  603. return $terms_update;
  604. }
  605. if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
  606. $meta_update = $this->meta->update_value( $request['meta'], $post_id );
  607. if ( is_wp_error( $meta_update ) ) {
  608. return $meta_update;
  609. }
  610. }
  611. $post = get_post( $post_id );
  612. $fields_update = $this->update_additional_fields_for_object( $post, $request );
  613. if ( is_wp_error( $fields_update ) ) {
  614. return $fields_update;
  615. }
  616. $request->set_param( 'context', 'edit' );
  617. /**
  618. * Fires after a single post is completely created or updated via the REST API.
  619. *
  620. * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
  621. *
  622. * Possible hook names include:
  623. *
  624. * - `rest_after_insert_post`
  625. * - `rest_after_insert_page`
  626. * - `rest_after_insert_attachment`
  627. *
  628. * @since 5.0.0
  629. *
  630. * @param WP_Post $post Inserted or updated post object.
  631. * @param WP_REST_Request $request Request object.
  632. * @param bool $creating True when creating a post, false when updating.
  633. */
  634. do_action( "rest_after_insert_{$this->post_type}", $post, $request, true );
  635. wp_after_insert_post( $post, false, null );
  636. $response = $this->prepare_item_for_response( $post, $request );
  637. $response = rest_ensure_response( $response );
  638. $response->set_status( 201 );
  639. $response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $post_id ) ) );
  640. return $response;
  641. }
  642. /**
  643. * Checks if a given request has access to update a post.
  644. *
  645. * @since 4.7.0
  646. *
  647. * @param WP_REST_Request $request Full details about the request.
  648. * @return true|WP_Error True if the request has access to update the item, WP_Error object otherwise.
  649. */
  650. public function update_item_permissions_check( $request ) {
  651. $post = $this->get_post( $request['id'] );
  652. if ( is_wp_error( $post ) ) {
  653. return $post;
  654. }
  655. $post_type = get_post_type_object( $this->post_type );
  656. if ( $post && ! $this->check_update_permission( $post ) ) {
  657. return new WP_Error(
  658. 'rest_cannot_edit',
  659. __( 'Sorry, you are not allowed to edit this post.' ),
  660. array( 'status' => rest_authorization_required_code() )
  661. );
  662. }
  663. if ( ! empty( $request['author'] ) && get_current_user_id() !== $request['author'] && ! current_user_can( $post_type->cap->edit_others_posts ) ) {
  664. return new WP_Error(
  665. 'rest_cannot_edit_others',
  666. __( 'Sorry, you are not allowed to update posts as this user.' ),
  667. array( 'status' => rest_authorization_required_code() )
  668. );
  669. }
  670. if ( ! empty( $request['sticky'] ) && ! current_user_can( $post_type->cap->edit_others_posts ) && ! current_user_can( $post_type->cap->publish_posts ) ) {
  671. return new WP_Error(
  672. 'rest_cannot_assign_sticky',
  673. __( 'Sorry, you are not allowed to make posts sticky.' ),
  674. array( 'status' => rest_authorization_required_code() )
  675. );
  676. }
  677. if ( ! $this->check_assign_terms_permission( $request ) ) {
  678. return new WP_Error(
  679. 'rest_cannot_assign_term',
  680. __( 'Sorry, you are not allowed to assign the provided terms.' ),
  681. array( 'status' => rest_authorization_required_code() )
  682. );
  683. }
  684. return true;
  685. }
  686. /**
  687. * Updates a single post.
  688. *
  689. * @since 4.7.0
  690. *
  691. * @param WP_REST_Request $request Full details about the request.
  692. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  693. */
  694. public function update_item( $request ) {
  695. $valid_check = $this->get_post( $request['id'] );
  696. if ( is_wp_error( $valid_check ) ) {
  697. return $valid_check;
  698. }
  699. $post_before = get_post( $request['id'] );
  700. $post = $this->prepare_item_for_database( $request );
  701. if ( is_wp_error( $post ) ) {
  702. return $post;
  703. }
  704. // Convert the post object to an array, otherwise wp_update_post() will expect non-escaped input.
  705. $post_id = wp_update_post( wp_slash( (array) $post ), true, false );
  706. if ( is_wp_error( $post_id ) ) {
  707. if ( 'db_update_error' === $post_id->get_error_code() ) {
  708. $post_id->add_data( array( 'status' => 500 ) );
  709. } else {
  710. $post_id->add_data( array( 'status' => 400 ) );
  711. }
  712. return $post_id;
  713. }
  714. $post = get_post( $post_id );
  715. /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php */
  716. do_action( "rest_insert_{$this->post_type}", $post, $request, false );
  717. $schema = $this->get_item_schema();
  718. if ( ! empty( $schema['properties']['format'] ) && ! empty( $request['format'] ) ) {
  719. set_post_format( $post, $request['format'] );
  720. }
  721. if ( ! empty( $schema['properties']['featured_media'] ) && isset( $request['featured_media'] ) ) {
  722. $this->handle_featured_media( $request['featured_media'], $post_id );
  723. }
  724. if ( ! empty( $schema['properties']['sticky'] ) && isset( $request['sticky'] ) ) {
  725. if ( ! empty( $request['sticky'] ) ) {
  726. stick_post( $post_id );
  727. } else {
  728. unstick_post( $post_id );
  729. }
  730. }
  731. if ( ! empty( $schema['properties']['template'] ) && isset( $request['template'] ) ) {
  732. $this->handle_template( $request['template'], $post->ID );
  733. }
  734. $terms_update = $this->handle_terms( $post->ID, $request );
  735. if ( is_wp_error( $terms_update ) ) {
  736. return $terms_update;
  737. }
  738. if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
  739. $meta_update = $this->meta->update_value( $request['meta'], $post->ID );
  740. if ( is_wp_error( $meta_update ) ) {
  741. return $meta_update;
  742. }
  743. }
  744. $post = get_post( $post_id );
  745. $fields_update = $this->update_additional_fields_for_object( $post, $request );
  746. if ( is_wp_error( $fields_update ) ) {
  747. return $fields_update;
  748. }
  749. $request->set_param( 'context', 'edit' );
  750. // Filter is fired in WP_REST_Attachments_Controller subclass.
  751. if ( 'attachment' === $this->post_type ) {
  752. $response = $this->prepare_item_for_response( $post, $request );
  753. return rest_ensure_response( $response );
  754. }
  755. /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php */
  756. do_action( "rest_after_insert_{$this->post_type}", $post, $request, false );
  757. wp_after_insert_post( $post, true, $post_before );
  758. $response = $this->prepare_item_for_response( $post, $request );
  759. return rest_ensure_response( $response );
  760. }
  761. /**
  762. * Checks if a given request has access to delete a post.
  763. *
  764. * @since 4.7.0
  765. *
  766. * @param WP_REST_Request $request Full details about the request.
  767. * @return true|WP_Error True if the request has access to delete the item, WP_Error object otherwise.
  768. */
  769. public function delete_item_permissions_check( $request ) {
  770. $post = $this->get_post( $request['id'] );
  771. if ( is_wp_error( $post ) ) {
  772. return $post;
  773. }
  774. if ( $post && ! $this->check_delete_permission( $post ) ) {
  775. return new WP_Error(
  776. 'rest_cannot_delete',
  777. __( 'Sorry, you are not allowed to delete this post.' ),
  778. array( 'status' => rest_authorization_required_code() )
  779. );
  780. }
  781. return true;
  782. }
  783. /**
  784. * Deletes a single post.
  785. *
  786. * @since 4.7.0
  787. *
  788. * @param WP_REST_Request $request Full details about the request.
  789. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  790. */
  791. public function delete_item( $request ) {
  792. $post = $this->get_post( $request['id'] );
  793. if ( is_wp_error( $post ) ) {
  794. return $post;
  795. }
  796. $id = $post->ID;
  797. $force = (bool) $request['force'];
  798. $supports_trash = ( EMPTY_TRASH_DAYS > 0 );
  799. if ( 'attachment' === $post->post_type ) {
  800. $supports_trash = $supports_trash && MEDIA_TRASH;
  801. }
  802. /**
  803. * Filters whether a post is trashable.
  804. *
  805. * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
  806. *
  807. * Possible hook names include:
  808. *
  809. * - `rest_post_trashable`
  810. * - `rest_page_trashable`
  811. * - `rest_attachment_trashable`
  812. *
  813. * Pass false to disable Trash support for the post.
  814. *
  815. * @since 4.7.0
  816. *
  817. * @param bool $supports_trash Whether the post type support trashing.
  818. * @param WP_Post $post The Post object being considered for trashing support.
  819. */
  820. $supports_trash = apply_filters( "rest_{$this->post_type}_trashable", $supports_trash, $post );
  821. if ( ! $this->check_delete_permission( $post ) ) {
  822. return new WP_Error(
  823. 'rest_user_cannot_delete_post',
  824. __( 'Sorry, you are not allowed to delete this post.' ),
  825. array( 'status' => rest_authorization_required_code() )
  826. );
  827. }
  828. $request->set_param( 'context', 'edit' );
  829. // If we're forcing, then delete permanently.
  830. if ( $force ) {
  831. $previous = $this->prepare_item_for_response( $post, $request );
  832. $result = wp_delete_post( $id, true );
  833. $response = new WP_REST_Response();
  834. $response->set_data(
  835. array(
  836. 'deleted' => true,
  837. 'previous' => $previous->get_data(),
  838. )
  839. );
  840. } else {
  841. // If we don't support trashing for this type, error out.
  842. if ( ! $supports_trash ) {
  843. return new WP_Error(
  844. 'rest_trash_not_supported',
  845. /* translators: %s: force=true */
  846. sprintf( __( "The post does not support trashing. Set '%s' to delete." ), 'force=true' ),
  847. array( 'status' => 501 )
  848. );
  849. }
  850. // Otherwise, only trash if we haven't already.
  851. if ( 'trash' === $post->post_status ) {
  852. return new WP_Error(
  853. 'rest_already_trashed',
  854. __( 'The post has already been deleted.' ),
  855. array( 'status' => 410 )
  856. );
  857. }
  858. // (Note that internally this falls through to `wp_delete_post()`
  859. // if the Trash is disabled.)
  860. $result = wp_trash_post( $id );
  861. $post = get_post( $id );
  862. $response = $this->prepare_item_for_response( $post, $request );
  863. }
  864. if ( ! $result ) {
  865. return new WP_Error(
  866. 'rest_cannot_delete',
  867. __( 'The post cannot be deleted.' ),
  868. array( 'status' => 500 )
  869. );
  870. }
  871. /**
  872. * Fires immediately after a single post is deleted or trashed via the REST API.
  873. *
  874. * They dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
  875. *
  876. * @since 4.7.0
  877. *
  878. * @param WP_Post $post The deleted or trashed post.
  879. * @param WP_REST_Response $response The response data.
  880. * @param WP_REST_Request $request The request sent to the API.
  881. */
  882. do_action( "rest_delete_{$this->post_type}", $post, $response, $request );
  883. return $response;
  884. }
  885. /**
  886. * Determines the allowed query_vars for a get_items() response and prepares
  887. * them for WP_Query.
  888. *
  889. * @since 4.7.0
  890. *
  891. * @param array $prepared_args Optional. Prepared WP_Query arguments. Default empty array.
  892. * @param WP_REST_Request $request Optional. Full details about the request.
  893. * @return array Items query arguments.
  894. */
  895. protected function prepare_items_query( $prepared_args = array(), $request = null ) {
  896. $query_args = array();
  897. foreach ( $prepared_args as $key => $value ) {
  898. /**
  899. * Filters the query_vars used in get_items() for the constructed query.
  900. *
  901. * The dynamic portion of the hook name, `$key`, refers to the query_var key.
  902. *
  903. * @since 4.7.0
  904. *
  905. * @param string $value The query_var value.
  906. */
  907. $query_args[ $key ] = apply_filters( "rest_query_var-{$key}", $value ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
  908. }
  909. if ( 'post' !== $this->post_type || ! isset( $query_args['ignore_sticky_posts'] ) ) {
  910. $query_args['ignore_sticky_posts'] = true;
  911. }
  912. // Map to proper WP_Query orderby param.
  913. if ( isset( $query_args['orderby'] ) && isset( $request['orderby'] ) ) {
  914. $orderby_mappings = array(
  915. 'id' => 'ID',
  916. 'include' => 'post__in',
  917. 'slug' => 'post_name',
  918. 'include_slugs' => 'post_name__in',
  919. );
  920. if ( isset( $orderby_mappings[ $request['orderby'] ] ) ) {
  921. $query_args['orderby'] = $orderby_mappings[ $request['orderby'] ];
  922. }
  923. }
  924. return $query_args;
  925. }
  926. /**
  927. * Checks the post_date_gmt or modified_gmt and prepare any post or
  928. * modified date for single post output.
  929. *
  930. * @since 4.7.0
  931. *
  932. * @param string $date_gmt GMT publication time.
  933. * @param string|null $date Optional. Local publication time. Default null.
  934. * @return string|null ISO8601/RFC3339 formatted datetime.
  935. */
  936. protected function prepare_date_response( $date_gmt, $date = null ) {
  937. // Use the date if passed.
  938. if ( isset( $date ) ) {
  939. return mysql_to_rfc3339( $date );
  940. }
  941. // Return null if $date_gmt is empty/zeros.
  942. if ( '0000-00-00 00:00:00' === $date_gmt ) {
  943. return null;
  944. }
  945. // Return the formatted datetime.
  946. return mysql_to_rfc3339( $date_gmt );
  947. }
  948. /**
  949. * Prepares a single post for create or update.
  950. *
  951. * @since 4.7.0
  952. *
  953. * @param WP_REST_Request $request Request object.
  954. * @return stdClass|WP_Error Post object or WP_Error.
  955. */
  956. protected function prepare_item_for_database( $request ) {
  957. $prepared_post = new stdClass();
  958. $current_status = '';
  959. // Post ID.
  960. if ( isset( $request['id'] ) ) {
  961. $existing_post = $this->get_post( $request['id'] );
  962. if ( is_wp_error( $existing_post ) ) {
  963. return $existing_post;
  964. }
  965. $prepared_post->ID = $existing_post->ID;
  966. $current_status = $existing_post->post_status;
  967. }
  968. $schema = $this->get_item_schema();
  969. // Post title.
  970. if ( ! empty( $schema['properties']['title'] ) && isset( $request['title'] ) ) {
  971. if ( is_string( $request['title'] ) ) {
  972. $prepared_post->post_title = $request['title'];
  973. } elseif ( ! empty( $request['title']['raw'] ) ) {
  974. $prepared_post->post_title = $request['title']['raw'];
  975. }
  976. }
  977. // Post content.
  978. if ( ! empty( $schema['properties']['content'] ) && isset( $request['content'] ) ) {
  979. if ( is_string( $request['content'] ) ) {
  980. $prepared_post->post_content = $request['content'];
  981. } elseif ( isset( $request['content']['raw'] ) ) {
  982. $prepared_post->post_content = $request['content']['raw'];
  983. }
  984. }
  985. // Post excerpt.
  986. if ( ! empty( $schema['properties']['excerpt'] ) && isset( $request['excerpt'] ) ) {
  987. if ( is_string( $request['excerpt'] ) ) {
  988. $prepared_post->post_excerpt = $request['excerpt'];
  989. } elseif ( isset( $request['excerpt']['raw'] ) ) {
  990. $prepared_post->post_excerpt = $request['excerpt']['raw'];
  991. }
  992. }
  993. // Post type.
  994. if ( empty( $request['id'] ) ) {
  995. // Creating new post, use default type for the controller.
  996. $prepared_post->post_type = $this->post_type;
  997. } else {
  998. // Updating a post, use previous type.
  999. $prepared_post->post_type = get_post_type( $request['id'] );
  1000. }
  1001. $post_type = get_post_type_object( $prepared_post->post_type );
  1002. // Post status.
  1003. if (
  1004. ! empty( $schema['properties']['status'] ) &&
  1005. isset( $request['status'] ) &&
  1006. ( ! $current_status || $current_status !== $request['status'] )
  1007. ) {
  1008. $status = $this->handle_status_param( $request['status'], $post_type );
  1009. if ( is_wp_error( $status ) ) {
  1010. return $status;
  1011. }
  1012. $prepared_post->post_status = $status;
  1013. }
  1014. // Post date.
  1015. if ( ! empty( $schema['properties']['date'] ) && ! empty( $request['date'] ) ) {
  1016. $current_date = isset( $prepared_post->ID ) ? get_post( $prepared_post->ID )->post_date : false;
  1017. $date_data = rest_get_date_with_gmt( $request['date'] );
  1018. if ( ! empty( $date_data ) && $current_date !== $date_data[0] ) {
  1019. list( $prepared_post->post_date, $prepared_post->post_date_gmt ) = $date_data;
  1020. $prepared_post->edit_date = true;
  1021. }
  1022. } elseif ( ! empty( $schema['properties']['date_gmt'] ) && ! empty( $request['date_gmt'] ) ) {
  1023. $current_date = isset( $prepared_post->ID ) ? get_post( $prepared_post->ID )->post_date_gmt : false;
  1024. $date_data = rest_get_date_with_gmt( $request['date_gmt'], true );
  1025. if ( ! empty( $date_data ) && $current_date !== $date_data[1] ) {
  1026. list( $prepared_post->post_date, $prepared_post->post_date_gmt ) = $date_data;
  1027. $prepared_post->edit_date = true;
  1028. }
  1029. }
  1030. // Sending a null date or date_gmt value resets date and date_gmt to their
  1031. // default values (`0000-00-00 00:00:00`).
  1032. if (
  1033. ( ! empty( $schema['properties']['date_gmt'] ) && $request->has_param( 'date_gmt' ) && null === $request['date_gmt'] ) ||
  1034. ( ! empty( $schema['properties']['date'] ) && $request->has_param( 'date' ) && null === $request['date'] )
  1035. ) {
  1036. $prepared_post->post_date_gmt = null;
  1037. $prepared_post->post_date = null;
  1038. }
  1039. // Post slug.
  1040. if ( ! empty( $schema['properties']['slug'] ) && isset( $request['slug'] ) ) {
  1041. $prepared_post->post_name = $request['slug'];
  1042. }
  1043. // Author.
  1044. if ( ! empty( $schema['properties']['author'] ) && ! empty( $request['author'] ) ) {
  1045. $post_author = (int) $request['author'];
  1046. if ( get_current_user_id() !== $post_author ) {
  1047. $user_obj = get_userdata( $post_author );
  1048. if ( ! $user_obj ) {
  1049. return new WP_Error(
  1050. 'rest_invalid_author',
  1051. __( 'Invalid author ID.' ),
  1052. array( 'status' => 400 )
  1053. );
  1054. }
  1055. }
  1056. $prepared_post->post_author = $post_author;
  1057. }
  1058. // Post password.
  1059. if ( ! empty( $schema['properties']['password'] ) && isset( $request['password'] ) ) {
  1060. $prepared_post->post_password = $request['password'];
  1061. if ( '' !== $request['password'] ) {
  1062. if ( ! empty( $schema['properties']['sticky'] ) && ! empty( $request['sticky'] ) ) {
  1063. return new WP_Error(
  1064. 'rest_invalid_field',
  1065. __( 'A post can not be sticky and have a password.' ),
  1066. array( 'status' => 400 )
  1067. );
  1068. }
  1069. if ( ! empty( $prepared_post->ID ) && is_sticky( $prepared_post->ID ) ) {
  1070. return new WP_Error(
  1071. 'rest_invalid_field',
  1072. __( 'A sticky post can not be password protected.' ),
  1073. array( 'status' => 400 )
  1074. );
  1075. }
  1076. }
  1077. }
  1078. if ( ! empty( $schema['properties']['sticky'] ) && ! empty( $request['sticky'] ) ) {
  1079. if ( ! empty( $prepared_post->ID ) && post_password_required( $prepared_post->ID ) ) {
  1080. return new WP_Error(
  1081. 'rest_invalid_field',
  1082. __( 'A password protected post can not be set to sticky.' ),
  1083. array( 'status' => 400 )
  1084. );
  1085. }
  1086. }
  1087. // Parent.
  1088. if ( ! empty( $schema['properties']['parent'] ) && isset( $request['parent'] ) ) {
  1089. if ( 0 === (int) $request['parent'] ) {
  1090. $prepared_post->post_parent = 0;
  1091. } else {
  1092. $parent = get_post( (int) $request['parent'] );
  1093. if ( empty( $parent ) ) {
  1094. return new WP_Error(
  1095. 'rest_post_invalid_id',
  1096. __( 'Invalid post parent ID.' ),
  1097. array( 'status' => 400 )
  1098. );
  1099. }
  1100. $prepared_post->post_parent = (int) $parent->ID;
  1101. }
  1102. }
  1103. // Menu order.
  1104. if ( ! empty( $schema['properties']['menu_order'] ) && isset( $request['menu_order'] ) ) {
  1105. $prepared_post->menu_order = (int) $request['menu_order'];
  1106. }
  1107. // Comment status.
  1108. if ( ! empty( $schema['properties']['comment_status'] ) && ! empty( $request['comment_status'] ) ) {
  1109. $prepared_post->comment_status = $request['comment_status'];
  1110. }
  1111. // Ping status.
  1112. if ( ! empty( $schema['properties']['ping_status'] ) && ! empty( $request['ping_status'] ) ) {
  1113. $prepared_post->ping_status = $request['ping_status'];
  1114. }
  1115. if ( ! empty( $schema['properties']['template'] ) ) {
  1116. // Force template to null so that it can be handled exclusively by the REST controller.
  1117. $prepared_post->page_template = null;
  1118. }
  1119. /**
  1120. * Filters a post before it is inserted via the REST API.
  1121. *
  1122. * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
  1123. *
  1124. * Possible hook names include:
  1125. *
  1126. * - `rest_pre_insert_post`
  1127. * - `rest_pre_insert_page`
  1128. * - `rest_pre_insert_attachment`
  1129. *
  1130. * @since 4.7.0
  1131. *
  1132. * @param stdClass $prepared_post An object representing a single post prepared
  1133. * for inserting or updating the database.
  1134. * @param WP_REST_Request $request Request object.
  1135. */
  1136. return apply_filters( "rest_pre_insert_{$this->post_type}", $prepared_post, $request );
  1137. }
  1138. /**
  1139. * Checks whether the status is valid for the given post.
  1140. *
  1141. * Allows for sending an update request with the current status, even if that status would not be acceptable.
  1142. *
  1143. * @since 5.6.0
  1144. *
  1145. * @param string $status The provided status.
  1146. * @param WP_REST_Request $request The request object.
  1147. * @param string $param The parameter name.
  1148. * @return true|WP_Error True if the status is valid, or WP_Error if not.
  1149. */
  1150. public function check_status( $status, $request, $param ) {
  1151. if ( $request['id'] ) {
  1152. $post = $this->get_post( $request['id'] );
  1153. if ( ! is_wp_error( $post ) && $post->post_status === $status ) {
  1154. return true;
  1155. }
  1156. }
  1157. $args = $request->get_attributes()['args'][ $param ];
  1158. return rest_validate_value_from_schema( $status, $args, $param );
  1159. }
  1160. /**
  1161. * Determines validity and normalizes the given status parameter.
  1162. *
  1163. * @since 4.7.0
  1164. *
  1165. * @param string $post_status Post status.
  1166. * @param WP_Post_Type $post_type Post type.
  1167. * @return string|WP_Error Post status or WP_Error if lacking the proper permission.
  1168. */
  1169. protected function handle_status_param( $post_status, $post_type ) {
  1170. switch ( $post_status ) {
  1171. case 'draft':
  1172. case 'pending':
  1173. break;
  1174. case 'private':
  1175. if ( ! current_user_can( $post_type->cap->publish_posts ) ) {
  1176. return new WP_Error(
  1177. 'rest_cannot_publish',
  1178. __( 'Sorry, you are not allowed to create private posts in this post type.' ),
  1179. array( 'status' => rest_authorization_required_code() )
  1180. );
  1181. }
  1182. break;
  1183. case 'publish':
  1184. case 'future':
  1185. if ( ! current_user_can( $post_type->cap->publish_posts ) ) {
  1186. return new WP_Error(
  1187. 'rest_cannot_publish',
  1188. __( 'Sorry, you are not allowed to publish posts in this post type.' ),
  1189. array( 'status' => rest_authorization_required_code() )
  1190. );
  1191. }
  1192. break;
  1193. default:
  1194. if ( ! get_post_status_object( $post_status ) ) {
  1195. $post_status = 'draft';
  1196. }
  1197. break;
  1198. }
  1199. return $post_status;
  1200. }
  1201. /**
  1202. * Determines the featured media based on a request param.
  1203. *
  1204. * @since 4.7.0
  1205. *
  1206. * @param int $featured_media Featured Media ID.
  1207. * @param int $post_id Post ID.
  1208. * @return bool|WP_Error Whether the post thumbnail was successfully deleted, otherwise WP_Error.
  1209. */
  1210. protected function handle_featured_media( $featured_media, $post_id ) {
  1211. $featured_media = (int) $featured_media;
  1212. if ( $featured_media ) {
  1213. $result = set_post_thumbnail( $post_id, $featured_media );
  1214. if ( $result ) {
  1215. return true;
  1216. } else {
  1217. return new WP_Error(
  1218. 'rest_invalid_featured_media',
  1219. __( 'Invalid featured media ID.' ),
  1220. array( 'status' => 400 )
  1221. );
  1222. }
  1223. } else {
  1224. return delete_post_thumbnail( $post_id );
  1225. }
  1226. }
  1227. /**
  1228. * Check whether the template is valid for the given post.
  1229. *
  1230. * @since 4.9.0
  1231. *
  1232. * @param string $template Page template filename.
  1233. * @param WP_REST_Request $request Request.
  1234. * @return bool|WP_Error True if template is still valid or if the same as existing value, or false if template not supported.
  1235. */
  1236. public function check_template( $template, $request ) {
  1237. if ( ! $template ) {
  1238. return true;
  1239. }
  1240. if ( $request['id'] ) {
  1241. $post = get_post( $request['id'] );
  1242. $current_template = get_page_template_slug( $request['id'] );
  1243. } else {
  1244. $post = null;
  1245. $current_template = '';
  1246. }
  1247. // Always allow for updating a post to the same template, even if that template is no longer supported.
  1248. if ( $template === $current_template ) {
  1249. return true;
  1250. }
  1251. // If this is a create request, get_post() will return null and wp theme will fallback to the passed post type.
  1252. $allowed_templates = wp_get_theme()->get_page_templates( $post, $this->post_type );
  1253. if ( isset( $allowed_templates[ $template ] ) ) {
  1254. return true;
  1255. }
  1256. return new WP_Error(
  1257. 'rest_invalid_param',
  1258. /* translators: 1: Parameter, 2: List of valid values. */
  1259. sprintf( __( '%1$s is not one of %2$s.' ), 'template', implode( ', ', array_keys( $allowed_templates ) ) )
  1260. );
  1261. }
  1262. /**
  1263. * Sets the template for a post.
  1264. *
  1265. * @since 4.7.0
  1266. * @since 4.9.0 Added the `$validate` parameter.
  1267. *
  1268. * @param string $template Page template filename.
  1269. * @param int $post_id Post ID.
  1270. * @param bool $validate Whether to validate that the template selected is valid.
  1271. */
  1272. public function handle_template( $template, $post_id, $validate = false ) {
  1273. if ( $validate && ! array_key_exists( $template, wp_get_theme()->get_page_templates( get_post( $post_id ) ) ) ) {
  1274. $template = '';
  1275. }
  1276. update_post_meta( $post_id, '_wp_page_template', $template );
  1277. }
  1278. /**
  1279. * Updates the post's terms from a REST request.
  1280. *
  1281. * @since 4.7.0
  1282. *
  1283. * @param int $post_id The post ID to update the terms form.
  1284. * @param WP_REST_Request $request The request object with post and terms data.
  1285. * @return null|WP_Error WP_Error on an error assigning any of the terms, otherwise null.
  1286. */
  1287. protected function handle_terms( $post_id, $request ) {
  1288. $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
  1289. foreach ( $taxonomies as $taxonomy ) {
  1290. $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
  1291. if ( ! isset( $request[ $base ] ) ) {
  1292. continue;
  1293. }
  1294. $result = wp_set_object_terms( $post_id, $request[ $base ], $taxonomy->name );
  1295. if ( is_wp_error( $result ) ) {
  1296. return $result;
  1297. }
  1298. }
  1299. }
  1300. /**
  1301. * Checks whether current user can assign all terms sent with the current request.
  1302. *
  1303. * @since 4.7.0
  1304. *
  1305. * @param WP_REST_Request $request The request object with post and terms data.
  1306. * @return bool Whether the current user can assign the provided terms.
  1307. */
  1308. protected function check_assign_terms_permission( $request ) {
  1309. $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
  1310. foreach ( $taxonomies as $taxonomy ) {
  1311. $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
  1312. if ( ! isset( $request[ $base ] ) ) {
  1313. continue;
  1314. }
  1315. foreach ( $request[ $base ] as $term_id ) {
  1316. // Invalid terms will be rejected later.
  1317. if ( ! get_term( $term_id, $taxonomy->name ) ) {
  1318. continue;
  1319. }
  1320. if ( ! current_user_can( 'assign_term', (int) $term_id ) ) {
  1321. return false;
  1322. }
  1323. }
  1324. }
  1325. return true;
  1326. }
  1327. /**
  1328. * Checks if a given post type can be viewed or managed.
  1329. *
  1330. * @since 4.7.0
  1331. *
  1332. * @param WP_Post_Type|string $post_type Post type name or object.
  1333. * @return bool Whether the post type is allowed in REST.
  1334. */
  1335. protected function check_is_post_type_allowed( $post_type ) {
  1336. if ( ! is_object( $post_type ) ) {
  1337. $post_type = get_post_type_object( $post_type );
  1338. }
  1339. if ( ! empty( $post_type ) && ! empty( $post_type->show_in_rest ) ) {
  1340. return true;
  1341. }
  1342. return false;
  1343. }
  1344. /**
  1345. * Checks if a post can be read.
  1346. *
  1347. * Correctly handles posts with the inherit status.
  1348. *
  1349. * @since 4.7.0
  1350. *
  1351. * @param WP_Post $post Post object.
  1352. * @return bool Whether the post can be read.
  1353. */
  1354. public function check_read_permission( $post ) {
  1355. $post_type = get_post_type_object( $post->post_type );
  1356. if ( ! $this->check_is_post_type_allowed( $post_type ) ) {
  1357. return false;
  1358. }
  1359. // Is the post readable?
  1360. if ( 'publish' === $post->post_status || current_user_can( 'read_post', $post->ID ) ) {
  1361. return true;
  1362. }
  1363. $post_status_obj = get_post_status_object( $post->post_status );
  1364. if ( $post_status_obj && $post_status_obj->public ) {
  1365. return true;
  1366. }
  1367. // Can we read the parent if we're inheriting?
  1368. if ( 'inherit' === $post->post_status && $post->post_parent > 0 ) {
  1369. $parent = get_post( $post->post_parent );
  1370. if ( $parent ) {
  1371. return $this->check_read_permission( $parent );
  1372. }
  1373. }
  1374. /*
  1375. * If there isn't a parent, but the status is set to inherit, assume
  1376. * it's published (as per get_post_status()).
  1377. */
  1378. if ( 'inherit' === $post->post_status ) {
  1379. return true;
  1380. }
  1381. return false;
  1382. }
  1383. /**
  1384. * Checks if a post can be edited.
  1385. *
  1386. * @since 4.7.0
  1387. *
  1388. * @param WP_Post $post Post object.
  1389. * @return bool Whether the post can be edited.
  1390. */
  1391. protected function check_update_permission( $post ) {
  1392. $post_type = get_post_type_object( $post->post_type );
  1393. if ( ! $this->check_is_post_type_allowed( $post_type ) ) {
  1394. return false;
  1395. }
  1396. return current_user_can( 'edit_post', $post->ID );
  1397. }
  1398. /**
  1399. * Checks if a post can be created.
  1400. *
  1401. * @since 4.7.0
  1402. *
  1403. * @param WP_Post $post Post object.
  1404. * @return bool Whether the post can be created.
  1405. */
  1406. protected function check_create_permission( $post ) {
  1407. $post_type = get_post_type_object( $post->post_type );
  1408. if ( ! $this->check_is_post_type_allowed( $post_type ) ) {
  1409. return false;
  1410. }
  1411. return current_user_can( $post_type->cap->create_posts );
  1412. }
  1413. /**
  1414. * Checks if a post can be deleted.
  1415. *
  1416. * @since 4.7.0
  1417. *
  1418. * @param WP_Post $post Post object.
  1419. * @return bool Whether the post can be deleted.
  1420. */
  1421. protected function check_delete_permission( $post ) {
  1422. $post_type = get_post_type_object( $post->post_type );
  1423. if ( ! $this->check_is_post_type_allowed( $post_type ) ) {
  1424. return false;
  1425. }
  1426. return current_user_can( 'delete_post', $post->ID );
  1427. }
  1428. /**
  1429. * Prepares a single post output for response.
  1430. *
  1431. * @since 4.7.0
  1432. *
  1433. * @param WP_Post $post Post object.
  1434. * @param WP_REST_Request $request Request object.
  1435. * @return WP_REST_Response Response object.
  1436. */
  1437. public function prepare_item_for_response( $post, $request ) {
  1438. $GLOBALS['post'] = $post;
  1439. setup_postdata( $post );
  1440. $fields = $this->get_fields_for_response( $request );
  1441. // Base fields for every post.
  1442. $data = array();
  1443. if ( rest_is_field_included( 'id', $fields ) ) {
  1444. $data['id'] = $post->ID;
  1445. }
  1446. if ( rest_is_field_included( 'date', $fields ) ) {
  1447. $data['date'] = $this->prepare_date_response( $post->post_date_gmt, $post->post_date );
  1448. }
  1449. if ( rest_is_field_included( 'date_gmt', $fields ) ) {
  1450. /*
  1451. * For drafts, `post_date_gmt` may not be set, indicating that the date
  1452. * of the draft should be updated each time it is saved (see #38883).
  1453. * In this case, shim the value based on the `post_date` field
  1454. * with the site's timezone offset applied.
  1455. */
  1456. if ( '0000-00-00 00:00:00' === $post->post_date_gmt ) {
  1457. $post_date_gmt = get_gmt_from_date( $post->post_date );
  1458. } else {
  1459. $post_date_gmt = $post->post_date_gmt;
  1460. }
  1461. $data['date_gmt'] = $this->prepare_date_response( $post_date_gmt );
  1462. }
  1463. if ( rest_is_field_included( 'guid', $fields ) ) {
  1464. $data['guid'] = array(
  1465. /** This filter is documented in wp-includes/post-template.php */
  1466. 'rendered' => apply_filters( 'get_the_guid', $post->guid, $post->ID ),
  1467. 'raw' => $post->guid,
  1468. );
  1469. }
  1470. if ( rest_is_field_included( 'modified', $fields ) ) {
  1471. $data['modified'] = $this->prepare_date_response( $post->post_modified_gmt, $post->post_modified );
  1472. }
  1473. if ( rest_is_field_included( 'modified_gmt', $fields ) ) {
  1474. /*
  1475. * For drafts, `post_modified_gmt` may not be set (see `post_date_gmt` comments
  1476. * above). In this case, shim the value based on the `post_modified` field
  1477. * with the site's timezone offset applied.
  1478. */
  1479. if ( '0000-00-00 00:00:00' === $post->post_modified_gmt ) {
  1480. $post_modified_gmt = gmdate( 'Y-m-d H:i:s', strtotime( $post->post_modified ) - ( get_option( 'gmt_offset' ) * 3600 ) );
  1481. } else {
  1482. $post_modified_gmt = $post->post_modified_gmt;
  1483. }
  1484. $data['modified_gmt'] = $this->prepare_date_response( $post_modified_gmt );
  1485. }
  1486. if ( rest_is_field_included( 'password', $fields ) ) {
  1487. $data['password'] = $post->post_password;
  1488. }
  1489. if ( rest_is_field_included( 'slug', $fields ) ) {
  1490. $data['slug'] = $post->post_name;
  1491. }
  1492. if ( rest_is_field_included( 'status', $fields ) ) {
  1493. $data['status'] = $post->post_status;
  1494. }
  1495. if ( rest_is_field_included( 'type', $fields ) ) {
  1496. $data['type'] = $post->post_type;
  1497. }
  1498. if ( rest_is_field_included( 'link', $fields ) ) {
  1499. $data['link'] = get_permalink( $post->ID );
  1500. }
  1501. if ( rest_is_field_included( 'title', $fields ) ) {
  1502. $data['title'] = array();
  1503. }
  1504. if ( rest_is_field_included( 'title.raw', $fields ) ) {
  1505. $data['title']['raw'] = $post->post_title;
  1506. }
  1507. if ( rest_is_field_included( 'title.rendered', $fields ) ) {
  1508. add_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
  1509. $data['title']['rendered'] = get_the_title( $post->ID );
  1510. remove_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
  1511. }
  1512. $has_password_filter = false;
  1513. if ( $this->can_access_password_content( $post, $request ) ) {
  1514. $this->password_check_passed[ $post->ID ] = true;
  1515. // Allow access to the post, permissions already checked before.
  1516. add_filter( 'post_password_required', array( $this, 'check_password_required' ), 10, 2 );
  1517. $has_password_filter = true;
  1518. }
  1519. if ( rest_is_field_included( 'content', $fields ) ) {
  1520. $data['content'] = array();
  1521. }
  1522. if ( rest_is_field_included( 'content.raw', $fields ) ) {
  1523. $data['content']['raw'] = $post->post_content;
  1524. }
  1525. if ( rest_is_field_included( 'content.rendered', $fields ) ) {
  1526. /** This filter is documented in wp-includes/post-template.php */
  1527. $data['content']['rendered'] = post_password_required( $post ) ? '' : apply_filters( 'the_content', $post->post_content );
  1528. }
  1529. if ( rest_is_field_included( 'content.protected', $fields ) ) {
  1530. $data['content']['protected'] = (bool) $post->post_password;
  1531. }
  1532. if ( rest_is_field_included( 'content.block_version', $fields ) ) {
  1533. $data['content']['block_version'] = block_version( $post->post_content );
  1534. }
  1535. if ( rest_is_field_included( 'excerpt', $fields ) ) {
  1536. /** This filter is documented in wp-includes/post-template.php */
  1537. $excerpt = apply_filters( 'get_the_excerpt', $post->post_excerpt, $post );
  1538. /** This filter is documented in wp-includes/post-template.php */
  1539. $excerpt = apply_filters( 'the_excerpt', $excerpt );
  1540. $data['excerpt'] = array(
  1541. 'raw' => $post->post_excerpt,
  1542. 'rendered' => post_password_required( $post ) ? '' : $excerpt,
  1543. 'protected' => (bool) $post->post_password,
  1544. );
  1545. }
  1546. if ( $has_password_filter ) {
  1547. // Reset filter.
  1548. remove_filter( 'post_password_required', array( $this, 'check_password_required' ) );
  1549. }
  1550. if ( rest_is_field_included( 'author', $fields ) ) {
  1551. $data['author'] = (int) $post->post_author;
  1552. }
  1553. if ( rest_is_field_included( 'featured_media', $fields ) ) {
  1554. $data['featured_media'] = (int) get_post_thumbnail_id( $post->ID );
  1555. }
  1556. if ( rest_is_field_included( 'parent', $fields ) ) {
  1557. $data['parent'] = (int) $post->post_parent;
  1558. }
  1559. if ( rest_is_field_included( 'menu_order', $fields ) ) {
  1560. $data['menu_order'] = (int) $post->menu_order;
  1561. }
  1562. if ( rest_is_field_included( 'comment_status', $fields ) ) {
  1563. $data['comment_status'] = $post->comment_status;
  1564. }
  1565. if ( rest_is_field_included( 'ping_status', $fields ) ) {
  1566. $data['ping_status'] = $post->ping_status;
  1567. }
  1568. if ( rest_is_field_included( 'sticky', $fields ) ) {
  1569. $data['sticky'] = is_sticky( $post->ID );
  1570. }
  1571. if ( rest_is_field_included( 'template', $fields ) ) {
  1572. $template = get_page_template_slug( $post->ID );
  1573. if ( $template ) {
  1574. $data['template'] = $template;
  1575. } else {
  1576. $data['template'] = '';
  1577. }
  1578. }
  1579. if ( rest_is_field_included( 'format', $fields ) ) {
  1580. $data['format'] = get_post_format( $post->ID );
  1581. // Fill in blank post format.
  1582. if ( empty( $data['format'] ) ) {
  1583. $data['format'] = 'standard';
  1584. }
  1585. }
  1586. if ( rest_is_field_included( 'meta', $fields ) ) {
  1587. $data['meta'] = $this->meta->get_value( $post->ID, $request );
  1588. }
  1589. $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
  1590. foreach ( $taxonomies as $taxonomy ) {
  1591. $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
  1592. if ( rest_is_field_included( $base, $fields ) ) {
  1593. $terms = get_the_terms( $post, $taxonomy->name );
  1594. $data[ $base ] = $terms ? array_values( wp_list_pluck( $terms, 'term_id' ) ) : array();
  1595. }
  1596. }
  1597. $post_type_obj = get_post_type_object( $post->post_type );
  1598. if ( is_post_type_viewable( $post_type_obj ) && $post_type_obj->public ) {
  1599. $permalink_template_requested = rest_is_field_included( 'permalink_template', $fields );
  1600. $generated_slug_requested = rest_is_field_included( 'generated_slug', $fields );
  1601. if ( $permalink_template_requested || $generated_slug_requested ) {
  1602. if ( ! function_exists( 'get_sample_permalink' ) ) {
  1603. require_once ABSPATH . 'wp-admin/includes/post.php';
  1604. }
  1605. $sample_permalink = get_sample_permalink( $post->ID, $post->post_title, '' );
  1606. if ( $permalink_template_requested ) {
  1607. $data['permalink_template'] = $sample_permalink[0];
  1608. }
  1609. if ( $generated_slug_requested ) {
  1610. $data['generated_slug'] = $sample_permalink[1];
  1611. }
  1612. }
  1613. }
  1614. $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
  1615. $data = $this->add_additional_fields_to_object( $data, $request );
  1616. $data = $this->filter_response_by_context( $data, $context );
  1617. // Wrap the data in a response object.
  1618. $response = rest_ensure_response( $data );
  1619. $links = $this->prepare_links( $post );
  1620. $response->add_links( $links );
  1621. if ( ! empty( $links['self']['href'] ) ) {
  1622. $actions = $this->get_available_actions( $post, $request );
  1623. $self = $links['self']['href'];
  1624. foreach ( $actions as $rel ) {
  1625. $response->add_link( $rel, $self );
  1626. }
  1627. }
  1628. /**
  1629. * Filters the post data for a REST API response.
  1630. *
  1631. * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
  1632. *
  1633. * Possible hook names include:
  1634. *
  1635. * - `rest_prepare_post`
  1636. * - `rest_prepare_page`
  1637. * - `rest_prepare_attachment`
  1638. *
  1639. * @since 4.7.0
  1640. *
  1641. * @param WP_REST_Response $response The response object.
  1642. * @param WP_Post $post Post object.
  1643. * @param WP_REST_Request $request Request object.
  1644. */
  1645. return apply_filters( "rest_prepare_{$this->post_type}", $response, $post, $request );
  1646. }
  1647. /**
  1648. * Overwrites the default protected title format.
  1649. *
  1650. * By default, WordPress will show password protected posts with a title of
  1651. * "Protected: %s", as the REST API communicates the protected status of a post
  1652. * in a machine readable format, we remove the "Protected: " prefix.
  1653. *
  1654. * @since 4.7.0
  1655. *
  1656. * @return string Protected title format.
  1657. */
  1658. public function protected_title_format() {
  1659. return '%s';
  1660. }
  1661. /**
  1662. * Prepares links for the request.
  1663. *
  1664. * @since 4.7.0
  1665. *
  1666. * @param WP_Post $post Post object.
  1667. * @return array Links for the given post.
  1668. */
  1669. protected function prepare_links( $post ) {
  1670. $base = sprintf( '%s/%s', $this->namespace, $this->rest_base );
  1671. // Entity meta.
  1672. $links = array(
  1673. 'self' => array(
  1674. 'href' => rest_url( trailingslashit( $base ) . $post->ID ),
  1675. ),
  1676. 'collection' => array(
  1677. 'href' => rest_url( $base ),
  1678. ),
  1679. 'about' => array(
  1680. 'href' => rest_url( 'wp/v2/types/' . $this->post_type ),
  1681. ),
  1682. );
  1683. if ( ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'author' ) )
  1684. && ! empty( $post->post_author ) ) {
  1685. $links['author'] = array(
  1686. 'href' => rest_url( 'wp/v2/users/' . $post->post_author ),
  1687. 'embeddable' => true,
  1688. );
  1689. }
  1690. if ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'comments' ) ) {
  1691. $replies_url = rest_url( 'wp/v2/comments' );
  1692. $replies_url = add_query_arg( 'post', $post->ID, $replies_url );
  1693. $links['replies'] = array(
  1694. 'href' => $replies_url,
  1695. 'embeddable' => true,
  1696. );
  1697. }
  1698. if ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'revisions' ) ) {
  1699. $revisions = wp_get_post_revisions( $post->ID, array( 'fields' => 'ids' ) );
  1700. $revisions_count = count( $revisions );
  1701. $links['version-history'] = array(
  1702. 'href' => rest_url( trailingslashit( $base ) . $post->ID . '/revisions' ),
  1703. 'count' => $revisions_count,
  1704. );
  1705. if ( $revisions_count > 0 ) {
  1706. $last_revision = array_shift( $revisions );
  1707. $links['predecessor-version'] = array(
  1708. 'href' => rest_url( trailingslashit( $base ) . $post->ID . '/revisions/' . $last_revision ),
  1709. 'id' => $last_revision,
  1710. );
  1711. }
  1712. }
  1713. $post_type_obj = get_post_type_object( $post->post_type );
  1714. if ( $post_type_obj->hierarchical && ! empty( $post->post_parent ) ) {
  1715. $links['up'] = array(
  1716. 'href' => rest_url( trailingslashit( $base ) . (int) $post->post_parent ),
  1717. 'embeddable' => true,
  1718. );
  1719. }
  1720. // If we have a featured media, add that.
  1721. $featured_media = get_post_thumbnail_id( $post->ID );
  1722. if ( $featured_media ) {
  1723. $image_url = rest_url( 'wp/v2/media/' . $featured_media );
  1724. $links['https://api.w.org/featuredmedia'] = array(
  1725. 'href' => $image_url,
  1726. 'embeddable' => true,
  1727. );
  1728. }
  1729. if ( ! in_array( $post->post_type, array( 'attachment', 'nav_menu_item', 'revision' ), true ) ) {
  1730. $attachments_url = rest_url( 'wp/v2/media' );
  1731. $attachments_url = add_query_arg( 'parent', $post->ID, $attachments_url );
  1732. $links['https://api.w.org/attachment'] = array(
  1733. 'href' => $attachments_url,
  1734. );
  1735. }
  1736. $taxonomies = get_object_taxonomies( $post->post_type );
  1737. if ( ! empty( $taxonomies ) ) {
  1738. $links['https://api.w.org/term'] = array();
  1739. foreach ( $taxonomies as $tax ) {
  1740. $taxonomy_obj = get_taxonomy( $tax );
  1741. // Skip taxonomies that are not public.
  1742. if ( empty( $taxonomy_obj->show_in_rest ) ) {
  1743. continue;
  1744. }
  1745. $tax_base = ! empty( $taxonomy_obj->rest_base ) ? $taxonomy_obj->rest_base : $tax;
  1746. $terms_url = add_query_arg(
  1747. 'post',
  1748. $post->ID,
  1749. rest_url( 'wp/v2/' . $tax_base )
  1750. );
  1751. $links['https://api.w.org/term'][] = array(
  1752. 'href' => $terms_url,
  1753. 'taxonomy' => $tax,
  1754. 'embeddable' => true,
  1755. );
  1756. }
  1757. }
  1758. return $links;
  1759. }
  1760. /**
  1761. * Get the link relations available for the post and current user.
  1762. *
  1763. * @since 4.9.8
  1764. *
  1765. * @param WP_Post $post Post object.
  1766. * @param WP_REST_Request $request Request object.
  1767. * @return array List of link relations.
  1768. */
  1769. protected function get_available_actions( $post, $request ) {
  1770. if ( 'edit' !== $request['context'] ) {
  1771. return array();
  1772. }
  1773. $rels = array();
  1774. $post_type = get_post_type_object( $post->post_type );
  1775. if ( 'attachment' !== $this->post_type && current_user_can( $post_type->cap->publish_posts ) ) {
  1776. $rels[] = 'https://api.w.org/action-publish';
  1777. }
  1778. if ( current_user_can( 'unfiltered_html' ) ) {
  1779. $rels[] = 'https://api.w.org/action-unfiltered-html';
  1780. }
  1781. if ( 'post' === $post_type->name ) {
  1782. if ( current_user_can( $post_type->cap->edit_others_posts ) && current_user_can( $post_type->cap->publish_posts ) ) {
  1783. $rels[] = 'https://api.w.org/action-sticky';
  1784. }
  1785. }
  1786. if ( post_type_supports( $post_type->name, 'author' ) ) {
  1787. if ( current_user_can( $post_type->cap->edit_others_posts ) ) {
  1788. $rels[] = 'https://api.w.org/action-assign-author';
  1789. }
  1790. }
  1791. $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
  1792. foreach ( $taxonomies as $tax ) {
  1793. $tax_base = ! empty( $tax->rest_base ) ? $tax->rest_base : $tax->name;
  1794. $create_cap = is_taxonomy_hierarchical( $tax->name ) ? $tax->cap->edit_terms : $tax->cap->assign_terms;
  1795. if ( current_user_can( $create_cap ) ) {
  1796. $rels[] = 'https://api.w.org/action-create-' . $tax_base;
  1797. }
  1798. if ( current_user_can( $tax->cap->assign_terms ) ) {
  1799. $rels[] = 'https://api.w.org/action-assign-' . $tax_base;
  1800. }
  1801. }
  1802. return $rels;
  1803. }
  1804. /**
  1805. * Retrieves the post's schema, conforming to JSON Schema.
  1806. *
  1807. * @since 4.7.0
  1808. *
  1809. * @return array Item schema data.
  1810. */
  1811. public function get_item_schema() {
  1812. if ( $this->schema ) {
  1813. return $this->add_additional_fields_schema( $this->schema );
  1814. }
  1815. $schema = array(
  1816. '$schema' => 'http://json-schema.org/draft-04/schema#',
  1817. 'title' => $this->post_type,
  1818. 'type' => 'object',
  1819. // Base properties for every Post.
  1820. 'properties' => array(
  1821. 'date' => array(
  1822. 'description' => __( "The date the post was published, in the site's timezone." ),
  1823. 'type' => array( 'string', 'null' ),
  1824. 'format' => 'date-time',
  1825. 'context' => array( 'view', 'edit', 'embed' ),
  1826. ),
  1827. 'date_gmt' => array(
  1828. 'description' => __( 'The date the post was published, as GMT.' ),
  1829. 'type' => array( 'string', 'null' ),
  1830. 'format' => 'date-time',
  1831. 'context' => array( 'view', 'edit' ),
  1832. ),
  1833. 'guid' => array(
  1834. 'description' => __( 'The globally unique identifier for the post.' ),
  1835. 'type' => 'object',
  1836. 'context' => array( 'view', 'edit' ),
  1837. 'readonly' => true,
  1838. 'properties' => array(
  1839. 'raw' => array(
  1840. 'description' => __( 'GUID for the post, as it exists in the database.' ),
  1841. 'type' => 'string',
  1842. 'context' => array( 'edit' ),
  1843. 'readonly' => true,
  1844. ),
  1845. 'rendered' => array(
  1846. 'description' => __( 'GUID for the post, transformed for display.' ),
  1847. 'type' => 'string',
  1848. 'context' => array( 'view', 'edit' ),
  1849. 'readonly' => true,
  1850. ),
  1851. ),
  1852. ),
  1853. 'id' => array(
  1854. 'description' => __( 'Unique identifier for the post.' ),
  1855. 'type' => 'integer',
  1856. 'context' => array( 'view', 'edit', 'embed' ),
  1857. 'readonly' => true,
  1858. ),
  1859. 'link' => array(
  1860. 'description' => __( 'URL to the post.' ),
  1861. 'type' => 'string',
  1862. 'format' => 'uri',
  1863. 'context' => array( 'view', 'edit', 'embed' ),
  1864. 'readonly' => true,
  1865. ),
  1866. 'modified' => array(
  1867. 'description' => __( "The date the post was last modified, in the site's timezone." ),
  1868. 'type' => 'string',
  1869. 'format' => 'date-time',
  1870. 'context' => array( 'view', 'edit' ),
  1871. 'readonly' => true,
  1872. ),
  1873. 'modified_gmt' => array(
  1874. 'description' => __( 'The date the post was last modified, as GMT.' ),
  1875. 'type' => 'string',
  1876. 'format' => 'date-time',
  1877. 'context' => array( 'view', 'edit' ),
  1878. 'readonly' => true,
  1879. ),
  1880. 'slug' => array(
  1881. 'description' => __( 'An alphanumeric identifier for the post unique to its type.' ),
  1882. 'type' => 'string',
  1883. 'context' => array( 'view', 'edit', 'embed' ),
  1884. 'arg_options' => array(
  1885. 'sanitize_callback' => array( $this, 'sanitize_slug' ),
  1886. ),
  1887. ),
  1888. 'status' => array(
  1889. 'description' => __( 'A named status for the post.' ),
  1890. 'type' => 'string',
  1891. 'enum' => array_keys( get_post_stati( array( 'internal' => false ) ) ),
  1892. 'context' => array( 'view', 'edit' ),
  1893. 'arg_options' => array(
  1894. 'validate_callback' => array( $this, 'check_status' ),
  1895. ),
  1896. ),
  1897. 'type' => array(
  1898. 'description' => __( 'Type of post.' ),
  1899. 'type' => 'string',
  1900. 'context' => array( 'view', 'edit', 'embed' ),
  1901. 'readonly' => true,
  1902. ),
  1903. 'password' => array(
  1904. 'description' => __( 'A password to protect access to the content and excerpt.' ),
  1905. 'type' => 'string',
  1906. 'context' => array( 'edit' ),
  1907. ),
  1908. ),
  1909. );
  1910. $post_type_obj = get_post_type_object( $this->post_type );
  1911. if ( is_post_type_viewable( $post_type_obj ) && $post_type_obj->public ) {
  1912. $schema['properties']['permalink_template'] = array(
  1913. 'description' => __( 'Permalink template for the post.' ),
  1914. 'type' => 'string',
  1915. 'context' => array( 'edit' ),
  1916. 'readonly' => true,
  1917. );
  1918. $schema['properties']['generated_slug'] = array(
  1919. 'description' => __( 'Slug automatically generated from the post title.' ),
  1920. 'type' => 'string',
  1921. 'context' => array( 'edit' ),
  1922. 'readonly' => true,
  1923. );
  1924. }
  1925. if ( $post_type_obj->hierarchical ) {
  1926. $schema['properties']['parent'] = array(
  1927. 'description' => __( 'The ID for the parent of the post.' ),
  1928. 'type' => 'integer',
  1929. 'context' => array( 'view', 'edit' ),
  1930. );
  1931. }
  1932. $post_type_attributes = array(
  1933. 'title',
  1934. 'editor',
  1935. 'author',
  1936. 'excerpt',
  1937. 'thumbnail',
  1938. 'comments',
  1939. 'revisions',
  1940. 'page-attributes',
  1941. 'post-formats',
  1942. 'custom-fields',
  1943. );
  1944. $fixed_schemas = array(
  1945. 'post' => array(
  1946. 'title',
  1947. 'editor',
  1948. 'author',
  1949. 'excerpt',
  1950. 'thumbnail',
  1951. 'comments',
  1952. 'revisions',
  1953. 'post-formats',
  1954. 'custom-fields',
  1955. ),
  1956. 'page' => array(
  1957. 'title',
  1958. 'editor',
  1959. 'author',
  1960. 'excerpt',
  1961. 'thumbnail',
  1962. 'comments',
  1963. 'revisions',
  1964. 'page-attributes',
  1965. 'custom-fields',
  1966. ),
  1967. 'attachment' => array(
  1968. 'title',
  1969. 'author',
  1970. 'comments',
  1971. 'revisions',
  1972. 'custom-fields',
  1973. ),
  1974. );
  1975. foreach ( $post_type_attributes as $attribute ) {
  1976. if ( isset( $fixed_schemas[ $this->post_type ] ) && ! in_array( $attribute, $fixed_schemas[ $this->post_type ], true ) ) {
  1977. continue;
  1978. } elseif ( ! isset( $fixed_schemas[ $this->post_type ] ) && ! post_type_supports( $this->post_type, $attribute ) ) {
  1979. continue;
  1980. }
  1981. switch ( $attribute ) {
  1982. case 'title':
  1983. $schema['properties']['title'] = array(
  1984. 'description' => __( 'The title for the post.' ),
  1985. 'type' => 'object',
  1986. 'context' => array( 'view', 'edit', 'embed' ),
  1987. 'arg_options' => array(
  1988. 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database().
  1989. 'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database().
  1990. ),
  1991. 'properties' => array(
  1992. 'raw' => array(
  1993. 'description' => __( 'Title for the post, as it exists in the database.' ),
  1994. 'type' => 'string',
  1995. 'context' => array( 'edit' ),
  1996. ),
  1997. 'rendered' => array(
  1998. 'description' => __( 'HTML title for the post, transformed for display.' ),
  1999. 'type' => 'string',
  2000. 'context' => array( 'view', 'edit', 'embed' ),
  2001. 'readonly' => true,
  2002. ),
  2003. ),
  2004. );
  2005. break;
  2006. case 'editor':
  2007. $schema['properties']['content'] = array(
  2008. 'description' => __( 'The content for the post.' ),
  2009. 'type' => 'object',
  2010. 'context' => array( 'view', 'edit' ),
  2011. 'arg_options' => array(
  2012. 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database().
  2013. 'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database().
  2014. ),
  2015. 'properties' => array(
  2016. 'raw' => array(
  2017. 'description' => __( 'Content for the post, as it exists in the database.' ),
  2018. 'type' => 'string',
  2019. 'context' => array( 'edit' ),
  2020. ),
  2021. 'rendered' => array(
  2022. 'description' => __( 'HTML content for the post, transformed for display.' ),
  2023. 'type' => 'string',
  2024. 'context' => array( 'view', 'edit' ),
  2025. 'readonly' => true,
  2026. ),
  2027. 'block_version' => array(
  2028. 'description' => __( 'Version of the content block format used by the post.' ),
  2029. 'type' => 'integer',
  2030. 'context' => array( 'edit' ),
  2031. 'readonly' => true,
  2032. ),
  2033. 'protected' => array(
  2034. 'description' => __( 'Whether the content is protected with a password.' ),
  2035. 'type' => 'boolean',
  2036. 'context' => array( 'view', 'edit', 'embed' ),
  2037. 'readonly' => true,
  2038. ),
  2039. ),
  2040. );
  2041. break;
  2042. case 'author':
  2043. $schema['properties']['author'] = array(
  2044. 'description' => __( 'The ID for the author of the post.' ),
  2045. 'type' => 'integer',
  2046. 'context' => array( 'view', 'edit', 'embed' ),
  2047. );
  2048. break;
  2049. case 'excerpt':
  2050. $schema['properties']['excerpt'] = array(
  2051. 'description' => __( 'The excerpt for the post.' ),
  2052. 'type' => 'object',
  2053. 'context' => array( 'view', 'edit', 'embed' ),
  2054. 'arg_options' => array(
  2055. 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database().
  2056. 'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database().
  2057. ),
  2058. 'properties' => array(
  2059. 'raw' => array(
  2060. 'description' => __( 'Excerpt for the post, as it exists in the database.' ),
  2061. 'type' => 'string',
  2062. 'context' => array( 'edit' ),
  2063. ),
  2064. 'rendered' => array(
  2065. 'description' => __( 'HTML excerpt for the post, transformed for display.' ),
  2066. 'type' => 'string',
  2067. 'context' => array( 'view', 'edit', 'embed' ),
  2068. 'readonly' => true,
  2069. ),
  2070. 'protected' => array(
  2071. 'description' => __( 'Whether the excerpt is protected with a password.' ),
  2072. 'type' => 'boolean',
  2073. 'context' => array( 'view', 'edit', 'embed' ),
  2074. 'readonly' => true,
  2075. ),
  2076. ),
  2077. );
  2078. break;
  2079. case 'thumbnail':
  2080. $schema['properties']['featured_media'] = array(
  2081. 'description' => __( 'The ID of the featured media for the post.' ),
  2082. 'type' => 'integer',
  2083. 'context' => array( 'view', 'edit', 'embed' ),
  2084. );
  2085. break;
  2086. case 'comments':
  2087. $schema['properties']['comment_status'] = array(
  2088. 'description' => __( 'Whether or not comments are open on the post.' ),
  2089. 'type' => 'string',
  2090. 'enum' => array( 'open', 'closed' ),
  2091. 'context' => array( 'view', 'edit' ),
  2092. );
  2093. $schema['properties']['ping_status'] = array(
  2094. 'description' => __( 'Whether or not the post can be pinged.' ),
  2095. 'type' => 'string',
  2096. 'enum' => array( 'open', 'closed' ),
  2097. 'context' => array( 'view', 'edit' ),
  2098. );
  2099. break;
  2100. case 'page-attributes':
  2101. $schema['properties']['menu_order'] = array(
  2102. 'description' => __( 'The order of the post in relation to other posts.' ),
  2103. 'type' => 'integer',
  2104. 'context' => array( 'view', 'edit' ),
  2105. );
  2106. break;
  2107. case 'post-formats':
  2108. // Get the native post formats and remove the array keys.
  2109. $formats = array_values( get_post_format_slugs() );
  2110. $schema['properties']['format'] = array(
  2111. 'description' => __( 'The format for the post.' ),
  2112. 'type' => 'string',
  2113. 'enum' => $formats,
  2114. 'context' => array( 'view', 'edit' ),
  2115. );
  2116. break;
  2117. case 'custom-fields':
  2118. $schema['properties']['meta'] = $this->meta->get_field_schema();
  2119. break;
  2120. }
  2121. }
  2122. if ( 'post' === $this->post_type ) {
  2123. $schema['properties']['sticky'] = array(
  2124. 'description' => __( 'Whether or not the post should be treated as sticky.' ),
  2125. 'type' => 'boolean',
  2126. 'context' => array( 'view', 'edit' ),
  2127. );
  2128. }
  2129. $schema['properties']['template'] = array(
  2130. 'description' => __( 'The theme file to use to display the post.' ),
  2131. 'type' => 'string',
  2132. 'context' => array( 'view', 'edit' ),
  2133. 'arg_options' => array(
  2134. 'validate_callback' => array( $this, 'check_template' ),
  2135. ),
  2136. );
  2137. $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
  2138. foreach ( $taxonomies as $taxonomy ) {
  2139. $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
  2140. if ( array_key_exists( $base, $schema['properties'] ) ) {
  2141. $taxonomy_field_name_with_conflict = ! empty( $taxonomy->rest_base ) ? 'rest_base' : 'name';
  2142. _doing_it_wrong(
  2143. 'register_taxonomy',
  2144. sprintf(
  2145. /* translators: 1: The taxonomy name, 2: The property name, either 'rest_base' or 'name', 3: The conflicting value. */
  2146. __( 'The "%1$s" taxonomy "%2$s" property (%3$s) conflicts with an existing property on the REST API Posts Controller. Specify a custom "rest_base" when registering the taxonomy to avoid this error.' ),
  2147. $taxonomy->name,
  2148. $taxonomy_field_name_with_conflict,
  2149. $base
  2150. ),
  2151. '5.4.0'
  2152. );
  2153. }
  2154. $schema['properties'][ $base ] = array(
  2155. /* translators: %s: Taxonomy name. */
  2156. 'description' => sprintf( __( 'The terms assigned to the post in the %s taxonomy.' ), $taxonomy->name ),
  2157. 'type' => 'array',
  2158. 'items' => array(
  2159. 'type' => 'integer',
  2160. ),
  2161. 'context' => array( 'view', 'edit' ),
  2162. );
  2163. }
  2164. $schema_links = $this->get_schema_links();
  2165. if ( $schema_links ) {
  2166. $schema['links'] = $schema_links;
  2167. }
  2168. // Take a snapshot of which fields are in the schema pre-filtering.
  2169. $schema_fields = array_keys( $schema['properties'] );
  2170. /**
  2171. * Filters the post's schema.
  2172. *
  2173. * The dynamic portion of the filter, `$this->post_type`, refers to the
  2174. * post type slug for the controller.
  2175. *
  2176. * @since 5.4.0
  2177. *
  2178. * @param array $schema Item schema data.
  2179. */
  2180. $schema = apply_filters( "rest_{$this->post_type}_item_schema", $schema );
  2181. // Emit a _doing_it_wrong warning if user tries to add new properties using this filter.
  2182. $new_fields = array_diff( array_keys( $schema['properties'] ), $schema_fields );
  2183. if ( count( $new_fields ) > 0 ) {
  2184. _doing_it_wrong(
  2185. __METHOD__,
  2186. sprintf(
  2187. /* translators: %s: register_rest_field */
  2188. __( 'Please use %s to add new schema properties.' ),
  2189. 'register_rest_field'
  2190. ),
  2191. '5.4.0'
  2192. );
  2193. }
  2194. $this->schema = $schema;
  2195. return $this->add_additional_fields_schema( $this->schema );
  2196. }
  2197. /**
  2198. * Retrieve Link Description Objects that should be added to the Schema for the posts collection.
  2199. *
  2200. * @since 4.9.8
  2201. *
  2202. * @return array
  2203. */
  2204. protected function get_schema_links() {
  2205. $href = rest_url( "{$this->namespace}/{$this->rest_base}/{id}" );
  2206. $links = array();
  2207. if ( 'attachment' !== $this->post_type ) {
  2208. $links[] = array(
  2209. 'rel' => 'https://api.w.org/action-publish',
  2210. 'title' => __( 'The current user can publish this post.' ),
  2211. 'href' => $href,
  2212. 'targetSchema' => array(
  2213. 'type' => 'object',
  2214. 'properties' => array(
  2215. 'status' => array(
  2216. 'type' => 'string',
  2217. 'enum' => array( 'publish', 'future' ),
  2218. ),
  2219. ),
  2220. ),
  2221. );
  2222. }
  2223. $links[] = array(
  2224. 'rel' => 'https://api.w.org/action-unfiltered-html',
  2225. 'title' => __( 'The current user can post unfiltered HTML markup and JavaScript.' ),
  2226. 'href' => $href,
  2227. 'targetSchema' => array(
  2228. 'type' => 'object',
  2229. 'properties' => array(
  2230. 'content' => array(
  2231. 'raw' => array(
  2232. 'type' => 'string',
  2233. ),
  2234. ),
  2235. ),
  2236. ),
  2237. );
  2238. if ( 'post' === $this->post_type ) {
  2239. $links[] = array(
  2240. 'rel' => 'https://api.w.org/action-sticky',
  2241. 'title' => __( 'The current user can sticky this post.' ),
  2242. 'href' => $href,
  2243. 'targetSchema' => array(
  2244. 'type' => 'object',
  2245. 'properties' => array(
  2246. 'sticky' => array(
  2247. 'type' => 'boolean',
  2248. ),
  2249. ),
  2250. ),
  2251. );
  2252. }
  2253. if ( post_type_supports( $this->post_type, 'author' ) ) {
  2254. $links[] = array(
  2255. 'rel' => 'https://api.w.org/action-assign-author',
  2256. 'title' => __( 'The current user can change the author on this post.' ),
  2257. 'href' => $href,
  2258. 'targetSchema' => array(
  2259. 'type' => 'object',
  2260. 'properties' => array(
  2261. 'author' => array(
  2262. 'type' => 'integer',
  2263. ),
  2264. ),
  2265. ),
  2266. );
  2267. }
  2268. $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
  2269. foreach ( $taxonomies as $tax ) {
  2270. $tax_base = ! empty( $tax->rest_base ) ? $tax->rest_base : $tax->name;
  2271. /* translators: %s: Taxonomy name. */
  2272. $assign_title = sprintf( __( 'The current user can assign terms in the %s taxonomy.' ), $tax->name );
  2273. /* translators: %s: Taxonomy name. */
  2274. $create_title = sprintf( __( 'The current user can create terms in the %s taxonomy.' ), $tax->name );
  2275. $links[] = array(
  2276. 'rel' => 'https://api.w.org/action-assign-' . $tax_base,
  2277. 'title' => $assign_title,
  2278. 'href' => $href,
  2279. 'targetSchema' => array(
  2280. 'type' => 'object',
  2281. 'properties' => array(
  2282. $tax_base => array(
  2283. 'type' => 'array',
  2284. 'items' => array(
  2285. 'type' => 'integer',
  2286. ),
  2287. ),
  2288. ),
  2289. ),
  2290. );
  2291. $links[] = array(
  2292. 'rel' => 'https://api.w.org/action-create-' . $tax_base,
  2293. 'title' => $create_title,
  2294. 'href' => $href,
  2295. 'targetSchema' => array(
  2296. 'type' => 'object',
  2297. 'properties' => array(
  2298. $tax_base => array(
  2299. 'type' => 'array',
  2300. 'items' => array(
  2301. 'type' => 'integer',
  2302. ),
  2303. ),
  2304. ),
  2305. ),
  2306. );
  2307. }
  2308. return $links;
  2309. }
  2310. /**
  2311. * Retrieves the query params for the posts collection.
  2312. *
  2313. * @since 4.7.0
  2314. * @since 5.4.0 The `tax_relation` query parameter was added.
  2315. * @since 5.7.0 The `modified_after` and `modified_before` query parameters were added.
  2316. *
  2317. * @return array Collection parameters.
  2318. */
  2319. public function get_collection_params() {
  2320. $query_params = parent::get_collection_params();
  2321. $query_params['context']['default'] = 'view';
  2322. $query_params['after'] = array(
  2323. 'description' => __( 'Limit response to posts published after a given ISO8601 compliant date.' ),
  2324. 'type' => 'string',
  2325. 'format' => 'date-time',
  2326. );
  2327. $query_params['modified_after'] = array(
  2328. 'description' => __( 'Limit response to posts modified after a given ISO8601 compliant date.' ),
  2329. 'type' => 'string',
  2330. 'format' => 'date-time',
  2331. );
  2332. if ( post_type_supports( $this->post_type, 'author' ) ) {
  2333. $query_params['author'] = array(
  2334. 'description' => __( 'Limit result set to posts assigned to specific authors.' ),
  2335. 'type' => 'array',
  2336. 'items' => array(
  2337. 'type' => 'integer',
  2338. ),
  2339. 'default' => array(),
  2340. );
  2341. $query_params['author_exclude'] = array(
  2342. 'description' => __( 'Ensure result set excludes posts assigned to specific authors.' ),
  2343. 'type' => 'array',
  2344. 'items' => array(
  2345. 'type' => 'integer',
  2346. ),
  2347. 'default' => array(),
  2348. );
  2349. }
  2350. $query_params['before'] = array(
  2351. 'description' => __( 'Limit response to posts published before a given ISO8601 compliant date.' ),
  2352. 'type' => 'string',
  2353. 'format' => 'date-time',
  2354. );
  2355. $query_params['modified_before'] = array(
  2356. 'description' => __( 'Limit response to posts modified before a given ISO8601 compliant date.' ),
  2357. 'type' => 'string',
  2358. 'format' => 'date-time',
  2359. );
  2360. $query_params['exclude'] = array(
  2361. 'description' => __( 'Ensure result set excludes specific IDs.' ),
  2362. 'type' => 'array',
  2363. 'items' => array(
  2364. 'type' => 'integer',
  2365. ),
  2366. 'default' => array(),
  2367. );
  2368. $query_params['include'] = array(
  2369. 'description' => __( 'Limit result set to specific IDs.' ),
  2370. 'type' => 'array',
  2371. 'items' => array(
  2372. 'type' => 'integer',
  2373. ),
  2374. 'default' => array(),
  2375. );
  2376. if ( 'page' === $this->post_type || post_type_supports( $this->post_type, 'page-attributes' ) ) {
  2377. $query_params['menu_order'] = array(
  2378. 'description' => __( 'Limit result set to posts with a specific menu_order value.' ),
  2379. 'type' => 'integer',
  2380. );
  2381. }
  2382. $query_params['offset'] = array(
  2383. 'description' => __( 'Offset the result set by a specific number of items.' ),
  2384. 'type' => 'integer',
  2385. );
  2386. $query_params['order'] = array(
  2387. 'description' => __( 'Order sort attribute ascending or descending.' ),
  2388. 'type' => 'string',
  2389. 'default' => 'desc',
  2390. 'enum' => array( 'asc', 'desc' ),
  2391. );
  2392. $query_params['orderby'] = array(
  2393. 'description' => __( 'Sort collection by post attribute.' ),
  2394. 'type' => 'string',
  2395. 'default' => 'date',
  2396. 'enum' => array(
  2397. 'author',
  2398. 'date',
  2399. 'id',
  2400. 'include',
  2401. 'modified',
  2402. 'parent',
  2403. 'relevance',
  2404. 'slug',
  2405. 'include_slugs',
  2406. 'title',
  2407. ),
  2408. );
  2409. if ( 'page' === $this->post_type || post_type_supports( $this->post_type, 'page-attributes' ) ) {
  2410. $query_params['orderby']['enum'][] = 'menu_order';
  2411. }
  2412. $post_type = get_post_type_object( $this->post_type );
  2413. if ( $post_type->hierarchical || 'attachment' === $this->post_type ) {
  2414. $query_params['parent'] = array(
  2415. 'description' => __( 'Limit result set to items with particular parent IDs.' ),
  2416. 'type' => 'array',
  2417. 'items' => array(
  2418. 'type' => 'integer',
  2419. ),
  2420. 'default' => array(),
  2421. );
  2422. $query_params['parent_exclude'] = array(
  2423. 'description' => __( 'Limit result set to all items except those of a particular parent ID.' ),
  2424. 'type' => 'array',
  2425. 'items' => array(
  2426. 'type' => 'integer',
  2427. ),
  2428. 'default' => array(),
  2429. );
  2430. }
  2431. $query_params['slug'] = array(
  2432. 'description' => __( 'Limit result set to posts with one or more specific slugs.' ),
  2433. 'type' => 'array',
  2434. 'items' => array(
  2435. 'type' => 'string',
  2436. ),
  2437. 'sanitize_callback' => 'wp_parse_slug_list',
  2438. );
  2439. $query_params['status'] = array(
  2440. 'default' => 'publish',
  2441. 'description' => __( 'Limit result set to posts assigned one or more statuses.' ),
  2442. 'type' => 'array',
  2443. 'items' => array(
  2444. 'enum' => array_merge( array_keys( get_post_stati() ), array( 'any' ) ),
  2445. 'type' => 'string',
  2446. ),
  2447. 'sanitize_callback' => array( $this, 'sanitize_post_statuses' ),
  2448. );
  2449. $query_params = $this->prepare_taxonomy_limit_schema( $query_params );
  2450. if ( 'post' === $this->post_type ) {
  2451. $query_params['sticky'] = array(
  2452. 'description' => __( 'Limit result set to items that are sticky.' ),
  2453. 'type' => 'boolean',
  2454. );
  2455. }
  2456. /**
  2457. * Filters collection parameters for the posts controller.
  2458. *
  2459. * The dynamic part of the filter `$this->post_type` refers to the post
  2460. * type slug for the controller.
  2461. *
  2462. * This filter registers the collection parameter, but does not map the
  2463. * collection parameter to an internal WP_Query parameter. Use the
  2464. * `rest_{$this->post_type}_query` filter to set WP_Query parameters.
  2465. *
  2466. * @since 4.7.0
  2467. *
  2468. * @param array $query_params JSON Schema-formatted collection parameters.
  2469. * @param WP_Post_Type $post_type Post type object.
  2470. */
  2471. return apply_filters( "rest_{$this->post_type}_collection_params", $query_params, $post_type );
  2472. }
  2473. /**
  2474. * Sanitizes and validates the list of post statuses, including whether the
  2475. * user can query private statuses.
  2476. *
  2477. * @since 4.7.0
  2478. *
  2479. * @param string|array $statuses One or more post statuses.
  2480. * @param WP_REST_Request $request Full details about the request.
  2481. * @param string $parameter Additional parameter to pass to validation.
  2482. * @return array|WP_Error A list of valid statuses, otherwise WP_Error object.
  2483. */
  2484. public function sanitize_post_statuses( $statuses, $request, $parameter ) {
  2485. $statuses = wp_parse_slug_list( $statuses );
  2486. // The default status is different in WP_REST_Attachments_Controller.
  2487. $attributes = $request->get_attributes();
  2488. $default_status = $attributes['args']['status']['default'];
  2489. foreach ( $statuses as $status ) {
  2490. if ( $status === $default_status ) {
  2491. continue;
  2492. }
  2493. $post_type_obj = get_post_type_object( $this->post_type );
  2494. if ( current_user_can( $post_type_obj->cap->edit_posts ) || 'private' === $status && current_user_can( $post_type_obj->cap->read_private_posts ) ) {
  2495. $result = rest_validate_request_arg( $status, $request, $parameter );
  2496. if ( is_wp_error( $result ) ) {
  2497. return $result;
  2498. }
  2499. } else {
  2500. return new WP_Error(
  2501. 'rest_forbidden_status',
  2502. __( 'Status is forbidden.' ),
  2503. array( 'status' => rest_authorization_required_code() )
  2504. );
  2505. }
  2506. }
  2507. return $statuses;
  2508. }
  2509. /**
  2510. * Prepares the 'tax_query' for a collection of posts.
  2511. *
  2512. * @since 5.7.0
  2513. *
  2514. * @param array $args WP_Query arguments.
  2515. * @param WP_REST_Request $request Full details about the request.
  2516. * @return array Updated query arguments.
  2517. */
  2518. private function prepare_tax_query( array $args, WP_REST_Request $request ) {
  2519. $relation = $request['tax_relation'];
  2520. if ( $relation ) {
  2521. $args['tax_query'] = array( 'relation' => $relation );
  2522. }
  2523. $taxonomies = wp_list_filter(
  2524. get_object_taxonomies( $this->post_type, 'objects' ),
  2525. array( 'show_in_rest' => true )
  2526. );
  2527. foreach ( $taxonomies as $taxonomy ) {
  2528. $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
  2529. $tax_include = $request[ $base ];
  2530. $tax_exclude = $request[ $base . '_exclude' ];
  2531. if ( $tax_include ) {
  2532. $terms = array();
  2533. $include_children = false;
  2534. $operator = 'IN';
  2535. if ( rest_is_array( $tax_include ) ) {
  2536. $terms = $tax_include;
  2537. } elseif ( rest_is_object( $tax_include ) ) {
  2538. $terms = empty( $tax_include['terms'] ) ? array() : $tax_include['terms'];
  2539. $include_children = ! empty( $tax_include['include_children'] );
  2540. if ( isset( $tax_include['operator'] ) && 'AND' === $tax_include['operator'] ) {
  2541. $operator = 'AND';
  2542. }
  2543. }
  2544. if ( $terms ) {
  2545. $args['tax_query'][] = array(
  2546. 'taxonomy' => $taxonomy->name,
  2547. 'field' => 'term_id',
  2548. 'terms' => $terms,
  2549. 'include_children' => $include_children,
  2550. 'operator' => $operator,
  2551. );
  2552. }
  2553. }
  2554. if ( $tax_exclude ) {
  2555. $terms = array();
  2556. $include_children = false;
  2557. if ( rest_is_array( $tax_exclude ) ) {
  2558. $terms = $tax_exclude;
  2559. } elseif ( rest_is_object( $tax_exclude ) ) {
  2560. $terms = empty( $tax_exclude['terms'] ) ? array() : $tax_exclude['terms'];
  2561. $include_children = ! empty( $tax_exclude['include_children'] );
  2562. }
  2563. if ( $terms ) {
  2564. $args['tax_query'][] = array(
  2565. 'taxonomy' => $taxonomy->name,
  2566. 'field' => 'term_id',
  2567. 'terms' => $terms,
  2568. 'include_children' => $include_children,
  2569. 'operator' => 'NOT IN',
  2570. );
  2571. }
  2572. }
  2573. }
  2574. return $args;
  2575. }
  2576. /**
  2577. * Prepares the collection schema for including and excluding items by terms.
  2578. *
  2579. * @since 5.7.0
  2580. *
  2581. * @param array $query_params Collection schema.
  2582. * @return array Updated schema.
  2583. */
  2584. private function prepare_taxonomy_limit_schema( array $query_params ) {
  2585. $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
  2586. if ( ! $taxonomies ) {
  2587. return $query_params;
  2588. }
  2589. $query_params['tax_relation'] = array(
  2590. 'description' => __( 'Limit result set based on relationship between multiple taxonomies.' ),
  2591. 'type' => 'string',
  2592. 'enum' => array( 'AND', 'OR' ),
  2593. );
  2594. $limit_schema = array(
  2595. 'type' => array( 'object', 'array' ),
  2596. 'oneOf' => array(
  2597. array(
  2598. 'title' => __( 'Term ID List' ),
  2599. 'description' => __( 'Match terms with the listed IDs.' ),
  2600. 'type' => 'array',
  2601. 'items' => array(
  2602. 'type' => 'integer',
  2603. ),
  2604. ),
  2605. array(
  2606. 'title' => __( 'Term ID Taxonomy Query' ),
  2607. 'description' => __( 'Perform an advanced term query.' ),
  2608. 'type' => 'object',
  2609. 'properties' => array(
  2610. 'terms' => array(
  2611. 'description' => __( 'Term IDs.' ),
  2612. 'type' => 'array',
  2613. 'items' => array(
  2614. 'type' => 'integer',
  2615. ),
  2616. 'default' => array(),
  2617. ),
  2618. 'include_children' => array(
  2619. 'description' => __( 'Whether to include child terms in the terms limiting the result set.' ),
  2620. 'type' => 'boolean',
  2621. 'default' => false,
  2622. ),
  2623. ),
  2624. 'additionalProperties' => false,
  2625. ),
  2626. ),
  2627. );
  2628. $include_schema = array_merge(
  2629. array(
  2630. /* translators: %s: Taxonomy name. */
  2631. 'description' => __( 'Limit result set to items with specific terms assigned in the %s taxonomy.' ),
  2632. ),
  2633. $limit_schema
  2634. );
  2635. // 'operator' is supported only for 'include' queries.
  2636. $include_schema['oneOf'][1]['properties']['operator'] = array(
  2637. 'description' => __( 'Whether items must be assigned all or any of the specified terms.' ),
  2638. 'type' => 'string',
  2639. 'enum' => array( 'AND', 'OR' ),
  2640. 'default' => 'OR',
  2641. );
  2642. $exclude_schema = array_merge(
  2643. array(
  2644. /* translators: %s: Taxonomy name. */
  2645. 'description' => __( 'Limit result set to items except those with specific terms assigned in the %s taxonomy.' ),
  2646. ),
  2647. $limit_schema
  2648. );
  2649. foreach ( $taxonomies as $taxonomy ) {
  2650. $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
  2651. $base_exclude = $base . '_exclude';
  2652. $query_params[ $base ] = $include_schema;
  2653. $query_params[ $base ]['description'] = sprintf( $query_params[ $base ]['description'], $base );
  2654. $query_params[ $base_exclude ] = $exclude_schema;
  2655. $query_params[ $base_exclude ]['description'] = sprintf( $query_params[ $base_exclude ]['description'], $base );
  2656. if ( ! $taxonomy->hierarchical ) {
  2657. unset( $query_params[ $base ]['oneOf'][1]['properties']['include_children'] );
  2658. unset( $query_params[ $base_exclude ]['oneOf'][1]['properties']['include_children'] );
  2659. }
  2660. }
  2661. return $query_params;
  2662. }
  2663. }