/**
 * Checks if the given option is not set and returns its default value.
 * 
 * @author Nevma (info@nevma.gr)
 * 
 * @param array  $options The associative array that holds the given options, which should be passed by reference
 *                        so it can be directly altered as necessary.
 * 
 * @param string $key     The name of the option to check if is set.
 * 
 * @return mixed The current value of the option if it is set or its default value if it is not set.
 */
function adaptive_images_plugin_check_empty_setting(&$options, $key)
{
    if (!isset($options[$key])) {
        $defaults = adaptive_images_plugin_get_default_settings();
        $options[$key] = $defaults[$key];
    }
}
/**
 * Validates the adaptive images submitted settings.
 * 
 * @author Nevma (info@nevma.gr)
 * 
 * @return The sanitized and validated data.
 */
function adaptive_images_admin_settings_sanitize($data)
{
    // To avoid the bug of sanitizing twice the first time the option is created.
    if (isset($data['sanitized']) && $data['sanitized']) {
        return $data;
    }
    // Get the defaults just in case.
    $defaults = adaptive_images_plugin_get_default_settings();
    // Resolutions field array validation.
    $resolutions = trim($data['resolutions']);
    $resolutions_array = explode(',', $resolutions);
    $resolutions_array_sanitized = array();
    for ($k = 0, $length = count($resolutions_array); $k < $length; $k++) {
        $resolution = trim($resolutions_array[$k]);
        $resolution = intval($resolution);
        if ($resolution > 0) {
            $resolutions_array_sanitized[] = $resolution;
        }
    }
    rsort($resolutions_array_sanitized);
    if (count($resolutions_array_sanitized) == 0) {
        $resolutions_array_sanitized = $defaults['resolutions'];
    }
    $data['resolutions'] = $resolutions_array_sanitized;
    adaptive_images_plugin_check_empty_setting($data, 'resolutions');
    // Landscape field validation.
    $landscape = isset($data['landscape']) && $data['landscape'] == 'on' ? TRUE : FALSE;
    $data['landscape'] = $landscape;
    adaptive_images_plugin_check_empty_setting($data, 'landscape');
    // Hidpi field validation.
    $hidpi = isset($data['hidpi']) && $data['hidpi'] == 'on' ? TRUE : FALSE;
    $data['hidpi'] = $hidpi;
    adaptive_images_plugin_check_empty_setting($data, 'hidpi');
    // CDN support field validation.
    $cdn_support = isset($data['cdn-support']) && $data['cdn-support'] == 'on' ? TRUE : FALSE;
    $data['cdn-support'] = $cdn_support;
    adaptive_images_plugin_check_empty_setting($data, 'cdn-support');
    // Cache field directory validation.
    $cache_directory = trim($data['cache-directory']);
    $cache_directory = preg_replace('/[^a-zA-Z\\d-_\\/]+/i', '', $cache_directory);
    $cache_directory = wp_normalize_path($cache_directory);
    $cache_directory = untrailingslashit($cache_directory);
    if (!adaptive_images_plugin_is_file_in_wp_content($cache_directory)) {
        $cache_directory == $defaults['cache-directory'];
    }
    $data['cache-directory'] = $cache_directory;
    adaptive_images_plugin_check_empty_setting($data, 'cache-directory');
    // Watched field directories validation.
    $watched_directories_string = trim($data['watched-directories']);
    $watched_directories_array = explode("\n", $watched_directories_string);
    $watched_directories_array_sanitized = array();
    foreach ($watched_directories_array as $directory) {
        $directory = preg_replace('/[^a-zA-Z\\d-_\\/]+/i', '', $directory);
        $directory = wp_normalize_path($directory);
        $directory = untrailingslashit($directory);
        if ($directory) {
            $watched_directories_array_sanitized[] = $directory;
        }
    }
    $data['watched-directories'] = $watched_directories_array_sanitized;
    adaptive_images_plugin_check_empty_setting($data, 'watched-directories');
    // JPEG quality field validation.
    $jpeg_quality = intval($data['jpeg-quality']);
    if ($jpeg_quality == 0) {
        $jpeg_quality = $defaults['jpeg-quality'];
    }
    $data['jpeg-quality'] = $jpeg_quality;
    adaptive_images_plugin_check_empty_setting($data, 'jpeg-quality');
    // Sharpen field validation.
    $sharpen_images = isset($data['sharpen-images']) && $data['sharpen-images'] == 'on' ? TRUE : FALSE;
    $data['sharpen-images'] = $sharpen_images;
    adaptive_images_plugin_check_empty_setting($data, 'sharpen-images');
    // Watch cache field validation.
    $watch_cache = isset($data['watch-cache']) && $data['watch-cache'] == 'on' ? TRUE : FALSE;
    $data['watch-cache'] = $watch_cache;
    adaptive_images_plugin_check_empty_setting($data, 'watch-cache');
    // Browser cache field validation.
    $browser_cache = floatval($data['browser-cache']);
    if ($browser_cache < 0) {
        $browser_cache = $defaults['browser-cache'];
    }
    $data['browser-cache'] = $browser_cache;
    adaptive_images_plugin_check_empty_setting($data, 'browser-cache');
    // Save plugin version.
    $data['version'] = adaptive_images_plugin_get_version();
    // To avoid the bug of sanitizing twice the first time the option is created.
    $data['sanitized'] = TRUE;
    // Notify user appropriately.
    $message = 'Adaptive Images &mdash; Settings updated. <hr /> <p>The settings have been saved in the database.</p>';
    // Add the adaptive images .htaccess rewrite block.
    $result = adaptive_images_actions_update_htaccess($data);
    if (is_wp_error($result)) {
        $error_data = $result->get_error_data();
        $htaccess = $error_data['htaccess'];
        $permissions = adaptive_images_plugin_file_permissions($htaccess);
        $message .= '<p>' . $result->get_error_message() . ' ' . 'This probably means a filesystem error or a permissions problem: ' . '<code>' . $htaccess . ' => ' . $permissions . '</code>.' . '</p>' . '<p>' . 'Consider adding this code to your .htaccess file manually: ' . '<blockquote><pre>' . htmlspecialchars(trim($error_data['rewrite'])) . '</pre></blockquote>' . '</p>';
    } else {
        $message .= '<p>' . 'The .htaccess file was successfully updated: ' . '<code>' . adaptive_images_plugin_get_htaccess_file_path() . '</code>.' . '</p>';
    }
    // Save user settings PHP file.
    $result = adaptive_images_actions_save_user_settings($data);
    if (is_wp_error($result)) {
        $file = adaptive_images_plugin_get_user_settings_file_path();
        $permissions = adaptive_images_plugin_file_permissions($file);
        $message .= '<p>' . $result->get_error_message() . ' ' . 'This probably means a filesystem error or a permissions problem.' . '<code>' . $file . ' => ' . $permissions . '</code>. <br/>' . '</p>' . '<p>' . 'The plugin will still be able to function but with its default settings until this problem is resolved.' . '</p>';
    } else {
        $message .= '<p>' . 'The user settings PHP file  was successfully updated: ' . '<code>' . adaptive_images_plugin_get_user_settings_file_path() . '</code>.' . '</p>';
    }
    // Inform user accordingly.
    add_settings_error('adaptive-images-settings', 'adaptive-images-settings-error', $message, 'updated');
    return $data;
}