/**
 * Write the current ComicPress Config to disk.
 */
function write_comicpress_config_functions_php($filepath, $just_show_config = false, $use_default_file = false)
{
    global $cpm_config, $default_comicpress_config_file;
    $file_lines = array();
    if ($use_default_file) {
        $file_lines = $default_comicpress_config_file;
    } else {
        foreach (file($filepath) as $line) {
            $file_lines[] = rtrim($line, "\r\n");
        }
    }
    include 'cp_configuration_options.php';
    $properties_written = array();
    $closing_line = null;
    for ($i = 0; $i < count($file_lines); $i++) {
        foreach (array_keys($cpm_config->properties) as $variable) {
            if (!in_array($variable, $properties_written)) {
                if (preg_match("#\\\${$variable}\\ *\\=\\ *([^\\;]*)\\;#", $file_lines[$i], $matches) > 0) {
                    $value = $cpm_config->properties[$variable];
                    $file_lines[$i] = '$' . $variable . ' = "' . $value . '";';
                    $properties_written[] = $variable;
                }
            }
        }
        if (strpos($file_lines[$i], "?>") !== false) {
            $closing_line = $i;
        }
    }
    foreach ($comicpress_configuration_options as $option_info) {
        $varname = isset($option_info['variable_name']) ? $option_info['variable_name'] : $option_info['id'];
        $value = isset($cpm_config->properties[$varname]) ? $cpm_config->properties[$varname] : $option_info['default'];
        if (!in_array($varname, $properties_written)) {
            $comicpress_lines = array();
            $comicpress_lines[] = "//{$option_info['name']} - {$option_info['description']} (default \"{$option_info['default']}\")";
            $comicpress_lines[] = "\${$varname} = \"{$value}\";";
            $comicpress_lines[] = "";
            array_splice($file_lines, $closing_line, 0, $comicpress_lines);
        }
    }
    $file_output = implode("\n", $file_lines);
    if (!$just_show_config) {
        if (can_write_comicpress_config($filepath)) {
            $target_filepath = $filepath . '.' . time();
            $temp_filepath = $target_filepath . '-tmp';
            if (@file_write_contents($temp_filepath, $file_output) !== false) {
                if (file_exists($temp_filepath)) {
                    @chmod($temp_filepath, CPM_FILE_UPLOAD_CHMOD);
                    if (@rename($filepath, $target_filepath)) {
                        if (@rename($temp_filepath, $filepath)) {
                            return array($target_filepath);
                        } else {
                            @unlink($temp_filepath);
                            @rename($target_filepath, $filepath);
                        }
                    } else {
                        @unlink($temp_filepath);
                    }
                }
            }
        }
    }
    return $file_output;
}
/**
 * Read information about the current installation.
 */
function cpm_read_information_and_check_config()
{
    global $cpm_config, $cpm_attempted_document_roots, $blog_id, $wpmu_version;
    $cpm_config->config_method = read_current_theme_comicpress_config();
    $cpm_config->config_filepath = get_functions_php_filepath();
    $cpm_config->can_write_config = can_write_comicpress_config($cpm_config->config_filepath);
    $cpm_config->path = get_comic_folder_path();
    $cpm_config->plugin_path = PLUGINDIR . '/' . plugin_basename(__FILE__);
    foreach (array_keys($cpm_config->separate_thumbs_folder_defined) as $type) {
        $cpm_config->separate_thumbs_folder_defined[$type] = $cpm_config->properties['comic_folder'] != $cpm_config->properties[$type . '_comic_folder'];
    }
    $cpm_config->errors = array();
    $cpm_config->warnings = array();
    $cpm_config->detailed_warnings = array();
    $cpm_config->messages = array();
    $cpm_config->show_config_editor = true;
    $folders = array(array('comic folder', 'comic_folder', true, ""), array('RSS feed folder', 'rss_comic_folder', false, 'rss'), array('archive folder', 'archive_comic_folder', false, 'archive'), array('mini thumb folder', 'mini_comic_folder', false, 'mini'));
    foreach ($folders as $folder_info) {
        list($name, $property, $is_fatal, $thumb_type) = $folder_info;
        if ($thumb_type != "") {
            $cpm_config->thumbs_folder_writable[$thumb_type] = null;
        }
    }
    if (cpm_option("cpm-skip-checks") == 1) {
        // if the user knows what they're doing, disabling all of the checks improves performance
        foreach ($folders as $folder_info) {
            list($name, $property, $is_fatal, $thumb_type) = $folder_info;
            $path = CPM_DOCUMENT_ROOT . '/' . $cpm_config->properties[$property];
            if ($thumb_type != "") {
                $cpm_config->thumbs_folder_writable[$thumb_type] = true;
            }
        }
        foreach (array('comic', 'blog') as $type) {
            $result = (object) get_category($cpm_config->properties["{$type}cat"]);
            if (!is_wp_error($result)) {
                $cpm_config->{"{$type}_category_info"} = get_object_vars($result);
            }
        }
        $cpm_config->comic_files = cpm_read_comics_folder();
    } else {
        // quick check to see if the theme is ComicPress.
        // this needs to be made more robust.
        if (preg_match('/ComicPress/', get_current_theme()) == 0) {
            $cpm_config->detailed_warnings[] = __("The current theme isn't the ComicPress theme.  If you've renamed the theme, ignore this warning.", 'comicpress-manager');
        }
        if (!extension_loaded('zip')) {
            $cpm_config->detailed_warnings[] = __("You do not have the Zip extension installed. Uploading a Zip file will not work.", 'comicpress-manager');
        }
        $any_cpm_document_root_failures = false;
        if (!$wpmu_version) {
            // is the site root configured properly?
            if (!file_exists(CPM_DOCUMENT_ROOT)) {
                $cpm_config->warnings[] = sprintf(__('The comics site root <strong>%s</strong> does not exist. Check your <a href="options-general.php">WordPress address and address settings</a>.', 'comicpress-manager'), CPM_DOCUMENT_ROOT);
                $any_cpm_document_root_failures = true;
            }
            if (!file_exists(CPM_DOCUMENT_ROOT . '/index.php')) {
                $cpm_config->warnings[] = sprintf(__('The comics site root <strong>%s</strong> does not contain a WordPress index.php file. Check your <a href="options-general.php">WordPress address and address settings</a>.', 'comicpress-manager'), CPM_DOCUMENT_ROOT);
                $any_cpm_document_root_failures = true;
            }
        }
        if ($any_cpm_document_root_failures) {
            $cpm_config->warnings[] = print_r($cpm_attempted_document_roots, true);
        }
        // folders that are the same as the comics folder won't be written to
        $all_the_same = array();
        foreach ($cpm_config->separate_thumbs_folder_defined as $type => $value) {
            if (!$value) {
                $all_the_same[] = $type;
            }
        }
        if (count($all_the_same) > 0) {
            $cpm_config->detailed_warnings[] = sprintf(__("The <strong>%s</strong> folders and the comics folder are the same.  You won't be able to generate thumbnails until you change these folders.", 'comicpress-manager'), implode(", ", $all_the_same));
        }
        if (cpm_option('cpm-did-first-run') == 1) {
            // check the existence and writability of all image folders
            foreach ($folders as $folder_info) {
                list($name, $property, $is_fatal, $thumb_type) = $folder_info;
                if ($thumb_type == "" || $cpm_config->separate_thumbs_folder_defined[$thumb_type] == true) {
                    $path = CPM_DOCUMENT_ROOT . '/' . $cpm_config->properties[$property];
                    if (!file_exists($path)) {
                        $cpm_config->errors[] = sprintf(__('The %1$s <strong>%2$s</strong> does not exist.  Did you create it within the <strong>%3$s</strong> folder?', 'comicpress-manager'), $name, $cpm_config->properties[$property], CPM_DOCUMENT_ROOT);
                    } else {
                        do {
                            $tmp_filename = "test-" . md5(rand());
                        } while (file_exists($path . '/' . $tmp_filename));
                        $ok_to_warn = true;
                        if ($thumb_type != "") {
                            $ok_to_warn = cpm_option("cpm-{$thumb_type}-generate-thumbnails") == 1;
                        }
                        if ($ok_to_warn) {
                            if (!@touch($path . '/' . $tmp_filename)) {
                                $message = sprintf(__('The %1$s <strong>%2$s</strong> is not writable by the Webserver.', 'comicpress-manager'), $name, $cpm_config->properties[$property]);
                                if ($is_fatal) {
                                    $cpm_config->errors[] = $message;
                                } else {
                                    $cpm_config->warnings[] = $message;
                                }
                                if ($thumb_type != "") {
                                    $cpm_config->thumbs_folder_writable[$thumb_type] = false;
                                }
                            } else {
                                if (@stat($path . '/' . $tmp_filename) === false) {
                                    $cpm_config->errors[] = __('<strong>Files written to the %s directory by the Webserver cannot be read again!</strong>  Are you using IIS7 with FastCGI?', $cpm_config->properties[$property]);
                                    if ($thumb_type != "") {
                                        $cpm_config->thumbs_folder_writable[$thumb_type] = false;
                                    }
                                }
                            }
                        }
                        if (is_null($cpm_config->thumbs_folder_writable[$thumb_type])) {
                            @unlink($path . '/' . $tmp_filename);
                            if ($thumb_type != "") {
                                $cpm_config->thumbs_folder_writable[$thumb_type] = true;
                            }
                        }
                    }
                }
            }
        }
        // to generate thumbnails, a supported image processor is needed
        if ($cpm_config->get_scale_method() == CPM_SCALE_NONE) {
            $cpm_config->detailed_warnings[] = __("No image resize methods are installed (GD or ImageMagick).  You are unable to generate thumbnails automatically.", 'comicpress-manager');
        }
        // are there enough categories created?
        if (count(get_all_category_ids()) < 2) {
            $cpm_config->errors[] = __("You need to define at least two categories, a blog category and a comics category, to use ComicPress.  Visit <a href=\"categories.php\">Manage -> Categories</a> and create at least two categories, then return here to continue your configuration.", 'comicpress-manager');
            $cpm_config->show_config_editor = false;
        } else {
            // ensure the defined comic category exists
            if (is_null($cpm_config->properties['comiccat'])) {
                // all non-blog categories are comic categories
                $cpm_config->comic_category_info = array('name' => __("All other categories", 'comicpress-manager'));
                $cpm_config->properties['comiccat'] = array_diff(get_all_category_ids(), array($cpm_config->properties['blogcat']));
                if (count($cpm_config->properties['comiccat']) == 1) {
                    $cpm_config->properties['comiccat'] = $cpm_config->properties['comiccat'][0];
                    $cpm_config->comic_category_info = get_object_vars(get_category($cpm_config->properties['comiccat']));
                }
            } else {
                if (!is_numeric($cpm_config->properties['comiccat'])) {
                    // the property is non-numeric
                    $cpm_config->errors[] = __("The comic category needs to be defined as a number, not an alphanumeric string.", 'comicpress-manager');
                } else {
                    // one comic category is specified
                    if (is_null($cpm_config->comic_category_info = get_category($cpm_config->properties['comiccat']))) {
                        $cpm_config->errors[] = sprintf(__("The requested category ID for your comic, <strong>%s</strong>, doesn't exist!", 'comicpress-manager'), $cpm_config->properties['comiccat']);
                    } else {
                        $cpm_config->comic_category_info = get_object_vars($cpm_config->comic_category_info);
                    }
                }
            }
            // ensure the defined blog category exists
            // TODO: multiple blog categories
            if (!is_numeric($cpm_config->properties['blogcat'])) {
                // the property is non-numeric
                $cpm_config->errors[] = __("The blog category needs to be defined as a number, not an alphanumeric string.", 'comicpress-manager');
            } else {
                if (is_null($cpm_config->blog_category_info = get_category($cpm_config->properties['blogcat']))) {
                    $cpm_config->errors[] = sprintf(__("The requested category ID for your blog, <strong>%s</strong>, doesn't exist!", 'comicpress-manager'), $cpm_config->properties['blogcat']);
                } else {
                    $cpm_config->blog_category_info = get_object_vars($cpm_config->blog_category_info);
                }
                if (!is_array($cpm_config->properties['blogcat']) && !is_array($cpm_config->properties['comiccat'])) {
                    if ($cpm_config->properties['blogcat'] == $cpm_config->properties['comiccat']) {
                        $cpm_config->warnings[] = __("Your comic and blog categories are the same.  This will cause browsing problems for visitors to your site.", 'comicpress-manager');
                    }
                }
            }
        }
        // a quick note if you have no comics uploaded.
        // could be a sign of something more serious.
        if (count($cpm_config->comic_files = cpm_read_comics_folder()) == 0) {
            $cpm_config->detailed_warnings[] = __("Your comics folder is empty!", 'comicpress-manager');
        }
    }
}