← Back
Editing: ShortCodeParser.php
<?php namespace FluentForm\App\Services\FormBuilder; use FluentForm\App\Models\SubmissionMeta; use FluentForm\App\Modules\Form\FormDataParser; use FluentForm\App\Modules\Form\FormFieldsParser; use FluentForm\App\Services\Browser\Browser; use FluentForm\Framework\Helpers\ArrayHelper; use FluentForm\App\Helpers\Helper; class ShortCodeParser { // community-events-location is core user meta that stores the user's IP address. const USER_SECRET_PROPERTIES = ['user_pass', 'user_activation_key', 'session_tokens', 'data', 'community-events-location']; protected static $form = null; protected static $entry = null; protected static $browser = null; protected static $formFields = null; protected static $provider = null; /** * Entry and acting user the cached {user.*} user was resolved for. */ protected static $userCacheKey = null; protected static $store = [ 'inputs' => null, 'original_inputs' => null, 'user' => null, 'post' => null, 'other' => null, 'submission' => null, ]; public static function parse($parsable, $entryId, $data = [], $form = null, $isUrl = false, $providerOrIsHTML = false, $htmlSanitized = false) { try { static::setDependencies($entryId, $data, $form, $providerOrIsHTML); if (is_array($parsable)) { return static::parseShortCodeFromArray($parsable, $isUrl, $providerOrIsHTML, $htmlSanitized); } return static::parseShortCodeFromString($parsable, $isUrl, $providerOrIsHTML, $htmlSanitized); } catch (\Exception $e) { if (defined('WP_DEBUG') && WP_DEBUG) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging only when WP_DEBUG is enabled, helps developers troubleshoot shortcode parsing issues error_log($e->getTraceAsString()); } return ''; } } protected static function setDependencies($entry, $data, $form, $provider) { static::setEntry($entry); static::setData($data); static::setForm($form); static::$provider = $provider; } protected static function setEntry($entry) { static::$entry = $entry; } protected static function setdata($data) { // The embed post comes from the inputs, so a new submission must not reuse the last one. static::$store['post'] = null; if (!is_null($data)) { static::$store['inputs'] = $data; static::$store['original_inputs'] = $data; } else { $data = json_decode(static::getEntry()->response, true); static::$store['inputs'] = $data; static::$store['original_inputs'] = $data; } } protected static function setForm($form) { if (!is_null($form)) { static::$form = $form; } else { static::$form = static::getEntry()->form_id; } } protected static function parseShortCodeFromArray($parsable, $isUrl = false, $provider = false, $htmlSanitized = false) { foreach ($parsable as $key => $value) { if (is_array($value)) { $parsable[$key] = static::parseShortCodeFromArray($value, $isUrl, $provider, $htmlSanitized); } else { $isHtml = false; if ($provider) { $isHtml = apply_filters_deprecated( 'ff_will_return_html', [ false, $provider, $key, ], FLUENTFORM_FRAMEWORK_UPGRADE, 'fluentform/will_return_html', 'Use fluentform/will_return_html instead of ff_will_return_html.' ); $isHtml = apply_filters('fluentform/will_return_html', $isHtml, $provider, $key); } if ('notifications' === $provider && in_array($key, ['cc', 'bcc'], true)) { $parsable[$key] = static::parseRecipientList($value); continue; } $parsable[$key] = static::parseShortCodeFromString($value, $isUrl, $isHtml, $htmlSanitized); } } return $parsable; } protected static function parseShortCodeFromString($parsable, $isUrl = false, $isHtml = false, $htmlSanitized = false) { if ('0' === $parsable) { return $parsable; } if (!$parsable) { return ''; } if ($htmlSanitized && !$isUrl) { return static::parseHtmlTemplate($parsable, $isHtml); } return preg_replace_callback('/{+(.*?)}/', function ($matches) use ($isUrl, $isHtml) { $value = static::resolveSmartCode($matches[1][0], $isHtml); // A complete URL that starts the template, like {wp.site_url}, stays as it is. // Anywhere later it is encoded, so a submitted value cannot add query parameters. $startsTemplate = 0 === $matches[0][1]; $isCompleteUrl = (bool) preg_match('#^https?://#i', (string) $value); if ($isUrl && !($startsTemplate && $isCompleteUrl)) { $value = rawurlencode($value); } // HTML bodies (email message, PDF) go through do_shortcode() for [ff_if] after this // parse, so a value must not add a shortcode or open or close a condition. if ($isHtml && !$isUrl && is_scalar($value)) { $value = Helper::encodeShortcodeBrackets($value); } return $value; }, $parsable, -1, $count, PREG_OFFSET_CAPTURE); } /** * Parse a cc or bcc recipient list. Each SmartCode must resolve to one valid address, as a * "To" field must, so a submitted value cannot add its own list of recipients. * * @param string $template * @return string */ protected static function parseRecipientList($template) { if (!is_string($template) || '' === $template) { return ''; } return preg_replace_callback('/{+(.*?)}/', function ($matches) { $choiceRecipients = static::choiceFieldRecipients($matches[1]); if (null !== $choiceRecipients) { return $choiceRecipients; } $value = trim((string) static::resolveSmartCode($matches[1])); return is_email($value) ? $value : ''; }, $template); } /** * Addresses a visitor picked in a checkbox, select or radio field, or null for other SmartCodes. * * Only exact option values the author wrote count, so several may be picked, but text typed * into an "Other" option cannot add an address. Dynamic Field options come from stored data, * so they are not trusted here. * * @param string $code SmartCode body, e.g. inputs.departments * @return string|null */ protected static function choiceFieldRecipients($code) { if (0 !== strpos($code, 'inputs.')) { return null; } $key = substr($code, strlen('inputs.')); // {inputs.x.value} is the raw value of the same field. if ('.value' === substr($key, -6)) { $key = substr($key, 0, -6); } if (is_null(static::$formFields)) { static::$formFields = FormFieldsParser::getShortCodeInputs( static::getForm(), ['admin_label', 'attributes', 'options', 'raw'] ); } $rawField = ArrayHelper::get(static::$formFields, $key . '.raw', []); $element = ArrayHelper::get($rawField, 'element'); if (!in_array($element, ['input_checkbox', 'select', 'input_radio'], true)) { return null; } $advancedOptions = ArrayHelper::get($rawField, 'settings.advanced_options', []); $flatOptions = Helper::flattenAdvancedOptions((array) $advancedOptions); $optionValues = array_map('sanitize_text_field', array_column($flatOptions, 'value')); $selected = (array) ArrayHelper::get(static::$store['original_inputs'], $key, []); $recipients = array_filter($selected, function ($value) use ($optionValues) { return is_string($value) && in_array($value, $optionValues, true) && is_email($value); }); return implode(',', $recipients); } /** * Parse SmartCodes in an HTML template with escaping that fits each value's position. * * A per-value kses pass leaves a bare `"` alone, so a value inside an attribute could close it. * The HTML API finds attribute values by real tokenizing; a regex split ends a tag at a quoted `>`. */ protected static function parseHtmlTemplate($template, $isHtml) { // Random per call, so a submitted value cannot forge a marker. $marker = 'ffsc' . bin2hex(random_bytes(8)); $markerPattern = '/' . $marker . '(\d+)e/'; $values = []; $marked = preg_replace_callback('/{+(.*?)}/', function ($matches) use ($isHtml, $marker, &$values) { $value = (string) static::resolveSmartCode($matches[1], $isHtml); // An unknown SmartCode comes back as literal brace text, e.g. JSON in a data attribute. if ('{' . $matches[1] . '}' === $value) { return $value; } $values[] = $value; return $marker . (count($values) - 1) . 'e'; }, $template); if (!$values) { return $marked; } $processor = new \WP_HTML_Tag_Processor($marked); $urls = []; while ($processor->next_tag()) { foreach ((array) $processor->get_attribute_names_with_prefix('') as $name) { static::fillAttribute($processor, $name, $marker, $markerPattern, $values, $urls); } } $html = $processor->get_updated_html(); foreach ($urls as $token => $url) { $html = str_replace('="' . $token . '"', '="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '"', $html); } $textMarkers = static::markersInText($html, $markerPattern); return preg_replace_callback($markerPattern, function ($matches) use ($values, $textMarkers) { // Not in text after the attribute pass: still inside a tag (a duplicate attribute or // another spot the attribute API does not expose), so the value cannot be placed safely. if (is_array($textMarkers) && !isset($textMarkers[$matches[0]])) { return ''; } return fluentform_sanitize_html($values[$matches[1]]); }, $html); } /** * Markers in text content, keyed by marker text: text nodes, comments and the contents of * textarea, title, style and script, as the HTML API tokenizes them. * * @param string $html * @param string $markerPattern * @return array|null Null when the HTML API cannot walk tokens (WordPress before 6.5, below the plugin minimum). */ protected static function markersInText($html, $markerPattern) { if (!method_exists('WP_HTML_Tag_Processor', 'next_token')) { return null; } $found = []; $walker = new \WP_HTML_Tag_Processor($html); while ($walker->next_token()) { $text = (string) $walker->get_modifiable_text(); if ('' !== $text && preg_match_all($markerPattern, $text, $matches)) { foreach ($matches[0] as $markerText) { $found[$markerText] = true; } } } return $found; } /** * Replace the markers in one attribute of the current tag with plain-text values. * * A URL attribute gets a "#token" stand-in value, listed in $urls and swapped for the URL * afterwards, because set_attribute() runs esc_url() on URL attributes, which strips a scheme * the form author wrote (whatsapp:, skype:) and %0A. The scheme is checked here instead. */ protected static function fillAttribute($processor, $name, $marker, $markerPattern, $values, &$urls = []) { // A SmartCode in an attribute name could write any attribute, e.g. an event handler. if (false !== strpos($name, $marker)) { $processor->remove_attribute($name); return; } $template = $processor->get_attribute($name); if (!is_string($template) || false === strpos($template, $marker)) { return; } // set_attribute() takes plain text, so decode first: an entity shows as its character, as in text. $value = preg_replace_callback($markerPattern, function ($matches) use ($values) { $plainValue = wp_strip_all_tags($values[$matches[1]]); return html_entity_decode($plainValue, ENT_QUOTES | ENT_HTML5, 'UTF-8'); }, $template); if (!static::isUrlAttribute($name)) { // set_attribute() escapes the value; it refuses one that escaping empties. if (!$processor->set_attribute($name, $value)) { $processor->remove_attribute($name); } return; } $authorPart = substr($template, 0, strpos($template, $marker)); $url = static::decodeEntitiesFully($value); if (!static::isAllowedUrl($url, static::decodeEntitiesFully($authorPart))) { $processor->remove_attribute($name); return; } // esc_url() keeps a fragment-only value as it is, so the token survives set_attribute(). $token = '#' . $marker . 'u' . count($urls); if ($processor->set_attribute($name, $token)) { $urls[$token] = $url; } else { $processor->remove_attribute($name); } } /** * Whether a URL attribute built from author text and SmartCode values may be written. * Always true for an attribute that is not a URL. * * @param string $name Attribute name. * @param string $url The composed URL, values in place. * @param string $authorPart The author's text before the first value. * @return bool */ public static function isSafeComposedUrl($name, $url, $authorPart) { if (!static::isUrlAttribute($name)) { return true; } $decodedUrl = static::decodeEntitiesFully($url); $decodedAuthorPart = static::decodeEntitiesFully($authorPart); return static::isAllowedUrl($decodedUrl, $decodedAuthorPart); } /** * Whether an attribute holds a URL a browser may follow or fetch. * * @param string $name * @return bool */ protected static function isUrlAttribute($name) { $urlAttributes = array_merge(wp_kses_uri_attributes(), ['xlink:href', 'ping']); return in_array(strtolower($name), $urlAttributes, true); } /** * Decode entities until the text stops changing, as a doubly encoded colon can survive one pass. * * @param string $text * @return string */ public static function decodeEntitiesFully($text) { for ($pass = 0; $pass < 5; $pass++) { $decoded = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8'); if ($decoded === $text) { break; } $text = $decoded; } return $text; } /** * Whether a composed URL may be written. Script schemes never; a scheme the form author * wrote before the first SmartCode is trusted; a scheme a value supplies must be allowed. * * @param string $url The composed, fully decoded URL. * @param string $authorPart The author's text before the first SmartCode, fully decoded. * @return bool */ protected static function isAllowedUrl($url, $authorPart) { $scheme = static::urlScheme($url); if ('' === $scheme) { return true; } if (in_array($scheme, ['javascript', 'vbscript'], true)) { return false; } if (static::urlScheme($authorPart) === $scheme) { return true; } return in_array($scheme, wp_allowed_protocols(), true); } /** * The URL scheme, lowercased, or '' for a relative URL. Browsers skip control characters * and spaces inside a scheme, so they are removed before matching. * * @param string $url * @return string */ protected static function urlScheme($url) { $compact = preg_replace('/[\x00-\x20\x7f]+/', '', (string) $url); return preg_match('/^([a-z][a-z0-9+.\-]*):/i', $compact, $matches) ? strtolower($matches[1]) : ''; } /** * Raw value of one SmartCode body (the text between the braces); arrays are joined. */ protected static function resolveSmartCode($code, $isHtml = false) { $value = ''; if (false !== strpos($code, 'inputs.')) { $formProperty = substr($code, strlen('inputs.')); $value = static::getFormData($formProperty, $isHtml); } elseif (false !== strpos($code, 'labels.')) { $formLabelProperty = substr($code, strlen('labels.')); $value = static::getFormLabelData($formLabelProperty); } elseif (false !== strpos($code, 'user.')) { $userProperty = substr($code, strlen('user.')); $value = static::getUserData($userProperty); } elseif (false !== strpos($code, 'embed_post.')) { $postProperty = substr($code, strlen('embed_post.')); $value = static::getPostData($postProperty); } elseif (false !== strpos($code, 'wp.')) { $wpProperty = substr($code, strlen('wp.')); $value = static::getWPData($wpProperty); } elseif (false !== strpos($code, 'submission.')) { $submissionProperty = substr($code, strlen('submission.')); $value = static::getSubmissionData($submissionProperty); } elseif (false !== strpos($code, 'cookie.')) { $scookieProperty = substr($code, strlen('cookie.')); $value = (!static::isBlockedCookie($scookieProperty) && array_key_exists($scookieProperty, $_COOKIE)) ? sanitize_text_field(wp_unslash($_COOKIE[$scookieProperty])) : ''; } elseif (false !== strpos($code, 'payment.')) { $property = substr($code, strlen('payment.')); $deprecatedValue = apply_filters_deprecated( 'fluentform_payment_smartcode', [ '', $property, self::getInstance(), ], FLUENTFORM_FRAMEWORK_UPGRADE, 'fluentform/payment_smartcode', 'Use fluentform/payment_smartcode instead of fluentform_payment_smartcode.' ); $value = apply_filters('fluentform/payment_smartcode', $deprecatedValue, $property, self::getInstance()); } else { $value = static::getOtherData($code); } if (is_array($value)) { $value = fluentImplodeRecursive(', ', $value); } return $value; } protected static function getFormData($key, $isHtml = false) { if (strpos($key, '.label')) { $key = str_replace('.label', '', $key); $isHtml = true; } if (strpos($key, '.value')) { $key = str_replace('.value', '', $key); return ArrayHelper::get(static::$store['original_inputs'], $key); } if (strpos($key, '.') && !isset(static::$store['inputs'][$key])) { return ArrayHelper::get( static::$store['original_inputs'], $key, '' ); } if (!isset(static::$store['inputs'][$key])) { static::$store['inputs'][$key] = ArrayHelper::get( static::$store['inputs'], $key, '' ); } if (is_null(static::$formFields)) { static::$formFields = FormFieldsParser::getShortCodeInputs( static::getForm(), ['admin_label', 'attributes', 'options', 'raw'] ); } $field = ArrayHelper::get(static::$formFields, $key, ''); if (!$field) { return ''; } if ($isHtml) { $originalInput = ArrayHelper::get(static::$store['original_inputs'], $key, ''); $originalInput = apply_filters_deprecated( 'fluentform_response_render_' . $field['element'], [ $originalInput, $field, static::getForm()->id, $isHtml, ], FLUENTFORM_FRAMEWORK_UPGRADE, 'fluentform/response_render_' . $field['element'], 'Use fluentform/response_render_' . $field['element'] . ' instead of fluentform_response_render_' . $field['element'] ); return apply_filters( 'fluentform/response_render_' . $field['element'], $originalInput, $field, static::getForm()->id, $isHtml ); } static::$store['inputs'][$key] = apply_filters_deprecated( 'fluentform_response_render_' . $field['element'], [ static::$store['inputs'][$key], $field, static::getForm()->id, $isHtml, ], FLUENTFORM_FRAMEWORK_UPGRADE, 'fluentform/response_render_' . $field['element'], 'Use fluentform/response_render_' . $field['element'] . ' instead of fluentform_response_render_' . $field['element'] ); return static::$store['inputs'][$key] = apply_filters( 'fluentform/response_render_' . $field['element'], static::$store['inputs'][$key], $field, static::getForm()->id, $isHtml ); } protected static function getFormLabelData($key) { if (is_null(static::$formFields)) { static::$formFields = FormFieldsParser::getShortCodeInputs( static::getForm(), ['admin_label', 'attributes', 'options', 'raw', 'label'] ); } // Resolve global validation messages {labels.current_field} shortcode. // Current field name attribute was setted as inputs data key 'current_field'. $currentFieldName = 'current_field' === $key ? ArrayHelper::get(static::$store['inputs'], $key) : null; if ($currentFieldName) { $currentFieldName = str_replace(['[', ']'], ['.', ''], $currentFieldName); $key = $currentFieldName; } $inputLabel = ArrayHelper::get(ArrayHelper::get(static::$formFields, $key, []), 'label', ''); $inputLabel = str_replace(['[', ']'], '', $inputLabel); $keys = explode('.', $key); if (count($keys) > 1) { $parentKey = array_shift($keys); $inputLabel = str_replace($parentKey, '', $inputLabel); } if (empty($inputLabel)) { $inputLabel = ArrayHelper::get(ArrayHelper::get(static::$formFields, $key, []), 'admin_label', ''); } if (empty($inputLabel) && isset($parentKey) && $parentKey) { $inputLabel = ArrayHelper::get(ArrayHelper::get(static::$formFields, $parentKey, []), 'label', ''); $key = $parentKey; } return apply_filters('fluentform/input_label_shortcode', $inputLabel, $key, static::getForm()); } protected static function getUserData($key) { // The user depends on the entry and on who runs the parse; a bulk resend changes both. $entry = static::$entry; $entryKey = is_object($entry) ? (isset($entry->id) ? (int) $entry->id : spl_object_id($entry)) : (int) $entry; $cacheKey = $entryKey . ':' . get_current_user_id(); if (is_null(static::$store['user']) || static::$userCacheKey !== $cacheKey) { static::$store['user'] = static::getSmartCodeUser(); static::$userCacheKey = $cacheKey; } $user = static::$store['user']; // SECURITY (FINDING-11): `$user->{$key}` reads straight from the wp_users row via // WP_User::__get, so an author-controlled {user.user_pass} (or {user.user_activation_key}) // would exfiltrate the *submitting* user's password hash / reset token in a notification. // Allow only a fixed set of safe profile fields; resolve anything else from user meta, // which never contains the sensitive wp_users columns. $allowed = [ 'ID', 'id', 'display_name', 'first_name', 'last_name', 'user_email', 'user_login', 'user_nicename', 'nickname', 'user_url', 'description', 'roles', 'user_registered', // non-sensitive wp_users column; keep {user.user_registered} working ]; if (static::isDeniedUserProperty($key)) { return ''; } if (in_array($key, $allowed, true)) { return $user->{$key}; } $key = (string) $key; // '' and '0' make get_user_meta() return every row. if (!$user->ID || '' === $key || '0' === $key) { return ''; } return get_user_meta($user->ID, $key, true); } /** * The user that {user.*} describes: the entry's submitter when there is an entry, else the current user. * * An admin approving, resending or replaying an entry is the current user, so resolving * against them would put the admin's profile into output the submitter receives. * Entries managers can reassign an entry's user_id, so the account is read only by that * account itself or by someone who may edit it. A logged-out run (payment return, IPN, * cron) is not proof of ownership, so it resolves no user, as it always did. * * @return \WP_User */ protected static function getSmartCodeUser() { $entry = static::$entry ? static::getEntry() : null; // Callers such as validation messages pass a stand-in object with no id; that is not an entry. if (!$entry || empty($entry->id)) { return wp_get_current_user(); } $entryUserId = (int) (isset($entry->user_id) ? $entry->user_id : 0); $currentUserId = get_current_user_id(); $canRead = $currentUserId && ($currentUserId === $entryUserId || current_user_can('edit_user', $entryUserId)); $user = ($entryUserId && $canRead) ? get_userdata($entryUserId) : false; return $user ? $user : new \WP_User(0); } /** * Whether a user column or meta key looks like a credential: protected "_" keys and token-like names. * * @param string $key * @return bool */ public static function isSensitiveUserMetaKey($key) { // Whole "_"/"-" segments, so profession, passport_number and author_bio still resolve; // a few joined forms (apikey, accesstoken) are matched anywhere. $pattern = apply_filters( 'fluentform/smartcode_sensitive_user_meta_pattern', '/^_|(^|[_-])(pass|passwd|password|pwd|token|tokens|secret|secrets|key|keys|auth|nonce|hash|otp|totp|hotp|2fa|mfa|api|session|sessions|capabilities|license|licence|credential|credentials|salt)([_-]|$)' . '|apikey|accesskey|secretkey|privatekey|accesstoken|authtoken|refreshtoken/' ); $matched = preg_match($pattern, strtolower(trim((string) $key))); // A broken filtered pattern must fail closed, not expose every key. return false === $matched || 1 === $matched; } /** * Whether the submitter may read the post they named as the embedding page. * * @param \WP_Post $post * @return bool */ protected static function canReadEmbedPost($post) { if (is_post_publicly_viewable($post)) { return true; } // read_post passes revisions via their parent and non-public types via plain 'read'. if (!is_post_type_viewable($post->post_type)) { return false; } $submitterId = static::getSubmitterId(); return $submitterId > 0 && user_can($submitterId, 'read_post', $post->ID); } /** * Whether the post's password hides its content from the submitter. WordPress shows the * title, permalink and author of such a post publicly, but not its content or fields. * * @param \WP_Post $post * @return bool */ protected static function isEmbedPostContentLocked($post) { if ('' === $post->post_password) { return false; } $submitterId = static::getSubmitterId(); if ($submitterId > 0 && user_can($submitterId, 'edit_post', $post->ID)) { return false; } // The password cookie belongs to whoever sent this request. Trust it only when that is // the submitter; an admin resend or a payment webhook must not unlock the post. if (get_current_user_id() !== $submitterId) { return true; } return post_password_required($post); } /** * The user who made the submission: the entry's user, or the current user before the entry exists. * * @return int */ protected static function getSubmitterId() { $entry = static::$entry ? static::getEntry() : null; // A stored entry with no user is a guest; never fall back to whoever is resending it. if (is_object($entry)) { return (int) ($entry->user_id ?? 0); } return get_current_user_id(); } protected static function getPostData($key) { if (is_null(static::$store['post'])) { $postId = static::$store['inputs']['__fluent_form_embded_post_id']; $post = get_post($postId); // The visitor submits the post ID, so it may name a private or draft post. static::$store['post'] = ($post && static::canReadEmbedPost($post)) ? $post : false; if (!static::$store['post']) { return ''; } static::$store['post']->permalink = get_the_permalink(static::$store['post']); } $post = static::$store['post']; if (!$post) { return ''; } $lockedKeys = ['post_content', 'post_excerpt', 'post_content_filtered']; $isLockedKey = in_array($key, $lockedKeys, true) || 0 === strpos($key, 'meta.') || 0 === strpos($key, 'acf.'); if ($isLockedKey && static::isEmbedPostContentLocked(static::$store['post'])) { return ''; } if (false !== strpos($key, 'author.')) { $authorProperty = substr($key, strlen('author.')); $authorId = $post->post_author; if ($authorId && !static::isDeniedUserProperty($authorProperty)) { $data = get_the_author_meta($authorProperty, $authorId); if (!is_array($data)) { return $data; } } return ''; } elseif (false !== strpos($key, 'meta.')) { $data = static::readEmbedPostMeta($post, substr($key, strlen('meta.'))); return is_array($data) ? '' : $data; } elseif (false !== strpos($key, 'acf.')) { $selector = substr($key, strlen('acf.')); if (!function_exists('get_field')) { if (static::isDeniedEmbedPostMetaKey($selector, $post)) { return ''; } } else { if (static::isDeniedEmbedPostAcfSelector($selector, $post) || static::isEmbedPostContentLocked($post)) { return ''; } $data = get_field($selector, $post->ID, true); return is_array($data) ? '' : $data; } } if ('post_password' === $key) { return ''; } // Real columns, the permalink we set, and WP_Post's computed properties. $computedProperties = ['page_template', 'post_category', 'tags_input', 'ancestors']; if (property_exists($post, $key) || in_array($key, $computedProperties, true)) { return $post->{$key}; } // Any other key is post meta, the same read WP_Post::__get() would do. return static::readEmbedPostMeta($post, $key); } /** * Single post-meta value for an {embed_post.*} SmartCode; '' when denied or password-locked. * * @param \WP_Post $post * @param string $metaKey * @return mixed */ protected static function readEmbedPostMeta($post, $metaKey) { if (static::isDeniedEmbedPostMetaKey($metaKey, $post) || static::isEmbedPostContentLocked($post)) { return ''; } return get_post_meta($post->ID, $metaKey, true); } /** * Whether an {embed_post.*} SmartCode must not read this meta key. * * @param string $metaKey * @param \WP_Post $post * @return bool */ public static function isDeniedEmbedPostMetaKey($metaKey, $post) { $metaKey = (string) $metaKey; // '' and '0' make get_post_meta() return every row, so no filter may allow them. if ('' === $metaKey || '0' === $metaKey) { return true; } // Protected keys that WooCommerce already shows publicly on the product page. $isPublicProductKey = 'product' === $post->post_type && in_array($metaKey, ['_price', '_regular_price', '_sale_price', '_sku'], true); $denied = is_protected_meta($metaKey, 'post') && !$isPublicProductKey; return (bool) apply_filters('fluentform/embed_post_smartcode_denied_meta', $denied, $metaKey, $post); } /** * Whether an ACF selector, or the field name ACF resolves it to, is denied. * * @param string $selector * @param \WP_Post $post * @return bool */ public static function isDeniedEmbedPostAcfSelector($selector, $post) { if (static::isDeniedEmbedPostMetaKey($selector, $post)) { return true; } // The same lookup get_field() does, so the checked name is the one ACF reads. $field = function_exists('acf_maybe_get_field') ? acf_maybe_get_field($selector, $post->ID) : false; $storageName = is_array($field) ? (string) ($field['name'] ?? '') : ''; return '' !== $storageName && static::isDeniedEmbedPostMetaKey($storageName, $post); } // Shared by {user.*} and {embed_post.author.*} in both parsers. get_the_author_meta() and // WP_User fall through to any user meta, where plugins keep 2FA secrets and tokens under // protected (underscore) keys, so the secret columns alone are not enough to deny. public static function isDeniedUserProperty($property) { // Same aliases get_the_author_meta() accepts: 'pass' means user_pass if (in_array($property, ['login', 'pass', 'nicename', 'email', 'url', 'registered', 'activation_key', 'status'], true)) { $property = 'user_' . $property; } $denied = (array) apply_filters('fluentform/smartcode_user_denied_properties', self::USER_SECRET_PROPERTIES); return in_array($property, $denied, true) || is_protected_meta($property, 'user') || static::isSensitiveUserMetaKey($property); } // A {cookie.*} smartcode is attacker-configurable (a form manager sets the notification body), // but resolves against the submitter's request, so an admin's auth cookie would be emailed out // and replayed. Block WordPress auth/session cookies; leave non-auth cookies (campaign, // comment_author) readable. Constants cover a site that renamed its auth cookies. public static function isBlockedCookie($name) { $blocked = 0 === strpos($name, 'wordpress_') || 0 === strpos($name, 'wp-postpass_'); if (!$blocked) { foreach (['AUTH_COOKIE', 'SECURE_AUTH_COOKIE', 'LOGGED_IN_COOKIE'] as $const) { if (defined($const) && constant($const) === $name) { $blocked = true; break; } } } return (bool) apply_filters('fluentform/smartcode_blocked_cookie', $blocked, $name); } protected static function getWPData($key) { if ('admin_email' === $key) { return get_option('admin_email'); } if ('site_url' === $key) { return site_url(); } if ('site_title' === $key) { return get_option('blogname'); } return $key; } protected static function getSubmissionData($key) { $entry = static::getEntry(); if (empty($entry->id)) { return ''; } $columns = Helper::getEntryColumns($entry); if (array_key_exists($key, $columns)) { $value = $entry->{$key}; if ('total_paid' === $key || 'payment_total' === $key) { return round($value / 100, 2); } if ('payment_method' === $key && 'test' === $value) { return __('Offline', 'fluentform'); } return $value; } if ('admin_view_url' === $key) { return admin_url('admin.php?page=fluent_forms&route=entries&form_id=' . $entry->form_id . '#/entries/' . $entry->id); } elseif ('entry_uid' === $key) { return static::getShortEntryUid($entry); } elseif ('entry_uid_link' === $key) { return static::getEntryUidLink($entry); } elseif (false !== strpos($key, 'meta.')) { $metaKey = substr($key, strlen('meta.')); $data = Helper::getSubmissionMeta($entry->id, $metaKey); if (!is_array($data)) { return $data; } return ''; } return ''; } protected static function getOtherData($key) { if (0 === strpos($key, 'date.')) { $format = str_replace('date.', '', $key); // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date -- {date.*} has always reported PHP's runtime timezone (c, T, U); gmdate() would change it. return date($format, strtotime(current_time('mysql'))); } elseif ('admin_email' === $key) { return get_option('admin_email', false); } elseif ('ip' === $key) { return static::getRequest()->getIp(); } elseif ('browser.platform' === $key) { return static::getUserAgent()->getPlatform(); } elseif ('browser.name' === $key) { return static::getUserAgent()->getBrowser(); } elseif (in_array($key, ['all_data', 'all_data_without_hidden_fields'], true)) { $formFields = FormFieldsParser::getEntryInputs(static::getForm()); $inputLabels = FormFieldsParser::getAdminLabels(static::getForm(), $formFields); $response = FormDataParser::parseFormSubmission(static::getEntry(), static::getForm(), $formFields, true); $status = apply_filters_deprecated( 'fluentform_all_data_skip_password_field', [ __return_true(), ], FLUENTFORM_FRAMEWORK_UPGRADE, 'fluentform/all_data_skip_password_field', 'Use fluentform/all_data_skip_password_field instead of fluentform_all_data_skip_password_field.' ); if (apply_filters('fluentform/all_data_skip_password_field', $status)) { $passwords = FormFieldsParser::getInputsByElementTypes(static::getForm(), ['input_password']); if (is_array($passwords) && !empty($passwords)) { $user_inputs = $response->user_inputs; ArrayHelper::forget($user_inputs, array_keys($passwords)); $response->user_inputs = $user_inputs; } } $hideHiddenField = true; $hideHiddenField = apply_filters_deprecated( 'fluentform_all_data_without_hidden_fields', [ $hideHiddenField, ], FLUENTFORM_FRAMEWORK_UPGRADE, 'fluentform/all_data_without_hidden_fields', 'Use fluentform/all_data_without_hidden_fields instead of fluentform_all_data_without_hidden_fields.' ); $skipHiddenFields = ('all_data_without_hidden_fields' === $key) && apply_filters('fluentform/all_data_without_hidden_fields', $hideHiddenField); if ($skipHiddenFields) { $hiddenFields = FormFieldsParser::getInputsByElementTypes(static::getForm(), ['input_hidden']); if (is_array($hiddenFields) && !empty($hiddenFields)) { ArrayHelper::forget($response->user_inputs, array_keys($hiddenFields)); } } $html = '<table class="ff_all_data" width="600" cellpadding="0" cellspacing="0"><tbody>'; foreach ($inputLabels as $inputKey => $label) { if (array_key_exists($inputKey, $response->user_inputs) && '' !== ArrayHelper::get($response->user_inputs, $inputKey)) { $data = ArrayHelper::get($response->user_inputs, $inputKey); if (is_array($data) || is_object($data)) { continue; } // $label is admin-set, $data is already sanitized via fluentFormSanitizer() on submission insert $html .= '<tr class="field-label"><th style="padding: 6px 12px; background-color: #f8f8f8; text-align: left;"><strong>' . $label . '</strong></th></tr><tr class="field-value"><td style="padding: 6px 12px 12px 12px;">' . $data . '</td></tr>'; } } $html .= '</tbody></table>'; $html = apply_filters_deprecated( 'fluentform_all_data_shortcode_html', [ $html, $formFields, $inputLabels, $response, ], FLUENTFORM_FRAMEWORK_UPGRADE, 'fluentform/all_data_shortcode_html', 'Use fluentform/all_data_shortcode_html instead of fluentform_all_data_shortcode_html.' ); return apply_filters('fluentform/all_data_shortcode_html', $html, $formFields, $inputLabels, $response); } elseif ('http_referer' === $key) { return wp_get_referer(); } elseif (0 === strpos($key, 'pdf.download_link.')) { $key = apply_filters_deprecated( 'fluentform_shortcode_parser_callback_pdf.download_link.public', [ $key, static::getInstance(), ], FLUENTFORM_FRAMEWORK_UPGRADE, 'fluentform/shortcode_parser_callback_pdf.download_link.public', 'Use fluentform/shortcode_parser_callback_pdf.download_link.public instead of fluentform_shortcode_parser_callback_pdf.download_link.public.' ); return apply_filters('fluentform/shortcode_parser_callback_pdf.download_link.public', $key, static::getInstance()); } elseif (false !== strpos($key, 'random_string.')) { $exploded = explode('.', $key); $prefix = array_pop($exploded); $value = $prefix . uniqid(); return apply_filters('fluentform/shortcode_parser_callback_random_string', $value, $prefix, static::getInstance()); } elseif ('form_title' === $key) { return static::getForm()->title; } elseif (false !== strpos($key, 'chat_gpt_response.')) { if (defined('FLUENTFORMPRO') && class_exists('\FluentFormPro\classes\Chat\ChatFieldController')) { $exploded = explode('.', $key); $prefix = array_pop($exploded); if (!$prefix) { return ''; } $exploded = explode('_', $prefix); $formId = reset($exploded); $feedId = end($exploded); $chatGPT = new \FluentFormPro\classes\Chat\ChatFieldController(wpFluentForm()); if ($chatGPT->api->isApiEnabled()) { $entry = static::getEntry(); $lastResponse = SubmissionMeta::retrieve("chat_gpt_response_{$feedId}", $entry->id); if (!$lastResponse) { $response = $chatGPT->chatGPTSubmissionMessageHandler($formId, $feedId, static::getInstance()); SubmissionMeta::persist($entry->id, "chat_gpt_response_{$feedId}", $response, $formId); return $response; } return $lastResponse; } } return ''; } // if it's multi line then just return if (false !== strpos($key, PHP_EOL)) { // most probably it's a css return '{' . $key . '}'; } $groups = explode('.', $key); if (count($groups) > 1) { $group = array_shift($groups); $property = implode('.', $groups); $handlerValue = apply_filters_deprecated( 'fluentform_smartcode_group_' . $group, [ $property, static::getInstance(), ], FLUENTFORM_FRAMEWORK_UPGRADE, 'fluentform/smartcode_group_' . $group, 'Use fluentform/smartcode_group_' . $group . ' instead of fluentform_smartcode_group_' . $group ); $handlerValue = apply_filters('fluentform/smartcode_group_' . $group, $handlerValue, static::getInstance()); // phpcs:ignore Universal.Operators.StrictComparisons.LooseNotEqual -- add-on filters return any type; strict would change which values fall through. if ($handlerValue != $property) { return $handlerValue; } } // This fallback actually $handlerValue = apply_filters_deprecated( 'fluentform_shortcode_parser_callback_' . $key, [ '{' . $key . '}', static::getInstance(), ], FLUENTFORM_FRAMEWORK_UPGRADE, 'fluentform/shortcode_parser_callback_' . $key, 'Use fluentform/shortcode_parser_callback_' . $key . ' instead of fluentform_shortcode_parser_callback_' . $key ); $handlerValue = apply_filters('fluentform/shortcode_parser_callback_' . $key, $handlerValue, static::getInstance()); if ($handlerValue) { return $handlerValue; } return ''; } public static function getForm() { if (!is_object(static::$form)) { static::$form = wpFluent()->table('fluentform_forms')->find(static::$form); } return static::$form; } public static function getProvider() { return static::$provider; } public static function getEntry() { if (!is_object(static::$entry)) { static::$entry = wpFluent()->table('fluentform_submissions')->find(static::$entry); } return static::$entry; } protected static function getRequest() { return wpFluentForm('request'); } protected static function getUserAgent() { if (is_null(static::$browser)) { static::$browser = new Browser(); } return static::$browser; } public static function getInstance() { static $instance; if ($instance) { return $instance; } $instance = new static(); return $instance; } public static function getInputs() { return static::$store['original_inputs']; } /** * Get the entry UID link for a submission * * @param object $entry * @return string */ protected static function getEntryUidLink($entry) { // Check if entry already has the entry_uid_link property if (isset($entry->entry_uid_link)) { return $entry->entry_uid_link; } // Check if front-end entry view is enabled for this form $frontEndSettings = Helper::getFormMeta($entry->form_id, 'front_end_entry_view', []); if (ArrayHelper::get($frontEndSettings, 'status') !== 'yes') { return ''; } // Get the UID hash from submission meta $meta = wpFluent()->table('fluentform_submission_meta') ->where('response_id', $entry->id) ->where('meta_key', '_entry_uid_hash') ->first(); if (!$meta || !$meta->value) { return ''; } // Generate the link return site_url('?ff_entry=1&hash=' . $meta->value); } protected static function getShortEntryUid($entry) { if (empty($entry->id)) { return ''; } $entryId = strtoupper(base_convert((string) absint($entry->id), 10, 36)); $entryHash = SubmissionMeta::retrieve('_entry_uid_hash', $entry->id); if (!$entryHash) { return $entryId; } return $entryId . '-' . strtoupper(substr($entryHash, 0, 4)); } public static function resetData() { self::$form = null; self::$entry = null; self::$browser = null; self::$formFields = null; FormFieldsParser::resetData(); FormDataParser::resetData(); } }
Save File
Cancel