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 testBreakdownComicFilename()
 {
     $_POST['upload-date-format'] = CPM_TEST_FILENAME_PATTERN;
     $test_date = "2008-01-01";
     foreach (array(array("meow", false), array("meow.xfm", false), array(md5(rand()), false), array("{$test_date}.jpg", array("title" => "", "date" => $test_date, "converted_title" => "")), array("comics/{$test_date}.jpg", false), array("{$test_date}-Test.jpg", array("title" => "-Test", "date" => $test_date, "converted_title" => "Test")), array("{$test_date}-test.jpg", array("title" => "-test", "date" => $test_date, "converted_title" => "Test")), array("1900-01-01.jpg", false), array("08-01-01.jpg", array("title" => "", "date" => $test_date, "converted_title" => ""))) as $test) {
         list($filename, $expected_value) = $test;
         $this->assertEqual($expected_value, cpm_breakdown_comic_filename($filename, true));
     }
 }
/**
 * Show the Latest Posts in the Sidebar.
 */
function cpm_show_latest_posts()
{
    global $cpm_config;
    $is_current = false;
    $is_previous = false;
    $current_timestamp = time();
    foreach (cpm_query_posts() as $comic_post) {
        $timestamp = strtotime($comic_post->post_date);
        if ($timestamp < $current_timestamp) {
            $is_current = true;
        }
        if ($is_current) {
            if ($is_previous) {
                $previous_post = $comic_post;
                break;
            }
            $current_post = $comic_post;
            $is_previous = true;
        } else {
            $upcoming_post = $comic_post;
        }
    }
    $found_posts = compact('previous_post', 'current_post', 'upcoming_post');
    $post_titles = array('previous_post' => __("Last Post", 'comicpress-manager'), 'current_post' => __("Current Post", 'comicpress-manager'), 'upcoming_post' => __("Upcoming Post", 'comicpress-manager'));
    ?>

  <div id="comicpress-latest-posts">
    <?php 
    if (!empty($found_posts)) {
        ?>
      <?php 
        foreach ($post_titles as $key => $title) {
            if (!empty($found_posts[$key])) {
                $timestamp = strtotime($found_posts[$key]->post_date);
                $post_date = date(CPM_DATE_FORMAT, $timestamp);
                $comic_file = null;
                foreach ($cpm_config->comic_files as $file) {
                    if (($result = cpm_breakdown_comic_filename(pathinfo($file, PATHINFO_BASENAME))) !== false) {
                        if ($result['date'] == $post_date) {
                            $comic_file = $file;
                            break;
                        }
                    }
                }
                ?>
          <div class="<?php 
                echo !empty($comic_file) ? "comic-found" : "comic-not-found";
                ?>
">
            <h3><?php 
                echo $title;
                ?>
 &mdash; <?php 
                echo $post_date;
                ?>
</h3>

            <h4><?php 
                echo $found_posts[$key]->post_title;
                ?>
 [<?php 
                echo generate_view_edit_post_links((array) $found_posts[$key]);
                ?>
]</h4>

            <?php 
                if (!empty($comic_file)) {
                    ?>
              <img alt="<?php 
                    echo $found_posts[$key]->post_title;
                    ?>
" src="<?php 
                    echo cpm_build_comic_uri($file, CPM_DOCUMENT_ROOT);
                    ?>
" width="320" />
            <?php 
                } else {
                    ?>
              <div class="alert">Comic file not found!</div>
            <?php 
                }
                ?>
          </div>
        <?php 
            }
        }
    } else {
        ?>
      <p>You don't have any comic posts!</p>
    <?php 
    }
    ?>
  </div>

  <?php 
}
    $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();
}
function cpm_action_create_missing_posts()
{
    global $cpm_config;
    $all_post_dates = array();
    foreach (cpm_query_posts() as $comic_post) {
        $all_post_dates[] = date(CPM_DATE_FORMAT, strtotime($comic_post->post_date));
    }
    $all_post_dates = array_unique($all_post_dates);
    $duplicate_posts_within_creation = array();
    $posts_created = array();
    $thumbnails_written = array();
    $thumbnails_not_written = array();
    $invalid_filenames = array();
    $duplicate_posts = array();
    $new_thumbnails_not_needed = array();
    $execution_time = ini_get("max_execution_time");
    $max_posts_imported = (int) ($execution_time / 2);
    $imported_post_count = 0;
    $safe_exit = false;
    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 {
        foreach ($cpm_config->comic_files as $comic_file) {
            $comic_file = pathinfo($comic_file, PATHINFO_BASENAME);
            if (($result = cpm_breakdown_comic_filename($comic_file)) !== false) {
                extract($result, EXTR_PREFIX_ALL, 'filename');
                $ok_to_create_post = !in_array($result['date'], $all_post_dates);
                $show_duplicate_post_message = false;
                $post_id = null;
                if (isset($duplicate_posts_within_creation[$result['date']])) {
                    $ok_to_create_post = false;
                    $show_duplicate_post_message = true;
                    $post_id = $duplicate_posts_within_creation[$result['date']];
                }
                if ($ok_to_create_post) {
                    if (isset($_POST['duplicate_check'])) {
                        $ok_to_create_post = ($post_id = post_exists($post_title, $post_content, $post_date)) == 0;
                    }
                } else {
                    if (!isset($_POST['duplicate_check'])) {
                        $ok_to_create_post = true;
                    }
                }
                if ($ok_to_create_post) {
                    if (($post_hash = generate_post_hash($filename_date, $filename_converted_title)) !== false) {
                        if (!is_null($post_id = wp_insert_post($post_hash))) {
                            $imported_post_count++;
                            $posts_created[] = get_post($post_id, ARRAY_A);
                            $date = date(CPM_DATE_FORMAT, strtotime($filename_date));
                            $all_post_dates[] = $date;
                            $duplicate_posts_within_creation[$date] = $post_id;
                            foreach (array('hovertext', 'transcript') as $field) {
                                if (!empty($_POST["{$field}-to-use"])) {
                                    update_post_meta($post_id, $field, $_POST["{$field}-to-use"]);
                                }
                            }
                            if (isset($_POST['thumbnails'])) {
                                $wrote_thumbnail = cpm_write_thumbnail($cpm_config->path . '/' . $comic_file, $comic_file);
                                if (!is_null($wrote_thumbnail)) {
                                    if ($wrote_thumbnail) {
                                        $thumbnails_written[] = $comic_file;
                                    } else {
                                        $thumbnails_not_written[] = $comic_file;
                                    }
                                } else {
                                    $new_thumbnails_not_needed[] = $comic_file;
                                }
                            }
                        }
                    } else {
                        $invalid_filenames[] = $comic_file;
                    }
                } else {
                    if ($show_duplicate_post_message) {
                        $duplicate_posts[] = array(get_post($post_id, ARRAY_A), $comic_file);
                    }
                }
            }
            if ($imported_post_count >= $max_posts_imported) {
                $safe_exit = true;
                break;
            }
        }
    }
    $cpm_config->import_safe_exit = $safe_exit;
    if ($safe_exit) {
        $cpm_config->messages[] = __("<strong>Import safely exited before you ran out of execution time.</strong> Scroll down to continue creating missing posts.", 'comicpress-manager');
    }
    if (count($posts_created) > 0) {
        cpm_display_operation_messages(compact('invalid_filenames', 'thumbnails_written', 'thumbnails_not_written', 'posts_created', 'duplicate_posts', 'new_thumbnails_not_needed'));
    } else {
        $cpm_config->messages[] = __("<strong>No new posts needed to be created.</strong>", 'comicpress-manager');
    }
}
/**
 * The change dates dialog.
 */
function cpm_manager_dates()
{
    global $cpm_config;
    $cpm_config->need_calendars = true;
    if (cpm_get_subcomic_directory() !== false) {
        $cpm_config->messages[] = __("<strong>Subdirectory support enabled.</strong> Change Dates may not work as expected.", 'comicpress-manager');
    }
    $comic_format_date_string = date(CPM_DATE_FORMAT);
    $dates_output_format = "Y-m-d";
    $start_date = date($dates_output_format);
    $end_date = substr(pathinfo(end($cpm_config->comic_files), PATHINFO_BASENAME), 0, strlen($comic_format_date_string));
    $end_date = date($dates_output_format, strtotime($end_date));
    if (isset($_POST['start-date']) && !empty($_POST['start-date'])) {
        $target_start_date = strtotime($_POST['start-date']);
        if ($target_start_date != -1 && $target_start_date !== false) {
            $start_date = date($dates_output_format, $target_start_date);
        } else {
            $cpm_config->warnings[] = $_POST['start-date'] . " is an invalid date.  Resetting to {$start_date}";
        }
        $target_end_date = strtotime($_POST['end-date']);
        if ($target_end_date != -1 && $target_end_date !== false) {
            $end_date = date($dates_output_format, $target_end_date);
        } else {
            $cpm_config->warnings[] = $_POST['end-date'] . " is an invalid date.  Resetting to {$end_date}";
        }
    }
    if (strtotime($end_date) < strtotime($start_date)) {
        list($start_date, $end_date) = array($end_date, $start_date);
    }
    $visible_comic_files = array();
    $visible_comic_files_md5 = array();
    $start_date_timestamp = strtotime($start_date);
    $end_date_timestamp = strtotime($end_date);
    foreach ($cpm_config->comic_files as $file) {
        $filename = pathinfo($file, PATHINFO_BASENAME);
        $result = cpm_breakdown_comic_filename($filename);
        $result_date_timestamp = strtotime($result['date']);
        if ($result_date_timestamp >= $start_date_timestamp && $result_date_timestamp <= $end_date_timestamp) {
            $visible_comic_files[] = $file;
            $visible_comic_files_md5[] = "\"" . md5($file) . "\"";
        }
    }
    $help_content = __("<p><strong>Change post &amp; comic dates</strong> lets you change the comic file names and post dates for any and every comic published. You will only be able to move a comic file and its associated post if there is no comic or post that exists on the destination date, as ComicPress Manager cannot automatically resolve such conflicts.</p>", 'comicpress-manager');
    $help_content .= __("<p><strong>This is a potentialy dangerous and resource-intensive operation.</strong> Back up your database and comics/archive/RSS folders before performing large move operations.  Additionally, if you experience script timeouts while moving large numbers of posts, you may have to move posts & comic files by hand rather than through ComicPress Manager.</p>", 'comicpress-manager');
    ob_start();
    ?>
  
  <h2 style="padding-right:0;"><?php 
    _e("Change Post &amp; Comic Dates", 'comicpress-manager');
    ?>
</h2>
  <h3>&mdash; <?php 
    _e("date changes will affect comics that are associated or not associated with posts", 'comicpress-manager');
    ?>
</h3>

  <?php 
    if (count($cpm_config->comic_files) > 0) {
        ?>
    <form action="" method="post">
      <?php 
        printf(__('Show comics between %1$s and %2$s', 'comicpress-manager'), "<input type=\"text\" id=\"start-date\" name=\"start-date\" size=\"12\" value=\"{$start_date}\" />", "<input type=\"text\" id=\"end-date\" name=\"end-date\" size=\"12\" value=\"{$end_date}\" />");
        ?>

      <input type="submit" value="<?php 
        _e("Filter", 'comicpress-manager');
        ?>
" />
    </form>

    <script type="text/javascript">
      var comic_files_keys = [ <?php 
        echo implode(", ", $visible_comic_files_md5);
        ?>
 ];

      var days_between_posts_message = "<?php 
        _e("How many days between posts?  Separate multiple intervals with commas (Ex: MWF is 2,2,3):", 'comicpress-manager');
        ?>
";
      var valid_interval_message = "<?php 
        _e("is a valid interval", 'comicpress-manager');
        ?>
";
    </script>
    <?php 
        cpm_include_javascript("comicpress_dates.js");
        ?>

    <form onsubmit="$('submit').disabled=true" action="" method="post">
      <input type="hidden" name="action" value="change-dates" />
      <input type="hidden" name="start-date" value="<?php 
        echo $start_date;
        ?>
" />
      <input type="hidden" name="end-date" value="<?php 
        echo $end_date;
        ?>
" />

      <?php 
        $field_to_setup = array();
        foreach ($visible_comic_files as $file) {
            $filename = pathinfo($file, PATHINFO_BASENAME);
            $result = cpm_breakdown_comic_filename($filename);
            $key = md5($file);
            $fields_to_setup[] = "'dates[{$key}]'";
            ?>
        <div id="holder-<?php 
            echo $key;
            ?>
" style="border-bottom: solid #666 1px; padding-bottom: 3px; margin-bottom: 3px">
          <table cellspacing="0">
            <tr>
              <td width="300" class="form-title"><?php 
            echo $filename;
            ?>
</td>
              <td><input size="12" onchange="$('holder-<?php 
            echo $key;
            ?>
').style.backgroundColor=(this.value != '<?php 
            echo $result['date'];
            ?>
' ? '#ddd' : '')" type="text" name="dates[<?php 
            echo $key;
            ?>
]" id="dates[<?php 
            echo $key;
            ?>
]" value="<?php 
            echo $result['date'];
            ?>
" />
              [<a title="<?php 
            printf(__("Reset date to %s", 'comicpress-manager'), $result['date']);
            ?>
" href="#" onclick="$('holder-<?php 
            echo $key;
            ?>
').style.backgroundColor=''; $('dates[<?php 
            echo $key;
            ?>
]').value = '<?php 
            echo $result['date'];
            ?>
'; return false">R</a> | <a title="<?php 
            _e("Re-schedule posts from this date at a daily interval", 'comicpress-manager');
            ?>
" href="#" onclick="reschedule_posts('<?php 
            echo $key;
            ?>
'); return false">I</a>]</td>
            </tr>
          </table>
        </div>
      <?php 
        }
        ?>
      <script type="text/javascript">
        var fields_to_setup = [ 'start-date', 'end-date', <?php 
        echo implode(", ", $fields_to_setup);
        ?>
 ];

        for (var i = 0, len = fields_to_setup.length; i < len; ++i) {
          var format = (i < 2) ? "%Y-%m-%d" : "<?php 
        echo preg_replace('/([a-zA-Z])/', '%\\1', CPM_DATE_FORMAT);
        ?>
";
          Calendar.setup({
            inputField: fields_to_setup[i],
            ifFormat: format,
            button: fields_to_setup[i]
          });
        }
      </script>
      <div style="text-align: center">
        <input class="button" type="submit" id="submit" value="<?php 
        _e("Change Dates", 'comicpress-manager');
        ?>
" />
      </div>
    </form>
  <?php 
    } else {
        ?>
    <p><?php 
        _e("You haven't uploaded any comics yet.", 'comicpress-manager');
        ?>
</p>
  <?php 
    }
    ?>

  <?php 
    $activity_content = ob_get_clean();
    cpm_wrap_content($help_content, $activity_content);
}
/**
 * The generate status dialog.
 */
function cpm_manager_status()
{
    global $cpm_config;
    $cpm_config->need_calendars = true;
    if (cpm_get_subcomic_directory() !== false) {
        $cpm_config->messages[] = sprintf(__("<strong>Reminder:</strong> You are managing the <strong>%s</strong> comic subdirectory.", 'comicpress-manager'), get_cat_name(get_option('comicpress-manager-manage-subcomic')));
    }
    if (cpm_option('cpm-skip-checks') != 1) {
        if (!function_exists('get_comic_path')) {
            $cpm_config->warnings[] = __('<strong>It looks like you\'re running an older version of ComicPress.</strong> Storyline, hovertext, and transcript are fully supported in <a href="http://comicpress.org/">ComicPress 2.7</a>. You can use hovertext and transcripts in earlier themes by using <tt>get_post_meta($post->ID, "hovertext", true)</tt> and <tt>get_post_meta($post->ID, "transcript", true)</tt>.', 'comicpress-manager');
        }
    }
    ob_start();
    ?>
  
  <h2 style="padding-right:0;"><?php 
    _e("Bulk Edit", 'comicpress-manager');
    ?>
</h2>
  <p><strong>ComicPress-related information, such as transcripts and Storyline categories for posts, and thumbnail regeneration, can be bulk edited here.</strong> To edit post-specific information, such as title and publishing date, use <strong><a href="edit.php">Edit Posts</a></strong>.

  <?php 
    $data_by_date = array();
    $dates_per_page = 15;
    foreach ($cpm_config->comic_files as $comic_filepath) {
        $comic_file = pathinfo($comic_filepath, PATHINFO_BASENAME);
        if (($result = cpm_breakdown_comic_filename($comic_file)) !== false) {
            $timestamp = strtotime($result['date']);
            $comic_date = date("Y-m-d", $timestamp);
            if (!isset($data_by_date[$comic_date])) {
                $data_by_date[$comic_date] = array();
            }
            $comic_info = array('type' => 'comic', 'timestamp' => $timestamp, 'comic_file' => $comic_file, 'file_title' => $result['converted_title'], 'comic_uri' => cpm_build_comic_uri($comic_filepath, CPM_DOCUMENT_ROOT));
            if (count($thumbnails_found = cpm_find_thumbnails_by_filename($comic_filepath)) > 0) {
                foreach ($thumbnails_found as $thumb_type => $thumb_filename) {
                    $comic_info["thumbnails_found_{$thumb_type}"] = cpm_build_comic_uri(CPM_DOCUMENT_ROOT . $thumb_filename, CPM_DOCUMENT_ROOT);
                }
            }
            $icon_file_to_use = $comic_filepath;
            foreach (array('rss', 'archive', 'mini') as $type) {
                if (isset($thumbnails_found[$type])) {
                    $icon_file_to_use = CPM_DOCUMENT_ROOT . $thumbnails_found[$type];
                }
            }
            $comic_info['icon_uri'] = cpm_build_comic_uri($icon_file_to_use, CPM_DOCUMENT_ROOT);
            $data_by_date[$comic_date][] = $comic_info;
        }
    }
    foreach (cpm_query_posts() as $comic_post) {
        $ok = true;
        if (cpm_get_subcomic_directory() !== false) {
            $ok = in_array(get_option('comicpress-manager-manage-subcomic'), wp_get_post_categories($comic_post->ID));
        }
        if ($ok) {
            $timestamp = strtotime($comic_post->post_date);
            $post_date = date("Y-m-d", $timestamp);
            if (!isset($data_by_date[$post_date])) {
                $data_by_date[$post_date] = array();
            }
            $post_info = array('type' => 'post', 'timestamp' => $timestamp, 'post_id' => $comic_post->ID, 'post_title' => $comic_post->post_title, 'post_object' => (array) $comic_post);
            $data_by_date[$post_date][] = $post_info;
        }
    }
    krsort($data_by_date);
    $all_months = array();
    foreach (array_keys($data_by_date) as $date) {
        list($year, $month, $day) = explode("-", $date);
        $key = "{$year}-{$month}";
        if (!isset($all_months[$key])) {
            $all_months[$key] = date("F Y", strtotime($date));
        }
    }
    krsort($all_months);
    if (isset($_POST['dates'])) {
        if ($_POST['dates'] != -1) {
            $new_data_by_date = array();
            foreach ($data_by_date as $date => $data) {
                if (strpos($date, $_POST['dates']) === 0) {
                    $new_data_by_date[$date] = $data;
                }
            }
            $data_by_date = $new_data_by_date;
        }
    }
    if (!isset($_GET['paged'])) {
        $_GET['paged'] = 1;
    }
    $page_links = paginate_links(array('base' => add_query_arg('paged', '%#%'), 'format' => '', 'prev_text' => __('&laquo;'), 'next_text' => __('&raquo;'), 'total' => ceil(count($data_by_date) / $dates_per_page), 'current' => $_GET['paged']));
    $total_data_by_date = count($data_by_date);
    $data_by_date = array_slice($data_by_date, ($_GET['paged'] - 1) * $dates_per_page, $dates_per_page);
    extract(cpm_normalize_storyline_structure());
    $comic_categories = array();
    foreach ($category_tree as $node) {
        $comic_categories[] = end(explode("/", $node));
    }
    $thumbnail_writes = cpm_get_thumbnails_to_generate();
    if ($total_data_by_date > 0) {
        $displaying_num_content = sprintf(__("Displaying %d-%d of %d", 'comicpress-manager'), ($_GET['paged'] - 1) * $dates_per_page + 1, min($total_data_by_date, ($_GET['paged'] - 1) * $dates_per_page + $dates_per_page), $total_data_by_date);
    } else {
        $displaying_num_content = __('No items to display', 'comicpress-manager');
    }
    ?>

  <style type="text/css">
    .storyline-checklist {
      overflow-y: scroll;
      border: solid #ddd 1px;
      height: 12em
    }

    #wpbody-content .bulk-edit-row-post .inline-edit-col-right {
      width: 42%
    }
  </style>
  <div id="table-holder">
    <form id="bulk-form" action="" method="post">
      <input type="hidden" name="action" value="batch-processing" />
      <div class="tablenav">
        <div class="alignleft actions">
          <select id="bulk-action" name="bulk-action">
            <option selected value="-1">Bulk Actions</option>
            <option value="individual">Submit Individual Changes</option>
            <option value="edit">Edit Selected</option>
            <option value="delete">Delete Selected</option>
            <option value="import">Create Posts for Selected Files</option>
            <option value="regen-thumbs">Regenerate Thumbs</option>
          </select>
          <input id="doaction" class="button-secondary action" type="submit" value="Apply" />
          <select id="dates" name="dates">
            <option selected value="-1">Show all dates</option>
            <?php 
    foreach ($all_months as $key => $date) {
        ?>
              <option value="<?php 
        echo $key;
        ?>
"<?php 
        echo $key == $_POST['dates'] ? " selected" : "";
        ?>
><?php 
        echo $date;
        ?>
</option>
            <?php 
    }
    ?>
          </select>
          <input id="dofilter" class="button-secondary action" type="submit" value="Filter" />
        </div>
        <div class="tablenav-pages">
          <span class="displaying-num"><?php 
    echo $displaying_num_content;
    ?>
</span>
          <?php 
    echo $page_links;
    ?>
        </div>
      </div>
      <table class="widefat fixed" id="status-table">
        <thead>
          <tr>
            <th class="check-column" width="3%">
              <input type="checkbox" name="toggle-all" class="batch-all" value="yes" />
            </th>
            <th width="12%"><?php 
    _e("Date", 'comicpress-manager');
    ?>
</th>
            <th width="34%"><?php 
    _e("Object Info", 'comicpress-manager');
    ?>
</th>
            <th width="61%"><?php 
    _e("Operations", 'comicpress-manager');
    ?>
</th>
          </tr>
        </thead>
        <tfoot>
          <tr>
            <th class="check-column">
              <input type="checkbox" name="toggle-all" class="batch-all" value="yes" />
            </th>
            <th><?php 
    _e("Date", 'comicpress-manager');
    ?>
</th>
            <th><?php 
    _e("Object Info", 'comicpress-manager');
    ?>
</th>
            <th><?php 
    _e("Operations", 'comicpress-manager');
    ?>
</th>
          </tr>
        </tfoot>
        <tbody>
          <tr style="display: none" id="bulk-edit" class="inline-edit-row inline-edit-row-post bulk-edit-row bulk-edit-row-post inline-editor">
            <td colspan="4">
              <fieldset class="inline-edit-col-left">
                <div class="inline-edit-col">
                  <h4>Bulk Edit Comic Posts</h4>
                  <div id="bulk-title-div">
                    <div id="bulk-titles" />
                  </div>
                </div>
              </fieldset>
              <fieldset class="inline-edit-col-center inline-edit-categories">
                <div class="inline-edit-col">
                  <span class="title inline-edit-categories-label">
                    Storyline
                  </span>
                  <div class="storyline-checklist">
                    <?php 
    cpm_display_storyline_checkboxes($category_tree, array(), "bulk-storyline");
    ?>
                  </div>
                </div>
              </fieldset>
              <fieldset class="inline-edit-col-right">
                <label>
                  <span class="title" style="width: auto; margin-right: 5px">&lt;img title&gt;/hovertext</span>
                  <input type="text" name="bulk-hovertext" style="width: 100%" />
                </label>
                <label>
                  <span class="title" style="width: auto; margin-right: 5px">Transcript</span>
                  <textarea name="bulk-transcript" style="height: 7em"></textarea>
                </label>
              </fieldset>
              <p class="submit inline-edit-save">
                <a id="cancel" class="button-secondary cancel alignleft" title="Cancel" href="#">Cancel</a>
                <input class="button-primary alignright" id="bulk-edit-submit" type="submit" value="Update Comic Posts" name="bulk-comic-edit" />
                <br class="clear" />
              </p>
            </td>
          </tr>
          <?php 
    $is_grey = false;
    $image_index = 0;
    foreach ($data_by_date as $date => $data) {
        $all_objects_by_type = array();
        foreach ($data as $object) {
            if (!isset($all_objects_by_type[$object['type']])) {
                $all_objects_by_type[$object['type']] = array();
            }
            $all_objects_by_type[$object['type']][] = $object;
        }
        $classes = array("data-row");
        if ($is_grey) {
            $classes[] = "grey";
        }
        $is_first_row = true;
        foreach ($data as $object) {
            ?>
              <tr class="<?php 
            echo implode(" ", $classes);
            ?>
">
                <?php 
            if ($is_first_row) {
                ?>
                  <td align="center" rowspan="<?php 
                echo count($data);
                ?>
">
                    <input id="batch-<?php 
                echo $date;
                ?>
" type="checkbox" class="batch" name="batch-<?php 
                echo $date;
                ?>
" value="yes" />
                  </td>
                  <td rowspan="<?php 
                echo count($data);
                ?>
"><?php 
                echo $date;
                ?>
</td>
                  <?php 
                $is_first_row = false;
            }
            ?>
                <td class="<?php 
            echo $object['type'];
            ?>
">
                  <?php 
            switch ($object['type']) {
                case "comic":
                    ?>
                        <div style="overflow: hidden">
                          <div><strong>
                            Comic: <?php 
                    echo empty($object['file_title']) ? $object['comic_file'] : $object['file_title'];
                    ?>
                          </strong></div>

                          <a href="<?php 
                    echo $object['comic_uri'];
                    ?>
"><img style="float: right; display: inline; margin-right: 5px; max-height: 100px" id="comic-icon-<?php 
                    echo $image_index;
                    ?>
" src="<?php 
                    echo $object['icon_uri'];
                    ?>
" /></a>

                        <?php 
                    $all_found = array();
                    foreach (array('rss', 'archive', 'mini') as $type) {
                        if (isset($object["thumbnails_found_{$type}"])) {
                            $all_found[$type] = $object["thumbnails_found_{$type}"];
                        }
                    }
                    if (count($all_found) > 0) {
                        ?>
                            [
                              <?php 
                        foreach ($all_found as $type => $uri) {
                            ?>
                                <a href="<?php 
                            echo $uri;
                            ?>
"><?php 
                            echo $type;
                            ?>
</a>
                              <?php 
                        }
                        ?>
                            ]
                          <?php 
                    } else {
                        ?>
                            [ No thumbnails found ]
                          <?php 
                    }
                    $image_index++;
                    ?>
                        </div>
                        <?php 
                    break;
                case "post":
                    if (isset($object['post_id'])) {
                        ?>
                          <strong>Post: <?php 
                        echo $object['post_title'];
                        ?>
</strong>
                          <em>(<?php 
                        echo $object['post_id'];
                        ?>
)</em><br />
                          [ <?php 
                        echo generate_view_edit_post_links($object['post_object']);
                        ?>
 ]
                        <?php 
                    }
                    break;
            }
            ?>
                </td>
                <td class="individual-operations <?php 
            echo $object['type'];
            ?>
">
                  <?php 
            switch ($object['type']) {
                case "comic":
                    ?>
                        <input type="hidden" name="file,<?php 
                    echo $date;
                    ?>
,<?php 
                    echo $object['comic_file'];
                    ?>
" value="yes" />

                        <?php 
                    if (count($all_objects_by_type['post']) == 0) {
                        ?>
                          <label><input type="checkbox" name="generate-post-<?php 
                        echo $object['comic_file'];
                        ?>
" value="yes" /> Generate a Post <em>(as a draft)</em></label><br />
                        <?php 
                    }
                    ?>

                        <?php 
                    if (count($thumbnail_writes) > 0) {
                        ?>
                          <label><input type="checkbox" name="regen-<?php 
                        echo $object['comic_file'];
                        ?>
" value="yes" /> Regenerate Thumbs</label><br />
                        <?php 
                    }
                    ?>

                        <label><input type="checkbox" class="delete-file" name="delete-file-<?php 
                    echo $object['comic_file'];
                    ?>
" value="yes" /> Delete Comic</label><br />
                        <!-- <input type="checkbox" id="do-redate-file-<?php 
                    echo $object['comic_file'];
                    ?>
" name="do-redate-file-<?php 
                    echo $object['comic_file'];
                    ?>
" /> Move to: <input class="needs-calendar" id="redate-file-<?php 
                    echo $object['comic_file'];
                    ?>
" type="text" name="redate-file-<?php 
                    echo $object['comic_file'];
                    ?>
" value="<?php 
                    echo $date;
                    ?>
" /> -->

                        <?php 
                    break;
                case "post":
                    $post_categories = array_intersect(wp_get_post_categories($object['post_id']), $comic_categories);
                    $post_category_names = array();
                    foreach ($post_categories as $category_id) {
                        $post_category_names[] = get_cat_name($category_id);
                    }
                    ?>
                        <input type="hidden" name="post,<?php 
                    echo $date;
                    ?>
,<?php 
                    echo $object['post_id'];
                    ?>
" value="yes" />
                        <label><input type="checkbox" class="delete-post" name="delete-post-<?php 
                    echo $object['post_id'];
                    ?>
" value="yes" /> Delete Post</label><br />
                        <!-- <input type="checkbox" id="do-redate-post-<?php 
                    echo $object['post_id'];
                    ?>
" name="do-redate-post-<?php 
                    echo $object['post_id'];
                    ?>
" /> Move to: <input type="text" class="needs-calendar" id="redate-post-<?php 
                    echo $object['post_id'];
                    ?>
" name="redate-post-<?php 
                    echo $object['post_if'];
                    ?>
" value="<?php 
                    echo $date;
                    ?>
" /><br /> -->

                        <?php 
                    $hovertext = get_post_meta($object['post_id'], 'hovertext', true);
                    if (!empty($hovertext)) {
                        ?>
                          <strong>&lt;img title&gt;/hovertext:</strong> <?php 
                        echo $hovertext;
                        ?>
<br />
                        <?php 
                    }
                    ?>

                         <?php 
                    $transcript = get_post_meta($object['post_id'], 'transcript', true);
                    if (!empty($transcript)) {
                        ?>
                          <strong>Transcript:</strong>
                          <div class="transcript-holder"><?php 
                        echo $transcript;
                        ?>
</div>
                        <?php 
                    }
                    ?>

                        <strong>Storyline:</strong> <span class="category-names"><?php 
                    echo implode(", ", $post_category_names);
                    ?>
</span> [ <a href="#" id="category-<?php 
                    echo $object['post_id'];
                    ?>
" class="category">Edit</a> ]
                        <div id="category-holder-<?php 
                    echo $object['post_id'];
                    ?>
" style="display: none">
                          <?php 
                    cpm_display_storyline_checkboxes($category_tree, $post_categories, $object['post_id']);
                    ?>
                        </div>

                        <?php 
                    break;
            }
            ?>
                </td>
              </tr>
            <?php 
        }
        $is_grey = !$is_grey;
    }
    ?>
        </tbody>
      </table>
      <div class="tablenav">
        <div class="alignleft actions">
          <select id="linked-bulk-action" name="linked-bulk-action">
            <option selected value="-1">Bulk Actions</option>
            <option value="individual">Submit Individual Changes</option>
            <option value="edit">Edit Selected</option>
            <option value="delete">Delete Selected</option>
            <option value="import">Create Posts for Selected Files</option>
            <option value="regen-thumbs">Regenerate Thumbs</option>
          </select>
          <input id="linked-doaction" class="button-secondary action" type="submit" value="Apply" />
        </div>
        <div class="tablenav-pages">
          <span class="displaying-num"><?php 
    echo $displaying_num_content;
    ?>
</span>
          <?php 
    echo $page_links;
    ?>
        </div>
      </div>
    </form>
    <script type="text/javascript">
      Event.observe(window, 'load', function() {
        Event.observe($('linked-bulk-action'), 'change', function() {
          $('bulk-action').selectedIndex = $('linked-bulk-action').selectedIndex;
        });

        Event.observe($('bulk-action'), 'change', function() {
          $('linked-bulk-action').selectedIndex = $('bulk-action').selectedIndex;
        });

        $$('.needs-calendar').each(function(element) {
          Calendar.setup({
            inputField: element.id,
            ifFormat: "%Y-%m-%d",
            button: element.id
          });

          Event.observe(element, 'click', function(e) {
            var element = Event.element(e);
            $("do-" + element.id).checked = true;
          });
        });

        $$('a.category').each(function(element) {
          Event.observe(element, 'click', function(e) {
            Event.stop(e);
            Element.toggle("category-holder-" + Event.element(e).id.replace(/^.*\-([0-9]+)$/, '$1'));
          });
        });
      });

      $$('.batch-all').each(function(element) {
        Event.observe(element, 'change', function(e) {
          $$('.batch').each(function(b) { b.checked = element.checked; });
          $$('.batch-all').each (function(b) { b.checked = element.checked; });
        });
      });

      $$('.individual-operations input[type=checkbox]').each(function(element) {
        Event.observe(element, 'click', function(e) {
          $('bulk-action').selectedIndex = 1;
          $('linked-bulk-action').selectedIndex = 1;
        });
      });

      var ok_to_submit = false;

      Event.observe($('bulk-form'), 'submit', function(e) {
        return ok_to_submit;
      });

      Event.observe($('bulk-edit-submit'), 'click', function(e) {
        ok_to_submit = true;
        $('bulk-form').submit();
      });

      Event.observe($('cancel'), 'click', function(e) {
        Event.stop(e);
        $('bulk-edit').hide();
        $('bulk-action').selectedIndex = 0;
      });

      Event.observe($('dofilter'), 'click', function(e) {
        Event.stop(e);
        $('bulk-action').selectedIndex = 0;
        ok_to_submit = true;
        $('bulk-form').submit();
      });

      ['doaction', 'linked-doaction'].each(function(which) {
        Event.observe($(which), 'click', function(e) {
          Event.stop(e);

          switch ($F('bulk-action')) {
            case -1:
            case "-1":
              break;
            case "edit":
              $('bulk-titles').innerHTML = "";
              var any_checked = false;
              $$('.batch').each(function(element) {
                if (element.checked) {
                  any_checked = true;
                  /\-(.*)$/.test(element.id);
                  var date = RegExp.$1;

                  var node = Builder.node("div", [
                    Builder.node("a", { id: date, className: "ntdelbutton", title: "Remove From Bulk Edit" }, [ "X" ]),
                    date
                  ]);

                  $('bulk-titles').insert(node);

                  Event.observe(node, 'click', function(evt) {
                    var node = Event.element(evt);
                    $('batch-' + node.id).checked = false;
                    Element.remove(node.parentNode);

                    var any_checked = false;
                    $$('.batch').each(function(n) {
                      if (n.checked) { any_checked = true; }
                    });

                    if (!any_checked) { $('bulk-edit').hide(); }
                  });
                }
              });

              if (any_checked) { $('bulk-edit').show(); }

              break;
            case "delete":
              if (confirm("<?php 
    _e('You are about to delete the selected posts and comic files. Are you sure?', 'comicpress-manager');
    ?>
")) {
                ok_to_submit = true;
                $('bulk-form').submit();
              }
              break;
            default:
              ok_to_submit = true;
              $('bulk-form').submit();
              break;
          }
        });
      });
    </script>
  </div>

  <?php 
    $activity_content = ob_get_clean();
    cpm_wrap_content($help_content, $activity_content, false);
}
/**
 * Find all the valid comics in the comics folder.
 * If CPM_SKIP_CHECKS is enabled, comic file validity is not checked, improving speed.
 * @return array The list of valid comic files in the comic folder.
 */
function cpm_read_comics_folder()
{
    global $cpm_config;
    $glob_results = glob(get_comic_folder_path() . "/*");
    if ($glob_results === false) {
        //$cpm_config->messages[] = "FYI: glob({$cpm_config->path}/*) returned false. This can happen on some PHP installations if you have no files in your comic directory. This message will disappear once you upload a comic to your site.";
        return array();
    }
    $filtered_glob_results = array();
    foreach ($glob_results as $result) {
        if (in_array(strtolower(pathinfo($result, PATHINFO_EXTENSION)), $cpm_config->allowed_extensions)) {
            $filtered_glob_results[] = $result;
        }
    }
    if (cpm_option("cpm-skip-checks") == 1) {
        return $filtered_glob_results;
    } else {
        $files = array();
        foreach ($filtered_glob_results as $file) {
            if (cpm_breakdown_comic_filename(pathinfo($file, PATHINFO_BASENAME)) !== false) {
                $files[] = $file;
            }
        }
        return $files;
    }
}
 /**
  * @dataProvider providerTestBreakdownComicFilename
  */
 function testBreakdownComicFilename($input, $expected_output)
 {
     $this->assertEquals($expected_output, cpm_breakdown_comic_filename($input));
 }
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();
}