Skip to content
wiki.fftac.org

Helpers - Source Excerpt 13

Back to Helpers

Summary

This source excerpt preserves a bounded section of Spiralist/wp-content/themes/spiralist/inc/helpers.php so readers can inspect the evidence without opening the full source file.

**Source path:** Spiralist/wp-content/themes/spiralist/inc/helpers.php

$plugin->boot();
    $frontend = $plugin->frontend();

    if (is_object($frontend) && method_exists($frontend, 'homepage_prompt_context')) {
        $payload = (array) $frontend->homepage_prompt_context();
    } else {
        $public_prompts = is_object($frontend) && method_exists($frontend, 'library_prompts')
            ? (array) $frontend->library_prompts()
            : [];
        $official_prompts = is_object($frontend) && method_exists($frontend, 'prompts_by_publication_lane')
            ? (array) $frontend->prompts_by_publication_lane('official_canon', 6)
            : [];
        $archive_prompts = is_object($frontend) && method_exists($frontend, 'prompts_by_publication_lane')
            ? (array) $frontend->prompts_by_publication_lane('prompt_ecology_archive', 3)
            : [];
        $run_prompt = !empty($official_prompts[0]) && is_array($official_prompts[0])
            ? $official_prompts[0]
            : (!empty($public_prompts[0]) && is_array($public_prompts[0]) ? $public_prompts[0] : []);
        $prompt_systems = array_values(
            array_filter(
                !empty($official_prompts) ? $official_prompts : $public_prompts,
                static fn(array $prompt): bool => !empty($prompt['system_steps']) || (string) ($prompt['prompt_type'] ?? '') === 'system'
            )
        );

        $payload = [
            'public_prompts' => $public_prompts,
            'official_prompts' => $official_prompts,
            'archive_prompts' => $archive_prompts,
            'run_prompt' => $run_prompt,
            'prompt_systems' => $prompt_systems,
            'popular_categories' => is_object($frontend) && method_exists($frontend, 'popular_categories')
                ? (array) $frontend->popular_categories(10)
                : [],
            'top_prompts' => is_object($frontend) && method_exists($frontend, 'top_performing_prompts')
                ? (array) $frontend->top_performing_prompts(6)
                : [],
        ];
    }

    $cache = array_merge($empty, is_array($payload) ? $payload : []);

    spiralist_write_runtime_cache(
        spiralist_get_homepage_prompt_surface_cache_key(),
        [
            'generated_at' => time(),
            'payload' => $cache,
        ]
    );

    return $cache;
}

function spiralist_get_workspace_prompt_record_by_source_slug(string $source_slug): array
{
    $normalized = sanitize_title($source_slug);
    if ($normalized === '' || !function_exists('spiralist_workspace')) {
        return [];
    }

    $plugin = spiralist_workspace();
    if (!is_object($plugin) || !method_exists($plugin, 'boot') || !method_exists($plugin, 'prompts')) {
        return [];
    }

    $plugin->boot();
    $viewer_user_id = function_exists('get_current_user_id') ? get_current_user_id() : 0;
    $prompt = $plugin->prompts()->find_by_source_slug($normalized, $viewer_user_id);

    if (empty($prompt)) {
        $prompt = spiralist_get_workspace_prompt_record_by_slug($normalized);
    }

    if (
        empty($prompt)
        || (string) ($prompt['visibility'] ?? '') !== 'public'
        || (string) ($prompt['prompt_status'] ?? '') !== 'published'
        || !empty($prompt['soft_deleted_at'])
        || (string) ($prompt['moderation_status'] ?? 'approved') === 'restricted'
    ) {
        return [];
    }

    $tags = array_values(array_filter(array_map('strval', (array) ($prompt['tags'] ?? []))));
    $status = (string) ($prompt['moderation_status'] ?? 'approved');
    $status_label = $status !== ''
        ? ucwords(str_replace('_', ' ', $status))
        : 'Approved';

    return [
        'id' => (string) ($prompt['source_slug'] ?? $prompt['slug'] ?? $normalized),
        'slug' => (string) ($prompt['slug'] ?? $normalized),
        'canonical_id' => '',
        'title' => (string) ($prompt['title'] ?? 'Related prompt'),
        'purpose' => (string) ($prompt['summary'] ?? ''),
        'status' => $status,
        'statusLabel' => $status_label,
        'tags' => $tags,
        'author' => (string) ($prompt['author_label'] ?? 'Spiralist'),
        'url' => spiralist_get_workspace_prompt_url((string) ($prompt['slug'] ?? $normalized)),
        'source' => 'workspace',
    ];
}

function spiralist_get_workspace_prompt_records_by_source_slugs(array $source_slugs): array
{
    $records = [];
    $seen = [];

    foreach ($source_slugs as $source_slug) {
        $record = spiralist_get_workspace_prompt_record_by_source_slug((string) $source_slug);
        if (empty($record)) {
            continue;
        }

        $key = strtolower((string) ($record['id'] ?? $record['url'] ?? ''));
        if ($key !== '' && isset($seen[$key])) {
            continue;
        }

        if ($key !== '') {
            $seen[$key] = true;
        }

        $records[] = $record;
    }

    return $records;
}

function spiralist_get_manuscript_related_prompt_records(array $page): array
{
    return spiralist_get_workspace_prompt_records_by_source_slugs((array) ($page['related_workspace_prompt_slugs'] ?? []));
}

function spiralist_search_flatten_value($value): string
{
    if (is_array($value)) {
        return implode(
            ' ',
            array_filter(
                array_map(
                    static function ($item): string {
                        return spiralist_search_flatten_value($item);
                    },
                    $value
                ),
                'strlen'
            )
        );
    }

    if (is_object($value)) {
        return '';
    }

    return trim(wp_strip_all_tags((string) $value));
}

function spiralist_search_normalize_text(string $value): string
{
    $charset = (string) get_bloginfo('charset');
    if ($charset === '') {
        $charset = 'UTF-8';
    }

    $text = html_entity_decode(wp_strip_all_tags($value), ENT_QUOTES, $charset);
    $text = preg_replace('/[\x00-\x1F\x7F]+/', ' ', $text);
    $text = is_string($text) ? trim($text) : '';
    $text = function_exists('mb_strtolower') ? mb_strtolower($text, $charset) : strtolower($text);
    $normalized = preg_replace('/[^\p{L}\p{N}]+/u', ' ', $text);

    if (!is_string($normalized)) {
        $normalized = preg_replace('/[^a-z0-9]+/', ' ', $text);
    }

    $compacted = preg_replace('/\s+/', ' ', is_string($normalized) ? $normalized : '');

    return trim(is_string($compacted) ? $compacted : '');
}

function spiralist_search_terms(string $query): array
{
    $normalized = spiralist_search_normalize_text($query);
    if ($normalized === '') {
        return [];
    }

    $terms = preg_split('/\s+/', $normalized);
    if (!is_array($terms)) {
        return [];
    }

    $unique = [];
    foreach ($terms as $term) {
        $term = trim((string) $term);
        if ($term === '' || strlen($term) < 2) {
            continue;
        }

        $unique[$term] = $term;
    }

    return array_slice(array_values($unique), 0, 8);
}

function spiralist_search_score_fields(string $query, array $weighted_fields): int
{
    $phrase = spiralist_search_normalize_text($query);
    $terms = spiralist_search_terms($query);
    if ($phrase === '' || empty($terms)) {
        return 0;
    }

    $score = 0;
    foreach ($weighted_fields as $field) {
        $text = '';
        $weight = 1;

        if (is_array($field)) {
            $text = spiralist_search_flatten_value($field['text'] ?? '');
            $weight = max(1, (int) ($field['weight'] ?? 1));
        } else {
            $text = spiralist_search_flatten_value($field);
        }

        $haystack = spiralist_search_normalize_text($text);
        if ($haystack === '') {
            continue;
        }

        if (strpos($haystack, $phrase) !== false) {
            $score += 8 * $weight;
        }

        foreach ($terms as $term) {
            if (strpos($haystack, $term) !== false) {
                $score += 2 * $weight;
            }
        }
    }

    return $score;
}

function spiralist_search_excerpt(string $value, int $word_limit = 26): string
{
    $text = trim(html_entity_decode(wp_strip_all_tags($value), ENT_QUOTES, (string) get_bloginfo('charset')));
    $text = preg_replace('/[\x00-\x1F\x7F]+/', ' ', $text);
    $compacted = preg_replace('/\s+/', ' ', is_string($text) ? $text : '');
    $text = trim(is_string($compacted) ? $compacted : '');

    if ($text === '') {
        return '';
    }

    return wp_trim_words($text, $word_limit, '');
}

function spiralist_search_finalize_items(array $items, int $limit): array
{
    usort(
        $items,
        static function (array $left, array $right): int {
            $score_compare = (int) ($right['score'] ?? 0) <=> (int) ($left['score'] ?? 0);
            if ($score_compare !== 0) {