/**
 * Handle uploading a set of files.
 * @param array $files A list of valid $_FILES keys to process.
 */
function cpm_handle_file_uploads($files)
{
    global $cpm_config;
    $posts_created = array();
    $duplicate_posts = array();
    $files_uploaded = array();
    $thumbnails_written = array();
    $invalid_filenames = array();
    $thumbnails_not_written = array();
    $files_not_uploaded = array();
    $invalid_image_types = array();
    $gd_rename_file = array();
    $did_convert_cmyk_jpeg = array();
    $target_root = CPM_DOCUMENT_ROOT . '/' . $cpm_config->properties[$_POST['upload-destination'] . "_folder"];
    if (($subdir = cpm_get_subcomic_directory()) !== false) {
        $target_root .= '/' . $subdir;
    }
    $write_thumbnails = isset($_POST['thumbnails']) && $_POST['upload-destination'] == "comic";
    $new_post = isset($_POST['new_post']) && $_POST['upload-destination'] == "comic";
    $ok_to_keep_uploading = true;
    $files_created_in_operation = array();
    $filename_original_titles = array();
    foreach ($files as $key) {
        if (is_uploaded_file($_FILES[$key]['tmp_name'])) {
            if ($_FILES[$key]['error'] != 0) {
                switch ($_FILES[$key]['error']) {
                    case UPLOAD_ERR_INI_SIZE:
                    case UPLOAD_ERR_FORM_SIZE:
                        $cpm_config->warnings[] = sprintf(__("<strong>The file you uploaded was too large.</strong>  The max allowed filesize for uploads to your server is %s.", 'comicpress-manager'), ini_get('upload_max_filesize'));
                        break;
                    case UPLOAD_ERR_NO_FILE:
                        break;
                    default:
                        $cpm_config->warnings[] = sprintf(__("<strong>There was an error in uploading.</strong>  The <a href='http://php.net/manual/en/features.file-upload.errors.php'>PHP upload error code</a> was %s.", 'comicpress-manager'), $_FILES[$key]['error']);
                        break;
                }
            } else {
                if (strpos($_FILES[$key]['name'], ".zip") !== false) {
                    $invalid_files = array();
                    //harmonious zip_open zip_entry_name zip_read zip_entry_read zip_entry_open zip_entry_filesize zip_entry_close zip_close
                    if (extension_loaded("zip")) {
                        if (is_resource($zip = zip_open($_FILES[$key]['tmp_name']))) {
                            while ($zip_entry = zip_read($zip)) {
                                if (zip_entry_open($zip, $zip_entry, "r")) {
                                    $temp_path = $target_root . '/' . md5(rand());
                                    file_write_contents($temp_path, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)));
                                    $comic_file = zip_entry_name($zip_entry);
                                    $target_filename = pathinfo(zip_entry_name($zip_entry), PATHINFO_BASENAME);
                                    $result = cpm_breakdown_comic_filename($target_filename, true);
                                    if (file_exists($temp_path)) {
                                        extract(cpm_do_gd_file_check_on_upload($temp_path, $target_filename));
                                        if ($result !== false) {
                                            extract($result, EXTR_PREFIX_ALL, "filename");
                                            if ($file_ok) {
                                                if (($obfuscated_filename = cpm_obfuscate_filename($target_filename)) !== $target_filename) {
                                                    $cpm_config->messages[] = sprintf(__('Uploaded file %1$s renamed to %2$s.', 'comicpress-manager'), $target_filename, $obfuscated_filename);
                                                    $filename_original_titles[$obfuscated_filename] = $result['converted_title'];
                                                    $target_filename = $obfuscated_filename;
                                                }
                                                @rename($temp_path, $target_root . '/' . $target_filename);
                                                $files_created_in_operation[] = $target_root . '/' . $target_filename;
                                                $files_uploaded[] = $target_filename;
                                                if ($gd_did_rename) {
                                                    $gd_rename_file[] = $comic_file;
                                                }
                                                if ($did_filecheck) {
                                                    if ($is_cmyk) {
                                                        $did_convert_cmyk_jpeg[] = $comic_file;
                                                    }
                                                }
                                            } else {
                                                if ($did_filecheck) {
                                                    $invalid_image_types[] = $comic_file;
                                                } else {
                                                    $invalid_filenames[] = $comic_file;
                                                }
                                            }
                                        } else {
                                            $files_not_uploaded[] = $comic_file;
                                        }
                                    } else {
                                        $invalid_filenames[] = $comic_file;
                                    }
                                    @unlink($temp_path);
                                    zip_entry_close($zip_entry);
                                }
                                if (($result = cpm_breakdown_comic_filename($target_filename, true)) !== false) {
                                    extract($result, EXTR_PREFIX_ALL, 'filename');
                                    $target_path = $target_root . '/' . $target_filename;
                                    if (isset($_POST['upload-date-format']) && !empty($_POST['upload-date-format'])) {
                                        $target_filename = date(CPM_DATE_FORMAT, strtotime($result['date'])) . $result['title'] . '.' . pathinfo($_FILES[$key]['name'], PATHINFO_EXTENSION);
                                    }
                                } else {
                                    $invalid_filenames[] = $comic_file;
                                }
                            }
                            zip_close($zip);
                        }
                    } else {
                        $cpm_config->warnings[] = sprintf(__("The Zip extension is not installed. %s was not processed.", 'comicpress-manager'), $_FILES[$key]['name']);
                    }
                    //harmonious_end
                } else {
                    $target_filename = $_FILES[$key]['name'];
                    if (get_magic_quotes_gpc()) {
                        $target_filename = stripslashes($target_filename);
                    }
                    $tried_replace = false;
                    if (!empty($_POST['overwrite-existing-file-choice'])) {
                        $tried_replace = true;
                        $original_filename = $target_filename;
                        $target_filename = $_POST['overwrite-existing-file-choice'];
                        if (get_magic_quotes_gpc()) {
                            $target_filename = stripslashes($target_filename);
                        }
                        $new_post = false;
                        if (pathinfo($original_filename, PATHINFO_EXTENSION) != pathinfo($target_filename, PATHINFO_EXTENSION)) {
                            if (@unlink($target_root . '/' . $target_filename)) {
                                foreach (cpm_get_thumbnails_to_generate() as $type) {
                                    $path = CPM_DOCUMENT_ROOT . '/' . $cpm_config->properties[$type . "_comic_folder"];
                                    if (($subdir = cpm_get_thumbnails_to_generate()) !== false) {
                                        $path .= '/' . $subdir;
                                    }
                                    @unlink($path . '/' . $target_filename);
                                }
                            }
                            $target_filename = preg_replace('#\\.[^\\.]+$#', '', $target_filename) . '.' . pathinfo($original_filename, PATHINFO_EXTENSION);
                        }
                        $result = cpm_breakdown_comic_filename($target_filename);
                        $cpm_config->messages[] = sprintf(__('Uploaded file <strong>%1$s</strong> renamed to <strong>%2$s</strong>.', 'comicpress-manager'), $original_filename, $target_filename);
                    } else {
                        if (count($files) == 1) {
                            if (!empty($_POST['override-date'])) {
                                $date = strtotime($_POST['override-date']);
                                if ($date !== false && $date !== -1) {
                                    $new_date = date(CPM_DATE_FORMAT, $date);
                                    $old_filename = $target_filename;
                                    if (($target_result = cpm_breakdown_comic_filename($target_filename, true)) !== false) {
                                        $target_filename = $new_date . $target_result['title'] . '.' . pathinfo($target_filename, PATHINFO_EXTENSION);
                                    } else {
                                        $target_filename = $new_date . '-' . $target_filename;
                                    }
                                    if ($old_filename !== $target_filename) {
                                        $cpm_config->messages[] = sprintf(__('Uploaded file %1$s renamed to %2$s.', 'comicpress-manager'), $_FILES[$key]['name'], $target_filename);
                                    }
                                    $result = cpm_breakdown_comic_filename($target_filename);
                                } else {
                                    if (preg_match('/\\S/', $_POST['override-date']) > 0) {
                                        $cpm_config->warnings[] = sprintf(__("Provided override date %s is not parseable by strtotime().", 'comicpress-manager'), $_POST['override-date']);
                                    }
                                }
                            }
                        }
                        $result = cpm_breakdown_comic_filename($target_filename, true);
                        if ($result !== false) {
                            // bad file, can we get a date attached?
                            if (isset($_POST['upload-date-format']) && !empty($_POST['upload-date-format'])) {
                                $target_filename = date(CPM_DATE_FORMAT, strtotime($result['date'])) . $result['title'] . '.' . pathinfo($_FILES[$key]['name'], PATHINFO_EXTENSION);
                            }
                        }
                    }
                    $comic_file = $_FILES[$key]['name'];
                    extract(cpm_do_gd_file_check_on_upload($_FILES[$key]['tmp_name'], $target_filename));
                    $output_file = null;
                    if ($result !== false) {
                        extract($result, EXTR_PREFIX_ALL, "filename");
                        if ($file_ok) {
                            if (($obfuscated_filename = cpm_obfuscate_filename($target_filename)) !== $target_filename) {
                                $cpm_config->messages[] = sprintf(__('Uploaded file %1$s renamed to %2$s.', 'comicpress-manager'), $target_filename, $obfuscated_filename);
                                $filename_original_titles[$obfuscated_filename] = $result['converted_title'];
                                $target_filename = $obfuscated_filename;
                            }
                            $output_file = $target_root . '/' . $target_filename;
                            @move_uploaded_file($_FILES[$key]['tmp_name'], $output_file);
                            $files_created_in_operation[] = $output_file;
                            if (file_exists($output_file)) {
                                $files_uploaded[] = $target_filename;
                                if ($gd_did_rename) {
                                    $gd_rename_file[] = $comic_file;
                                }
                            } else {
                                $files_not_uploaded[] = $target_filename;
                            }
                            if ($did_filecheck) {
                                if ($is_cmyk) {
                                    $did_convert_cmyk_jpeg[] = $comic_file;
                                }
                            }
                        } else {
                            if ($did_filecheck) {
                                $invalid_image_types[] = $comic_file;
                            } else {
                                $invalid_filenames[] = $comic_file;
                            }
                        }
                    } else {
                        if (!$tried_replace) {
                            $invalid_filenames[] = $comic_file;
                        }
                    }
                    if ($cpm_config->scale_method_cache == CPM_SCALE_IMAGEMAGICK && cpm_option('cpm-strip-icc-profiles') == "1" && !empty($output_file)) {
                        $temp_output_file = $output_file . '.' . md5(rand());
                        $command = array("convert", "\"{$output_file}\"", "-strip", "\"{$temp_output_file}\"");
                        $strip_profiles = escapeshellcmd(implode(" ", $command));
                        exec($strip_profiles);
                        if (file_exists($temp_output_file)) {
                            @unlink($output_file);
                            @rename($temp_output_file, $output_file);
                        }
                    }
                }
            }
        }
        if ($wpmu_version) {
            if (cpm_wpmu_is_over_storage_limit()) {
                $ok_to_keep_uploading = false;
                break;
            }
        }
    }
    if ($ok_to_keep_uploading) {
        foreach ($files_uploaded as $target_filename) {
            $target_path = $target_root . '/' . $target_filename;
            @chmod($target_path, CPM_FILE_UPLOAD_CHMOD);
            if ($write_thumbnails) {
                $wrote_thumbnail = cpm_write_thumbnail($target_path, $target_filename);
            }
            if (!is_null($wrote_thumbnail)) {
                if (is_array($wrote_thumbnail)) {
                    $thumbnails_written[] = $target_filename;
                    $files_created_in_operation = array_merge($files_created_in_operation, $wrote_thumbnail);
                } else {
                    $thumbnails_not_written[] = $target_filename;
                }
            }
        }
        if ($wpmu_version) {
            if (cpm_wpmu_is_over_storage_limit()) {
                $ok_to_keep_uploading = false;
            }
        }
    }
    if ($ok_to_keep_uploading) {
        foreach ($files_uploaded as $target_filename) {
            if ($new_post) {
                extract(cpm_breakdown_comic_filename($target_filename), EXTR_PREFIX_ALL, "filename");
                if (isset($filename_original_titles[$target_filename])) {
                    $filename_converted_title = $filename_original_titles[$target_filename];
                }
                if (($post_hash = generate_post_hash($filename_date, $filename_converted_title)) !== false) {
                    extract($post_hash);
                    $ok_to_create_post = true;
                    if (isset($_POST['duplicate_check'])) {
                        $ok_to_create_post = ($post_id = post_exists($post_title, $post_content, $post_date)) == 0;
                    }
                    if ($ok_to_create_post) {
                        if (!is_null($post_id = wp_insert_post($post_hash))) {
                            $posts_created[] = get_post($post_id, ARRAY_A);
                            foreach (array('hovertext', 'transcript') as $field) {
                                if (!empty($_POST["{$field}-to-use"])) {
                                    update_post_meta($post_id, $field, $_POST["{$field}-to-use"]);
                                }
                            }
                        }
                    } else {
                        $duplicate_posts[] = array(get_post($post_id, ARRAY_A), $target_filename);
                    }
                } else {
                    $invalid_filenames[] = $target_filename;
                }
            }
        }
        cpm_display_operation_messages(compact('invalid_filenames', 'files_uploaded', 'files_not_uploaded', 'thumbnails_written', 'thumbnails_not_written', 'posts_created', 'duplicate_posts', 'invalid_image_types', 'gd_rename_file', 'did_convert_cmyk_jpeg'));
    } else {
        $cpm_config->messages = array();
        $cpm_config->warnings = array($cpm_config->wpmu_disk_space_message);
        foreach ($files_created_in_operation as $file) {
            @unlink($file);
        }
    }
    return array($posts_created, $duplicate_posts);
}
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');
    }
}