Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.
PHP ai-agentsblueskyfacebookinstagramlaravellinkedinmastodonmcpmcp-serveropen-sourcerest-apiself-hostedsocial-mediasocial-media-managementsocial-media-schedulerthreadstiktokvuejsxyoutube
<?php
declare(strict_types=1);
namespace App\Support;
use App\Enums\GoogleBusiness\CtaAction;
use App\Enums\GoogleBusiness\TopicType;
use App\Enums\Instagram\TrialGraduation;
use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Enums\TikTok\PrivacyLevel;
use App\Enums\YouTube\Category;
use App\Enums\YouTube\License;
use App\Enums\YouTube\PrivacyStatus;
use App\Models\Post;
use App\Models\SocialAccount;
use App\Rules\ValidYouTubeDescription;
use App\Services\Social\ContentSanitizer;
use App\Support\Social\MastodonPoll;
use App\Support\Social\Poll;
use App\Support\Social\ThreadsPoll;
use App\Support\Social\XPoll;
use Closure;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Illuminate\Validation\Validator;
/**
* Single source of truth for per-platform `PostPlatform.meta` validation, shared
* by the web, public REST API, and MCP post create/update flows so every entry
* point accepts the same per-platform settings and enforces the same
* required-on-publish rules.
*/
class PostPlatformMetaRules
{
/**
* Keys TryPost writes itself once a post is live (Telegram reactions): never
* taken from a request, and kept when the post's settings are edited.
*/
public const SYSTEM_KEYS = ['reactions'];
/** What an Instagram music pick stores; anything else sent with it is dropped. */
private const array INSTAGRAM_AUDIO_FIELDS = ['id', 'title', 'artist', 'cover_url', 'preview_url', 'audio_volume', 'video_volume'];
/** Instagram takes up to three collaborators on a feed post, carousel or reel. */
public const INSTAGRAM_MAX_COLLABORATORS = 3;
/**
* What a post needs before it is scheduled or published, told to MCP
* clients by every tool that schedules or publishes, so a new rule is
* written here once.
*/
public const SCHEDULING_REQUIREMENTS = 'Before a post can be scheduled or published it needs: TikTok meta.privacy_level (get-tiktok-creator-info-tool), Pinterest meta.board_id (list-pinterest-boards-tool), Discord meta.channel_id (list-discord-channels-tool), Google Business events and offers meta.event (title and dates), YouTube a title (meta.title, or the first line of the text), a poll (content_type x_poll, mastodon_poll or threads_poll) meta.poll with at least 2 options plus text as its question, and on X and Mastodon duration_minutes (a reply poll in meta.thread_replies on X or Mastodon needs the same, its text being the question); list-content-types-tool lists the TikTok, Pinterest and Discord ones per platform as required_meta. A scheduled or published post also needs text or media; a poll needs text and takes no media.';
/** An Instagram username, with or without its leading @. */
public const INSTAGRAM_USERNAME_PATTERN = '/^@?[A-Za-z0-9._]{1,30}$/';
/**
* Validation rules for the post's meta and all its per-platform sub-keys,
* under `$prefix` (`meta`, or `destinations.*.meta` for a list of channels).
* Spread into a FormRequest/MCP tool rule set as the complete meta contract.
*
* @return array<string, mixed>
*/
public static function rules(string $prefix = 'meta'): array
{
return [
"{$prefix}" => ['sometimes', 'nullable', 'array'],
"{$prefix}.share_to_feed" => ['sometimes', 'boolean'],
"{$prefix}.collaborators" => ['sometimes', 'nullable', 'array', 'max:'.self::INSTAGRAM_MAX_COLLABORATORS],
"{$prefix}.collaborators.*" => ['string', 'regex:'.self::INSTAGRAM_USERNAME_PATTERN],
"{$prefix}.trial_graduation" => ['sometimes', 'nullable', 'string', Rule::enum(TrialGraduation::class)],
"{$prefix}.audio" => ['sometimes', 'nullable', 'array'],
"{$prefix}.audio.id" => ['sometimes', 'nullable', 'string', 'max:64', 'regex:/^[0-9]+$/'],
"{$prefix}.audio.title" => ['sometimes', 'nullable', 'string', 'max:255'],
"{$prefix}.audio.artist" => ['sometimes', 'nullable', 'string', 'max:255'],
"{$prefix}.audio.cover_url" => ['sometimes', 'nullable', 'url:http,https', 'max:2048'],
"{$prefix}.audio.preview_url" => ['sometimes', 'nullable', 'url:http,https', 'max:4096'],
"{$prefix}.audio.audio_volume" => ['sometimes', 'nullable', 'integer', 'between:0,100'],
"{$prefix}.audio.video_volume" => ['sometimes', 'nullable', 'integer', 'between:0,100'],
"{$prefix}.poll" => ['sometimes', 'nullable', 'array'],
"{$prefix}.poll.options" => ['sometimes', 'nullable', 'array', self::pollOptionsCount(...)],
"{$prefix}.poll.options.*" => ['nullable', 'string'],
"{$prefix}.poll.duration_minutes" => ['sometimes', 'nullable', 'integer'],
"{$prefix}.poll.multiple" => ['sometimes', 'nullable', 'boolean'],
"{$prefix}.poll.hide_totals" => ['sometimes', 'nullable', 'boolean'],
"{$prefix}.spoiler_text" => ['sometimes', 'nullable', 'string', 'max:500'],
"{$prefix}.thread_replies" => ['sometimes', 'nullable', 'array', 'max:'.ThreadReplies::MAX_REPLIES],
"{$prefix}.thread_replies.*" => ['nullable', function (string $attribute, mixed $value, Closure $fail): void {
if (! is_string($value) && ! is_array($value)) {
$fail(__('validation.array', ['attribute' => $attribute]));
}
if (is_string($value) && mb_strlen($value) > Post::CONTENT_MAX_LENGTH) {
$fail(__('validation.max.string', ['attribute' => $attribute, 'max' => Post::CONTENT_MAX_LENGTH]));
}
}],
"{$prefix}.thread_replies.*.text" => ['sometimes', 'nullable', 'string', 'max:'.Post::CONTENT_MAX_LENGTH],
"{$prefix}.thread_replies.*.media" => ['sometimes', 'nullable', 'array'],
"{$prefix}.thread_replies.*.media.*" => ['array'],
"{$prefix}.thread_replies.*.media.*.id" => ['sometimes', 'nullable', 'string'],
"{$prefix}.thread_replies.*.media.*.upload_token" => ['sometimes', 'nullable', 'string'],
"{$prefix}.thread_replies.*.media.*.url" => ['sometimes', 'nullable', 'string'],
"{$prefix}.thread_replies.*.poll" => ['sometimes', 'nullable', 'array'],
"{$prefix}.thread_replies.*.poll.options" => ['sometimes', 'nullable', 'array', self::pollOptionsCount(...)],
"{$prefix}.thread_replies.*.poll.options.*" => ['nullable', 'string'],
"{$prefix}.thread_replies.*.poll.duration_minutes" => ['sometimes', 'nullable', 'integer'],
"{$prefix}.thread_replies.*.poll.multiple" => ['sometimes', 'nullable', 'boolean'],
"{$prefix}.thread_replies.*.poll.hide_totals" => ['sometimes', 'nullable', 'boolean'],
"{$prefix}.document_title" => ['sometimes', 'nullable', 'string', 'max:300'],
"{$prefix}.privacy_level" => ['sometimes', 'nullable', 'string', Rule::enum(PrivacyLevel::class)],
"{$prefix}.auto_add_music" => ['sometimes', 'boolean'],
"{$prefix}.allow_comments" => ['sometimes', 'boolean'],
"{$prefix}.allow_duet" => ['sometimes', 'boolean'],
"{$prefix}.allow_stitch" => ['sometimes', 'boolean'],
"{$prefix}.is_aigc" => ['sometimes', 'boolean'],
"{$prefix}.disclose" => ['sometimes', 'boolean'],
"{$prefix}.brand_content_toggle" => ['sometimes', 'boolean'],
"{$prefix}.brand_organic_toggle" => ['sometimes', 'boolean'],
"{$prefix}.board_id" => ['sometimes', 'nullable', 'string'],
"{$prefix}.title" => ['sometimes', 'nullable', 'string', 'max:100'],
"{$prefix}.link" => ['sometimes', 'nullable', 'url:http,https', 'max:2048'],
"{$prefix}.description" => ['sometimes', 'nullable', 'string', new ValidYouTubeDescription],
"{$prefix}.category_id" => ['sometimes', 'nullable', Rule::in(array_column(Category::cases(), 'value'))],
"{$prefix}.privacy_status" => ['sometimes', 'nullable', 'string', Rule::enum(PrivacyStatus::class)],
"{$prefix}.license" => ['sometimes', 'nullable', 'string', Rule::enum(License::class)],
"{$prefix}.notify_subscribers" => ['sometimes', 'boolean'],
"{$prefix}.embeddable" => ['sometimes', 'boolean'],
"{$prefix}.made_for_kids" => ['sometimes', 'boolean'],
"{$prefix}.is_ai_generated" => ['sometimes', 'boolean'],
"{$prefix}.link_preview" => ['sometimes', 'boolean:strict'],
"{$prefix}.topic_tag" => ['sometimes', 'nullable', 'string', function (string $attribute, mixed $value, Closure $fail): void {
if (! self::isThreadsTopicTag((string) $value)) {
$fail(__('posts.form.threads.topic_invalid'));
}
}],
"{$prefix}.channel_id" => ['sometimes', 'nullable', 'string'],
"{$prefix}.mentions" => ['sometimes', 'nullable', 'array'],
"{$prefix}.mentions.*.token" => ['required', 'string'],
"{$prefix}.mentions.*.label" => ['sometimes', 'nullable', 'string'],
"{$prefix}.embeds" => ['sometimes', 'nullable', 'array', 'max:10'],
"{$prefix}.embeds.*.title" => ['sometimes', 'nullable', 'string', 'max:256'],
"{$prefix}.embeds.*.description" => ['sometimes', 'nullable', 'string', 'max:4096'],
"{$prefix}.embeds.*.url" => ['sometimes', 'nullable', 'url'],
"{$prefix}.embeds.*.image" => ['sometimes', 'nullable', 'url'],
"{$prefix}.embeds.*.color" => ['sometimes', 'nullable', 'string', 'regex:/^#?[0-9A-Fa-f]{6}$/'],
"{$prefix}.topic_type" => ['sometimes', 'nullable', 'string', Rule::enum(TopicType::class)],
"{$prefix}.call_to_action" => ['sometimes', 'nullable', 'array'],
"{$prefix}.call_to_action.action_type" => ['sometimes', 'nullable', 'string', Rule::enum(CtaAction::class)],
"{$prefix}.call_to_action.url" => ['sometimes', 'nullable', 'url:http,https', 'max:2048'],
"{$prefix}.event" => ['sometimes', 'nullable', 'array'],
"{$prefix}.event.title" => ['sometimes', 'nullable', 'string', 'max:'.TopicType::TITLE_MAX_LENGTH],
"{$prefix}.event.start_date" => ['sometimes', 'nullable', 'date'],
"{$prefix}.event.end_date" => ['sometimes', 'nullable', 'date', "after_or_equal:{$prefix}.event.start_date"],
"{$prefix}.event.start_time" => ['sometimes', 'nullable', 'date_format:H:i'],
"{$prefix}.event.end_time" => ['sometimes', 'nullable', 'date_format:H:i'],
"{$prefix}.offer" => ['sometimes', 'nullable', 'array'],
"{$prefix}.offer.coupon_code" => ['sometimes', 'nullable', 'string'],
"{$prefix}.offer.redeem_online_url" => ['sometimes', 'nullable', 'url:http,https', 'max:2048'],
"{$prefix}.offer.terms_conditions" => ['sometimes', 'nullable', 'string', 'max:5000'],
];
}
/**
* The meta without any key that has no rule in rules().
*
* @param array<string, mixed> $meta
* @return array<string, mixed>
*/
public static function onlyKnown(array $meta): array
{
$known = collect(array_keys(self::rules()))
->filter(fn (string $key): bool => str_starts_with($key, 'meta.'))
->map(fn (string $key): string => explode('.', substr($key, strlen('meta.')))[0])
->unique()
->all();
return array_intersect_key($meta, array_flip($known));
}
/**
* Custom validation messages for meta fields shown in the UI.
*
* @return array<string, string>
*/
public static function messages(string $prefix = 'meta'): array
{
return [
"{$prefix}.link.url" => __('posts.form.pinterest.link_invalid'),
"{$prefix}.link.max" => __('posts.form.pinterest.link_max'),
"{$prefix}.title.max" => __('posts.form.pinterest.title_max'),
"{$prefix}.collaborators.max" => __('posts.form.instagram.collaborators.max', ['max' => self::INSTAGRAM_MAX_COLLABORATORS]),
"{$prefix}.collaborators.*.regex" => __('posts.form.instagram.collaborators.invalid'),
"{$prefix}.event.end_date.after_or_equal" => __('posts.form.google_business.event_end_date_before_start'),
"{$prefix}.event.title.max" => __('posts.form.google_business.title_max'),
"{$prefix}.poll.array" => __('posts.form.poll.poll_object'),
"{$prefix}.poll.options.array" => __('posts.form.poll.options_list'),
"{$prefix}.poll.options.*.string" => __('posts.form.poll.choice_text'),
"{$prefix}.poll.duration_minutes.integer" => __('posts.form.poll.duration_whole'),
"{$prefix}.thread_replies.*.poll.array" => __('posts.form.poll.poll_object'),
"{$prefix}.thread_replies.*.poll.options.array" => __('posts.form.poll.options_list'),
"{$prefix}.thread_replies.*.poll.options.*.string" => __('posts.form.poll.choice_text'),
"{$prefix}.thread_replies.*.poll.duration_minutes.integer" => __('posts.form.poll.duration_whole'),
];
}
/**
* A poll's choices (the post's poll and each reply's): four at most on
* every network. The length of each choice and of the poll depends on the
* network, so `formatErrors()` checks them once the channel is known.
*/
private static function pollOptionsCount(string $attribute, mixed $value, Closure $fail): void
{
transform(Poll::optionsCountViolation($value), $fail);
}
/**
* Friendly attribute names so default messages never expose raw meta keys.
*
* @return array<string, string>
*/
public static function attributes(string $prefix = 'meta'): array
{
return [
"{$prefix}.title" => __('posts.form.pinterest.title'),
"{$prefix}.description" => __('posts.form.youtube.description'),
"{$prefix}.link" => __('posts.form.pinterest.link'),
"{$prefix}.event.title" => __('posts.form.google_business.event_title'),
"{$prefix}.call_to_action.url" => __('posts.form.google_business.cta_url'),
];
}
/**
* Plain-text description of every per-platform meta key, shown to MCP
* clients on the create and update post tools.
*/
public static function documentation(): string
{
return implode(' ', [
'Per-platform metadata. A thread on X, Bluesky or Mastodon, or a comment on LinkedIn, is meta.thread_replies (see below).',
'TikTok: privacy_level PUBLIC_TO_EVERYONE|MUTUAL_FOLLOW_FRIENDS|FOLLOWER_OF_CREATOR|SELF_ONLY (required to publish; call get-tiktok-creator-info-tool first and pick one of its privacy_level_options, and keep allow_comments/allow_duet/allow_stitch false when it reports them disabled) + flags allow_comments, disclose (commercial content), brand_content_toggle (paid partnership), brand_organic_toggle (your own brand); on tiktok_video also allow_duet, allow_stitch and is_aigc (AI-generated content label), on tiktok_photo also auto_add_music. SELF_ONLY cannot be combined with brand_content_toggle.',
'Mastodon: spoiler_text (content warning, ≤500; counts toward the 500-character post limit).',
'Pinterest: board_id (required to publish — call list-pinterest-boards-tool first, or create-pinterest-board-tool), title (≤100), link (destination URL). Pin description comes from the post content; a video pin cover frame is the media item meta.cover_offset_ms.',
'Discord: channel_id (required to publish — call list-discord-channels-tool first), mentions ([{token,label}], e.g. {token: "@everyone"} or {token: "<@&roleId>"}), embeds (up to 10 [{title ≤256, description ≤4096, url, image (URL), color (#RRGGBB)}]).',
'YouTube Shorts: title (≤100, no < or >; omitted, it is derived from the first non-empty line of the content with < and > removed, cut to 100 characters), description (plain text, at most 5000 bytes; omit or null to use the content), category_id (YouTube category id: '.collect(Category::cases())->map(fn (Category $category): string => "{$category->value}=".__($category->labelKey(), [], 'en'))->implode(', ').'; default '.Category::DEFAULT->value.'), privacy_status (public|unlisted|private, default public), license (youtube|creativeCommon), notify_subscribers (default true), embeddable (default true), made_for_kids (default false), is_ai_generated (discloses altered or synthetic content). A cover image is the media item meta.cover, set as the thumbnail once YouTube processes the video.',
'Instagram: is_ai_generated (feed, reels, stories, carousels), share_to_feed (instagram_reel only, default true), collaborators (up to '.self::INSTAGRAM_MAX_COLLABORATORS.' Instagram usernames invited as co-authors; feed, reels and carousels, not stories; the post shows on a collaborator\'s profile only after they accept the invite in the Instagram app, and a username that does not exist is only refused when the post publishes, so confirm the usernames first), trial_graduation (instagram_reel only: MANUAL|SS_PERFORMANCE publishes a trial reel shown only to non-followers, graduated by hand in the app or by Instagram when it performs well; not with collaborators, and only on accounts where Instagram offers trial reels), audio (instagram_reel only, Instagram connected through Facebook, platform instagram-facebook: {id} of an Instagram audio track from search-instagram-audio-tool, with optional title, artist, cover_url and preview_url copied from that result so the app can show the track, and audio_volume and video_volume from 0 to 100, default 100). An instagram_feed post with a single video publishes as a Reel. People tags are the media item meta.user_tags, a video cover frame is meta.cover_offset_ms and an instagram_reel may take an uploaded image as its cover in the media item meta.cover with cover_source image (it then wins over the frame).',
'X: is_ai_generated (sent as made_with_ai, discloses AI-generated media on the post). poll (content_type x_poll only, no media; the post content is the question; a reply of the thread can be a poll too, see thread_replies, up to '.XPoll::QUESTION_MAX_LENGTH.' characters): {options (list of '.Poll::MIN_OPTIONS.' to '.Poll::MAX_OPTIONS.' choices of 1 to '.XPoll::OPTION_MAX_LENGTH.' characters, no two the same; blank ones are dropped), duration_minutes ('.XPoll::MIN_DURATION.' to '.XPoll::MAX_DURATION.', how long voting stays open)}, both required to schedule or publish.',
'Mastodon poll (content_type mastodon_poll only, no media; the post content is the question; a reply of the thread can be a poll too, see thread_replies): {options (list of '.Poll::MIN_OPTIONS.' to '.Poll::MAX_OPTIONS.' choices of 1 to '.MastodonPoll::OPTION_MAX_LENGTH.' characters, no two the same; blank ones are dropped), duration_minutes ('.MastodonPoll::MIN_DURATION.' to '.MastodonPoll::MAX_DURATION.', how long voting stays open), multiple (default false: voters may pick several choices), hide_totals (default false: votes stay hidden until the poll ends)}, options and duration_minutes required to schedule or publish.',
'Threads poll (content_type threads_poll only, a text post without media; the post content is the question): {options (list of '.Poll::MIN_OPTIONS.' to '.Poll::MAX_OPTIONS.' choices of 1 to '.ThreadsPoll::OPTION_MAX_LENGTH.' characters, no two the same; blank ones are dropped)}, required to schedule or publish; Threads sets how long it stays open.',
'Threads: topic_tag (1-50 characters after a leading # is dropped, no . or &). Use content_type threads_ghost_post for a text-only post archived after 24 hours (no media, no topic).',
'Facebook, Bluesky, LinkedIn: link_preview (default true; false publishes a text post with a link without its preview card).',
'LinkedIn (profile and page): document_title (≤300, the title shown on a PDF document post; defaults to the file name).',
'Google Business Profile: topic_type STANDARD (default)|EVENT|OFFER; call_to_action {action_type: '.implode('|', array_column(CtaAction::cases(), 'value')).', url} (not on OFFER; url required unless NONE or CALL); event {title ≤'.TopicType::TITLE_MAX_LENGTH.', start_date, end_date (YYYY-MM-DD), start_time, end_time (HH:MM)} (required on EVENT and OFFER, the title being the offer title); offer {coupon_code, redeem_online_url, terms_conditions ≤5000} (OFFER only).',
'Telegram, Facebook reels and stories: no settings. Stories (Instagram and Facebook) publish no text.',
'Threads of posts: thread_replies (list of up to '.ThreadReplies::MAX_REPLIES.' replies published under the post as a thread, each {text, media} where media is a list of up to 4 media items ({url}, {id} or {upload_token}, with optional meta.alt_text) for that reply alone; a plain string is a text-only reply) on Bluesky, Mastodon and X; on LinkedIn (profile and page) a post takes one reply, published as a comment from the same profile or page, text only, up to 3000 characters; each reply needs text or media, its media follows the rules of a post on that network, and its text must fit the account limit (Bluesky 300, Mastodon 500 including the content warning, which every reply repeats, X 280 or 25000 for accounts with long posts). On X and Mastodon a reply may instead be a poll: {text, poll} with poll under the same rules as that network\'s meta.poll, no media, and the reply text as its question (required; on X up to '.XPoll::QUESTION_MAX_LENGTH.' characters).',
]);
}
/**
* Adds the validation error for meta that becomes mandatory once a post is
* published or scheduled (TikTok privacy, Pinterest board, Discord channel).
*/
public static function addRequiredOnPublishErrors(Validator $validator, Platform|SocialAccount|null $target, mixed $meta, string $prefix = 'meta', ?ContentType $contentType = null): void
{
$violation = self::requiredMetaViolation($target, $meta, $contentType);
if (blank($violation)) {
return;
}
[$field, $message] = $violation;
$key = "{$prefix}.{$field}";
if (! $validator->errors()->has($key)) {
$validator->errors()->add($key, $message);
}
}
/**
* Asserts that the post's stored meta is enough to publish. Used by entry
* points that publish a post's stored state without resubmitting it (e.g.
* the MCP publish tool), so a misconfigured post fails fast with a clear
* message instead of only at publish time.
*
* @throws ValidationException
*/
public static function assertStoredPostPublishable(Post $post): void
{
if (! $post->hasDestination()) {
return;
}
$violation = self::requiredMetaViolation($post->socialAccount ?? $post->platform, $post->meta, $post->content_type)
?? self::contentMetaViolation($post->platform, $post->meta, (string) $post->content);
if (filled($violation)) {
[$field, $message] = $violation;
throw ValidationException::withMessages(["meta.{$field}" => $message]);
}
$question = transform($post->content_type?->poll(), fn (string $poll): ?string => $poll::questionViolation($post->content));
if (filled($question)) {
throw ValidationException::withMessages(['content' => $question]);
}
}
/**
* Meta keys stored as given by any entry point, normalized to the shape
* the composer and publishers read: the YouTube category id is a string and
* every thread reply is `{text, media}`.
*
* @param array<string, mixed> $meta
* @return array<string, mixed>
*/
public static function normalize(array $meta): array
{
if (is_int(data_get($meta, 'category_id'))) {
$meta['category_id'] = (string) $meta['category_id'];
}
if (is_string(data_get($meta, 'topic_tag'))) {
$meta['topic_tag'] = self::threadsTopicTag($meta['topic_tag']);
}
if (is_array(data_get($meta, 'thread_replies'))) {
$meta['thread_replies'] = ThreadReplies::of($meta);
}
if (is_array(data_get($meta, 'poll'))) {
$meta['poll'] = Poll::normalize($meta['poll']);
}
if (is_array(data_get($meta, 'collaborators'))) {
$meta['collaborators'] = self::instagramCollaborators($meta['collaborators']);
}
if (is_array(data_get($meta, 'audio'))) {
$meta['audio'] = Arr::only($meta['audio'], self::INSTAGRAM_AUDIO_FIELDS);
}
return $meta;
}
/**
* Instagram usernames as the API takes them: without the @, each once.
*
* @param array<int, mixed> $collaborators
* @return list<string>
*/
public static function instagramCollaborators(array $collaborators): array
{
return collect($collaborators)
->map(fn (mixed $username): string => ltrim(Str::trim((string) $username), '@'))
->filter()
->unique(fn (string $username): string => Str::lower($username))
->values()
->all();
}
/**
* A Threads topic as the API takes it: trimmed, without a leading #.
*/
public static function threadsTopicTag(string $value): string
{
return ltrim(Str::trim($value), '#');
}
/**
* Threads accepts 1-50 characters without . or &, judged after the leading # is dropped.
*/
private static function isThreadsTopicTag(string $value): bool
{
$tag = self::threadsTopicTag($value);
return $tag !== '' && mb_strlen($tag) <= 50 && preg_match('/[.&]/', $tag) !== 1;
}
/**
* Every meta value no post may store, even as a draft, keyed by field: a
* YouTube title with < or >, and on a poll (the post's or a reply's)
* repeated choices, a choice or a length beyond what the network takes.
*
* @return array<string, string>
*/
public static function formatErrors(?Platform $platform, ?array $meta, ?ContentType $contentType = null): array
{
if ($platform === Platform::YouTube) {
return transform(YouTubeMetadata::violation($meta), fn (array $violation): array => [$violation[0] => $violation[1]], []);
}
return [
...transform($contentType?->poll(), fn (string $poll): array => $poll::formatErrors($meta), []),
...ThreadReplies::pollFormatErrors($platform, $meta),
];
}
/**
* The missing required meta field for a platform about to publish, or null when
* nothing is missing. Single source of "what each platform requires to publish".
* Instagram music and trial reels only exist on reels, so their rules apply
* only when `$contentType` is a reel.
*
* @return array{0: string, 1: string}|null [field, message]
*/
public static function requiredMetaViolation(Platform|SocialAccount|null $target, mixed $meta, ?ContentType $type = null): ?array
{
$platform = $target instanceof SocialAccount ? $target->platform : $target;
$threadViolation = ThreadReplies::violation($target, $meta);
if ($threadViolation !== null) {
return $threadViolation;
}
$topicType = TopicType::fromMeta(data_get($meta, 'topic_type'));
$ctaAction = CtaAction::fromMeta(data_get($meta, 'call_to_action.action_type'));
$needsGoogleBusinessEvent = $platform === Platform::GoogleBusiness && $topicType->requiresEvent();
return match (true) {
$platform === Platform::YouTube => self::youtubeDescriptionViolation($meta) ?? YouTubeMetadata::violation($meta),
$platform === Platform::TikTok => self::tiktokPrivacyViolation($meta),
$type === ContentType::InstagramReel => self::instagramReelViolation($platform, $meta),
$type?->isPoll() === true => $type->poll()::firstViolation($meta),
$platform === Platform::Pinterest && blank(data_get($meta, 'board_id')) => ['board_id', trans('posts.form.pinterest.board_required')],
$platform === Platform::Discord && blank(data_get($meta, 'channel_id')) => ['channel_id', trans('posts.form.discord.channel_required')],
$needsGoogleBusinessEvent
&& blank(data_get($meta, 'event.title')) => [
'event.title',
trans($topicType === TopicType::Offer
? 'posts.form.google_business.offer_title_required'
: 'posts.form.google_business.event_title_required'),
],
$needsGoogleBusinessEvent
&& self::googleBusinessEventTitleExceedsLimit($meta) => [
'event.title',
trans('posts.form.google_business.title_max'),
],
$needsGoogleBusinessEvent
&& blank(data_get($meta, 'event.start_date')) => ['event.start_date', trans('posts.form.google_business.event_start_date_required')],
$needsGoogleBusinessEvent
&& blank(data_get($meta, 'event.end_date')) => ['event.end_date', trans('posts.form.google_business.event_end_date_required')],
$needsGoogleBusinessEvent
&& self::googleBusinessEventEndsBeforeStart($meta) => self::googleBusinessEventRangeViolation($meta),
$platform === Platform::GoogleBusiness
&& $topicType->allowsCallToAction()
&& $ctaAction->requiresUrl()
&& blank(data_get($meta, 'call_to_action.url')) => ['call_to_action.url', trans('posts.form.google_business.cta_url_required')],
default => null,
};
}
/**
* The meta keys a platform always needs before a post is scheduled or
* published, read from `requiredMetaViolation()` on empty meta. Meta that
* depends on other settings (a Google Business event) or that the text can
* stand in for (a YouTube title) is not listed.
*
* @return list<string>
*/
public static function requiredMetaKeys(Platform $platform): array
{
$violation = self::requiredMetaViolation($platform, []);
return $violation === null ? [] : [$violation[0]];
}
/**
* Required meta that the post text can stand in for, so it is only missing
* once the text is known: a YouTube title falls back to the first line.
*
* @return array{0: string, 1: string}|null [field, message]
*/
public static function contentMetaViolation(Platform $platform, mixed $meta, string $content): ?array
{
if ($platform !== Platform::YouTube) {
return null;
}
return YouTubeMetadata::missingTitleViolation(
is_array($meta) ? $meta : null,
app(ContentSanitizer::class)->sanitize($content, $platform),
);
}
/**
* @return array{0: string, 1: string}|null
*/
private static function youtubeDescriptionViolation(mixed $meta): ?array
{
$key = YouTubeDescription::violation(data_get($meta, 'description'));
return $key === null ? null : ['description', __($key)];
}
/**
* Event/offer titles over TITLE_MAX_LENGTH fail publish even when stored
* outside rules() — MCP PublishPostTool only runs requiredMetaViolation().
*/
private static function googleBusinessEventTitleExceedsLimit(mixed $meta): bool
{
$title = data_get($meta, 'event.title');
return filled($title) && Str::length((string) $title) > TopicType::TITLE_MAX_LENGTH;
}
/**
* Whether the Google Business event/offer schedule ends before it starts.
* Same-day times count: 18:00 → 09:00 is invalid even when the dates match.
*/
public static function googleBusinessEventEndsBeforeStart(mixed $meta): bool
{
$startDate = data_get($meta, 'event.start_date');
$endDate = data_get($meta, 'event.end_date');
if (blank($startDate) || blank($endDate)) {
return false;
}
$startDate = (string) $startDate;
$endDate = (string) $endDate;
if ($endDate < $startDate) {
return true;
}
if ($endDate !== $startDate) {
return false;
}
$startTime = data_get($meta, 'event.start_time');
$endTime = data_get($meta, 'event.end_time');
return filled($startTime) && filled($endTime) && (string) $endTime < (string) $startTime;
}
/**
* @return array{0: string, 1: string}
*/
private static function googleBusinessEventRangeViolation(mixed $meta): array
{
$sameDay = (string) data_get($meta, 'event.end_date') === (string) data_get($meta, 'event.start_date')
&& filled(data_get($meta, 'event.start_time'))
&& filled(data_get($meta, 'event.end_time'));
return $sameDay
? ['event.end_time', trans('posts.form.google_business.event_end_time_before_start')]
: ['event.end_date', trans('posts.form.google_business.event_end_date_before_start')];
}
/**
* Music needs a track id and an Instagram account connected through
* Facebook, and Instagram refuses a trial reel that has collaborators.
*
* @return array{0: string, 1: string}|null
*/
private static function instagramReelViolation(?Platform $platform, mixed $meta): ?array
{
return match (true) {
$platform === Platform::Instagram && filled(data_get($meta, 'audio.id')) => ['audio', trans('posts.form.instagram.music.requires_facebook')],
filled(data_get($meta, 'audio')) && blank(data_get($meta, 'audio.id')) => ['audio.id', trans('validation.required', ['attribute' => 'audio id'])],
filled(data_get($meta, 'trial_graduation')) && filled(data_get($meta, 'collaborators')) => ['trial_graduation', trans('posts.form.instagram.trial_reel.no_collaborators')],
default => null,
};
}
/**
* @return array{0: string, 1: string}|null
*/
private static function tiktokPrivacyViolation(mixed $meta): ?array
{
$privacyLevel = PrivacyLevel::tryFrom((string) data_get($meta, 'privacy_level'));
if ($privacyLevel === null) {
return ['privacy_level', trans('posts.form.tiktok.privacy_required')];
}
if ($privacyLevel === PrivacyLevel::SelfOnly && data_get($meta, 'brand_content_toggle')) {
return ['privacy_level', trans('posts.form.tiktok.privacy.private_disabled_branded')];
}
return null;
}
}