Esempio n. 1
0
function fa_get_wpsmiliestrans()
{
    global $wpsmiliestrans;
    $wpsmilies = array_unique($wpsmiliestrans);
    foreach ($wpsmilies as $alt => $src_path) {
        $emoji = str_replace(array('&#x', ';'), '', wp_encode_emoji($src_path));
        $output .= '<a class="add-smily" data-smilies="' . $alt . '"><img class="wp-smiley" src="' . get_bloginfo('template_directory') . '/72x72/' . $emoji . 'png" /></a>';
    }
    return $output;
}
Esempio n. 2
0
/**
 * Insert or update a post.
 *
 * If the $postarr parameter has 'ID' set to a value, then post will be updated.
 *
 * You can set the post date manually, by setting the values for 'post_date'
 * and 'post_date_gmt' keys. You can close the comments or open the comments by
 * setting the value for 'comment_status' key.
 *
 * @since 1.0.0
 * @since 4.2.0 Support was added for encoding emoji in the post title, content, and excerpt.
 * @since 4.4.0 A 'meta_input' array can now be passed to `$postarr` to add post meta data.
 *
 * @see sanitize_post()
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @param array $postarr {
 *     An array of elements that make up a post to update or insert.
 *
 *     @type int    $ID                    The post ID. If equal to something other than 0,
 *                                         the post with that ID will be updated. Default 0.
 *     @type int    $post_author           The ID of the user who added the post. Default is
 *                                         the current user ID.
 *     @type string $post_date             The date of the post. Default is the current time.
 *     @type string $post_date_gmt         The date of the post in the GMT timezone. Default is
 *                                         the value of `$post_date`.
 *     @type mixed  $post_content          The post content. Default empty.
 *     @type string $post_content_filtered The filtered post content. Default empty.
 *     @type string $post_title            The post title. Default empty.
 *     @type string $post_excerpt          The post excerpt. Default empty.
 *     @type string $post_status           The post status. Default 'draft'.
 *     @type string $post_type             The post type. Default 'post'.
 *     @type string $comment_status        Whether the post can accept comments. Accepts 'open' or 'closed'.
 *                                         Default is the value of 'default_comment_status' option.
 *     @type string $ping_status           Whether the post can accept pings. Accepts 'open' or 'closed'.
 *                                         Default is the value of 'default_ping_status' option.
 *     @type string $post_password         The password to access the post. Default empty.
 *     @type string $post_name             The post name. Default is the sanitized post title.
 *     @type string $to_ping               Space or carriage return-separated list of URLs to ping.
 *                                         Default empty.
 *     @type string $pinged                Space or carriage return-separated list of URLs that have
 *                                         been pinged. Default empty.
 *     @type string $post_modified         The date when the post was last modified. Default is
 *                                         the current time.
 *     @type string $post_modified_gmt     The date when the post was last modified in the GMT
 *                                         timezone. Default is the current time.
 *     @type int    $post_parent           Set this for the post it belongs to, if any. Default 0.
 *     @type int    $menu_order            The order the post should be displayed in. Default 0.
 *     @type string $post_mime_type        The mime type of the post. Default empty.
 *     @type string $guid                  Global Unique ID for referencing the post. Default empty.
 *     @type array  $tax_input             Array of taxonomy terms keyed by their taxonomy name. Default empty.
 *     @type array  $meta_input            Array of post meta values keyed by their post meta key. Default empty.
 * }
 * @param bool  $wp_error Optional. Whether to allow return of WP_Error on failure. Default false.
 * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure.
 */
function wp_insert_post($postarr, $wp_error = false)
{
    global $wpdb;
    $user_id = get_current_user_id();
    $defaults = array('post_author' => $user_id, 'post_content' => '', 'post_content_filtered' => '', 'post_title' => '', 'post_excerpt' => '', 'post_status' => 'draft', 'post_type' => 'post', 'comment_status' => '', 'ping_status' => '', 'post_password' => '', 'to_ping' => '', 'pinged' => '', 'post_parent' => 0, 'menu_order' => 0, 'guid' => '', 'import_id' => 0, 'context' => '');
    $postarr = wp_parse_args($postarr, $defaults);
    unset($postarr['filter']);
    $postarr = sanitize_post($postarr, 'db');
    // Are we updating or creating?
    $post_ID = 0;
    $update = false;
    $guid = $postarr['guid'];
    if (!empty($postarr['ID'])) {
        $update = true;
        // Get the post ID and GUID.
        $post_ID = $postarr['ID'];
        $post_before = get_post($post_ID);
        if (is_null($post_before)) {
            if ($wp_error) {
                return new WP_Error('invalid_post', __('Invalid post ID.'));
            }
            return 0;
        }
        $guid = get_post_field('guid', $post_ID);
        $previous_status = get_post_field('post_status', $post_ID);
    } else {
        $previous_status = 'new';
    }
    $post_type = empty($postarr['post_type']) ? 'post' : $postarr['post_type'];
    $post_title = $postarr['post_title'];
    $post_content = $postarr['post_content'];
    $post_excerpt = $postarr['post_excerpt'];
    if (isset($postarr['post_name'])) {
        $post_name = $postarr['post_name'];
    }
    $maybe_empty = 'attachment' !== $post_type && !$post_content && !$post_title && !$post_excerpt && post_type_supports($post_type, 'editor') && post_type_supports($post_type, 'title') && post_type_supports($post_type, 'excerpt');
    /**
     * Filter whether the post should be considered "empty".
     *
     * The post is considered "empty" if both:
     * 1. The post type supports the title, editor, and excerpt fields
     * 2. The title, editor, and excerpt fields are all empty
     *
     * Returning a truthy value to the filter will effectively short-circuit
     * the new post being inserted, returning 0. If $wp_error is true, a WP_Error
     * will be returned instead.
     *
     * @since 3.3.0
     *
     * @param bool  $maybe_empty Whether the post should be considered "empty".
     * @param array $postarr     Array of post data.
     */
    if (apply_filters('wp_insert_post_empty_content', $maybe_empty, $postarr)) {
        if ($wp_error) {
            return new WP_Error('empty_content', __('Content, title, and excerpt are empty.'));
        } else {
            return 0;
        }
    }
    $post_status = empty($postarr['post_status']) ? 'draft' : $postarr['post_status'];
    if ('attachment' === $post_type && !in_array($post_status, array('inherit', 'private', 'trash'))) {
        $post_status = 'inherit';
    }
    if (!empty($postarr['post_category'])) {
        // Filter out empty terms.
        $post_category = array_filter($postarr['post_category']);
    }
    // Make sure we set a valid category.
    if (empty($post_category) || 0 == count($post_category) || !is_array($post_category)) {
        // 'post' requires at least one category.
        if ('post' == $post_type && 'auto-draft' != $post_status) {
            $post_category = array(get_option('default_category'));
        } else {
            $post_category = array();
        }
    }
    // Don't allow contributors to set the post slug for pending review posts.
    if ('pending' == $post_status && !current_user_can('publish_posts')) {
        $post_name = '';
    }
    /*
     * Create a valid post name. Drafts and pending posts are allowed to have
     * an empty post name.
     */
    if (empty($post_name)) {
        if (!in_array($post_status, array('draft', 'pending', 'auto-draft'))) {
            $post_name = sanitize_title($post_title);
        } else {
            $post_name = '';
        }
    } else {
        // On updates, we need to check to see if it's using the old, fixed sanitization context.
        $check_name = sanitize_title($post_name, '', 'old-save');
        if ($update && strtolower(urlencode($post_name)) == $check_name && get_post_field('post_name', $post_ID) == $check_name) {
            $post_name = $check_name;
        } else {
            // new post, or slug has changed.
            $post_name = sanitize_title($post_name);
        }
    }
    /*
     * If the post date is empty (due to having been new or a draft) and status
     * is not 'draft' or 'pending', set date to now.
     */
    if (empty($postarr['post_date']) || '0000-00-00 00:00:00' == $postarr['post_date']) {
        if (empty($postarr['post_date_gmt']) || '0000-00-00 00:00:00' == $postarr['post_date_gmt']) {
            $post_date = current_time('mysql');
        } else {
            $post_date = get_date_from_gmt($postarr['post_date_gmt']);
        }
    } else {
        $post_date = $postarr['post_date'];
    }
    // Validate the date.
    $mm = substr($post_date, 5, 2);
    $jj = substr($post_date, 8, 2);
    $aa = substr($post_date, 0, 4);
    $valid_date = wp_checkdate($mm, $jj, $aa, $post_date);
    if (!$valid_date) {
        if ($wp_error) {
            return new WP_Error('invalid_date', __('Whoops, the provided date is invalid.'));
        } else {
            return 0;
        }
    }
    if (empty($postarr['post_date_gmt']) || '0000-00-00 00:00:00' == $postarr['post_date_gmt']) {
        if (!in_array($post_status, array('draft', 'pending', 'auto-draft'))) {
            $post_date_gmt = get_gmt_from_date($post_date);
        } else {
            $post_date_gmt = '0000-00-00 00:00:00';
        }
    } else {
        $post_date_gmt = $postarr['post_date_gmt'];
    }
    if ($update || '0000-00-00 00:00:00' == $post_date) {
        $post_modified = current_time('mysql');
        $post_modified_gmt = current_time('mysql', 1);
    } else {
        $post_modified = $post_date;
        $post_modified_gmt = $post_date_gmt;
    }
    if ('attachment' !== $post_type) {
        if ('publish' == $post_status) {
            $now = gmdate('Y-m-d H:i:59');
            if (mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false)) {
                $post_status = 'future';
            }
        } elseif ('future' == $post_status) {
            $now = gmdate('Y-m-d H:i:59');
            if (mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false)) {
                $post_status = 'publish';
            }
        }
    }
    // Comment status.
    if (empty($postarr['comment_status'])) {
        if ($update) {
            $comment_status = 'closed';
        } else {
            $comment_status = get_default_comment_status($post_type);
        }
    } else {
        $comment_status = $postarr['comment_status'];
    }
    // These variables are needed by compact() later.
    $post_content_filtered = $postarr['post_content_filtered'];
    $post_author = isset($postarr['post_author']) ? $postarr['post_author'] : $user_id;
    $ping_status = empty($postarr['ping_status']) ? get_default_comment_status($post_type, 'pingback') : $postarr['ping_status'];
    $to_ping = isset($postarr['to_ping']) ? sanitize_trackback_urls($postarr['to_ping']) : '';
    $pinged = isset($postarr['pinged']) ? $postarr['pinged'] : '';
    $import_id = isset($postarr['import_id']) ? $postarr['import_id'] : 0;
    /*
     * The 'wp_insert_post_parent' filter expects all variables to be present.
     * Previously, these variables would have already been extracted
     */
    if (isset($postarr['menu_order'])) {
        $menu_order = (int) $postarr['menu_order'];
    } else {
        $menu_order = 0;
    }
    $post_password = isset($postarr['post_password']) ? $postarr['post_password'] : '';
    if ('private' == $post_status) {
        $post_password = '';
    }
    if (isset($postarr['post_parent'])) {
        $post_parent = (int) $postarr['post_parent'];
    } else {
        $post_parent = 0;
    }
    /**
     * Filter the post parent -- used to check for and prevent hierarchy loops.
     *
     * @since 3.1.0
     *
     * @param int   $post_parent Post parent ID.
     * @param int   $post_ID     Post ID.
     * @param array $new_postarr Array of parsed post data.
     * @param array $postarr     Array of sanitized, but otherwise unmodified post data.
     */
    $post_parent = apply_filters('wp_insert_post_parent', $post_parent, $post_ID, compact(array_keys($postarr)), $postarr);
    $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
    // Don't unslash.
    $post_mime_type = isset($postarr['post_mime_type']) ? $postarr['post_mime_type'] : '';
    // Expected_slashed (everything!).
    $data = compact('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'post_mime_type', 'guid');
    $emoji_fields = array('post_title', 'post_content', 'post_excerpt');
    foreach ($emoji_fields as $emoji_field) {
        if (isset($data[$emoji_field])) {
            $charset = $wpdb->get_col_charset($wpdb->posts, $emoji_field);
            if ('utf8' === $charset) {
                $data[$emoji_field] = wp_encode_emoji($data[$emoji_field]);
            }
        }
    }
    if ('attachment' === $post_type) {
        /**
         * Filter attachment post data before it is updated in or added to the database.
         *
         * @since 3.9.0
         *
         * @param array $data    An array of sanitized attachment post data.
         * @param array $postarr An array of unsanitized attachment post data.
         */
        $data = apply_filters('wp_insert_attachment_data', $data, $postarr);
    } else {
        /**
         * Filter slashed post data just before it is inserted into the database.
         *
         * @since 2.7.0
         *
         * @param array $data    An array of slashed post data.
         * @param array $postarr An array of sanitized, but otherwise unmodified post data.
         */
        $data = apply_filters('wp_insert_post_data', $data, $postarr);
    }
    $data = wp_unslash($data);
    $where = array('ID' => $post_ID);
    if ($update) {
        /**
         * Fires immediately before an existing post is updated in the database.
         *
         * @since 2.5.0
         *
         * @param int   $post_ID Post ID.
         * @param array $data    Array of unslashed post data.
         */
        do_action('pre_post_update', $post_ID, $data);
        if (false === $wpdb->update($wpdb->posts, $data, $where)) {
            if ($wp_error) {
                return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
            } else {
                return 0;
            }
        }
    } else {
        // If there is a suggested ID, use it if not already present.
        if (!empty($import_id)) {
            $import_id = (int) $import_id;
            if (!$wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE ID = %d", $import_id))) {
                $data['ID'] = $import_id;
            }
        }
        if (false === $wpdb->insert($wpdb->posts, $data)) {
            if ($wp_error) {
                return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
            } else {
                return 0;
            }
        }
        $post_ID = (int) $wpdb->insert_id;
        // Use the newly generated $post_ID.
        $where = array('ID' => $post_ID);
    }
    if (empty($data['post_name']) && !in_array($data['post_status'], array('draft', 'pending', 'auto-draft'))) {
        $data['post_name'] = wp_unique_post_slug(sanitize_title($data['post_title'], $post_ID), $post_ID, $data['post_status'], $post_type, $post_parent);
        $wpdb->update($wpdb->posts, array('post_name' => $data['post_name']), $where);
        clean_post_cache($post_ID);
    }
    if (is_object_in_taxonomy($post_type, 'category')) {
        wp_set_post_categories($post_ID, $post_category);
    }
    if (isset($postarr['tags_input']) && is_object_in_taxonomy($post_type, 'post_tag')) {
        wp_set_post_tags($post_ID, $postarr['tags_input']);
    }
    // New-style support for all custom taxonomies.
    if (!empty($postarr['tax_input'])) {
        foreach ($postarr['tax_input'] as $taxonomy => $tags) {
            $taxonomy_obj = get_taxonomy($taxonomy);
            if (!$taxonomy_obj) {
                /* translators: %s: taxonomy name */
                _doing_it_wrong(__FUNCTION__, sprintf(__('Invalid taxonomy: %s.'), $taxonomy), '4.4.0');
                continue;
            }
            // array = hierarchical, string = non-hierarchical.
            if (is_array($tags)) {
                $tags = array_filter($tags);
            }
            if (current_user_can($taxonomy_obj->cap->assign_terms)) {
                wp_set_post_terms($post_ID, $tags, $taxonomy);
            }
        }
    }
    if (!empty($postarr['meta_input'])) {
        foreach ($postarr['meta_input'] as $field => $value) {
            update_post_meta($post_ID, $field, $value);
        }
    }
    $current_guid = get_post_field('guid', $post_ID);
    // Set GUID.
    if (!$update && '' == $current_guid) {
        $wpdb->update($wpdb->posts, array('guid' => get_permalink($post_ID)), $where);
    }
    if ('attachment' === $postarr['post_type']) {
        if (!empty($postarr['file'])) {
            update_attached_file($post_ID, $postarr['file']);
        }
        if (!empty($postarr['context'])) {
            add_post_meta($post_ID, '_wp_attachment_context', $postarr['context'], true);
        }
    }
    clean_post_cache($post_ID);
    $post = get_post($post_ID);
    if (!empty($postarr['page_template']) && 'page' == $data['post_type']) {
        $post->page_template = $postarr['page_template'];
        $page_templates = wp_get_theme()->get_page_templates($post);
        if ('default' != $postarr['page_template'] && !isset($page_templates[$postarr['page_template']])) {
            if ($wp_error) {
                return new WP_Error('invalid_page_template', __('The page template is invalid.'));
            }
            update_post_meta($post_ID, '_wp_page_template', 'default');
        } else {
            update_post_meta($post_ID, '_wp_page_template', $postarr['page_template']);
        }
    }
    if ('attachment' !== $postarr['post_type']) {
        wp_transition_post_status($data['post_status'], $previous_status, $post);
    } else {
        if ($update) {
            /**
             * Fires once an existing attachment has been updated.
             *
             * @since 2.0.0
             *
             * @param int $post_ID Attachment ID.
             */
            do_action('edit_attachment', $post_ID);
            $post_after = get_post($post_ID);
            /**
             * Fires once an existing attachment has been updated.
             *
             * @since 4.4.0
             *
             * @param int     $post_ID      Post ID.
             * @param WP_Post $post_after   Post object following the update.
             * @param WP_Post $post_before  Post object before the update.
             */
            do_action('attachment_updated', $post_ID, $post_after, $post_before);
        } else {
            /**
             * Fires once an attachment has been added.
             *
             * @since 2.0.0
             *
             * @param int $post_ID Attachment ID.
             */
            do_action('add_attachment', $post_ID);
        }
        return $post_ID;
    }
    if ($update) {
        /**
         * Fires once an existing post has been updated.
         *
         * @since 1.2.0
         *
         * @param int     $post_ID Post ID.
         * @param WP_Post $post    Post object.
         */
        do_action('edit_post', $post_ID, $post);
        $post_after = get_post($post_ID);
        /**
         * Fires once an existing post has been updated.
         *
         * @since 3.0.0
         *
         * @param int     $post_ID      Post ID.
         * @param WP_Post $post_after   Post object following the update.
         * @param WP_Post $post_before  Post object before the update.
         */
        do_action('post_updated', $post_ID, $post_after, $post_before);
    }
    /**
     * Fires once a post has been saved.
     *
     * The dynamic portion of the hook name, `$post->post_type`, refers to
     * the post type slug.
     *
     * @since 3.7.0
     *
     * @param int     $post_ID Post ID.
     * @param WP_Post $post    Post object.
     * @param bool    $update  Whether this is an existing post being updated or not.
     */
    do_action("save_post_{$post->post_type}", $post_ID, $post, $update);
    /**
     * Fires once a post has been saved.
     *
     * @since 1.5.0
     *
     * @param int     $post_ID Post ID.
     * @param WP_Post $post    Post object.
     * @param bool    $update  Whether this is an existing post being updated or not.
     */
    do_action('save_post', $post_ID, $post, $update);
    /**
     * Fires once a post has been saved.
     *
     * @since 2.0.0
     *
     * @param int     $post_ID Post ID.
     * @param WP_Post $post    Post object.
     * @param bool    $update  Whether this is an existing post being updated or not.
     */
    do_action('wp_insert_post', $post_ID, $post, $update);
    return $post_ID;
}
Esempio n. 3
0
 public function check_post_header($post_id = true, &$obj = false)
 {
     if (empty($this->p->options['plugin_check_head'])) {
         return $post_id;
     }
     if (!is_object($obj) && ($obj = $this->p->util->get_post_object($post_id)) === false) {
         return $post_id;
     }
     // only check publicly available posts
     if (!isset($obj->post_status) || $obj->post_status !== 'publish') {
         return $post_id;
     }
     // only check registered front-end post types (to avoid menu items, product variations, etc.)
     $ptns = $this->p->util->get_post_types('names');
     if (empty($obj->post_type) || !in_array($obj->post_type, $ptns)) {
         return $post_id;
     }
     $charset = get_bloginfo('charset');
     $permalink = get_permalink($post_id);
     $permalink_html = wp_encode_emoji(htmlentities(urldecode($permalink), ENT_QUOTES, $charset, false));
     // double_encode = false
     $permalink_no_meta = add_query_arg(array('NGFB_META_TAGS_DISABLE' => 1), $permalink);
     $check_opts = apply_filters($this->p->cf['lca'] . '_check_head_meta_options', SucomUtil::preg_grep_keys('/^add_/', $this->p->options, false, ''), $post_id);
     if (current_user_can('manage_options')) {
         $notice_suffix = ' (' . sprintf(__('see <a href="%s">Theme Integration</a> settings', 'nextgen-facebook'), $this->p->util->get_admin_url('advanced#sucom-tabset_plugin-tab_integration')) . ')...';
     } else {
         $notice_suffix = '...';
     }
     $this->p->notice->inf(sprintf(__('Checking %1$s webpage header for duplicate meta tags', 'nextgen-facebook'), '<a href="' . $permalink . '">' . $permalink_html . '</a>') . $notice_suffix, true);
     // use the permalink and have get_head_meta() remove our own meta tags
     // to avoid issues with caching plugins that ignore query arguments
     if (($metas = $this->p->util->get_head_meta($permalink, '/html/head/link|/html/head/meta', true)) !== false) {
         foreach (array('link' => array('rel'), 'meta' => array('name', 'itemprop', 'property')) as $tag => $types) {
             if (isset($metas[$tag])) {
                 foreach ($metas[$tag] as $m) {
                     foreach ($types as $t) {
                         if (isset($m[$t]) && $m[$t] !== 'generator' && !empty($check_opts[$tag . '_' . $t . '_' . $m[$t]])) {
                             $this->p->notice->err('Possible conflict detected &mdash; your theme or another plugin is adding a <code>' . $tag . ' ' . $t . '="' . $m[$t] . '"</code> HTML tag to the head section of this webpage.', true);
                         }
                     }
                 }
             }
         }
     }
     return $post_id;
 }
Esempio n. 4
0
/**
 * Convert emoji to a static img element.
 *
 * @since 4.2.0
 *
 * @param string $text The content to encode.
 * @return string The encoded content.
 */
function wp_staticize_emoji($text)
{
    $text = wp_encode_emoji($text);
    /** This filter is documented in wp-includes/formatting.php */
    $cdn_url = apply_filters('emoji_url', set_url_scheme('//s.w.org/images/core/emoji/72x72/'));
    /** This filter is documented in wp-includes/formatting.php */
    $ext = apply_filters('emoji_ext', '.png');
    $output = '';
    /*
     * HTML loop taken from smiley function, which was taken from texturize function.
     * It'll never be consolidated.
     *
     * First, capture the tags as well as in between.
     */
    $textarr = preg_split('/(<.*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
    $stop = count($textarr);
    // Ignore processing of specific tags.
    $tags_to_ignore = 'code|pre|style|script|textarea';
    $ignore_block_element = '';
    for ($i = 0; $i < $stop; $i++) {
        $content = $textarr[$i];
        // If we're in an ignore block, wait until we find its closing tag.
        if ('' == $ignore_block_element && preg_match('/^<(' . $tags_to_ignore . ')>/', $content, $matches)) {
            $ignore_block_element = $matches[1];
        }
        // If it's not a tag and not in ignore block.
        if ('' == $ignore_block_element && strlen($content) > 0 && '<' != $content[0]) {
            $matches = array();
            if (preg_match_all('/(&#x1f1(e[6-9a-f]|f[0-9a-f]);){2}/', $content, $matches)) {
                if (!empty($matches[0])) {
                    foreach ($matches[0] as $flag) {
                        $chars = str_replace(array('&#x', ';'), '', $flag);
                        list($char1, $char2) = str_split($chars, 5);
                        $entity = sprintf('<img src="%s" alt="%s" class="wp-smiley" style="height: 1em; max-height: 1em;" />', $cdn_url . $char1 . '-' . $char2 . $ext, html_entity_decode($flag));
                        $content = str_replace($flag, $entity, $content);
                    }
                }
            }
            // Loosely match the Emoji Unicode range.
            $regex = '/(&#x[2-3][0-9a-f]{3};|&#x1f[1-6][0-9a-f]{2};)/';
            $matches = array();
            if (preg_match_all($regex, $content, $matches)) {
                if (!empty($matches[1])) {
                    foreach ($matches[1] as $emoji) {
                        $char = str_replace(array('&#x', ';'), '', $emoji);
                        $entity = sprintf('<img src="%s" alt="%s" class="wp-smiley" style="height: 1em; max-height: 1em;" />', $cdn_url . $char . $ext, html_entity_decode($emoji));
                        $content = str_replace($emoji, $entity, $content);
                    }
                }
            }
        }
        // Did we exit ignore block.
        if ('' != $ignore_block_element && '</' . $ignore_block_element . '>' == $content) {
            $ignore_block_element = '';
        }
        $output .= $content;
    }
    return $output;
}
 /**
  * Generates the content tokens and puts them into the tokens array
  *
  * @param object $the_post the post object
  * @param array $tokens tokens array
  *
  * @return int keywords count
  */
 private function tokenizeContent($the_post, &$tokens)
 {
     $args = $this->args;
     $content = $the_post->post_content;
     if ($args['extract_shortcodes']) {
         // WP Table Reloaded support
         if (defined('WP_TABLE_RELOADED_ABSPATH')) {
             include_once WP_TABLE_RELOADED_ABSPATH . 'controllers/controller-frontend.php';
             $wpt_reloaded = new WP_Table_Reloaded_Controller_Frontend();
         }
         // TablePress support
         if (defined('TABLEPRESS_ABSPATH')) {
             $tp_controller = TablePress::load_controller('frontend');
             $tp_controller->init_shortcodes();
         }
         // Remove user defined shortcodes
         $shortcodes = explode(',', $args['exclude_shortcodes']);
         foreach ($shortcodes as $shortcode) {
             remove_shortcode(trim($shortcode));
             add_shortcode(trim($shortcode), array($this, 'return_empty_string'));
         }
         // Remove some shortcodes
         remove_shortcode('wpdreams_ajaxsearchpro');
         add_shortcode('wpdreams_ajaxsearchpro', array($this, 'return_empty_string'));
         remove_shortcode('wpdreams_ajaxsearchpro_results');
         add_shortcode('wpdreams_ajaxsearchpro_results', array($this, 'return_empty_string'));
         remove_shortcode('wpdreams_asp_settings');
         add_shortcode('wpdreams_asp_settings', array($this, 'return_empty_string'));
         remove_shortcode('contact-form');
         add_shortcode('contact-form', array($this, 'return_empty_string'));
         remove_shortcode('starrater');
         add_shortcode('starrater', array($this, 'return_empty_string'));
         remove_shortcode('responsive-flipbook');
         add_shortcode('responsive-flipbook', array($this, 'return_empty_string'));
         remove_shortcode('avatar_upload');
         add_shortcode('avatar_upload', array($this, 'return_empty_string'));
         remove_shortcode('product_categories');
         add_shortcode('product_categories', array($this, 'return_empty_string'));
         remove_shortcode('recent_products');
         add_shortcode('recent_products', array($this, 'return_empty_string'));
         $content = do_shortcode($content);
         // WP 4.2 emoji strip
         if (function_exists('wp_encode_emoji')) {
             $content = wp_encode_emoji($content);
         }
         if (defined('TABLEPRESS_ABSPATH')) {
             unset($tp_controller);
         }
         if (defined('WP_TABLE_RELOADED_ABSPATH')) {
             unset($wpt_reloaded);
         }
     }
     // Strip the remaining shortcodes
     $content = strip_shortcodes($content);
     $content = preg_replace('/<[a-zA-Z\\/][^>]*>/', ' ', $content);
     $content = strip_tags($content);
     $filtered_content = apply_filters('asp_post_content_before_tokenize', $content);
     if ($filtered_content == "") {
         return 0;
     }
     $content_keywords = $this->tokenize($filtered_content);
     foreach ($content_keywords as $keyword) {
         $this->insertToken($tokens, $keyword[0], $keyword[1], 'content');
     }
     return count($content_keywords);
 }
Esempio n. 6
0
function relevanssi_search($args)
{
    global $wpdb, $relevanssi_variables;
    $relevanssi_table = $relevanssi_variables['relevanssi_table'];
    $filtered_args = apply_filters('relevanssi_search_filters', $args);
    extract($filtered_args);
    $hits = array();
    $query_restrictions = "";
    if (!isset($tax_query_relation)) {
        $tax_query_relation = "or";
    }
    $tax_query_relation = strtolower($tax_query_relation);
    $term_tax_id = array();
    $term_tax_ids = array();
    $not_term_tax_ids = array();
    $and_term_tax_ids = array();
    if (is_array($tax_query)) {
        foreach ($tax_query as $row) {
            if ($row['field'] == 'slug') {
                $slug = $row['terms'];
                $numeric_slugs = array();
                $slug_in = null;
                if (is_array($slug)) {
                    $slugs = array();
                    $term_id = array();
                    foreach ($slug as $t_slug) {
                        $term = get_term_by('slug', $t_slug, $row['taxonomy']);
                        if (!$term && is_numeric($t_slug)) {
                            $numeric_slugs[] = "'{$t_slug}'";
                        } else {
                            $t_slug = sanitize_title($t_slug);
                            $term_id[] = $term->term_id;
                            $slugs[] = "'{$t_slug}'";
                        }
                    }
                    if (!empty($slugs)) {
                        $slug_in = implode(',', $slugs);
                    }
                } else {
                    $term = get_term_by('slug', $slug, $row['taxonomy']);
                    if (!$term && is_numeric($slug)) {
                        $numeric_slugs[] = $slug;
                    } else {
                        $term_id = $term->term_id;
                        $slug_in = "'{$slug}'";
                    }
                }
                if (!empty($slug_in)) {
                    $row_taxonomy = sanitize_text_field($row['taxonomy']);
                    $tt_q = "SELECT tt.term_taxonomy_id\n\t\t\t\t\t\t  \tFROM {$wpdb->term_taxonomy} AS tt\n\t\t\t\t\t\t  \tLEFT JOIN {$wpdb->terms} AS t ON (tt.term_id=t.term_id)\n\t\t\t\t\t\t  \tWHERE tt.taxonomy = '{$row_taxonomy}' AND t.slug IN ({$slug_in})";
                    // Clean: $row_taxonomy is sanitized, each slug in $slug_in is sanitized
                    $term_tax_id = $wpdb->get_col($tt_q);
                }
                if (!empty($numeric_slugs)) {
                    $row['field'] = 'id';
                }
            }
            if ($row['field'] == 'id' || $row['field'] == 'term_id') {
                $id = $row['terms'];
                $term_id = $id;
                if (is_array($id)) {
                    $numeric_values = array();
                    foreach ($id as $t_id) {
                        if (is_numeric($t_id)) {
                            $numeric_values[] = $t_id;
                        }
                    }
                    $id = implode(',', $numeric_values);
                }
                $row_taxonomy = sanitize_text_field($row['taxonomy']);
                $tt_q = "SELECT tt.term_taxonomy_id\n\t\t\t\t  \tFROM {$wpdb->term_taxonomy} AS tt\n\t\t\t\t  \tLEFT JOIN {$wpdb->terms} AS t ON (tt.term_id=t.term_id)\n\t\t\t\t  \tWHERE tt.taxonomy = '{$row_taxonomy}' AND t.term_id IN ({$id})";
                // Clean: $row_taxonomy is sanitized, $id is checked to be numeric
                $id_term_tax_id = $wpdb->get_col($tt_q);
                if (!empty($term_tax_id) && is_array($term_tax_id)) {
                    $term_tax_id = array_unique(array_merge($term_tax_id, $id_term_tax_id));
                } else {
                    $term_tax_id = $id_term_tax_id;
                }
            }
            if (!isset($row['include_children']) || $row['include_children'] == true) {
                if (!is_array($term_id)) {
                    $term_id = array($term_id);
                }
                foreach ($term_id as $t_id) {
                    $kids = get_term_children($t_id, $row['taxonomy']);
                    foreach ($kids as $kid) {
                        $term = get_term_by('id', $kid, $row['taxonomy']);
                        $term_tax_id[] = relevanssi_get_term_tax_id('id', $kid, $row['taxonomy']);
                    }
                }
            }
            $term_tax_id = array_unique($term_tax_id);
            if (!empty($term_tax_id)) {
                $n = count($term_tax_id);
                $term_tax_id = implode(',', $term_tax_id);
                $tq_operator = 'IN';
                if (isset($row['operator'])) {
                    $tq_operator = strtoupper($row['operator']);
                }
                if ($tq_operator != 'IN' && $tq_operator != 'NOT IN' && $tq_operator != 'AND') {
                    $tq_operator = 'IN';
                }
                if ($tax_query_relation == 'and') {
                    if ($tq_operator == 'AND') {
                        $query_restrictions .= " AND relevanssi.doc IN (\n\t\t\t\t\t\t\tSELECT ID FROM {$wpdb->posts} WHERE 1=1 \n\t\t\t\t\t\t\tAND (\n\t\t\t\t\t\t\t\tSELECT COUNT(1) \n\t\t\t\t\t\t\t\tFROM {$wpdb->term_relationships} AS tr\n\t\t\t\t\t\t\t\tWHERE tr.term_taxonomy_id IN ({$term_tax_id}) \n\t\t\t\t\t\t\t\tAND tr.object_id = {$wpdb->posts}.ID ) = {$n}\n\t\t\t\t\t\t\t)";
                        // Clean: $term_tax_id and $n are Relevanssi-generated
                    } else {
                        $query_restrictions .= " AND relevanssi.doc {$tq_operator} (SELECT DISTINCT(tr.object_id) FROM {$wpdb->term_relationships} AS tr\n\t\t\t\t\t\tWHERE tr.term_taxonomy_id IN ({$term_tax_id}))";
                        // Clean: all variables are Relevanssi-generated
                    }
                } else {
                    if ($tq_operator == 'IN') {
                        $term_tax_ids[] = $term_tax_id;
                    }
                    if ($tq_operator == 'NOT IN') {
                        $not_term_tax_ids[] = $term_tax_id;
                    }
                    if ($tq_operator == 'AND') {
                        $and_term_tax_ids[] = $term_tax_id;
                    }
                }
            } else {
                global $wp_query;
                $wp_query->is_category = false;
            }
        }
        if ($tax_query_relation == 'or') {
            $term_tax_ids = array_unique($term_tax_ids);
            if (count($term_tax_ids) > 0) {
                $term_tax_ids = implode(',', $term_tax_ids);
                $query_restrictions .= " AND relevanssi.doc IN (SELECT DISTINCT(tr.object_id) FROM {$wpdb->term_relationships} AS tr\n\t\t\t    \tWHERE tr.term_taxonomy_id IN ({$term_tax_ids}))";
                // Clean: all variables are Relevanssi-generated
            }
            if (count($not_term_tax_ids) > 0) {
                $not_term_tax_ids = implode(',', $not_term_tax_ids);
                $query_restrictions .= " AND relevanssi.doc NOT IN (SELECT DISTINCT(tr.object_id) FROM {$wpdb->term_relationships} AS tr\n\t\t\t    \tWHERE tr.term_taxonomy_id IN ({$not_term_tax_ids}))";
                // Clean: all variables are Relevanssi-generated
            }
            if (count($and_term_tax_ids) > 0) {
                $and_term_tax_ids = implode(',', $and_term_tax_ids);
                $n = count(explode(',', $and_term_tax_ids));
                $query_restrictions .= " AND relevanssi.doc IN (\n\t\t\t\t\tSELECT ID FROM {$wpdb->posts} WHERE 1=1 \n\t\t\t\t\tAND (\n\t\t\t\t\t\tSELECT COUNT(1) \n\t\t\t\t\t\tFROM {$wpdb->term_relationships} AS tr\n\t\t\t\t\t\tWHERE tr.term_taxonomy_id IN ({$and_term_tax_ids}) \n\t\t\t\t\t\tAND tr.object_id = {$wpdb->posts}.ID ) = {$n}\n\t\t\t\t\t)";
                // Clean: all variables are Relevanssi-generated
            }
        }
    }
    if (is_array($post_query)) {
        if (!empty($post_query['in'])) {
            $valid_values = array();
            foreach ($post_query['in'] as $post_in_id) {
                if (is_numeric($post_in_id)) {
                    $valid_values[] = $post_in_id;
                }
            }
            $posts = implode(',', $valid_values);
            if (!empty($posts)) {
                $query_restrictions .= " AND relevanssi.doc IN ({$posts})";
            }
            // Clean: $posts is checked to be integers
        }
        if (!empty($post_query['not in'])) {
            $valid_values = array();
            foreach ($post_query['not in'] as $post_not_in_id) {
                if (is_numeric($post_not_in_id)) {
                    $valid_values[] = $post_not_in_id;
                }
            }
            $posts = implode(',', $valid_values);
            if (!empty($posts)) {
                $query_restrictions .= " AND relevanssi.doc NOT IN ({$posts})";
            }
            // Clean: $posts is checked to be integers
        }
    }
    if (is_array($parent_query)) {
        if (!empty($parent_query['parent in'])) {
            $valid_values = array();
            foreach ($parent_query['parent in'] as $post_in_id) {
                if (is_numeric($post_in_id)) {
                    $valid_values[] = $post_in_id;
                }
            }
            $posts = implode(',', $valid_values);
            if (!empty($posts)) {
                $query_restrictions .= " AND relevanssi.doc IN (SELECT ID FROM {$wpdb->posts} WHERE post_parent IN ({$posts}))";
            }
            // Clean: $posts is checked to be integers
        }
        if (!empty($parent_query['parent not in'])) {
            $valid_values = array();
            foreach ($parent_query['parent not in'] as $post_not_in_id) {
                if (is_numeric($post_not_in_id)) {
                    $valid_values[] = $post_not_in_id;
                }
            }
            $posts = implode(',', $valid_values);
            if (!empty($posts)) {
                $query_restrictions .= " AND relevanssi.doc NOT IN (SELECT ID FROM {$wpdb->posts} WHERE post_parent IN ({$posts}))";
            }
            // Clean: $posts is checked to be integers
        }
    }
    if (is_array($meta_query)) {
        $meta_query_restrictions = "";
        $mq_vars = array('meta_query' => $meta_query);
        $mq = new WP_Meta_Query();
        $mq->parse_query_vars($mq_vars);
        $meta_sql = $mq->get_sql('post', 'relevanssi', 'doc');
        $meta_join = "";
        $meta_where = "";
        if ($meta_sql) {
            $meta_join = $meta_sql['join'];
            $meta_where = $meta_sql['where'];
        }
        $query_restrictions .= $meta_where;
    }
    if (!empty($date_query)) {
        if (is_object($date_query) && method_exists($date_query, 'get_sql')) {
            $sql = $date_query->get_sql();
            // AND ( the query itself )
            $query_restrictions .= " AND relevanssi.doc IN ( SELECT DISTINCT(ID) FROM {$wpdb->posts} WHERE 1 {$sql} )";
            // Clean: $sql generated by $date_query->get_sql() query
        }
    }
    if (!$post_type && get_option('relevanssi_respect_exclude') == 'on') {
        if (function_exists('get_post_types')) {
            $pt_1 = get_post_types(array('exclude_from_search' => '0'));
            $pt_2 = get_post_types(array('exclude_from_search' => false));
            $post_type = implode(',', array_merge($pt_1, $pt_2));
        }
    }
    if ($post_type) {
        if ($post_type == -1) {
            $post_type = null;
        }
        // Facetious sets post_type to -1 if not selected
        if (!is_array($post_type)) {
            $post_types = esc_sql(explode(',', $post_type));
        } else {
            $post_types = esc_sql($post_type);
        }
        $post_type = count($post_types) ? "'" . implode("', '", $post_types) . "'" : 'NULL';
    }
    if ($post_status) {
        if (!is_array($post_status)) {
            $post_statuses = esc_sql(explode(',', $post_status));
        } else {
            $post_statuses = esc_sql($post_status);
        }
        $post_status = count($post_statuses) ? "'" . implode("', '", $post_statuses) . "'" : 'NULL';
    }
    //Added by OdditY:
    //Exclude Post_IDs (Pages) for non-admin search ->
    $postex = '';
    if (!empty($expost)) {
        if ($expost != "") {
            $aexpids = explode(",", $expost);
            foreach ($aexpids as $exid) {
                $exid = esc_sql(trim($exid, ' -'));
                $postex .= " AND relevanssi.doc != '{$exid}'";
                // Clean: escaped
            }
        }
    }
    // <- OdditY End
    if ($expost) {
        //added by OdditY
        $query_restrictions .= $postex;
    }
    $remove_stopwords = true;
    if (function_exists('wp_encode_emoji')) {
        $q = wp_encode_emoji($q);
    }
    $phrases = relevanssi_recognize_phrases($q);
    if (function_exists('relevanssi_recognize_negatives')) {
        $negative_terms = relevanssi_recognize_negatives($q);
    } else {
        $negative_terms = false;
    }
    if (function_exists('relevanssi_recognize_positives')) {
        $positive_terms = relevanssi_recognize_positives($q);
    } else {
        $positive_terms = false;
    }
    $terms = relevanssi_tokenize($q, $remove_stopwords);
    if (count($terms) < 1) {
        // Tokenizer killed all the search terms.
        return $hits;
    }
    $terms = array_keys($terms);
    // don't care about tf in query
    if ($negative_terms) {
        $terms = array_diff($terms, $negative_terms);
        if (count($terms) < 1) {
            return $hits;
        }
    }
    // Go get the count from the options table, but keep running the full query if it's not available
    $D = get_option('relevanssi_doc_count');
    if (!$D || $D < 1) {
        $D = $wpdb->get_var("SELECT COUNT(DISTINCT(relevanssi.doc)) FROM {$relevanssi_table} AS relevanssi");
        // Clean: no external inputs
        update_option('relevanssi_doc_count', $D);
    }
    $total_hits = 0;
    $title_matches = array();
    $tag_matches = array();
    $comment_matches = array();
    $link_matches = array();
    $body_matches = array();
    $category_matches = array();
    $taxonomy_matches = array();
    $scores = array();
    $term_hits = array();
    $fuzzy = get_option('relevanssi_fuzzy');
    if (function_exists('relevanssi_negatives_positives')) {
        $query_restrictions .= relevanssi_negatives_positives($negative_terms, $positive_terms, $relevanssi_table);
        // Clean: escaped in the function
    }
    if (!empty($author)) {
        $author_in = array();
        $author_not_in = array();
        foreach ($author as $id) {
            if (!is_numeric($id)) {
                continue;
            }
            if ($id > 0) {
                $author_in[] = $id;
            } else {
                $author_not_in[] = abs($id);
            }
        }
        if (count($author_in) > 0) {
            $authors = implode(',', $author_in);
            $query_restrictions .= " AND relevanssi.doc IN (SELECT DISTINCT(posts.ID) FROM {$wpdb->posts} AS posts\n\t\t\t    WHERE posts.post_author IN ({$authors}))";
            // Clean: $authors is always just numbers
        }
        if (count($author_not_in) > 0) {
            $authors = implode(',', $author_not_in);
            $query_restrictions .= " AND relevanssi.doc NOT IN (SELECT DISTINCT(posts.ID) FROM {$wpdb->posts} AS posts\n\t\t\t    WHERE posts.post_author IN ({$authors}))";
            // Clean: $authors is always just numbers
        }
    }
    if ($post_type) {
        // the -1 is there to get user profiles and category pages
        $query_restrictions .= " AND ((relevanssi.doc IN (SELECT DISTINCT(posts.ID) FROM {$wpdb->posts} AS posts\n\t\t\tWHERE posts.post_type IN ({$post_type}))) OR (doc = -1))";
        // Clean: $post_type is escaped
    }
    if ($post_status) {
        // the -1 is there to get user profiles and category pages
        $query_restrictions .= " AND ((relevanssi.doc IN (SELECT DISTINCT(posts.ID) FROM {$wpdb->posts} AS posts\n\t\t\tWHERE posts.post_status IN ({$post_status}))) OR (doc = -1))";
        // Clean: $post_status is escaped
    }
    if ($phrases) {
        $query_restrictions .= " {$phrases}";
        // Clean: $phrases is escaped earlier
    }
    if (isset($_REQUEST['by_date'])) {
        $n = $_REQUEST['by_date'];
        $u = substr($n, -1, 1);
        switch ($u) {
            case 'h':
                $unit = "HOUR";
                break;
            case 'd':
                $unit = "DAY";
                break;
            case 'm':
                $unit = "MONTH";
                break;
            case 'y':
                $unit = "YEAR";
                break;
            case 'w':
                $unit = "WEEK";
                break;
            default:
                $unit = "DAY";
        }
        $n = preg_replace('/[hdmyw]/', '', $n);
        if (is_numeric($n)) {
            $query_restrictions .= " AND relevanssi.doc IN (SELECT DISTINCT(posts.ID) FROM {$wpdb->posts} AS posts\n\t\t\t\tWHERE posts.post_date > DATE_SUB(NOW(), INTERVAL {$n} {$unit}))";
            // Clean: $n is always numeric, $unit is Relevanssi-generated
        }
    }
    $query_restrictions = apply_filters('relevanssi_where', $query_restrictions);
    // Charles St-Pierre
    $query_join = "";
    if (!empty($meta_join)) {
        $query_join = $meta_join;
    }
    $query_join = apply_filters('relevanssi_join', $query_join);
    $no_matches = true;
    if ("always" == $fuzzy) {
        $o_term_cond = apply_filters('relevanssi_fuzzy_query', "(relevanssi.term LIKE '#term#%' OR relevanssi.term_reverse LIKE CONCAT(REVERSE('#term#'), '%')) ");
    } else {
        $o_term_cond = " relevanssi.term = '#term#' ";
    }
    $post_type_weights = get_option('relevanssi_post_type_weights');
    if (function_exists('relevanssi_get_recency_bonus')) {
        list($recency_bonus, $recency_cutoff_date) = relevanssi_get_recency_bonus();
    } else {
        $recency_bonus = false;
        $recency_cutoff_date = false;
    }
    $min_length = get_option('relevanssi_min_word_length');
    $search_again = false;
    $title_boost = floatval(get_option('relevanssi_title_boost'));
    $link_boost = floatval(get_option('relevanssi_link_boost'));
    $comment_boost = floatval(get_option('relevanssi_comment_boost'));
    $include_these_posts = array();
    do {
        foreach ($terms as $term) {
            $term = trim($term);
            // numeric search terms will start with a space
            if (strlen($term) < $min_length) {
                continue;
            }
            $term = esc_sql($term);
            if (strpos($o_term_cond, 'LIKE') !== false) {
                // only like_escape() if necessary, otherwise _ in search terms will not work
                if (method_exists($wpdb, 'esc_like')) {
                    $term = $wpdb->esc_like($term);
                } else {
                    // Compatibility for pre-4.0 WordPress
                    $term = like_escape($term);
                }
            }
            $term_cond = str_replace('#term#', $term, $o_term_cond);
            !empty($post_type_weights['post_tag']) ? $tag = $post_type_weights['post_tag'] : ($tag = $relevanssi_variables['post_type_weight_defaults']['post_tag']);
            !empty($post_type_weights['category']) ? $cat = $post_type_weights['category'] : ($cat = $relevanssi_variables['post_type_weight_defaults']['category']);
            $query = "SELECT relevanssi.*, relevanssi.title * {$title_boost} + relevanssi.content + relevanssi.comment * {$comment_boost} + relevanssi.tag * {$tag} + relevanssi.link * {$link_boost} + relevanssi.author + relevanssi.category * {$cat} + relevanssi.excerpt + relevanssi.taxonomy + relevanssi.customfield + relevanssi.mysqlcolumn AS tf \n\t\t\t\t\t  FROM {$relevanssi_table} AS relevanssi {$query_join} WHERE {$term_cond} {$query_restrictions}";
            // Clean: $query_restrictions is escaped, $term_cond is escaped
            $query = apply_filters('relevanssi_query_filter', $query);
            $matches = $wpdb->get_results($query);
            if (count($matches) < 1) {
                continue;
            } else {
                $no_matches = false;
                if (count($include_these_posts) > 0) {
                    $post_ids_to_add = implode(',', array_keys($include_these_posts));
                    $existing_ids = array();
                    foreach ($matches as $match) {
                        $existing_ids[] = $match->doc;
                    }
                    $existing_ids = implode(',', $existing_ids);
                    $query = "SELECT relevanssi.*, relevanssi.title * {$title_boost} + relevanssi.content + relevanssi.comment * {$comment_boost} + relevanssi.tag * {$tag} + relevanssi.link * {$link_boost} + relevanssi.author + relevanssi.category * {$cat} + relevanssi.excerpt + relevanssi.taxonomy + relevanssi.customfield + relevanssi.mysqlcolumn AS tf \n\t\t\t\t\t\t  FROM {$relevanssi_table} AS relevanssi WHERE relevanssi.doc IN ({$post_ids_to_add}) AND relevanssi.doc NOT IN ({$existing_ids}) AND {$term_cond}";
                    // Clean: no unescaped user inputs
                    $matches_to_add = $wpdb->get_results($query);
                    $matches = array_merge($matches, $matches_to_add);
                }
            }
            relevanssi_populate_array($matches);
            global $relevanssi_post_types;
            $total_hits += count($matches);
            $query = "SELECT COUNT(DISTINCT(relevanssi.doc)) FROM {$relevanssi_table} AS relevanssi {$query_join} WHERE {$term_cond} {$query_restrictions}";
            // Clean: $query_restrictions is escaped, $term_cond is escaped
            $query = apply_filters('relevanssi_df_query_filter', $query);
            $df = $wpdb->get_var($query);
            if ($df < 1 && "sometimes" == $fuzzy) {
                $query = "SELECT COUNT(DISTINCT(relevanssi.doc)) FROM {$relevanssi_table} AS relevanssi {$query_join}\n\t\t\t\t\tWHERE (relevanssi.term LIKE '{$term}%' OR relevanssi.term_reverse LIKE CONCAT(REVERSE('{$term}), %')) {$query_restrictions}";
                // Clean: $query_restrictions is escaped, $term is escaped
                $query = apply_filters('relevanssi_df_query_filter', $query);
                $df = $wpdb->get_var($query);
            }
            $idf = log($D + 1 / (1 + $df));
            $idf = $idf * $idf;
            foreach ($matches as $match) {
                if ('user' == $match->type) {
                    $match->doc = 'u_' . $match->item;
                } else {
                    if (!in_array($match->type, array('post', 'attachment'))) {
                        $match->doc = '**' . $match->type . '**' . $match->item;
                    }
                }
                if (isset($match->taxonomy_detail)) {
                    $match->taxonomy_score = 0;
                    $match->taxonomy_detail = unserialize($match->taxonomy_detail);
                    if (is_array($match->taxonomy_detail)) {
                        foreach ($match->taxonomy_detail as $tax => $count) {
                            if ($tax == 'post_tag') {
                                $match->tag = $count;
                            }
                            if (empty($post_type_weights[$tax])) {
                                $match->taxonomy_score += $count * 1;
                            } else {
                                $match->taxonomy_score += $count * $post_type_weights[$tax];
                            }
                        }
                    }
                }
                $match->tf = $match->title * $title_boost + $match->content + $match->comment * $comment_boost + $match->link * $link_boost + $match->author + $match->excerpt + $match->taxonomy_score + $match->customfield + $match->mysqlcolumn;
                $term_hits[$match->doc][$term] = $match->title + $match->content + $match->comment + $match->tag + $match->link + $match->author + $match->category + $match->excerpt + $match->taxonomy + $match->customfield + $match->mysqlcolumn;
                $match->weight = $match->tf * $idf;
                if ($recency_bonus) {
                    $post = relevanssi_get_post($match->doc);
                    if (strtotime($post->post_date) > $recency_cutoff_date) {
                        $match->weight = $match->weight * $recency_bonus['bonus'];
                    }
                }
                isset($body_matches[$match->doc]) ? $body_matches[$match->doc] += $match->content : ($body_matches[$match->doc] = $match->content);
                isset($title_matches[$match->doc]) ? $title_matches[$match->doc] += $match->title : ($title_matches[$match->doc] = $match->title);
                isset($link_matches[$match->doc]) ? $link_matches[$match->doc] += $match->link : ($link_matches[$match->doc] = $match->link);
                isset($tag_matches[$match->doc]) ? $tag_matches[$match->doc] += $match->tag : ($tag_matches[$match->doc] = $match->tag);
                isset($category_matches[$match->doc]) ? $category_matches[$match->doc] += $match->category : ($category_matches[$match->doc] = $match->category);
                isset($taxonomy_matches[$match->doc]) ? $taxonomy_matches[$match->doc] += $match->taxonomy : ($taxonomy_matches[$match->doc] = $match->taxonomy);
                isset($comment_matches[$match->doc]) ? $comment_matches[$match->doc] += $match->comment : ($comment_matches[$match->doc] = $match->comment);
                isset($relevanssi_post_types[$match->doc]) ? $type = $relevanssi_post_types[$match->doc] : ($type = null);
                if (!empty($post_type_weights[$type])) {
                    $match->weight = $match->weight * $post_type_weights[$type];
                }
                $match = apply_filters('relevanssi_match', $match, $idf);
                if ($match->weight == 0) {
                    continue;
                }
                // the filters killed the match
                $post_ok = true;
                $post_ok = apply_filters('relevanssi_post_ok', $post_ok, $match->doc);
                if ($post_ok) {
                    $doc_terms[$match->doc][$term] = true;
                    // count how many terms are matched to a doc
                    isset($doc_weight[$match->doc]) ? $doc_weight[$match->doc] += $match->weight : ($doc_weight[$match->doc] = $match->weight);
                    isset($scores[$match->doc]) ? $scores[$match->doc] += $match->weight : ($scores[$match->doc] = $match->weight);
                    if (is_numeric($match->doc)) {
                        // this is to weed out taxonomies and users (t_XXX, u_XXX)
                        $include_these_posts[$match->doc] = true;
                    }
                }
            }
        }
        if (!isset($doc_weight)) {
            $no_matches = true;
        }
        if ($no_matches) {
            if ($search_again) {
                // no hits even with fuzzy search!
                $search_again = false;
            } else {
                if ("sometimes" == $fuzzy) {
                    $search_again = true;
                    $o_term_cond = "(term LIKE '%#term#' OR term LIKE '#term#%') ";
                }
            }
        } else {
            $search_again = false;
        }
    } while ($search_again);
    $strip_stops = true;
    $temp_terms_without_stops = array_keys(relevanssi_tokenize(implode(' ', $terms), $strip_stops));
    $terms_without_stops = array();
    foreach ($temp_terms_without_stops as $temp_term) {
        if (strlen($temp_term) >= $min_length) {
            array_push($terms_without_stops, $temp_term);
        }
    }
    $total_terms = count($terms_without_stops);
    if (isset($doc_weight)) {
        $doc_weight = apply_filters('relevanssi_results', $doc_weight);
    }
    if (isset($doc_weight) && count($doc_weight) > 0) {
        arsort($doc_weight);
        $i = 0;
        foreach ($doc_weight as $doc => $weight) {
            if (count($doc_terms[$doc]) < $total_terms && $operator == "AND") {
                // AND operator in action:
                // doc didn't match all terms, so it's discarded
                continue;
            }
            if (!empty($fields)) {
                if ($fields == 'ids') {
                    $hits[intval($i)] = $doc;
                }
                if ($fields == 'id=>parent') {
                    $object = new StdClass();
                    $object->ID = $doc;
                    $object->post_parent = wp_get_post_parent_id($doc);
                    $hits[intval($i)] = $object;
                }
            } else {
                $hits[intval($i)] = relevanssi_get_post($doc);
                $hits[intval($i)]->relevance_score = round($weight, 2);
            }
            $i++;
        }
    }
    if (count($hits) < 1) {
        if ($operator == "AND" and get_option('relevanssi_disable_or_fallback') != 'on') {
            $or_args = $args;
            $or_args['operator'] = "OR";
            $or_args['q'] = relevanssi_add_synonyms($q);
            $return = relevanssi_search($or_args);
            extract($return);
        }
    }
    global $wp;
    $default_order = get_option('relevanssi_default_orderby', 'relevance');
    if (empty($orderby)) {
        $orderby = $default_order;
    }
    // the sorting function checks for non-existing keys, cannot whitelist here
    if (empty($order)) {
        $order = 'desc';
    }
    $order = strtolower($order);
    $order_accepted_values = array('asc', 'desc');
    if (!in_array($order, $order_accepted_values)) {
        $order = 'desc';
    }
    $orderby = apply_filters('relevanssi_orderby', $orderby);
    $order = apply_filters('relevanssi_order', $order);
    if ($orderby != 'relevance') {
        relevanssi_object_sort($hits, $orderby, $order);
    }
    $return = array('hits' => $hits, 'body_matches' => $body_matches, 'title_matches' => $title_matches, 'tag_matches' => $tag_matches, 'category_matches' => $category_matches, 'taxonomy_matches' => $taxonomy_matches, 'comment_matches' => $comment_matches, 'scores' => $scores, 'term_hits' => $term_hits, 'query' => $q, 'link_matches' => $link_matches);
    return $return;
}
Esempio n. 7
0
 public function get_single_mt($tag = 'meta', $type = 'property', $name, $value = '', $cmt = '', $use_post = false)
 {
     // known exceptions for the 'property' $type
     if ($tag === 'meta' && $type === 'property' && (strpos($name, 'twitter:') === 0 || strpos($name, ':') === false)) {
         $type = 'name';
     }
     $ret = array();
     $attr = $tag === 'link' ? 'href' : 'content';
     $log_pre = $tag . ' ' . $type . ' ' . $name;
     $charset = get_bloginfo('charset');
     if (is_array($value)) {
         if ($this->p->debug->enabled) {
             $this->p->debug->log($log_pre . ' value is an array (skipped)');
         }
         return $ret;
     } elseif (is_object($value)) {
         if ($this->p->debug->enabled) {
             $this->p->debug->log($log_pre . ' value is an object (skipped)');
         }
         return $ret;
     }
     if (strpos($value, '%%')) {
         $value = $this->p->util->replace_inline_vars($value, $use_post);
     }
     switch ($name) {
         case 'og:image':
         case 'og:image:url':
         case 'og:video':
         case 'og:video:url':
             // add secure_url meta tag for open graph images and videos
             if (strpos($value, 'https://') === 0) {
                 $secure_value = $value;
                 $secure_name = preg_replace('/:url$/', '', $name) . ':secure_url';
                 $value = preg_replace('/^https:/', 'http:', $value);
                 $ret[] = array('', $tag, $type, $secure_name, $attr, $secure_value, $cmt);
             }
             break;
     }
     $ret[] = array('', $tag, $type, $name, $attr, $value, $cmt);
     // filtering of single meta tags can be enabled by defining NGFB_FILTER_SINGLE_TAGS as true
     if (defined('NGFB_FILTER_SINGLE_TAGS') && NGFB_FILTER_SINGLE_TAGS) {
         $ret = $this->filter_single_mt($ret, $use_post);
     }
     // $parts = array( $html, $tag, $type, $name, $attr, $value, $cmt );
     foreach ($ret as $num => $parts) {
         $log_pre = $parts[1] . ' ' . $parts[2] . ' ' . $parts[3];
         if ($this->p->debug->enabled) {
             $this->p->debug->log($log_pre . ' = "' . $parts[5] . '"');
         }
         if ($parts[5] === '' || $parts[5] === null) {
             // allow for 0
             if ($this->p->debug->enabled) {
                 $this->p->debug->log($log_pre . ' value is empty (skipped)');
             }
         } elseif ($parts[5] == -1) {
             // -1 is reserved
             if ($this->p->debug->enabled) {
                 $this->p->debug->log($log_pre . ' value is -1 (skipped)');
             }
         } elseif (!empty($this->p->options['add_' . $parts[1] . '_' . $parts[2] . '_' . $parts[3]])) {
             // change meta itemtype "image.url" to "url" (for example)
             if ($parts[1] === 'meta' && $parts[2] === 'itemprop' && strpos($parts[3], '.') !== 0) {
                 $parts[3] = preg_replace('/^.*\\./', '', $parts[3]);
             }
             switch ($parts[3]) {
                 case 'og:url':
                 case 'og:image':
                 case 'og:image:url':
                 case 'og:image:secure_url':
                 case 'og:video':
                 case 'og:video:url':
                 case 'og:video:url:secure_url':
                 case 'og:video:url:embed_url':
                 case 'twitter:image':
                 case 'twitter:player':
                 case 'canonical':
                 case 'url':
                     $parts[5] = SucomUtil::esc_url_encode($parts[5]);
                     break;
                 case 'og:title':
                 case 'og:description':
                 case 'twitter:title':
                 case 'twitter:description':
                 case 'description':
                 case 'name':
                     $parts[5] = wp_encode_emoji(htmlentities($parts[5], ENT_QUOTES, $charset, false));
                     // double_encode = false
                 // double_encode = false
                 default:
                     $parts[5] = htmlentities($parts[5], ENT_QUOTES, $charset, false);
                     // double_encode = false
                     break;
             }
             $parts[0] = (empty($parts[6]) ? '' : '<!-- ' . $parts[6] . ' -->') . '<' . $parts[1] . ' ' . $parts[2] . '="' . $parts[3] . '" ' . $parts[4] . '="' . $parts[5] . '"/>' . "\n";
             $ret[$num] = $parts;
         } elseif ($this->p->debug->enabled) {
             $this->p->debug->log($log_pre . ' is disabled (skipped)');
         }
     }
     return $ret;
 }
Esempio n. 8
0
function relevanssi_index_doc($indexpost, $remove_first = false, $custom_fields = false, $bypassglobalpost = false)
{
    global $wpdb, $post, $relevanssi_variables;
    $relevanssi_table = $relevanssi_variables['relevanssi_table'];
    $post_was_null = false;
    $previous_post = NULL;
    // Check if this is a Jetpack Contact Form entry
    if (isset($_REQUEST['contact-form-id'])) {
        return;
    }
    if ($bypassglobalpost) {
        // if $bypassglobalpost is set, relevanssi_index_doc() will index the post object or post
        // ID as specified in $indexpost
        isset($post) ? $previous_post = $post : ($post_was_null = true);
        is_object($indexpost) ? $post = $indexpost : ($post = get_post($indexpost));
    } else {
        // Quick edit has an array in the global $post, so fetch the post ID for the post to edit.
        if (is_array($post)) {
            $post = get_post($post['ID']);
        }
        if (empty($post)) {
            // No $post set, so we need to use $indexpost, if it's a post object
            $post_was_null = true;
            if (is_object($indexpost)) {
                $post = $indexpost;
            } else {
                $post = get_post($indexpost);
            }
        } else {
            // $post was set, let's grab the previous value in case we need it
            $previous_post = $post;
        }
    }
    if ($post == NULL) {
        // At this point we should have something in $post; if not, quit.
        if ($post_was_null) {
            $post = null;
        }
        if ($previous_post) {
            $post = $previous_post;
        }
        return;
    }
    // Finally fetch the post again by ID. Complicated, yes, but unless we do this, we might end
    // up indexing the post before the updates come in.
    $post = get_post($post->ID);
    if (function_exists('relevanssi_hide_post')) {
        if (relevanssi_hide_post($post->ID)) {
            if ($post_was_null) {
                $post = null;
            }
            if ($previous_post) {
                $post = $previous_post;
            }
            return;
        }
    }
    $index_this_post = false;
    $post->indexing_content = true;
    $index_types = get_option('relevanssi_index_post_types');
    if (!is_array($index_types)) {
        $index_types = array();
    }
    if (in_array($post->post_type, $index_types)) {
        $index_this_post = true;
    }
    if (true == apply_filters('relevanssi_do_not_index', false, $post->ID)) {
        // filter says no
        $index_this_post = false;
    }
    if ($remove_first) {
        // we are updating a post, so remove the old stuff first
        relevanssi_remove_doc($post->ID, true);
        if (function_exists('relevanssi_remove_item')) {
            relevanssi_remove_item($post->ID, 'post');
        }
    }
    // This needs to be here, after the call to relevanssi_remove_doc(), because otherwise
    // a post that's in the index but shouldn't be there won't get removed.
    if (!$index_this_post) {
        if ($post_was_null) {
            $post = null;
        }
        if ($previous_post) {
            $post = $previous_post;
        }
        return;
    }
    $n = 0;
    $post = apply_filters('relevanssi_post_to_index', $post);
    $min_word_length = get_option('relevanssi_min_word_length', 3);
    $insert_data = array();
    //Added by OdditY - INDEX COMMENTS of the POST ->
    if ("none" != get_option("relevanssi_index_comments")) {
        $pcoms = relevanssi_get_comments($post->ID);
        if ($pcoms != "") {
            $pcoms = relevanssi_strip_invisibles($pcoms);
            $pcoms = preg_replace('/<[a-zA-Z\\/][^>]*>/', ' ', $pcoms);
            $pcoms = strip_tags($pcoms);
            $pcoms = relevanssi_tokenize($pcoms, true, $min_word_length);
            if (count($pcoms) > 0) {
                foreach ($pcoms as $pcom => $count) {
                    $n++;
                    $insert_data[$pcom]['comment'] = $count;
                }
            }
        }
    }
    //Added by OdditY END <-
    $taxonomies = get_option("relevanssi_index_taxonomies_list");
    // Then process all taxonomies, if any.
    foreach ($taxonomies as $taxonomy) {
        $insert_data = relevanssi_index_taxonomy_terms($post, $taxonomy, $insert_data);
    }
    // index author
    if ("on" == get_option("relevanssi_index_author")) {
        $auth = $post->post_author;
        $display_name = $wpdb->get_var("SELECT display_name FROM {$wpdb->users} WHERE ID={$auth}");
        $names = relevanssi_tokenize($display_name, false, $min_word_length);
        foreach ($names as $name => $count) {
            isset($insert_data[$name]['author']) ? $insert_data[$name]['author'] += $count : ($insert_data[$name]['author'] = $count);
        }
    }
    if ($custom_fields) {
        $remove_underscore_fields = false;
        if ($custom_fields == 'all') {
            $custom_fields = get_post_custom_keys($post->ID);
        }
        if ($custom_fields == 'visible') {
            $custom_fields = get_post_custom_keys($post->ID);
            $remove_underscore_fields = true;
        }
        $custom_fields = apply_filters('relevanssi_index_custom_fields', $custom_fields);
        if (is_array($custom_fields)) {
            foreach ($custom_fields as $field) {
                if ($remove_underscore_fields) {
                    if (substr($field, 0, 1) == '_') {
                        continue;
                    }
                }
                $values = get_post_meta($post->ID, $field, false);
                if ("" == $values) {
                    continue;
                }
                foreach ($values as $value) {
                    $value_tokens = relevanssi_tokenize($value, true, $min_word_length);
                    foreach ($value_tokens as $token => $count) {
                        isset($insert_data[$token]['customfield']) ? $insert_data[$token]['customfield'] += $count : ($insert_data[$token]['customfield'] = $count);
                        if (function_exists('relevanssi_customfield_detail')) {
                            $insert_data = relevanssi_customfield_detail($insert_data, $token, $count, $field);
                        }
                    }
                }
            }
        }
    }
    if (isset($post->post_excerpt) && ("on" == get_option("relevanssi_index_excerpt") || "attachment" == $post->post_type)) {
        // include excerpt for attachments which use post_excerpt for captions - modified by renaissancehack
        $excerpt_tokens = relevanssi_tokenize($post->post_excerpt, true, $min_word_length);
        foreach ($excerpt_tokens as $token => $count) {
            isset($insert_data[$token]['excerpt']) ? $insert_data[$token]['excerpt'] += $count : ($insert_data[$token]['excerpt'] = $count);
        }
    }
    if (function_exists('relevanssi_index_mysql_columns')) {
        $insert_data = relevanssi_index_mysql_columns($insert_data, $post->ID);
    }
    $index_titles = true;
    if (apply_filters('relevanssi_index_titles', $index_titles)) {
        $filtered_title = apply_filters('relevanssi_post_title_before_tokenize', $post->post_title, $post);
        $titles = relevanssi_tokenize(apply_filters('the_title', $filtered_title));
        if (count($titles) > 0) {
            foreach ($titles as $title => $count) {
                $n++;
                isset($insert_data[$title]['title']) ? $insert_data[$title]['title'] += $count : ($insert_data[$title]['title'] = $count);
            }
        }
    }
    $index_content = true;
    if (apply_filters('relevanssi_index_content', $index_content)) {
        remove_shortcode('noindex');
        add_shortcode('noindex', 'relevanssi_noindex_shortcode_indexing');
        $contents = apply_filters('relevanssi_post_content', $post->post_content, $post);
        // Allow user to add extra content for Relevanssi to index
        // Thanks to Alexander Gieg
        $additional_content = trim(apply_filters('relevanssi_content_to_index', '', $post));
        if ('' != $additional_content) {
            $contents .= ' ' . $additional_content;
        }
        if ('on' == get_option('relevanssi_expand_shortcodes')) {
            if (function_exists("do_shortcode")) {
                // WP Table Reloaded support
                if (defined('WP_TABLE_RELOADED_ABSPATH')) {
                    include_once WP_TABLE_RELOADED_ABSPATH . 'controllers/controller-frontend.php';
                    $My_WP_Table_Reloaded = new WP_Table_Reloaded_Controller_Frontend();
                }
                // TablePress support
                if (defined('TABLEPRESS_ABSPATH')) {
                    $My_TablePress_Controller = TablePress::load_controller('frontend');
                    $My_TablePress_Controller->init_shortcodes();
                }
                $disable_shortcodes = get_option('relevanssi_disable_shortcodes');
                $shortcodes = explode(',', $disable_shortcodes);
                foreach ($shortcodes as $shortcode) {
                    remove_shortcode(trim($shortcode));
                }
                remove_shortcode('contact-form');
                // Jetpack Contact Form causes an error message
                remove_shortcode('starrater');
                // GD Star Rating rater shortcode causes problems
                remove_shortcode('responsive-flipbook');
                // Responsive Flipbook causes problems
                remove_shortcode('avatar_upload');
                // WP User Avatar is incompatible
                remove_shortcode('product_categories');
                // A problematic WooCommerce shortcode
                remove_shortcode('recent_products');
                // A problematic WooCommerce shortcode
                remove_shortcode('php');
                // PHP Code for Posts
                $post_before_shortcode = $post;
                $contents = do_shortcode($contents);
                $post = $post_before_shortcode;
                if (defined('TABLEPRESS_ABSPATH')) {
                    unset($My_TablePress_Controller);
                }
                if (defined('WP_TABLE_RELOADED_ABSPATH')) {
                    unset($My_WP_Table_Reloaded);
                }
            }
        } else {
            if (function_exists("strip_shortcodes")) {
                // WP 2.5 doesn't have the function
                $contents = strip_shortcodes($contents);
            }
        }
        remove_shortcode('noindex');
        add_shortcode('noindex', 'relevanssi_noindex_shortcode');
        $contents = relevanssi_strip_invisibles($contents);
        if (function_exists('relevanssi_process_internal_links')) {
            $contents = relevanssi_process_internal_links($contents, $post->ID);
        }
        $contents = preg_replace('/<[a-zA-Z\\/][^>]*>/', ' ', $contents);
        $contents = strip_tags($contents);
        if (function_exists('wp_encode_emoji')) {
            $contents = wp_encode_emoji($contents);
        }
        $contents = apply_filters('relevanssi_post_content_before_tokenize', $contents, $post);
        $contents = relevanssi_tokenize($contents, true, $min_word_length);
        if (count($contents) > 0) {
            foreach ($contents as $content => $count) {
                $n++;
                isset($insert_data[$content]['content']) ? $insert_data[$content]['content'] += $count : ($insert_data[$content]['content'] = $count);
            }
        }
    }
    $type = 'post';
    if ($post->post_type == 'attachment') {
        $type = 'attachment';
    }
    $insert_data = apply_filters('relevanssi_indexing_data', $insert_data, $post);
    $values = array();
    foreach ($insert_data as $term => $data) {
        $content = 0;
        $title = 0;
        $comment = 0;
        $tag = 0;
        $link = 0;
        $author = 0;
        $category = 0;
        $excerpt = 0;
        $taxonomy = 0;
        $customfield = 0;
        $taxonomy_detail = '';
        $customfield_detail = '';
        $mysqlcolumn = 0;
        extract($data);
        $term = trim($term);
        $value = $wpdb->prepare("(%d, %s, REVERSE(%s), %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %s, %s, %s, %d)", $post->ID, $term, $term, $content, $title, $comment, $tag, $link, $author, $category, $excerpt, $taxonomy, $customfield, $type, $taxonomy_detail, $customfield_detail, $mysqlcolumn);
        array_push($values, $value);
    }
    $values = apply_filters('relevanssi_indexing_values', $values, $post);
    if (!empty($values)) {
        $values = implode(', ', $values);
        $query = "INSERT IGNORE INTO {$relevanssi_table} (doc, term, term_reverse, content, title, comment, tag, link, author, category, excerpt, taxonomy, customfield, type, taxonomy_detail, customfield_detail, mysqlcolumn)\n\t\t\tVALUES {$values}";
        $wpdb->query($query);
    }
    if ($post_was_null) {
        $post = null;
    }
    if ($previous_post) {
        $post = $previous_post;
    }
    return $n;
}
Esempio n. 9
0
function gwolle_gb_maybe_encode_emoji($string, $field)
{
    global $wpdb;
    if (method_exists($wpdb, 'get_col_charset')) {
        $charset = $wpdb->get_col_charset($wpdb->gwolle_gb_entries, $field);
        if ('utf8' === $charset && function_exists('wp_encode_emoji')) {
            $string = wp_encode_emoji($string);
        }
    }
    return $string;
}
 /**
  * Create a post object for a given event
  *
  * Can't call `wp_insert_post()` because `wp_unique_post_slug()` breaks the plugin's expectations
  * Also doesn't call `wp_insert_post()` because this function is needed before post types and capabilities are ready.
  */
 public function create_or_update_job($timestamp, $action, $args, $update_id = null)
 {
     // Limit how many events to insert at once
     if (!Lock::check_lock(self::LOCK, JOB_CREATION_CONCURRENCY_LIMIT)) {
         return false;
     }
     global $wpdb;
     // Build minimum information needed to create a post
     $instance = md5(serialize($args['args']));
     $job_post = array('post_title' => $this->event_title($timestamp, $action, $instance), 'post_name' => $this->event_name($timestamp, $action, $instance), 'post_content_filtered' => maybe_serialize(array('action' => $action, 'instance' => $instance, 'args' => $args)), 'post_date' => date('Y-m-d H:i:s', $timestamp), 'post_date_gmt' => date('Y-m-d H:i:s', $timestamp), 'post_modified' => current_time('mysql'), 'post_modified_gmt' => current_time('mysql', true), 'post_type' => self::POST_TYPE, 'post_status' => self::POST_STATUS_PENDING, 'post_author' => 0, 'post_parent' => 0, 'comment_status' => 'closed', 'ping_status' => 'closed');
     // Some sanitization in place of `sanitize_post()`, which we can't use this early
     foreach (array('post_title', 'post_name', 'post_content_filtered') as $field) {
         $job_post[$field] = sanitize_text_field($job_post[$field]);
     }
     // Duplicate some processing performed in `wp_insert_post()`
     $charset = $wpdb->get_col_charset($wpdb->posts, 'post_title');
     if ('utf8' === $charset) {
         $job_post['post_title'] = wp_encode_emoji($job_post['post_title']);
     }
     $job_post = wp_unslash($job_post);
     // Set this so it isn't empty, even though it serves us no purpose
     $job_post['guid'] = esc_url(add_query_arg(self::POST_TYPE, $job_post['post_name'], home_url('/')));
     // Create the post, or update an existing entry to run again in the future
     if (is_int($update_id) && $update_id > 0) {
         $inserted = $wpdb->update($wpdb->posts, $job_post, array('ID' => $update_id));
         $this->posts_to_clean[] = $update_id;
     } else {
         $inserted = $wpdb->insert($wpdb->posts, $job_post);
     }
     // Clear caches for new posts once the post type is registered
     if ($inserted) {
         $this->posts_to_clean[] = $wpdb->insert_id;
     }
     // Delete internal cache
     wp_cache_delete(self::CACHE_KEY);
     // Allow more events to be created
     Lock::free_lock(self::LOCK);
 }
Esempio n. 11
0
 public function get_description($textlen = 156, $trailing = '...', $use_post = false, $use_cache = true, $add_hashtags = true, $encode = true, $md_idx = 'og_desc', $src_id = '')
 {
     if ($this->p->debug->enabled) {
         $this->p->debug->mark('render description');
         // start timer
         $this->p->debug->args(array('textlen' => $textlen, 'trailing' => $trailing, 'use_post' => $use_post, 'use_cache' => $use_cache, 'add_hashtags' => $add_hashtags, 'encode' => $encode, 'md_idx' => $md_idx, 'src_id' => $src_id));
     }
     $desc = false;
     $hashtags = '';
     $post_id = 0;
     $page = '';
     if (is_singular() || $use_post !== false) {
         if (($obj = $this->p->util->get_post_object($use_post)) === false) {
             if ($this->p->debug->enabled) {
                 $this->p->debug->log('exiting early: invalid object type');
             }
             return $desc;
         }
         $post_id = empty($obj->ID) || empty($obj->post_type) ? 0 : $obj->ID;
     }
     // skip if no metadata index / key name
     if (!empty($md_idx)) {
         if (is_singular() || $use_post !== false) {
             if (!empty($post_id)) {
                 $desc = $this->p->util->get_mod_options('post', $post_id, array($md_idx, 'og_desc'));
             }
         } elseif (SucomUtil::is_term_page()) {
             $term = $this->p->util->get_term_object();
             if (!empty($term->term_id)) {
                 $desc = $this->p->util->get_mod_options('taxonomy', $term->term_id, $md_idx);
             }
         } elseif (SucomUtil::is_author_page()) {
             $author = $this->p->util->get_author_object();
             if (!empty($author->ID)) {
                 $desc = $this->p->util->get_mod_options('user', $author->ID, $md_idx);
             }
         }
         if ($this->p->debug->enabled) {
             if (empty($desc)) {
                 $this->p->debug->log('no custom description found');
             } else {
                 $this->p->debug->log('custom description = "' . $desc . '"');
             }
         }
     }
     // get seed if no custom meta description
     if (empty($desc)) {
         $desc = apply_filters($this->p->cf['lca'] . '_description_seed', '', $use_post, $add_hashtags, $md_idx, $src_id);
         if (!empty($desc)) {
             if ($this->p->debug->enabled) {
                 $this->p->debug->log('description seed = "' . $desc . '"');
             }
         }
     }
     // remove and save trailing hashtags
     if (preg_match('/^(.*)(( *#[a-z][a-z0-9\\-]+)+)$/U', $desc, $match)) {
         $desc = $match[1];
         $hashtags = trim($match[2]);
     } elseif (is_singular() || $use_post !== false) {
         if (!empty($add_hashtags) && !empty($this->p->options['og_desc_hashtags'])) {
             $hashtags = $this->get_hashtags($post_id, $add_hashtags);
         }
     }
     if ($this->p->debug->enabled) {
         $this->p->debug->log('hashtags found = "' . $hashtags . '"');
     }
     // if there's no custom description, and no pre-seed,
     // then go ahead and generate the description value
     if (empty($desc)) {
         // $obj and $post_id are defined above, with the same test, so we should be good
         if (is_singular() || $use_post !== false) {
             // use the excerpt, if we have one
             if (has_excerpt($post_id)) {
                 $desc = $obj->post_excerpt;
                 if (!empty($this->p->options['plugin_filter_excerpt'])) {
                     $filter_removed = apply_filters($this->p->cf['lca'] . '_pre_filter_remove', false, 'get_the_excerpt');
                     if ($this->p->debug->enabled) {
                         $this->p->debug->log('calling apply_filters(\'get_the_excerpt\')');
                     }
                     $desc = apply_filters('get_the_excerpt', $desc);
                     if ($filter_removed) {
                         $filter_added = apply_filters($this->p->cf['lca'] . '_post_filter_add', false, 'get_the_excerpt');
                     }
                 }
             } elseif ($this->p->debug->enabled) {
                 $this->p->debug->log('no post_excerpt for post_id ' . $post_id);
             }
             // if there's no excerpt, then fallback to the content
             if (empty($desc)) {
                 $desc = $this->get_content($post_id, $use_post, $use_cache, $md_idx, $src_id);
             }
             // ignore everything before the first paragraph if true
             if ($this->p->options['plugin_p_strip']) {
                 if ($this->p->debug->enabled) {
                     $this->p->debug->log('removing all text before the first paragraph');
                 }
                 $desc = preg_replace('/^.*?<p>/i', '', $desc);
                 // question mark makes regex un-greedy
             }
         } elseif (SucomUtil::is_term_page()) {
             if (is_tag()) {
                 $desc = tag_description();
                 if (empty($desc)) {
                     $desc = sprintf('Tagged with %s', single_tag_title('', false));
                 }
             } elseif (is_category()) {
                 $desc = category_description();
                 if (empty($desc)) {
                     $desc = sprintf('%s Category', single_cat_title('', false));
                 }
             } else {
                 // other taxonomies
                 $term = $this->p->util->get_term_object();
                 if (!empty($term->description)) {
                     $desc = $term->description;
                 } elseif (!empty($term->name)) {
                     $desc = $term->name . ' Archives';
                 }
             }
         } elseif (SucomUtil::is_author_page()) {
             $author = $this->p->util->get_author_object();
             if (!empty($author->description)) {
                 $desc = $author->description;
             } elseif (!empty($author->display_name)) {
                 $desc = sprintf('Authored by %s', $author->display_name);
             }
         } elseif (is_day()) {
             $desc = sprintf('Daily Archives for %s', get_the_date());
         } elseif (is_month()) {
             $desc = sprintf('Monthly Archives for %s', get_the_date('F Y'));
         } elseif (is_year()) {
             $desc = sprintf('Yearly Archives for %s', get_the_date('Y'));
         }
     }
     // if there's still no description, then fallback to a generic version
     if (empty($desc)) {
         if (is_admin() && !empty($obj->post_status) && $obj->post_status == 'auto-draft') {
             if ($this->p->debug->enabled) {
                 $this->p->debug->log('post_status is auto-draft - using empty description');
             }
         } else {
             // pass options array to allow fallback if locale option does not exist
             $key = SucomUtil::get_locale_key('og_site_description', $this->p->options, $post_id);
             if (!empty($this->p->options[$key])) {
                 if ($this->p->debug->enabled) {
                     $this->p->debug->log('description is empty - custom site description (' . $key . ')');
                 }
                 $desc = $this->p->options[$key];
             } else {
                 if ($this->p->debug->enabled) {
                     $this->p->debug->log('description is empty - using blog description');
                 }
                 $desc = get_bloginfo('description', 'display');
             }
         }
     }
     if ($this->p->debug->enabled) {
         $this->p->debug->log('description strlen before html cleanup ' . strlen($desc));
     }
     $desc = $this->p->util->cleanup_html_tags($desc, true, $this->p->options['plugin_use_img_alt']);
     $desc = apply_filters($this->p->cf['lca'] . '_description_pre_limit', $desc);
     if ($textlen > 0) {
         if (!empty($add_hashtags) && !empty($hashtags)) {
             $textlen = $textlen - strlen($hashtags) - 1;
         }
         if ($this->p->debug->enabled) {
             $this->p->debug->log('description strlen before limit length ' . strlen($desc) . ' (limiting to ' . $textlen . ' chars)');
         }
         $desc = $this->p->util->limit_text_length($desc, $textlen, $trailing, false);
         // don't run cleanup_html_tags()
     } elseif ($this->p->debug->enabled) {
         $this->p->debug->log('description limit text length skipped');
     }
     if (!empty($add_hashtags) && !empty($hashtags)) {
         $desc .= ' ' . $hashtags;
     }
     if ($encode === true) {
         $desc = wp_encode_emoji(htmlentities($desc, ENT_QUOTES, get_bloginfo('charset'), false));
     }
     // double_encode = false
     if ($this->p->debug->enabled) {
         $this->p->debug->mark('render description');
     }
     // stop timer
     return apply_filters($this->p->cf['lca'] . '_description', $desc, $use_post, $add_hashtags, $md_idx, $src_id);
 }
 /**
  * Send the message
  *
  * @global    object $wpdb
  * @global    int $blog_id
  *
  * @param    int $chat_id Chat ID
  * @param    string $name Name
  * @param    string $avatar URL or e-mail
  * @param    string $message Payload message
  * @param    string $moderator Moderator
  */
 function chat_session_send_message($message, $chat_session)
 {
     global $wpdb;
     //$wpdb->real_escape = true;
     //$time_stamp = date("Y-m-d H:i:s");
     $time_stamp_seconds = time();
     $time_stamp_formated = date("Y-m-d H:i:s", $time_stamp_seconds);
     $blog_id = $chat_session['blog_id'];
     $chat_id = $chat_session['id'];
     $session_type = trim($chat_session['session_type']);
     $name = trim($this->chat_auth['name']);
     $user_avatar = trim($this->chat_auth['avatar']);
     $auth_hash = trim($this->chat_auth['auth_hash']);
     $user_type = trim($this->chat_auth['type']);
     $ip_address = isset($_SERVER['HTTP_X_FORWARD_FOR']) ? $_SERVER['HTTP_X_FORWARD_FOR'] : $_SERVER['REMOTE_ADDR'];
     $message = trim($message);
     $moderator_str = trim($chat_session['moderator']);
     if ($message == '') {
         return false;
     }
     $log_row_id = $this->chat_session_get_meta($chat_session, 'log_row_id');
     //echo "log_row_id[". $log_row_id ."]<br />";
     // If we don't find a record we insert a new one
     if (empty($log_row_id) || $log_row_id == "__EMPTY__") {
         $sql_str = $wpdb->prepare("INSERT INTO " . WPMUDEV_Chat::tablename('log') . " (`blog_id`, `chat_id`, `session_type`, `start`, `end`, `box_title`, `archived`) VALUES (%d, %s, %s, %s, %s, %s, %s);", $chat_session['blog_id'], $chat_session['id'], $chat_session['session_type'], $time_stamp_formated, '', $chat_session['box_title'], 'no');
         //echo "sql_str[". $sql_str ."]<br />";
         //die();
         $ret = $wpdb->query($sql_str);
         if (isset($wpdb->insert_id) && $wpdb->insert_id > 0) {
             $this->chat_session_set_meta($chat_session, 'log_row_id', $wpdb->insert_id);
             $log_row_id = $wpdb->insert_id;
         }
     }
     // If DB charset is not utf8mb4, emojis needs to be encoded as html entities.
     if (!strpos($wpdb->charset, 'mb4') && function_exists('wp_encode_emoji')) {
         $message = wp_encode_emoji($message);
     }
     $sql_str = $wpdb->prepare("INSERT INTO " . WPMUDEV_Chat::tablename('message') . "\r\r\n\t\t\t\t\t(`blog_id`, `chat_id`, `session_type`, `timestamp`, `name`, `avatar`, `auth_hash`, `ip_address`, `message`, `moderator`, `deleted`, `archived`, `log_id`, `user_type`) VALUES (%d, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %d, %s);", $blog_id, $chat_id, $session_type, $time_stamp_formated, $name, $user_avatar, $auth_hash, $ip_address, $message, $moderator_str, 'no', 'no', $log_row_id, $user_type);
     $ret = $wpdb->query($sql_str);
     if (isset($wpdb->insert_id) && $wpdb->insert_id > 0) {
         $this->chat_session_set_meta($chat_session, 'last_row_id', $wpdb->insert_id);
         return $wpdb->insert_id;
     }
 }
 public static function sanitize_content($value)
 {
     global $wpdb;
     $options = get_option('iwt_options');
     $allowed = wp_kses_allowed_html('post');
     if (array_key_exists('contentelements', $options) && json_decode($options['contentelements']) != null) {
         $allowed = json_decode($options['contentelements'], true);
     }
     $charset = $wpdb->get_col_charset($wpdb->posts, $emoji_field);
     if ('utf8' === $charset) {
         $value = wp_encode_emoji($value);
     }
     return wp_kses((string) $value, $allowed);
 }
Esempio n. 14
0
 * @param int   $post_ID     Post ID.
 * @param array $new_postarr Array of parsed post data.
 * @param array $postarr     Array of sanitized, but otherwise unmodified post data.
 */
$post_parent = apply_filters('wp_insert_post_parent', $post_parent, $post_ID, compact(array_keys($postarr)), $postarr);
$post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
// Don't unslash.
$post_mime_type = isset($postarr['post_mime_type']) ? $postarr['post_mime_type'] : '';
// Expected_slashed (everything!).
$data = compact('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'post_mime_type', 'guid');
$emoji_fields = array('post_title', 'post_content', 'post_excerpt');
foreach ($emoji_fields as $emoji_field) {
    if (isset($data[$emoji_field])) {
        $charset = $wpdb->get_col_charset($wpdb->posts, $emoji_field);
        if ('utf8' === $charset) {
            $data[$emoji_field] = wp_encode_emoji($data[$emoji_field]);
        }
    }
}
if ('attachment' === $post_type) {
    /**
     * Filter attachment post data before it is updated in or added to the database.
     *
     * @since 3.9.0
     *
     * @param array $data    An array of sanitized attachment post data.
     * @param array $postarr An array of unsanitized attachment post data.
     */
    $data = apply_filters('wp_insert_attachment_data', $data, $postarr);
} else {
    /**
Esempio n. 15
0
 /**
  * Send the message
  *
  * @global    object $wpdb
  * @global    int $blog_id
  *
  * @param    int $chat_id Chat ID
  * @param    string $name Name
  * @param    string $avatar URL or e-mail
  * @param    string $message Payload message
  * @param    string $moderator Moderator
  */
 function send_message($chat_id, $name, $avatar, $message, $moderator)
 {
     global $wpdb, $blog_id;
     $wpdb->real_escape = true;
     $time_stamp = date("Y-m-d H:i:s");
     $moderator_str = 'no';
     if (empty($message)) {
         return false;
     }
     if ($moderator) {
         $moderator_str = 'yes';
     }
     $table = Chat::tablename('message');
     // If Table charset is not utf8mb4, emojis needs to be encoded as html entities.
     if (!strpos($wpdb->charset, 'mb4') && function_exists('wp_encode_emoji')) {
         $message = wp_encode_emoji($message);
     }
     $sql = $wpdb->prepare("INSERT INTO {$table} (blog_id, chat_id, timestamp, name, avatar, message, archived, moderator) VALUES (%d, %d, %s, %s, %s, %s, %s, %s)", $blog_id, $chat_id, $time_stamp, $name, $avatar, $message, 'no', $moderator_str);
     return $wpdb->query($sql);
 }
Esempio n. 16
0
 public function sanitize_option_value($key, $val, $def_val, $network = false, $mod = false)
 {
     // remove localization for more generic match
     if (preg_match('/(#.*|:[0-9]+)$/', $key) > 0) {
         $key = preg_replace('/(#.*|:[0-9]+)$/', '', $key);
     }
     // hooked by the sharing class
     $option_type = apply_filters($this->p->cf['lca'] . '_option_type', false, $key, $network, $mod);
     // pre-filter most values to remove html
     switch ($option_type) {
         case 'html':
             // leave html and css / javascript code blocks as-is
         // leave html and css / javascript code blocks as-is
         case 'code':
             $val = stripslashes($val);
             break;
         default:
             $val = stripslashes($val);
             $val = wp_filter_nohtml_kses($val);
             $val = wp_encode_emoji(htmlentities($val, ENT_QUOTES, get_bloginfo('charset'), false));
             // double_encode = false
             break;
     }
     switch ($option_type) {
         // must be empty or texturized
         case 'textured':
             if ($val !== '') {
                 $val = trim(wptexturize(' ' . $val . ' '));
             }
             break;
             // must be empty or a url
         // must be empty or a url
         case 'url':
             if ($val !== '') {
                 $val = $this->cleanup_html_tags($val);
                 if (strpos($val, '//') === false) {
                     $this->p->notice->err(sprintf('The value of option \'%s\' must be a URL - resetting the option to its default value.', $key), true);
                     $val = $def_val;
                 }
             }
             break;
             // strip leading urls off facebook usernames
         // strip leading urls off facebook usernames
         case 'url_base':
             if ($val !== '') {
                 $val = $this->cleanup_html_tags($val);
                 $val = preg_replace('/(http|https):\\/\\/[^\\/]*?\\//', '', $val);
             }
             break;
             // twitter-style usernames (prepend with an @ character)
         // twitter-style usernames (prepend with an @ character)
         case 'at_name':
             if ($val !== '') {
                 $val = substr(preg_replace('/[^a-zA-Z0-9_]/', '', $val), 0, 15);
                 if (!empty($val)) {
                     $val = '@' . $val;
                 }
             }
             break;
         case 'pos_num':
             // integer options that must be 1 or more (not zero)
         // integer options that must be 1 or more (not zero)
         case 'img_dim':
             // image dimensions, subject to minimum value (typically, at least 200px)
             if ($option_type == 'img_dim') {
                 $min_int = empty($this->p->cf['head']['min_img_dim']) ? 200 : $this->p->cf['head']['min_img_dim'];
             } else {
                 $min_int = 1;
             }
             // custom meta options are allowed to be empty
             if ($val === '' && $mod !== false) {
                 break;
             } elseif (!is_numeric($val) || $val < $min_int) {
                 $this->p->notice->err(sprintf('The value of option \'%s\' must be greater or equal to %s - resetting the option to its default value.', $key, $min_int), true);
                 $val = $def_val;
             }
             break;
             // must be blank or numeric
         // must be blank or numeric
         case 'blank_num':
             if ($val !== '' && !is_numeric($val)) {
                 $this->p->notice->err(sprintf('The value of option \'%s\' must be numeric - resetting the option to its default value.', $key), true);
                 $val = $def_val;
             }
             break;
             // must be numeric
         // must be numeric
         case 'numeric':
             if (!is_numeric($val)) {
                 $this->p->notice->err(sprintf('The value of option \'%s\' must be numeric - resetting the option to its default value.', $key), true);
                 $val = $def_val;
             }
             break;
             // must be alpha-numeric uppercase (hyphens are allowed as well)
         // must be alpha-numeric uppercase (hyphens are allowed as well)
         case 'auth_id':
             $val = trim($val);
             if ($val !== '' && preg_match('/[^A-Z0-9\\-]/', $val)) {
                 $this->p->notice->err(sprintf('\'%s\' is not an acceptable value for option \'%s\' - resetting the option to its default value.', $val, $key), true);
                 $val = $def_val;
             }
             break;
             // blank or alpha-numeric (upper or lower case), plus underscores
         // blank or alpha-numeric (upper or lower case), plus underscores
         case 'api_key':
             $val = trim($val);
             if ($val !== '' && preg_match('/[^a-zA-Z0-9_]/', $val)) {
                 $this->p->notice->err(sprintf('The value of option \'%s\' must be alpha-numeric - resetting the option to its default value.', $key), true);
                 $val = $def_val;
             }
             break;
             // text strings that can be blank
         // text strings that can be blank
         case 'ok_blank':
             if ($val !== '') {
                 $val = trim($val);
             }
             break;
         case 'desc':
         case 'one_line':
             if ($val !== '') {
                 $val = trim(preg_replace('/[\\s\\n\\r]+/s', ' ', $val));
             }
             break;
         case 'html':
             if ($val !== '') {
                 $val = trim($val);
                 if (!preg_match('/<.*>/', $val)) {
                     $this->p->notice->err(sprintf('The value of option \'%s\' must be HTML code - resetting the option to its default value.', $key), true);
                     $val = $def_val;
                 }
             }
             break;
             // options that cannot be blank
         // options that cannot be blank
         case 'code':
         case 'not_blank':
             if ($val === '') {
                 $this->p->notice->err(sprintf('The value of option \'%s\' cannot be empty - resetting the option to its default value.', $key), true);
                 $val = $def_val;
             }
             break;
             // everything else is a 1 or 0 checkbox option
         // everything else is a 1 or 0 checkbox option
         case 'checkbox':
         default:
             if ($def_val === 0 || $def_val === 1) {
                 // make sure the default option is also a 1 or 0, just in case
                 $val = empty($val) ? 0 : 1;
             }
             break;
     }
     return $val;
 }