<?php
// $Id$ 

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

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

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

    theme_check_memory_limit(true);
    themler_enable_theme($theme_name); // enable theme 
    check_preview($theme_name); // looking for preview in the theme enabled directory
}

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_rebuild_theme_data();
    }
    foreach ($themes as $theme_name) {
        $status = array_key_exists($theme_name, $all_themes) && ($all_themes[$theme_name]->status == 0);
        if ($status) {
            theme_enable(array($theme_name)); //enable theme
        }
        $clear = $clear || $status;
    }
    if ($clear) {
        drupal_flush_all_caches();
    }
}

function themler_page() {
    $theme_name = getValue('theme');
    $username = getValue('username');
    $passwd = getValue('passwd');
    $query = array('query' => themler_get_params());
    $url = '';
    if (user_is_logged_in()) {
        if ($theme_name) {
            if ($username || $passwd) {
                $url = themler_get_base_path();
            }
            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/appearance/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/appearance/settings';

                } else {
                    echo themler_show($theme_name);
                }
            }
        } else {
            drupal_set_message('Themler: wrong theme name parameter', 'error');
            $url = 'admin/appearance/settings';
        }
    }
    else {
        if ($theme_name && $username && $passwd && ($uid = user_authenticate($username, $passwd))) {
            $form_state = array('uid' => $uid);
            user_login_submit(array(), $form_state);
            $url = themler_get_base_path();
        } else {
            drupal_set_message('Access denied: please login first', 'error');
            $url = 'user/login';
            $query = array('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) {
    $version = theme_get_manifest_version($theme_name);
    if (isset($query['query'])) {
        if (isset($query['query']['destination'])) {
            $desktop = theme_get_desktop_params();
            $query['query']['destination'] .= '&ver=' . $version . $desktop;
        } else {
            $params = theme_get_desktop_params_array();
            $query['ver'] = $version;
            foreach ($params as $key => $value)
                $query['query'][$key] = $value;
        }
    }
}

function themler_get_params() {
    $dest = drupal_get_destination();
    $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']);
    return $params;
}

function themler_custom_theme() {
    $theme_name = getValue('theme');
    if ($theme_name) {
        return get_preview_theme_name($theme_name);
    }
}

function get_original_node_type($node_type) {
    $result = db_select('node_type', 'n')->fields('n',array('type'))->condition('orig_type', $node_type,'=')->execute()->fetchAssoc();
    return ($result && isset($result['type'])) ? $result['type'] : false;
}

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'];
                    $orig_type = get_original_node_type($nodeType);
                    $query = db_select('node', 'n')
                        ->condition('n.status', '1')
                        ->condition('n.type', $orig_type);
                        $query->addExpression('MIN(n.nid)');
                    $min_nid = $query->execute()->fetchField();
                    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('article' => 'singlePostTemplate', 'page' => 'pageTemplate', 'forum' => 'forumTemplate');
    foreach ($node_types as $type => $name) {
        $orig_type = get_original_node_type($type);
        $query = db_select('node', 'n')
            ->condition('n.status', '1')
            ->condition('n.type', $orig_type);
            $query->addExpression('MIN(n.nid)');
        $min_nid = $query->execute()->fetchField();
        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();