/**
 * This function allows the platform admin to choose the default stylesheet
 * @author Patrick Cool <*****@*****.**>, Ghent University
 * @author Julio Montoya <*****@*****.**>, Chamilo
 */
function handle_stylesheets()
{
    global $_configuration;
    // Current style.
    $currentstyle = api_get_setting('stylesheets');
    $is_style_changeable = false;
    if ($_configuration['access_url'] != 1) {
        $style_info = api_get_settings('stylesheets', '', 1, 0);
        $url_info = api_get_access_url($_configuration['access_url']);
        if ($style_info[0]['access_url_changeable'] == 1 && $url_info['active'] == 1) {
            $is_style_changeable = true;
        }
    } else {
        $is_style_changeable = true;
    }
    $form = new FormValidator('stylesheet_upload', 'post', 'settings.php?category=Stylesheets#tabs-2');
    $form->addElement('text', 'name_stylesheet', get_lang('NameStylesheet'), array('size' => '40', 'maxlength' => '40'));
    $form->addRule('name_stylesheet', get_lang('ThisFieldIsRequired'), 'required');
    $form->addElement('file', 'new_stylesheet', get_lang('UploadNewStylesheet'));
    $allowed_file_types = array('css', 'zip', 'jpeg', 'jpg', 'png', 'gif', 'ico', 'psd');
    $form->addRule('new_stylesheet', get_lang('InvalidExtension') . ' (' . implode(',', $allowed_file_types) . ')', 'filetype', $allowed_file_types);
    $form->addRule('new_stylesheet', get_lang('ThisFieldIsRequired'), 'required');
    $form->addButtonUpload(get_lang('Upload'), 'stylesheet_upload');
    $show_upload_form = false;
    if (!is_writable(CSS_UPLOAD_PATH)) {
        Display::display_error_message(CSS_UPLOAD_PATH . get_lang('IsNotWritable'));
    } else {
        // Uploading a new stylesheet.
        if ($_configuration['access_url'] == 1) {
            $show_upload_form = true;
        } else {
            if ($is_style_changeable) {
                $show_upload_form = true;
            }
        }
    }
    // Stylesheet upload.
    if (isset($_POST['stylesheet_upload'])) {
        if ($form->validate()) {
            $values = $form->exportValues();
            $picture_element = $form->getElement('new_stylesheet');
            $picture = $picture_element->getValue();
            $result = upload_stylesheet($values, $picture);
            // Add event to the system log.
            $user_id = api_get_user_id();
            $category = $_GET['category'];
            Event::addEvent(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, api_get_utc_datetime(), $user_id);
            if ($result) {
                Display::display_confirmation_message(get_lang('StylesheetAdded'));
            }
        }
    }
    $form_change = new FormValidator('stylesheet_upload', 'post', api_get_self() . '?category=Stylesheets', null, array('id' => 'stylesheets_id'));
    $list_of_names = array();
    $selected = '';
    $dirpath = '';
    $safe_style_dir = '';
    if ($handle = @opendir(CSS_UPLOAD_PATH)) {
        $counter = 1;
        while (false !== ($style_dir = readdir($handle))) {
            if (substr($style_dir, 0, 1) == '.') {
                // Skip directories starting with a '.'
                continue;
            }
            $dirpath = CSS_UPLOAD_PATH . $style_dir;
            if (is_dir($dirpath)) {
                if ($style_dir != '.' && $style_dir != '..') {
                    if (isset($_POST['style']) && (isset($_POST['preview']) || isset($_POST['download'])) && $_POST['style'] == $style_dir) {
                        $safe_style_dir = $style_dir;
                    } else {
                        if ($currentstyle == $style_dir || $style_dir == 'chamilo' && !$currentstyle) {
                            if (isset($_POST['style'])) {
                                $selected = Database::escape_string($_POST['style']);
                            } else {
                                $selected = $style_dir;
                            }
                        }
                    }
                    $show_name = ucwords(str_replace('_', ' ', $style_dir));
                    if ($is_style_changeable) {
                        $list_of_names[$style_dir] = $show_name;
                    }
                    $counter++;
                }
            }
        }
        closedir($handle);
    }
    // Sort styles in alphabetical order.
    asort($list_of_names);
    $select_list = array();
    foreach ($list_of_names as $style_dir => $item) {
        $select_list[$style_dir] = $item;
    }
    $styles =& $form_change->addElement('select', 'style', get_lang('NameStylesheet'), $select_list);
    $styles->setSelected($selected);
    if ($form_change->validate()) {
        // Submit stylesheets.
        if (isset($_POST['save'])) {
            store_stylesheets();
            Display::display_normal_message(get_lang('Saved'));
        }
        if (isset($_POST['download'])) {
            $arch = api_get_path(SYS_ARCHIVE_PATH) . $safe_style_dir . '.zip';
            $dir = api_get_path(SYS_CSS_PATH) . 'themes/' . $safe_style_dir;
            if (is_dir($dir)) {
                $zip = new PclZip($arch);
                // Remove path prefix except the style name and put file on disk
                $zip->create($dir, PCLZIP_OPT_REMOVE_PATH, substr($dir, 0, -strlen($safe_style_dir)));
                //@TODO: use more generic script to download.
                $str = '<a class="btn btn-primary btn-large" href="' . api_get_path(WEB_CODE_PATH) . 'course_info/download.php?archive=' . str_replace(api_get_path(SYS_ARCHIVE_PATH), '', $arch) . '">' . get_lang('ClickHereToDownloadTheFile') . '</a>';
                Display::display_normal_message($str, false);
            } else {
                Display::addFlash(Display::return_message(get_lang('FileNotFound'), 'warning'));
            }
        }
    }
    if ($is_style_changeable) {
        $group = [$form_change->addButtonSave(get_lang('SaveSettings'), 'save', true), $form_change->addButtonPreview(get_lang('Preview'), 'preview', true), $form_change->addButtonDownload(get_lang('Download'), 'download', true)];
        $form_change->addGroup($group);
        if ($show_upload_form) {
            echo '<script>
            $(function() {
                $( "#tabs" ).tabs();
            });
            </script>';
            echo Display::tabs(array(get_lang('Update'), get_lang('UploadNewStylesheet')), array($form_change->return_form(), $form->return_form()));
        } else {
            $form_change->display();
        }
    } else {
        $form_change->freeze();
    }
}
$language_file[] = 'scorm_cloud';
// resetting the course id
$cidReset = true;
// including some necessary dokeos files
include_once '../inc/global.inc.php';
require_once api_get_path(LIBRARY_PATH) . 'formvalidator/FormValidator.class.php';
require_once api_get_path(LIBRARY_PATH) . 'fileManage.lib.php';
require_once api_get_path(LIBRARY_PATH) . 'fileUpload.lib.php';
// setting the section (for the tabs)
$this_section = SECTION_PLATFORM_ADMIN;
$_SESSION['this_section'] = $this_section;
// Access restrictions
api_protect_admin_script();
// Submit Stylesheets
if (isset($_POST['submit_stylesheets'])) {
    $message = store_stylesheets();
    header("Location: " . api_get_self() . "?category=stylesheets");
    exit;
}
// Database Table Definitions
$table_settings_current = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
// setting breadcrumbs
$interbreadcrumb[] = array("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
// setting the name of the tool
$tool_name = get_lang('DokeosConfigSettings');
// setting for templates
$fck_attribute['ToolbarSet'] = "AdminTemplates";
$fck_attribute['Width'] = '100%';
$fck_attribute['Height'] = '400';
// Build the form
if (!empty($_GET['category']) and !in_array($_GET['category'], array('Plugins', 'stylesheets', 'Search'))) {