<?php
// $Id$ 

require_once(dirname(__FILE__).'/actions.php');
set_error_handler('error_handler', E_ALL);

function themler_get_base_path() {
    return 'admin/settings/themler';
}

function themler_init() {
    $theme_name = getValue('theme');
    if (!$theme_name) {
        return;
    }

    theme_check_memory_limit(true);
    check_preview($theme_name);
    themler_enable_theme($theme_name);
    
    global $custom_theme;
    $custom_theme = get_preview_theme_name($theme_name);
}

function themler_enable_theme($theme_name) {
    $preview_theme_name = get_preview_theme_name($theme_name);
    $themes = array($theme_name, $preview_theme_name);
    $all_themes = list_themes(); //Get all the available themes
    $clear = false;
    if (!array_key_exists($theme_name, $all_themes)) {
        $clear = true;
        $all_themes = system_theme_data();
    }
    foreach ($themes as $theme_name) {
        $status = array_key_exists($theme_name, $all_themes) && ($all_themes[$theme_name]->status == 0);
        if ($status) {
            db_query("UPDATE {system} SET status = 1 WHERE type = 'theme' and name = '%s'", $theme_name);
        }
        $clear = $clear || $status;
    }
    if ($clear) {
        drupal_flush_all_caches();
    }
}

function themler_page() {
    global $user;
    $theme_name = getValue('theme');
    $username = getValue('username');
    $passwd = getValue('passwd');
    $query = themler_get_params();
    $url = '';
    if (user_is_logged_in()) {
        $theme_name = getValue('theme');
        if ($theme_name) {
            if ($username || $passwd) {
                $url = 'admin/settings/themler';
            }
            else {
                check_permissions($theme_name);
                $project = get_project(get_theme_dir($theme_name));
                $php_version = phpversion();
                $required_php_version = '5.3.0';

                if (!count((array)$project)) {

                    drupal_set_message(sprintf('The theme `%s` cannot be opened because /project/project.json file is missing or corrupted.', $theme_name), 'error');
                    $url = 'admin/build/themes/settings';

                } elseif ($php_version && version_compare($php_version, $required_php_version, '<')) {

                    drupal_set_message(sprintf('Unable to open theme. Your server is running php version %s but Themler requires %s or higher. Please upgrade PHP version to continue.', $php_version,  $required_php_version), 'error');
                    $url = 'admin/build/themes/settings';

                } else {
                    echo themler_show($theme_name);
                }
            }
        } else {
            drupal_set_message('Billion Themler: wrong theme name parameter', 'error');
            $url = 'admin/build/themes/settings';
        }
    }
    else {
        $params = array('name' => $username, 'pass' => $passwd);
        if ($theme_name && $username && $passwd && ($user = user_authenticate($params))) {
            $form_state = array();
            $form_state['uid'] = $user->uid;      
            user_login_submit(array(), $form_state);
            $url = 'admin/settings/themler';
        } else {
            drupal_set_message('Access denied: please login first', 'error');
            $url = 'user/login';
            $query = drupal_get_destination();
        }
    }
    themler_add_manifest_version($theme_name, $query);
    // for theme_show when user login
    if (!empty($url))
        drupal_goto($url, $query);
}

function themler_add_manifest_version($theme_name, &$query) {
    if ($theme_name) {
        $query .= '&ver=' . theme_get_manifest_version($theme_name);
    }
}

function themler_get_params() { // TODO: check working
    parse_str(drupal_get_destination(), $dest);
    $query = parse_url($dest['destination'], PHP_URL_QUERY);
    parse_str($query, $params);
    if (isset($params['username'])) unset($params['username']);
    if (isset($params['passwd'])) unset($params['passwd']);
    $prev = ini_get('arg_separator.output');
    ini_set('arg_separator.output','&');
    $result = http_build_query($params);
    ini_set('arg_separator.output', $prev);
    return $result;
}

function get_original_node_type($node_type) {
    return db_result(db_query("SELECT node_type.type FROM {node_type} WHERE type = '%s'", $node_type));
}

function get_templates_url($base_url, $theme_name) {
    $clean_url = get_base_clean_urls($base_url); // $base_url?q=
    $path      = get_preview_theme_dir(get_theme_dir($theme_name)) . '/templates/templates.php';
    $tokens    = array('home' => '', 'blog' => 'node', 'default' => 'user', 'template404' => 'not-found');

    if (file_exists($path)) {
        require($path); // not require_once

        $result    = array();
        foreach ($templates as $type => $template) {
            foreach ($template as $t) {
                if (!empty($t['nodeType'])) {
                    $nodeType = $t['nodeType'] == 'article' ? 'story' : $t['nodeType'];
                    $orig_type = get_original_node_type($nodeType);
                    $min_nid = db_result(db_query("SELECT MIN(node.nid) FROM {node} WHERE type = '%s' AND status = %d", $orig_type, 1));
                    if (!empty($min_nid)) {
                        $url = $clean_url . 'node/' . $min_nid . '&';
                    } else {
                        $url = $type === 'customTemplate' ? $base_url . '?' : $clean_url . 'notemplate/' . $nodeType . '&';
                    }
                } else {
                    $url = !empty($tokens[$type]) ? $clean_url . $tokens[$type] . '&' 
                                                  : $base_url . '?'; // home template only
                }
                $result[$t['name']] = $url . 'theme=' . $theme_name . '&template=' . $t['d'.get_major_version()];       
            }
        }
        return $result;
    }
    return get_backward_templates($base_url, $theme_name);
}

function get_backward_templates($base_url, $theme_name) {
    $templates = array();
    $templates['home'] = $base_url . '?theme=' . $theme_name;

    $base_url = get_base_clean_urls($base_url);
    $param = (strpos($base_url, '?') !== FALSE ? '&' : '?') . 'theme=' . $theme_name;
    
    $templates['blogTemplate'] = $base_url . 'node' . $param;
    $node_types = array('story' => 'singlePostTemplate', 'page' => 'pageTemplate', 'forum' => 'forumTemplate');
    foreach ($node_types as $type => $name) {
        $orig_type = get_original_node_type($nodeType);
        $min_nid = db_result(db_query("SELECT MIN(node.nid) FROM {node} WHERE type = '%s' AND status = %d", $orig_type, 1));
        if ($min_nid) {
            $templates[$name] = $base_url . 'node/' . $min_nid . $param;
        } else {
            $templates[$name] = $base_url . 'notemplate/' . $type . $param;
        }
    }

    $templates['default'] = $base_url . 'user' . $param;
    $templates['template404'] = $base_url . 'not-found'. $param;
    return $templates;
}

restore_error_handler();
