<?php
/*
    File: Basics Functions
    Comments: -//-
*/
if( ! defined( 'ABSPATH' ) ) exit;

if ( ! function_exists('is_greyd_blocks') ) {

    /**
     * Check if this is a blocks site
     * 
     * @param bool $use_cache   Whether to use the cached value.
     * @param bool $default     The default value if no value is found.
     * 
     * @return bool
     */
    function is_greyd_blocks( $use_cache=true, $default=true ) {

		/**
		 * Support for constant override.
		 * @since 1.6.2
		 */
		if ( defined('IS_GREYD_BLOCKS') && constant('IS_GREYD_BLOCKS') ) {
			return true;
		}

        if ( $use_cache && $_cache = wp_cache_get( 'is_greyd_blocks', 'greyd' ) ) {
            return $_cache === '1';
        }

        $is_blocks_site = (
            /**
             * If option 'greyd_gutenberg' is set, this is a pure gutenberg install.
             * @since 1.0   The option is set in hub > ajax.php on firstrun.
             */
            (get_option('greyd_gutenberg') === true || get_option('greyd_gutenberg') == '1')
            /**
             * ...otherwise we check if this has the builder option set to 'gutenberg'
             */
            || \basics::get_setting(array('site', 'builder')) === 'gg-gg'
            || (
                isset(get_option('settings_site_greyd_tp', \basics::$defaults['site'])['builder']) && 
                get_option('settings_site_greyd_tp', \basics::$defaults['site'])['builder'] === 'gg-gg'
            )
            /**
             * ...if this is the first time activating the SUITE, use @param $default
             */
            || ( empty( get_posts( array(
                'posts_per_page'   => 1,
                'post_type'        => 'dynamic_template',
            ) ) ) && $default )
        );

        wp_cache_set( 'is_greyd_blocks', strval($is_blocks_site), 'greyd' );

        return $is_blocks_site;
    }
}

if ( ! function_exists('is_pure_greyd_blocks') ) {

    /**
     * Check if this is a pure blocks site
     * 
     * @since 1.2.2
     * 
     * @return bool
     */
    function is_pure_greyd_blocks() {
        return get_option('greyd_gutenberg') === true || get_option('greyd_gutenberg') == '1';
    }
}

new basics();
class basics {
    
    public static $defaults = array( 
        'global' => array( 
            // 'serial' => '', 
            // 'update' => 'manual',
            'cache' => array(
                'settings' => 'greyd',
                'enable' => null,
                'max_size' => 512,
                'no_emails' => null,
            ),
            'global_search' => array(
                'network_sites__in' => null,
                'network_sites__not_in' => null
            )
        ),
        'site' => array(
            'seo' => array(
                'sitemap' => 'greyd',
                'show_taxes' => 'false',
                'show_authors' => 'false',
                'show_archives' => 'false',
                'add_dates' => 'true',
            ),
            'analytics' => array(
                'enable' => null,
                'code_head' => null,
                'code_body' => null,
                'track_admins' => null
            ),
            'cache' => array(
                'settings' => 'greyd',
                'enable' => null,
                'max_size' => 512,
                'no_emails' => null,
            ),
            'lottie' => array(
                'mode' => 'default',
                'time' => 1,
                'mobile' => null,
            ),
            'lazyload' => 'false',
            'font_lazyload' => 'false',
            'is_webshop' => 'false', // deprecated
            'webshop' => array(
                'pagespeed' => 'true',
                'product_blocks' => 'false',
            ),
            'search_metafields' => 'false',
            'advanced_search' => array(
                'postviews_counter' => 'false',
                'relevance' => 'false',
                'live_search' => 'false',
                'global_search' => 'false',
                'exclude_posts_from_search' => "",
                'exclude_terms_from_search' => "",
            ),
            'builder' => 'vc-vc',
            'template_library' => array(
                'hide_welcome' => 'false',
                'hide_pattern_library' => 'false',
            )
        )
    );
    
    public function __construct() {
        
        // experimental features
        if (defined('ENABLE_GREYD_EXPERIMENTS') && ENABLE_GREYD_EXPERIMENTS === 'true') {
            // debug("experiments enabled!");
            add_action( 'wp_enqueue_scripts', function() { 
                // add js indicator var
                wp_add_inline_script( 'default_js', 'var greyd_experiments = true;', 'before' );
            }, 99 );
            
            self::$defaults['site']['experiments'] = array(
                // 'builder' => 'vc-vc'
            );
        }

        if ( is_greyd_blocks() ) {
            // debug("gutenberg default");
            self::$defaults['site']['builder'] = 'gg-gg';
            self::unset_plugin('js_composer');

            // enable vc frontend replacement (shortcode rendering)
            if ( !is_admin() ) require get_template_directory() . '/inc/vc/basics.php';
            // enable block features
            require get_template_directory() . '/inc/modules/blocks.php';
        }
        else {
            // remove block scripts and styles
            remove_action( 'wp_enqueue_scripts', 'wp_common_block_scripts_and_styles' );
            remove_action( 'admin_enqueue_scripts', 'wp_common_block_scripts_and_styles' );
            self::unset_plugin('greyd_blocks');
            self::unset_plugin('gutenberg');

            // set 'switch-to-blocks' admin notice
            add_action( "admin_notices", array($this, "display_blocks_notice"), 9 );
            add_action( "admin_notices", array($this, "ignore_blocks_notice"), 1 );
        }

        // setup
        add_action( 'switch_theme', array($this, 'deactivate_theme'));
        add_action( 'after_switch_theme', array($this, 'activate_theme'));
        add_action( 'after_setup_theme', array($this, 'theme_load_settings'), 1 );
        add_action( 'after_setup_theme', array($this, 'theme_setup'), 2 );
        add_action( 'all_admin_notices', array($this, 'theme_check_setup') );
        // stop updating translations
        add_filter( 'auto_update_translation', '__return_false' );

        // required plugins
        add_action( 'admin_init', array($this, 'theme_check_plugins'));
        add_action( 'tgmpa_register', array($this, 'register_required_plugins') );
        add_filter( 'plugins_api', array($this, 'get_plugin_info'), 23, 3 );
        add_action( 'vc_before_init', array($this, 'vcSetAsTheme') );

        // set required versions
        // deprecated - remove in next version
        add_filter( 'greyd_hub_required_versions', array($this, 'set_required_hub_version') );
        add_filter( 'greyd_forms_required_versions', array($this, 'set_required_form_version') );
        add_filter( 'greyd_blocks_required_versions', array($this, 'set_required_blocks_version') );
        
        // display errors in backend
        add_action( 'admin_notices', array($this, 'display_errors') );
        add_action( 'network_admin_notices', array($this, 'display_errors') );

        // add custom upload types
        add_filter( 'upload_mimes', array($this, 'add_upload_mimes') );
        add_filter( 'wp_check_filetype_and_ext', array($this, 'disable_mime_check'), 10, 4 );
        add_filter( 'wp_get_attachment_image_src', array($this, 'get_attachment_image_src'), 10, 4 );
        // Enable svg and json support for the media preview
        add_filter( 'wp_prepare_attachment_for_js', array($this, 'add_attachment_preview'), 10, 3 );
        
        // generic stuff and fixes
        // add_action( 'init', array($this, 'add_access_origin') );
        add_filter( 'document_title_separator', array($this, 'document_title_separator') );
        add_action( 'pre_get_posts', array($this, 'search_by_cat') );
        add_action( 'map_meta_cap', array($this, 'custom_manage_privacy_options'), 1, 4 );

        // head
        add_filter( 'xmlrpc_methods', array( $this, 'remove_xmlrpc_methods') );
        add_action( 'wp_head', array($this, 'add_meta'), 0 );
        remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
        remove_action( 'wp_head', 'rsd_link' );
        remove_action( 'wp_head', 'wlwmanifest_link' );
        remove_action( 'wp_head', 'wp_generator' );
        remove_action( 'wp_head', 'wp_site_icon', 99 );
        add_action( 'wp_head', 'wp_site_icon', 1 );
        add_action( 'wp_head', array($this, 'extend_favicon'), 1 );

        add_action( 'after_init_suite', array($this, 'display_license_watermark') );
    }

    public static function deactivate_theme() {
        $required_plugins = self::get_required_plugins();
        foreach($required_plugins as $plugin) {
            if ( (isset($plugin['required']) && $plugin['required'] === true ) ) {
                self::unset_plugin($plugin['slug']);
            }
        }
    }
    
    public function activate_theme() {
        ob_start();
        echo "<div class='updated notice is-dismissible'>
                <p>".__("Die GREYD.SUITE ist jetzt aktiviert.", 'core')."</p>
            </div>";
        return ob_get_contents();
    }
    
    public function theme_check_setup() {
        if ( is_admin() && ini_get('allow_url_fopen') == false ) {
            echo '<div class="notice notice-error">
                <p><strong>'.__("Achtung: Die PHP Einstellungen des Servers sind nicht mit der GREYD.SUITE kompatibel.", 'core')."</strong></p>
                <p>".__("Die Variable <i>allow_url_fopen</i> ist deaktiviert, was zu diversen Fehlern im Wizard, Hub und der Darstellung im Frontend führt. Bitte kontaktiere deinen Server Adminstrator um das Problem zu beheben.", 'core').'</p>
            </div>';
        }
    }
    
    /**
     * Displays errors
     */
    public static $errors = array();
    
    public function display_errors() {

        // check if the current theme needs an update
        if ( $this->theme_needs_update() && ! ( isset($_GET['action']) && $_GET['action'] === 'do-theme-upgrade' ) ) {

            global $config;
            echo "<div class='error notice'>
                <p>".sprintf(
                    __("Das Theme %s benötigt eine neuere Version. Bitte %saktualisiere das Theme%s, um mögliche Fehler zu verhindern.", 'core'),
                    "<strong>".$config->theme_name_full."</strong>",
                    "<a href='".( is_multisite() ? network_admin_url('update-core.php') : admin_url('update-core.php') )."'>",
                    "</a>"
                )."</p>
            </div>";
        }

        // display other errors
        if ( is_array(self::$errors) && count(self::$errors) > 0 ) {
            foreach ( self::$errors as $error ) {
                echo $error;
            }
        }
    }

    /**
     * Check if theme needs an update
     * 
     * @return bool Returns true if the theme needs an update.
     */
    public function theme_needs_update() {

        /**
         * Get required versions
		 * @deprecated
         * 
         * @filter greyd_theme_required_versions
         */
        $requirements = apply_filters( 'greyd_theme_required_versions', array() );

		/**
		 * Get required versions of the theme
		 * 
		 * @filter greyd_versions
		 */
        global $config;
		$versions = apply_filters( 'greyd_versions', array() );
		foreach( $versions as $n => $v ) {
			if ( isset($v['required'][$config->theme_name]) ) {
				$requirements[$n] = $v['required'][$config->theme_name];
			}
		}

        if ( empty($requirements) || !is_array($requirements) ) return false;
        // debug( 'theme requirements' );
        // debug( $requirements );

        $theme = is_child_theme() ? wp_get_theme(get_template()) : wp_get_theme();
        if ( !$theme->exists() ) {
            self::$errors[] = __("Das aktivierte Theme scheint nicht mehr zu existieren. Bitte kontaktiere einen Administrator.", "core");;
            return false;
        }
        
        $all_true           = true;
        $current_version    = $theme->get( 'Version' );
        foreach ( $requirements as $required_version ) {
            if ( $all_true ) {
                $all_true = version_compare( $current_version, $required_version, '>=' );
            }
        }
        return !$all_true;
    }

    public function theme_check_plugins() {
        
        // the plugins 'greyd_hub' & 'js_composer' always need to be active
        $required_plugins = self::get_required_plugins();
        $hub_installed = false;
        foreach($required_plugins as $plugin) {
            if ( (isset($plugin['required']) && $plugin['required'] === true) ) {

                // internal plugins
                if ( isset($plugin['source']) ) {
                    $result = self::set_plugin($plugin['slug'], $plugin['source']);
                }
                // external plugins (wordpress.org)
                else if ( isset($plugin['external_url']) ) {
                    $external_zip = trailingslashit($plugin['external_url']);
                    $external_zip .= $plugin['slug'];
                    if ( isset($plugin['version']) ) $external_zip .= '.'.$plugin['version'];
                    $external_zip .= '.zip';
                    $result = self::set_plugin($plugin['slug'], $external_zip );
                }
                
                if (strpos($result, "error::") === 0) {
                    // error ...
                    self::$errors[] = '<div class="notice notice-error">
                        <p><strong>'.__("Achtung: Es gab einen Fehler mit einem erforderlichen Plugin.", 'core')."</strong></p>
                        <p>".sprintf(
                            __("Das Plugin '%s' konnte nicht installiert bzw. aktiviert werden. Kontaktiere einen Administrator, um die installierten Plugins und den Ordner 'wp-content/plugins' nach möglichen Konflikten zu überprüfen.", 'core'),
                            $plugin['name']
                    ).'</p>
                    </div>';
                }
                if ($plugin['slug'] === 'js_composer') {
                    delete_transient( '_vc_page_welcome_redirect' );
                }
                else if ($plugin['slug'] === 'greyd_tp_management') {
                    $hub_installed = true;
                }
            }
        }
        
        // If the hub plugin is not installed, the installation process would throw a fatal error
        if ( !$hub_installed ) return false;
        
        // If we're in the customizer preview, the installation process would throw a fatal error
        if ( is_customize_preview() ) return false;
        
        // If option 'greyd_installed' is set, we don't need to look further
        if ( get_option('greyd_installed') === true || get_option('greyd_installed') == '1' ) return false;
        
        /**
         * Now we're checking if theme_mods are set or templates do exist
         * this is a good way to find out if a legacy version of the SUITE is installed
         * --> back then the option was not yet introduced
         */
        $theme_mods = get_theme_mods();
        $templates = get_posts( array(
            'posts_per_page'   => 1,
            'post_type'        => 'dynamic_template',
        ) );
        if ( count($theme_mods) >= 15 && !empty($templates) ) {
            update_option('greyd_installed', "1");
            return false;
        }
        
        /**
         *  if nothing of the above hits, we're starting the activation process
         *  this triggers a redirect to the wizard in the end
         */
        do_action('greyd_suite_activated');
        
    }

    /**
     * Display an update notice when blocks version is not active
     */
    public function display_blocks_notice() {

        // don't display when gutenberg is active
        if ( is_greyd_blocks() ) return;

        // don't display on 'GREYD.SUITE > Settings' page
        if ( isset($_GET["page"]) && $_GET["page"] === "greyd_settings" ) return;

        // user dismissed notice
        global $current_user;
        $user_id = $current_user->ID;
        if ( get_user_meta( $user_id, "ignore_greyd_blocks", true ) ) return;

        echo "<div class='updated notice is-dismissible' style='border-left-color: #9b51e0;'>
            <div class='flex' style='padding: 12px 0; flex-direction: row; justify-content: flex-start; align-items: center;'>
                <img style='width: 46px; display: inline-block; margin: 0 20px 0 10px;' src='".get_template_directory_uri()."/assets/icon/greyd-logo-dark.svg'/>
                <div>
                    <p>".__("Großartige Neuigkeiten: Die GREYD.SUITE ist die erste All-in-one Lösung die zu 100% in Gutenberg integriert ist. Steige jetzt auf den Block Editor um und profitiere durch ein modernes und intuitives Nutzererlebnis, herausragende Performance und brandneuen Entwicklungen.", 'core')."</p>
                    <p>
                        <a class='' href=".admin_url('admin.php?page=greyd_settings').">".__("Auf Gutenberg umsteigen", 'core')."</a>
                        &nbsp;|&nbsp;
                        <a style='color: inherit;' href=".add_query_arg( "ignore_greyd_blocks", "true" ).">".__("diese Meldung verbergen", 'core')."</a>
                    </p>
                </div>
            </div>
        </div>";
    }

    /**
     * Ignore the notice
     */
    public function ignore_blocks_notice() {
        
        if ( is_greyd_blocks() ) return;

        if ( isset($_GET["ignore_greyd_blocks"]) && $_GET["ignore_greyd_blocks"] === "true" ) {
            global $current_user;
            $user_id = $current_user->ID;
            add_user_meta($user_id, "ignore_greyd_blocks", "true", true);
        }
    }

    public static function set_plugin($plugin_slug, $plugin_zip="") {
        // if (!function_exists('plugins_api')) {
        //     require_once ABSPATH.'wp-admin/includes/plugin-install.php';
        // }
        if ($plugin_zip == "") {
            if (!function_exists('plugins_api')) {
                require_once ABSPATH.'wp-admin/includes/plugin-install.php';
            }
            $api = plugins_api( 'plugin_information', array( 'slug' => $plugin_slug, 'fields' => array( 'sections' => false ) ) );
            if ($api !== false && isset($api->download_link) ) {
                $plugin_zip = $api->download_link;
            }
        }
        // Check if new plugin is already installed
        $plugin_php = self::is_plugin_installed($plugin_slug);
        if ($plugin_php !== false) {
            // debug($plugin_php);
            $installed = true;
        } 
        else {
            // it's not installed: Installing
            $installed = self::install_plugin($plugin_zip, $plugin_slug);
            $plugin_php = self::is_plugin_installed($plugin_slug);
        }
        if (!is_wp_error($installed) && $installed) {
            // Activating new plugin
            $activate = activate_plugin($plugin_php);
            if (is_null($activate)) {
                // Done! Everything went smooth
                return true;
            }
            else {
                // Could not activate the new plugin
                return "error::unable to activate plugin: ".$plugin_slug;
            }
        } 
        else {
            // Could not install the new plugin
            return "error::unable to install plugin: ".$plugin_slug;
        }
    }
    
    public static function unset_plugin($slug) {
        $plugin_php = self::is_plugin_installed($slug);
        if ($plugin_php !== false && !is_plugin_active_for_network($slug)) {
            deactivate_plugins( array( $plugin_php ) );
        } 
    }
    
    public static function is_plugin_installed($slug) {
        if (!function_exists('get_plugins')) {
            require_once ABSPATH.'wp-admin/includes/plugin.php';
        }
        $all_plugins = get_plugins();
        foreach($all_plugins as $plugin => $details)
            if (strpos($plugin, $slug.'/') === 0) 
                return $plugin;
        return false;
    }
    
    public static function install_plugin($plugin_zip, $plugin_slug) {
        if (!class_exists('Plugin_Upgrader', false)) {
            require_once ABSPATH.'wp-admin/includes/class-wp-upgrader.php';
        }
        if (!function_exists('request_filesystem_credentials')) {
            require_once ABSPATH.'wp-admin/includes/file.php';
        }
        wp_cache_flush();
        $upgrader = new \Plugin_Upgrader(new WP_Ajax_Upgrader_Skin());
        $installed = $upgrader->install($plugin_zip);
        
        // error installing
        if ( !$installed ) {
            
            /**
             * Check if plugin folder already exists without the plugin
             * being installed.
             * 
             * When the installation of a plugin was aborted, sometimes the
             * plugin folder exists, without it being an installed plugin.
             * This causes the plugin to not be installable anymore. If the
             * plugin is required for the GREYD.SUITE, this could cause fatal
             * errors. To prevent this, we're deleting the orphaned folder
             * and restart the plugin installation.
             */
            $plugin_dir = defined('WP_PLUGIN_DIR') ? WP_PLUGIN_DIR."/".$plugin_slug : null;
            if ( is_dir( $plugin_dir ) && !self::is_plugin_installed($plugin_slug) ) {
                $result = self::deleteDirectory( $plugin_dir );
                if ( $result ) {
                    return self::install_plugin($plugin_zip, $plugin_slug);
                }
            }
        }
        
        return $installed;
    }
    
    public static function deleteDirectory($dir) {
        if (!file_exists($dir)) {
            return true;
        }
        if (!is_dir($dir)) {
            return unlink($dir);
        }
        foreach (scandir($dir) as $item) {
            if ($item == '.' || $item == '..') {
                continue;
            }
            if (!self::deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
                return false;
            }
        }
        return rmdir($dir);
    }

    public static function theme_load_settings() {
        global $config;

        if ( empty($config) || !is_object($config) ) {
            $config = (object) $config;
        }
        
        // load settings
        // $config->theme_version = wp_get_theme()->get( 'Version' );
        if (is_multisite())
            $global = get_network_option(null, "settings_greyd_tp", self::$defaults['global']);
        else
            $global = get_option("settings_greyd_tp", self::$defaults['global']);
        $site = get_option('settings_site_greyd_tp', self::$defaults['site']);
        // update experimental setting to stable
        if (!isset($site['builder']) && isset($site['experiments']['builder'])) {
            $experimental_builder = strval($site['experiments']['builder']);
            if ($experimental_builder != 'vc-vc') {
                if ($experimental_builder == 'vc-gg') $experimental_builder = 'gg-gg';
                $site['builder'] = $experimental_builder;
                unset($site['experiments']['builder']);
                update_option('settings_site_greyd_tp', $site);
            }
        }
        // get final settings
        $config->settings = array(
            'global' => self::check_settings($global, self::$defaults['global']),
            'site' => self::check_settings($site, self::$defaults['site'])
        );
        // debug($config);
    }
    public static function check_settings($settings, $default) {
        foreach ($default as $key => $value) {
            if (!is_array($value)) {
                if (!isset($settings[$key])) $settings[$key] = $value;
            }
            else {
                if (!isset($settings[$key])) $settings[$key] = array();
                $settings[$key] = self::check_settings($settings[$key], $value);
            }
        }
        return $settings;
    }
    public static function get_setting($key, $default=true) {
        global $config;
        if ( !isset($config->settings) ) return null;
        $value = false;
        if (!is_array($key)) {
            $set = $config->settings[$key];
            $def = self::$defaults[$key];
        }
        else {
            $set = $config->settings;
            $def = self::$defaults;
            foreach ($key as $k) {
                $set = isset($set[$k]) ? $set[$k] : null;
                $def = isset($def[$k]) ? $def[$k] : null;
            }
        }
        if (isset($set)) $value = $set;
        else if ($default && isset($def)) $value = $def;

        return $value;
    }

    public function theme_setup() {
        global $config;

        // include puc lib
        if ( ! class_exists('Puc_v4_Factory') ) {
            require_once get_template_directory().'/libs/plugin-update-checker/plugin-update-checker.php';
        }
        
        // manage updates
        if (class_exists('Puc_v4_Factory') && !$this->is_frozen()) {
            if ( isset($config) && isset($config->update_file) && isset($config->theme_file) && isset($config->theme_name) ) {
                $myUpdateChecker = \Puc_v4_Factory::buildUpdateChecker(
                    $config->update_file,     // Full path to the update server manifest file.
                    $config->theme_file,     // Full path to the main plugin file or functions.php.
                    $config->theme_name      // Insert Plugin slug, usually same as directory name.
                );
            }
        }

        // deactive js_composer
        if ( basics::get_setting(array('site', 'builder')) == "gg-gg" && vc\helper::is_active_plugin('js_composer/js_composer.php')) {
            self::unset_plugin('js_composer');
        }
        
        // translations
        load_theme_textdomain( 'core', get_template_directory(). '/languages/' );
        load_theme_textdomain( 'tgmpa', get_template_directory().'/languages/' );
        
        // wp theme support
        add_theme_support( 'title-tag' );
        add_theme_support( 'post-thumbnails' );
        add_theme_support( 'custom-logo', array(
            'flex-width'  => true,
            'flex-height'  => true,
            'header-text' => array( 'site-title', 'site-description' ),
        ) );

        // wp menus
        register_nav_menus( array(
            'main-menu' => esc_html__( 'Hauptmenü', 'core' ),
            'meta-menu' => esc_html__( 'Menü für zweiten Header', 'core' ),
        ) );
        
        // starter content for preview
        if (is_customize_preview()) {
            $preview = isset($_GET['theme']) ? $_GET['theme'] : "";
            if (strpos($preview, 'greyd') !== false) {
                self::set_plugin('greyd_tp_management', 'https://update.greyd.io/review/plugins/greyd_hub/greyd_tp_management.zip');
                starter::set_starter_contents();
            }
        }
    }

    public function is_frozen() {
        $l = get_option('gtpl');
        return $l && !empty($l) && is_array($l) && isset($l['frozen']) && $l['frozen'];
    }

    public function get_plugin_info( $res, $action, $args ) {
        // debug($res);
        // debug($action);
        // debug($args);
        if ($action == 'plugin_information') {
            $plugins = array(
                'greyd_blocks' => 'https://update.greyd.io/review/plugins/greyd_blocks/metadata.json',
                'greyd_tp_forms' => 'https://update.greyd.io/review/plugins/greyd_forms/metadata.json',
                'greyd_tp_management' => 'https://update.greyd.io/review/plugins/greyd_hub/metadata.json',
            );
            if (in_array($args->slug, array_keys($plugins))) {
                // debug("get data: ".$plugins[$args->slug]);
                $remote = wp_remote_get(
                    $plugins[$args->slug], 
                    array(
                        'timeout' => 10,
                        'headers' => array( 'Accept' => 'application/json' )
                    )
                );
                $res = (object)json_decode($remote['body']);
                if (isset($res->sections)) $res->sections = (array)$res->sections;

                // $strings = array();
                foreach ($res->sections as $key => $value) {
                    $res->sections[$key] = __( $value, 'core' );
                //     array_push($strings, '__("'.$value.'", 'core')');
                }
                // debug($strings);

                if (isset($res->icons)) $res->icons = (array)$res->icons;
                if (isset($res->banners)) $res->banners = (array)$res->banners;
                return $res;
            }
        }
        return false;
    }
    
    public static function get_required_plugins() {
        $plugins = array(
            // require wpbakery
            array(
                'name'              => 'WPBakery Visual Composer', // The plugin name
                'slug'              => 'js_composer', // The plugin slug (typically the folder name)
                'source'            => 'https://update.greyd.io/misc/js_composer/js_composer.zip', // The plugin source
                'required'          => true, // If false, the plugin is only 'recommended' instead of required
                'version'           => '6.10.0', // E.g. 1.0.0. If set, the active plugin must be this version or higher, otherwise a notice is presented
                'force_activation'  => true, // If true, plugin is activated upon theme activation and cannot be deactivated until theme switch
                'force_deactivation'=> true, // If true, plugin is deactivated upon theme switch, useful for theme-specific plugins
                'external_url'      => '', // If set, overrides default API URL and points to an external URL
            ),
            // require greyd management
            array(
                'name'              => 'GREYD.Hub',
                'slug'              => 'greyd_tp_management',
                'source'            => 'https://update.greyd.io/review/plugins/greyd_hub/greyd_tp_management.zip',
                'required'          => true,
                'version'           => '1.8.2',
                'force_activation'  => true,
                'force_deactivation'=> true,
                // 'external_url'      => '',
            ),
            
            // recommend greyd forms
            array(
                'name'              => 'GREYD.Forms',
                'slug'              => 'greyd_tp_forms',
                'source'            => 'https://update.greyd.io/review/plugins/greyd_forms/greyd_tp_forms.zip',
                'required'          => false,
                'version'           => '1.8.2',
                'force_activation'  => false,
                'force_deactivation'=> true,
                // 'external_url'      => '',
                'default'           => true, // needed for installation process
            ),
            
            // // borlabs
            // array(
            //     'name'      => 'Borlabs Cookie - Cookie Opt-in',
            //     'slug'      => 'borlabs-cookie',
            //     'required'  => false, // this plugin is recommended
            // ),
            // // wpml
            // array(
            //     'name'      => 'WPML Multilingual CMS',
            //     'slug'      => 'sitepress-multilingual-cms',
            //     'required'  => false, // this plugin is recommended
            // ),
            // autoptimize
            // array(
            //     'name'      => 'Autoptimize',
            //     'slug'      => 'autoptimize',
            //     'required'  => false, // this plugin is recommended
            //     'external_url' => 'https://wordpress.org/plugins/autoptimize/',
            // ),
            // tinymce advanced
            // array(
            //     'name'      => 'Advanced Editor Tools',
            //     'slug'      => 'tinymce-advanced',
            //     'required'  => false, // this plugin is recommended
            //     'external_url' => 'https://wordpress.org/plugins/tinymce-advanced/',
            // ),
            // yoast
            // array(
            //     'name'      => 'Yoast SEO',
            //     'slug'      => 'wordpress-seo',
            //     'required'  => false, // this plugin is recommended
            //     'external_url' => 'https://wordpress.org/plugins/wordpress-seo/',
            // ),
            // enable media replace
            // array(
            //     'name'      => 'Enable Media Replace',
            //     'slug'      => 'enable-media-replace',
            //     'required'  => false, // this plugin is recommended
            //     'external_url' => 'https://wordpress.org/plugins/enable-media-replace/',
            // ),
            // hide login
            // array(
            //     'name'      => 'WPS Hide Login',
            //     'slug'      => 'wps-hide-login',
            //     'required'  => false, // this plugin is recommended
            //     'external_url' => 'https://wordpress.org/plugins/wps-hide-login/',
            // ),
            // // recommend woocommerce
            // array(
            //     'name'      => 'WooCommerce',
            //     'slug'      => 'woocommerce',
            //     'required'  => false, // this plugin is recommended
            //     'external_url' => 'https://wordpress.org/plugins/woocommerce/',
            // ),
            // array(
            //     'name'      => 'Germanized für WooCommerce',
            //     'slug'      => 'woocommerce-germanized',
            //     'required'  => false, // this plugin is recommended
            //     'external_url' => 'https://wordpress.org/plugins/woocommerce-germanized/',
            // ),
        );

        /**
         * Modify or add required & recommended plugins for the SUITE.
         * 
         * @filter 'greyd_required_plugins'
         * 
         * @param array $plugins   Array of all plugins.
         */
        $plugins = apply_filters('greyd_required_plugins', $plugins);
        return $plugins;
    }

    /**
     * Register the required plugins for this theme.
     *
     * The variable passed to tgmpa_register_plugins() should be an array of plugin arrays.
     *
     * This function is hooked into tgmpa_init, which is fired within the
     * TGM_Plugin_Activation class constructor.
     */
    public function register_required_plugins() {
        // global $config;
        /**
         * Array of plugin arrays. Required keys are name and slug.
         * If the source is NOT from the .org repo, then source is also required.
         */
        $plugins = self::get_required_plugins();

        // Change this to your theme text domain, used for internationalising strings
        $theme_text_domain = 'core';

        /**
         * Array of configuration settings. Amend each line as needed.
         * Some of the strings are added into a sprintf, so see the comments at the
         * end of each line for what each argument will be.
         */
        $tgm_config = array(
            'domain'            => $theme_text_domain, // Text domain - likely want to be the same as your theme.
            'default_path'      => '', // Default absolute path to pre-packaged plugins
            'menu'              => 'install-required-plugins', // Menu slug
            'parent_slug'       => 'greyd_dashboard', // Parent menu slug.
            'capability'        => 'manage_options', // Parent menu slug.
            'has_notices'       => false, // Show admin notices or not
            'dismissable'       => true, // If 'dismissable' is false, this message will be output at top of nag.
            'is_automatic'      => true, // Automatically activate plugins after installation or not
            'message'           => '<p style="max-width:740px;">'.__( 'Damit deine Website optimal läuft und den neuesten Anforderungen entspricht, empfehlen wir dir, die aufgeführten Plugins zu installieren. Markiere dazu einfach die gewünschten Plugins und wähle die Aktion „Installieren“ aus.', $theme_text_domain ).'</p>', // Message to output right before the plugins table
            'strings' => array(
                'page_title'        => __( 'Plugins für die GREYD.SUITE installieren', $theme_text_domain ),
                'menu_title'        => __( 'Plugins', $theme_text_domain ),
                'installing'        => __( 'Installiert Plugin: %s', $theme_text_domain ), // %1$s = plugin name
                'updating'          => __( 'Aktualisiert Plugin: %s', $theme_text_domain ),
                'oops'              => __( 'Etwas ist schief gelaufen. Bitte versuche es nochmal oder wende dich an den Support.', $theme_text_domain ),
                
                'notice_can_install_required'     => _n_noop(
                    /* translators: 1: plugin name(s). */
                    'Die GREYD.SUITE benötigt das Plugin „%1$s“.',
                    'Die GREYD.SUITE benötigt die folgenden Plugins: %1$s.',
                    $theme_text_domain
                ),
                'notice_can_install_recommended'  => _n_noop(
                    /* translators: 1: plugin name(s). */
                    'Damit du die volle Power der GREYD.SUITE nutzen kannst, empfehlen wir das Plugin „%1$s“.',
                    'Damit du die volle Power der GREYD.SUITE nutzen kannst, empfehlen wir folgende Plugins: %1$s.',
                    $theme_text_domain
                ),
                'notice_ask_to_update'            => _n_noop(
                    /* translators: 1: plugin name(s). */
                    'Bitte aktualisiere das Plugin „%1$s“, damit die GREYD.SUITE reibungslos funktioniert.',
                    'Bitte aktualisiere diese Plugins, damit die GREYD.SUITE reibungslos funktioniert: %1$s.',
                    $theme_text_domain
                ),
                'notice_ask_to_update_maybe'      => _n_noop(
                    /* translators: 1: plugin name(s). */
                    'Für das Plugin „%1$s“ steht ein Update zur Verfügung.',
                    'Für diese Plugins steht ein Update zur Verfügung: %1$s.',
                    $theme_text_domain
                ),
                'notice_can_activate_required'    => _n_noop(
                    /* translators: 1: plugin name(s). */
                    'Das benötigte Plugin „%1$s“ ist zurzeit nicht aktiviert.',
                    'Diese benötigten Plugins sind zurzeit nicht aktiviert: %1$s.',
                    $theme_text_domain
                ),
                'notice_can_activate_recommended' => _n_noop(
                    /* translators: 1: plugin name(s). */
                    'Das empfohlene Plugin „%1$s“ ist zurzeit nicht aktiviert.',
                    'Diese empfohlenen Plugins sind zurzeit nicht aktiviert: %1$s.',
                    $theme_text_domain
                ),
                'install_link'                    => _n_noop(
                    'Plugin installieren',
                    'Plugins installieren',
                    $theme_text_domain
                ),
                'update_link'                     => _n_noop(
                    'Plugin aktualisieren',
                    'Plugins aktualisieren',
                    $theme_text_domain
                ),
                'activate_link'                   => _n_noop(
                    'Installiertes Plugin aktivieren',
                    'Installierte Plugins aktivieren',
                    $theme_text_domain
                ),
                'return'                          => __( 'Zurück zur Übersicht aller Plugins', $theme_text_domain ),
                'dashboard'                       => __( 'Zurück zum Dashboard', $theme_text_domain ),
                'plugin_activated'                => __( 'Das Plugin wurde aktiviert.', $theme_text_domain ),
                'activated_successfully'          => __( 'Das folgende Plugin wurde erfolgreich aktiviert:', $theme_text_domain ),
                /* translators: 1: plugin name. */
                'plugin_already_active'           => __( 'Das Plugin „%1$s“ ist bereits aktiv.', $theme_text_domain ),
                /* translators: 1: plugin name. */
                'plugin_needs_higher_version'     => __( 'Das Plugin „%s“ wurde nicht aktiviert, da eine aktuellere Version für die GREYD.SUITE erforderlich ist. Bitte aktualisiere das Plugin.', $theme_text_domain ),
                /* translators: 1: dashboard link. */
                'complete'                        => __( 'Alle Plugins wurden erfolgreich installiert &amp; aktualisiert. %s', $theme_text_domain ), // %1$s = dashboard link
                'dismiss'                         => __( 'Diese Meldung nicht mehr anzeigen', $theme_text_domain ),
                'notice_cannot_install_activate'  => __( 'Es gibt mindestens ein Plugin, das installiert, aktualisiert oder aktiviert werden sollte.', $theme_text_domain ),
                'contact_admin'                   => __( 'Bitte kontaktiere den Administrator deiner Seite.', $theme_text_domain ),
                'nag_type'                        => 'updated' // Determines admin notice type - can only be 'updated' or 'error'
            )
        );
        tgmpa( $plugins, $tgm_config );
    }

    /**
     * Add required GREYD.Hub Version
     * 
     * @filter greyd_hub_required_versions
     */
    public function set_required_hub_version($return) {
        global $config;
        $versions = isset($config->required_versions) ? $config->required_versions : array();
        $version = isset($versions['greyd_hub']) ? $versions['greyd_hub'] : null;
        if ( $version ) {
            $return[$config->theme_name] = $version;
        }
        return $return;
    }

    /**
     * Add required GREYD.Forms Version
     * 
     * @filter greyd_forms_required_versions
     */
    public function set_required_form_version($return) {
        global $config;
        $versions = isset($config->required_versions) ? $config->required_versions : array();
        $version = isset($versions['greyd_forms']) ? $versions['greyd_forms'] : null;
        if ( $version ) {
            $return[$config->theme_name] = $version;
        }
        return $return;
    }

    /**
     * Add required GREYD.Blocks Version
     * 
     * @filter greyd_blocks_required_versions
     */
    public function set_required_blocks_version($return) {
        global $config;
        $versions = isset($config->required_versions) ? $config->required_versions : array();
        $version = isset($versions['greyd_blocks']) ? $versions['greyd_blocks'] : null;
        if ( $version ) {
            $return[$config->theme_name] = $version;
        }
        return $return;
    }

    /**
     * Force Visual Composer to initialize as "built into the theme". This will hide certain tabs under the Settings->Visual Composer page
     */
    public function vcSetAsTheme() {
        vc_set_as_theme();
    }

    /*
        Add custom mimes to allowed upload types
    */
    public function add_upload_mimes($mime_types) {
        $mime_types['svg'] = 'image/svg+xml';
        $mime_types['json'] = 'application/json';
        return $mime_types;
    }
    public function disable_mime_check($data, $file, $filename, $mimes) {
        // https://almostinevitable.com/wp-svg-problems-with-wp-5/
        // https://secure.wphackedhelp.com/blog/fix-file-type-not-permitted-for-security-reasons-wordpress-error/
        $wp_filetype = wp_check_filetype($filename, $mimes);
        $ext = $wp_filetype['ext'];
        $type = $wp_filetype['type'];
        $proper_filename = $data['proper_filename'];
        return compact('ext', 'type', 'proper_filename');
    }
    /*
        Get width and height for svg images
    */
    public function get_attachment_image_src( $image, $attachment_id, $size, $icon ) {
        if (isset($image[0]) && strpos($image[0], ".svg") > 0) {

			if ( method_exists( 'Greyd\Helper', 'get_file_contents' ) ) {
				$image_file = \Greyd\Helper::get_file_contents($image[0]);
			} else {
				$image_file = \vc\helper::get_file_contents($image[0]);
			}
			if ( ! $image_file ) {
				return $image;
			}
            // parse svg xml
			$xmlget = @simplexml_load_string( $image_file,'SimpleXMLElement', LIBXML_PARSEHUGE );
			if ( ! $xmlget || ! is_object($xmlget) || ! method_exists($xmlget, 'attributes') ) {
				return $image;
			}

            $xmlattributes = $xmlget->attributes();
            // debug($xmlattributes);
            if (isset($xmlattributes->width) && isset($xmlattributes->height)) {
                $width = (int) $xmlattributes->width; 
                $height = (int) $xmlattributes->height;
                // set with and height
                $image[1] = $width;
                $image[2] = $height;
            }
            else if (isset($xmlattributes->viewBox)) {
                $tmp = explode(' ', $xmlattributes->viewBox);
                $width = (int) $tmp[2] - (int) $tmp[0];
                $height = (int) $tmp[3] - (int) $tmp[1];
                // set with and height
                $image[1] = $width;
                $image[2] = $height;
            }
        }
        // debug($image);
        return $image;
    }
    /*
        Enable svg and json support for the media preview
    */
    public function add_attachment_preview($response, $attachment, $meta) {
        global $config;
        if (!class_exists('SimpleXMLElement')) return;
        if ($response['type'] === 'image' && $response['subtype'] === 'svg+xml' ) {
            try {
                $path = get_attached_file($attachment->ID);
                if (@file_exists($path)) {
                    $svg = new SimpleXMLElement(@file_get_contents($path));
                    $src = $response['url'];
                    $width = (int) $svg['width'];
                    $height = (int) $svg['height'];
                    //media gallery
                    // $response['icon'] = $src;
                    $response['image'] = compact( 'src', 'width', 'height' );
                    $response['thumb'] = compact( 'src', 'width', 'height' );
                    //media single
                    $response['sizes']['full'] = array(
                        'height'        => $height,
                        'width'         => $width,
                        'url'           => $src,
                        'orientation'   => $height > $width ? 'portrait' : 'landscape',
                    );
                }
            }
            catch (Exception $e) {}
        }
        if ($config->settings['site']['lottie']['mode'] !== 'disable' &&
            $response['type'] === 'application' && $response['subtype'] === 'json' ) {
            $src = $response['url'];
            $width = 100;
            $height = 100;
            //media gallery
            $response['image'] = compact( 'src', 'width', 'height' );
            $response['thumb'] = compact( 'src', 'width', 'height' );
            //media single
            $response['sizes']['full'] = array(
                'height'        => $height,
                'width'         => $width,
                'url'           => $src,
                'orientation'   => $height > $width ? 'portrait' : 'landscape',
            );
        }
        return $response;
    }
    
    /* 
        generic stuff and fixes
    */
    public function document_title_separator($sep) {
        $sep = '|';
        return $sep;
    }
    public function add_access_origin() {
        header('Access-Control-Allow-Origin: *');
    }
    /* fix post_type=page in search query */
    public function search_by_cat() {
        global $wp_query;
        if (is_search()) {
            // debug($_GET['post_type']);
            // debug($wp_query);
            if (isset($_GET['post_type']))
                $wp_query->query_vars['post_type'] = $_GET['post_type'];
        }
    }
    /* modify 'manage_privacy_options' for privacy policy page */
    public function custom_manage_privacy_options($caps, $cap, $user_id, $args) {
        if ($cap === 'manage_privacy_options') {
            // remove the require cap to let admins and editors on multisites manage the privacy options
            $manage_name = is_multisite() ? 'manage_network' : 'manage_options';
            $caps = array_diff($caps, [ $manage_name ]);
        }
        return $caps;
    }

    public function display_license_watermark() {
        $license = get_option( 'greyd_suite_license' );
        $license = $license ? (object)$license : null;
        if ( !$license || $license->invalid ) {
            $watermark = get_template_directory_uri().'/assets/icon/wizard/wm.svg';
            $text = 'Built&nbsp;with&nbsp;<strong style="line-height:15px!important;">GREYD.SUITE</strong>';
            $is_site_admin = in_array('administrator',  wp_get_current_user()->roles);
            $link_url = $is_site_admin ? admin_url("admin.php?page=greyd_suite_license") : "https://www.greyd.de";
            $link_text = $is_site_admin ? 'Activate&nbsp;your&nbsp;license&nbsp;to&nbsp;hide&nbsp;this&nbsp;banner.' : 'Find&nbsp;out&nbsp;what&nbsp;makes&nbsp;us&nbsp;unique.';
            $style = 'text-align:left!important;
                display:block!important;
                opacity:1!important;
                color:#3D3449!important;
                position:fixed!important;
                right:-30px!important;
                bottom:20px!important;
                padding:12px 42px 8px 70px!important;
                background:url('.$watermark.') 0% 50%/auto 100% no-repeat #fff!important;
                font:normal normal 15px/1 system-ui, sans-serif!important;
                border-radius:6px 0 0 6px!important;
                -webkit-box-shadow:0 4px 6px rgba(50,50,93,.18),0 1px 3px rgba(0,0,0,.08)!important;
                box-shadow:0 4px 6px rgba(50,50,93,.18), 0 1px 3px rgba(0,0,0,.08)!important;
                -webkit-animation:wp-gwm .6s ease!important;
                animation:wp-gwm .6s ease!important;
                z-index: 999;
                visibility:visible!important;';
            $link_style ='font:normal normal 11px/20px system-ui,sans-serif!important;
                color:#2F80ED!important;
                text-decoration:underline!important;
                height:auto!important;
                width:auto!important;
                padding:0!important;';
            $banner = '<div style="'.$style.'"><span style="line-height:15px!important;">'.$text.'</span><br><a href="'.$link_url.'" target="_blank" style="'.$link_style.'">'.$link_text.'</a></div>';
            echo $banner;
        }
    }

    /*
        Head
    */
    public function remove_xmlrpc_methods($methods) {
        // https://blog.cloudflare.com/a-look-at-the-new-wordpress-brute-force-amplification-attack/
        unset( $methods['system.multicall'] );
        return $methods;
    }
    public function add_meta() {
        $title = is_front_page() ? get_bloginfo('name') : wp_title('  ', false, 'right');
        $charset = get_bloginfo('charset');
        $ie9 = "<!--[if lt IE 9]> <script src='".esc_url(get_template_directory_uri())."/libs/html5.js'></script> <![endif]-->";

        $cache = "";
        // if (check_enqueue(array( 'vc_form', 'contact-form-7', 'ninja_form' ))) {
        //     $cache .= "<meta http-equiv='Cache-control' content='no-cache, no-store, must-revalidate'>"; //HTTP 1.1
        //     $cache .= "<meta http-equiv='Pragma' content='no-cache'>"; //HTTP 1.0
        //     $cache .= "<meta http-equiv='Expires' content='Sat, 26 Jul 1997 05:00:00 GMT'>"; // Date in the past
        //     $cache .= "<meta http-equiv='Date' content='".date('D, j M Y H:i:s T')."'>"; // Server Date
        // }

        ob_start();
        
            echo "<meta charset='".$charset."'>
                ".$ie9."
                <meta name='viewport' content='width=device-width, initial-scale=1'>
                <meta name='referrer' content='no-referrer-when-downgrade'>
                <meta http-equiv='X-UA-Compatible' content='IE=11'>
                ".$cache;

        return ob_get_contents();
    }
    public function extend_favicon() {
        $favicon = "";
        $icon  = get_option( 'site_icon', false );
        if ($icon) {
            $icon = wp_get_attachment_url($icon);
            $favicon = "<meta name='msapplication-square150x150logo' content='$icon' />
                        <link rel='shortcut icon' href='$icon'>
                        <link rel='apple-touch-icon' href='$icon' />";
        }

        $title = is_front_page() ? get_bloginfo('name') : wp_title('  ', false, 'right');
        $meta = "<meta name='theme-color' content='#fff'>
                <meta name='msapplication-navbutton-color' content='#fff'>
                <meta name='apple-mobile-web-app-status-bar-style' content='#fff'>

                <meta name='mobile-web-app-capable' content='no' />
                <meta name='apple-mobile-web-app-capable' content='no' />
                <meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />
                <meta name='application-name' content='".$title."'>
                <meta name='apple-mobile-web-app-title' content='".$title."'>";
        
    
        ob_start();

            echo $favicon;
            echo $meta;

        return ob_get_contents();
    }
}


/**
 * =================================================================
 *                          Global Functions
 * =================================================================
 */

/**
 * Debug Function
 */
if ( ! function_exists( 'debug' ) ) {
	function debug( $a, $b = false ) {
		echo '<pre>';
		! $b ? print_r( $a ) : var_dump( $a );
		echo '</pre>';
	}
}

if ( ! function_exists( 'var_error_log' ) ) {
	function var_error_log( $object = null ) {
		ob_start();                    // start buffer capture
		var_dump( $object );           // dump the values
		$contents = ob_get_contents(); // put the buffer into a variable
		ob_end_clean();                // end capture
		error_log( $contents );        // log contents of the result of var_dump( $object )
	}
}

/**
 * Get Thumbnail Image
 */
if ( ! function_exists( 'get_image' ) ) {
	function get_image( $id, $size ) {
		$size = ! $size ? 'full' : $size;
		// foreach(get_intermediate_image_sizes() as $sze) {
		// debug($sze);
		// debug(wp_get_attachment_image_src($id, $sze));
		// }
		$thumb = wp_get_attachment_image_src( $id, $size );
		return $thumb === false ? $thumb : $thumb[0];
	}
}

if ( ! function_exists( 'get_imageset' ) ) {
	function get_imageset( $id ) {
		$fullsize = wp_get_attachment_image_src( $id, 'full' );
		if ( $fullsize === false ) {
			return false;
		}
		// $srcset = array( $fullsize[1] => $fullsize[0] );
		$srcset = array( 'full' => $fullsize[0] );
		foreach ( get_intermediate_image_sizes() as $sze ) {
			$size = wp_get_attachment_image_src( $id, $sze );
			if ( ! isset( $srcset[ $size[1] ] ) && $size[0] != $srcset['full'] ) {
				$srcset[ $size[1] ] = $size[0];
			}
		}
		ksort( $srcset );
		return $srcset;
	}
}

/**
 * Get language
 */
if ( ! function_exists( 'get_language' ) ) {
	function get_language( $lang = 'de' ) {
		if ( defined( 'ICL_LANGUAGE_CODE' ) ) {
			$lang = substr( ICL_LANGUAGE_CODE, 0, 2 );
		} else {
			$lang = substr( get_locale(), 0, 2 );
			// define('ICL_LANGUAGE_CODE', $lang);
		}
		// debug($lang);
		return $lang;
	}
}

/**
 * Get languages
 */
if ( ! function_exists( 'get_languages' ) ) {
	function get_languages( $lang = 'de' ) {
		if ( function_exists( 'icl_get_languages' ) ) {
			$languages = icl_get_languages( 'skip_missing=N&orderby=KEY&order=asc&link_empty_to=str' );
		} else {
			$lang      = substr( get_locale(), 0, 2 );
			$languages = array(
				$lang => array(
					'code' => $lang,
					'url'  => '',
				),
			);
		}
		// debug($languages);
		return $languages;
	}
}

/**
 * Enqueue checker
 *
 * TBD - deprecate/remove (see basics.php):
 * function is never used.
 * last use in modules/maps removed due to debugging.
 */

if ( ! function_exists( 'run_enque' ) ) {
	function run_enque( $sc = array(), $js = array(), $css = array() ) {
		return enqueue::check_enqueue( $sc );
	}
}
if ( ! function_exists( 'check_enqueue' ) ) {
	function check_enqueue( $sc = array() ) {
		return enqueue::check_enqueue( $sc );
	}
}

if ( ! function_exists( 'wp_process_style' ) ) {
	function wp_process_style( $handle, $path ) {
		$data = processor::process_styles( $path );
		wp_add_inline_style( $handle, $data );
	}
}
if ( ! function_exists( 'wp_process_style_string' ) ) {
	function wp_process_style_string( $handle, $style ) {
		$data = processor::process_styles_string( $style );
		wp_add_inline_style( $handle, $data );
	}
}