function cpm_action_delete_comic_and_post()
{
    global $cpm_config;
    $comic_file = pathinfo($_POST['comic'], PATHINFO_BASENAME);
    if (file_exists($cpm_config->path . '/' . $comic_file)) {
        if (($result = cpm_breakdown_comic_filename($comic_file)) !== false) {
            extract($result, EXTR_PREFIX_ALL, 'filename');
            $all_possible_posts = array();
            foreach (cpm_query_posts() as $comic_post) {
                if (date(CPM_DATE_FORMAT, strtotime($comic_post->post_date)) == $filename_date) {
                    $all_possible_posts[] = $comic_post->ID;
                }
            }
            if (count($all_possible_posts) > 1) {
                $cpm_config->messages[] = sprintf(__('There are multiple posts (%1$s) with the date %2$s in the comic categories. Please manually delete the posts.', 'comicpress-manager'), implode(", ", $all_possible_posts), $filename_date);
            } else {
                $delete_targets = array($cpm_config->path . '/' . $comic_file);
                foreach ($cpm_config->thumbs_folder_writable as $type => $value) {
                    $delete_targets[] = CPM_DOCUMENT_ROOT . '/' . $cpm_config->properties[$type . "_comic_folder"] . '/' . $comic_file;
                }
                foreach ($delete_targets as $target) {
                    @unlink($target);
                }
                if (count($all_possible_posts) == 0) {
                    $cpm_config->messages[] = sprintf(__("<strong>%s deleted.</strong>  No matching posts found.  Any associated thumbnails were also deleted.", 'comicpress-manager'), $comic_file);
                } else {
                    wp_delete_post($all_possible_posts[0]);
                    $cpm_config->messages[] = sprintf(__('<strong>%1$s and post %2$s deleted.</strong>  Any associated thumbnails were also deleted.', 'comicpress-manager'), $comic_file, $all_possible_posts[0]);
                }
                $cpm_config->comic_files = cpm_read_comics_folder();
            }
        }
    }
}
function cpm_action_multiple_upload_file()
{
    global $cpm_config;
    if (strtotime($_POST['time']) === false) {
        $cpm_config->warnings[] = sprintf(__('<strong>There was an error in the post time (%1$s)</strong>.  The time is not parseable by strtotime().', 'comicpress-manager'), $_POST['time']);
    } else {
        $files_to_handle = array();
        foreach ($_FILES as $name => $info) {
            if (strpos($name, "upload-") !== false) {
                if (is_uploaded_file($_FILES[$name]['tmp_name'])) {
                    $files_to_handle[] = $name;
                } else {
                    switch ($_FILES[$name]['error']) {
                        case UPLOAD_ERR_INI_SIZE:
                        case UPLOAD_ERR_FORM_SIZE:
                            $cpm_config->warnings[] = sprintf(__("<strong>The file %s was too large.</strong>  The max allowed filesize for uploads to your server is %s.", 'comicpress-manager'), $_FILES[$name]['name'], ini_get('upload_max_filesize'));
                            break;
                        case UPLOAD_ERR_NO_FILE:
                            break;
                        default:
                            $cpm_config->warnings[] = sprintf(__("<strong>There was an error in uploading %s.</strong>  The <a href='http://php.net/manual/en/features.file-upload.errors.php'>PHP upload error code</a> was %s.", 'comicpress-manager'), $_FILES[$name]['name'], $_FILES[$name]['error']);
                            break;
                    }
                }
            }
        }
        if (count($files_to_handle) > 0) {
            cpm_handle_file_uploads($files_to_handle);
            $cpm_config->comic_files = cpm_read_comics_folder();
        } else {
            $cpm_config->warnings[] = __("<strong>You didn't upload any files!</strong>", 'comicpress-manager');
        }
    }
}
    $cpm_config = new ComicPressConfig();
    cpm_read_information_and_check_config();
    if (isset($_REQUEST['blog_id']) && function_exists('switch_to_blog')) {
        switch_to_blog((int) $_REQUEST['blog_id']);
    }
    // TODO: handle different comic categories differently, this is still too geared
    // toward one blog/one comic...
    $all_post_dates = array();
    $format = CPM_DATE_FORMAT;
    if (isset($_POST['format'])) {
        $format = $_POST['format'];
    }
    foreach (cpm_query_posts() as $comic_post) {
        $all_post_dates[] = date($format, strtotime($comic_post->post_date));
    }
    $all_post_dates = array_unique($all_post_dates);
    ob_start();
    $missing_comic_count = 0;
    foreach (cpm_read_comics_folder() as $comic_file) {
        $comic_file = pathinfo($comic_file, PATHINFO_BASENAME);
        if (($result = cpm_breakdown_comic_filename($comic_file, $format)) !== false) {
            if (!in_array($result['date'], $all_post_dates)) {
                if (($post_hash = generate_post_hash($result['date'], $result['converted_title'])) !== false) {
                    $missing_comic_count++;
                }
            }
        }
    }
    header("X-JSON: {missing_posts: {$missing_comic_count}}");
    ob_end_flush();
}
function cpm_action_change_dates()
{
    global $cpm_config;
    $comic_posts_to_date_shift = array();
    $comic_files_to_date_shift = array();
    $comic_post_target_date_counts = array();
    $wp_date_string_length = strlen(date("Y-m-d"));
    $cpm_date_string_length = strlen(date(CPM_DATE_FORMAT));
    $cpm_config->is_cpm_managing_posts = true;
    // find all comic files that will be shifted
    foreach ($cpm_config->comic_files as $comic_file) {
        $comic_filename = pathinfo($comic_file, PATHINFO_BASENAME);
        $filename_info = cpm_breakdown_comic_filename($comic_filename);
        $key = md5($comic_file);
        if (isset($_POST['dates'][$key])) {
            if ($_POST['dates'][$key] != $filename_info['date']) {
                $timestamp = strtotime($_POST['dates'][$key]);
                if ($timestamp !== false && $timestamp !== -1) {
                    $target_date = date(CPM_DATE_FORMAT, $timestamp);
                    $new_comic_filename = $target_date . substr($comic_filename, $cpm_date_string_length);
                    $comic_posts_to_date_shift[strtotime($filename_info['date'])] = $timestamp;
                    if (!isset($comic_post_target_date_counts[$timestamp])) {
                        $comic_post_target_date_counts[$timestamp] = 0;
                    }
                    $comic_post_target_date_counts[$timestamp]++;
                    if (!isset($comic_files_to_date_shift[$timestamp])) {
                        $comic_files_to_date_shift[$timestamp] = array($comic_filename, $new_comic_filename);
                    }
                }
            }
        }
    }
    $comic_posts_to_change = array();
    $all_posts = cpm_query_posts();
    // get the target dates for all files to move
    if (count($comic_posts_to_date_shift) > 0) {
        foreach ($all_posts as $comic_post) {
            $post_date_day = substr($comic_post->post_date, 0, $wp_date_string_length);
            $post_date_day_timestamp = strtotime($post_date_day);
            if (isset($comic_posts_to_date_shift[$post_date_day_timestamp])) {
                if ($comic_post_target_date_counts[$comic_posts_to_date_shift[$post_date_day_timestamp]] == 1) {
                    $new_post_date = date("Y-m-d", $comic_posts_to_date_shift[$post_date_day_timestamp]) . substr($comic_post->post_date, $wp_date_string_length);
                    $comic_posts_to_change[$comic_post->ID] = array($comic_post, $new_post_date);
                }
            }
        }
    }
    $final_post_day_counts = array();
    // intersect all existing and potential new posts, counting how many
    // posts occur on each day
    foreach ($all_posts as $comic_post) {
        if (isset($comic_posts_to_change[$comic_post->ID])) {
            $date_to_use = $comic_posts_to_change[$comic_post->ID][1];
        } else {
            $date_to_use = $comic_post->post_date;
        }
        $day_to_use = strtotime(substr($date_to_use, 0, $wp_date_string_length));
        if (!isset($final_post_day_counts[$day_to_use])) {
            $final_post_day_counts[$day_to_use] = 0;
        }
        $final_post_day_counts[$day_to_use]++;
    }
    $posts_moved = array();
    // move what can be moved
    foreach ($comic_posts_to_change as $id => $info) {
        list($comic_post, $new_post_date) = $info;
        $new_post_day = strtotime(substr($new_post_date, 0, $wp_date_string_length));
        if ($final_post_day_counts[$new_post_day] == 1) {
            $old_post_date = $comic_post->post_date;
            $comic_post->post_date = $new_post_date;
            $comic_post->post_date_gmt = get_gmt_from_date($new_post_date);
            wp_update_post($comic_post);
            $cpm_config->messages[] = sprintf(__('<strong>Post %1$s moved to %2$s.</strong>', 'comicpress-manager'), $id, date("Y-m-d", $new_post_day));
            $posts_moved[$new_post_day] = array($comic_post, $old_post_date);
        } else {
            $cpm_config->warnings[] = sprintf(__('<strong>Moving post %1$s to %2$s would cause two comic posts to exist on the same day.</strong>  This is not allowed in the automated process.', 'comicpress-manager'), $id, date("Y-m-d", $new_post_day));
        }
    }
    // try to move all the files, and roll back any changes to files and posts that fail
    foreach ($comic_post_target_date_counts as $target_date => $count) {
        if (!isset($final_post_day_counts[$target_date]) || $final_post_day_counts[$target_date] == 1) {
            if ($count > 1) {
                $cpm_config->warnings[] = sprintf(__("<strong>You are moving two comics to the same date: %s.</strong>  This is not allowed in the automated process.", 'comicpress-manager'), $target_date);
            } else {
                list($comic_filename, $new_comic_filename) = $comic_files_to_date_shift[$target_date];
                $roll_back_change = false;
                $calculate_do_move = array();
                foreach (array(array(__('comic folder', 'comicpress-manager'), 'comic_folder', ""), array(__('RSS feed folder', 'comicpress-manager'), 'rss_comic_folder', "rss"), array(__('Mini thumb folder', 'comicpress-manager'), 'mini_comic_folder', "rss"), array(__('archive folder', 'comicpress-manager'), 'archive_comic_folder', "archive")) as $folder_info) {
                    list($name, $property, $type) = $folder_info;
                    $do_move = true;
                    if ($type != "") {
                        if ($cpm_config->separate_thumbs_folder_defined[$type]) {
                            if ($cpm_config->thumbs_folder_writable[$type]) {
                                $do_move = cpm_option("{$type}-generate-thumbnails") == 1;
                            }
                        }
                        $calculate_do_move[$type] = $do_move;
                    }
                    if ($do_move) {
                        $path = CPM_DOCUMENT_ROOT . '/' . $cpm_config->properties[$property];
                        if (!file_exists($path)) {
                            $cpm_config->errors[] = sprintf(__('The %1$s <strong>%2$s</strong> does not exist.', 'comicpress-manager'), $name, $cpm_config->properties[$property]);
                            $roll_back_change = true;
                        } else {
                            if (file_exists($path . '/' . $comic_filename)) {
                                if (@rename($path . '/' . $comic_filename, $path . '/' . $new_comic_filename)) {
                                    $cpm_config->messages[] = sprintf(__('<strong>Rename %1$s file %2$s to %3$s.</strong>', 'comicpress-manager'), $name, $comic_filename, $new_comic_filename);
                                } else {
                                    $cpm_config->warnings[] = sprintf(__('<strong>The renaming of %1$s to %2$s failed.</strong>  Check the permissions on %3$s', 'comicpress-manager'), $comic_filename, $new_comic_filename, $path);
                                    $roll_back_change = true;
                                }
                            }
                        }
                    }
                }
                if ($roll_back_change) {
                    foreach (array(array(__('comic folder', 'comicpress-manager'), 'comic_folder', ""), array(__('RSS feed folder', 'comicpress-manager'), 'rss_comic_folder', "rss"), array(__('Mini thumb folder', 'comicpress-manager'), 'mini_comic_folder', "rss"), array(__('archive folder', 'comicpress-manager'), 'archive_comic_folder', "archive")) as $folder_info) {
                        list($name, $property) = $folder_info;
                        $do_move = isset($calculate_do_move[$type]) ? $calculate_do_move[$type] : true;
                        if ($do_move) {
                            $path = CPM_DOCUMENT_ROOT . '/' . $cpm_config->properties[$property];
                            if (file_exists($path . '/' . $new_comic_filename)) {
                                @rename($path . '/' . $new_comic_filename, $path . '/' . $comic_filename);
                                $cpm_config->messages[] = sprintf(__("<strong>Rolling back %s.</strong>", 'comicpress-manager'), $new_comic_filename);
                            }
                        }
                    }
                    if (isset($posts_moved[$target_date])) {
                        list($comic_post, $old_post_date) = $posts_moved[$target_date];
                        $comic_post->post_date = $old_post_date;
                        $comic_post->post_date_gmt = get_gmt_from_date($old_post_date);
                        wp_update_post($comic_post);
                        $cpm_config->messages[] = sprintf(__('<strong>Rename error, rolling back post %1$s to %2$s.</strong>', 'comicpress-manager'), $comic_post->ID, $old_post_date);
                    }
                }
            }
        }
    }
    $cpm_config->comic_files = cpm_read_comics_folder();
}
/**
 * Read information about the current installation.
 */
function cpm_read_information_and_check_config()
{
    global $cpm_config, $cpm_attempted_document_roots, $blog_id, $wpmu_version;
    $cpm_config->config_method = read_current_theme_comicpress_config();
    $cpm_config->config_filepath = get_functions_php_filepath();
    $cpm_config->can_write_config = can_write_comicpress_config($cpm_config->config_filepath);
    $cpm_config->path = get_comic_folder_path();
    $cpm_config->plugin_path = PLUGINDIR . '/' . plugin_basename(__FILE__);
    foreach (array_keys($cpm_config->separate_thumbs_folder_defined) as $type) {
        $cpm_config->separate_thumbs_folder_defined[$type] = $cpm_config->properties['comic_folder'] != $cpm_config->properties[$type . '_comic_folder'];
    }
    $cpm_config->errors = array();
    $cpm_config->warnings = array();
    $cpm_config->detailed_warnings = array();
    $cpm_config->messages = array();
    $cpm_config->show_config_editor = true;
    $folders = array(array('comic folder', 'comic_folder', true, ""), array('RSS feed folder', 'rss_comic_folder', false, 'rss'), array('archive folder', 'archive_comic_folder', false, 'archive'), array('mini thumb folder', 'mini_comic_folder', false, 'mini'));
    foreach ($folders as $folder_info) {
        list($name, $property, $is_fatal, $thumb_type) = $folder_info;
        if ($thumb_type != "") {
            $cpm_config->thumbs_folder_writable[$thumb_type] = null;
        }
    }
    if (cpm_option("cpm-skip-checks") == 1) {
        // if the user knows what they're doing, disabling all of the checks improves performance
        foreach ($folders as $folder_info) {
            list($name, $property, $is_fatal, $thumb_type) = $folder_info;
            $path = CPM_DOCUMENT_ROOT . '/' . $cpm_config->properties[$property];
            if ($thumb_type != "") {
                $cpm_config->thumbs_folder_writable[$thumb_type] = true;
            }
        }
        foreach (array('comic', 'blog') as $type) {
            $result = (object) get_category($cpm_config->properties["{$type}cat"]);
            if (!is_wp_error($result)) {
                $cpm_config->{"{$type}_category_info"} = get_object_vars($result);
            }
        }
        $cpm_config->comic_files = cpm_read_comics_folder();
    } else {
        // quick check to see if the theme is ComicPress.
        // this needs to be made more robust.
        if (preg_match('/ComicPress/', get_current_theme()) == 0) {
            $cpm_config->detailed_warnings[] = __("The current theme isn't the ComicPress theme.  If you've renamed the theme, ignore this warning.", 'comicpress-manager');
        }
        if (!extension_loaded('zip')) {
            $cpm_config->detailed_warnings[] = __("You do not have the Zip extension installed. Uploading a Zip file will not work.", 'comicpress-manager');
        }
        $any_cpm_document_root_failures = false;
        if (!$wpmu_version) {
            // is the site root configured properly?
            if (!file_exists(CPM_DOCUMENT_ROOT)) {
                $cpm_config->warnings[] = sprintf(__('The comics site root <strong>%s</strong> does not exist. Check your <a href="options-general.php">WordPress address and address settings</a>.', 'comicpress-manager'), CPM_DOCUMENT_ROOT);
                $any_cpm_document_root_failures = true;
            }
            if (!file_exists(CPM_DOCUMENT_ROOT . '/index.php')) {
                $cpm_config->warnings[] = sprintf(__('The comics site root <strong>%s</strong> does not contain a WordPress index.php file. Check your <a href="options-general.php">WordPress address and address settings</a>.', 'comicpress-manager'), CPM_DOCUMENT_ROOT);
                $any_cpm_document_root_failures = true;
            }
        }
        if ($any_cpm_document_root_failures) {
            $cpm_config->warnings[] = print_r($cpm_attempted_document_roots, true);
        }
        // folders that are the same as the comics folder won't be written to
        $all_the_same = array();
        foreach ($cpm_config->separate_thumbs_folder_defined as $type => $value) {
            if (!$value) {
                $all_the_same[] = $type;
            }
        }
        if (count($all_the_same) > 0) {
            $cpm_config->detailed_warnings[] = sprintf(__("The <strong>%s</strong> folders and the comics folder are the same.  You won't be able to generate thumbnails until you change these folders.", 'comicpress-manager'), implode(", ", $all_the_same));
        }
        if (cpm_option('cpm-did-first-run') == 1) {
            // check the existence and writability of all image folders
            foreach ($folders as $folder_info) {
                list($name, $property, $is_fatal, $thumb_type) = $folder_info;
                if ($thumb_type == "" || $cpm_config->separate_thumbs_folder_defined[$thumb_type] == true) {
                    $path = CPM_DOCUMENT_ROOT . '/' . $cpm_config->properties[$property];
                    if (!file_exists($path)) {
                        $cpm_config->errors[] = sprintf(__('The %1$s <strong>%2$s</strong> does not exist.  Did you create it within the <strong>%3$s</strong> folder?', 'comicpress-manager'), $name, $cpm_config->properties[$property], CPM_DOCUMENT_ROOT);
                    } else {
                        do {
                            $tmp_filename = "test-" . md5(rand());
                        } while (file_exists($path . '/' . $tmp_filename));
                        $ok_to_warn = true;
                        if ($thumb_type != "") {
                            $ok_to_warn = cpm_option("cpm-{$thumb_type}-generate-thumbnails") == 1;
                        }
                        if ($ok_to_warn) {
                            if (!@touch($path . '/' . $tmp_filename)) {
                                $message = sprintf(__('The %1$s <strong>%2$s</strong> is not writable by the Webserver.', 'comicpress-manager'), $name, $cpm_config->properties[$property]);
                                if ($is_fatal) {
                                    $cpm_config->errors[] = $message;
                                } else {
                                    $cpm_config->warnings[] = $message;
                                }
                                if ($thumb_type != "") {
                                    $cpm_config->thumbs_folder_writable[$thumb_type] = false;
                                }
                            } else {
                                if (@stat($path . '/' . $tmp_filename) === false) {
                                    $cpm_config->errors[] = __('<strong>Files written to the %s directory by the Webserver cannot be read again!</strong>  Are you using IIS7 with FastCGI?', $cpm_config->properties[$property]);
                                    if ($thumb_type != "") {
                                        $cpm_config->thumbs_folder_writable[$thumb_type] = false;
                                    }
                                }
                            }
                        }
                        if (is_null($cpm_config->thumbs_folder_writable[$thumb_type])) {
                            @unlink($path . '/' . $tmp_filename);
                            if ($thumb_type != "") {
                                $cpm_config->thumbs_folder_writable[$thumb_type] = true;
                            }
                        }
                    }
                }
            }
        }
        // to generate thumbnails, a supported image processor is needed
        if ($cpm_config->get_scale_method() == CPM_SCALE_NONE) {
            $cpm_config->detailed_warnings[] = __("No image resize methods are installed (GD or ImageMagick).  You are unable to generate thumbnails automatically.", 'comicpress-manager');
        }
        // are there enough categories created?
        if (count(get_all_category_ids()) < 2) {
            $cpm_config->errors[] = __("You need to define at least two categories, a blog category and a comics category, to use ComicPress.  Visit <a href=\"categories.php\">Manage -> Categories</a> and create at least two categories, then return here to continue your configuration.", 'comicpress-manager');
            $cpm_config->show_config_editor = false;
        } else {
            // ensure the defined comic category exists
            if (is_null($cpm_config->properties['comiccat'])) {
                // all non-blog categories are comic categories
                $cpm_config->comic_category_info = array('name' => __("All other categories", 'comicpress-manager'));
                $cpm_config->properties['comiccat'] = array_diff(get_all_category_ids(), array($cpm_config->properties['blogcat']));
                if (count($cpm_config->properties['comiccat']) == 1) {
                    $cpm_config->properties['comiccat'] = $cpm_config->properties['comiccat'][0];
                    $cpm_config->comic_category_info = get_object_vars(get_category($cpm_config->properties['comiccat']));
                }
            } else {
                if (!is_numeric($cpm_config->properties['comiccat'])) {
                    // the property is non-numeric
                    $cpm_config->errors[] = __("The comic category needs to be defined as a number, not an alphanumeric string.", 'comicpress-manager');
                } else {
                    // one comic category is specified
                    if (is_null($cpm_config->comic_category_info = get_category($cpm_config->properties['comiccat']))) {
                        $cpm_config->errors[] = sprintf(__("The requested category ID for your comic, <strong>%s</strong>, doesn't exist!", 'comicpress-manager'), $cpm_config->properties['comiccat']);
                    } else {
                        $cpm_config->comic_category_info = get_object_vars($cpm_config->comic_category_info);
                    }
                }
            }
            // ensure the defined blog category exists
            // TODO: multiple blog categories
            if (!is_numeric($cpm_config->properties['blogcat'])) {
                // the property is non-numeric
                $cpm_config->errors[] = __("The blog category needs to be defined as a number, not an alphanumeric string.", 'comicpress-manager');
            } else {
                if (is_null($cpm_config->blog_category_info = get_category($cpm_config->properties['blogcat']))) {
                    $cpm_config->errors[] = sprintf(__("The requested category ID for your blog, <strong>%s</strong>, doesn't exist!", 'comicpress-manager'), $cpm_config->properties['blogcat']);
                } else {
                    $cpm_config->blog_category_info = get_object_vars($cpm_config->blog_category_info);
                }
                if (!is_array($cpm_config->properties['blogcat']) && !is_array($cpm_config->properties['comiccat'])) {
                    if ($cpm_config->properties['blogcat'] == $cpm_config->properties['comiccat']) {
                        $cpm_config->warnings[] = __("Your comic and blog categories are the same.  This will cause browsing problems for visitors to your site.", 'comicpress-manager');
                    }
                }
            }
        }
        // a quick note if you have no comics uploaded.
        // could be a sign of something more serious.
        if (count($cpm_config->comic_files = cpm_read_comics_folder()) == 0) {
            $cpm_config->detailed_warnings[] = __("Your comics folder is empty!", 'comicpress-manager');
        }
    }
}
function cpm_action_batch_processing()
{
    global $cpm_config;
    $files_to_delete = array();
    $posts_to_delete = array();
    $thumbnails_to_regenerate = array();
    $files_to_redate = array();
    $posts_to_redate = array();
    $posts_to_generate = array();
    $posts_that_exist = array();
    $posts_to_recategorize = array();
    extract(cpm_normalize_storyline_structure());
    $comic_categories = array();
    foreach ($category_tree as $node) {
        $comic_categories[] = end(explode("/", $node));
    }
    $cpm_config->is_cpm_managing_posts = true;
    foreach ($_POST as $field => $value) {
        if ($_POST['bulk-action'] != "-1" && $_POST['bulk-action'] != "individual") {
            $bulk_posts_updated = array();
            if (preg_match("#^(file|post),([^\\,]*),(.*)\$#", $field, $matches) > 0) {
                list($all, $type, $date, $id) = $matches;
                if (isset($_POST["batch-{$date}"])) {
                    switch ($_POST['bulk-action']) {
                        case "delete":
                            switch ($type) {
                                case "file":
                                    if (($result = cpm_match_id_to_file($id)) !== false) {
                                        $files_to_delete[] = $result;
                                    }
                                    break;
                                case "post":
                                    $posts_to_delete[] = $id;
                                    break;
                            }
                            break;
                        case "regen-thumbs":
                            if ($type == "file") {
                                if (($result = cpm_match_id_to_file($id)) !== false) {
                                    $thumbnails_to_regenerate[] = $result;
                                }
                            }
                            break;
                        case "edit":
                            if ($type == "post") {
                                foreach (array('hovertext' => 'bulk-hovertext', 'transcript' => 'bulk-transcript') as $meta_name => $post_name) {
                                    if (isset($_POST[$post_name])) {
                                        update_post_meta($id, $meta_name, $_POST[$post_name]);
                                    }
                                }
                                $post_categories = wp_get_post_categories($id);
                                $did_change = false;
                                if (isset($_POST['bulk-storyline-in-comic-category'])) {
                                    foreach ($comic_categories as $category_id) {
                                        if (in_array($category_id, $_POST['bulk-storyline-in-comic-category'])) {
                                            if (!in_array($category_id, $post_categories)) {
                                                $did_change = true;
                                                $post_categories[] = $category_id;
                                            }
                                        } else {
                                            if (($index = array_search($category_id, $post_categories)) !== false) {
                                                $did_change = true;
                                                array_splice($post_categories, $index, 1);
                                            }
                                        }
                                    }
                                }
                                if ($did_change) {
                                    wp_set_post_categories($id, $post_categories);
                                }
                                $bulk_posts_updates[] = $id;
                            }
                            break;
                        case "import":
                            switch ($type) {
                                case "file":
                                    if (($result = cpm_match_id_to_file($id)) !== false) {
                                        $posts_to_generate[] = $result;
                                    }
                                    break;
                                case "post":
                                    $posts_that_exist[] = $date;
                                    break;
                            }
                            break;
                    }
                }
            }
        } else {
            if (preg_match('#^([0-9]+)-in-comic-category#', $field, $matches) > 0) {
                if (get_post($matches[1])) {
                    $posts_to_recategorize[$matches[1]] = $value;
                }
            }
            if (preg_match("#^delete-file-(.*)\$#", $field, $matches) > 0) {
                if (($result = cpm_match_id_to_file($matches[1])) !== false) {
                    $files_to_delete[] = $result;
                }
            }
            if (preg_match("#^delete-post-(.*)\$#", $field, $matches) > 0) {
                if (get_post($matches[1])) {
                    $posts_to_delete[] = $matches[1];
                }
            }
            if (preg_match('#^regen-(.*)$#', $field, $matches) > 0) {
                if (($result = cpm_match_id_to_file($matches[1])) !== false) {
                    $thumbnails_to_regenerate[] = $result;
                }
            }
            if (preg_match("#^do-redate-file-(.*)\$#", $field, $matches) > 0) {
                if (($result = cpm_match_id_to_file($matches[1])) !== false) {
                    $files_to_redate[$result] = $value;
                }
            }
            if (preg_match("#^generate-post-(.*)\$#", $field, $matches) > 0) {
                if (($result = cpm_match_id_to_file($matches[1])) !== false) {
                    $posts_to_generate[] = $result;
                }
            }
            if (preg_match("#^delete-post-(.*)\$#", $field, $matches) > 0) {
                if (get_post($matches[1])) {
                    $posts_to_redate[$matches[1]] = $value;
                }
            }
        }
    }
    $did_generate_thumbs = array();
    $ok_to_keep_uploading = true;
    $files_created_in_operation = array();
    if (count($thumbnails_to_regenerate) > 0) {
        $thumbnails_written = array();
        $thumbnails_not_written = array();
        foreach ($thumbnails_to_regenerate as $file) {
            $comic_file = pathinfo($file, PATHINFO_BASENAME);
            $wrote_thumbnail = cpm_write_thumbnail($file, $comic_file, true);
            if (!is_null($wrote_thumbnail)) {
                if (is_array($wrote_thumbnail)) {
                    $files_created_in_operation = array_merge($files_created_in_operation, $wrote_thumbnail);
                    $thumbnails_written[] = $comic_file;
                } else {
                    $thumbnails_not_written[] = $comic_file;
                }
            }
            if (function_exists('cpm_wpmu_is_over_storage_limit')) {
                if (cpm_wpmu_is_over_storage_limit()) {
                    $ok_to_keep_uploading = false;
                    break;
                }
            }
        }
        if (count($thumbnails_written) > 0) {
            $cpm_config->messages[] = sprintf(__("<strong>The following thumbnails were written:</strong> %s", 'comicpress-manager'), implode(", ", $thumbnails_written));
        }
        if (count($thumbnails_not_written) > 0) {
            $cpm_config->warnings[] = sprintf(__("<strong>The following thumbnails were not written:</strong> %s", 'comicpress-manager'), implode(", ", $thumbnails_not_written));
        }
    }
    if (count($bulk_posts_updates) > 0) {
        $cpm_config->messages[] = sprintf(__("<strong>The following posts were updated:</strong> %s", 'comicpress-manager'), implode(", ", $bulk_posts_updates));
    }
    if (count($files_to_delete) > 0) {
        $comic_files_deleted = array();
        foreach ($files_to_delete as $file) {
            $comic_file = pathinfo($file, PATHINFO_BASENAME);
            $delete_targets = array($file);
            foreach ($cpm_config->thumbs_folder_writable as $type => $value) {
                $path = CPM_DOCUMENT_ROOT . '/' . $cpm_config->properties[$type . "_comic_folder"];
                if (($subdir = cpm_get_subcomic_directory()) !== false) {
                    $path .= '/' . $subdir;
                }
                $path .= '/' . $comic_file;
                $delete_targets[] = $path;
            }
            foreach ($delete_targets as $target) {
                if (file_exists($target)) {
                    @unlink($target);
                }
            }
            $comic_files_deleted[] = $comic_file;
        }
        $cpm_config->messages[] = sprintf(__("<strong>The following comic files and their associated thumbnails were deleted:</strong> %s", 'comicpress-manager'), implode(", ", $comic_files_deleted));
    }
    if (count($posts_to_delete) > 0) {
        foreach ($posts_to_delete as $post) {
            wp_delete_post($post);
        }
        $cpm_config->messages[] = sprintf(__("<strong>The following posts were deleted:</strong> %s", 'comicpress-manager'), implode(", ", $posts_to_delete));
    }
    $master_category = end(explode("/", reset($category_tree)));
    foreach ($posts_to_generate as $file) {
        $ok = false;
        $comic_file = pathinfo($file, PATHINFO_BASENAME);
        if (($result = cpm_breakdown_comic_filename($comic_file)) !== false) {
            if (!in_array(date("Y-m-d", strtotime($result['date'])), $posts_that_exist)) {
                if (($post_hash = generate_post_hash($result['date'], $result['converted_title'])) !== false) {
                    $post_hash['post_category'] = array($master_category);
                    $ok = !is_null($post_id = wp_insert_post($post_hash));
                }
            }
        }
        if ($ok) {
            $cpm_config->messages[] = sprintf(__('<strong>Created post %1$s for %2$s.</strong>', 'comicpress-manager'), $post_id, $comic_file);
        } else {
            $cpm_config->warnings[] = sprintf(__("<strong>Could not create post for %s.</strong>", 'comicpress-manager'), $comic_file);
        }
    }
    foreach ($posts_to_recategorize as $id => $requested_comic_categories) {
        if (!in_array($id, $posts_to_delete)) {
            $post_categories = wp_get_post_categories($id);
            $did_change = false;
            foreach ($comic_categories as $category_id) {
                if (in_array($category_id, $requested_comic_categories)) {
                    if (!in_array($category_id, $post_categories)) {
                        $did_change = true;
                        $post_categories[] = $category_id;
                    }
                } else {
                    if (($index = array_search($category_id, $post_categories)) !== false) {
                        $did_change = true;
                        array_splice($post_categories, $index, 1);
                    }
                }
            }
            if ($did_change) {
                wp_set_post_categories($id, $post_categories);
                $cpm_config->messages[] = sprintf(__("<strong>Storyline for post %s updated.</strong>", 'comicpress-manager'), $id);
            }
        }
    }
    if (!$ok_to_keep_uploading) {
        $cpm_config->warnings = array($cpm_config->wpmu_disk_space_message);
        foreach ($files_created_in_operation as $file) {
            @unlink($file);
        }
    }
    $cpm_config->comic_files = cpm_read_comics_folder();
}