, in "), * kept in the settings; our page follows a new title while its title is still * one the plugin gave it (aiprofile_inside_retitle_page()). * * Since 1.4.2: "Update this site automatically" starts ticked on the Connect * screen (a site connected before shows its stored choice), and the settings * screen asks the owner to turn on WordPress's own automatic updates for this * plugin. Only the owner's click adds it to auto_update_plugins; the card is * hidden when they are on, forced or disabled, and "No thanks" hides it * (includes/admin.php, includes/admin-screen.php). */ if ( ! defined( 'ABSPATH' ) ) { exit; } define( 'AIPROFILE_INSIDE_VERSION', '1.4.2' ); define( 'AIPROFILE_INSIDE_FILE', __FILE__ ); /** How long a fetched fragment is served before we ask again. */ define( 'AIPROFILE_INSIDE_FRESH_TTL', 10 * MINUTE_IN_SECONDS ); /** How long the last good copy is kept as a fallback. */ define( 'AIPROFILE_INSIDE_GOOD_TTL', 7 * DAY_IN_SECONDS ); /** After a failed fetch, wait this long before trying again. */ define( 'AIPROFILE_INSIDE_RETRY_TTL', 2 * MINUTE_IN_SECONDS ); /** Option that lists the cache keys in use, so uninstall can clean them up. */ define( 'AIPROFILE_INSIDE_KEYS_OPTION', 'aiprofile_inside_cache_keys' ); /** Option with the outcome of the most recent fetch (shown on the settings screen). */ define( 'AIPROFILE_INSIDE_STATUS_OPTION', 'aiprofile_inside_last_fetch' ); /** Option with the profile connected in Settings, AiProfile, its page and the switches. */ define( 'AIPROFILE_INSIDE_SETTINGS_OPTION', 'aiprofile_inside_settings' ); /** * Where the AiProfile platform lives. Production by default; a test site can * point at another deploy with * define( 'AIPROFILE_INSIDE_ORIGIN', 'https://wip.aiprofile.tech' ); * in wp-config.php, or with the `aiprofile_inside_origin` filter. * * @return string Origin without a trailing slash, or '' when it is not https. */ function aiprofile_inside_origin() { $origin = defined( 'AIPROFILE_INSIDE_ORIGIN' ) ? AIPROFILE_INSIDE_ORIGIN : 'https://www.aiprofile.com'; $origin = apply_filters( 'aiprofile_inside_origin', $origin ); return untrailingslashit( esc_url_raw( (string) $origin, array( 'https' ) ) ); } /** * The connection made in Settings, AiProfile. * * @return array { key, name, page_id, menu, adopted } plus the switches, or an empty array. */ function aiprofile_inside_settings() { $s = get_option( AIPROFILE_INSIDE_SETTINGS_OPTION, array() ); return is_array( $s ) ? $s : array(); } /** * One switch, with its default. Everything that sends more to AiProfile than * the content request, or that changes the site beyond the answers page, is * off until the owner switches it on. * * @param string $name instant, questions, schema, llms, credit, robots_fix, layout or visits. * @return mixed */ function aiprofile_inside_option( $name ) { $defaults = array( 'instant' => false, // Register the site for pings (sends the site address and a key). Ticked on the Connect form since 1.4.2. 'questions' => false, // The question form under the answers. 'schema' => 'faq', // LocalBusiness JSON-LD: off, faq (the answers page) or site. 'llms' => false, // Serve /llms.txt. 'credit' => false, // The "Powered by AiProfile" link (wordpress.org guideline 10: opt-in). 'robots_fix' => false, // Let AI crawlers in through the virtual robots.txt. 'layout' => 'auto', // The answers page's layout: auto, plugin or theme (includes/layout.php). 'visits' => false, // Report each view of the answers page to AiProfile (includes/visits.php, 1.4.0). ); $s = aiprofile_inside_settings(); return array_key_exists( $name, $s ) ? $s[ $name ] : ( isset( $defaults[ $name ] ) ? $defaults[ $name ] : null ); } /** * The profile key from a link or the shortcode. Accepts: * - the short link: aiprofile.com/, with or without https:// or www.; * - a profile URL or path: /nl/netherlands/amsterdam/cafe-de-jaren; * - the business id or the handle on its own. * * @param string $raw What the owner pasted or the shortcode said. * @return string Key with only safe characters, or ''. */ function aiprofile_inside_normalize_key( $raw ) { $raw = trim( (string) $raw ); $raw = (string) preg_replace( '#^[a-z]+://#i', '', $raw ); // A host in front (aiprofile.com/..., www.aiprofile.com/...): keep the path. if ( preg_match( '#^[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+(:\d+)?(/.*)?$#', $raw, $m ) ) { $raw = isset( $m[3] ) ? $m[3] : ''; } $raw = (string) preg_replace( '#[?\#].*$#', '', $raw ); $parts = array_values( array_filter( explode( '/', $raw ), 'strlen' ) ); if ( 4 === count( $parts ) ) { $key = '/' . implode( '/', $parts ); } elseif ( 1 === count( $parts ) ) { $key = $parts[0]; } else { return ''; } return substr( (string) preg_replace( '#[^A-Za-z0-9_/-]#', '', $key ), 0, 200 ); } /** * The business name from the fragment's own heading, in any of its languages. * * @param string $html Fragment HTML (with its title). * @return string */ function aiprofile_inside_name_from_html( $html ) { if ( ! preg_match( '#

(.*?)

#s', (string) $html, $m ) ) { return ''; } $title = html_entity_decode( wp_strip_all_tags( $m[1] ), ENT_QUOTES, 'UTF-8' ); $patterns = array( '/^Veelgestelde vragen over (.+)$/u', '/^Frequently asked questions about (.+)$/u', '/^Häufige Fragen zu (.+)$/u', '/^Questions fréquentes sur (.+)$/u', '/^Preguntas frecuentes sobre (.+)$/u', '/^Domande frequenti su (.+)$/u', '/^Συχνές ερωτήσεις για (.+)$/u', '/^(.+) hakkında sık sorulan sorular$/u', '/^关于(.+)的常见问题$/u', ); foreach ( $patterns as $pattern ) { if ( preg_match( $pattern, $title, $n ) ) { return trim( $n[1] ); } } return trim( $title ); } /** * The language to ask for: the shortcode's `taal` (or `lang`), else the * site's own language. When the profile does not have that language, * AiProfile serves the profile's home language (the business's country * language, then English). A profile URL's own /nl/ does not count: it only * says which profile. * * @param string $attr The shortcode's taal or lang attribute. * @param string $key The normalized profile key. * @return string Two or three lowercase letters. */ function aiprofile_inside_lang( $attr, $key ) { unset( $key ); $lang = strtolower( (string) $attr ); if ( '' === $lang ) { $lang = (string) get_locale(); } $lang = strtolower( substr( (string) preg_replace( '/[^A-Za-z].*$/', '', $lang ), 0, 3 ) ); return '' !== $lang ? $lang : 'en'; } /** * The language AiProfile served the answers in: the fragment's own lang * attribute. AiProfile falls back to the profile's home language when it does * not have the one asked for, so this can differ from the site's. * * @param string $html Fragment HTML. * @return string Two or three lowercase letters, or ''. */ function aiprofile_inside_html_lang( $html ) { return preg_match( '#
array( 'class' => true, 'lang' => true, 'data-aiprofile-version' => true, ), 'h2' => array( 'class' => true ), 'h3' => array( 'class' => true ), 'details' => array( 'class' => true ), 'summary' => array( 'class' => true ), 'p' => array( 'class' => true ), 'small' => array(), 'a' => array( 'href' => true, 'rel' => true, 'target' => true, 'class' => true, 'title' => true, ), ); } /** * Sanitize the fragment's HTML: scripts and styles go entirely (content * included), then wp_kses keeps only the allow-list with http(s) links. * * @param string $html Fragment HTML. * @return string Safe HTML. */ function aiprofile_inside_kses( $html ) { $html = (string) preg_replace( '#<(script|style)\b[^>]*>.*?#is', '', (string) $html ); return wp_kses( $html, aiprofile_inside_allowed_html(), array( 'http', 'https' ) ); } /** * Fit the fragment's headings into the host page. By default the page's own * title (its H1) is the heading, so our "Frequently asked questions about ..." * title goes and the theme groups move up from h3 to h2: H1 page title, H2 * theme, then the questions. With $with_title the title stays as an h2 and the * groups stay h3, for a block in the middle of other content. * * @param string $html Sanitized fragment. * @param bool $with_title Keep our own heading. * @return string */ function aiprofile_inside_headings( $html, $with_title ) { if ( $with_title ) { return $html; } $html = (string) preg_replace( '#

.*?

\s*#s', '', $html ); return (string) preg_replace( '#.*?)#s', '', $html ); } /** * The "Powered by AiProfile" link in the fragment's stamp. Off by * default (wordpress.org guideline 10: a credit link is opt-in). When the * owner switches it on it is a normal, followed link: the point is that his * site and his verified profile are seen to belong together. * * @param string $html Sanitized fragment. * @param bool $show Whether the owner switched the link on. * @return string */ function aiprofile_inside_credit( $html, $show ) { if ( ! $show ) { return (string) preg_replace( '#

.*?

\s*#s', '', $html ); } return (string) preg_replace_callback( '#

.*?

#s', function ( $m ) { $p = str_replace( 'rel="nofollow noopener"', 'rel="noopener"', $m[0] ); $cdot = sprintf( '', esc_url( plugins_url( 'assets/cdot-disc.svg', AIPROFILE_INSIDE_FILE ) ), aiprofile_inside_style( 'cdot' ) ); // Since 1.3.8 the C-dot is an image of its own (assets/cdot-disc.svg), // no longer inside.css's ::before, so it shows without the stylesheet. // A callback, so nothing in the image's URL reads as a backreference. // Since 1.3.9 the link has a title: AiProfile sends one; a copy from // before that gets the plugin's own. return (string) preg_replace_callback( '#]*)>#', function ( $a ) use ( $cdot ) { $attrs = $a[1]; if ( false === strpos( $attrs, 'title="' ) ) { $attrs .= ' title="' . esc_attr( aiprofile_inside_credit_title() ) . '"'; } return '' . $cdot; }, $p, 1 ); }, $html ); } /** * The title of a link to AiProfile (since 1.3.9), on "Powered by AiProfile" * and the footer link. Always English, like "Powered by AiProfile" itself, * with the business name when the plugin knows it (the connected profile's * name, kept in the settings). * * @return string Plain text; escape it for an attribute. */ function aiprofile_inside_credit_title() { $settings = aiprofile_inside_settings(); $name = isset( $settings['name'] ) ? trim( wp_strip_all_tags( (string) $settings['name'] ) ) : ''; return '' !== $name ? sprintf( 'Questions answered by the owner of %s, via AiProfile', $name ) : 'Questions answered by the owner, via AiProfile'; } /** * The stamp at the top of the block (since 1.3.0): the check mark of * "✓ Verified by ..." gets a span of its own, so the stylesheet can colour * it green. Our own markup, added after sanitising. * * @param string $html Sanitized fragment. * @return string */ function aiprofile_inside_stamp( $html ) { return (string) preg_replace( '#(

)\x{2713}\s*#u', '$1 ', $html ); } /** * The AI services in the stamp as their marks (since 1.3.5). AiProfile sends * "Optimized for AI agents: ChatGPT, Google and Claude" as text (in the * profile's language for the "and"); the plugin puts the three marks from its * own assets/ in place of the names, each with its name as alt text, so a * crawler still reads the names. Our own markup, added after sanitising; no * image is loaded from AiProfile. An older plugin, or the script embed, keeps * the text. * * @param string $html Sanitized fragment. * @return string */ function aiprofile_inside_agents( $html ) { $agents = array( 'chatgpt' => 'ChatGPT', 'google' => 'Google', 'claude' => 'Claude', ); $marks = ''; foreach ( $agents as $file => $name ) { $marks .= sprintf( '%s', esc_url( plugins_url( 'assets/agent-' . $file . '.png', AIPROFILE_INSIDE_FILE ) ), esc_attr( $name ), esc_attr( $name ), aiprofile_inside_style( 'agent' ) ); } return (string) preg_replace_callback( '#

Optimized for AI agents:.*?

#s', function () use ( $marks ) { return '

Optimized for AI agents: ' . $marks . '

'; }, $html ); } /** * The inline styles (since 1.3.8), one per element. The same strings as * EMBED_STYLES in AiProfile's src/lib/embed/fragment.ts, which a test there * keeps equal: the block looks the same from the plugin and from the script * embed. Fixed strings of ours, never from the fragment. * * @return array Element name => CSS declarations. */ function aiprofile_inside_styles() { return array( 'root' => 'overflow-wrap:anywhere', 'question' => 'overflow-wrap:anywhere;white-space:normal', 'answer' => 'overflow-wrap:anywhere;white-space:normal', 'stamp' => 'box-sizing:border-box;display:flex;flex-wrap:wrap;align-items:center;column-gap:37px;row-gap:8px;width:fit-content;max-width:100%;margin:0 0 2em;padding:12px 18px;overflow:hidden;font-family:inherit;line-height:1.4;direction:ltr;text-align:left;text-transform:none;letter-spacing:normal;color:#18222f;background:#fff;border:1px solid #e2e8f0;border-radius:14px;box-shadow:0 6px 18px rgba(24,34,47,.06)', 'text' => 'flex:1 1 220px;min-width:0;max-width:max-content;margin:0;padding:0', 'verified' => 'margin:0 0 4px;padding:0;max-width:none;font-size:15px;line-height:1.4;color:#18222f', 'check' => 'margin-right:.15em;font-weight:700;color:#1f8a5b', 'optimized' => 'margin:0;padding:0;max-width:none;font-size:12px;font-weight:600;line-height:1.4;color:#556273', 'small' => 'font-size:inherit', 'agents' => 'display:inline-flex;align-items:center;gap:6px;margin-left:2px;vertical-align:middle', 'agent' => 'display:inline-block;width:auto;height:16px;max-width:none;margin:0;padding:0;border:0;border-radius:0;box-shadow:none;vertical-align:middle', 'credit' => 'flex:none;display:flex;align-items:center;align-self:stretch;margin:0 0 0 -19px;padding:0 0 0 18px;max-width:none;font-size:12px;line-height:1.4;white-space:nowrap;border-left:1px solid #e2e8f0', 'link' => 'display:inline-flex;align-items:center;gap:8px;font-weight:600;color:#556273 !important;text-decoration:none;background:none;border:0;box-shadow:none', 'cdot' => 'display:block;flex:none;width:22px;height:22px;max-width:none;margin:0;padding:0;border:0;border-radius:50%;box-shadow:none', 'intro' => 'margin:0 0 1.5em;max-width:none', ); } /** * One inline style, escaped for an attribute. * * @param string $name Element name in aiprofile_inside_styles(). * @return string */ function aiprofile_inside_style( $name ) { $styles = aiprofile_inside_styles(); return isset( $styles[ $name ] ) ? esc_attr( $styles[ $name ] ) : ''; } /** * The block's look as inline styles (since 1.3.8): the stamp is the designed * card (text left, "Powered by AiProfile" right of a thin line, under it on a * narrow screen) and long questions and answers wrap, with or without * inside.css. A headless front end that shows the page's HTML from the REST * API never loads the stylesheet; the inline styles travel with the HTML. Our * own markup, added after sanitising and after aiprofile_inside_stamp(), * aiprofile_inside_agents() and aiprofile_inside_credit(), whose patterns * expect the bare tags. * * @param string $html Sanitized fragment with the plugin's own markup. * @return string */ function aiprofile_inside_inline_styles( $html ) { $html = (string) preg_replace_callback( '#
.*?
#s', function ( $m ) { // The text column: the Verified and Optimized lines in one div, so // the credit sits right of both. Built here, never taken from the // fragment (the kses list has no div), so it also holds for a cached // copy from before AIP-695. $stamp = (string) preg_replace_callback( '#^(
)((?:

.*?

)?\s*(?:

.*?

)?)#s', function ( $t ) { return '' === trim( $t[2] ) ? $t[0] : $t[1] . '
' . $t[2] . '
'; }, $m[0], 1 ); return strtr( $stamp, array( '
' => '
', '
' => '
', '

' => '

', '

' => '

', '

' => '

', '' => '', ) ); }, $html, 1 ); $html = (string) preg_replace( '#

#', '
', $html, 1 ); return strtr( $html, array( '' => '', '

' => '

', // The first sentence above the answers (since 1.4.1, AIP-703). '

' => '

', ) ); } /** The block's small stylesheet: sentence case, spacing and the credit's hover (assets/inside.css). */ function aiprofile_inside_enqueue_style() { wp_enqueue_style( 'aiprofile-inside', plugins_url( 'assets/inside.css', AIPROFILE_INSIDE_FILE ), array(), AIPROFILE_INSIDE_VERSION ); } /** * Load it in the head already on a page whose content holds the shortcode, * so a classic theme does not print it late in the footer. Nowhere else. */ function aiprofile_inside_maybe_enqueue_style() { if ( ! is_singular() ) { return; } $post = get_post(); if ( $post && has_shortcode( (string) $post->post_content, 'aiprofile' ) ) { aiprofile_inside_enqueue_style(); } } add_action( 'wp_enqueue_scripts', 'aiprofile_inside_maybe_enqueue_style' ); /** * The profile URL on AiProfile, from the fragment's credit link. * * @param string $html Fragment. * @return string */ function aiprofile_inside_profile_url_from_html( $html ) { if ( preg_match( '#

.*?href="([^"]+)"#s', (string) $html, $m ) ) { return esc_url_raw( html_entity_decode( $m[1], ENT_QUOTES, 'UTF-8' ), array( 'https', 'http' ) ); } return ''; } /** * Is a shortcode attribute switched on? Accepts ja, yes, 1, true, on. * * @param string $value Attribute value. * @return bool */ function aiprofile_inside_truthy( $value ) { return in_array( strtolower( trim( (string) $value ) ), array( '1', 'ja', 'yes', 'true', 'on', 'y', 'j' ), true ); } /** * Leave the X-AiProfile-Page header out of the content requests of this * request (since 1.4.1): during Connect the stored page id can still be the * one from before (a reinstall), and "none" would clear the profile's link * to the answers page. The next front-end fetch reports the real page. * * @param bool|null $skip True or false to set, null to read. * @return bool */ function aiprofile_inside_skip_page_header( $skip = null ) { static $skipped = false; if ( null !== $skip ) { $skipped = (bool) $skip; } return $skipped; } /** * The X-AiProfile-Page header (since 1.3.9): the address of the answers page * when $key is the connected profile and its page is published, "none" when * that page is not published (any more), and '' (no header) for any other * profile, which the shortcode can also show. * * @param string $key Profile key of the request. * @return string */ function aiprofile_inside_answers_page_header( $key ) { $settings = aiprofile_inside_settings(); if ( empty( $settings['key'] ) || aiprofile_inside_normalize_key( (string) $settings['key'] ) !== $key ) { return ''; } $page_id = isset( $settings['page_id'] ) ? (int) $settings['page_id'] : 0; if ( ! $page_id || 'publish' !== get_post_status( $page_id ) ) { return 'none'; } $url = esc_url_raw( (string) get_permalink( $page_id ), array( 'https', 'http' ) ); return '' !== $url ? $url : 'none'; } /** * The arguments for every request to AiProfile: short timeout, our * User-Agent, and the site's address as Referer (as WordPress itself sends in * its own User-Agent), so AiProfile can count which sites show which profile. * Nothing about visitors. * * @param array $extra Arguments to add or override. * @return array */ function aiprofile_inside_http_args( $extra = array() ) { return array_merge( array( 'timeout' => 5, 'redirection' => 2, 'limit_response_size' => 1024 * 1024, 'user-agent' => 'AiProfileInside/' . AIPROFILE_INSIDE_VERSION . ' (WordPress/' . get_bloginfo( 'version' ) . '; ' . home_url( '/' ) . ')', 'headers' => array( 'Accept' => 'text/html', 'Referer' => home_url( '/' ), ), ), $extra ); } /** * Keep the language the connected profile's answers come in (since 1.4.0, * settings `answers_lang`), for the footer link's text, and (since 1.4.1) the * page title and footer alt text AiProfile sends (settings `texts`). Only for * the site's own language (what the answers page shows), and written only when * it changed. * * @param string $key Profile key of the fetch. * @param string $lang Language asked for. * @param string $html The fetched fragment. * @param array $texts { pageTitle, footerAlt } from AiProfile, or an empty array. */ function aiprofile_inside_note_answers_lang( $key, $lang, $html, $texts = array() ) { $settings = aiprofile_inside_settings(); if ( empty( $settings['key'] ) || aiprofile_inside_normalize_key( (string) $settings['key'] ) !== $key ) { return; } $changed = false; $served = aiprofile_inside_html_lang( $html ); $site_lang = aiprofile_inside_site_own_lang(); // The answers page's language is set at Connect. It follows a fetch only // in the site's own language (site_lang, kept at Connect): when the // profile gains the site's language, the answers switch to it. A fetch in // any other language never changes it: on a multilingual site (Polylang, // WPML) the locale differs per request, and /en/ and /nl/ would take // turns. A site from before 1.4.1 without a language takes the first one // a fetch in its own language brings. if ( '' !== $served && ( ( $served === $site_lang && ( empty( $settings['answers_lang'] ) || $settings['answers_lang'] !== $served ) ) || ( empty( $settings['answers_lang'] ) && $site_lang === $lang ) ) ) { $settings['answers_lang'] = $served; $changed = true; } // Since 1.4.1 (AIP-703): the page title and footer alt text AiProfile // sends with the answers, only when they are in the language of the // answers page (answers_lang), so other languages never rename it. A new // title renames our page while its title is still one we gave it. $retitle = false; $ours = '' !== $served && ! empty( $settings['answers_lang'] ) && $settings['answers_lang'] === $served; if ( $ours && ! empty( $texts ) && ( ! isset( $settings['texts'] ) || $settings['texts'] !== $texts ) ) { $retitle = ! isset( $settings['texts']['pageTitle'] ) || $settings['texts']['pageTitle'] !== $texts['pageTitle']; $settings['texts'] = $texts; $changed = true; } if ( $changed ) { update_option( AIPROFILE_INSIDE_SETTINGS_OPTION, $settings, false ); } if ( $retitle && function_exists( 'aiprofile_inside_retitle_later' ) ) { aiprofile_inside_retitle_later(); } } /** * The site's own language (since 1.4.1): kept in the settings at Connect * (`site_lang`), else the language set under Settings, General, never the * locale of this request, which a multilingual plugin changes per page. * * @return string Two or three lowercase letters. */ function aiprofile_inside_site_own_lang() { $settings = aiprofile_inside_settings(); if ( ! empty( $settings['site_lang'] ) ) { return (string) $settings['site_lang']; } $locale = (string) get_option( 'WPLANG' ); return aiprofile_inside_lang( '' !== $locale ? $locale : 'en_US', '' ); } /** * The texts AiProfile sends with the answers (since 1.4.1, AIP-703): the X-AiProfile-Texts header, * percent-encoded JSON with the page title and the footer alt text in the answers' language. * Plain text, at most 300 characters each; only when both are there. * * @param array|WP_Error $response The content request's response. * @return array { pageTitle, footerAlt }, or an empty array. */ function aiprofile_inside_texts_from_response( $response ) { $raw = (string) wp_remote_retrieve_header( $response, 'x-aiprofile-texts' ); $data = '' !== $raw ? json_decode( rawurldecode( $raw ), true ) : null; if ( ! is_array( $data ) || empty( $data['pageTitle'] ) || empty( $data['footerAlt'] ) ) { return array(); } // Plain text: tags out, white space as one space, at most 300 characters // (mb_substr: a business name can hold any letter). Not // sanitize_text_field, which would eat a "%" followed by two hex digits; // wp_update_post() escapes the title itself. // A "<" that cannot start a tag ("Tom <3 Coffee") is kept: it is set // aside before the tags go and put back after, as sanitize_text_field // does with its own check. $clean = function ( $value ) { $text = (string) preg_replace( '/<(?![a-zA-Z\/!?])/', "\x01", (string) $value ); $text = str_replace( "\x01", '<', wp_strip_all_tags( $text ) ); $text = trim( (string) preg_replace( '/\s+/u', ' ', $text ) ); return trim( mb_substr( $text, 0, 300 ) ); }; $texts = array( 'pageTitle' => $clean( $data['pageTitle'] ), 'footerAlt' => $clean( $data['footerAlt'] ), ); return '' !== $texts['pageTitle'] && '' !== $texts['footerAlt'] ? $texts : array(); } /** * Fetch the fragment from AiProfile. * * @param string $key Profile key. * @param string $lang Language. * @return array { * @type string $status 'ok', 'not_found' or 'error'. * @type string $html Sanitized fragment (status ok). * @type array $jsonld Decoded FAQPage JSON-LD, or null. * @type string $detail HTTP code or error text, for the status line. * } */ function aiprofile_inside_fetch( $key, $lang ) { $origin = aiprofile_inside_origin(); if ( '' === $origin ) { return array( 'status' => 'error', 'detail' => 'origin is not an https URL', ); } $url = $origin . '/api/v1/embed?id=' . rawurlencode( $key ) . '&lang=' . rawurlencode( $lang ); // After a ping: a new address, so no cache on the way serves the old copy. $bust = aiprofile_inside_bust(); if ( $bust ) { $url .= '&v=' . $bust; } // Since 1.3.5 the request also says whether the owner switched "Link to // your AiProfile" on, so AiProfile can count the sites that link back. $headers = array( 'Accept' => 'text/html', 'Referer' => home_url( '/' ), 'X-AiProfile-Credit' => aiprofile_inside_option( 'credit' ) ? 'on' : 'off', ); // Since 1.3.9, for the connected profile only: where the answers page is, // so the AiProfile profile can link to it ("none" when it is not published). $page = aiprofile_inside_skip_page_header() ? '' : aiprofile_inside_answers_page_header( $key ); if ( '' !== $page ) { $headers['X-AiProfile-Page'] = $page; } $response = wp_safe_remote_get( $url, aiprofile_inside_http_args( array( 'headers' => $headers, ) ) ); if ( is_wp_error( $response ) ) { return array( 'status' => 'error', 'detail' => $response->get_error_message(), ); } $code = (int) wp_remote_retrieve_response_code( $response ); if ( 404 === $code || 400 === $code ) { // Authoritative: the profile does not exist, is archived, or has no answers. return array( 'status' => 'not_found', 'detail' => (string) $code, ); } $body = (string) wp_remote_retrieve_body( $response ); if ( 200 !== $code || false === strpos( $body, '

'error', 'detail' => 'HTTP ' . $code, ); } $jsonld = null; if ( preg_match( '##s', $body, $m ) ) { $decoded = json_decode( $m[1], true ); if ( is_array( $decoded ) ) { $jsonld = $decoded; } } return array( 'status' => 'ok', 'html' => aiprofile_inside_kses( $body ), 'jsonld' => $jsonld, 'texts' => aiprofile_inside_texts_from_response( $response ), 'detail' => (string) $code, ); } /** * Remember a cache key so uninstall and a ping can remove it even with an * object cache. * * @param string $cache_key Transient name. */ function aiprofile_inside_remember_key( $cache_key ) { $keys = get_option( AIPROFILE_INSIDE_KEYS_OPTION, array() ); if ( ! is_array( $keys ) ) { $keys = array(); } if ( in_array( $cache_key, $keys, true ) ) { return; } $keys[] = $cache_key; update_option( AIPROFILE_INSIDE_KEYS_OPTION, array_slice( $keys, -500 ), false ); } /** Drop the fresh cached copy of every profile; the last good copies stay. */ function aiprofile_inside_clear_fresh_cache() { $keys = get_option( AIPROFILE_INSIDE_KEYS_OPTION, array() ); foreach ( is_array( $keys ) ? $keys : array() as $cache_key ) { delete_transient( (string) $cache_key ); } } /** * The transient name for a key and language. Not keyed by origin: a wrong * AIPROFILE_INSIDE_ORIGIN keeps the last good copy. * * @param string $key Profile key. * @param string $lang Language. * @return string */ function aiprofile_inside_cache_key( $key, $lang ) { return 'aiprofile_inside_' . md5( $key . '|' . $lang ); } /** * The copy we keep of a successful fetch. Since 1.3.2 it says which profile * and language it is, so the twice-daily check (includes/page-cache.php) * knows what to fetch again. * * @param string $key Profile key. * @param string $lang Language. * @param array $result A fetch result with status ok. * @return array */ function aiprofile_inside_payload( $key, $lang, $result ) { return array( 'html' => $result['html'], 'jsonld' => $result['jsonld'], 'fetched_at' => time(), 'stale' => false, 'key' => $key, 'lang' => $lang, 'texts' => isset( $result['texts'] ) ? $result['texts'] : array(), ); } /** * The fragment for a key and language, from cache or from AiProfile. * * @param string $key Profile key. * @param string $lang Language. * @return array { html, jsonld, fetched_at, stale, key, lang } or an empty array. */ function aiprofile_inside_get( $key, $lang ) { $cache_key = aiprofile_inside_cache_key( $key, $lang ); $good_key = $cache_key . '_good'; $cached = get_transient( $cache_key ); if ( is_array( $cached ) ) { return $cached; } aiprofile_inside_remember_key( $cache_key ); $result = aiprofile_inside_fetch( $key, $lang ); $now = time(); if ( 'ok' === $result['status'] ) { $payload = aiprofile_inside_payload( $key, $lang, $result ); set_transient( $cache_key, $payload, AIPROFILE_INSIDE_FRESH_TTL ); set_transient( $good_key, $payload, AIPROFILE_INSIDE_GOOD_TTL ); $served = 'fresh'; aiprofile_inside_note_answers_lang( $key, $lang, $result['html'], isset( $result['texts'] ) ? $result['texts'] : array() ); } elseif ( 'not_found' === $result['status'] ) { $payload = array(); set_transient( $cache_key, $payload, AIPROFILE_INSIDE_FRESH_TTL ); delete_transient( $good_key ); $served = 'nothing (not found)'; } else { $good = get_transient( $good_key ); if ( is_array( $good ) && ! empty( $good['html'] ) ) { $payload = $good; $payload['stale'] = true; $served = 'last good copy'; } else { $payload = array(); $served = 'nothing (no copy yet)'; } set_transient( $cache_key, $payload, AIPROFILE_INSIDE_RETRY_TTL ); } update_option( AIPROFILE_INSIDE_STATUS_OPTION, array( 'time' => $now, 'key' => $key, 'lang' => $lang, 'status' => $result['status'], 'detail' => isset( $result['detail'] ) ? substr( (string) $result['detail'], 0, 200 ) : '', 'served' => $served, ), false ); return $payload; } /** * [aiprofile] or [aiprofile profiel="cmot2owhi1peqp2cpww02jr8v" taal="nl"] * * The page the wizard makes holds the bare [aiprofile]: the profile connected * in Settings, AiProfile. The attributes are the advanced route: * * profiel (or profile, or id): which AiProfile to show. The business id, the * owner's short handle (aiprofile.com/), or the profile's URL * or path such as /nl/netherlands/amsterdam/cafe-de-jaren. * taal (or lang): optional; defaults to the site's language when the profile * has it, then the profile's home language. * titel (or title): "ja" adds our own heading ("Veelgestelde vragen over * ...") as an h2. Off by default: the page's title is the heading. * jsonld: "0" leaves out the FAQPage structured data (for example when an SEO * plugin already prints it). Also the `aiprofile_inside_print_jsonld` * filter. * * @param array|string $atts Shortcode attributes. * @return string HTML. */ function aiprofile_inside_shortcode( $atts ) { // The answers page: the theme did show its content (includes/layout.php). aiprofile_inside_layout_note_render(); $atts = shortcode_atts( array( 'profiel' => '', 'profile' => '', 'id' => '', 'taal' => '', 'lang' => '', 'titel' => '', 'title' => '', 'jsonld' => '1', ), $atts, 'aiprofile' ); $raw = '' !== $atts['profiel'] ? $atts['profiel'] : ( '' !== $atts['profile'] ? $atts['profile'] : $atts['id'] ); $settings = aiprofile_inside_settings(); $connected = '' === trim( (string) $raw ); if ( $connected ) { // [aiprofile] on its own: the profile connected in Settings, AiProfile. $raw = isset( $settings['key'] ) ? $settings['key'] : ''; } $key = aiprofile_inside_normalize_key( $raw ); if ( '' === $key ) { return ''; } $lang = aiprofile_inside_lang( '' !== $atts['taal'] ? $atts['taal'] : $atts['lang'], $key ); if ( $connected && function_exists( 'aiprofile_inside_note_visit' ) ) { // Since 1.4.0, only when the owner switched it on: report this view (includes/visits.php). aiprofile_inside_note_visit( $key ); } $data = aiprofile_inside_get( $key, $lang ); if ( empty( $data['html'] ) ) { return ''; } $with_title = aiprofile_inside_truthy( '' !== $atts['titel'] ? $atts['titel'] : $atts['title'] ); $html = aiprofile_inside_headings( aiprofile_inside_kses( $data['html'] ), $with_title ); $html = aiprofile_inside_credit( $html, (bool) aiprofile_inside_option( 'credit' ) ); $html = aiprofile_inside_inline_styles( aiprofile_inside_agents( aiprofile_inside_stamp( $html ) ) ); $out = '
' . $html; aiprofile_inside_enqueue_style(); $print_jsonld = apply_filters( 'aiprofile_inside_print_jsonld', '0' !== (string) $atts['jsonld'], $key, $lang ); if ( $print_jsonld && ! empty( $data['jsonld'] ) && is_array( $data['jsonld'] ) ) { // Re-encoded from the decoded data, never the raw text: JSON_HEX_TAG // writes < and > as unicode escapes, so nothing can close the tag. $json = wp_json_encode( $data['jsonld'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP ); if ( is_string( $json ) ) { $out .= ''; } } $out .= '
'; // The question form only under the connected profile: the site is // registered for that one. if ( $connected && function_exists( 'aiprofile_inside_question_form' ) ) { $out .= aiprofile_inside_question_form( isset( $settings['name'] ) ? (string) $settings['name'] : '' ); } if ( ! empty( $data['stale'] ) && ! empty( $data['fetched_at'] ) ) { $out .= ''; } return $out; } add_shortcode( 'aiprofile', 'aiprofile_inside_shortcode' ); /** After activation, open the "Connect your AiProfile" screen once. */ function aiprofile_inside_activate() { set_transient( 'aiprofile_inside_activation_redirect', get_current_user_id(), 5 * MINUTE_IN_SECONDS ); } register_activation_hook( __FILE__, 'aiprofile_inside_activate' ); require_once __DIR__ . '/includes/site-link.php'; require_once __DIR__ . '/includes/schema.php'; require_once __DIR__ . '/includes/robots.php'; require_once __DIR__ . '/includes/form.php'; require_once __DIR__ . '/includes/footer.php'; require_once __DIR__ . '/includes/page-cache.php'; require_once __DIR__ . '/includes/answers-page.php'; require_once __DIR__ . '/includes/layout.php'; require_once __DIR__ . '/includes/visits.php'; // Only in the ZIP for direct installs, not in the WordPress.org build. if ( is_readable( __DIR__ . '/includes/languages.php' ) ) { require_once __DIR__ . '/includes/languages.php'; } if ( is_admin() ) { require_once __DIR__ . '/includes/admin.php'; }