user may not want to configure a whole theme and just pass in the theme we give them wholesale, lets convert it
344145
function convertRawTheme(theme) {
  if (!Array.isArray(theme.constants)) {
    return {
      constants: Object.keys(theme.constants).map(key => theme.constants[key]),
      styles: [].concat(theme.styles),
      animations: [].concat(theme.animations)
    }
  }
  else
    return theme;
}
510663
public function restrictThemeManagement() {
		$locked = $this->isLocked();
		if ( $locked ) {
			$data = $this->getLockData();

			// Redirect and notify users of theme lock status.

			$check_against_url = wp_parse_url( ( is_ssl() ? 'http://' : 'https://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], PHP_URL_PATH );
			$redirect_url = get_site_url( get_current_blog_id(), '/wp-admin/' );

			// ---------------------------------------------------------------------------------------------------------------
			// Don't let user go to theme (options) page, under any circumstance

			$restricted = [
				'themes',
			];

			$expr = '~/wp-admin/(' . implode( '|', $restricted ) . ')\.php$~';
			if ( preg_match( $expr, $check_against_url ) ) {
				$_SESSION['pb_errors'][] = sprintf(
					__( 'Your book&rsquo;s theme, %1$s, was locked in its current state as of %2$s at %3$s. To select a new theme or change your theme options, please %4$s.', 'pressbooks' ),
					$data['name'],
					strftime( '%x', $data['timestamp'] ),
					strftime( '%X', $data['timestamp'] ),
					sprintf(
						'<a href="%s">%s</a>',
						admin_url( 'options-general.php?page=pressbooks_export_options' ),
						'unlock your theme'
					)
				);
				\Pressbooks\Redirect\location( $redirect_url );
			}
		}
	}
732244
protected function addSampleTheme() {
        // replacements
        $values = array(
            '{themeLabel}' => $this->label . ' default theme',
            '{themeId}' => StringUtils::camelize($this->label . ' default theme'),
            '{platformTheme}' => StringUtils::camelize($this->label . ' default theme', true)
        );
        $pathValues = array();
        foreach($values as $key => $value) {
            $pathValues[trim($key, '{}')] = $value;
        }

        // copy templates
        $samplePath = \common_ext_ExtensionsManager::singleton()->getExtensionById('taoDevTools')->getDir()
            .'models'.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR;
        $paths = array(
            array('model','theme','*.sample'),
            array('scripts','install','*.sample'),
            array('views','templates','themes','platform','themeId','*.sample'),
            array('views','scss','themes','items','*.sample'),
            array('views','scss','themes','platform','themeId','*.sample')
        );

        $templates = array();
        foreach($paths as $path) {
            $templates = array_merge($templates, glob($samplePath.implode(DIRECTORY_SEPARATOR, $path)));
        }
        
        foreach($templates as $template) {
            $template = \tao_helpers_File::getRelPath($samplePath, $template);
            $template = substr($template, 0, strrpos($template, '.'));
            $this->copyFile($template, str_replace(array_keys($pathValues), $pathValues, $template), $values);
        }
    }
348504
protected function _setTheme()
    {
        $theme = $this->request->getParam('theme');
        if ($theme) {
            $this->viewBuilder()->setTheme($theme);
        }
    }
169785
function convertConfig(config) {
    let {colors, prev = '', output, src = 'css/rsuite.min.css'} =config;
    return Object.keys(colors).map(key => {
        return {
            baseColor: colors[key],
            src,
            dist: Path.join(output, `${prev}${key}${Path.extname(src)}`)
        }
    });
}
995621
function updateThemes(cm) {
        var newTheme = prefs.get("theme"),
            cmTheme  = (cm.getOption("theme") || "").replace(/[\s]*/, ""); // Normalize themes string

        // Check if the editor already has the theme applied...
        if (cmTheme === newTheme) {
            return;
        }

        // Setup current and further documents to get the new theme...
        CodeMirror.defaults.theme = newTheme;
        cm.setOption("theme", newTheme);
    }
618970
public static function setup_theme() {

		global $pagenow;

		if ( ( is_admin() && 'themes.php' == $pagenow ) || ! self::can_switch_themes() ) {
			return;
		}

		self::check_reset();
		self::load_cookie();

		if ( empty( self::$theme ) ) {
			return;
		}

		add_filter( 'pre_option_template', array( self::$theme, 'get_template' ) );
		add_filter( 'pre_option_stylesheet', array( self::$theme, 'get_stylesheet' ) );
		add_filter( 'pre_option_stylesheet_root', array( self::$theme, 'get_theme_root' ) );
		$parent = self::$theme->parent();
		add_filter( 'pre_option_template_root', array( empty( $parent ) ? self::$theme : $parent, 'get_theme_root' ) );
		add_filter( 'pre_option_current_theme', '__return_false' );
	}
100930
function(themeName, extOptions) {
        var options = presetOptions[themeName];

        if (!options) {
            options = presetOptions[themeNameConst.DEFAULT];
        }
        options = $.extend(true, {}, options, extOptions);
        setDocumentStyle(options);
    }
1104639
function changeConfig(oldConfig, newConfig) {
  invariant(isObject(oldConfig), 'Old config is not valid');
  invariant(isObject(newConfig), 'Config is not valid');

  if (newConfig.host) {
    var host = newConfig.host;
    var prefix = '';

    if (host.indexOf('http://') < 0 && host.indexOf('https://') < 0) {
      prefix += 'http://';
    }

    oldConfig.host = prefix + newConfig.host;
  }

  if (newConfig.port) {
    oldConfig.port = newConfig.port;
  }
}
521328
function _replaceTheme( doc, theme ) {
    const HAS_THEME = /(theme-)[^"'\s]+/;

    if ( !theme ) {
        return doc;
    }

    const formClassAttr = doc.root().get( '/root/form' ).attr( 'class' );
    const formClassValue = formClassAttr.value();

    if ( HAS_THEME.test( formClassValue ) ) {
        formClassAttr.value( formClassValue.replace( HAS_THEME, `$1${theme}` ) );
    } else {
        formClassAttr.value( `${formClassValue} theme-${theme}` );
    }

    return doc;
}
517049
public function reset_theme_and_output() {
        global $COURSE, $SITE;

        $COURSE = clone($SITE);
        $this->_theme = null;
        $this->_wherethemewasinitialised = null;
        $this->_course = null;
        $this->_cm = null;
        $this->_module = null;
        $this->_context = null;
    }
1214508
protected function setThemeProperties()
    {
        $this->theme_frontend = $this->config('theme', 'frontend');
        $this->theme_backend = $this->config('theme_backend', 'backend');

        if ($this->is_backend) {
            $this->theme = $this->theme_backend;
        } elseif ($this->is_install) {
            $this->theme = $this->theme_frontend;
        } elseif (!empty($this->current_store)) {
            $this->theme_frontend = $this->store->getConfig('theme');
            $this->theme = $this->theme_frontend;
        }

        $this->hook->attach('theme', $this);

        if (empty($this->theme)) {
            $this->response->outputError404();
        }

        $this->current_theme = $this->module->getInfo($this->theme);

        if (empty($this->current_theme)) {
            $this->response->outputError404();
        }

        $this->theme_settings = (array) $this->getModuleSettings($this->theme, null, array());
        $this->templates = $this->getDefaultTemplates();

        if (!empty($this->current_theme['data']['templates'])) {
            $this->templates = array_merge($this->templates, $this->current_theme['data']['templates']);
        }
    }
939116
function updateThemeClass(theme) {
        if (!theme) return;
        if (!registered(theme)) {
          $log.warn('Attempted to use unregistered theme \'' + theme + '\'. ' +
                    'Register it with $mdThemingProvider.theme().');
        }

        var oldTheme = el.data('$mdThemeName');
        if (oldTheme) el.removeClass('md-' + oldTheme +'-theme');
        el.addClass('md-' + theme + '-theme');
        el.data('$mdThemeName', theme);
        if (ctrl) {
          el.data('$mdThemeController', ctrl);
        }
      }
95265
function View_resolve(toPath, fromPath) {
            var file = di.normalizePath(toPath),
                themes = this.config.themes.slice(),
                theme,
                re,
                filePath,
                normalizers = this.normalizers.slice(),
                isNormalized = false,
                path,
                pathRegex,
                pathReplace,
                trace = [];

            // file name normalizers
            while (normalizers.length) {
                path = di.normalizePath(normalizers.shift());
                pathReplace = path.replace(/\\/g, '\\\\');
                pathRegex = new RegExp(pathReplace);
                if (file.match(pathRegex)) {
                    file = file.replace(pathRegex, '').replace(this.suffix, '');
                    isNormalized = true;
                    break;
                }
            }
            // try normalize fromPath
            if (!isNormalized && !!fromPath) {
                normalizers = this.normalizers.slice();
                fromPath = di.normalizePath(fromPath);
                // file name normalizers
                while (normalizers.length) {
                    path = di.normalizePath(normalizers.shift());
                    pathReplace = path.replace(/\\/g, '\\\\');
                    pathRegex = new RegExp(pathReplace);
                    if (fromPath.match(pathRegex)) {
                        isNormalized = true;
                        break;
                    }
                }
            }

            // check themes
            if (isNormalized) {
                while (themes.length) {
                    theme = di.normalizePath(themes.shift() + '/');
                    pathReplace = theme.replace(/\\/g, '\\\\');
                    re = new RegExp('^' + pathReplace);
                    file = file.replace(re, '');

                    filePath = di.normalizePath(path + theme + '/' + file + this.config.suffix);
                    if (this.isFile(filePath)) {
                        return filePath;
                    }
                    trace.push({
                        theme: theme,
                        path: path,
                        filePath: filePath
                    });
                }
            }


            throw new error.HttpError(500, {
                from: fromPath,
                load: toPath,
                filePath: filePath,
                paths: this.paths,
                isNormalized: isNormalized,
                file: file,
                path: path,
                trace: trace,
                themes: this.config.themes
            }, "View.resolve: template don't exists");
        }
687020
function promptIfMainTheme(env) {
  return new Promise((resolve, reject) => {
    const c = config.shopify[env]

    if (!c.api_key) {
      console.log(chalk.yellow(`The "${env}" environment in config/shopify.yml does not specify an "api_key". Skipping check for if is main theme.`))
      resolve()
      return
    }

    // c.theme_id is live or equal to mainThemeId
    if (c.theme_id === 'live' || (mainThemeId && mainThemeId === c.theme_id)) {
      const question = 'You are about to deploy to the main theme. Continue ?'

      prompt(question, false).then((isYes) => {
        if (isYes) {
          resolve()
          return
        }

        reject('Aborting. You aborted the deploy.')
      })

      return
    }

    // we already have a mainThemeId and it's not c.theme_id
    if (mainThemeId && mainThemeId !== c.theme_id) {
      resolve()
      return
    }

    fetchMainThemeId(env)
      .then((id) => {
        mainThemeId = id
        promptIfMainTheme(env).then(resolve).catch(reject)
      })
      .catch(reject)
  })
}
162809
static function __duo($masterfile, $palette = null, $tint = null, array $overrides = null)
	{
		//	THEME vs. SCHEME vs. SKIN
		//	Theme = light/dark! AKA `tint` in the current system ... ie. `What theme would you like?` asking the user to choose a color scheme!
		//	Scheme = `Color Scheme` = club/brand colors = several headers/borders colored with this color scheme
		//	Skin = related to Scheme ... The club/brand skin is the backgrounds, like watermarks, background images representing a club/brand!
		static $basepath = '../app/duo/';
		static $cachepath = '../app/duo/cache/';
		static $duos = array();
		if (!isset($duos[$masterfile])) $duos[$masterfile] = require($basepath . $masterfile . '.php');
		$arr =& $duos[$masterfile];
		$files = array();
		$max_mtime = 0;
		if ($palette === null && $tint === null && $overrides === null)
		{
			if (isset($arr['static']))
				foreach ($arr['static'] as $static)
				{
					$mtime = filemtime($basepath . $static);
					$max_mtime = max($max_mtime, $mtime);
					$files[] = $cachepath . pathinfo($static, PATHINFO_FILENAME) . '-' . $mtime . /* '-' . md5($static) */ '.css';
				}
			$global_md5 = md5(serialize($arr['global']));
			foreach ($arr['themeable'] as $themeable)
			{
				$mtime = filemtime($basepath . $themeable);
				$max_mtime = max($max_mtime, $mtime);
				$files[] = $cachepath . pathinfo($themeable, PATHINFO_FILENAME) . '-' . $mtime . '-' . $global_md5 . '.css';
			}
			$result = 'styles/duo-' . $max_mtime . '-' . md5(serialize($files)) . '.css';
			if (file_exists($result)) return $result;
			//
			//	Global/base style file doesn't exists, create a new one!
			//
			$result_contents = null;	//	contents of the final file!
			require_once APP_LIB . 'duocss.php';
			$index = 0;	//	$files[$index] ... because static messes up the counter! ... can't we just add the count($arr['static']) ???
			if (isset($arr['static']))
				foreach ($arr['static'] as $static)
				{
					if (!file_exists($files[$index]))
					{
						$result_contents .= $contents = minify_css(file_get_contents($basepath . $static));
						file_put_contents($files[$index], $contents);
					}
					else
						$result_contents .= file_get_contents($files[$index]);
					$index++;
				}
			$global_keys = array_keys($arr['global']);	//	Get the global keys for str_replace()
			foreach ($arr['themeable'] as $themeable)
			{
				if (!file_exists($files[$index]))
				{
					$pattern = array();	//	Remove ALL lines with palette styles! Even if they include global styles!
					foreach ($arr['palette'] as $key => $unused)		//	We run the preg_replace() first, because it will reduce the contents, making str_replace() slightly faster!
						$pattern[] = '~[^{;]*' . $key . '[^;}]*;?~';
					//	We need to minify FIRST, because there might be some comments with styles! eg. border: BORDER /* BORDER-OLD */; But there might be other cases that screw up the regular expressions!
					$result_contents .= $contents = minify_css(str_replace($global_keys, $arr['global'], preg_replace($pattern, '', minify_css(file_get_contents($basepath . $themeable)))));
					file_put_contents($files[$index], $contents);
				}
				else
					$result_contents .= file_get_contents($files[$index]);
				$index++;
			}
			file_put_contents($result, $result_contents);
			return $result;
		}
		else
		{
		//	There `should` be too many variables and tints for an array_merge() to be feasable/viable! Also, this cannot account for $arr['palette'][$tint] coming before loading the palette file!
		//	$palettes = $palette === null ? $arr['palette'] : array_merge($arr['palette'], require '../app/duo/palettes/' . $palette . '.php');
			//
			//	Generate Palette
			//
			if ($palette !== null) $palette = require '../app/duo/palettes/' . $palette . '.php';
			//	`$files` is currently a blank array, so we use it as an empty array paceholder
			$palette = array_merge($arr['palette'], isset($arr['tints'][$tint]) ? $arr['tints'][$tint] : $files, isset($palette[0]) ? $palette[0] : $files, isset($palette[$tint]) ? $palette[$tint] : $files, $overrides === null ? $files : $overrides);
			//	Create an md5 hash of the palette. Used as part of the filename in each cached themeable file!
			$palette_md5 = md5(serialize($palette));	//	. serialize($arr['global']) .... DISABLED (the serialize) FOR NOW!  TEST  IT !! The reason why we need to include the global, is in-case a global value changed ... HOWEVER, in that case, wouldn't the files also change ??? However again, we might be using dynamic overrides !?!?
			//	Add each `themeable` file to the files array! To be serialized and md5 hashed later to test the existance of the final file!
			foreach ($arr['themeable'] as $themeable)
			{
				$mtime = filemtime($basepath . $themeable);
				$max_mtime = max($max_mtime, $mtime);
				$files[] = $cachepath . pathinfo($themeable, PATHINFO_FILENAME) . '-' . $mtime . '-' . $palette_md5 . '.css';
			}
			$result = 'styles/duo-' . $max_mtime . '-' . md5(serialize($files)) . '.css';
			if (file_exists($result)) return $result;
			//
			//	Public styled palette doesn't exist; test the existence of each cached themeable file
			//
			$result_contents = null;	//	contents of the final file!
			require_once APP_LIB . 'duocss.php';
			$keys = array_merge(array_keys($arr['global']), array_keys($arr['palette']));	//	Create an array of the merged global and palette keys!
			$keys_md5 = md5(serialize($keys));
			$patterns = array();
			//	Build an array of keys to extract! We will split each file into class names and content, then scan the content for our keys and extract them!
			foreach ($keys as $key)
				$patterns[] = '~[^;]*' . $key . '[^;]*~';
			$global_keys = array_keys($arr['global']);
			$palette_keys = array_keys($palette);
			$palette_patterns = array();
			foreach ($palette_keys as $key)
				$palette_patterns[] = '~[^;]*' . $key . '[^;]*~';	//	Build the palette patterns! Once we split the cached contents into classes and attributes, then we can run these patterns!

			foreach ($arr['themeable'] as $key => $themeable)
			{
				if (!file_exists($files[$key]))
				{	//	First test for the intermediate cached file. This file contains ALL the possible styleable global and palette variables/attributes/styles.
					$mtime = filemtime($basepath . $themeable);
					$filename = pathinfo($themeable, PATHINFO_FILENAME);
					$cache = $cachepath . $filename . '-' . $mtime . '-' . $keys_md5 . '.css';
					if (!file_exists($cache))
					{	//	Create the intermediate cached file with ALL possible overwriteable styles!
						$path = $basepath . $themeable;
						$contents = minify_css(file_get_contents($path));	//	Minify the contents, mainly to remove the comments, because they CAN interfere with the class names and the regular expression matches (because they can contain the following characters {;} !!!
						preg_match_all('~([^{;}]+){([^{}]+)}~', $contents, $split);	//	Split the file into classes and content!	eg. html{overflow:auto} => `html` && `overflow:auto`
						$preserve = array();	//	classes and attributes/styles to preserve, basically we `remove` all the styles which are not configurable (we do this by INCLUDING only valid styleable classes and attributes here)! Leaving only styles that include a global or palette constant!
						foreach ($split[2] as $index => $value)	//	loop through each class and attribute list and extract the customizeable styles!
							foreach ($patterns as $pattern)
								if (preg_match_all($pattern, $value, $matches))	//	our `$patterns` don't actually capture anything, so we are able to use $matches[0]!
									if (isset($preserve[$split[1][$index]]))
										$preserve[$split[1][$index]] .= ';' . implode(';', $matches[0]);
									else
										$preserve[$split[1][$index]] = implode(';', $matches[0]);
						$contents = ''; // reset & rebuild contents with our `preserved` classes and constants!
						foreach ($preserve as $class => $style)
							$contents .= $class . '{' . $style . '}';
						file_put_contents($cache, $contents);
					}
					else
						$contents = file_get_contents($cache);

					//	Now we have the intermediate content, which includes both global and palette styles! Now we need to extract only the styles we need! For example, many `global` styles will be dropped here!
					preg_match_all('~([^{;}]+){([^{}]+)}~', $contents, $split);
					$preserve = array();
					foreach ($split[2] as $index => $value)
						foreach ($palette_patterns as $pattern)
							if (preg_match_all($pattern, $value, $matches))
								if (isset($preserve[$split[1][$index]]))
									$preserve[$split[1][$index]] .= ';' . implode(';', $matches[0]);
								else
									$preserve[$split[1][$index]] = implode(';', $matches[0]);
					$contents = '';	//	rebuild the contents, unused styles should have been removed!?!?
					foreach ($preserve as $class => $style)
						$contents .= $class . '{' . $style . '}';

				/*	//	This is only necessary if we use the str_replace() variant !!!
					if (!env::$production && preg_match_all('|[A-Z]{2,}(?:-[A-Z]{2,})+|', $contents, $matches))
						foreach ($matches[0] as $match)
							if (!isset($palette[$match]))
								die('<b>ERROR</b> finding the CSS variable: <b>' . $match . '</b> in file: <b>' . $themeable);
				*/

					// Now we have rebuilt the content, we need to replace the style placeholders!
					//	First, we replace the PALETTE styles, which could include global style overrides! THEN we place the global styles, if there are any left over! This has to be done if we've mixed palette with global styles! eg. border: BORDER-WIDTH BORDER-COLOR ... where BORDER-WIDTH might be a global, and BORDER-COLOR is a palette value!
				//	$result_contents .= $contents = str_replace($global_keys, $arr['global'], str_replace($palette_keys, $palette, $contents));	//	we `could` run the minifier AGAIN, but it's already 99.9% minified! For example, the placeholders could be unminified eg. `BORDER` => `0 0 0 0` instead of just 0 ... or `0px` instead of 0
					$result_contents .= $contents = preg_replace_callback('|[A-Z]{2,}(?:-[A-Z]{2,})+|', function($matches)use($palette){return $palette[$matches[0]];}, $contents);	// The preg_replace_callback() variant was about 30% faster than str_replace() on a very large file (about +200K)! They still executed at 0.01s vs. 0.007 on a very large file with 30 other files!

					file_put_contents($files[$key], $contents);
				}
				else
					$result_contents .= file_get_contents($files[$key]);
			}

			file_put_contents($result, $result_contents);
			return $result;
		}
	}
90903
public static function convertFromLegacyTheme($theme)
    {
        if ($theme instanceof ConfigurablePlatformTheme) {
            return $theme;
        }

        // older themes are stored as an instance, newer ones as array
        if(is_array($theme)) {
            if(empty($theme[ThemeServiceInterface::THEME_CLASS_OFFSET])) {
                throw new \common_exception_MissingParameter(
                    ThemeServiceInterface::THEME_CLASS_OFFSET,
                    __METHOD__
                );
            }

            $options = !empty($theme[ThemeServiceInterface::THEME_OPTIONS_OFFSET])
                ? $theme[ThemeServiceInterface::THEME_OPTIONS_OFFSET]
                : []
            ;

            $theme = new $theme[ThemeServiceInterface::THEME_CLASS_OFFSET]($options);
        }

        // list of all previously used templates
        $templates = ['footer', 'header', 'header-logo', 'login-message'];

        // all keys associated with a public getter from previously used theme classes
        $getKeys = ['id', 'label', 'stylesheet', 'logoUrl', 'link', 'message', 'customTexts'];

        // collect options
        $options = [];
        if (method_exists($theme, 'getOptions')) {
            $options = $theme->getOptions();
        }

        if (method_exists($theme, 'getThemeData')) {
            $options = array_merge($options, $theme->getThemeData());
        }
        unset($options['data']);

        foreach ($getKeys as $key) {
            $method = 'get' . ucfirst($key);
            if (method_exists($theme, $method)) {
                $options[$key] = $theme->{$method}();
            }
        }
        // TAO default logo URL is different
        if($theme instanceof DefaultTheme) {
            $options['logoUrl'] = Template::img('tao-logo.png', 'tao');
        }

        if (method_exists($theme, 'getTemplate')) {
            if (empty($options[ConfigurablePlatformTheme::TEMPLATES])) {
                $options[ConfigurablePlatformTheme::TEMPLATES] = [];
            }
            foreach ($templates as $id) {
                $template = $theme->getTemplate($id);
                if(!is_null($template)) {
                    $options[ConfigurablePlatformTheme::TEMPLATES][$id] = $template;
                }
            }
        }

        // example: oat\taoExtension\model\theme\MyTheme
        $themeClass = get_class($theme);
        //@todo: map to container id
        if (empty($options[ConfigurablePlatformTheme::EXTENSION_ID])) {
            strtok($themeClass, '\\');
            $options[ConfigurablePlatformTheme::EXTENSION_ID] = strtok('\\');
        }

        if (empty($options[ConfigurablePlatformTheme::LABEL])) {
            $options[ConfigurablePlatformTheme::LABEL] = basename($themeClass);
        }
        return new ConfigurablePlatformTheme($options);
    }