<?php
|
|
namespace JVBase\rest\routes;
|
|
use JVBase\managers\queue\executors\ContentExecutor;
|
use JVBase\managers\queue\TypeConfig;
|
use JVBase\meta\Meta;
|
use JVBase\rest\PermissionHandler;
|
use JVBase\rest\Response;
|
use JVBase\rest\Rest;
|
use JVBase\managers\Cache;
|
use JVBase\rest\Route;
|
use JVBase\utility\Features;
|
use WP_Post;
|
use WP_Query;
|
use WP_Error;
|
use WP_REST_Request;
|
use WP_REST_Response;
|
use Exception;
|
|
if (!defined('ABSPATH')) {
|
exit; // Exit if accessed directly
|
}
|
|
class ContentRoutes extends Rest
|
{
|
protected array $fields = [];
|
protected array $taxonomies = [];
|
protected string $post_type = '';
|
protected string $user_id = '';
|
|
//For Timeline-specific posts
|
protected array $timelineSharedFields = [];
|
protected array $timelineUniqueFields = [];
|
protected static ?string $action = 'dash-';
|
protected Meta $meta;
|
|
public function __construct()
|
{
|
$this->cacheName = 'user_content_' . get_current_user_id();
|
parent::__construct();
|
if (JVB_TESTING) {
|
$this->cache->flush();
|
}
|
$this->cache->connect('post', true);
|
add_action('init', [$this, 'registerContentExecutors'], 5);
|
}
|
|
/**
|
* Register content operation types with the queue's TypeRegistry
|
*/
|
public function registerContentExecutors(): void
|
{
|
$registry = JVB()->queue()->registry();
|
$executor = new ContentExecutor();
|
|
// Content updates - chunked at 10 posts
|
$registry->register('content_update', new TypeConfig(
|
executor: $executor,
|
chunkKey: 'posts',
|
chunkSize: 10
|
));
|
|
// Batch creation (from uploads) TODO: I believe this is all handled by UploadExecutor
|
// $registry->register('batch_creation', new TypeConfig(
|
// executor: $executor
|
// ));
|
}
|
|
/**
|
* Registers content routes
|
* @return void
|
*/
|
public function registerRoutes(): void
|
{
|
Route::for('content')
|
->get([$this, 'getContent'])
|
->auth(PermissionHandler::combine(['user', 'nonce', ['actionNonce'=>'dash-']]))
|
->rateLimit(20)
|
->post([$this, 'postContent'])
|
->auth(PermissionHandler::combine(['user', 'nonce', ['actionNonce'=>'dash-']]))
|
->rateLimit(30);
|
}
|
|
protected function initTimelineFields(string $content): void
|
{
|
$content = jvbNoBase($content);
|
if (!Features::forContent($content)->has('is_timeline')) {
|
return;
|
}
|
$config = Features::getConfig($content);
|
$this->fields = $config['fields'];
|
|
$this->timelineSharedFields = $this->getTimelineSharedFields($content);
|
array_unshift($this->timelineSharedFields, 'post_thumbnail');
|
array_unshift($this->timelineSharedFields, 'post_title');
|
array_unshift($this->timelineSharedFields, 'post_status');
|
|
$this->timelineUniqueFields = $this->getTimelineUniqueFields($content);
|
}
|
|
public function getTimelineUniqueFields(string $content): array
|
{
|
$content = jvbNoBase($content);
|
if (!Features::forContent($content)->has('is_timeline')) {
|
return [];
|
}
|
$config = Features::getConfig($content);
|
$allFields = $config['fields'];
|
|
return array_keys(array_filter($allFields, function ($field) {
|
if (array_key_exists('for_all', $field) && $field['for_all'] === true) {
|
return true;
|
}
|
return false;
|
}));
|
}
|
|
public function getTimelineSharedFields(string $content): array
|
{
|
$content = jvbNoBase($content);
|
if (!Features::forContent($content)->has('is_timeline')) {
|
return [];
|
}
|
$config = Features::getConfig($content);
|
if (!$config || empty($config)) {
|
return [];
|
}
|
$allFields = $config['fields'] ?? [];
|
|
return array_keys(array_filter($allFields, function ($field) {
|
if (!array_key_exists('for_all', $field) || $field['for_all'] === false) {
|
return true;
|
}
|
return false;
|
}));
|
}
|
|
/**
|
* Handle content update/creation
|
* @param WP_REST_Request $request
|
*
|
* @return WP_REST_Response
|
*/
|
public function postContent(WP_REST_Request $request): WP_REST_Response
|
{
|
$data = $request->get_params();
|
$user_id = $data['user'];
|
|
if (!array_key_exists('posts', $data) || !is_array($data['posts'])) {
|
return Response::success(['message'=>'No posts found in request']);
|
}
|
|
$count = count($data['posts']);
|
$operationId = $data['id'];
|
unset($data['user']);
|
unset($data['id']);
|
|
error_log('[CONTENT]:'.print_r($data, true));
|
|
$queue = JVB()->queue();
|
$queue->queueOperation(
|
'content_update',
|
$user_id,
|
$data,
|
[
|
'count' => $count,
|
'chunk_key' => 'posts',
|
'chunk_size' => 10,
|
'operation_id' => $operationId
|
]
|
);
|
|
return Response::queued($operationId);
|
}
|
|
|
/**
|
* Handle request
|
* @param WP_REST_Request $request
|
*
|
* @return WP_REST_Response
|
*/
|
public function getContent(WP_REST_Request $request): WP_REST_Response
|
{
|
$params = $request->get_params();
|
$user_id = $params['user'];
|
|
$post_status = $params['status'];
|
if ($post_status === 'all') {
|
$post_status = ['publish', 'draft'];
|
} else {
|
$post_status = explode(',', $post_status);
|
}
|
$post_type = str_replace('-', '_', jvbCheckBase($params['content']));
|
|
|
// Build query args
|
$args = [
|
'post_type' => $post_type,
|
'posts_per_page' => $params['per_page'] ?? 30,
|
'paged' => $params['page'],
|
'orderby' => 'date',
|
'order' => 'DESC',
|
'author' => $user_id,
|
'post_status' => $post_status
|
];
|
//Only top level posts for timeline types
|
if (Features::forContent($post_type)->has('is_timeline')) {
|
$args['post_parent'] = 0;
|
}
|
|
//Calendar filters
|
if (Features::forContent($post_type)->has('is_calendar')) {
|
$args = $this->applyCalendarFilters($args, $params);
|
}
|
$taxonomies = array_filter($params, function ($param) {
|
return str_starts_with($param, 'tax_');
|
}, ARRAY_FILTER_USE_KEY);
|
if (!empty($taxonomies)) {
|
$params['taxonomies'] = [];
|
foreach ($taxonomies as $taxonomy => $terms) {
|
$taxonomy = str_replace('tax_', '', $taxonomy);
|
$params['taxonomies'][$taxonomy] = $terms;
|
}
|
}
|
if (array_key_exists('taxonomies', $params)) {
|
$args = $this->applyTaxonomyFilters($args, $params);
|
}
|
if (array_key_exists('date-filter', $params) || array_key_exists('dateFrom', $params)) {
|
$args = $this->applyDateFilters($args, $params);
|
}
|
if (array_key_exists('orderby', $params) || array_key_exists('order', $params)) {
|
$args = $this->applyOrderFilters($args, $params);
|
}
|
|
if (array_key_exists('search', $params)) {
|
$args['s'] = sanitize_text_field($params['search']);
|
}
|
|
|
$key = $this->cache->generateKey($args);
|
// Check HTTP cache headers with the specific content type
|
$cache_check = $this->checkHeaders($request, $key);
|
if ($cache_check) {
|
return $cache_check;
|
}
|
|
$cache = $this->cache->get($key);
|
if ($cache) {
|
$response = Response::success($cache);
|
return $this->addCacheHeaders($response);
|
}
|
|
$this->post_type = jvbCheckBase($params['content'] ?? $params['type']);
|
// Only expand search to taxonomies if we're actually going to query
|
if (array_key_exists('s', $args)) {
|
$args = $this->applySearchFilters($args, $params);
|
}
|
|
// Run query
|
$query = new WP_Query($args);
|
|
|
$this->fields = jvbGetFields(str_replace('-', '_', $this->post_type));
|
$this->taxonomies = $this->getTaxonomies($this->post_type);
|
$posts = array_map([$this, 'prepareItem'], $query->posts);
|
|
$data = [
|
'items' => $posts,
|
'total' => $query->found_posts,
|
'total_pages' => $query->max_num_pages,
|
'has_more' => $args['paged']??1 < $query->max_num_pages,
|
];
|
|
|
$this->cache->set($key, $data);
|
|
$response = Response::success($data);
|
return $this->addCacheHeaders($response);
|
}
|
|
protected function applySearchFilters(array $args, array $params): array
|
{
|
$search_term = sanitize_text_field($params['search']);
|
|
// Search term is already in $args['s'] from earlier
|
|
// Get all taxonomies registered to this post type
|
$taxonomies = get_object_taxonomies($this->post_type, 'names');
|
|
if (empty($taxonomies)) {
|
return $args;
|
}
|
|
// Cache the taxonomy term lookup per search term + post type
|
$term_cache_key = 'search_terms_' . md5($search_term . $this->post_type);
|
$matching_term_ids = $this->cache->get($term_cache_key);
|
|
if ($matching_term_ids === false) {
|
$matching_term_ids = [];
|
|
foreach ($taxonomies as $taxonomy) {
|
$terms = get_terms([
|
'taxonomy' => $taxonomy,
|
'search' => $search_term,
|
'hide_empty' => false,
|
'fields' => 'ids'
|
]);
|
|
if (!is_wp_error($terms) && !empty($terms)) {
|
$matching_term_ids = array_merge($matching_term_ids, $terms);
|
}
|
}
|
|
// Cache term IDs for 1 hour
|
$this->cache->set($term_cache_key, $matching_term_ids, 3600);
|
}
|
|
if (empty($matching_term_ids)) {
|
return $args;
|
}
|
|
// Build tax_query for matching terms
|
$term_queries = [];
|
|
foreach ($taxonomies as $taxonomy) {
|
$taxonomy_term_ids = array_filter($matching_term_ids, function ($term_id) use ($taxonomy) {
|
$term = get_term($term_id);
|
return !is_wp_error($term) && $term->taxonomy === $taxonomy;
|
});
|
|
if (!empty($taxonomy_term_ids)) {
|
$term_queries[] = [
|
'taxonomy' => $taxonomy,
|
'field' => 'term_id',
|
'terms' => array_values($taxonomy_term_ids),
|
'operator' => 'IN'
|
];
|
}
|
}
|
|
if (!empty($term_queries)) {
|
if (isset($args['tax_query'])) {
|
$args['tax_query'] = [
|
'relation' => 'OR',
|
$args['tax_query'],
|
[
|
'relation' => 'OR',
|
...$term_queries
|
]
|
];
|
} else {
|
$args['tax_query'] = [
|
'relation' => 'OR',
|
...$term_queries
|
];
|
}
|
}
|
|
return $args;
|
}
|
|
/**
|
* Gets allowed taxonomies for a particular content
|
* @param string $content
|
*
|
* @return array
|
*/
|
protected function getTaxonomies(string $content): array
|
{
|
$taxonomy_for = jvbGlobalTaxonomyFor();
|
$out = [];
|
foreach ($taxonomy_for as $tax => $postTypes) {
|
if (in_array($content, $postTypes)) {
|
$out[BASE . $tax] = [
|
'label' => JVB_CONTENT[$content]['plural'],
|
'icon' => $tax,
|
];
|
}
|
}
|
return $out;
|
}
|
|
|
|
/**
|
* Generates a post title, based on content type
|
* @param string $content the post type
|
*
|
* @return string
|
*/
|
protected function generatePostTitle(string $content): string
|
{
|
$username = get_user_meta($this->user_id, 'first_name', true);
|
$link = get_user_meta($this->user_id, BASE . 'link', true);
|
$city = jvbArtistCity($link);
|
return ucfirst($content) . ' by ' . $city . ' artist ' . $username;
|
}
|
|
/**
|
* @param WP_Post $post the post object
|
*
|
* @return array
|
*/
|
protected function prepareItem(WP_Post $post, bool $skip = false, bool $fields = true): array
|
{
|
if (!$skip && Features::forContent($post->post_type)->has('is_timeline')) {
|
$this->initTimelineFields($post->post_type);
|
return $this->formatTimeline($post);
|
}
|
$this->meta = Meta::forPost($post->ID);
|
$data = [
|
'id' => $post->ID,
|
'title' => $post->post_title,
|
'status' => $post->post_status,
|
'date' => $post->post_date,
|
'modified' => $post->post_modified,
|
'thumbnail' => get_the_post_thumbnail_url($post->ID),
|
'alt' => get_post_meta(get_post_thumbnail_id(), '_wp_attachment_image_alt', true),
|
'icon' => $this->post_type,
|
'taxonomies' => [],
|
'fields' => ($fields) ? $this->meta->getAll() : [],
|
'images' => [],
|
];
|
|
// Add taxonomy terms
|
foreach ($this->taxonomies as $taxonomy => $options) {
|
$tax = str_replace(BASE, '', $taxonomy);
|
$terms = wp_get_object_terms(
|
$post->ID,
|
$taxonomy,
|
['fields' => 'id=>name']
|
);
|
$data['taxonomies'][$tax] = [
|
'terms' => (is_wp_error($terms)) ? [] : $terms,
|
'name' => $options['label'],
|
'icon' => $tax
|
];
|
}
|
|
$images = $this->extractImages();
|
|
|
if (!empty($images)) {
|
$data['images'] = $images;
|
}
|
|
return $data;
|
}
|
|
protected function extractImages(array $fields = []): array
|
{
|
//Extract images
|
$images = [];
|
$get = [];
|
$fields = (empty($fields)) ? $this->fields : $fields;
|
foreach ($fields as $field => $config) {
|
if ($config['type'] === 'gallery' || $config['type'] === 'image' || $field === 'post_thumbnail') {
|
$get[] = $field;
|
}
|
}
|
|
if (!empty($get)) {
|
$allImages = $this->meta->getAll($get);
|
foreach ($allImages as $k => $imgs) {
|
$temp = explode(',', $imgs);
|
foreach ($temp as $img) {
|
if (is_numeric($img) && !array_key_exists($img, $images)) {
|
$images[$img] = jvbImageData((int)$img);
|
}
|
}
|
}
|
}
|
return $images;
|
}
|
|
public function formatTimeline(WP_Post $post): array
|
{
|
$item = $this->prepareItem($post, true, false);
|
//Step 1: Get the fields that apply to all posts
|
$mainMeta = Meta::forPost($post->ID);
|
$item['fields'] = $mainMeta->getAll($this->timelineSharedFields);
|
|
//Step 2: Get the fields for each individual posts
|
$children = get_children(['post_parent' => $post->ID, 'orderby' => 'date', 'order' => 'ASC', 'post_status' => ['publish', 'draft'], 'fields' => 'ids']);
|
array_unshift($children, $post->ID);
|
|
$subFields = [];
|
$images = [];
|
foreach ($children as $child) {
|
$meta = Meta::forPost($child);
|
$f = $meta->getAll($this->timelineUniqueFields);
|
$f = ['id' => $child] + $f;
|
$subFields[] = $f;
|
|
$images[$f['post_thumbnail']] = jvbImageData((int)$f['post_thumbnail']);
|
}
|
$item['fields']['timeline'] = $subFields;
|
$item['images'] = $item['images'] + $images;
|
$item['number'] = $mainMeta->get('number');
|
|
return $item;
|
}
|
}
|