/**
  * Run the converter now
  *
  * @since 1.0
  *
  * @param array $args can be extension
  * @param array $vars
  */
 function update_attachments($args = array(), $vars = array())
 {
     $images = Tiff_Converter::get_images();
     $mime_type = 'image/jpg';
     // Maybe $args[0] for changing it
     if ($images) {
         $succeed = $failed = 0;
         foreach ($images as $image) {
             $file = get_attached_file($image->ID);
             $result = Tiff_Converter_Handle::convert_image($file, $mime_type);
             if (!is_wp_error($result)) {
                 $update_args = array('ID' => $image->ID, 'post_mime_type' => $result['mime-type']);
                 $result2 = wp_update_post($update_args, true);
                 if ($result2 && !is_wp_error($result2)) {
                     unlink($file);
                     update_attached_file($image->ID, $result['path']);
                     wp_update_attachment_metadata($image->ID, wp_generate_attachment_metadata($image->ID, $result['path']));
                     $succeed++;
                 } else {
                     unlink($result['path']);
                     $failed++;
                 }
             } else {
                 $failed++;
             }
         }
         WP_CLI::success(sprintf('%d images are converted and %s failed', $succeed, $failed));
     } else {
         WP_CLI::success('No images to convert');
     }
 }
 /**
  * Sufffix random characters to attachment to prevent direct access to it by guessing URL
  *
  * @param int $attachment_id ID of attachment
  * @return boolean True on success else false
  */
 public function secure_attachment_file($attachment_id)
 {
     $file = get_attached_file($attachment_id);
     $file_parts = pathinfo($file);
     $file_new = $file_parts['dirname'] . '/' . $file_parts['filename'] . '_' . wp_generate_password(5, false) . '.' . $file_parts['extension'];
     if (rename($file, $file_new)) {
         update_attached_file($attachment_id, $file_new);
         return true;
     } else {
         return false;
     }
 }
Esempio n. 3
0
 function detheme_get_image_id($image_url)
 {
     if (!function_exists('wp_generate_attachment_metadata')) {
         require_once ABSPATH . 'wp-admin/includes/image.php';
     }
     global $wpdb;
     $upload_dir_paths = wp_upload_dir();
     $attachment = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE guid='%s';", $image_url));
     if (!$attachment && false !== strpos($image_url, $upload_dir_paths['baseurl'])) {
         // If this is the URL of an auto-generated thumbnail, get the URL of the original image
         $attachment_url = preg_replace('/-\\d+x\\d+(?=\\.(jpg|jpeg|png|gif)$)/i', '', $image_url);
         // Remove the upload path base directory from the attachment URL
         $attachment_url = str_replace($upload_dir_paths['baseurl'] . '/', '', $attachment_url);
         $image_path = $upload_dir_paths['basedir'] . "/" . $attachment_url;
         $attachment = wp_insert_attachment(array('post_title' => sanitize_title(basename($image_url)), 'post_mime_type' => 'image/jpg', 'guid' => $image_url));
         wp_update_attachment_metadata($attachment, wp_generate_attachment_metadata($attachment, $image_path));
         update_attached_file($attachment, $image_path);
     }
     return $attachment;
 }
Esempio n. 4
0
/**
 * Update the attachment's meta data after being converted 
 */
function ewww_image_optimizer_update_attachment($meta, $ID)
{
    global $ewww_debug;
    global $wpdb;
    $ewww_debug .= "<b>ewww_image_optimizer_update_attachment()</b><br>";
    // update the file location in the post metadata based on the new path stored in the attachment metadata
    update_attached_file($ID, $meta['file']);
    // retrieve the post information based on the $ID
    $post = get_post($ID);
    // save the previous attachment address
    $old_guid = $post->guid;
    // construct the new guid based on the filename from the attachment metadata
    $guid = dirname($post->guid) . "/" . basename($meta['file']);
    // retrieve any posts that link the image
    $esql = $wpdb->prepare("SELECT ID, post_content FROM {$wpdb->posts} WHERE post_content LIKE '%%%s%%'", $old_guid);
    // while there are posts to process
    $rows = $wpdb->get_results($esql, ARRAY_A);
    foreach ($rows as $row) {
        // replace all occurences of the old guid with the new guid
        $post_content = str_replace($old_guid, $guid, $row['post_content']);
        $ewww_debug .= "replacing {$old_guid} with {$guid} in post " . $row['ID'] . '<br>';
        // send the updated content back to the database
        $wpdb->update($wpdb->posts, array('post_content' => $post_content), array('ID' => $row['ID']));
    }
    if (isset($meta['sizes'])) {
        // for each resized version
        foreach ($meta['sizes'] as $size => $data) {
            // if the resize was converted
            if (isset($data['converted'])) {
                // generate the url for the old image
                if (empty($data['real_orig_file'])) {
                    $old_sguid = dirname($post->guid) . "/" . basename($data['orig_file']);
                } else {
                    $old_sguid = dirname($post->guid) . "/" . basename($data['real_orig_file']);
                    unset($meta['sizes'][$size]['real_orig_file']);
                }
                $ewww_debug .= "processing: {$size}<br>";
                $ewww_debug .= "old guid: {$old_sguid} <br>";
                // generate the url for the new image
                $sguid = dirname($post->guid) . "/" . basename($data['file']);
                $ewww_debug .= "new guid: {$sguid} <br>";
                // retrieve any posts that link the resize
                $ersql = $wpdb->prepare("SELECT ID, post_content FROM {$wpdb->posts} WHERE post_content LIKE '%%%s%%'", $old_sguid);
                $ewww_debug .= "using query: {$ersql}<br>";
                $rows = $wpdb->get_results($ersql, ARRAY_A);
                // while there are posts to process
                foreach ($rows as $row) {
                    // replace all occurences of the old guid with the new guid
                    $post_content = str_replace($old_sguid, $sguid, $row['post_content']);
                    $ewww_debug .= "replacing {$old_sguid} with {$sguid} in post " . $row['ID'] . '<br>';
                    // send the updated content back to the database
                    $wpdb->update($wpdb->posts, array('post_content' => $post_content), array('ID' => $row['ID']));
                }
            }
        }
    }
    // if the new image is a JPG
    if (preg_match('/.jpg$/i', basename($meta['file']))) {
        // set the mimetype to JPG
        $mime = 'image/jpg';
    }
    // if the new image is a PNG
    if (preg_match('/.png$/i', basename($meta['file']))) {
        // set the mimetype to PNG
        $mime = 'image/png';
    }
    if (preg_match('/.gif$/i', basename($meta['file']))) {
        // set the mimetype to GIF
        $mime = 'image/gif';
    }
    // update the attachment post with the new mimetype and guid
    wp_update_post(array('ID' => $ID, 'post_mime_type' => $mime, 'guid' => $guid));
    ewww_image_optimizer_debug_log();
    ewwwio_memory(__FUNCTION__);
    return $meta;
}
Esempio n. 5
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. 6
0
/**
 * Saves image to post along with enqueued changes
 * in $_REQUEST['history']
 *
 * @param int $post_id
 * @return \stdClass
 */
function wp_save_image($post_id)
{
    global $_wp_additional_image_sizes;
    $return = new stdClass();
    $success = $delete = $scaled = $nocrop = false;
    $post = get_post($post_id);
    $img = wp_get_image_editor(_load_image_to_edit_path($post_id, 'full'));
    if (is_wp_error($img)) {
        $return->error = esc_js(__('Unable to create new image.'));
        return $return;
    }
    $fwidth = !empty($_REQUEST['fwidth']) ? intval($_REQUEST['fwidth']) : 0;
    $fheight = !empty($_REQUEST['fheight']) ? intval($_REQUEST['fheight']) : 0;
    $target = !empty($_REQUEST['target']) ? preg_replace('/[^a-z0-9_-]+/i', '', $_REQUEST['target']) : '';
    $scale = !empty($_REQUEST['do']) && 'scale' == $_REQUEST['do'];
    if ($scale && $fwidth > 0 && $fheight > 0) {
        $size = $img->get_size();
        $sX = $size['width'];
        $sY = $size['height'];
        // Check if it has roughly the same w / h ratio.
        $diff = round($sX / $sY, 2) - round($fwidth / $fheight, 2);
        if (-0.1 < $diff && $diff < 0.1) {
            // Scale the full size image.
            if ($img->resize($fwidth, $fheight)) {
                $scaled = true;
            }
        }
        if (!$scaled) {
            $return->error = esc_js(__('Error while saving the scaled image. Please reload the page and try again.'));
            return $return;
        }
    } elseif (!empty($_REQUEST['history'])) {
        $changes = json_decode(wp_unslash($_REQUEST['history']));
        if ($changes) {
            $img = image_edit_apply_changes($img, $changes);
        }
    } else {
        $return->error = esc_js(__('Nothing to save, the image has not changed.'));
        return $return;
    }
    $meta = wp_get_attachment_metadata($post_id);
    $backup_sizes = get_post_meta($post->ID, '_wp_attachment_backup_sizes', true);
    if (!is_array($meta)) {
        $return->error = esc_js(__('Image data does not exist. Please re-upload the image.'));
        return $return;
    }
    if (!is_array($backup_sizes)) {
        $backup_sizes = array();
    }
    // Generate new filename.
    $path = get_attached_file($post_id);
    $path_parts = pathinfo($path);
    $filename = $path_parts['filename'];
    $suffix = time() . rand(100, 999);
    if (defined('IMAGE_EDIT_OVERWRITE') && IMAGE_EDIT_OVERWRITE && isset($backup_sizes['full-orig']) && $backup_sizes['full-orig']['file'] != $path_parts['basename']) {
        if ('thumbnail' == $target) {
            $new_path = "{$path_parts['dirname']}/{$filename}-temp.{$path_parts['extension']}";
        } else {
            $new_path = $path;
        }
    } else {
        while (true) {
            $filename = preg_replace('/-e([0-9]+)$/', '', $filename);
            $filename .= "-e{$suffix}";
            $new_filename = "{$filename}.{$path_parts['extension']}";
            $new_path = "{$path_parts['dirname']}/{$new_filename}";
            if (file_exists($new_path)) {
                $suffix++;
            } else {
                break;
            }
        }
    }
    // Save the full-size file, also needed to create sub-sizes.
    if (!wp_save_image_file($new_path, $img, $post->post_mime_type, $post_id)) {
        $return->error = esc_js(__('Unable to save the image.'));
        return $return;
    }
    if ('nothumb' == $target || 'all' == $target || 'full' == $target || $scaled) {
        $tag = false;
        if (isset($backup_sizes['full-orig'])) {
            if ((!defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE) && $backup_sizes['full-orig']['file'] != $path_parts['basename']) {
                $tag = "full-{$suffix}";
            }
        } else {
            $tag = 'full-orig';
        }
        if ($tag) {
            $backup_sizes[$tag] = array('width' => $meta['width'], 'height' => $meta['height'], 'file' => $path_parts['basename']);
        }
        $success = $path === $new_path || update_attached_file($post_id, $new_path);
        $meta['file'] = _wp_relative_upload_path($new_path);
        $size = $img->get_size();
        $meta['width'] = $size['width'];
        $meta['height'] = $size['height'];
        if ($success && ('nothumb' == $target || 'all' == $target)) {
            $sizes = get_intermediate_image_sizes();
            if ('nothumb' == $target) {
                $sizes = array_diff($sizes, array('thumbnail'));
            }
        }
        $return->fw = $meta['width'];
        $return->fh = $meta['height'];
    } elseif ('thumbnail' == $target) {
        $sizes = array('thumbnail');
        $success = $delete = $nocrop = true;
    }
    if (isset($sizes)) {
        $_sizes = array();
        foreach ($sizes as $size) {
            $tag = false;
            if (isset($meta['sizes'][$size])) {
                if (isset($backup_sizes["{$size}-orig"])) {
                    if ((!defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE) && $backup_sizes["{$size}-orig"]['file'] != $meta['sizes'][$size]['file']) {
                        $tag = "{$size}-{$suffix}";
                    }
                } else {
                    $tag = "{$size}-orig";
                }
                if ($tag) {
                    $backup_sizes[$tag] = $meta['sizes'][$size];
                }
            }
            if (isset($_wp_additional_image_sizes[$size])) {
                $width = intval($_wp_additional_image_sizes[$size]['width']);
                $height = intval($_wp_additional_image_sizes[$size]['height']);
                $crop = $nocrop ? false : $_wp_additional_image_sizes[$size]['crop'];
            } else {
                $height = get_option("{$size}_size_h");
                $width = get_option("{$size}_size_w");
                $crop = $nocrop ? false : get_option("{$size}_crop");
            }
            $_sizes[$size] = array('width' => $width, 'height' => $height, 'crop' => $crop);
        }
        $meta['sizes'] = array_merge($meta['sizes'], $img->multi_resize($_sizes));
    }
    unset($img);
    if ($success) {
        wp_update_attachment_metadata($post_id, $meta);
        update_post_meta($post_id, '_wp_attachment_backup_sizes', $backup_sizes);
        if ($target == 'thumbnail' || $target == 'all' || $target == 'full') {
            // Check if it's an image edit from attachment edit screen
            if (!empty($_REQUEST['context']) && 'edit-attachment' == $_REQUEST['context']) {
                $thumb_url = wp_get_attachment_image_src($post_id, array(900, 600), true);
                $return->thumbnail = $thumb_url[0];
            } else {
                $file_url = wp_get_attachment_url($post_id);
                if (!empty($meta['sizes']['thumbnail']) && ($thumb = $meta['sizes']['thumbnail'])) {
                    $return->thumbnail = path_join(dirname($file_url), $thumb['file']);
                } else {
                    $return->thumbnail = "{$file_url}?w=128&h=128";
                }
            }
        }
    } else {
        $delete = true;
    }
    if ($delete) {
        wp_delete_file($new_path);
    }
    $return->msg = esc_js(__('Image saved'));
    return $return;
}
/**
 * Adds image to library.
 *
 * @param type $post
 * @param type $abspath
 */
function wpcf_image_add_to_library($post, $abspath)
{
    $guid = wpcf_image_attachment_url($abspath);
    if (!wpcf_image_is_attachment($guid)) {
        $wp_filetype = wp_check_filetype(basename($abspath), null);
        $attachment = array('post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($abspath)), 'post_content' => '', 'post_status' => 'inherit', 'guid' => $guid);
        $attach_id = wp_insert_attachment($attachment, $abspath, $post->ID);
        require_once ABSPATH . "wp-admin" . '/includes/image.php';
        $attach_data = wp_generate_attachment_metadata($attach_id, $abspath);
        $attach_data['file'] = str_replace('\\', '/', wpcf_image_normalize_attachment($attach_data['file']));
        wp_update_attachment_metadata($attach_id, $attach_data);
        update_attached_file($attach_id, $attach_data['file']);
    }
}
Esempio n. 8
0
/**
 * wpsc_convert_products_to_posts function.
 *
 * @access public
 * @return void
 */
function wpsc_convert_products_to_posts()
{
    global $wpdb, $user_ID;
    // Select all products
    $wpsc_update = WPSC_Update::get_instance();
    if (!empty($wpdb->charset)) {
        $charset_collate = "DEFAULT CHARACTER SET {$wpdb->charset}";
    }
    if (!empty($wpdb->collate)) {
        $charset_collate .= " COLLATE {$wpdb->collate}";
    }
    if (!($offset = get_transient('wpsc_update_product_offset'))) {
        $offset = 0;
    }
    $limit = 90;
    $sql = "\n\t\tSELECT * FROM " . WPSC_TABLE_PRODUCT_LIST . "\n\t\tWHERE active = '1'\n\t\tLIMIT %d, %d\n\t";
    $post_created = get_transient('wpsc_update_current_product');
    $total = $wpdb->get_var("SELECT COUNT(*) FROM " . WPSC_TABLE_PRODUCT_LIST . " WHERE active='1'");
    $progress = new WPSC_Update_Progress($total);
    while (true) {
        $product_data = $wpdb->get_results($wpdb->prepare($sql, $offset, $limit), ARRAY_A);
        $i = $offset;
        if (empty($product_data)) {
            break;
        }
        foreach ((array) $product_data as $product) {
            $wpsc_update->check_timeout('</div>');
            $post_id = 0;
            // if a product is in the middle of being converted
            if ($post_created && !empty($post_created['original_id']) && $post_created['original_id'] == $product['id']) {
                $post_id = $post_created['post_id'];
            }
            $sku = old_get_product_meta($product['id'], 'sku', true);
            if ($post_id == 0) {
                $post_status = "publish";
                if ($product['publish'] != 1) {
                    $post_status = "draft";
                }
                //check the product added time with the current time to make sure its not out - this aviods the future post status
                $product_added_time = strtotime($product['date_added']);
                $current_time = time();
                $post_date = $product['date_added'];
                if ((int) $current_time < (int) $product_added_time) {
                    $post_date = date("Y-m-d H:i:s");
                }
                $product_post_values = array('post_author' => $user_ID, 'post_date' => $post_date, 'post_content' => $product['description'], 'post_excerpt' => $product['additional_description'], 'post_title' => $product['name'], 'post_status' => $post_status, 'post_type' => "wpsc-product", 'post_name' => $product['name']);
                $product['order'] = $wpdb->get_var($wpdb->prepare("\n\t\t\t\t\tSELECT `order` FROM " . WPSC_TABLE_PRODUCT_ORDER . "\n\t\t\t\t\tWHERE product_id = %d\n\t\t\t\t", $product['id']));
                $product_post_values['menu_order'] = $product['order'];
                $post_id = wp_insert_post($product_post_values);
                $post_created = array('original_id' => $product['id'], 'post_id' => $post_id);
                set_transient('wpsc_update_current_product', $post_created, 604800);
            }
            $product_meta_sql = $wpdb->prepare("\n\t\t\t\tSELECT \tIF( ( `custom` != 1\t),\n\t\t\t\t\t\tCONCAT( '_wpsc_', `meta_key` ) ,\n\t\t\t\t\t`meta_key`\n\t\t\t\t\t) AS `meta_key`,\n\t\t\t\t\t`meta_value`\n\t\t\t\tFROM `" . WPSC_TABLE_PRODUCTMETA . "`\n\t\t\t\tWHERE `product_id` = %d\n\t\t\t\tAND `meta_value` != ''", $product['id']);
            $product_meta = $wpdb->get_results($product_meta_sql, ARRAY_A);
            $post_data = array();
            foreach ($product_meta as $k => $pm) {
                if ($pm['meta_value'] == 'om') {
                    $pm['meta_value'] = 1;
                }
                $pm['meta_value'] = maybe_unserialize($pm['meta_value']);
                if (strpos($pm['meta_key'], '_wpsc_') === 0) {
                    $post_data['_wpsc_product_metadata'][$pm['meta_key']] = $pm['meta_value'];
                } else {
                    update_post_meta($post_id, $pm['meta_key'], $pm['meta_value']);
                }
            }
            $post_data['_wpsc_original_id'] = (int) $product['id'];
            $post_data['_wpsc_price'] = (double) $product['price'];
            $post_data['_wpsc_special_price'] = $post_data['_wpsc_price'] - (double) $product['special_price'];
            // special price get stored in a weird way in 3.7.x
            $post_data['_wpsc_stock'] = (double) $product['quantity'];
            $post_data['_wpsc_is_donation'] = $product['donation'];
            $post_data['_wpsc_sku'] = $sku;
            if ((bool) $product['quantity_limited'] != true) {
                $post_data['_wpsc_stock'] = false;
            }
            unset($post_data['_wpsc_limited_stock']);
            $post_data['_wpsc_product_metadata']['is_stock_limited'] = (int) (bool) $product['quantity_limited'];
            // Product Weight
            $post_data['_wpsc_product_metadata']['weight'] = wpsc_convert_weight($product['weight'], $product['weight_unit'], "pound", true);
            $post_data['_wpsc_product_metadata']['weight_unit'] = $product['weight_unit'];
            $post_data['_wpsc_product_metadata']['display_weight_as'] = $product['weight_unit'];
            $post_data['_wpsc_product_metadata']['has_no_shipping'] = (int) (bool) $product['no_shipping'];
            $post_data['_wpsc_product_metadata']['shipping'] = array('local' => $product['pnp'], 'international' => $product['international_pnp']);
            $post_data['_wpsc_product_metadata']['quantity_limited'] = (int) (bool) $product['quantity_limited'];
            $post_data['_wpsc_product_metadata']['special'] = (int) (bool) $product['special'];
            if (isset($post_data['meta'])) {
                $post_data['_wpsc_product_metadata']['notify_when_none_left'] = (int) (bool) $post_data['meta']['_wpsc_product_metadata']['notify_when_none_left'];
                $post_data['_wpsc_product_metadata']['unpublish_when_none_left'] = (int) (bool) $post_data['meta']['_wpsc_product_metadata']['unpublish_when_none_left'];
            }
            $post_data['_wpsc_product_metadata']['no_shipping'] = (int) (bool) $product['no_shipping'];
            foreach ($post_data as $meta_key => $meta_value) {
                // prefix all meta keys with _wpsc_
                update_post_meta($post_id, $meta_key, $meta_value);
            }
            // get the wordpress upload directory data
            $wp_upload_dir_data = wp_upload_dir();
            $wp_upload_basedir = $wp_upload_dir_data['basedir'];
            $category_ids = array();
            $category_data = $wpdb->get_col("SELECT `category_id` FROM `" . WPSC_TABLE_ITEM_CATEGORY_ASSOC . "` WHERE `product_id` IN ('{$product['id']}')");
            foreach ($category_data as $old_category_id) {
                $category_ids[] = wpsc_get_meta($old_category_id, 'category_id', 'wpsc_old_category');
            }
            wp_set_product_categories($post_id, $category_ids);
            $product_data = get_post($post_id);
            $image_data_sql = $wpdb->prepare("SELECT * FROM `" . WPSC_TABLE_PRODUCT_IMAGES . "` WHERE `product_id` = %d ORDER BY `image_order` ASC", $product['id']);
            $image_data = $wpdb->get_results($image_data_sql, ARRAY_A);
            foreach ((array) $image_data as $image_row) {
                $wpsc_update->check_timeout('</div>');
                // Get the image path info
                $image_pathinfo = pathinfo($image_row['image']);
                // use the path info to clip off the file extension
                $image_name = basename($image_pathinfo['basename'], ".{$image_pathinfo['extension']}");
                // construct the full image path
                $full_image_path = WPSC_IMAGE_DIR . $image_row['image'];
                $attached_file_path = str_replace($wp_upload_basedir . "/", '', $full_image_path);
                $upload_dir = wp_upload_dir();
                $new_path = $upload_dir['path'] . '/' . $image_name . '.' . $image_pathinfo['extension'];
                if (is_file($full_image_path)) {
                    copy($full_image_path, $new_path);
                } else {
                    continue;
                }
                // construct the full image url
                $subdir = $upload_dir['subdir'] . '/' . $image_name . '.' . $image_pathinfo['extension'];
                $subdir = substr($subdir, 1);
                $attachment_id_sql = $wpdb->prepare("SELECT `ID` FROM `{$wpdb->posts}` WHERE `post_title` = %s AND `post_parent` = %d LIMIT 1", $image_name, $post_id);
                $attachment_id = (int) $wpdb->get_var($attachment_id_sql);
                // get the image MIME type
                $mime_type_data = wpsc_get_mimetype($full_image_path, true);
                if ((int) $attachment_id == 0) {
                    // construct the image data array
                    $image_post_values = array('post_author' => $user_ID, 'post_parent' => $post_id, 'post_date' => $product_data->post_date, 'post_content' => $image_name, 'post_title' => $image_name, 'post_status' => "inherit", 'post_type' => "attachment", 'post_name' => sanitize_title($image_name), 'post_mime_type' => $mime_type_data['mime_type'], 'menu_order' => absint($image_row['image_order']), 'guid' => $new_path);
                    $attachment_id = wp_insert_post($image_post_values);
                }
                update_attached_file($attachment_id, $new_path);
                wp_update_attachment_metadata($attachment_id, wp_generate_attachment_metadata($attachment_id, $new_path));
            }
            $i++;
            $progress->update($i);
            set_transient('wpsc_update_product_offset', $i, 604800);
        }
        $offset += $limit;
    }
    //Just throwing the payment gateway update in here because it doesn't really warrant it's own function :)
    $custom_gateways = get_option('custom_gateway_options');
    array_walk($custom_gateways, "wpec_update_gateway");
    update_option('custom_gateway_options', $custom_gateways);
}
Esempio n. 9
0
 public static function attachment_fields_to_save($post, $attachment)
 {
     if (isset($attachment[self::META_POSITION]) && $attachment[self::META_POSITION]) {
         $previousPosition = self::getMeta($post['ID']);
         $position = json_decode($attachment[self::META_POSITION]);
         update_post_meta($post['ID'], self::META_POSITION, $position);
         // Update the thumbnail if the position changed
         if ($previousPosition[0] != $position[0] || $previousPosition[1] != $position[1]) {
             $realOldImagePath = get_attached_file($post['ID']);
             $oldImagePath = str_ireplace('-focalcropped', '', $realOldImagePath);
             // Rename file, while keeping the previous version
             // Generate new filename
             $oldImagePathParts = pathinfo($oldImagePath);
             $filename = $oldImagePathParts['filename'];
             $suffix = '-focalcropped';
             //time() . rand(100, 999);
             $filename = str_ireplace('-focalcropped', '', $filename);
             $filename .= $suffix;
             $newImageFile = "{$filename}.{$oldImagePathParts['extension']}";
             $newImagePath = "{$oldImagePathParts['dirname']}/{$newImageFile}";
             $url = '';
             if (copy($oldImagePath, $newImagePath)) {
                 $url = $newImagePath;
             }
             if (!$url) {
                 return false;
             }
             @set_time_limit(900);
             // 5 minutes per image should be PLENTY
             update_attached_file($post['ID'], $url);
             $metadata = wp_generate_attachment_metadata($post['ID'], $url);
             if (!$metadata || is_wp_error($metadata)) {
                 wp_send_json_error('empty metadata');
             }
             wp_update_attachment_metadata($post['ID'], $metadata);
             //@unlink($file);
             clean_post_cache($post['ID']);
         }
     }
     return $post;
 }
Esempio n. 10
0
function unitydog_add_attachment($pid)
{
    $post = get_post($pid);
    $file = get_attached_file($pid);
    $path = pathinfo($file);
    // If it's not a unity file - get outa here stalker
    if ($path['extension'] != "unity3d") {
        return;
    }
    $newfile = $file . ".zip";
    // add a zip
    rename($file, $newfile);
    update_attached_file($pid, $newfile);
}
 /**
  * Updates the review widget graphic and saves it as an attachment
  */
 public function update_review_widget()
 {
     $filename = $this->id . '.gif';
     $raw_data = file_get_contents('https://www.trustedshops.com/bewertung/widget/widgets/' . $filename);
     $uploads = wp_upload_dir(date('Y-m'));
     if (is_wp_error($uploads)) {
         return;
     }
     $filepath = $uploads['path'] . '/' . $filename;
     file_put_contents($filepath, $raw_data);
     $attachment = array('guid' => $uploads['url'] . '/' . basename($filepath), 'post_mime_type' => 'image/gif', 'post_title' => _x('Trusted Shops Customer Reviews', 'trusted-shops', 'woocommerce-germanized'), 'post_content' => '', 'post_status' => 'publish');
     if (!$this->get_review_widget_attachment()) {
         $attachment_id = wp_insert_attachment($attachment, $filepath);
         update_option('woocommerce_gzd_trusted_shops_review_widget_attachment', $attachment_id);
     } else {
         $attachment_id = $this->get_review_widget_attachment();
         update_attached_file($attachment_id, $filepath);
         $attachment['ID'] = $attachment_id;
         wp_update_post($attachment);
     }
     require_once ABSPATH . 'wp-admin/includes/image.php';
     // Generate the metadata for the attachment, and update the database record.
     $attach_data = wp_generate_attachment_metadata($attachment_id, $filepath);
     wp_update_attachment_metadata($attachment_id, $attach_data);
 }
	function woo_cd_admin_init() {

		global $export, $wp_roles;

		$troubleshooting_url = 'http://www.visser.com.au/documentation/store-exporter-deluxe/usage/';

		// Time to tell the store owner if we were unable to disable the basic Store Exporter
		if( defined( 'WOO_CE_PREFIX' ) ) {
			// Display notice if we were unable to de-activate basic Store Exporter
			if( ( is_plugin_active( 'woocommerce-exporter/exporter.php' ) || is_plugin_active( 'woocommerce-store-exporter/exporter.php' ) ) && current_user_can( 'activate_plugins' ) ) {
				$plugins_url = esc_url( add_query_arg( '', '', 'plugins.php' ) );
				$message = sprintf( __( 'We did our best to de-activate Store Exporter for you but may have failed, please check that the basic Store Exporter is de-activated from the <a href="%s">Plugins screen</a>.', 'woo_ce' ), $plugins_url );
				woo_cd_admin_notice( $message, 'error', array( 'plugins.php', 'update-core.php' ) );
			}
		}

		// Detect if another e-Commerce platform is activated
		if( !woo_is_woo_activated() && ( woo_is_jigo_activated() || woo_is_wpsc_activated() ) ) {
			$message = sprintf( __( 'We have detected another e-Commerce Plugin than WooCommerce activated, please check that you are using Store Exporter Deluxe for the correct platform. <a href="%s" target="_blank">Need help?</a>', 'woo_ce' ), $troubleshooting_url );
			woo_cd_admin_notice( $message, 'error', 'plugins.php' );
		} else if( !woo_is_woo_activated() ) {
			$message = sprintf( __( 'We have been unable to detect the WooCommerce Plugin activated on this WordPress site, please check that you are using Store Exporter Deluxe for the correct platform. <a href="%s" target="_blank">Need help?</a>', 'woo_ce' ), $troubleshooting_url );
			woo_cd_admin_notice( $message, 'error', 'plugins.php' );
		}

		// Detect if WooCommerce Subscriptions Exporter is activated
		if( function_exists( 'wc_subs_exporter_admin_init' ) ) {
			$message = sprintf( __( 'We have detected a WooCommerce Plugin that is activated and known to conflict with Store Exporter Deluxe, please de-activate WooCommerce Subscriptions Exporter to resolve export issues. <a href="%s" target="_blank">Need help?</a>', 'woo_ce' ), $troubleshooting_url );
			woo_cd_admin_notice( $message, 'error', array( 'plugins.php', 'admin.php' ) );
		}

		// Displays a HTML notice where we have detected the site has moved or this is staging site
		if(
			woo_ce_get_option( 'duplicate_site_prompt', 0 )
			&& ( woo_ce_get_option( 'override_duplicate_site_prompt', 0 ) == false )
			&& ( woo_ce_get_option( 'dismiss_duplicate_site_prompt', 0 ) == false )
		) {
			$dismiss_url = esc_url( add_query_arg( 'action', 'dismiss_duplicate_site_prompt' ) );
			$override_url = esc_url( add_query_arg( 'action', 'override_duplicate_site_prompt' ) );
			$message = __( 'It looks like this site has moved or is a duplicate site. Store Exporter Deluxe has disabled scheduled exports on this site to prevent duplicate scheduled exports being generated from a staging or test environment.', 'woo_ce' ) . '<br /><br /><a href="' . $override_url . '" class="button-primary">' . __( 'Continue running scheduled exports', 'woo_ce' ) . '</a>' . '<span style="float:right;"><a href="' . $dismiss_url . '">' . __( 'Dismiss', 'woo_ce' ) . '</a></span>';
			woo_cd_admin_notice( $message, 'error' );
		}

		add_action( 'after_plugin_row_' . WOO_CD_RELPATH, 'woo_ce_admin_plugin_row' );

		// Check the User has the view_woocommerce_reports capability
		if( current_user_can( 'view_woocommerce_reports' ) ) {
			// Load Dashboard widget for Scheduled Exports
			add_action( 'wp_dashboard_setup', 'woo_ce_dashboard_setup' );
			// Add Export Status to Orders screen
			add_filter( 'manage_edit-shop_order_columns', 'woo_ce_admin_order_column_headers', 20 );
			add_action( 'manage_shop_order_posts_custom_column', 'woo_ce_admin_order_column_content' );
			// Load Download buttons for Orders screen
			wp_enqueue_style( 'dashicons' );
			wp_enqueue_style( 'woo_ce_styles', plugins_url( '/templates/admin/export.css', WOO_CD_RELPATH ) );
			// Add our export to CSV, XML, XLS, XLSX action buttons
			add_filter( 'woocommerce_admin_order_actions', 'woo_ce_admin_order_actions', 10, 2 );
			add_action( 'wp_ajax_woo_ce_export_order', 'woo_ce_ajax_export_order' );
			// Add Download as... options to Orders Bulk
			add_action( 'admin_footer', 'woo_ce_admin_order_bulk_actions' );
			add_action( 'load-edit.php', 'woo_ce_admin_order_process_bulk_action' );
			// Add Download as... options to Edit Order Actions
			add_action( 'woocommerce_order_actions', 'woo_ce_admin_order_single_actions' );
			add_action( 'woocommerce_order_action_woo_ce_export_order_csv', 'woo_ce_admin_order_single_export_csv' );
			add_action( 'woocommerce_order_action_woo_ce_export_order_xml', 'woo_ce_admin_order_single_export_xml' );
			add_action( 'woocommerce_order_action_woo_ce_export_order_xls', 'woo_ce_admin_order_single_export_xls' );
			add_action( 'woocommerce_order_action_woo_ce_export_order_xlsx', 'woo_ce_admin_order_single_export_xlsx' );
		}

		// Check that we are on the Store Exporter screen
		$page = ( isset($_GET['page'] ) ? sanitize_text_field( $_GET['page'] ) : false );
		if( $page != strtolower( WOO_CD_PREFIX ) )
			return;

		// Process any pre-export notice confirmations
		$action = woo_get_action();
		switch( $action ) {

			// Delete all Archives
			case 'nuke_archives':
				// We need to verify the nonce.
				if( !empty( $_GET ) && check_admin_referer( 'woo_ce_nuke_archives' ) ) {
					if( woo_ce_nuke_archive_files() ) {
						$message = __( 'All existing Archives and their export files have been deleted from your WordPress site.', 'woo_ce' );
						woo_cd_admin_notice( $message );
					} else {
						$message = __( 'There were no existing Archives to be deleted from your WordPress site.', 'woo_ce' );
						woo_cd_admin_notice( $message, 'error' );
					}
				}
				break;

			// Prompt on Export screen when insufficient memory (less than 64M is allocated)
			case 'dismiss_memory_prompt':
				woo_ce_update_option( 'dismiss_memory_prompt', 1 );
				$url = esc_url( add_query_arg( 'action', null ) );
				wp_redirect( $url );
				exit();
				break;

			// Prompt on Export screen when PHP configuration option max_execution_time cannot be increased
			case 'dismiss_execution_time_prompt':
				woo_ce_update_option( 'dismiss_execution_time_prompt', 1 );
				$url = esc_url( add_query_arg( 'action', null ) );
				wp_redirect( $url );
				exit();
				break;

			// Prompt on Export screen when insufficient memory (less than 64M is allocated)
			case 'dismiss_php_legacy':
				woo_ce_update_option( 'dismiss_php_legacy', 1 );
				$url = esc_url( add_query_arg( 'action', null ) );
				wp_redirect( $url );
				exit();
				break;

			case 'dismiss_subscription_prompt':
				woo_ce_update_option( 'dismiss_subscription_prompt', 1 );
				$url = esc_url( add_query_arg( 'action', null ) );
				wp_redirect( $url );
				exit();
				break;

			case 'dismiss_duplicate_site_prompt':
				woo_ce_update_option( 'dismiss_duplicate_site_prompt', 1 );
				$url = esc_url( add_query_arg( 'action', null ) );
				wp_redirect( $url );
				exit();
				break;

			case 'dismiss_secure_archives_prompt':
				woo_ce_update_option( 'dismiss_secure_archives_prompt', 1 );
				$url = esc_url( add_query_arg( 'action', null ) );
				wp_redirect( $url );
				exit();
				break;

			case 'override_duplicate_site_prompt':
				woo_ce_update_option( 'override_duplicate_site_prompt', 1 );
				// Enable scheduled exports again
				woo_ce_update_option( 'enable_auto', 1 );
				$url = esc_url( add_query_arg( 'action', null ) );
				wp_redirect( $url );
				exit();
				break;

			// Move legacy archives exports to the sed-exports directory within Uploads
			case 'relocate_archived_exports':

				// Create the sed-exports directory if it hasn't been
				woo_cd_create_secure_archives_dir();

				$updated = 0;
				if( $files = woo_ce_get_archive_files() ) {
					foreach( $files as $key => $file ) {
						$filepath = get_attached_file( $file->ID );
						// Check for archived exports that have not been moved to sed-exports
						if( strpos( $filepath, 'sed-exports' ) == false ) {
							// Move the export

							// Update the Post meta key _wp_attached_file
							$attached_file = get_post_meta( $file->ID, '_wp_attached_file', true );
							if( !empty( $attached_file ) )
								$attached_file = trailingslashit( 'sed-exports' ) . basename( $attached_file );
							$updated++;
						}
					}
				}

				// Show the response
				$message = sprintf( __( 'That\'s sorted, we\'ve relocated %d export files to the newly created <code>sed-exports</code> folder within the WordPress Uploads directory. Happy exporting!', 'woo_ce' ), $updated );
				woo_cd_admin_notice_html( $message );
				break;

			// Save skip overview preference
			case 'skip_overview':
				$skip_overview = false;
				if( isset( $_POST['skip_overview'] ) )
					$skip_overview = 1;
				woo_ce_update_option( 'skip_overview', $skip_overview );

				if( $skip_overview == 1 ) {
					$url = esc_url( add_query_arg( 'tab', 'export' ) );
					wp_redirect( $url );
					exit();
				}
				break;

			// This is where the magic happens
			case 'export':

				// Make sure we play nice with other WooCommerce and WordPress exporters
				if( !isset( $_POST['woo_ce_export'] ) )
					return;

				check_admin_referer( 'manual_export', 'woo_ce_export' );

				// Set up the basic export options
				$export = new stdClass();
				$export->cron = 0;
				$export->scheduled_export = 0;
				$export->start_time = time();
				$export->idle_memory_start = woo_ce_current_memory_usage();
				$export->delete_file = woo_ce_get_option( 'delete_file', 1 );
				$export->encoding = woo_ce_get_option( 'encoding', get_option( 'blog_charset', 'UTF-8' ) );
				// Reset the Encoding if corrupted
				if( $export->encoding == '' || $export->encoding == false || $export->encoding == 'System default' ) {
					error_log( '[store-exporter-deluxe] Warning: Encoding export option was corrupted, defaulted to UTF-8' );
					$export->encoding = 'UTF-8';
					woo_ce_update_option( 'encoding', 'UTF-8' );
				}
				$export->delimiter = woo_ce_get_option( 'delimiter', ',' );
				// Reset the Delimiter if corrupted
				if( $export->delimiter == '' || $export->delimiter == false ) {
					error_log( '[store-exporter-deluxe] Warning: Delimiter export option was corrupted, defaulted to ,' );
					$export->delimiter = ',';
					woo_ce_update_option( 'delimiter', ',' );
				} else if( $export->delimiter == 'TAB' ) {
					$export->delimiter = "\t";
				}
				$export->category_separator = woo_ce_get_option( 'category_separator', '|' );
				// Reset the Category Separator if corrupted
				if( $export->category_separator == '' || $export->category_separator == false ) {
					error_log( '[store-exporter-deluxe] Warning: Category Separator export option was corrupted, defaulted to |' );
					$export->category_separator = '|';
					woo_ce_update_option( 'category_separator', '|' );
				}
				// Override for line break (LF) support in Category Separator
				if( $export->category_separator == 'LF' )
					$export->category_separator = "\n";
				$export->bom = woo_ce_get_option( 'bom', 1 );
				$export->escape_formatting = woo_ce_get_option( 'escape_formatting', 'all' );
				// Reset the Escape Formatting if corrupted
				if( $export->escape_formatting == '' || $export->escape_formatting == false ) {
					error_log( '[store-exporter-deluxe] Warning: Escape Formatting export option was corrupted, defaulted to all' );
					$export->escape_formatting = 'all';
					woo_ce_update_option( 'escape_formatting', 'all' );
				}
				$export->header_formatting = woo_ce_get_option( 'header_formatting', 1 );
				$export->date_format = woo_ce_get_option( 'date_format', 'd/m/Y' );
				// Reset the Date Format if corrupted
				if( $export->date_format == '1' || $export->date_format == '' || $export->date_format == false ) {
					error_log( '[store-exporter-deluxe] Warning: Date Format export option was corrupted, defaulted to d/m/Y' );
					$export->date_format = 'd/m/Y';
					woo_ce_update_option( 'date_format', 'd/m/Y' );
				}

				// Save export option changes made on the Export screen
				$export->limit_volume = ( isset( $_POST['limit_volume'] ) ? sanitize_text_field( $_POST['limit_volume'] ) : '' );
				woo_ce_update_option( 'limit_volume', $export->limit_volume );
				if( $export->limit_volume == '' )
					$export->limit_volume = -1;
				$export->offset = ( isset( $_POST['offset'] ) ? sanitize_text_field( $_POST['offset'] ) : '' );
				woo_ce_update_option( 'offset', $export->offset );
				if( $export->offset == '' )
					$export->offset = 0;
				$export->type = ( isset( $_POST['dataset'] ) ? sanitize_text_field( $_POST['dataset'] ) : false );
				if( in_array( $export->type, array( 'product', 'category', 'tag', 'brand', 'order' ) ) ) {
					$export->description_excerpt_formatting = ( isset( $_POST['description_excerpt_formatting'] ) ? absint( $_POST['description_excerpt_formatting'] ) : false );
					if( $export->description_excerpt_formatting <> woo_ce_get_option( 'description_excerpt_formatting' ) )
						woo_ce_update_option( 'variation_formatting', $export->description_excerpt_formatting );
				}
				woo_ce_update_option( 'export_format', sanitize_text_field( $_POST['export_format'] ) );

				// Set default values for all export options to be later passed onto the export process
				$export->fields = array();
				$export->fields_order = false;
				$export->export_format = woo_ce_get_option( 'export_format', 'csv' );

				// Product sorting
				$export->product_categories = false;
				$export->product_tags = false;
				$export->product_brands = false;
				$export->product_vendors = false;
				$export->product_status = false;
				$export->product_type = false;
				$export->product_stock = false;
				$export->product_language = false;
				$export->product_orderby = false;
				$export->product_order = false;
				$export->gallery_formatting = false;
				$export->gallery_unique = false;
				$export->max_product_gallery = false;
				$export->upsell_formatting = false;
				$export->crosssell_formatting = false;
				$export->variation_formatting = false;

				// Category sorting
				$export->category_language = false;
				$export->category_orderby = false;
				$export->category_order = false;

				// Tag sorting
				$export->tag_language = false;
				$export->tag_orderby = false;
				$export->tag_order = false;

				// Brand sorting
				$export->brand_orderby = false;
				$export->brand_order = false;

				// Order sorting
				$export->order_dates_filter = false;
				$export->order_dates_from = '';
				$export->order_dates_to = '';
				$export->order_dates_filter_variable = false;
				$export->order_dates_filter_variable_length = false;
				$export->order_status = false;
				$export->order_customer = false;
				$export->order_billing_country = false;
				$export->order_shipping_country = false;
				$export->order_user_roles = false;
				$export->order_product = false;
				$export->order_coupons = false;
				$export->order_category = false;
				$export->order_tag = false;
				$export->order_brand = false;
				$export->order_ids = false;
				$export->order_payment = false;
				$export->order_shipping = false;
				$export->order_items = 'combined';
				$export->order_items_types = false;
				$export->order_orderby = false;
				$export->order_order = false;
				$export->max_order_items = false;

				// User sorting
				$export->user_orderby = false;
				$export->user_order = false;

				// Coupon sorting
				$export->coupon_discount_types = false;
				$export->coupon_orderby = false;
				$export->coupon_order = false;

				// Subscription sorting
				$export->subscription_status = false;
				$export->subscription_product = false;

				// Commission sorting
				$export->commission_dates_filter = false;
				$export->commission_dates_from = '';
				$export->commission_dates_to = '';
				$export->commission_dates_filter_variable = false;
				$export->commission_dates_filter_variable_length = false;
				$export->commission_product_vendors = false;
				$export->commission_status = false;
				$export->commission_orderby = false;
				$export->commission_order = false;

				// Shipping Class sorting
				$export->shipping_class_orderby = false;
				$export->shipping_class_order = false;

				if( !empty( $export->type ) ) {
					$export->fields = ( isset( $_POST[$export->type . '_fields'] ) ? array_map( 'sanitize_text_field', $_POST[$export->type . '_fields'] ) : false );
					$export->fields_order = ( isset( $_POST[$export->type . '_fields_order'] ) ? array_map( 'absint', $_POST[$export->type . '_fields_order'] ) : false );
					woo_ce_update_option( 'last_export', $export->type );
				}
				switch( $export->type ) {

					case 'product':
						// Set up dataset specific options
						$export->product_categories = ( isset( $_POST['product_filter_category'] ) ? woo_ce_format_product_filters( array_map( 'absint', $_POST['product_filter_category'] ) ) : false );
						$export->product_tags = ( isset( $_POST['product_filter_tag'] ) ? woo_ce_format_product_filters( array_map( 'absint', $_POST['product_filter_tag'] ) ) : false );
						$export->product_brands = ( isset( $_POST['product_filter_brand'] ) ? woo_ce_format_product_filters( array_map( 'absint', $_POST['product_filter_brand'] ) ) : false );
						$export->product_vendors = ( isset( $_POST['product_filter_vendor'] ) ? woo_ce_format_product_filters( array_map( 'absint', $_POST['product_filter_vendor'] ) ) : false );
						$export->product_status = ( isset( $_POST['product_filter_status'] ) ? woo_ce_format_product_filters( array_map( 'sanitize_text_field', $_POST['product_filter_status'] ) ) : false );
						$export->product_type = ( isset( $_POST['product_filter_type'] ) ? woo_ce_format_product_filters( array_map( 'sanitize_text_field', $_POST['product_filter_type'] ) ) : false );
						$export->product_stock = ( isset( $_POST['product_filter_stock'] ) ? sanitize_text_field( $_POST['product_filter_stock'] ) : false );
						$export->product_language = ( isset( $_POST['product_filter_language'] ) ? array_map( 'sanitize_text_field', $_POST['product_filter_language'] ) : false );
						$export->product_orderby = ( isset( $_POST['product_orderby'] ) ? sanitize_text_field( $_POST['product_orderby'] ) : false );
						$export->product_order = ( isset( $_POST['product_order'] ) ? sanitize_text_field( $_POST['product_order'] ) : false );
						$export->gallery_formatting = ( isset( $_POST['product_gallery_formatting'] ) ? absint( $_POST['product_gallery_formatting'] ) : false );
						$export->gallery_unique = ( isset( $_POST['product_gallery_unique'] ) ? absint( $_POST['product_gallery_unique'] ) : false );
						$export->upsell_formatting = ( isset( $_POST['product_upsell_formatting'] ) ? absint( $_POST['product_upsell_formatting'] ) : false );
						$export->crosssell_formatting = ( isset( $_POST['product_crosssell_formatting'] ) ? absint( $_POST['product_crosssell_formatting'] ) : false );
						$export->variation_formatting = ( isset( $_POST['variation_formatting'] ) ? absint( $_POST['variation_formatting'] ) : false );

						// Save dataset export specific options
						if( $export->product_orderby <> woo_ce_get_option( 'product_orderby' ) )
							woo_ce_update_option( 'product_orderby', $export->product_orderby );
						if( $export->product_order <> woo_ce_get_option( 'product_order' ) )
							woo_ce_update_option( 'product_order', $export->product_order );
						if( $export->upsell_formatting <> woo_ce_get_option( 'upsell_formatting' ) )
							woo_ce_update_option( 'upsell_formatting', $export->upsell_formatting );
						if( $export->crosssell_formatting <> woo_ce_get_option( 'crosssell_formatting' ) )
							woo_ce_update_option( 'crosssell_formatting', $export->crosssell_formatting );
						if( $export->variation_formatting <> woo_ce_get_option( 'variation_formatting' ) )
							woo_ce_update_option( 'variation_formatting', $export->variation_formatting );
						if( $export->gallery_formatting <> woo_ce_get_option( 'gallery_formatting' ) )
							woo_ce_update_option( 'gallery_formatting', $export->gallery_formatting );
						if( $export->gallery_unique <> woo_ce_get_option( 'gallery_unique' ) )
							woo_ce_update_option( 'gallery_unique', $export->gallery_unique );
						if( isset( $_POST['max_product_gallery'] ) ) {
							$export->max_product_gallery = absint( $_POST['max_product_gallery'] );
							if( $export->max_product_gallery <> woo_ce_get_option( 'max_product_gallery' ) )
								woo_ce_update_option( 'max_product_gallery', $export->max_product_gallery );
						}
						break;

					case 'category':
						// Set up dataset specific options
						$export->category_language = ( isset( $_POST['category_filter_language'] ) ? array_map( 'sanitize_text_field', $_POST['category_filter_language'] ) : false );
						$export->category_orderby = ( isset( $_POST['category_orderby'] ) ? sanitize_text_field( $_POST['category_orderby'] ) : false );
						$export->category_order = ( isset( $_POST['category_order'] ) ? sanitize_text_field( $_POST['category_order'] ) : false );

						// Save dataset export specific options
						if( $export->category_orderby <> woo_ce_get_option( 'category_orderby' ) )
							woo_ce_update_option( 'category_orderby', $export->category_orderby );
						if( $export->category_order <> woo_ce_get_option( 'category_order' ) )
							woo_ce_update_option( 'category_order', $export->category_order );
						break;

					case 'tag':
						// Set up dataset specific options
						$export->tag_language = ( isset( $_POST['tag_filter_language'] ) ? array_map( 'sanitize_text_field', $_POST['tag_filter_language'] ) : false );
						$export->tag_orderby = ( isset( $_POST['tag_orderby'] ) ? sanitize_text_field( $_POST['tag_orderby'] ) : false );
						$export->tag_order = ( isset( $_POST['tag_order'] ) ? sanitize_text_field( $_POST['tag_order'] ) : false );

						// Save dataset export specific options
						if( $export->tag_orderby <> woo_ce_get_option( 'tag_orderby' ) )
							woo_ce_update_option( 'tag_orderby', $export->tag_orderby );
						if( $export->tag_order <> woo_ce_get_option( 'tag_order' ) )
							woo_ce_update_option( 'tag_order', $export->tag_order );
						break;

					case 'brand':
						// Set up dataset specific options
						$export->brand_orderby = ( isset( $_POST['brand_orderby'] ) ? sanitize_text_field( $_POST['brand_orderby'] ) : false );
						$export->brand_order = ( isset( $_POST['brand_order'] ) ? sanitize_text_field( $_POST['brand_order'] ) : false );

						// Save dataset export specific options
						if( $export->brand_orderby <> woo_ce_get_option( 'brand_orderby' ) )
							woo_ce_update_option( 'brand_orderby', $export->brand_orderby );
						if( $export->brand_order <> woo_ce_get_option( 'brand_order' ) )
							woo_ce_update_option( 'brand_order', $export->brand_order );
						break;

					case 'order':
						// Set up dataset specific options
						$export->order_dates_filter = ( isset( $_POST['order_dates_filter'] ) ? sanitize_text_field( $_POST['order_dates_filter'] ) : false );
						$export->order_dates_from = sanitize_text_field( $_POST['order_dates_from'] );
						$export->order_dates_to = sanitize_text_field( $_POST['order_dates_to'] );
						$export->order_dates_filter_variable = ( isset( $_POST['order_dates_filter_variable'] ) ? absint( $_POST['order_dates_filter_variable'] ) : false );
						$export->order_dates_filter_variable_length = ( isset( $_POST['order_dates_filter_variable_length'] ) ? sanitize_text_field( $_POST['order_dates_filter_variable_length'] ) : false );
						$export->order_status = ( isset( $_POST['order_filter_status'] ) ? woo_ce_format_product_filters( array_map( 'sanitize_text_field', $_POST['order_filter_status'] ) ) : false );
						$export->order_customer = ( isset( $_POST['order_filter_customer'] ) ? array_map( 'absint', $_POST['order_filter_customer'] ) : false );
						$export->order_billing_country = ( isset( $_POST['order_filter_billing_country'] ) ? array_map( 'sanitize_text_field', $_POST['order_filter_billing_country'] ) : false );
						$export->order_shipping_country = ( isset( $_POST['order_filter_shipping_country'] ) ? array_map( 'sanitize_text_field', $_POST['order_filter_shipping_country'] ) : false );
						$export->order_user_roles = ( isset( $_POST['order_filter_user_role'] ) ? woo_ce_format_user_role_filters( array_map( 'sanitize_text_field', $_POST['order_filter_user_role'] ) ) : false );
						$export->order_coupons = ( isset( $_POST['order_filter_coupon'] ) ? woo_ce_format_product_filters( array_map( 'absint', $_POST['order_filter_coupon'] ) ) : false );
						$export->order_product = ( isset( $_POST['order_filter_product'] ) ? woo_ce_format_product_filters( array_map( 'sanitize_text_field', $_POST['order_filter_product'] ) ) : false );
						$export->order_category = ( isset( $_POST['order_filter_category'] ) ? woo_ce_format_product_filters( array_map( 'absint', $_POST['order_filter_category'] ) ) : false );
						$export->order_tag = ( isset( $_POST['order_filter_tag'] ) ? woo_ce_format_product_filters( array_map( 'absint', $_POST['order_filter_tag'] ) ) : false );
						$export->order_brand = ( isset( $_POST['order_filter_brand'] ) ? woo_ce_format_product_filters( array_map( 'absint', $_POST['order_filter_brand'] ) ) : false );
						$export->order_ids = ( isset( $_POST['order_filter_id'] ) ? sanitize_text_field( $_POST['order_filter_id'] ) : false );
						$export->order_payment = ( isset( $_POST['order_filter_payment_gateway'] ) ? array_map( 'sanitize_text_field', $_POST['order_filter_payment_gateway'] ) : false );
						$export->order_shipping = ( isset( $_POST['order_filter_shipping_method'] ) ? array_map( 'sanitize_text_field', $_POST['order_filter_shipping_method'] ) : false );
						$export->order_orderby = ( isset( $_POST['order_orderby'] ) ? sanitize_text_field( $_POST['order_orderby'] ) : false );
						$export->order_order = ( isset( $_POST['order_order'] ) ? sanitize_text_field( $_POST['order_order'] ) : false );

						// Save dataset export specific options
						if( isset( $_POST['order_items'] ) ) {
							$export->order_items = sanitize_text_field( $_POST['order_items'] );
							if( $export->order_items <> woo_ce_get_option( 'order_items_formatting' ) )
								woo_ce_update_option( 'order_items_formatting', $export->order_items );
						}
						if( isset( $_POST['order_items_types'] ) ) {
							$export->order_items_types = array_map( 'sanitize_text_field', $_POST['order_items_types'] );
							if( $export->order_items_types <> woo_ce_get_option( 'order_items_types' ) )
								woo_ce_update_option( 'order_items_types', $export->order_items_types );
						}
						if( isset( $_POST['max_order_items'] ) ) {
							$export->max_order_items = absint( $_POST['max_order_items'] );
							if( $export->max_order_items <> woo_ce_get_option( 'max_order_items' ) )
								woo_ce_update_option( 'max_order_items', $export->max_order_items );
						}
						if( $export->order_orderby <> woo_ce_get_option( 'order_orderby' ) )
							woo_ce_update_option( 'order_orderby', $export->order_orderby );
						if( $export->order_order <> woo_ce_get_option( 'order_order' ) )
							woo_ce_update_option( 'order_order', $export->order_order );
						break;

					case 'customer':
						// Set up dataset specific options

						// Save dataset export specific options
						$export->order_status = ( isset( $_POST['customer_filter_status'] ) ? woo_ce_format_product_filters( array_map( 'sanitize_text_field', $_POST['customer_filter_status'] ) ) : false );
						$export->order_user_roles = ( isset( $_POST['customer_filter_user_role'] ) ? woo_ce_format_user_role_filters( array_map( 'sanitize_text_field', $_POST['customer_filter_user_role'] ) ) : false );
						break;

					case 'user':
						// Set up dataset specific options
						$export->user_orderby = ( isset( $_POST['user_orderby'] ) ? sanitize_text_field( $_POST['user_orderby'] ) : false );
						$export->user_order = ( isset( $_POST['user_order'] ) ? sanitize_text_field( $_POST['user_order'] ) : false );

						// Save dataset export specific options
						if( $export->user_orderby <> woo_ce_get_option( 'user_orderby' ) )
							woo_ce_update_option( 'user_orderby', $export->user_orderby );
						if( $export->user_order <> woo_ce_get_option( 'user_order' ) )
							woo_ce_update_option( 'user_order', $export->user_order );
						break;

					case 'coupon':
						// Set up dataset specific options
						$export->coupon_discount_types = ( isset( $_POST['coupon_filter_discount_type'] ) ? woo_ce_format_product_filters( array_map( 'sanitize_text_field', $_POST['coupon_filter_discount_type'] ) ) : false );
						$export->coupon_orderby = ( isset( $_POST['coupon_orderby'] ) ? sanitize_text_field( $_POST['coupon_orderby'] ) : false );
						$export->coupon_order = ( isset( $_POST['coupon_order'] ) ? sanitize_text_field( $_POST['coupon_order'] ) : false );

						// Save dataset export specific options
						if( $export->coupon_orderby <> woo_ce_get_option( 'coupon_orderby' ) )
							woo_ce_update_option( 'coupon_orderby', $export->coupon_orderby );
						if( $export->coupon_order <> woo_ce_get_option( 'coupon_order' ) )
							woo_ce_update_option( 'coupon_order', $export->coupon_order );
						break;

					case 'subscription':
						// Set up dataset specific options

						// Save dataset export specific options
						$export->subscription_status = ( isset( $_POST['subscription_filter_status'] ) ? woo_ce_format_product_filters( array_map( 'sanitize_text_field', $_POST['subscription_filter_status'] ) ) : false );
						$export->subscription_product = ( isset( $_POST['subscription_filter_product'] ) ? woo_ce_format_product_filters( array_map( 'absint', $_POST['subscription_filter_product'] ) ) : false );
						break;

					case 'attribute':
						break;

					case 'product_vendor':
						break;

					case 'commission':
						$export->commission_dates_filter = ( isset( $_POST['commission_dates_filter'] ) ? sanitize_text_field( $_POST['commission_dates_filter'] ) : false );
						$export->commission_dates_from = sanitize_text_field( $_POST['commission_dates_from'] );
						$export->commission_dates_to = sanitize_text_field( $_POST['commission_dates_to'] );
						$export->commission_dates_filter_variable = ( isset( $_POST['commission_dates_filter_variable'] ) ? absint( $_POST['commission_dates_filter_variable'] ) : false );
						$export->commission_dates_filter_variable_length = ( isset( $_POST['commission_dates_filter_variable_length'] ) ? sanitize_text_field( $_POST['commission_dates_filter_variable_length'] ) : false );
						$export->commission_product_vendors = ( isset( $_POST['commission_filter_product_vendor'] ) ? woo_ce_format_product_filters( array_map( 'absint', $_POST['commission_filter_product_vendor'] ) ) : false );
						$export->commission_status = ( isset( $_POST['commission_filter_commission_status'] ) ? woo_ce_format_product_filters( array_map( 'sanitize_text_field', $_POST['commission_filter_commission_status'] ) ) : false );
						$export->commission_orderby = ( isset( $_POST['commission_orderby'] ) ? sanitize_text_field( $_POST['commission_orderby'] ) : false );
						$export->commission_order = ( isset( $_POST['commission_order'] ) ? sanitize_text_field( $_POST['commission_order'] ) : false );

						// Save dataset export specific options
						if( $export->commission_orderby <> woo_ce_get_option( 'commission_orderby' ) )
							woo_ce_update_option( 'commission_orderby', $export->commission_orderby );
						if( $export->commission_order <> woo_ce_get_option( 'commission_order' ) )
							woo_ce_update_option( 'commission_order', $export->commission_order );
						break;

					case 'shipping_class':
						// Set up dataset specific options
						$export->shipping_class_orderby = ( isset( $_POST['shipping_class_orderby'] ) ? sanitize_text_field( $_POST['shipping_class_orderby'] ) : false );
						$export->shipping_class_order = ( isset( $_POST['shipping_class_order'] ) ? sanitize_text_field( $_POST['shipping_class_order'] ) : false );

						// Save dataset export specific options
						if( $export->shipping_class_orderby <> woo_ce_get_option( 'shipping_class_orderby' ) )
							woo_ce_update_option( 'shipping_class_orderby', $export->shipping_class_orderby );
						if( $export->shipping_class_order <> woo_ce_get_option( 'shipping_class_order' ) )
							woo_ce_update_option( 'shipping_class_order', $export->shipping_class_order );
						break;

				}
				if( $export->type ) {

					$timeout = 600;
					if( isset( $_POST['timeout'] ) ) {
						$timeout = absint( $_POST['timeout'] );
						if( $timeout <> woo_ce_get_option( 'timeout' ) )
							woo_ce_update_option( 'timeout', $timeout );
					}
					if( !ini_get( 'safe_mode' ) )
						@set_time_limit( $timeout );

					@ini_set( 'memory_limit', WP_MAX_MEMORY_LIMIT );
					@ini_set( 'max_execution_time', $timeout );

					$export->args = array(
						'limit_volume' => $export->limit_volume,
						'offset' => $export->offset,
						'encoding' => $export->encoding,
						'date_format' => $export->date_format,
						'product_categories' => $export->product_categories,
						'product_tags' => $export->product_tags,
						'product_brands' => $export->product_brands,
						'product_vendors' => $export->product_vendors,
						'product_status' => $export->product_status,
						'product_type' => $export->product_type,
						'product_stock' => $export->product_stock,
						'product_language' => $export->product_language,
						'product_orderby' => $export->product_orderby,
						'product_order' => $export->product_order,
						'category_language' => $export->category_language,
						'category_orderby' => $export->category_orderby,
						'category_order' => $export->category_order,
						'tag_language' => $export->tag_language,
						'tag_orderby' => $export->tag_orderby,
						'tag_order' => $export->tag_order,
						'brand_orderby' => $export->brand_orderby,
						'brand_order' => $export->brand_order,
						'order_status' => $export->order_status,
						'order_dates_filter' => $export->order_dates_filter,
						'order_dates_from' => woo_ce_format_order_date( $export->order_dates_from ),
						'order_dates_to' => woo_ce_format_order_date( $export->order_dates_to ),
						'order_dates_filter_variable' => $export->order_dates_filter_variable,
						'order_dates_filter_variable_length' => $export->order_dates_filter_variable_length,
						'order_customer' => $export->order_customer,
						'order_billing_country' => $export->order_billing_country,
						'order_shipping_country' => $export->order_shipping_country,
						'order_user_roles' => $export->order_user_roles,
						'order_coupons' => $export->order_coupons,
						'order_product' => $export->order_product,
						'order_category' => $export->order_category,
						'order_tag' => $export->order_tag,
						'order_brand' => $export->order_brand,
						'order_ids' => $export->order_ids,
						'order_payment' => $export->order_payment,
						'order_shipping' => $export->order_shipping,
						'order_items' => $export->order_items,
						'order_items_types' => $export->order_items_types,
						'order_orderby' => $export->order_orderby,
						'order_order' => $export->order_order,
						'user_orderby' => $export->user_orderby,
						'user_order' => $export->user_order,
						'coupon_discount_types' => $export->coupon_discount_types,
						'coupon_orderby' => $export->coupon_orderby,
						'coupon_order' => $export->coupon_order,
						'subscription_status' => $export->subscription_status,
						'subscription_product' => $export->subscription_product,
						'commission_dates_filter' => $export->commission_dates_filter,
						'commission_dates_from' => woo_ce_format_order_date( $export->commission_dates_from ),
						'commission_dates_to' => woo_ce_format_order_date( $export->commission_dates_to ),
						'commission_dates_filter_variable' => $export->commission_dates_filter_variable,
						'commission_dates_filter_variable_length' => $export->commission_dates_filter_variable_length,
						'commission_product_vendors' => $export->commission_product_vendors,
						'commission_status' => $export->commission_status,
						'commission_orderby' => $export->commission_orderby,
						'commission_order' => $export->commission_order,
						'shipping_class_orderby' => $export->shipping_class_orderby,
						'shipping_class_order' => $export->shipping_class_order
					);

					if( empty( $export->fields ) ) {
						$message = __( 'No export fields were selected, please try again with at least a single export field.', 'woo_ce' );
						woo_cd_admin_notice( $message, 'error' );
						return;
					}
					woo_ce_save_fields( $export->type, $export->fields, $export->fields_order );
					unset( $export->fields_order );

					$export->filename = woo_ce_generate_filename( $export->type );

					$export->idle_memory_end = woo_ce_current_memory_usage();
					$export->end_time = time();

					// Let's spin up PHPExcel for supported Export Types and Export Formats
					if( in_array( $export->export_format, array( 'csv', 'xls', 'xlsx' ) ) ) {

						$dataset = woo_ce_export_dataset( $export->type );
						if( empty( $dataset ) ) {
							$message = __( 'No export entries were found, please try again with different export filters.', 'woo_ce' );
							woo_cd_admin_notice( $message, 'error' );
							return;
						}

						// Load up the fatal error notice if we 500, timeout or encounter a fatal PHP error
						add_action( 'shutdown', 'woo_ce_fatal_error' );

						// Check that PHPExcel is where we think it is
						if( file_exists( WOO_CD_PATH . 'classes/PHPExcel.php' ) ) {
							// Check if PHPExcel has already been loaded
							if( !class_exists( 'PHPExcel' ) ) {
								include_once( WOO_CD_PATH . 'classes/PHPExcel.php' );
							} else {
								$message = sprintf( __( 'The PHPExcel library was already loaded by another WordPress Plugin, if there\'s issues with your export file you know where to look. <a href="%s" target="_blank">Need help?</a>', 'woo_ce' ), $troubleshooting_url );
								woo_cd_admin_notice( $message, 'error' );
							}
						} else {
							$message = sprintf( __( 'We couldn\'t load the PHPExcel library <code>%s</code> within <code>%s</code>, this file should be present. <a href="%s" target="_blank">Need help?</a>', 'woo_ce' ), 'PHPExcel.php', WOO_CD_PATH . 'classes/...', $troubleshooting_url );
							woo_cd_admin_notice( $message, 'error' );
							return;
						}

						$excel = new PHPExcel();
						$excel->setActiveSheetIndex( 0 );
						$excel->getActiveSheet()->setTitle( ucfirst( $export->type ) );

						$row = 1;
						// Skip headers if Heading Formatting is turned off
						if( $export->header_formatting ) {
							$col = 0;
							foreach( $export->columns as $column ) {
								$excel->getActiveSheet()->setCellValueByColumnAndRow( $col, $row, $column );
								$excel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->getStyle()->getFont()->setBold( true );
								$excel->getActiveSheet()->getColumnDimensionByColumn( $col )->setAutoSize( true );
								$col++;
							}
							$row = 2;
						}
						$col = 0;
						foreach( $dataset as $data ) {
							$col = 0;
							foreach( array_keys( $export->fields ) as $field ) {
								$excel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->getStyle()->getFont()->setBold( false );
								if( $export->encoding == 'UTF-8' ) {
									if( woo_ce_detect_value_string( ( isset( $data->$field ) ? $data->$field : null ) ) ) {
										// Treat this cell as a string
										$excel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->setValueExplicit( ( isset( $data->$field ) ? wp_specialchars_decode( $data->$field ) : '' ), PHPExcel_Cell_DataType::TYPE_STRING );
									} else {
										$excel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->setValue( ( isset( $data->$field ) ? wp_specialchars_decode( $data->$field ) : '' ) );
									}
								} else {
									// PHPExcel only deals with UTF-8 regardless of encoding type
									if( woo_ce_detect_value_string( ( isset( $data->$field ) ? $data->$field : null ) ) ) {
										// Treat this cell as a string
										$excel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->setValueExplicit( ( isset( $data->$field ) ? utf8_encode( wp_specialchars_decode( $data->$field ) ) : '' ), PHPExcel_Cell_DataType::TYPE_STRING );
									} else {
										$excel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->setValue( ( isset( $data->$field ) ? utf8_encode( wp_specialchars_decode( $data->$field ) ) : '' ) );
									}
								}
								$col++;
							}
							$row++;
						}
						// Override the export format to CSV if debug mode is enabled
						if( WOO_CD_DEBUG )
							$export->export_format = 'csv';
						switch( $export->export_format ) {

							case 'csv':
								woo_cd_load_phpexcel_sed_csv_writer();
								$php_excel_format = 'SED_CSV';
								$file_extension = 'csv';
								$post_mime_type = 'text/csv';
								break;

							case 'xls':
								$php_excel_format = 'Excel5';
								$file_extension = 'xls';
								$post_mime_type = 'application/vnd.ms-excel';
								break;

							case 'xlsx':
								$php_excel_format = 'Excel2007';
								$file_extension = 'xlsx';
								$post_mime_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
								break;

						}
						$export->filename = $export->filename . '.' . $file_extension;
						$objWriter = PHPExcel_IOFactory::createWriter( $excel, $php_excel_format );

						// Only write headers if we're not in debug mode
						if( WOO_CD_DEBUG !== true ) {

							// Print to browser
							woo_ce_generate_file_headers( $post_mime_type );
							switch( $export->export_format ) {
	
								case 'csv':
									$objWriter->setUseBOM( true );
									// Check if we're using a non-standard delimiter
									if( $export->delimiter != ',' )
										$objWriter->setDelimiter( $export->delimiter );
									break;

								case 'xlsx':
									$objWriter->setPreCalculateFormulas( false );
									break;

							}
							// Print directly to browser, do not save
							if( $export->delete_file ) {
								// The end memory usage and time is collected at the very last opportunity prior to the file header being rendered to the screen
								woo_ce_update_file_detail( $post_ID, '_woo_idle_memory_end', woo_ce_current_memory_usage() );
								woo_ce_update_file_detail( $post_ID, '_woo_end_time', time() );
								delete_option( WOO_CD_PREFIX . '_exported' );
								$objWriter->save( 'php://output' );
							} else {
								// Save to file and insert to WordPress Media
								$temp_filename = tempnam( apply_filters( 'woo_ce_sys_get_temp_dir', sys_get_temp_dir() ), 'tmp' );
								// Check if we were given a temporary filename
								if( $temp_filename == false ) {
									$message = sprintf( __( 'We could not create a temporary export file in <code>%s</code>, ensure that WordPress can read and write files here and try again.', 'woo_ce' ), apply_filters( 'woo_ce_sys_get_temp_dir', sys_get_temp_dir() ) );
									woo_cd_admin_notice( $message, 'error' );
									wp_redirect( esc_url( add_query_arg( array( 'failed' => true, 'message' => urlencode( $message ) ) ) ) );
									exit();
								} else {
									$objWriter->save( $temp_filename );
									$bits = file_get_contents( $temp_filename );
								}
								unlink( $temp_filename );

								$post_ID = woo_ce_save_file_attachment( $export->filename, $post_mime_type );
								$upload = wp_upload_bits( $export->filename, null, $bits );
								// Check if the upload succeeded otherwise delete Post and return error notice
								if( ( $post_ID == false ) || $upload['error'] ) {
									wp_delete_attachment( $post_ID, true );
									if( isset( $upload['error'] ) )
										wp_redirect( esc_url( add_query_arg( array( 'failed' => true, 'message' => urlencode( $upload['error'] ) ) ) ) );
									else
										wp_redirect( esc_url( add_query_arg( array( 'failed' => true ) ) ) );
									return;
								}
								if( file_exists( ABSPATH . 'wp-admin/includes/image.php' ) ) {
									$attach_data = wp_generate_attachment_metadata( $post_ID, $upload['file'] );
									wp_update_attachment_metadata( $post_ID, $attach_data );
									update_attached_file( $post_ID, $upload['file'] );
									if( !empty( $post_ID ) ) {
										woo_ce_save_file_guid( $post_ID, $export->type, $upload['url'] );
										woo_ce_save_file_details( $post_ID );
									}
								} else {
									error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, __( 'Could not load image.php within /wp-admin/includes/image.php', 'woo_ce' ) ) );
								}
								// The end memory usage and time is collected at the very last opportunity prior to the file header being rendered to the screen
								woo_ce_update_file_detail( $post_ID, '_woo_idle_memory_end', woo_ce_current_memory_usage() );
								woo_ce_update_file_detail( $post_ID, '_woo_end_time', time() );
								delete_option( WOO_CD_PREFIX . '_exported' );
								$objWriter->save( 'php://output' );

							}

							// Clean up PHPExcel
							$excel->disconnectWorksheets();
							unset( $objWriter, $excel );
							exit();

						} else {

							// Save to temporary file then dump into export log screen
							$objWriter->setUseBOM( true );
							$temp_filename = tempnam( apply_filters( 'woo_ce_sys_get_temp_dir', sys_get_temp_dir() ), 'tmp' );
							// Check if we were given a temporary filename
							if( $temp_filename == false ) {
								$message = sprintf( __( 'We could not create a temporary export file in <code>%s</code>, ensure that WordPress can read and write files here and try again.', 'woo_ce' ), apply_filters( 'woo_ce_sys_get_temp_dir', sys_get_temp_dir() ) );
								woo_cd_admin_notice( $message, 'error' );
							} else {
								$objWriter->save( $temp_filename );
								$bits = file_get_contents( $temp_filename );
							}
							unlink( $temp_filename );

							// Clean up PHPExcel
							$excel->disconnectWorksheets();
							unset( $objWriter, $excel );

							// Save the export contents to the WordPress Transient
							$response = set_transient( WOO_CD_PREFIX . '_debug_log', base64_encode( $bits ), woo_ce_get_option( 'timeout', MINUTE_IN_SECONDS ) );
							if( $response !== true ) {
								$message = __( 'The export contents were too large to store in a single WordPress transient, use the Volume offset / Limit volume options to reduce the size of your export and try again.', 'woo_ce' ) . ' (<a href="' . $troubleshooting_url . '" target="_blank">' . __( 'Need help?', 'woo_ce' ) . '</a>)';
								woo_cd_admin_notice( $message, 'error' );
							}

						}

						// Remove our fatal error notice to play nice with other Plugins
						remove_action( 'shutdown', 'woo_ce_fatal_error' );

					// Run the default engine for the XML and RSS export formats
					} else if( in_array( $export->export_format, array( 'xml', 'rss' ) ) ) {

						// Check if SimpleXMLElement is present
						if( !class_exists( 'SED_SimpleXMLElement' ) ) {
							$message = sprintf( __( 'We couldn\'t load the SimpleXMLElement class, the SimpleXMLElement class is required for XML and RSS feed generation. <a href="%s" target="_blank">Need help?</a>', 'woo_ce' ), $troubleshooting_url );
							woo_cd_admin_notice( $message, 'error' );
							return;
						}

						switch( $export->export_format ) {

							case 'xml':
								$file_extension = 'xml';
								$post_mime_type = 'application/xml';
								break;

							case 'rss':
								$file_extension = 'xml';
								$post_mime_type = 'application/rss+xml';
								break;

						}
						$export->filename = $export->filename . '.' . $file_extension;

						if( $export->export_format == 'xml' ) {
							$xml = new SED_SimpleXMLElement( sprintf( apply_filters( 'woo_ce_export_xml_first_line', '<?xml version="1.0" encoding="%s"?><%s/>' ), esc_attr( $export->encoding ), esc_attr( apply_filters( 'woo_ce_export_xml_store_node', 'store' ) ) ) );
							if( woo_ce_get_option( 'xml_attribute_url', 1 ) )
								$xml->addAttribute( 'url', get_site_url() );
							if( woo_ce_get_option( 'xml_attribute_date', 1 ) )
								$xml->addAttribute( 'date', date( 'Y-m-d' ) );
							if( woo_ce_get_option( 'xml_attribute_time', 0 ) )
								$xml->addAttribute( 'time', date( 'H:i:s' ) );
							if( woo_ce_get_option( 'xml_attribute_title', 1 ) )
								$xml->addAttribute( 'name', htmlspecialchars( get_bloginfo( 'name' ) ) );
							if( woo_ce_get_option( 'xml_attribute_export', 1 ) )
								$xml->addAttribute( 'export', htmlspecialchars( $export->type ) );
							if( woo_ce_get_option( 'xml_attribute_orderby', 1 ) && isset( $export->{$export->type . '_orderby'} ) )
								$xml->addAttribute( 'orderby', $export->{$export->type . '_orderby'} );
							if( woo_ce_get_option( 'xml_attribute_order', 1 ) && isset( $export->{$export->type . '_order'} ) )
								$xml->addAttribute( 'order', $export->{$export->type . '_order'} );
							if( woo_ce_get_option( 'xml_attribute_limit', 1 ) )
								$xml->addAttribute( 'limit', $export->limit_volume );
							if( woo_ce_get_option( 'xml_attribute_offset', 1 ) )
								$xml->addAttribute( 'offset', $export->offset );
							$bits = woo_ce_export_dataset( $export->type, $xml );
						} else if( $export->export_format == 'rss' ) {
							$xml = new SED_SimpleXMLElement( sprintf( apply_filters( 'woo_ce_export_rss_first_line', '<?xml version="1.0" encoding="%s"?><rss version="2.0"%s/>' ), esc_attr( $export->encoding ), ' xmlns:g="http://base.google.com/ns/1.0"' ) );
							$child = $xml->addChild( apply_filters( 'woo_ce_export_rss_channel_node', 'channel' ) );
							$child->addChild( 'title', woo_ce_get_option( 'rss_title', '' ) );
							$child->addChild( 'link', woo_ce_get_option( 'rss_link', '' ) );
							$child->addChild( 'description', woo_ce_get_option( 'rss_description', '' ) );
							$bits = woo_ce_export_dataset( $export->type, $child );
						}

						if( empty( $bits ) ) {
							$message = __( 'No export entries were found, please try again with different export filters.', 'woo_ce' );
							woo_cd_admin_notice( $message, 'error' );
							return;
						}

						if( WOO_CD_DEBUG !== true ) {
							if( $export->delete_file ) {

								// Print directly to browser
								woo_ce_generate_file_headers( $post_mime_type );
								if( $bits = woo_ce_format_xml( $bits ) )
									echo $bits;
								exit();

							} else {

								// Save to file and insert to WordPress Media
								if( $export->filename && $bits ) {
									$post_ID = woo_ce_save_file_attachment( $export->filename, $post_mime_type );
									$bits = woo_ce_format_xml( $bits );
									$upload = wp_upload_bits( $export->filename, null, $bits );
									// Check for issues saving to WordPress Media
									if( ( $post_ID == false ) || !empty( $upload['error'] ) ) {
										wp_delete_attachment( $post_ID, true );
										if( isset( $upload['error'] ) )
											wp_redirect( esc_url( add_query_arg( array( 'failed' => true, 'message' => urlencode( $upload['error'] ) ) ) ) );
										else
											wp_redirect( esc_url( add_query_arg( array( 'failed' => true ) ) ) );
										return;
									}
									$attach_data = wp_generate_attachment_metadata( $post_ID, $upload['file'] );
									wp_update_attachment_metadata( $post_ID, $attach_data );
									update_attached_file( $post_ID, $upload['file'] );
									if( $post_ID ) {
										woo_ce_save_file_guid( $post_ID, $export->type, $upload['url'] );
										woo_ce_save_file_details( $post_ID );
									}
									$export_type = $export->type;
									unset( $export );

									// The end memory usage and time is collected at the very last opportunity prior to the XML header being rendered to the screen
									woo_ce_update_file_detail( $post_ID, '_woo_idle_memory_end', woo_ce_current_memory_usage() );
									woo_ce_update_file_detail( $post_ID, '_woo_end_time', time() );
									delete_option( WOO_CD_PREFIX . '_exported' );

									// Generate XML header
									woo_ce_generate_file_headers( $post_mime_type );
									unset( $export_type );

									// Print file contents to screen
									if( !empty( $upload['file'] ) ) {
										// Check if readfile() is disabled on this host
										$disabled = explode( ',', ini_get( 'disable_functions' ) );
										if( !in_array( 'readfile', $disabled ) ) {
											readfile( $upload['file'] );
										} else {
											// Workaround for disabled readfile on some hosts
											$fp = fopen( $upload['file'], 'rb' );
											fpassthru( $fp );
											fclose( $fp );
											unset( $fp );
										}
										unset( $disabled );
									} else {
										wp_redirect( esc_url( add_query_arg( 'failed', true ) ) );
									}
									unset( $upload );
								} else {
									wp_redirect( esc_url( add_query_arg( 'failed', true ) ) );
								}
								exit();

							}
						}

					}

				}
				break;

			// Save changes on Settings screen
			case 'save-settings':
				woo_ce_admin_save_settings();
				break;

			// Save changes on Field Editor screen
			case 'save-fields':
				$fields = ( isset( $_POST['fields'] ) ? array_filter( $_POST['fields'] ) : array() );
				$hidden = ( isset( $_POST['hidden'] ) ? array_filter( $_POST['hidden'] ) : array() );
				$export_type = ( isset( $_POST['type'] ) ? sanitize_text_field( $_POST['type'] ) : '' );
				$types = array_keys( woo_ce_return_export_types() );
				// Check we are saving against a valid export type
				if( in_array( $export_type, $types ) ) {
					woo_ce_update_option( $export_type . '_labels', $fields );
					woo_ce_update_option( $export_type . '_hidden', $hidden );
					$message = __( 'Changes have been saved.', 'woo_ce' );
					woo_cd_admin_notice( $message );
				} else {
					$message = __( 'Changes could not be saved as we could not detect a valid export type. Raise this as a Premium Support issue and include what export type you were editing.', 'woo_ce' );
					woo_cd_admin_notice( $message, 'error' );
				}
				break;

		}

	}
Esempio n. 13
0
function woo_ce_cron_export( $gui = '', $type = '', $is_scheduled = false ) {

	global $export;

	$export = new stdClass;
	$export->cron = ( $is_scheduled ? 0 : 1 );
	$export->scheduled_export = ( $is_scheduled ? 1 : 0 );
	$export->start_time = time();
	$export->idle_memory_start = woo_ce_current_memory_usage();
	$export->error = '';

	$bits = '';
	$type = ( isset( $_GET['type'] ) ? $_GET['type'] : $type );
	if( empty( $type ) ) {
		if( $gui == 'gui' ) {
			$output = sprintf( '<p>%s</p>', __( 'No export type was provided.', 'woo_ce' ) );
		} else {
			error_log( sprintf( '[store-exporter-deluxe] -: Error: %s', __( 'No export type was provided', 'woo_ce' ) ) );
			return false;
		}
	} else {
		$types = array_keys( woo_ce_return_export_types() );
		$export->type = $type;
		// Check that export is in the list of available exports
		if( !in_array( $export->type, $types ) ) {
			if( $gui == 'gui' ) {
				$output = '<p>' . __( 'An invalid export type was provided.', 'woo_ce' ) . '</p>';
			} else {
				error_log( sprintf( '[store-exporter-deluxe] -: Error: %s', __( 'An invalid export type was provided', 'woo_ce' ) ) );
				return false;
			}
		} else {
			$export->export_format = ( isset( $_GET['format'] ) ? sanitize_text_field( $_GET['format'] ) : woo_ce_get_option( 'export_format', 'csv' ) );

			// Override the export format if outputting to screen in friendly design
			if( $gui == 'gui' && in_array( $export->export_format, array( 'csv', 'xls', 'xlsx' ) ) )
				$export->export_format = 'csv';

			// Override the export format if this is a scheduled export
			if( $export->scheduled_export )
				$export->export_format = woo_ce_get_option( 'auto_format', 'csv' );

			// Override the export format if the single order Transient is set
			$single_export_format = get_transient( WOO_CD_PREFIX . '_single_export_format' );
			if( $single_export_format !== false )
				$export->export_format = $single_export_format;
			unset( $single_export_format );

			$export->delimiter = ( isset( $_GET['delimiter'] ) ? sanitize_text_field( $_GET['delimiter'] ) : woo_ce_get_option( 'delimiter', ',' ) );
			if( $export->delimiter == '' || $export->delimiter == false ) {
				error_log( '[store-exporter-deluxe] Warning: Delimiter export option was corrupted, defaulted to ,' );
				$export->delimiter = ',';
				woo_ce_update_option( 'delimiter', ',' );
			} else if( $export->delimiter == 'TAB' ) {
				$export->delimiter = "\t";
			}
			$export->category_separator = ( isset( $_GET['category_separator'] ) ? sanitize_text_field( $_GET['category_separator'] ) : woo_ce_get_option( 'category_separator', '|' ) );
			// Override for line break (LF) support in Category Separator
			if( $export->category_separator == 'LF' )
				$export->category_separator = "\n";
			$export->bom = ( isset( $_GET['bom'] ) ? absint( $_GET['bom'] ) : woo_ce_get_option( 'bom', 1 ) );
			$export->encoding = ( isset( $_GET['encoding'] ) ? sanitize_text_field( $_GET['encoding'] ) : woo_ce_get_option( 'encoding', 'UTF-8' ) );
			$export->timeout = woo_ce_get_option( 'timeout', 600 );
			$export->escape_formatting = ( isset( $_GET['escape_formatting'] ) ? sanitize_text_field( $_GET['escape_formatting'] ) : woo_ce_get_option( 'escape_formatting', 'all' ) );
			$export->header_formatting = ( isset( $_GET['header_formatting'] ) ? absint( $_GET['header_formatting'] ) : woo_ce_get_option( 'header_formatting', 1 ) );
			$export->date_format = woo_ce_get_option( 'date_format', 'd/m/Y' );
			$export->order_items = ( isset( $_GET['order_items'] ) ? sanitize_text_field( $_GET['order_items'] ) : woo_ce_get_option( 'order_items_formatting', 'unique' ) );
			$export->order_items_types = ( isset( $_GET['order_items_types'] ) ? sanitize_text_field( $_GET['order_items_types'] ) : woo_ce_get_option( 'order_items_types', false ) );
			$export->upsell_formatting = woo_ce_get_option( 'upsell_formatting', 1 );
			$export->crosssell_formatting = woo_ce_get_option( 'crosssell_formatting', 1 );
			$export->gallery_formatting = woo_ce_get_option( 'gallery_formatting', 0 );
			$export->gallery_unique = woo_ce_get_option( 'gallery_unique', 0 );
			$export->max_product_gallery = woo_ce_get_option( 'max_product_gallery', 3 );
			$export->filename = woo_ce_generate_filename( $export->type );
			switch( $export->export_format ) {

				case 'csv':
					$php_excel_format = 'SED_CSV';
					$file_extension = 'csv';
					$post_mime_type = 'text/csv';
					break;

				case 'xls':
					$php_excel_format = 'Excel5';
					$file_extension = 'xls';
					$post_mime_type = 'application/vnd.ms-excel';
					break;

				case 'xlsx':
					$php_excel_format = 'Excel2007';
					$file_extension = 'xlsx';
					$post_mime_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
					break;

				case 'xml':
					$file_extension = 'xml';
					$post_mime_type = 'application/xml';
					break;

				case 'rss':
					$file_extension = 'xml';
					$post_mime_type = 'application/rss+xml';
					break;

				default:
					error_log( sprintf( '[store-exporter-deluxe] -: Warning: %s', __( 'An invalid export format was provided', 'woo_ce' ) ) );
					return;
					break;

			}
			$export->filename = $export->filename . '.' . $file_extension;
			$export->limit_volume = ( isset( $_GET['limit'] ) ? absint( $_GET['limit'] ) : -1 );
			$export->offset = ( isset( $_GET['offset'] ) ? absint( $_GET['offset'] ) : 0 );
			// Select all export fields for CRON export
			$export->fields = woo_ce_cron_export_fields( $export->type, $export->scheduled_export );
			// Grab to value if response is e-mail or remote POST
			if( in_array( $gui, array( 'email', 'post' ) ) ) {
				if( $gui == 'email' )
					$export->to = ( isset( $_GET['to'] ) ? sanitize_email( $_GET['to'] ) : woo_ce_get_option( 'email_to', '' ) );
				else if( $gui == 'post' )
					$export->to = ( isset( $_GET['to'] ) ? esc_url_raw( $_GET['to'] ) : woo_ce_get_option( 'post_to', '' ) );
			}
			$export = woo_ce_check_cron_export_arguments( $export );

			$export->args = array(
				'limit_volume' => $export->limit_volume,
				'offset' => $export->offset,
				'encoding' => $export->encoding,
				'date_format' => $export->date_format,
				'order_items' => $export->order_items,
				'order_items_types' => $export->order_items_types
			);

			$orderby = ( isset( $_GET['orderby'] ) ? sanitize_text_field( $_GET['orderby'] ) : null );
			$order = ( isset( $_GET['order'] ) ? sanitize_text_field( $_GET['order'] ) : null );
			switch( $export->type ) {

				case 'product':
					$export->args['product_orderby'] = $orderby;
					$export->args['product_order'] = $order;
					if( $export->scheduled_export ) {
						$product_filter_type = woo_ce_get_option( 'auto_product_type', false );
						$product_filter_status = woo_ce_get_option( 'auto_product_status', false );
						$product_filter_stock = woo_ce_get_option( 'auto_product_stock', false );
						$product_filter_category = woo_ce_get_option( 'auto_product_category', false );
						$product_filter_tag = woo_ce_get_option( 'auto_product_tag', false );
						$export->args['product_type'] = ( !empty( $product_filter_type ) ? $product_filter_type : false );
						$export->args['product_status'] = ( !empty( $product_filter_status ) ? $product_filter_status : false );
						$export->args['product_stock'] = ( !empty( $product_filter_stock ) ? $product_filter_stock : false );
						$export->args['product_categories'] = ( !empty( $product_filter_category ) ? $product_filter_category : false );
						$export->args['product_tags'] = ( !empty( $product_filter_tag ) ? $product_filter_tag : false );
					} else {
						$export->args['product_status'] = ( isset( $_GET['product_status'] ) ? sanitize_text_field( $_GET['product_status'] ) : null );
						$export->args['product_stock'] = ( isset( $_GET['stock_status'] ) ? sanitize_text_field( $_GET['stock_status'] ) : null );
					}
					break;

				case 'category':
					$export->args['category_orderby'] = $orderby;
					$export->args['category_order'] = $order;
					break;

				case 'tag':
					$export->args['tag_orderby'] = $orderby;
					$export->args['tag_order'] = $order;
					break;

				case 'order':
					$export->args['order_orderby'] = $orderby;
					$export->args['order_order'] = $order;
					$export->args['order_ids'] = ( isset( $_GET['order_ids'] ) ? sanitize_text_field( $_GET['order_ids'] ) : null );

					// Override Filter Orders by Order ID if a single order transient is set
					$single_export_order_ids = get_transient( WOO_CD_PREFIX . '_single_export_order_ids' );
					if( $single_export_order_ids !== false )
						$export->args['order_ids'] = sanitize_text_field( $single_export_order_ids );
					unset( $single_export_order_ids );

					if( $export->scheduled_export ) {

						// Scheduled export engine

						// Order Status
						$order_filter_status = woo_ce_get_option( 'auto_order_status', '' );
						$export->args['order_status'] = ( !empty( $order_filter_status ) ? (array)$order_filter_status : array() );
						// Order Date
						$order_dates_filter = woo_ce_get_option( 'auto_order_date', false );
						if( $order_dates_filter ) {
							$export->args['order_dates_filter'] = $order_dates_filter;
							switch( $order_dates_filter ) {

								case 'manual':
									$order_filter_dates_from = woo_ce_get_option( 'auto_order_dates_from', false );
									$order_filter_dates_to = woo_ce_get_option( 'auto_order_dates_to', false );
									$export->args['order_dates_from'] = ( !empty( $order_filter_dates_from ) ? sanitize_text_field( $order_filter_dates_from ) : false );
									$export->args['order_dates_to'] = ( !empty( $order_filter_dates_to ) ? sanitize_text_field( $order_filter_dates_to ) : false );
									break;

								case 'variable':
									$order_filter_date_variable = woo_ce_get_option( 'auto_order_date_variable', false );
									$order_filter_date_variable_length = woo_ce_get_option( 'auto_order_date_variable_length', false );
									$export->args['order_dates_filter_variable'] = ( !empty( $order_filter_date_variable ) ? absint( $order_filter_date_variable ) : false );
									$export->args['order_dates_filter_variable_length'] = ( !empty( $order_filter_date_variable_length ) ? sanitize_text_field( $order_filter_date_variable_length ) : false );
									break;

							}
						}
						// Product
						$order_filter_product = woo_ce_get_option( 'auto_order_product', '' );
						$export->args['order_product'] = ( !empty( $order_filter_product ) ? (array)$order_filter_product : array() );
						// Billing Country
						$order_filter_billing_country = woo_ce_get_option( 'auto_order_billing_country', false );
						$export->args['order_billing_country'] = ( !empty( $order_filter_billing_country ) ? array_map( 'sanitize_text_field', $order_filter_billing_country ) : false );
						// Shipping Country
						$order_filter_shipping_country = woo_ce_get_option( 'auto_order_shipping_country', false );
						$export->args['order_shipping_country'] = ( !empty( $order_filter_shipping_country ) ? array_map( 'sanitize_text_field', $order_filter_shipping_country ) : false );
						// Payment Gateway
						$order_filter_payment = woo_ce_get_option( 'auto_order_payment', array() );
						$export->args['order_payment'] = ( !empty( $order_filter_payment ) ? array_map( 'sanitize_text_field', $order_filter_payment ) : false );
						// Shipping Method
						$order_filter_shipping = woo_ce_get_option( 'auto_order_shipping', array() );
						$export->args['order_shipping'] = ( !empty( $order_filter_shipping ) ? array_map( 'sanitize_text_field', $order_filter_shipping ) : false );
					} else {

						// CRON export engine

						// Order Status
						if( isset( $_GET['order_status'] ) ) {
							$order_filter_status = sanitize_text_field( $_GET['order_status'] );
							$order_filter_status = explode( ',', $order_filter_status );
							$export->args['order_status'] = $order_filter_status;
						}
						// Product
						if( isset( $_GET['order_product'] ) ) {
							$order_filter_product = sanitize_text_field( $_GET['order_product'] );
							$order_filter_product = explode( ',', $order_filter_product );
							$export->args['order_product'] = $order_filter_product;
						}
						// Order Date
						if( isset( $_GET['order_date_from'] ) && isset( $_GET['order_date_to'] ) ) {
							$order_filter_dates_from = $_GET['order_date_from'];
							$order_filter_dates_to = $_GET['order_date_to'];
							$export->args['order_dates_filter'] = 'manual';
							$export->args['order_dates_from'] = ( !empty( $order_filter_dates_from ) ? sanitize_text_field( $order_filter_dates_from ) : false );
							$export->args['order_dates_to'] = ( !empty( $order_filter_dates_to ) ? sanitize_text_field( $order_filter_dates_to ) : false );
						}
						// Billing Country
						if( isset( $_GET['billing_country'] ) ) {
							$order_filter_billing_country = sanitize_text_field( $_GET['billing_country'] );
							$order_filter_billing_country = explode( ',', $order_filter_billing_country );
							$export->args['order_billing_country'] = ( !empty( $order_filter_billing_country ) ? $order_filter_billing_country : false );
						}
						// Shipping Country
						if( isset( $_GET['shipping_country'] ) ) {
							$order_filter_shipping_country = sanitize_text_field( $_GET['shipping_country'] );
							$order_filter_shipping_country = explode( ',', $order_filter_shipping_country );
							$export->args['order_shipping_country'] = ( !empty( $order_filter_shipping_country ) ? $order_filter_shipping_country : false );
						}
						// Payment Gateway
						if( isset( $_GET['payment_gateway'] ) ) {
							$order_filter_payment = sanitize_text_field( $_GET['order_payment'] );
							$order_filter_payment = explode( ',', $order_filter_payment );
							$export->args['order_payment'] = ( !empty( $order_filter_payment ) ? $order_filter_payment : false );
						}
						// Shipping Method
						if( isset( $_GET['shipping_method'] ) ) {
							$order_filter_shipping = sanitize_text_field( $_GET['shipping_method'] );
							$order_filter_shipping = explode( ',', $order_filter_shipping );
							$export->args['order_shipping'] = ( !empty( $order_filter_shipping ) ? $order_filter_shipping : false );
						}
					}
					break;

				case 'subscription':
					$export->args['subscription_orderby'] = $orderby;
					$export->args['subscription_order'] = $order;
					break;

				case 'product_vendor':
					$export->args['product_vendor_orderby'] = $orderby;
					$export->args['product_vendor_order'] = $order;
					break;

				case 'commission':
					// Commission Date
					$commission_dates_filter = woo_ce_get_option( 'auto_commission_date', false );
					if( $commission_dates_filter ) {
						$export->args['commission_dates_filter'] = $commission_dates_filter;
						switch( $commission_dates_filter ) {

							case 'manual':
								$commission_filter_dates_from = woo_ce_get_option( 'auto_commission_dates_from', false );
								$commission_filter_dates_to = woo_ce_get_option( 'auto_commission_date_to', false );
								$export->args['commission_dates_from'] = ( !empty( $commission_filter_dates_from ) ? sanitize_text_field( $commission_filter_dates_from ) : false );
								$export->args['commission_dates_to'] = ( !empty( $commission_filter_dates_to ) ? sanitize_text_field( $commission_filter_dates_to ) : false );
								break;

							case 'variable':
								$commission_filter_date_variable = woo_ce_get_option( 'auto_commission_date_variable', false );
								$commission_filter_date_variable_length = woo_ce_get_option( 'auto_commission_date_variable_length', false );
								$export->args['commission_dates_filter_variable'] = ( !empty( $commission_filter_date_variable ) ? absint( $commission_filter_date_variable ) : false );
								$export->args['commission_dates_filter_variable_length'] = ( !empty( $commission_filter_date_variable_length ) ? sanitize_text_field( $commission_filter_date_variable_length ) : false );
								break;

						}
					}
					break;

				case 'shipping_class':
					$export->args['shipping_class_orderby'] = $orderby;
					$export->args['shipping_class_order'] = $order;
					break;

			}
			$export->filename = woo_ce_generate_filename( $export->type ) . '.' . $file_extension;
			// Let's spin up PHPExcel for supported Export Types and Export Formats
			if( in_array( $export->export_format, array( 'csv', 'xls', 'xlsx' ) ) ) {
				// Check if we are using PHPExcel or not for supported Export Types
				$dataset = woo_ce_export_dataset( $export->type );
				if( !empty( $dataset ) ) {
					// Check that PHPExcel is where we think it is
					if( file_exists( WOO_CD_PATH . 'classes/PHPExcel.php' ) ) {
						// Check if PHPExcel has already been loaded
						if( !class_exists( 'PHPExcel' ) ) {
							include_once( WOO_CD_PATH . 'classes/PHPExcel.php' );
						} else {
							error_log( sprintf( '[store-exporter-deluxe] %s: Warning: %s', $export->filename, __( 'The PHPExcel library was already loaded by another WordPress Plugin, if there\'s issues with your export file you know where to look.', 'woo_ce' ) ) );
						}
						$excel = new PHPExcel();
						$excel->setActiveSheetIndex( 0 );
						$excel->getActiveSheet()->setTitle( ucfirst( $export->type ) );
						$row = 1;
						// Skip headers if Heading Formatting is turned off
						if( $export->header_formatting ) {
							$col = 0;
							foreach( $export->columns as $column ) {
								$excel->getActiveSheet()->setCellValueByColumnAndRow( $col, $row, $column );
								$excel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->getStyle()->getFont()->setBold( true );
								$excel->getActiveSheet()->getColumnDimensionByColumn( $col )->setAutoSize( true );
								$col++;
							}
							$row = 2;
						}
						foreach( $dataset as $data ) {
							$col = 0;
							foreach( array_keys( $export->fields ) as $field ) {
								$excel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->getStyle()->getFont()->setBold( false );
								if( $export->encoding == 'UTF-8' ) {
									if( woo_ce_detect_value_string( ( isset( $data->$field ) ? $data->$field : null ) ) ) {
										// Treat this cell as a string
										$excel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->setValueExplicit( ( isset( $data->$field ) ? wp_specialchars_decode( $data->$field ) : '' ), PHPExcel_Cell_DataType::TYPE_STRING );
									} else {
										$excel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->setValue( ( isset( $data->$field ) ? wp_specialchars_decode( $data->$field ) : '' ) );
									}
								} else {
									// PHPExcel only deals with UTF-8 regardless of encoding type
									if( woo_ce_detect_value_string( ( isset( $data->$field ) ? $data->$field : null ) ) ) {
										// Treat this cell as a string
										$excel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->setValueExplicit( ( isset( $data->$field ) ? utf8_encode( wp_specialchars_decode( $data->$field ) ) : '' ), PHPExcel_Cell_DataType::TYPE_STRING );
									} else {
										$excel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->setValue( ( isset( $data->$field ) ? utf8_encode( wp_specialchars_decode( $data->$field ) ) : '' ) );
									}
								}
								$col++;
							}
							$row++;
						}
						switch( $export->export_format ) {

							case 'csv':
								// We need to load this after the PHPExcel Class has been created
								woo_cd_load_phpexcel_sed_csv_writer();
								break;

						}
						$objWriter = PHPExcel_IOFactory::createWriter( $excel, $php_excel_format );
						switch( $export->export_format ) {

							case 'csv':
								$objWriter->setUseBOM( true );
								// Check if we're using a non-standard delimiter
								if( $export->delimiter != ',' )
									$objWriter->setDelimiter( $export->delimiter );
								break;

							case 'xlsx':
								$objWriter->setPreCalculateFormulas( false );
								break;

						}
						if( in_array( $gui, array( 'raw' ) ) ) {
							$objWriter->save( 'php://output' );
						} else {
							// Save to file and insert to WordPress Media
							$temp_filename = tempnam( apply_filters( 'woo_ce_sys_get_temp_dir', sys_get_temp_dir() ), 'tmp' );
							// Check if we were given a temporary filename
							if( $temp_filename == false ) {
								$message = sprintf( __( 'We could not create a temporary export file in %s, ensure that WordPress can read and write files here and try again.', 'woo_ce' ), apply_filters( 'woo_ce_sys_get_temp_dir', sys_get_temp_dir() ) );
								error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, $message ) );
							} else {
								$objWriter->save( $temp_filename );
								$bits = file_get_contents( $temp_filename );
							}
							unlink( $temp_filename );
						}

						// Clean up PHPExcel
						$excel->disconnectWorksheets();
						unset( $objWriter, $excel );

					} else {
						error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, __( 'We couldn\'t load the PHPExcel library, this file should be present.' ) ) );
					}
				}
			// Run the default engine for the XML and RSS export formats
			} else if( in_array( $export->export_format, array( 'xml', 'rss' ) ) ) {
				// Check if SimpleXMLElement is present
				if( class_exists( 'SED_SimpleXMLElement' ) ) {
					if( $export->export_format == 'xml' ) {
						$xml = new SED_SimpleXMLElement( sprintf( apply_filters( 'woo_ce_export_xml_first_line', '<?xml version="1.0" encoding="%s"?><%s/>' ), esc_attr( $export->encoding ), esc_attr( apply_filters( 'woo_ce_export_xml_store_node', 'store' ) ) ) );
						if( woo_ce_get_option( 'xml_attribute_url', 1 ) )
							$xml->addAttribute( 'url', get_site_url() );
						if( woo_ce_get_option( 'xml_attribute_date', 1 ) )
							$xml->addAttribute( 'date', date( 'Y-m-d' ) );
						if( woo_ce_get_option( 'xml_attribute_time', 0 ) )
							$xml->addAttribute( 'time', date( 'H:i:s' ) );
						if( woo_ce_get_option( 'xml_attribute_title', 1 ) )
							$xml->addAttribute( 'name', htmlspecialchars( get_bloginfo( 'name' ) ) );
						if( woo_ce_get_option( 'xml_attribute_export', 1 ) )
							$xml->addAttribute( 'export', htmlspecialchars( $export->type ) );
						if( woo_ce_get_option( 'xml_attribute_orderby', 1 ) )
							$xml->addAttribute( 'orderby', $orderby );
						if( woo_ce_get_option( 'xml_attribute_order', 1 ) )
							$xml->addAttribute( 'order', $order );
						if( woo_ce_get_option( 'xml_attribute_limit', 1 ) )
							$xml->addAttribute( 'limit', $export->limit_volume );
						if( woo_ce_get_option( 'xml_attribute_offset', 1 ) )
							$xml->addAttribute( 'offset', $export->offset );
						$xml = woo_ce_export_dataset( $export->type, $xml );
					} else if( $export->export_format == 'rss' ) {
						$xml = new SED_SimpleXMLElement( sprintf( apply_filters( 'woo_ce_export_rss_first_line', '<?xml version="1.0" encoding="%s"?><rss version="2.0"%s/>' ), esc_attr( $export->encoding ), ' xmlns:g="http://base.google.com/ns/1.0"' ) );
						$child = $xml->addChild( apply_filters( 'woo_ce_export_rss_channel_node', 'channel' ) );
						$child->addChild( 'title', woo_ce_get_option( 'rss_title', '' ) );
						$child->addChild( 'link', woo_ce_get_option( 'rss_link', '' ) );
						$child->addChild( 'description', woo_ce_get_option( 'rss_description', '' ) );
						$bits = woo_ce_export_dataset( $export->type, $child );
					}
					$bits = woo_ce_format_xml( $xml );
				} else {
					$bits = false;
					error_log( '[store-exporter-deluxe] Error: The SimpleXMLElement class does not exist for XML file generation' );
				}
			}
			if( !empty( $bits ) ) {
				$output = '<p>' . __( 'Export completed successfully.', 'woo_ce' ) . '</p>';
				if( $gui == 'gui' )
					$output .= '<textarea readonly="readonly">' . esc_textarea( str_replace( '<br />', "\n", $bits ) ) . '</textarea>';
			} else {
				if( $gui == 'gui' ) {
					$output = sprintf( '<p>%s</p>', __( 'No export entries were found.', 'woo_ce' ) );
				} else {
					error_log( sprintf( '[store-exporter-deluxe] %s: Warning: %s', $export->filename, __( 'No export entries were found', 'woo_ce' ) ) );
					return false;
				}
			}
		}
	}

	// Return raw export to browser without file headers
	if( $gui == 'raw' && !empty( $bits ) ) {
		return $bits;
	// Return export as file download to browser
	} else if( $gui == 'download' && !empty( $bits ) ) {
		woo_ce_generate_file_headers( $post_mime_type );
		if( defined( 'DOING_AJAX' ) || get_transient( WOO_CD_PREFIX . '_single_export_format' ) !== false )
			echo $bits;
		else
			return $bits;
	// HTTP Post export contents to remote URL
	} else if( $gui == 'post' && !empty( $bits ) ) {
		$args = apply_filters( 'woo_ce_cron_export_post_args', array(
			'method'      => 'POST',
			'timeout'     => 60,
			'redirection' => 0,
			'httpversion' => '1.0',
			'sslverify'   => false,
			'blocking'    => true,
			'headers'     => array(
				'accept'       => $post_mime_type,
				'content-type' => $post_mime_type
			),
			'body'        => $bits,
			'cookies'     => array(),
			'user-agent'  => sprintf( 'WordPress/%s', $GLOBALS['wp_version'] ),
		) );
		$response = wp_remote_post( $export->to, $args );
		if( is_wp_error( $response ) ) {
			error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, $response->get_error_message() ) );
			return false;
		} else {
			error_log( sprintf( '[store-exporter-deluxe] %s: Success: %s', $export->filename, sprintf( __( 'Remote POST sent to %s', 'woo_ce' ), $export->to ) ) );
		}
	// Output to screen in friendly design with on-screen error responses
	} else if( $gui == 'gui' ) {
		if( file_exists( WOO_CD_PATH . 'templates/admin/cron.php' ) ) {
			include_once( WOO_CD_PATH . 'templates/admin/cron.php' );
		} else {
			error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, __( 'Could not load template file within /templates/admin/cron.php', 'woo_ce' ) ) );
		}
		if( isset( $output ) )
			echo $output;
		echo '
	</body>
</html>';
	// Save export file to WordPress Media before sending/saving/etc. action
	} else if( in_array( $gui, array( 'gui', 'archive', 'url', 'file', 'email', 'ftp' ) ) ) {
		$upload = false;
		if( $export->filename && !empty( $bits ) ) {
			$post_ID = woo_ce_save_file_attachment( $export->filename, $post_mime_type );
			$upload = wp_upload_bits( $export->filename, null, $bits );
			if( ( $post_ID == false ) || $upload['error'] ) {
				wp_delete_attachment( $post_ID, true );
				error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, $upload['error'] ) );
				return false;
			}
			if( file_exists( ABSPATH . 'wp-admin/includes/image.php' ) ) {
				include_once( ABSPATH . 'wp-admin/includes/image.php' );
				$attach_data = wp_generate_attachment_metadata( $post_ID, $upload['file'] );
				wp_update_attachment_metadata( $post_ID, $attach_data );
				update_attached_file( $post_ID, $upload['file'] );
				if( !empty( $post_ID ) ) {
					woo_ce_save_file_guid( $post_ID, $export->type, $upload['url'] );
					woo_ce_save_file_details( $post_ID );
				}
			} else {
				error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, __( 'Could not load image.php within /wp-admin/includes/image.php', 'woo_ce' ) ) );
			}
		}
		// Return URL to export file
		if( $gui == 'url' )
			return $upload['url'];
		// Return system path to export file
		if( $gui == 'file' )
			return $upload['file'];
		// E-mail export file to preferred address or WordPress site owner address
		if( $gui == 'email' ) {

			global $woocommerce;

			$mailer = $woocommerce->mailer();
			$subject = woo_ce_cron_email_subject( $export->type, $export->filename );
			$attachment = $upload['file'];
			$email_heading = sprintf( __( 'Export: %s', 'woo_ce' ), ucwords( $export->type ) );
			$recipient_name = apply_filters( 'woo_ce_email_recipient_name', __( 'there', 'woo_ce' ) );
			$email_contents = apply_filters( 'woo_ce_email_contents', wpautop( __( 'Please find attached your export ready to review.', 'woo_ce' ) ) );

			// Buffer
			ob_start();

			// Get mail template
			if( file_exists( WOO_CD_PATH . 'templates/emails/scheduled_export.php' ) ) {
				include_once( WOO_CD_PATH . 'templates/emails/scheduled_export.php' );
			} else {
				echo wpautop( sprintf( __( 'Hi %s', 'woo_ce' ), $recipient_name ) );
				echo $email_contents;
				error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, sprintf( __( 'Could not load template file %s within %s, defaulted to hard coded template.', 'woo_ce' ), 'scheduled_export.php', '/templates/emails/...' ) ) );
			}

			// Get contents
			$message = ob_get_clean();

			// Send the mail using WooCommerce mailer
			if( function_exists( 'woocommerce_mail' ) ) {
				woocommerce_mail( $export->to, $subject, $message, null, $attachment );
			} else {
				// Default to wp_mail()
				add_filter( 'wp_mail_content_type', 'woo_ce_set_html_content_type' );
				wp_mail( $export->to, $subject, $message, null, $attachment );
				remove_filter( 'wp_mail_content_type', 'woo_ce_set_html_content_type' );
			}
			// Delete the export file regardless of whether e-mail was successful or not
			wp_delete_attachment( $post_ID, true );
			error_log( sprintf( '[store-exporter-deluxe] %s: Success: %s', $export->filename, sprintf( __( 'Scheduled export e-mail of %s sent to %s', 'woo_ce' ), $export->filename, $export->to ) ) );

		}
		if( $gui == 'ftp' ) {

			// Load up our FTP/SFTP resources
			$host = woo_ce_get_option( 'auto_ftp_method_host', '' );
			if( !empty( $host ) )
				$host = woo_ce_format_ftp_host( $host );
			$port = woo_ce_get_option( 'auto_ftp_method_port', '' );
			$port = ( !empty( $port ) ? absint( $port ) : false );
			$user = woo_ce_get_option( 'auto_ftp_method_user', '' );
			$pass = woo_ce_get_option( 'auto_ftp_method_pass', '' );
			$path = woo_ce_get_option( 'auto_ftp_method_path', '' );
			$filename = woo_ce_get_option( 'auto_ftp_method_filename', '' );
			// Switch to fixed export filename if provided
			if( !empty( $filename ) )
				$export->filename = woo_ce_generate_filename( $export->type, $filename ) . '.' . $file_extension;

			// Check what protocol are we using; FTP or SFTP?
			$protocol = woo_ce_get_option( 'auto_ftp_method_protocol', 'ftp' );
			switch( $protocol ) {

				case 'ftp':
				default:
					// Check if ftp_connect() is available
					if( function_exists( 'ftp_connect' ) ) {
						$passive = woo_ce_get_option( 'auto_ftp_method_passive', '' );
						$timeout = woo_ce_get_option( 'auto_ftp_method_timeout', '' );
						if( $connection = @ftp_connect( $host, $port ) ) {
							// Update the FTP timeout if available and if a timeout was provided at export
							$remote_timeout = ftp_get_option( $connection, FTP_TIMEOUT_SEC );
							$timeout = absint( $timeout );
							if( $remote_timeout !== false && !empty( $timeout ) ) {
								// Compare the server timeout and the timeout provided at export
								if( $remote_timeout <> $timeout ) {
									if( ftp_set_option( $connection, FTP_TIMEOUT_SEC, $timeout ) == false )
										error_log( sprintf( '[store-exporter-deluxe] %s: Warning: %s', $export->filename, sprintf( __( 'Could not change the FTP server timeout on %s', 'woo_ce' ), $host ) ) );
								}
							}
							unset( $remote_timeout );
							if( ftp_login( $connection, $user, $pass ) ) {
								// Check if Transfer Mode is set to Auto/Pasive and if passive mode is available
								if( in_array( $passive, array( 'auto', 'passive' ) ) ) {
									$features = ftp_raw( $connection, 'FEAT' );
									if( !empty( $features ) ) {
										if( in_array( 'PASV', $features ) ) {
											if( ftp_pasv( $connection, true ) == false )
												error_log( sprintf( '[store-exporter-deluxe] %s: Warning: %s', 'woo_ce', $export->filename, sprintf( __( 'Could not switch to FTP passive mode on %s', 'woo_ce' ), $host ) ) );
										}
									}
								}
								// Change directory if neccesary
								if( !empty( $directory ) ) {
									$current_directory  = ftp_pwd( $connection );
									if( $current_directory !== false && @ftp_chdir( $connection, $path ) )
										ftp_chdir( $connection, $path );
								}
								if( ftp_put( $connection, sprintf( '%s/%s', $path, $export->filename ), $upload['file'], FTP_ASCII ) ) {
									error_log( sprintf( '[store-exporter-deluxe] %s: Success: %s', $export->filename, sprintf( __( 'Scheduled export of %s to %s via FTP uploaded', 'woo_ce' ), $export->filename, $path ) ) );
								} else {
									$export->error = sprintf( __( 'There was a problem uploading %s to %s via FTP, response: %s', 'woo_ce' ), $export->filename, $path, woo_ce_error_get_last_message() );
									error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, $export->error ) );
								}
							} else {
								$export->error = sprintf( __( 'Login incorrect for user %s on FTP server at %s, response: %s', 'woo_ce' ), $user, $host, woo_ce_error_get_last_message() );
								error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, $export->error ) );
							}
						} else {
							$export->error = sprintf( __( 'There was a problem connecting to %s via FTP', 'woo_ce' ), $host );
							error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, $export->error ) );
						}
					} else {
						$export->error = __( 'The function ftp_connect() is disabled within your WordPress site, cannot upload to FTP server', 'woo_ce' );
						error_log( __( '[store-exporter-deluxe] %s: Error: %s', 'woo_ce' ), $export->filename, $export->error );
					}
					break;

				case 'sftp':
					// Check if ssh2_connect() is available
					if( function_exists( 'ssh2_connect' ) ) {
						if( $connection = @ssh2_connect( $host, $port ) ) {
							if( ssh2_auth_password( $connection, $user, $pass ) ) {
								// Initialize SFTP subsystem
								if( $session = ssh2_sftp( $connection ) ) {
									if( $handle = fopen( sprintf( 'ssh2.sftp://%s/%s/%s', $session, $path, $export->filename ), 'w+' ) ) {
										error_log( sprintf( '[store-exporter-deluxe] %s: Success: %s', $export->filename, sprintf( __( 'Scheduled export of %s to %s via SFTP uploaded', 'woo_ce' ), $export->filename, $path ) ) );
									} else {
										$export->error = sprintf( __( 'There was a problem uploading %s to %s via SFTP', 'woo_ce' ), $export->filename, $path );
										error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, $export->error ) );
									}
								} else {
									$export->error = sprintf( __( 'Could not initialize SFTP subsystem on SFTP server at %s', 'woo_ce' ), $host );
									error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, $export->error ) );
								}
							} else {
								$export->error = sprintf( __( 'Login incorrect for user %s on SFTP server at %s', 'woo_ce' ), $user, $host );
								error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, $export->error ) );
							}
						} else {
							$export->error = sprintf( __( 'There was a problem connecting to %s via SFTP', 'woo_ce' ), $host );
							error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, $export->error ) );
						}
					} else {
						$export->error = __( 'The function ssh2_connect() is disabled within your WordPress site, cannot upload to SFTP server', 'woo_ce' );
						error_log( sprintf( __( '[store-exporter-deluxe] %s: Error: %s', 'woo_ce' ), $export->filename, $export->error ) );
					}
					break;

			}
			// Delete the export file regardless of whether upload was successful or not
			wp_delete_attachment( $post_ID, true );
		}
	}

	// Only include scheduled exports to the Recent Scheduled Exports list
	if( $export->scheduled_export ) {
		$recent_exports = woo_ce_get_option( 'recent_scheduled_exports', array() );
		if( empty( $recent_exports ) )
			$recent_exports = array();
		$size = count( $recent_exports );
		// Get the limit from the WordPress Dashboard widget
		if( !$widget_options = get_option( 'woo_ce_recent_scheduled_export_widget_options', array() ) ) {
			$widget_options = array(
				'number' => 5
			);
		}

		// Check if we have maxed out our recent scheduled exports
		if( $size >= $widget_options['number'] )
			array_shift( $recent_exports );
		$post_ID = ( isset( $post_ID ) ? $post_ID : 0 );
		$recent_exports[] = array(
			'post_id' => ( empty( $export->error ) ? $post_ID : 0 ),
			'name' => $export->filename,
			'date' => time(),
			'method' => $gui,
			'error' => $export->error
		);
		woo_ce_update_option( 'recent_scheduled_exports', $recent_exports );
	}

	delete_option( WOO_CD_PREFIX . '_exported' );

	// If the CRON process gets this far, pass on the good news!
	return true;

}
 /**
  * Process a single image ID (this is an AJAX handler)
  * 
  * @access public
  * @since 1.0
  */
 function ajax_process_image()
 {
     // No timeout limit
     set_time_limit(0);
     // Don't break the JSON result
     error_reporting(0);
     $id = (int) $_REQUEST['id'];
     try {
         header('Content-type: application/json');
         $image = get_post($id);
         if (is_null($image)) {
             throw new Exception(sprintf(__('Failed: %d is an invalid image ID.', 'force-regenerate-thumbnails'), $id));
         }
         if ('attachment' != $image->post_type || 'image/' != substr($image->post_mime_type, 0, 6)) {
             throw new Exception(sprintf(__('Failed: %d is an invalid image ID.', 'force-regenerate-thumbnails'), $id));
         }
         if (!current_user_can($this->capability)) {
             throw new Exception(__('Your user account does not have permission to regenerate images.', 'force-regenerate-thumbnails'));
         }
         /**
          * Fix for get_option('upload_path')
          * Thanks (@DavidLingren)
          * 
          * @since 2.0.1
          */
         $upload_dir = wp_upload_dir();
         // Get original image
         $image_fullpath = get_attached_file($image->ID);
         $debug_1 = $image_fullpath;
         $debug_2 = '';
         $debug_3 = '';
         $debug_4 = '';
         // Can't get image path
         if (false === $image_fullpath || strlen($image_fullpath) == 0) {
             // Try get image path from url
             if (strrpos($image->guid, $upload_dir['baseurl']) !== false) {
                 $image_fullpath = realpath($upload_dir['basedir'] . DIRECTORY_SEPARATOR . substr($image->guid, strlen($upload_dir['baseurl']), strlen($image->guid)));
                 $debug_2 = $image_fullpath;
                 if (realpath($image_fullpath) === false) {
                     throw new Exception(sprintf(__('The originally uploaded image file cannot be found at &quot;%s&quot;.', 'force-regenerate-thumbnails'), esc_html((string) $image_fullpath)));
                 }
             } else {
                 throw new Exception(__('The originally uploaded image file cannot be found.', 'force-regenerate-thumbnails'));
             }
         }
         // Image path incomplete
         if (strrpos($image_fullpath, $upload_dir['basedir']) === false) {
             $image_fullpath = $upload_dir['basedir'] . DIRECTORY_SEPARATOR . $image_fullpath;
             $debug_3 = $image_fullpath;
         }
         // Image don't exists
         if (!file_exists($image_fullpath) || realpath($image_fullpath) === false) {
             // Try get image path from url
             if (strrpos($image->guid, $upload_dir['baseurl']) !== false) {
                 $image_fullpath = realpath($upload_dir['basedir'] . DIRECTORY_SEPARATOR . substr($image->guid, strlen($upload_dir['baseurl']), strlen($image->guid)));
                 $debug_4 = $image_fullpath;
                 if (realpath($image_fullpath) === false) {
                     throw new Exception(sprintf(__('The originally uploaded image file cannot be found at &quot;%s&quot;.', 'force-regenerate-thumbnails'), esc_html((string) $image_fullpath)));
                 }
             } else {
                 throw new Exception(sprintf(__('The originally uploaded image file cannot be found at &quot;%s&quot;.', 'force-regenerate-thumbnails'), esc_html((string) $image_fullpath)));
             }
         }
         /**
          * Update META POST
          * Thanks (@norecipes)
          *
          * @since 2.0.2
          */
         update_attached_file($image->ID, $image_fullpath);
         // Results
         $thumb_deleted = array();
         $thumb_error = array();
         $thumb_regenerate = array();
         // Hack to find thumbnail
         $file_info = pathinfo($image_fullpath);
         $file_info['filename'] .= '-';
         /**
          * Try delete all thumbnails
          */
         $files = array();
         $path = opendir($file_info['dirname']);
         if (false !== $path) {
             while (false !== ($thumb = readdir($path))) {
                 if (!(strrpos($thumb, $file_info['filename']) === false)) {
                     $files[] = $thumb;
                 }
             }
             closedir($path);
             sort($files);
         }
         foreach ($files as $thumb) {
             $thumb_fullpath = $file_info['dirname'] . DIRECTORY_SEPARATOR . $thumb;
             $thumb_info = pathinfo($thumb_fullpath);
             $valid_thumb = explode($file_info['filename'], $thumb_info['filename']);
             if ($valid_thumb[0] == "") {
                 $dimension_thumb = explode('x', $valid_thumb[1]);
                 if (count($dimension_thumb) == 2) {
                     if (is_numeric($dimension_thumb[0]) && is_numeric($dimension_thumb[1])) {
                         unlink($thumb_fullpath);
                         if (!file_exists($thumb_fullpath)) {
                             $thumb_deleted[] = sprintf("%sx%s", $dimension_thumb[0], $dimension_thumb[1]);
                         } else {
                             $thumb_error[] = sprintf("%sx%s", $dimension_thumb[0], $dimension_thumb[1]);
                         }
                     }
                 }
             }
         }
         /**
          * Regenerate all thumbnails
          */
         $metadata = wp_generate_attachment_metadata($image->ID, $image_fullpath);
         if (is_wp_error($metadata)) {
             throw new Exception($metadata->get_error_message());
         }
         if (empty($metadata)) {
             throw new Exception(__('Unknown failure reason.', 'force-regenerate-thumbnails'));
         }
         wp_update_attachment_metadata($image->ID, $metadata);
         /**
          * Verify results (deleted, errors, success)
          */
         $files = array();
         $path = opendir($file_info['dirname']);
         if (false !== $path) {
             while (false !== ($thumb = readdir($path))) {
                 if (!(strrpos($thumb, $file_info['filename']) === false)) {
                     $files[] = $thumb;
                 }
             }
             closedir($path);
             sort($files);
         }
         foreach ($files as $thumb) {
             $thumb_fullpath = $file_info['dirname'] . DIRECTORY_SEPARATOR . $thumb;
             $thumb_info = pathinfo($thumb_fullpath);
             $valid_thumb = explode($file_info['filename'], $thumb_info['filename']);
             if ($valid_thumb[0] == "") {
                 $dimension_thumb = explode('x', $valid_thumb[1]);
                 if (count($dimension_thumb) == 2) {
                     if (is_numeric($dimension_thumb[0]) && is_numeric($dimension_thumb[1])) {
                         $thumb_regenerate[] = sprintf("%sx%s", $dimension_thumb[0], $dimension_thumb[1]);
                     }
                 }
             }
         }
         // Remove success if has in error list
         foreach ($thumb_regenerate as $key => $regenerate) {
             if (in_array($regenerate, $thumb_error)) {
                 unset($thumb_regenerate[$key]);
             }
         }
         // Remove deleted if has in success list
         foreach ($thumb_deleted as $key => $deleted) {
             if (in_array($deleted, $thumb_regenerate)) {
                 unset($thumb_deleted[$key]);
             }
         }
         /**
          * Display results
          */
         $message = sprintf(__('<b>&quot;%s&quot; (ID %s)</b>', 'force-regenerate-thumbnails'), esc_html(get_the_title($id)), $image->ID);
         $message .= "<br /><br />";
         $message .= sprintf(__("<code>BaseDir: %s</code><br />", 'force-regenerate-thumbnails'), $upload_dir['basedir']);
         $message .= sprintf(__("<code>BaseUrl: %s</code><br />", 'force-regenerate-thumbnails'), $upload_dir['baseurl']);
         $message .= sprintf(__("<code>Image: %s</code><br />", 'force-regenerate-thumbnails'), $debug_1);
         if ($debug_2 != '') {
             $message .= sprintf(__("<code>Image Debug 2: %s</code><br />", 'force-regenerate-thumbnails'), $debug_2);
         }
         if ($debug_3 != '') {
             $message .= sprintf(__("<code>Image Debug 3: %s</code><br />", 'force-regenerate-thumbnails'), $debug_3);
         }
         if ($debug_4 != '') {
             $message .= sprintf(__("<code>Image Debug 4: %s</code><br />", 'force-regenerate-thumbnails'), $debug_4);
         }
         if (count($thumb_deleted) > 0) {
             $message .= sprintf(__('<br />Deleted: %s', 'force-regenerate-thumbnails'), implode(', ', $thumb_deleted));
         }
         if (count($thumb_error) > 0) {
             $message .= sprintf(__('<br /><b><span style="color: #DD3D36;">Deleted error: %s</span></b>', 'force-regenerate-thumbnails'), implode(', ', $thumb_error));
             $message .= sprintf(__('<br /><span style="color: #DD3D36;">Please, check the folder permission (chmod 777): %s</span>', 'force-regenerate-thumbnails'), $upload_dir['basedir']);
         }
         if (count($thumb_regenerate) > 0) {
             $message .= sprintf(__('<br />Regenerate: %s</span>', 'force-regenerate-thumbnails'), implode(', ', $thumb_regenerate));
             if (count($thumb_error) <= 0) {
                 $message .= sprintf(__('<br />Successfully regenerated in %s seconds', 'force-regenerate-thumbnails'), timer_stop());
             }
         }
         if (count($thumb_error) > 0) {
             die(json_encode(array('error' => '<div id="message" class="error fade"><p>' . $message . '</p></div>')));
         } else {
             die(json_encode(array('success' => '<div id="message" class="updated fade"><p>' . $message . '</p></div>')));
         }
     } catch (Exception $e) {
         $this->die_json_failure_msg($id, '<b><span style="color: #DD3D36;">' . $e->getMessage() . '</span></b>');
     }
     exit;
 }
Esempio n. 15
0
 /**
  *main function to process encoding via ffmpeg for the front end uploader and the backend
  *@access public
  */
 public function wpvp_encode($ID, $front_end_postID = NULL)
 {
     global $encodeFormat, $shortCode;
     $videoPostID = 0;
     //$ID is an attachment post passed from attachment processing
     $helper = new WPVP_Helper();
     $options = $helper->wpvp_get_full_options();
     $ffmpeg_exists = $options['ffmpeg_exists'];
     $width = $options['video_width'];
     $height = $options['video_height'];
     $ffmpeg_path = $options['ffmpeg_path'];
     $mp4box_path = $options['mp4box_path'];
     $debug_mode = $options['debug_mode'];
     $allowed_ext = array('mp4', 'flv');
     $encodeFormat = 'mp4';
     // Other formats will be available soon...
     // Handle various formats options here...
     if ($encodeFormat == 'flash') {
         $extension = '.flv';
         $thumbfmt = '.jpg';
     } else {
         if ($encodeFormat == 'mp4') {
             $extension = '.mp4';
             $thumbfmt = '.jpg';
         }
     }
     //Get the attachment details (we can access the items individually)
     $postDetails = get_post($ID);
     //check if attachment is video
     if ($helper->is_video($postDetails->post_mime_type) == 'video') {
         $upload_dir = wp_upload_dir();
         $uploadPath = $upload_dir['path'];
         $uploadUrl = $upload_dir['url'];
         $originalFilePath = get_attached_file($ID);
         //get the path to the ORIGINAL file
         $fileDetails = pathinfo($originalFilePath);
         $fileExtension = $fileDetails['extension'];
         //check if ffmpeg exists and if video extension is allowed
         if (!in_array($fileExtension, $allowed_ext) && !$ffmpeg_exists) {
             //do not proceed
             if ($debug_mode) {
                 $helper->wpvp_dump('No FFMPEG found. Only mp4 and flv extensions are supported. The currently uploaded extension (' . $fileExtension . ') is not supported. Please encode the file manually and reupload.');
             }
             return;
         } else {
             //debug_mode is true
             if ($debug_mode) {
                 $helper->wpvp_dump('Initial file details...');
                 $helper->wpvp_dump($fileDetails);
             }
             //normalize the file name and make sure its not a duplicate
             $fileFound = true;
             $i = '';
             while ($fileFound) {
                 $fname = $fileDetails['filename'] . $i;
                 $newFile = $uploadPath . '/' . $fname . $extension;
                 $guid = $uploadUrl . '/' . $fname . $extension;
                 $newFileTB = $uploadPath . '/' . $fname . $thumbfmt;
                 $guidTB = $uploadUrl . '/' . $fname . $thumbfmt;
                 if ($ffmpeg_exists) {
                     $file_encoded = 1;
                     if (file_exists($newFile)) {
                         $i = $i == '' ? 1 : $i + 1;
                     } else {
                         $fileFound = false;
                     }
                 } else {
                     $file_encoded = 0;
                     $fileFound = false;
                 }
             }
             //while fileFound ends
             //debug_mode is true
             if ($debug_mode) {
                 $helper->wpvp_dump('New files path on the server: video and image ...');
                 $helper->wpvp_dump('video: ' . $newFile);
                 $helper->wpvp_dump('image: ' . $newFileTB);
                 $helper->wpvp_dump('New files url on the server: video and image ...');
                 $helper->wpvp_dump('video: ' . $guid);
                 $helper->wpvp_dump('image: ' . $guidTB);
             }
             if ($file_encoded) {
                 if ($debug_mode) {
                     $helper->wpvp_dump('FFMPEG found on the server. Encoding initializing...');
                 }
                 //ffmpeg to get a thumb from the video
                 $this->wpvp_convert_thumb($originalFilePath, $newFileTB);
                 //ffmpeg to convert video
                 $this->wpvp_convert_video($originalFilePath, $newFile, $encodeFormat);
                 //pathinfo on the FULL path to the NEW file
                 if ($debug_mode) {
                     if (!file_exists($newFile)) {
                         $helper->wpvp_dump('Video file was not converted. Possible reasons: missing libraries for ffmpeg, permissions on the directory where the file is being written to...');
                     } else {
                         $helper->wpvp_dump('Video was converted: ' . $newFile);
                     }
                     if (!file_exists($newFileTB)) {
                         $helper->wpvp_dump('Thumbnail was not created. Possible reasons: missing libraries for ffmpeg, permissions on the directory where the file is being written to...');
                     } else {
                         $helper->wpvp_dump('Thumbnail was created: ' . $newFileTB);
                     }
                 }
                 //update attachment file
                 $updated = update_attached_file($ID, $newfile);
             } else {
                 if ($debug_mode) {
                     $helper->wpvp_dump('FFMPEG is not found on the server. Possible reasons: not installed, not properly configured, the path is not provided correctly in the plugin\'s options settings...');
                 }
                 $defaultImg = get_option('wpvp_default_img', '') ? get_option('wpvp_default_img') : '';
                 if ($defaultImg != '') {
                     $newFileTB = $defaultImg;
                     $guidTB = str_replace($uploadPath, $uploadUrl, $newFileTB);
                 } else {
                     $default_img_path = $uploadPath . '/default_image.jpg';
                     copy(plugin_dir_path(dirname(__FILE__)) . 'images/default_image.jpg', $default_img_path);
                     if (file_exists($default_img_path)) {
                         update_option('wpvp_default_img', $default_img_path);
                         $newFileTB = $default_img_path;
                         $guidTB = str_replace($uploadPath, $uploadUrl, $default_img_path);
                     }
                 }
                 $guid = str_replace($uploadPath, $uploadUrl, $originalFilePath);
                 $newFile = $originalFilePath;
             }
             //no ffmpeg - no encoding
             $newFileDetails = pathinfo($newFile);
             $newTmbDetails = pathinfo($newFileTB);
             //shortcode for the player
             $shortCode = '[wpvp_player src=' . $guid . ' width=' . $width . ' height=' . $height . ' splash=' . $guidTB . ']';
             //update the auto created post with our data
             if (empty($front_end_postID)) {
                 $postID = intval($_REQUEST['post_id']);
             } else {
                 $postID = $front_end_postID;
             }
             $videoPostID = $postID;
             $postObj = get_post($videoPostID);
             $currentContent = $postObj->post_content;
             $newContent = $shortCode . $currentContent;
             $videopost = array('ID' => $postID, 'post_content' => $newContent);
             //update video post with a shortcode inserted in the content
             $updatedPost = wp_update_post($videopost);
             //add a thumbnail attachment and set as featured image
             $img_filetype = wp_check_filetype($newTmbDetails['basename'], null);
             $attachment = array('guid' => $guidTB, 'post_mime_type' => $img_filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', $newTmbDetails['basename']), 'post_content' => '', 'post_status' => 'inherit');
             $att_id = wp_insert_attachment($attachment, $newFileTB, $updatedPost);
             if ($att_id) {
                 $attach_data = wp_generate_attachment_metadata($att_id, $newFileTB);
                 wp_update_attachment_metadata($att_id, $attach_data);
                 add_post_meta($updatedPost, '_thumbnail_id', $att_id);
                 update_post_meta($updatedPost, '_wp_attached_file', $newFileTB);
             }
             //add the video file as attachment for the post
             //$video_filetype = wp_check_filetype($newFileDetails['basename']);
             //hardcode for now
             $video_filetype['type'] = 'video/mp4';
             $video_post = array('post_title' => preg_replace('/\\.[^.]+$/', '', $newFileDetails['basename']), 'guid' => $guid, 'post_parent' => $updatedPost, 'post_mime_type' => $video_filetype['type'], 'ID' => $ID);
             wp_update_post($video_post);
             update_post_meta($ID, '_wp_attached_file', $newFile);
             if ($file_encoded) {
                 //delete the original file
                 unlink($originalFilePath);
                 //rename($originalFileUrl,$newFile);
             }
             if (!$ID) {
                 return false;
             } else {
                 return $ID;
             }
         }
         //ffmpeg and uploaded extension is supported
     }
     //if uploaded attachment is a video
 }
Esempio n. 16
0
 function evc_save_remote_attachment($a, $post_parent = null, $title = '', $obj = false)
 {
     $options = get_option('evc_comments');
     // Create Img Filename
     $pi = pathinfo($a['img']);
     $filename = $pi['basename'];
     // print__r($pi);
     // Create Img
     $params = array('file_name' => $filename, 'url' => $a['img']);
     $img = evc_fetch_remote_file($params);
     if (is_wp_error($img)) {
         // print '<p>'. $img->get_error_message() . '</p>';
         return false;
     }
     $url = $img['url'];
     $type = $img['content-type'];
     $file = $img['file'];
     $att = array('post_status' => 'publish', 'ping_status' => 'closed', 'guid' => $url, 'post_mime_type' => $type);
     if (isset($post_parent) && $obj != 'user') {
         $att['post_parent'] = $post_parent;
     }
     if (isset($post_parent) && $obj == 'user') {
         $att['post_author'] = $post_parent;
     }
     if (isset($a['title'])) {
         $att['post_title'] = $a['title'];
     } else {
         $att['post_title'] = $title;
     }
     if (isset($a['text'])) {
         $att['post_content'] = $a['text'];
     }
     if (isset($a['description'])) {
         $att['post_content'] = $a['description'];
     }
     $att = apply_filters('evc_save_remote_attachment', $att);
     $att_ID = wp_insert_attachment($att);
     if (!$att_ID) {
         //print "<p>Can not create attachment for $img[file]</p>";
         return false;
     }
     if (!function_exists('wp_generate_attachment_metadata')) {
         require_once ABSPATH . 'wp-admin/includes/image.php';
     }
     $attachment_metadata = wp_generate_attachment_metadata($att_ID, $file);
     wp_update_attachment_metadata($att_ID, $attachment_metadata);
     update_attached_file($att_ID, $file);
     // Update Attachment Meta For POsts And Comments
     if (isset($a['type'])) {
         $meta = array('vk_type' => $a['type'], 'vk_owner_id' => $a['owner_id'], 'vk_access_key' => $a['access_key']);
     }
     if (isset($a['vk_player'])) {
         $meta['vk_player'] = $a['vk_player'];
     }
     if (isset($a['duration'])) {
         $meta['vk_duration'] = $a['duration'];
     }
     if ($obj != 'user' && isset($a['vk_item_id'])) {
         $meta['vk_item_id'] = $a['vk_item_id'];
     }
     if (isset($meta) && !empty($meta)) {
         evc_update_post_metas($meta, $att_ID);
     }
     // Update Attachment Meta For Users
     if ($obj == 'user') {
         update_user_meta($post_parent, $a['key'], $att_ID);
     }
     if (isset($a['key']) && $obj != 'user') {
         update_post_meta($post_parent, $a['key'], $att_ID);
     }
     do_action('evc_save_remote_attachment_action', $a, $att_ID, $att, $obj);
     return $att_ID;
 }
Esempio n. 17
0
/**
 * wp_insert_attachment() - Insert an attachment
 *
 * {@internal Missing Long Description}}
 *
 * @package WordPress
 * @subpackage Post
 * @since 2.0
 *
 * @uses $wpdb
 * @uses $user_ID
 *
 * @param object $object attachment object
 * @param string $file filename
 * @param int $post_parent parent post ID
 * @return int {@internal Missing Description}}
 */
function wp_insert_attachment($object, $file = false, $parent = 0)
{
    global $wpdb, $user_ID;
    $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID, 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '', 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '');
    $object = wp_parse_args($object, $defaults);
    if (!empty($parent)) {
        $object['post_parent'] = $parent;
    }
    $object = sanitize_post($object, 'db');
    // export array as variables
    extract($object, EXTR_SKIP);
    // Make sure we set a valid category
    if (0 == count($post_category) || !is_array($post_category)) {
        $post_category = array(get_option('default_category'));
    }
    if (empty($post_author)) {
        $post_author = $user_ID;
    }
    $post_type = 'attachment';
    $post_status = 'inherit';
    // Are we updating or creating?
    $update = false;
    if (!empty($ID)) {
        $update = true;
        $post_ID = (int) $ID;
    }
    // Create a valid post name.
    if (empty($post_name)) {
        $post_name = sanitize_title($post_title);
    } else {
        $post_name = sanitize_title($post_name);
    }
    // expected_slashed ($post_name)
    $post_name_check = $wpdb->get_var($wpdb->prepare("SELECT post_name FROM {$wpdb->posts} WHERE post_name = '{$post_name}' AND post_status = 'inherit' AND ID != %d LIMIT 1", $post_ID));
    if ($post_name_check) {
        $suffix = 2;
        while ($post_name_check) {
            $alt_post_name = $post_name . "-{$suffix}";
            // expected_slashed ($alt_post_name, $post_name)
            $post_name_check = $wpdb->get_var($wpdb->prepare("SELECT post_name FROM {$wpdb->posts} WHERE post_name = '{$alt_post_name}' AND post_status = 'inherit' AND ID != %d AND post_parent = %d LIMIT 1", $post_ID, $post_parent));
            $suffix++;
        }
        $post_name = $alt_post_name;
    }
    if (empty($post_date)) {
        $post_date = current_time('mysql');
    }
    if (empty($post_date_gmt)) {
        $post_date_gmt = current_time('mysql', 1);
    }
    if (empty($post_modified)) {
        $post_modified = $post_date;
    }
    if (empty($post_modified_gmt)) {
        $post_modified_gmt = $post_date_gmt;
    }
    if (empty($comment_status)) {
        if ($update) {
            $comment_status = 'closed';
        } else {
            $comment_status = get_option('default_comment_status');
        }
    }
    if (empty($ping_status)) {
        $ping_status = get_option('default_ping_status');
    }
    if (isset($to_ping)) {
        $to_ping = preg_replace('|\\s+|', "\n", $to_ping);
    } else {
        $to_ping = '';
    }
    if (isset($post_parent)) {
        $post_parent = (int) $post_parent;
    } else {
        $post_parent = 0;
    }
    if (isset($menu_order)) {
        $menu_order = (int) $menu_order;
    } else {
        $menu_order = 0;
    }
    if (!isset($post_password)) {
        $post_password = '';
    }
    if (!isset($pinged)) {
        $pinged = '';
    }
    // expected_slashed (everything!)
    $data = compact(array('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'));
    $data = stripslashes_deep($data);
    if ($update) {
        $wpdb->update($wpdb->posts, $data, array('ID' => $post_ID));
    } else {
        $wpdb->insert($wpdb->posts, $data);
        $post_ID = (int) $wpdb->insert_id;
    }
    if (empty($post_name)) {
        $post_name = sanitize_title($post_title, $post_ID);
        $wpdb->update($wpdb->posts, compact("post_name"), array('ID' => $post_ID));
    }
    wp_set_post_categories($post_ID, $post_category);
    if ($file) {
        update_attached_file($post_ID, $file);
    }
    clean_post_cache($post_ID);
    if ($update) {
        do_action('edit_attachment', $post_ID);
    } else {
        do_action('add_attachment', $post_ID);
    }
    return $post_ID;
}
 function attach_image($post_id, $uploaded_file, $is_update)
 {
     // Get the path to the upload directory.
     $wp_upload_dir = wp_upload_dir();
     $filename = $wp_upload_dir['path'] . '/' . $uploaded_file;
     // Check the type of file. We'll use this as the 'post_mime_type'.
     $filetype = wp_check_filetype(basename($filename), null);
     $guid = $wp_upload_dir['url'] . '/' . basename($filename);
     // Prepare an array of post data for the attachment.
     $attachment = array('guid' => $guid, 'post_mime_type' => $filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($filename)), 'post_content' => '', 'post_status' => 'inherit');
     // Insert the attachment.
     $attach_id = wp_insert_attachment($attachment, $filename, $post_id);
     if ($is_update) {
         update_attached_file($attach_id, $filename);
     }
     // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
     require_once ABSPATH . 'wp-admin/includes/image.php';
     // Generate the metadata for the attachment, and update the database record.
     $attach_data = wp_generate_attachment_metadata($attach_id, $filename);
     wp_update_attachment_metadata($attach_id, $attach_data);
     set_post_thumbnail($post_id, $attach_id);
 }
Esempio n. 19
0
	function woo_ce_read_export_file( $post = false ) {

		if( empty( $post ) ) {
			if( isset( $_GET['post'] ) )
				$post = get_post( $_GET['post'] );
		}

		if( $post->post_type != 'attachment' )
			return false;

		// Check if the Post matches one of our Post Mime Types
		if( !in_array( $post->post_mime_type, array( 'text/csv', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/xml', 'application/rss+xml' ) ) )
			return false;

		$filepath = get_attached_file( $post->ID );

		// We can only read CSV and XML file types, the others are encoded
		if( in_array( $post->post_mime_type, array( 'text/csv', 'application/xml', 'application/rss+xml' ) ) ) {

			$contents = __( 'No export entries were found, please try again with different export filters.', 'woo_ce' );
			if( file_exists( $filepath ) ) {
				$contents = file_get_contents( $filepath );
			} else {
				// This resets the _wp_attached_file Post meta key to the correct value
				update_attached_file( $post->ID, $post->guid );
				// Try grabbing the file contents again
				$filepath = get_attached_file( $post->ID );
				if( file_exists( $filepath ) ) {
					$handle = fopen( $filepath, "r" );
					$contents = stream_get_contents( $handle );
					fclose( $handle );
				}
			}
			if( !empty( $contents ) )
				include_once( WOO_CD_PATH . 'templates/admin/media-csv_file.php' );

		}

		// We can still show the Export Details for any supported Post Mime Type
		$export_type = get_post_meta( $post->ID, '_woo_export_type', true );
		$columns = get_post_meta( $post->ID, '_woo_columns', true );
		$rows = get_post_meta( $post->ID, '_woo_rows', true );
		$start_time = get_post_meta( $post->ID, '_woo_start_time', true );
		$end_time = get_post_meta( $post->ID, '_woo_end_time', true );
		$idle_memory_start = get_post_meta( $post->ID, '_woo_idle_memory_start', true );
		$data_memory_start = get_post_meta( $post->ID, '_woo_data_memory_start', true );
		$data_memory_end = get_post_meta( $post->ID, '_woo_data_memory_end', true );
		$idle_memory_end = get_post_meta( $post->ID, '_woo_idle_memory_end', true );

		include_once( WOO_CD_PATH . 'templates/admin/media-export_details.php' );

	}
/**
 * Function to fetch the image from URL and generate the required thumbnails
 */
function apt_generate_post_thumb($matches, $key, $post_content, $post_id)
{
    // Make sure to assign correct title to the image. Extract it from img tag
    $imageTitle = '';
    preg_match_all('/<\\s*img [^\\>]*title\\s*=\\s*[\\""\']?([^\\""\'>]*)/i', $post_content, $matchesTitle);
    if (count($matchesTitle) && isset($matchesTitle[1])) {
        $imageTitle = $matchesTitle[1][$key];
    }
    // Get the URL now for further processing
    $imageUrl = $matches[1][$key];
    // Get the file name
    $filename = substr($imageUrl, strrpos($imageUrl, '/') + 1);
    if (!(($uploads = wp_upload_dir(current_time('mysql'))) && false === $uploads['error'])) {
        return null;
    }
    // Generate unique file name
    $filename = wp_unique_filename($uploads['path'], $filename);
    // Move the file to the uploads dir
    $new_file = $uploads['path'] . "/{$filename}";
    if (!ini_get('allow_url_fopen')) {
        $file_data = curl_get_file_contents($imageUrl);
    } else {
        $file_data = @file_get_contents($imageUrl);
    }
    if (!$file_data) {
        return null;
    }
    file_put_contents($new_file, $file_data);
    // Set correct file permissions
    $stat = stat(dirname($new_file));
    $perms = $stat['mode'] & 0666;
    @chmod($new_file, $perms);
    // Get the file type. Must to use it as a post thumbnail.
    $wp_filetype = wp_check_filetype($filename, $mimes);
    extract($wp_filetype);
    // No file type! No point to proceed further
    if ((!$type || !$ext) && !current_user_can('unfiltered_upload')) {
        return null;
    }
    // Compute the URL
    $url = $uploads['url'] . "/{$filename}";
    // Construct the attachment array
    $attachment = array('post_mime_type' => $type, 'guid' => $url, 'post_parent' => null, 'post_title' => $imageTitle, 'post_content' => '');
    $thumb_id = wp_insert_attachment($attachment, $file, $post_id);
    if (!is_wp_error($thumb_id)) {
        require_once ABSPATH . '/wp-admin/includes/image.php';
        // Added fix by misthero as suggested
        wp_update_attachment_metadata($thumb_id, wp_generate_attachment_metadata($thumb_id, $new_file));
        update_attached_file($thumb_id, $new_file);
        return $thumb_id;
    }
    return null;
}
Esempio n. 21
0
function wp_save_image($post_id)
{
    $return = new stdClass();
    $success = $delete = $scaled = $nocrop = false;
    $post = get_post($post_id);
    @ini_set('memory_limit', apply_filters('admin_memory_limit', WP_MAX_MEMORY_LIMIT));
    $img = load_image_to_edit($post_id, $post->post_mime_type);
    if (!is_resource($img)) {
        $return->error = esc_js(__('Unable to create new image.'));
        return $return;
    }
    $fwidth = !empty($_REQUEST['fwidth']) ? intval($_REQUEST['fwidth']) : 0;
    $fheight = !empty($_REQUEST['fheight']) ? intval($_REQUEST['fheight']) : 0;
    $target = !empty($_REQUEST['target']) ? preg_replace('/[^a-z0-9_-]+/i', '', $_REQUEST['target']) : '';
    $scale = !empty($_REQUEST['do']) && 'scale' == $_REQUEST['do'];
    if ($scale && $fwidth > 0 && $fheight > 0) {
        $sX = imagesx($img);
        $sY = imagesy($img);
        // check if it has roughly the same w / h ratio
        $diff = round($sX / $sY, 2) - round($fwidth / $fheight, 2);
        if (-0.1 < $diff && $diff < 0.1) {
            // scale the full size image
            $dst = wp_imagecreatetruecolor($fwidth, $fheight);
            if (imagecopyresampled($dst, $img, 0, 0, 0, 0, $fwidth, $fheight, $sX, $sY)) {
                imagedestroy($img);
                $img = $dst;
                $scaled = true;
            }
        }
        if (!$scaled) {
            $return->error = esc_js(__('Error while saving the scaled image. Please reload the page and try again.'));
            return $return;
        }
    } elseif (!empty($_REQUEST['history'])) {
        $changes = json_decode(stripslashes($_REQUEST['history']));
        if ($changes) {
            $img = image_edit_apply_changes($img, $changes);
        }
    } else {
        $return->error = esc_js(__('Nothing to save, the image has not changed.'));
        return $return;
    }
    $meta = wp_get_attachment_metadata($post_id);
    $backup_sizes = get_post_meta($post->ID, '_wp_attachment_backup_sizes', true);
    if (!is_array($meta)) {
        $return->error = esc_js(__('Image data does not exist. Please re-upload the image.'));
        return $return;
    }
    if (!is_array($backup_sizes)) {
        $backup_sizes = array();
    }
    // generate new filename
    $path = get_attached_file($post_id);
    $path_parts = pathinfo($path);
    $filename = $path_parts['filename'];
    $suffix = time() . rand(100, 999);
    if (defined('IMAGE_EDIT_OVERWRITE') && IMAGE_EDIT_OVERWRITE && isset($backup_sizes['full-orig']) && $backup_sizes['full-orig']['file'] != $path_parts['basename']) {
        if ('thumbnail' == $target) {
            $new_path = "{$path_parts['dirname']}/{$filename}-temp.{$path_parts['extension']}";
        } else {
            $new_path = $path;
        }
    } else {
        while (true) {
            $filename = preg_replace('/-e([0-9]+)$/', '', $filename);
            $filename .= "-e{$suffix}";
            $new_filename = "{$filename}.{$path_parts['extension']}";
            $new_path = "{$path_parts['dirname']}/{$new_filename}";
            if (file_exists($new_path)) {
                $suffix++;
            } else {
                break;
            }
        }
    }
    // save the full-size file, also needed to create sub-sizes
    if (!wp_save_image_file($new_path, $img, $post->post_mime_type, $post_id)) {
        $return->error = esc_js(__('Unable to save the image.'));
        return $return;
    }
    if ('nothumb' == $target || 'all' == $target || 'full' == $target || $scaled) {
        $tag = false;
        if (isset($backup_sizes['full-orig'])) {
            if ((!defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE) && $backup_sizes['full-orig']['file'] != $path_parts['basename']) {
                $tag = "full-{$suffix}";
            }
        } else {
            $tag = 'full-orig';
        }
        if ($tag) {
            $backup_sizes[$tag] = array('width' => $meta['width'], 'height' => $meta['height'], 'file' => $path_parts['basename']);
        }
        $success = update_attached_file($post_id, $new_path);
        $meta['file'] = _wp_relative_upload_path($new_path);
        $meta['width'] = imagesx($img);
        $meta['height'] = imagesy($img);
        list($uwidth, $uheight) = wp_constrain_dimensions($meta['width'], $meta['height'], 128, 96);
        $meta['hwstring_small'] = "height='{$uheight}' width='{$uwidth}'";
        if ($success && ('nothumb' == $target || 'all' == $target)) {
            $sizes = get_intermediate_image_sizes();
            if ('nothumb' == $target) {
                $sizes = array_diff($sizes, array('thumbnail'));
            }
        }
        $return->fw = $meta['width'];
        $return->fh = $meta['height'];
    } elseif ('thumbnail' == $target) {
        $sizes = array('thumbnail');
        $success = $delete = $nocrop = true;
    }
    if (isset($sizes)) {
        foreach ($sizes as $size) {
            $tag = false;
            if (isset($meta['sizes'][$size])) {
                if (isset($backup_sizes["{$size}-orig"])) {
                    if ((!defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE) && $backup_sizes["{$size}-orig"]['file'] != $meta['sizes'][$size]['file']) {
                        $tag = "{$size}-{$suffix}";
                    }
                } else {
                    $tag = "{$size}-orig";
                }
                if ($tag) {
                    $backup_sizes[$tag] = $meta['sizes'][$size];
                }
            }
            $crop = $nocrop ? false : get_option("{$size}_crop");
            $resized = image_make_intermediate_size($new_path, get_option("{$size}_size_w"), get_option("{$size}_size_h"), $crop);
            if ($resized) {
                $meta['sizes'][$size] = $resized;
            } else {
                unset($meta['sizes'][$size]);
            }
        }
    }
    if ($success) {
        wp_update_attachment_metadata($post_id, $meta);
        update_post_meta($post_id, '_wp_attachment_backup_sizes', $backup_sizes);
        if ($target == 'thumbnail' || $target == 'all' || $target == 'full') {
            $file_url = wp_get_attachment_url($post_id);
            if ($thumb = $meta['sizes']['thumbnail']) {
                $return->thumbnail = path_join(dirname($file_url), $thumb['file']);
            } else {
                $return->thumbnail = "{$file_url}?w=128&h=128";
            }
        }
    } else {
        $delete = true;
    }
    if ($delete) {
        $delpath = apply_filters('wp_delete_file', $new_path);
        @unlink($delpath);
    }
    imagedestroy($img);
    $return->msg = esc_js(__('Image saved'));
    return $return;
}
Esempio n. 22
0
function wp_insert_attachment($object, $file = false, $parent = 0)
{
    global $wpdb, $user_ID;
    $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID, 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '');
    $object = wp_parse_args($object, $defaults);
    if (!empty($parent)) {
        $object['post_parent'] = $parent;
    }
    $object = sanitize_post($object, 'db');
    // export array as variables
    extract($object, EXTR_SKIP);
    // Make sure we set a valid category
    if (0 == count($post_category) || !is_array($post_category)) {
        $post_category = array(get_option('default_category'));
    }
    if (empty($post_author)) {
        $post_author = $user_ID;
    }
    $post_type = 'attachment';
    $post_status = 'inherit';
    // Are we updating or creating?
    $update = false;
    if (!empty($ID)) {
        $update = true;
        $post_ID = (int) $ID;
    }
    // Create a valid post name.
    if (empty($post_name)) {
        $post_name = sanitize_title($post_title);
    } else {
        $post_name = sanitize_title($post_name);
    }
    $post_name_check = $wpdb->get_var("SELECT post_name FROM {$wpdb->posts} WHERE post_name = '{$post_name}' AND post_status = 'inherit' AND ID != '{$post_ID}' LIMIT 1");
    if ($post_name_check) {
        $suffix = 2;
        while ($post_name_check) {
            $alt_post_name = $post_name . "-{$suffix}";
            $post_name_check = $wpdb->get_var("SELECT post_name FROM {$wpdb->posts} WHERE post_name = '{$alt_post_name}' AND post_status = 'inherit' AND ID != '{$post_ID}' AND post_parent = '{$post_parent}' LIMIT 1");
            $suffix++;
        }
        $post_name = $alt_post_name;
    }
    if (empty($post_date)) {
        $post_date = current_time('mysql');
    }
    if (empty($post_date_gmt)) {
        $post_date_gmt = current_time('mysql', 1);
    }
    if (empty($comment_status)) {
        if ($update) {
            $comment_status = 'closed';
        } else {
            $comment_status = get_option('default_comment_status');
        }
    }
    if (empty($ping_status)) {
        $ping_status = get_option('default_ping_status');
    }
    if (isset($to_ping)) {
        $to_ping = preg_replace('|\\s+|', "\n", $to_ping);
    } else {
        $to_ping = '';
    }
    if (isset($post_parent)) {
        $post_parent = (int) $post_parent;
    } else {
        $post_parent = 0;
    }
    if (isset($menu_order)) {
        $menu_order = (int) $menu_order;
    } else {
        $menu_order = 0;
    }
    if (!isset($post_password)) {
        $post_password = '';
    }
    if (!isset($pinged)) {
        $pinged = '';
    }
    if ($update) {
        $wpdb->query("UPDATE {$wpdb->posts} SET\n\t\t\tpost_author = '{$post_author}',\n\t\t\tpost_date = '{$post_date}',\n\t\t\tpost_date_gmt = '{$post_date_gmt}',\n\t\t\tpost_content = '{$post_content}',\n\t\t\tpost_content_filtered = '{$post_content_filtered}',\n\t\t\tpost_title = '{$post_title}',\n\t\t\tpost_excerpt = '{$post_excerpt}',\n\t\t\tpost_status = '{$post_status}',\n\t\t\tpost_type = '{$post_type}',\n\t\t\tcomment_status = '{$comment_status}',\n\t\t\tping_status = '{$ping_status}',\n\t\t\tpost_password = '******',\n\t\t\tpost_name = '{$post_name}',\n\t\t\tto_ping = '{$to_ping}',\n\t\t\tpinged = '{$pinged}',\n\t\t\tpost_modified = '" . current_time('mysql') . "',\n\t\t\tpost_modified_gmt = '" . current_time('mysql', 1) . "',\n\t\t\tpost_parent = '{$post_parent}',\n\t\t\tmenu_order = '{$menu_order}',\n\t\t\tpost_mime_type = '{$post_mime_type}',\n\t\t\tguid = '{$guid}'\n\t\t\tWHERE ID = {$post_ID}");
    } else {
        $wpdb->query("INSERT INTO {$wpdb->posts}\n\t\t\t(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)\n\t\t\tVALUES\n\t\t\t('{$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_date}', '{$post_date_gmt}', '{$post_parent}', '{$menu_order}', '{$post_mime_type}', '{$guid}')");
        $post_ID = (int) $wpdb->insert_id;
    }
    if (empty($post_name)) {
        $post_name = sanitize_title($post_title, $post_ID);
        $wpdb->query("UPDATE {$wpdb->posts} SET post_name = '{$post_name}' WHERE ID = '{$post_ID}'");
    }
    wp_set_post_categories($post_ID, $post_category);
    if ($file) {
        update_attached_file($post_ID, $file);
    }
    clean_post_cache($post_ID);
    if ($update) {
        do_action('edit_attachment', $post_ID);
    } else {
        do_action('add_attachment', $post_ID);
    }
    return $post_ID;
}
Esempio n. 23
0
function upgrade_160()
{
    global $wpdb, $table_prefix, $wp_current_db_version;
    $users = $wpdb->get_results("SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = '{$table_prefix}capabilities'", ARRAY_A);
    upgrade_160_helper($users);
    $users = $wpdb->get_results("SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = '{$table_prefix}user_level'", ARRAY_A);
    upgrade_160_helper($users);
    $old_user_fields = array('user_firstname', 'user_lastname', 'user_icq', 'user_aim', 'user_msn', 'user_yim', 'user_idmode', 'user_ip', 'user_domain', 'user_browser', 'user_description', 'user_nickname', 'user_level');
    $wpdb->hide_errors();
    foreach ($old_user_fields as $old) {
        $wpdb->query("ALTER TABLE {$wpdb->users} DROP {$old}");
    }
    $wpdb->show_errors();
    // populate comment_count field of posts table
    $comments = $wpdb->get_results("SELECT comment_post_ID, COUNT(*) as c FROM {$wpdb->comments} WHERE comment_approved = '1' GROUP BY comment_post_ID");
    if (is_array($comments)) {
        foreach ($comments as $comment) {
            $wpdb->update($wpdb->posts, array('comment_count' => $comment->c), array('ID' => $comment->comment_post_ID));
        }
    }
    // Some alpha versions used a post status of object instead of attachment and put
    // the mime type in post_type instead of post_mime_type.
    if ($wp_current_db_version > 2541 && $wp_current_db_version <= 3091) {
        $objects = $wpdb->get_results("SELECT ID, post_type FROM {$wpdb->posts} WHERE post_status = 'object'");
        foreach ($objects as $object) {
            $wpdb->update($wpdb->posts, array('post_status' => 'attachment', 'post_mime_type' => $object->post_type, 'post_type' => ''), array('ID' => $object->ID));
            $meta = get_post_meta($object->ID, 'imagedata', true);
            if (!empty($meta['file'])) {
                update_attached_file($object->ID, $meta['file']);
            }
        }
    }
}
Esempio n. 24
0
/**
 * Insert an attachment.
 *
 * If you set the 'ID' in the $object parameter, it will mean that you are
 * updating and attempt to update the attachment. You can also set the
 * attachment name or title by setting the key 'post_name' or 'post_title'.
 *
 * You can set the dates for the attachment manually by setting the 'post_date'
 * and 'post_date_gmt' keys' values.
 *
 * By default, the comments will use the default settings for whether the
 * comments are allowed. You can close them manually or keep them open by
 * setting the value for the 'comment_status' key.
 *
 * The $object parameter can have the following:
 *     'post_status'   - Default is 'draft'. Can not be overridden, set the same as parent post.
 *     'post_type'     - Default is 'post', will be set to attachment. Can not override.
 *     'post_author'   - Default is current user ID. The ID of the user, who added the attachment.
 *     'ping_status'   - Default is the value in default ping status option. Whether the attachment
 *                       can accept pings.
 *     'post_parent'   - Default is 0. Can use $parent parameter or set this for the post it belongs
 *                       to, if any.
 *     'menu_order'    - Default is 0. The order it is displayed.
 *     'to_ping'       - Whether to ping.
 *     'pinged'        - Default is empty string.
 *     'post_password' - Default is empty string. The password to access the attachment.
 *     'guid'          - Global Unique ID for referencing the attachment.
 *     'post_content_filtered' - Attachment post content filtered.
 *     'post_excerpt'  - Attachment excerpt.
 *
 * @since 2.0.0
 * @uses $wpdb
 * @uses do_action() Calls 'edit_attachment' on $post_ID if this is an update.
 * @uses do_action() Calls 'add_attachment' on $post_ID if this is not an update.
 *
 * @param string|array $object Arguments to override defaults.
 * @param string $file Optional filename.
 * @param int $parent Parent post ID.
 * @return int Attachment ID.
 */
function wp_insert_attachment($object, $file = false, $parent = 0)
{
    global $wpdb;
    $user_id = get_current_user_id();
    $defaults = array('post_status' => 'inherit', 'post_type' => 'post', 'post_author' => $user_id, 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 'post_title' => '', 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '', 'post_content' => '', 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0, 'context' => '');
    $object = wp_parse_args($object, $defaults);
    if (!empty($parent)) {
        $object['post_parent'] = $parent;
    }
    unset($object['filter']);
    $object = sanitize_post($object, 'db');
    // export array as variables
    extract($object, EXTR_SKIP);
    if (empty($post_author)) {
        $post_author = $user_id;
    }
    $post_type = 'attachment';
    if (!in_array($post_status, array('inherit', 'private'))) {
        $post_status = 'inherit';
    }
    if (!empty($post_category)) {
        $post_category = array_filter($post_category);
    }
    // Filter out empty terms
    // Make sure we set a valid category.
    if (empty($post_category) || 0 == count($post_category) || !is_array($post_category)) {
        $post_category = array();
    }
    // Are we updating or creating?
    if (!empty($ID)) {
        $update = true;
        $post_ID = (int) $ID;
    } else {
        $update = false;
        $post_ID = 0;
    }
    // Create a valid post name.
    if (empty($post_name)) {
        $post_name = sanitize_title($post_title);
    } else {
        $post_name = sanitize_title($post_name);
    }
    // expected_slashed ($post_name)
    $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
    if (empty($post_date)) {
        $post_date = current_time('mysql');
    }
    if (empty($post_date_gmt)) {
        $post_date_gmt = current_time('mysql', 1);
    }
    if (empty($post_modified)) {
        $post_modified = $post_date;
    }
    if (empty($post_modified_gmt)) {
        $post_modified_gmt = $post_date_gmt;
    }
    if (empty($comment_status)) {
        if ($update) {
            $comment_status = 'closed';
        } else {
            $comment_status = get_option('default_comment_status');
        }
    }
    if (empty($ping_status)) {
        $ping_status = get_option('default_ping_status');
    }
    if (isset($to_ping)) {
        $to_ping = preg_replace('|\\s+|', "\n", $to_ping);
    } else {
        $to_ping = '';
    }
    if (isset($post_parent)) {
        $post_parent = (int) $post_parent;
    } else {
        $post_parent = 0;
    }
    if (isset($menu_order)) {
        $menu_order = (int) $menu_order;
    } else {
        $menu_order = 0;
    }
    if (!isset($post_password)) {
        $post_password = '';
    }
    if (!isset($pinged)) {
        $pinged = '';
    }
    // expected_slashed (everything!)
    $data = compact(array('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'));
    $data = wp_unslash($data);
    if ($update) {
        $wpdb->update($wpdb->posts, $data, array('ID' => $post_ID));
    } 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;
            }
        }
        $wpdb->insert($wpdb->posts, $data);
        $post_ID = (int) $wpdb->insert_id;
    }
    if (empty($post_name)) {
        $post_name = sanitize_title($post_title, $post_ID);
        $wpdb->update($wpdb->posts, compact("post_name"), array('ID' => $post_ID));
    }
    if (is_object_in_taxonomy($post_type, 'category')) {
        wp_set_post_categories($post_ID, $post_category);
    }
    if (isset($tags_input) && is_object_in_taxonomy($post_type, 'post_tag')) {
        wp_set_post_tags($post_ID, $tags_input);
    }
    // support for all custom taxonomies
    if (!empty($tax_input)) {
        foreach ($tax_input as $taxonomy => $tags) {
            $taxonomy_obj = get_taxonomy($taxonomy);
            if (is_array($tags)) {
                // array = hierarchical, string = non-hierarchical.
                $tags = array_filter($tags);
            }
            if (current_user_can($taxonomy_obj->cap->assign_terms)) {
                wp_set_post_terms($post_ID, $tags, $taxonomy);
            }
        }
    }
    if ($file) {
        update_attached_file($post_ID, $file);
    }
    clean_post_cache($post_ID);
    if (!empty($context)) {
        add_post_meta($post_ID, '_wp_attachment_context', $context, true);
    }
    if ($update) {
        do_action('edit_attachment', $post_ID);
    } else {
        do_action('add_attachment', $post_ID);
    }
    return $post_ID;
}
        $sql = $wpdb->prepare("UPDATE {$postmeta_table_name} SET meta_value = '{$new_meta_name}' WHERE meta_key = '_wp_attached_file' AND post_id = %d;", (int) $_POST["ID"]);
        $wpdb->query($sql);
        // Make thumb and/or update metadata
        wp_update_attachment_metadata((int) $_POST["ID"], wp_generate_attachment_metadata((int) $_POST["ID"], $new_file));
        // Search-and-replace filename in post database
        $sql = $wpdb->prepare("SELECT ID, post_content FROM {$table_name} WHERE post_content LIKE %s;", '%' . $current_guid . '%');
        $rs = $wpdb->get_results($sql, ARRAY_A);
        foreach ($rs as $rows) {
            // replace old guid with new guid
            $post_content = $rows["post_content"];
            $post_content = addslashes(str_replace($current_guid, $new_guid, $post_content));
            $sql = $wpdb->prepare("UPDATE {$table_name} SET post_content = '{$post_content}' WHERE ID = %d;", $rows["ID"]);
            $wpdb->query($sql);
        }
        // Trigger possible updates on CDN and other plugins
        update_attached_file((int) $_POST["ID"], $new_file);
    }
    $returnurl = get_bloginfo("wpurl") . "/wp-admin/post.php?post={$_POST["ID"]}&action=edit&message=1";
    // Execute hook actions - thanks rubious for the suggestion!
    if (isset($new_guid)) {
        do_action("enable-media-replace-upload-done", $new_guid ? $new_guid : $current_guid);
    }
} else {
    //TODO Better error handling when no file is selected.
    //For now just go back to media management
    $returnurl = get_bloginfo("wpurl") . "/wp-admin/upload.php";
}
if (FORCE_SSL_ADMIN) {
    $returnurl = str_replace("http:", "https:", $returnurl);
}
//save redirection
Esempio n. 26
0
function fetch_thumbnail_image($matches, $key, $post_content, $post_id)
{
    $imageTitle = '';
    preg_match_all('/<\\s*img [^\\>]*title\\s*=\\s*[\\""\']?([^\\""\'>]*)/i', $post_content, $matchesTitle);
    if (count($matchesTitle) && isset($matchesTitle[1])) {
        $imageTitle = $matchesTitle[1][$key];
    }
    $imageUrl = $matches[1][$key];
    $filename = substr($imageUrl, strrpos($imageUrl, '/') + 1);
    if (!(($uploads = wp_upload_dir(current_time('mysql'))) && false === $uploads['error'])) {
        return null;
    }
    $filename = wp_unique_filename($uploads['path'], $filename);
    $new_file = $uploads['path'] . "/{$filename}";
    if (!ini_get('allow_url_fopen')) {
        $file_data = curl_get_file_contents($imageUrl);
    } else {
        if (WP_Filesystem()) {
            global $wp_filesystem;
            $file_data = @$wp_filesystem->get_contents($imageUrl);
        }
    }
    if (!$file_data) {
        return null;
    }
    if (WP_Filesystem()) {
        global $wp_filesystem;
        $wp_filesystem->put_contents($new_file, $file_data);
    }
    $stat = stat(dirname($new_file));
    $perms = $stat['mode'] & 0666;
    @chmod($new_file, $perms);
    $wp_filetype = wp_check_filetype($filename, $mimes);
    extract($wp_filetype);
    if ((!$type || !$ext) && !current_user_can('unfiltered_upload')) {
        return null;
    }
    $url = $uploads['url'] . "/{$filename}";
    $attachment = array('post_mime_type' => $type, 'guid' => $url, 'post_parent' => null, 'post_title' => $imageTitle, 'post_content' => '');
    $thumb_id = wp_insert_attachment($attachment, $file, $post_id);
    if (!is_wp_error($thumb_id)) {
        wp_update_attachment_metadata($thumb_id, wp_generate_attachment_metadata($thumb_id, $new_file));
        update_attached_file($thumb_id, $new_file);
        return $thumb_id;
    }
    return null;
}
Esempio n. 27
0
/**
 * Execute changes made in WordPress 2.0.
 *
 * @since 2.0.0
 */
function upgrade_160()
{
    global $wpdb, $wp_current_db_version;
    populate_roles_160();
    $users = $wpdb->get_results("SELECT * FROM {$wpdb->users}");
    foreach ($users as $user) {
        if (!empty($user->user_firstname)) {
            update_user_meta($user->ID, 'first_name', $wpdb->escape($user->user_firstname));
        }
        if (!empty($user->user_lastname)) {
            update_user_meta($user->ID, 'last_name', $wpdb->escape($user->user_lastname));
        }
        if (!empty($user->user_nickname)) {
            update_user_meta($user->ID, 'nickname', $wpdb->escape($user->user_nickname));
        }
        if (!empty($user->user_level)) {
            update_user_meta($user->ID, $wpdb->prefix . 'user_level', $user->user_level);
        }
        if (!empty($user->user_icq)) {
            update_user_meta($user->ID, 'icq', $wpdb->escape($user->user_icq));
        }
        if (!empty($user->user_aim)) {
            update_user_meta($user->ID, 'aim', $wpdb->escape($user->user_aim));
        }
        if (!empty($user->user_msn)) {
            update_user_meta($user->ID, 'msn', $wpdb->escape($user->user_msn));
        }
        if (!empty($user->user_yim)) {
            update_user_meta($user->ID, 'yim', $wpdb->escape($user->user_icq));
        }
        if (!empty($user->user_description)) {
            update_user_meta($user->ID, 'description', $wpdb->escape($user->user_description));
        }
        if (isset($user->user_idmode)) {
            $idmode = $user->user_idmode;
            if ($idmode == 'nickname') {
                $id = $user->user_nickname;
            }
            if ($idmode == 'login') {
                $id = $user->user_login;
            }
            if ($idmode == 'firstname') {
                $id = $user->user_firstname;
            }
            if ($idmode == 'lastname') {
                $id = $user->user_lastname;
            }
            if ($idmode == 'namefl') {
                $id = $user->user_firstname . ' ' . $user->user_lastname;
            }
            if ($idmode == 'namelf') {
                $id = $user->user_lastname . ' ' . $user->user_firstname;
            }
            if (!$idmode) {
                $id = $user->user_nickname;
            }
            $wpdb->update($wpdb->users, array('display_name' => $id), array('ID' => $user->ID));
        }
        // FIXME: RESET_CAPS is temporary code to reset roles and caps if flag is set.
        $caps = get_user_meta($user->ID, $wpdb->prefix . 'capabilities');
        if (empty($caps) || defined('RESET_CAPS')) {
            $level = get_user_meta($user->ID, $wpdb->prefix . 'user_level', true);
            $role = translate_level_to_role($level);
            update_user_meta($user->ID, $wpdb->prefix . 'capabilities', array($role => true));
        }
    }
    $old_user_fields = array('user_firstname', 'user_lastname', 'user_icq', 'user_aim', 'user_msn', 'user_yim', 'user_idmode', 'user_ip', 'user_domain', 'user_browser', 'user_description', 'user_nickname', 'user_level');
    $wpdb->hide_errors();
    foreach ($old_user_fields as $old) {
        $wpdb->query("ALTER TABLE {$wpdb->users} DROP {$old}");
    }
    $wpdb->show_errors();
    // populate comment_count field of posts table
    $comments = $wpdb->get_results("SELECT comment_post_ID, COUNT(*) as c FROM {$wpdb->comments} WHERE comment_approved = '1' GROUP BY comment_post_ID");
    if (is_array($comments)) {
        foreach ($comments as $comment) {
            $wpdb->update($wpdb->posts, array('comment_count' => $comment->c), array('ID' => $comment->comment_post_ID));
        }
    }
    // Some alpha versions used a post status of object instead of attachment and put
    // the mime type in post_type instead of post_mime_type.
    if ($wp_current_db_version > 2541 && $wp_current_db_version <= 3091) {
        $objects = $wpdb->get_results("SELECT ID, post_type FROM {$wpdb->posts} WHERE post_status = 'object'");
        foreach ($objects as $object) {
            $wpdb->update($wpdb->posts, array('post_status' => 'attachment', 'post_mime_type' => $object->post_type, 'post_type' => ''), array('ID' => $object->ID));
            $meta = get_post_meta($object->ID, 'imagedata', true);
            if (!empty($meta['file'])) {
                update_attached_file($object->ID, $meta['file']);
            }
        }
    }
}
Esempio n. 28
0
function wp_insert_attachment($object, $file = false, $post_parent = 0) {
	global $wpdb, $user_ID;

	if ( is_object($object) )
		$object = get_object_vars($object);

	// Export array as variables
	extract($object);

	// Get the basics.
	$post_content    = apply_filters('content_save_pre',   $post_content);
	$post_content_filtered = apply_filters('content_filtered_save_pre',   $post_content_filtered);
	$post_excerpt    = apply_filters('excerpt_save_pre',   $post_excerpt);
	$post_title      = apply_filters('title_save_pre',     $post_title);
	$post_category   = apply_filters('category_save_pre',  $post_category);
	$post_name       = apply_filters('name_save_pre',      $post_name);
	$comment_status  = apply_filters('comment_status_pre', $comment_status);
	$ping_status     = apply_filters('ping_status_pre',    $ping_status);
	$post_mime_type  = apply_filters('post_mime_type_pre', $post_mime_type);

	// Make sure we set a valid category
	if (0 == count($post_category) || !is_array($post_category)) {
		$post_category = array(get_option('default_category'));
	}
	$post_cat = $post_category[0];

	if ( empty($post_author) )
		$post_author = $user_ID;

	$post_type = 'attachment';
	$post_status = 'inherit';

	// Are we updating or creating?
	$update = false;
	if ( !empty($ID) ) {
		$update = true;
		$post_ID = (int) $ID;
	}

	// Create a valid post name.
	if ( empty($post_name) )
		$post_name = sanitize_title($post_title);
	else
		$post_name = sanitize_title($post_name);

	$post_name_check =
		$wpdb->get_var("SELECT post_name FROM $wpdb->posts WHERE post_name = '$post_name' AND post_status = 'inherit' AND ID != '$post_ID' LIMIT 1");

	if ($post_name_check) {
		$suffix = 2;
		while ($post_name_check) {
			$alt_post_name = $post_name . "-$suffix";
			$post_name_check = $wpdb->get_var("SELECT post_name FROM $wpdb->posts WHERE post_name = '$alt_post_name' AND post_status = 'inherit' AND ID != '$post_ID' AND post_parent = '$post_parent' LIMIT 1");
			$suffix++;
		}
		$post_name = $alt_post_name;
	}

	if (empty($post_date))
		$post_date = current_time('mysql');
	if (empty($post_date_gmt))
		$post_date_gmt = current_time('mysql', 1);

	if ( empty($comment_status) ) {
		if ( $update )
			$comment_status = 'closed';
		else
			$comment_status = get_option('default_comment_status');
	}
	if ( empty($ping_status) )
		$ping_status = get_option('default_ping_status');
	if ( empty($post_pingback) )
		$post_pingback = get_option('default_pingback_flag');

	if ( isset($to_ping) )
		$to_ping = preg_replace('|\s+|', "\n", $to_ping);
	else
		$to_ping = '';

	if ( isset($post_parent) )
		$post_parent = (int) $post_parent;
	else
		$post_parent = 0;

	if ( isset($menu_order) )
		$menu_order = (int) $menu_order;
	else
		$menu_order = 0;

	if ( !isset($post_password) )
		$post_password = '';

	if ( isset($to_ping) )
		$to_ping = preg_replace('|\s+|', "\n", $to_ping);
	else
		$to_ping = '';

	if ( ! isset($pinged) )
		$pinged = '';

	if ($update) {
		$wpdb->query(
			"UPDATE $wpdb->posts SET
			post_author = '$post_author',
			post_date = '$post_date',
			post_date_gmt = '$post_date_gmt',
			post_content = '$post_content',
			post_content_filtered = '$post_content_filtered',
			post_title = '$post_title',
			post_excerpt = '$post_excerpt',
			post_status = '$post_status',
			post_type = '$post_type',
			comment_status = '$comment_status',
			ping_status = '$ping_status',
			post_password = '******',
			post_name = '$post_name',
			to_ping = '$to_ping',
			pinged = '$pinged',
			post_modified = '".current_time('mysql')."',
			post_modified_gmt = '".current_time('mysql',1)."',
			post_parent = '$post_parent',
			menu_order = '$menu_order',
			post_mime_type = '$post_mime_type',
			guid = '$guid'
			WHERE ID = $post_ID");
	} else {
		$wpdb->query(
			"INSERT INTO $wpdb->posts
			(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)
			VALUES
			('$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_date', '$post_date_gmt', '$post_parent', '$menu_order', '$post_mime_type', '$guid')");
			$post_ID = (int) $wpdb->insert_id;
	}

	if ( empty($post_name) ) {
		$post_name = sanitize_title($post_title, $post_ID);
		$wpdb->query( "UPDATE $wpdb->posts SET post_name = '$post_name' WHERE ID = '$post_ID'" );
	}

	wp_set_post_categories($post_ID, $post_category);

	if ( $file )
		update_attached_file( $post_ID, $file );

	clean_post_cache($post_ID);

	if ( $update) {
		do_action('edit_attachment', $post_ID);
	} else {
		do_action('add_attachment', $post_ID);
	}

	return $post_ID;
}
Esempio n. 29
0
/**
 * Insert an attachment.
 *
 * If you set the 'ID' in the $object parameter, it will mean that you are
 * updating and attempt to update the attachment. You can also set the
 * attachment name or title by setting the key 'post_name' or 'post_title'.
 *
 * You can set the dates for the attachment manually by setting the 'post_date'
 * and 'post_date_gmt' keys' values.
 *
 * By default, the comments will use the default settings for whether the
 * comments are allowed. You can close them manually or keep them open by
 * setting the value for the 'comment_status' key.
 *
 * The $object parameter can have the following:
 *     'post_status'   - Default is 'draft'. Can not be overridden, set the same as parent post.
 *     'post_type'     - Default is 'post', will be set to attachment. Can not override.
 *     'post_author'   - Default is current user ID. The ID of the user, who added the attachment.
 *     'ping_status'   - Default is the value in default ping status option. Whether the attachment
 *                       can accept pings.
 *     'post_parent'   - Default is 0. Can use $parent parameter or set this for the post it belongs
 *                       to, if any.
 *     'menu_order'    - Default is 0. The order it is displayed.
 *     'to_ping'       - Whether to ping.
 *     'pinged'        - Default is empty string.
 *     'post_password' - Default is empty string. The password to access the attachment.
 *     'guid'          - Global Unique ID for referencing the attachment.
 *     'post_content_filtered' - Attachment post content filtered.
 *     'post_excerpt'  - Attachment excerpt.
 *
 * @since 2.0.0
 * @uses $wpdb
 * @uses $user_ID
 * @uses do_action() Calls 'edit_attachment' on $post_ID if this is an update.
 * @uses do_action() Calls 'add_attachment' on $post_ID if this is not an update.
 *
 * @param string|array $object Arguments to override defaults.
 * @param string $file Optional filename.
 * @param int $parent Parent post ID.
 * @return int Attachment ID.
 */
function wp_insert_attachment($object, $file = false, $parent = 0)
{
    global $wpdb, $user_ID;
    $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID, 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '', 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0);
    $object = wp_parse_args($object, $defaults);
    if (!empty($parent)) {
        $object['post_parent'] = $parent;
    }
    $object = sanitize_post($object, 'db');
    // export array as variables
    extract($object, EXTR_SKIP);
    if (empty($post_author)) {
        $post_author = $user_ID;
    }
    $post_type = 'attachment';
    $post_status = 'inherit';
    // Make sure we set a valid category.
    if (!isset($post_category) || 0 == count($post_category) || !is_array($post_category)) {
        // 'post' requires at least one category.
        if ('post' == $post_type) {
            $post_category = array(get_option('default_category'));
        } else {
            $post_category = array();
        }
    }
    // Are we updating or creating?
    if (!empty($ID)) {
        $update = true;
        $post_ID = (int) $ID;
    } else {
        $update = false;
        $post_ID = 0;
    }
    // Create a valid post name.
    if (empty($post_name)) {
        $post_name = sanitize_title($post_title);
    } else {
        $post_name = sanitize_title($post_name);
    }
    // expected_slashed ($post_name)
    $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
    if (empty($post_date)) {
        $post_date = current_time('mysql');
    }
    if (empty($post_date_gmt)) {
        $post_date_gmt = current_time('mysql', 1);
    }
    if (empty($post_modified)) {
        $post_modified = $post_date;
    }
    if (empty($post_modified_gmt)) {
        $post_modified_gmt = $post_date_gmt;
    }
    if (empty($comment_status)) {
        if ($update) {
            $comment_status = 'closed';
        } else {
            $comment_status = get_option('default_comment_status');
        }
    }
    if (empty($ping_status)) {
        $ping_status = get_option('default_ping_status');
    }
    if (isset($to_ping)) {
        $to_ping = preg_replace('|\\s+|', "\n", $to_ping);
    } else {
        $to_ping = '';
    }
    if (isset($post_parent)) {
        $post_parent = (int) $post_parent;
    } else {
        $post_parent = 0;
    }
    if (isset($menu_order)) {
        $menu_order = (int) $menu_order;
    } else {
        $menu_order = 0;
    }
    if (!isset($post_password)) {
        $post_password = '';
    }
    if (!isset($pinged)) {
        $pinged = '';
    }
    // expected_slashed (everything!)
    $data = compact(array('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'));
    $data = stripslashes_deep($data);
    if ($update) {
        $wpdb->update($wpdb->posts, $data, array('ID' => $post_ID));
    } 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;
            }
        }
        $wpdb->insert($wpdb->posts, $data);
        $post_ID = (int) $wpdb->insert_id;
    }
    if (empty($post_name)) {
        $post_name = sanitize_title($post_title, $post_ID);
        $wpdb->update($wpdb->posts, compact("post_name"), array('ID' => $post_ID));
    }
    wp_set_post_categories($post_ID, $post_category);
    if ($file) {
        update_attached_file($post_ID, $file);
    }
    clean_post_cache($post_ID);
    if (isset($post_parent) && $post_parent < 0) {
        add_post_meta($post_ID, '_wp_attachment_temp_parent', $post_parent, true);
    }
    if ($update) {
        do_action('edit_attachment', $post_ID);
    } else {
        do_action('add_attachment', $post_ID);
    }
    return $post_ID;
}
Esempio n. 30
0
/**
 * Update the attachment's meta data after being converted 
 */
function ewww_image_optimizer_update_attachment($meta, $ID)
{
    ewwwio_debug_message('<b>' . __FUNCTION__ . '()</b>');
    global $wpdb;
    // update the file location in the post metadata based on the new path stored in the attachment metadata
    update_attached_file($ID, $meta['file']);
    $guid = wp_get_attachment_url($ID);
    if (empty($meta['real_orig_file'])) {
        $old_guid = dirname($guid) . "/" . basename($meta['orig_file']);
    } else {
        $old_guid = dirname($guid) . "/" . basename($meta['real_orig_file']);
        unset($meta['real_orig_file']);
    }
    // construct the new guid based on the filename from the attachment metadata
    ewwwio_debug_message("old guid: {$old_guid}");
    ewwwio_debug_message("new guid: {$guid}");
    if (substr($old_guid, -1) == '/' || substr($guid, -1) == '/') {
        ewwwio_debug_message('could not obtain full url for current and previous image, bailing');
        return $meta;
    }
    // retrieve any posts that link the image
    $esql = $wpdb->prepare("SELECT ID, post_content FROM {$wpdb->posts} WHERE post_content LIKE '%%%s%%'", $old_guid);
    ewwwio_debug_message("using query: {$esql}");
    // while there are posts to process
    $rows = $wpdb->get_results($esql, ARRAY_A);
    foreach ($rows as $row) {
        // replace all occurences of the old guid with the new guid
        $post_content = str_replace($old_guid, $guid, $row['post_content']);
        ewwwio_debug_message("replacing {$old_guid} with {$guid} in post " . $row['ID']);
        // send the updated content back to the database
        $wpdb->update($wpdb->posts, array('post_content' => $post_content), array('ID' => $row['ID']));
    }
    if (isset($meta['sizes'])) {
        // for each resized version
        foreach ($meta['sizes'] as $size => $data) {
            // if the resize was converted
            if (isset($data['converted'])) {
                // generate the url for the old image
                if (empty($data['real_orig_file'])) {
                    $old_sguid = dirname($old_guid) . "/" . basename($data['orig_file']);
                } else {
                    $old_sguid = dirname($old_guid) . "/" . basename($data['real_orig_file']);
                    unset($meta['sizes'][$size]['real_orig_file']);
                }
                ewwwio_debug_message("processing: {$size}");
                ewwwio_debug_message("old sguid: {$old_sguid}");
                // generate the url for the new image
                $sguid = dirname($old_guid) . "/" . basename($data['file']);
                ewwwio_debug_message("new sguid: {$sguid}");
                if (substr($old_sguid, -1) == '/' || substr($sguid, -1) == '/') {
                    ewwwio_debug_message('could not obtain full url for current and previous resized image, bailing');
                    continue;
                }
                // retrieve any posts that link the resize
                $ersql = $wpdb->prepare("SELECT ID, post_content FROM {$wpdb->posts} WHERE post_content LIKE '%%%s%%'", $old_sguid);
                //ewwwio_debug_message( "using query: $ersql" );
                $rows = $wpdb->get_results($ersql, ARRAY_A);
                // while there are posts to process
                foreach ($rows as $row) {
                    // replace all occurences of the old guid with the new guid
                    $post_content = str_replace($old_sguid, $sguid, $row['post_content']);
                    ewwwio_debug_message("replacing {$old_sguid} with {$sguid} in post " . $row['ID']);
                    // send the updated content back to the database
                    $wpdb->update($wpdb->posts, array('post_content' => $post_content), array('ID' => $row['ID']));
                }
            }
        }
    }
    // if the new image is a JPG
    if (preg_match('/.jpg$/i', basename($meta['file']))) {
        // set the mimetype to JPG
        $mime = 'image/jpg';
    }
    // if the new image is a PNG
    if (preg_match('/.png$/i', basename($meta['file']))) {
        // set the mimetype to PNG
        $mime = 'image/png';
    }
    if (preg_match('/.gif$/i', basename($meta['file']))) {
        // set the mimetype to GIF
        $mime = 'image/gif';
    }
    // update the attachment post with the new mimetype and id
    wp_update_post(array('ID' => $ID, 'post_mime_type' => $mime));
    ewww_image_optimizer_debug_log();
    ewwwio_memory(__FUNCTION__);
    return $meta;
}