/**
 * 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;
}
/**
 * Saves the adaptive images settings in the designated PHP file.
 * 
 * @author Nevma (info@nevma.gr)
 * 
 * @param array $data The validated data submitted in the plugin admin settings page.
 * 
 * @return boolean|WP_Error Whether the user settings file was successfully saved or not!
 */
function adaptive_images_actions_save_user_settings($data)
{
    $settings_code = "<?php \n" . "\n" . "    //##############################################################################################\\\\\n" . "    //                                                                                              \\\\\n" . "    //  DO NOT EDIT THIS FILE MANUALLY. IT IS AUTOMATICALLY GENERATED BY THE PLUGIN SETTINGS PAGE.  \\\\\n" . "    //                                                                                              \\\\\n" . "\n" . "        // Device widths resolutions. \n" . "\n" . "        \$resolutions = array( " . implode(', ', $data['resolutions']) . " ); \n" . "\n" . "        // Whether to take the landscape width into account or not. \n" . "\n" . "        \$landscape = " . ($data['landscape'] ? 'TRUE' : 'FALSE') . "; \n" . "\n" . "        // Whether to show higher resolution images to HiDPI screens or not. \n" . "\n" . "        \$hidpi = " . ($data['hidpi'] ? 'TRUE' : 'FALSE') . "; \n" . "\n" . "        // The directory of the images cache. \n" . "\n" . "        \$cache_dir = \"" . $data['cache-directory'] . "\"; \n" . "\n" . "        // JPEG quality of resized images. \n" . "\n" . "        \$jpg_quality = " . $data['jpeg-quality'] . "; \n" . "\n" . "        // Sharpen resized images. \n" . "\n" . "        \$sharpen = " . ($data['sharpen-images'] ? 'TRUE' : 'FALSE') . "; \n" . "\n" . "        // Check for new versions of cached images. \n" . "\n" . "        \$watch_cache = " . ($data['watch-cache'] ? 'TRUE' : 'FALSE') . "; \n" . "\n" . "        // Browser cache duration for images. \n" . "\n" . "        \$browser_cache = 60 * 60 * 24 * " . $data['browser-cache'] . "; \n" . "\n" . "    //                                                                                              \\\\\n" . "    //  DO NOT EDIT THIS FILE MANUALLY. IT IS AUTOMATICALLY GENERATED BY THE PLUGIN SETTINGS PAGE.  \\\\\n" . "    //                                                                                              \\\\\n" . "    //==============================================================================================\\\\\n" . "\n" . "?>";
    $file = adaptive_images_plugin_get_user_settings_file_path();
    $bytes = @file_put_contents($file, $settings_code);
    if ($bytes === FALSE) {
        return new WP_Error('adaptive-images-user-settings-not-updated', 'User settings file could not be updated.', array('file' => $file));
    } else {
        return TRUE;
    }
}