/**
 * Write a thumbnail image to the thumbnail folders.
 * @param string $input The input image filename.
 * @param string $target_filename The filename for the thumbnails.
 * @param boolean $do_rebuild If true, force rebuilding thumbnails.
 * @return mixed True if successful, false if not, null if unable to write.
 */
function cpm_write_thumbnail($input, $target_filename, $do_rebuild = false)
{
    global $cpm_config;
    $target_format = pathinfo($target_filename, PATHINFO_EXTENSION);
    $files_created_in_operation = array();
    $write_targets = array();
    foreach ($cpm_config->separate_thumbs_folder_defined as $type => $value) {
        if ($value) {
            if ($cpm_config->thumbs_folder_writable[$type]) {
                if (cpm_option("cpm-{$type}-generate-thumbnails") == 1) {
                    $converted_target_filename = preg_replace('#\\.[^\\.]+$#', '', $target_filename) . '.' . $target_format;
                    $target = CPM_DOCUMENT_ROOT . '/' . $cpm_config->properties[$type . "_comic_folder"];
                    if (($subdir = cpm_get_subcomic_directory()) !== false) {
                        $target .= '/' . $subdir;
                    }
                    $target .= '/' . $converted_target_filename;
                    if (!in_array($target, $write_targets)) {
                        $write_targets[$type] = $target;
                    }
                }
            }
        }
    }
    if (count($write_targets) > 0) {
        if (!$do_rebuild) {
            if (file_exists($input)) {
                if (file_exists($target)) {
                    if (filemtime($input) > filemtime($target)) {
                        $do_rebuild = true;
                    }
                } else {
                    $do_rebuild = true;
                }
            }
        }
        if ($do_rebuild) {
            switch ($cpm_config->get_scale_method()) {
                case CPM_SCALE_NONE:
                    return null;
                case CPM_SCALE_IMAGEMAGICK:
                    $original_size = getimagesize($input);
                    $unique_colors = exec("identify -format '%k' '{$input}'");
                    if (empty($unique_colors)) {
                        $unique_colors = 256;
                    }
                    $ok = true;
                    foreach ($write_targets as $type => $target) {
                        $width_to_use = isset($cpm_config->properties["{$type}_comic_width"]) ? $cpm_config->properties["{$type}_comic_width"] : $cpm_config->properties['archive_comic_width'];
                        if ($width_to_use < $original_size[0]) {
                            $command = array("convert", "\"{$input}\"", "-filter Lanczos", "-resize " . $width_to_use . "x");
                            $im_target = $target;
                            switch (strtolower($target_format)) {
                                case "jpg":
                                case "jpeg":
                                    $command[] = "-quality " . cpm_option("cpm-thumbnail-quality");
                                    break;
                                case "gif":
                                    $command[] = "-colors {$unique_colors}";
                                    break;
                                case "png":
                                    if ($unique_colors <= 256) {
                                        $im_target = "png8:{$im_target}";
                                        $command[] = "-colors {$unique_colors}";
                                    }
                                    $command[] = "-quality 100";
                                    break;
                                default:
                            }
                            $command[] = "\"{$im_target}\"";
                            $convert_to_thumb = escapeshellcmd(implode(" ", $command));
                            exec($convert_to_thumb);
                            if (!file_exists($target)) {
                                $ok = false;
                            } else {
                                @chmod($target, CPM_FILE_UPLOAD_CHMOD);
                                $files_created_in_operation[] = $target;
                            }
                        } else {
                            copy($input, $target);
                        }
                    }
                    return $ok ? $files_created_in_operation : false;
                case CPM_SCALE_GD:
                    list($width, $height) = getimagesize($input);
                    if ($width > 0) {
                        $pixel_size_buffer = 1.25;
                        $max_bytes = cpm_short_size_string_to_bytes(ini_get('memory_limit'));
                        if ($max_bytes > 0) {
                            $max_thumb_size = 0;
                            foreach ($write_targets as $type => $target) {
                                $width_to_use = isset($cpm_config->properties["{$type}_comic_width"]) ? $cpm_config->properties["{$type}_comic_width"] : $cpm_config->properties['archive_comic_width'];
                                $archive_comic_height = (int) ($width_to_use * $height / $width);
                                $max_thumb_size = max($width_to_use * $archive_comic_height * 4, $max_thumb_size);
                            }
                            $input_image_size = $width * $height * 4;
                            if (strtolower(pathinfo($input, PATHINFO_EXTENSION)) == "gif") {
                                $input_image_size *= 2;
                            }
                            $recommended_size = ($input_image_size + $max_thumb_size) * $pixel_size_buffer;
                            if (function_exists('memory_get_usage')) {
                                $recommended_size += memory_get_usage();
                            }
                            if ($recommended_size > $max_bytes) {
                                $cpm_config->warnings[] = sprintf(__("<strong>You don't have enough memory available to PHP and GD to process this file.</strong> You should <strong>set your PHP <tt>memory_size</tt></strong> to at least <strong><tt>%sM</tt></strong> and try again. For more information, read the ComicPress Manager FAQ.", 'comicpress-manager'), (int) ($recommended_size / (1024 * 1024)));
                                return false;
                            }
                        }
                        foreach ($write_targets as $type => $target) {
                            $width_to_use = isset($cpm_config->properties["{$type}_comic_width"]) ? $cpm_config->properties["{$type}_comic_width"] : $cpm_config->properties['archive_comic_width'];
                            if ($width_to_use < $width) {
                                $archive_comic_height = (int) ($width_to_use * $height / $width);
                                $pathinfo = pathinfo($input);
                                $thumb_image = imagecreatetruecolor($width_to_use, $archive_comic_height);
                                imagealphablending($thumb_image, true);
                                switch (strtolower($pathinfo['extension'])) {
                                    case "jpg":
                                    case "jpeg":
                                        $comic_image = imagecreatefromjpeg($input);
                                        break;
                                    case "gif":
                                        $is_gif = true;
                                        $temp_comic_image = imagecreatefromgif($input);
                                        list($width, $height) = getimagesize($input);
                                        $comic_image = imagecreatetruecolor($width, $height);
                                        imagecopy($comic_image, $temp_comic_image, 0, 0, 0, 0, $width, $height);
                                        imagedestroy($temp_comic_image);
                                        break;
                                    case "png":
                                        $comic_image = imagecreatefrompng($input);
                                        break;
                                    default:
                                        return false;
                                }
                                imagealphablending($comic_image, true);
                                if ($is_palette = !imageistruecolor($comic_image)) {
                                    $number_of_colors = imagecolorstotal($comic_image);
                                }
                                imagecopyresampled($thumb_image, $comic_image, 0, 0, 0, 0, $width_to_use, $archive_comic_height, $width, $height);
                                $ok = true;
                                @touch($target);
                                if (file_exists($target)) {
                                    @unlink($target);
                                    switch (strtolower($target_format)) {
                                        case "jpg":
                                        case "jpeg":
                                            if (imagetypes() & IMG_JPG) {
                                                @imagejpeg($thumb_image, $target, cpm_option("cpm-thumbnail-quality"));
                                            } else {
                                                return false;
                                            }
                                            break;
                                        case "gif":
                                            if (imagetypes() & IMG_GIF) {
                                                if (function_exists('imagecolormatch')) {
                                                    $temp_comic_image = imagecreate($width_to_use, $archive_comic_height);
                                                    imagecopymerge($temp_comic_image, $thumb_image, 0, 0, 0, 0, $width_to_use, $archive_comic_height, 100);
                                                    imagecolormatch($thumb_image, $temp_comic_image);
                                                    @imagegif($temp_comic_image, $target);
                                                    imagedestroy($temp_comic_image);
                                                } else {
                                                    @imagegif($thumb_image, $target);
                                                }
                                            } else {
                                                return false;
                                            }
                                            break;
                                        case "png":
                                            if (imagetypes() & IMG_PNG) {
                                                if ($is_palette) {
                                                    imagetruecolortopalette($thumb_image, true, $number_of_colors);
                                                }
                                                @imagepng($thumb_image, $target, 9);
                                            } else {
                                                return false;
                                            }
                                            break;
                                        default:
                                            return false;
                                    }
                                }
                            } else {
                                copy($input, $target);
                            }
                            if (!file_exists($target)) {
                                $ok = false;
                            } else {
                                @chmod($target, CPM_FILE_UPLOAD_CHMOD);
                                $files_created_in_operation[] = $target;
                            }
                            imagedestroy($comic_image);
                            imagedestroy($thumb_image);
                        }
                    } else {
                        $ok = false;
                    }
                    return $ok ? $files_created_in_operation : false;
            }
        }
    }
    return null;
}
/**
 * The main manager screen.
 */
function cpm_manager_index()
{
    global $cpm_config;
    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')));
    }
    $cpm_config->need_calendars = true;
    $example_date = cpm_generate_example_date(CPM_DATE_FORMAT);
    $example_real_date = date(CPM_DATE_FORMAT);
    $zip_extension_loaded = extension_loaded('zip');
    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');
        }
    }
    if (count($_POST) == 0 && isset($_GET['upload'])) {
        $cpm_config->warnings[] = sprintf(__("Your uploaded files were larger than the <strong><tt>post_max_size</tt></strong> setting, which is currently <strong><tt>%s</tt></strong>. Either upload fewer/smaller files, upload them via FTP/SFTP, or increase your server's <strong><tt>post_max_size</tt></strong>.", 'comicpress-manager'), ini_get('post_max_size'));
    }
    ob_start();
    ?>
    <p>
      <strong>
        <?php 
    _e("ComicPress Manager manages your comics and your time.", 'comicpress-manager');
    ?>
      </strong>
      <?php 
    _e("It makes uploading new comics, importing comics from a non-ComicPress setup, and batch uploading a lot of comics at once, very fast and configurable.", 'comicpress-manager');
    ?>
    </p>

    <p>
      <strong>
        <?php 
    _e("ComicPress Manager also manages yours and your Website's sanity.", 'comicpress-manager');
    ?>
      </strong>

      <?php 
    printf(__("It can check for misconfigured ComicPress setups, for incorrectly-named files (remember, it's <em>%s-single-comic-title.ext</em>) and for when you might be duplicating a post. You will also be shown which comic will appear with which blog post in the Post editor.", 'comicpress-manager'), $example_date);
    ?>
    </p>

    <p>
      <?php 
    printf(__("<strong>Single comic titles</strong> are generated from the incoming filename.  If you've named your file <strong>%s-my-new-years-day.jpg</strong> and create a new post for the file, the post title will be <strong>My New Years Day</strong>.  This default should handle the majority of cases.  If a comic file does not have a title, the date in <strong>MM/DD/YYYY</strong> format will be used.", 'comicpress-manager'), $example_real_date);
    ?>
    </p>

    <p>
      <?php 
    _e("<strong>Upload image files</strong> lets you upload multiple comics at a time, and add a default post body for each comic.", 'comicpress-manager');
    ?>
      <?php 
    if ($zip_extension_loaded) {
        ?>
        <?php 
        _e("You can <strong>upload a Zip file and create new posts</strong> from the files contained within the Zip file.", 'comicpress-manager');
        ?>
      <?php 
    } else {
        ?>
        <?php 
        _e("<strong>You can't upload a Zip file</strong> because you do not have the PHP <strong>zip</strong> extension installed.", 'comicpress-manager');
        ?>
      <?php 
    }
    ?>
    </p>

    <p>
      <?php 
    _e("Has ComicPress Manager saved you time and sanity?  <strong>Donate a few bucks to show your appreciation!</strong>", 'comicpress-manager');
    ?>
      <span style="display: block; text-align: center">
        <form action="https://www.paypal.com/cgi-bin/webscr" method="post">
        <input type="hidden" name="cmd" value="_s-xclick">
        <input type="hidden" name="encrypted" value="-----BEGIN P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XZlX2NlcnRzMREwDwYDVQQDFAhsaXZlX2FwaTEcMBoGCSqGSIb3DQEJARYNcmVAcGF5cGFsLmNvbQIBADAJBgUrDgMCGgUAoF0wGAYJKoZIhvcNAQkDMQsGCSqGSIb3DQEHATAcBgkqhkiG9w0BCQUxDxcNMDkwMTA2MDAyOTQwWjAjBgkqhkiG9w0BCQQxFgQUITTqZaXyM43N5f08PBPDuRmzzdEwDQYJKoZIhvcNAQEBBQAEgYAV0szDQPbcyW/O9pZ7jUghTRdgHbCX4RyjPzR35IrI8MrqmtK94ENuD6Xf8PxkAJ3QdDr9OvkzWOHFVrb6YrAdh+XxBsMf1lD17UbwN3XZFn5HqvoWNFxNr5j3qx0DBsCh5RlGex+HAvtIoJu21uGRjbOQQsYFdlAPHxokkVP/Xw==-----END PKCS7-----
        ">
        <input type="image" src="https://www.paypal.com/en_US/i/btn/btn_donate_SM.gif" border="0" name="submit" alt="">
        <img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">
        </form>
      </span>
    </p>
  <?php 
    $help_content = ob_get_clean();
    ob_start();
    ?>

  <h2 style="padding-right:0;">
    <?php 
    if ($zip_extension_loaded) {
        _e("Upload Image &amp; Zip Files", 'comicpress-manager');
    } else {
        _e("Upload Image Files", 'comicpress-manager');
    }
    ?>
  </h2>
  <h3>&mdash;
    <?php 
    if (cpm_option('cpm-obfuscate-filenames-on-upload') === "none") {
        ?>
      <?php 
        _e("any existing files with the same name will be overwritten", 'comicpress-manager');
        ?>
    <?php 
    } else {
        ?>
      <?php 
        _e("uploaded filenames will be obfuscated, therefore no old files will be overwritten after uploading", 'comicpress-manager');
        ?>
    <?php 
    }
    ?>
  </h3>

  <?php 
    $target_url = add_query_arg("upload", "1");
    ?>

  <form onsubmit="$('submit').disabled=true" action="<?php 
    echo $target_url;
    ?>
" method="post" enctype="multipart/form-data">
    <input type="hidden" name="action" value="multiple-upload-file" />
    <input type="hidden" name="MAX_FILE_SIZE" value="<?php 
    echo cpm_short_size_string_to_bytes(ini_get('upload_max_filesize'));
    ?>
" />
    <div id="multiple-file-upload">
    </div>
    <div style="text-align: center">
      [<a href="#" onclick="add_file_upload(); return false"><?php 
    _e("Add file to upload", 'comicpress-manager');
    ?>
</a>]
    </div>

    <table class="form-table">
      <tr>
        <th scope="row"><?php 
    _e("Destination for uploaded files:", 'comicpress-manager');
    ?>
</th>
        <td>
          <select name="upload-destination" id="upload-destination">
            <option value="comic"><?php 
    _e("Comics folder", 'comicpress-manager');
    ?>
</option>
            <option value="archive_comic"><?php 
    _e("Archive folder", 'comicpress-manager');
    ?>
</option>
            <option value="rss_comic"><?php 
    _e("RSS feed folder", 'comicpress-manager');
    ?>
</option>
          </select>
        </td>
      </tr>
      <?php 
    if (count($cpm_config->comic_files) > 0) {
        ?>
        <tr id="overwrite-existing-holder">
          <th scope="row"><?php 
        _e("Overwrite an existing file:", 'comicpress-manager');
        ?>
</th>
          <td>
            <select name="overwrite-existing-file-choice" id="overwrite-existing-file-choice">
              <option value=""><?php 
        _e("-- no --", 'comicpress-manager');
        ?>
</option>
              <?php 
        foreach ($cpm_config->comic_files as $file) {
            $basename = pathinfo($file, PATHINFO_BASENAME);
            ?>
                <option value="<?php 
            echo $basename;
            ?>
"
                <?php 
            echo $_GET['replace'] == $basename ? "selected" : "";
            ?>
><?php 
            echo $basename;
            ?>
</option>
              <?php 
        }
        ?>
            </select>
          </td>
        </tr>
        <tr id="rebuild-thumbnails">
          <th scope="row"><?php 
        _e("Rebuild thumbnails?", 'comicpress-manager');
        ?>
</th>
          <td>
            <label>
              <input type="checkbox" id="replace-comic-rebuild-thumbnails" name="replace-comic-rebuild-thumbnails" value="yes" checked />
              <em>(if replacing a comic in the <strong>comic</strong> folder, you can also regenerate thumbnails)</em>
            </label>
          </td>
        </tr>
      <?php 
    }
    ?>
      <tr>
        <td align="center" colspan="2">
          <input class="button" id="submit" type="submit" value="<?php 
    if (extension_loaded("zip")) {
        _e("Upload Image &amp; Zip Files", 'comicpress-manager');
    } else {
        _e("Upload Image Files", 'comicpress-manager');
    }
    ?>
" />
        </td>
      </tr>
    </table>

    <div id="upload-destination-holder">
      <table class="form-table">
        <tr>
          <th scope="row"><?php 
    _e("Generate new posts for each uploaded file:", 'comicpress-manager');
    ?>
</th>
          <td>
            <input id="multiple-new-post-checkbox" type="checkbox" name="new_post" value="yes" checked />
            <label for="multiple-new-post-checkbox"><em>(if you only want to upload a series of files to replace others, leave this unchecked)</em></label>
          </td>
        </tr>
      </table>

      <div id="multiple-new-post-holder">
        <table class="form-table" id="specify-date-holder">
          <tr>
            <th scope="row"><?php 
    _e("Date for uploaded file:", 'comicpress-manager');
    ?>
</th>
            <td>
              <div class="curtime"><input type="text" id="override-date" name="override-date" /> <?php 
    _e("<em>(click to open calendar. for single file uploads only. can accept any date format parseable by <a href=\"http://us.php.net/strtotime\" target=\"php\">strtotime()</a>)</em>", 'comicpress-manager');
    ?>
</div>
            </td>
          </tr>
        </table>

        <?php 
    cpm_post_editor(420);
    ?>

        <table class="form-table">
          <tr>
            <td align="center">
              <input class="button" id="top-submit" type="submit" value="<?php 
    if (extension_loaded("zip")) {
        _e("Upload Image &amp; Zip Files", 'comicpress-manager');
    } else {
        _e("Upload Image Files", 'comicpress-manager');
    }
    ?>
" />
            </td>
          </tr>
        </table>
      </div>
    </div>
  </form>
  <script type="text/javascript">
    Calendar.setup({
      inputField: "override-date",
      ifFormat: "%Y-%m-%d",
      button: "override-date"
    });
  </script>

  <?php 
    $activity_content = ob_get_clean();
    cpm_wrap_content($help_content, $activity_content);
}
/**
 * Show the comic in the Post editor.
 */
function cpm_show_comic()
{
    global $post, $cpm_config;
    $form_target = plugin_basename(realpath(dirname(__FILE__) . "/../comicpress_manager_admin.php"));
    read_current_theme_comicpress_config();
    $has_comic_file = false;
    $in_comics_category = false;
    $thumbnails_to_generate = cpm_get_thumbnails_to_generate();
    $post_categories = array();
    $comic_categories = array();
    extract(cpm_normalize_storyline_structure());
    foreach ($category_tree as $node) {
        $comic_categories[] = end(explode("/", $node));
    }
    if ($post->ID !== 0) {
        $post_time = time();
        foreach (array('post_date', 'post_modified', 'post_date_gmt', 'post_modified_gmt') as $time_value) {
            if (($result = strtotime($post->{$time_value})) !== false) {
                $post_time = $result;
                break;
            }
        }
        $post_categories = wp_get_post_categories($post->ID);
        if (isset($cpm_config->properties['comiccat'])) {
            $in_comics_category = count(array_intersect($comic_categories, $post_categories)) > 0;
        }
        $ok = true;
        if (cpm_get_subcomic_directory() !== false) {
            $ok = in_array(get_option('comicpress-manager-manage-subcomic'), wp_get_post_categories($post->ID));
        }
        if ($ok) {
            if (($comic = find_comic_by_date($post_time)) !== false) {
                $comic_uri = cpm_build_comic_uri($comic);
                $comic_filename = preg_replace('#^.*/([^\\/]*)$#', '\\1', $comic_uri);
                $link = "<strong><a target=\"comic_window\" href=\"{$comic_uri}\">{$comic_filename}</a></strong>";
                $date_root = substr($comic_filename, 0, strlen(date(CPM_DATE_FORMAT)));
                $thumbnails_found = cpm_find_thumbnails_by_filename($comic);
                $icon_file_to_use = $comic;
                foreach (array('rss', 'archive') as $type) {
                    if (isset($thumbnails_found[$type])) {
                        $icon_file_to_use = $thumbnails_found[$type];
                    }
                }
                $icon_uri = cpm_build_comic_uri($icon_file_to_use);
                $has_comic_file = true;
            }
        }
    }
    ?>

  <script type="text/javascript">
    function show_comic() {
      if ($('comic-icon').offsetWidth > $('comic-icon').offsetHeight) {
        $('preview-comic').width = 400;
      } else {
        $('preview-comic').height = 400;
      }
      Element.clonePosition('comic-hover', 'comic-icon', { setWidth: false, setHeight: false, offsetTop: -((Element.getDimensions('comic-hover')['height'] - Element.getDimensions('comic-icon')['height'])/2) });
      $('comic-hover').show();
    }

    function hide_comic() { $('comic-hover').hide(); }

    var all_comic_categories = [ <?php 
    echo implode(",", $comic_categories);
    ?>
 ];
    var storyline_enabled = <?php 
    echo get_option('comicpress-enable-storyline-support') == 1 ? 'true' : 'false';
    ?>
;

    Event.observe(window, 'load', function() {
      $('post').encoding = "multipart/form-data";
    });
  </script>

  <?php 
    if (count($cpm_config->comic_files) == 0) {
        ?>
    <div style="border: solid #daa 1px; background-color: #ffe7e7; padding: 5px">
      <strong>It looks like this is a new ComicPress install.</strong> You should test to make
      sure uploading works correctly by visiting <a href="admin.php?page=<?php 
        echo plugin_basename(realpath(dirname(__FILE__) . '/../comicpress_manager_admin.php'));
        ?>
">ComicPress -> Upload</a>.
    </div>
  <?php 
    }
    ?>
  <?php 
    if ($has_comic_file) {
        ?>
    <div id="comic-hover" style="border: solid black 1px; position: absolute; display: none" onmouseout="hide_comic()">
      <img id="preview-comic" src="<?php 
        echo $comic_uri;
        ?>
" />
    </div>
    <a href="#" onclick="return false" onmouseover="show_comic()"><img id="comic-icon" src="<?php 
        echo $icon_uri;
        ?>
" height="100" align="right" /></a>
    <p>
      <?php 
        printf(__("The comic that will be shown with this post is %s.", 'comicpress-manager'), $link);
        ?>
      <?php 
        _e("Mouse over the icon to the right to see a larger version of the image.", 'comicpress-manager');
        ?>
    </p>

    <?php 
        if (cpm_get_subcomic_directory() !== false) {
            printf(__("Comic files will be uploaded to the <strong>%s</strong> comic subdirectory.", 'comicpress-manager'), get_cat_name(get_option('comicpress-manager-manage-subcomic')));
        }
        ?>

    <?php 
        if (count($thumbnails_found) > 0) {
            ?>
      <p><?php 
            _e("The following thumbnails for this comic were also found:", 'comicpress-manager');
            ?>
        <?php 
            foreach ($thumbnails_found as $type => $file) {
                ?>
          <a target="comic_window" href="<?php 
                echo cpm_build_comic_uri(CPM_DOCUMENT_ROOT . '/' . $file);
                ?>
"><?php 
                echo $type;
                ?>
</a>
        <?php 
            }
            ?>
      </p>
    <?php 
        }
        ?>
  <?php 
    }
    ?>

  <?php 
    if (cpm_option("cpm-edit-post-integrate") == 1) {
        ?>
    <p><em><strong>ComicPress Manager Edit Post file management is enabled.</strong></em> Any changes to post date, or deleting this post, will affect any associated comic files.</p>
  <?php 
    }
    ?>

  <p><strong>NOTE: Upload errors will not be reported.</strong> If you are having trouble uploading files, use the <a href="admin.php?page=<?php 
    echo plugin_basename(realpath(dirname(__FILE__) . '/../comicpress_manager_admin.php'));
    ?>
">ComicPress -> Upload</a> screen.</p>

  <table class="form-table">
    <tr>
      <th scope="row">
        <?php 
    if ($has_comic_file) {
        ?>
          <?php 
        _e("Replace This Image", 'comicpress-manager');
        ?>
        <?php 
    } else {
        ?>
          <?php 
        _e("Upload a New Single Image", 'comicpress-manager');
        ?>
        <?php 
    }
    ?>
      </th>
      <td>
        <input type="hidden" name="MAX_FILE_SIZE" value="<?php 
    echo cpm_short_size_string_to_bytes(ini_get('upload_max_filesize'));
    ?>
" />
        <input type="file" id="comicpress-replace-image" name="comicpress-replace-image" class="button" /> <?php 
    echo empty($thumbnails_to_generate) ? "" : __("<em>(thumbnails will be generated)</em>", 'comicpress-manager');
    ?>
<br />
        <?php 
    if ($has_comic_file) {
        ?>
          <input type="hidden" name="overwrite-existing-file-choice" value="<?php 
        echo $comic_filename;
        ?>
" />
        <?php 
    }
    ?>
        <input type="hidden" name="upload-destination" value="comic" />
        <input type="hidden" name="thumbnails" value="yes" />
      </td>
      <script type="text/javascript">
        var handle_click = function() {
          var any_checked = false
          $$('input[name="post_category[]"]').each(function(i) {
            if (i.type == "radio") {
              if (i.checked) {
                any_checked = true;
              }
            }
          });

          if (!any_checked) {
            var has_checked = false;
            $$('input[name="post_category[]"]').each(function(i) {
              if (!has_checked) {
                if (i.type == "radio") {
                  i.checked = true;
                  has_checked = true;
                }
              }
            });
          }
        };

        [ 'click', 'blur' ].each(function(w) { $('comicpress-replace-image').observe(w, handle_click); });
      </script>
    </tr>
    <?php 
    if (cpm_option('cpm-skip-checks') != 1) {
        if (!function_exists('get_comic_path')) {
            ?>
          <tr>
            <td colspan="2" style="background-color: #fee; border: solid #daa 1px">
              <?php 
            _e('<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');
            ?>
            </td>
          </tr>
        <?php 
        }
    }
    ?>
    <?php 
    if (get_option('comicpress-enable-storyline-support') == 1) {
        ?>
      <tr>
        <th scope="row">
          <?php 
        if (count($category_tree) > 1) {
            _e("Storyline", 'comicpress-manager');
        } else {
            _e("Category", 'comicpress-manager');
        }
        ?>
        </th>
        <td>
          <?php 
        cpm_display_storyline_checkboxes($category_tree, $post_categories, null, "post_category");
        ?>
        </td>
      </tr>
    <?php 
    }
    ?>
    <tr>
      <th scope="row"><?php 
    _e('&lt;img title&gt;/hover text', 'comicpress-manager');
    ?>
</th>
      <td><input type="text" name="comicpress-img-title" style="width:99%" value="<?php 
    echo get_post_meta($post->ID, 'hovertext', true);
    ?>
" /></td>
    </tr>
    <tr>
      <th scope="row"><?php 
    _e("Transcript", 'comicpress-manager');
    ?>
</th>
      <td>
        <textarea name="comicpress-transcript" rows="8" style="width:99%"><?php 
    echo get_post_meta($post->ID, 'transcript', true);
    ?>
</textarea>
        <?php 
    if (!is_plugin_active('what-did-they-say/what-did-they-say.php')) {
        ?>
          <p>
            <?php 
        _e('Want even better control over your transcripts? Try <a href="http://wordpress.org/extend/plugins/what-did-they-say/" target="wdts">What Did They Say?!?</a>', 'comicpress-manager');
        ?>
          </p>
        <?php 
    }
    ?>
      </td>
    </tr>
  </table>
  
  <?php 
}
/**
 * Write Comic Post is the QuomicPress panel on the Dashboard..
 */
function cpm_manager_write_comic($form_target, $show_header = true)
{
    global $cpm_config;
    $ok_to_generate_thumbs = false;
    $thumbnails_to_generate = array();
    $cpm_config->need_calendars = true;
    $thumbnails_to_generate = cpm_get_thumbnails_to_generate();
    $go_live_time_string = cpm_option('cpm-default-post-time') == "now" ? __("<strong>now</strong>", 'comicpress-manager') : sprintf(__("at <strong>%s</strong>", 'comicpress-manager'), cpm_option('cpm-default-post-time'));
    cpm_write_global_styles_scripts();
    ?>
  <div class="wrap">
    <?php 
    cpm_handle_warnings();
    ?>
    <?php 
    if (count($cpm_config->errors) == 0) {
        ?>
      <?php 
        if ($show_header) {
            ?>
        <h2><?php 
            _e("Write Comic Post", 'comicpress-manager');
            ?>
</h2>
      <?php 
        }
        ?>

      <?php 
        if (count($cpm_config->comic_files) == 0 && cpm_get_subcomic_directory() === false) {
            ?>
        <div style="border: solid #daa 1px; background-color: #ffe7e7; padding: 5px">
          <strong>It looks like this is a new ComicPress install.</strong> You should test to make
          sure uploading works correctly by visiting <a href="admin.php?page=<?php 
            echo plugin_basename(realpath(dirname(__FILE__) . '/../comicpress_manager_admin.php'));
            ?>
">ComicPress -> Upload</a>.
        </div>
      <?php 
        }
        ?>

      <p>
        <?php 
        printf(__("<strong>Upload a single comic file</strong> and immediately start editing the associated published post. Your post will be going live %s on the provided date and will be posted in the <strong>%s</strong> category.", 'comicpress-manager'), $go_live_time_string, generate_comic_categories_options('category'));
        ?>

        <?php 
        if (cpm_get_subcomic_directory() !== false) {
            printf(__("Comic files will be uploaded to the <strong>%s</strong> comic subdirectory.", 'comicpress-manager'), get_cat_name(get_option('comicpress-manager-manage-subcomic')));
        }
        ?>

        <?php 
        if (!empty($thumbnails_to_generate)) {
            $thumbnail_strings = array();
            foreach ($thumbnails_to_generate as $type) {
                $thumbnail_strings[] = sprintf(__("<strong>%s</strong> thumbnails that are <strong>%spx</strong> wide", 'comicpress-manager'), $type, $cpm_config->properties["{$type}_comic_width"]);
            }
            ?>
          <?php 
            printf(__("You'll be generating: %s.", 'comicpress-manager'), implode(", ", $thumbnail_strings));
            ?>
        <?php 
        }
        ?>
      </p>

      <form action="?page=<?php 
        echo $form_target;
        ?>
" method="post" enctype="multipart/form-data">
        <input type="hidden" name="MAX_FILE_SIZE" value="<?php 
        echo cpm_short_size_string_to_bytes(ini_get('upload_max_filesize'));
        ?>
" />
        <input type="hidden" name="action" value="write-comic-post" />
        <input type="hidden" name="upload-destination" value="comic" />
        <input type="hidden" name="thumbnails" value="yes" />
        <input type="hidden" name="new_post" value="yes" />
        <?php 
        echo generate_comic_categories_options('in-comic-category[]', false);
        ?>
        <input type="hidden" name="time" value="<?php 
        echo cpm_option('cpm-default-post-time');
        ?>
" />

        <table class="form-table">
          <tr>
            <th scope="row"><?php 
        _e('File:', 'comicpress-manager');
        ?>
</th>
            <td><input type="file" name="upload" /></td>
          </tr>
          <?php 
        if (count($category_checkboxes = cpm_generate_additional_categories_checkboxes()) > 0) {
            ?>
            <tr>
              <th scope="row"><?php 
            _e("Additional Categories:", 'comicpress-manager');
            ?>
</th>
              <td><?php 
            echo implode("\n", $category_checkboxes);
            ?>
</td>
            </tr>
          <?php 
        }
        ?>
          <tr>
            <th scope="row"><?php 
        _e("Post date (leave blank if already in filename):", 'comicpress-manager');
        ?>
</th>
            <td>
              <div class="curtime"><input type="text" id="override-date" name="override-date" /></div>
            </td>
          </tr>
          <tr>
            <td colspan="2"><input type="submit" class="button" value="Upload Comic File and Edit Post" /></td>
          </tr>
        </table>
      </form>
      <script type="text/javascript">
        Calendar.setup({
          inputField: "override-date",
          ifFormat: "%Y-%m-%d",
          button: "override-date"
        });
      </script>
    <?php 
    }
    ?>
  </div>

  <?php 
}