/** * Constructor. * * @param string $css CSS data. * @param Sabberworm\CSS\Settings $charset Parser settings. */ public function __construct($css, Sabberworm\CSS\Settings $settings = null) { if (is_null($settings)) { $settings = Sabberworm\CSS\Settings::create(); $settings->withMultibyteSupport(false); } $this->parser = new Sabberworm\CSS\Parser($css, $settings); $this->doc = $this->parser->parse(); }
public static function processCSSContent($sContent, $oFile) { $oCache = new Cache('preview_css' . $oFile->getInternalPath(), DIRNAME_TEMPLATES); header("Content-Type: text/css;charset=" . Settings::getSetting('encoding', 'browser', 'utf-8')); if ($oCache->entryExists() && !$oCache->isOutdated($oFile->getFullPath())) { $oCache->sendCacheControlHeaders(); $oCache->passContents(); exit; } $oParser = new Sabberworm\CSS\Parser($sContent, Sabberworm\CSS\Settings::create()->withDefaultCharset(Settings::getSetting('encoding', 'browser', 'utf-8'))); $oCssContents = $oParser->parse(); //Make all rules important // foreach($oCssContents->getAllRuleSets() as $oCssRuleSet) { // foreach($oCssRuleSet->getRules() as $oRule) { // $oRule->setIsImportant(true); // } // } //Multiply all rules and prepend specific strings $aPrependages = array('#rapila_admin_menu', '.filled-container.editing', '.ui-dialog', '.cke_dialog_contents', '#widget-notifications', '.cke_reset', 'body > .cke_reset_all', '.tag_panel'); foreach ($oCssContents->getAllDeclarationBlocks() as $oBlock) { $aNewSelector = array(); foreach ($oBlock->getSelectors() as $iKey => $oSelector) { $sSelector = $oSelector->getSelector(); if (StringUtil::startsWith($sSelector, "body ") || StringUtil::startsWith($sSelector, "html ")) { $aNewSelector[] = $sSelector; } else { foreach ($aPrependages as $sPrependage) { if (StringUtil::startsWith($sSelector, "{$sPrependage} ") || StringUtil::startsWith($sSelector, "{$sPrependage}.") || $sSelector === $sPrependage) { $aNewSelector[] = $sSelector; } else { $aNewSelector[] = "{$sPrependage} {$sSelector}"; } } } } $oBlock->setSelector($aNewSelector); } //Absolutize all URLs foreach ($oCssContents->getAllValues() as $oValue) { if ($oValue instanceof Sabberworm\CSS\Value\URL) { $sURL = $oValue->getURL()->getString(); if (!StringUtil::startsWith($sURL, '/') && !preg_match('/^\\w+:/', $sURL)) { $sURL = $oFile->getFrontendDirectoryPath() . DIRECTORY_SEPARATOR . $sURL; } $oValue->setURL(new Sabberworm\CSS\Value\CSSString($sURL)); } } $sContents = $oCssContents->render(Sabberworm\CSS\OutputFormat::createCompact()); $oCache->setContents($sContents); $oCache->sendCacheControlHeaders(); print $sContents; }
/** * @param string $attribute * @param string $stylesheet * @param string $parameters * @return boolean */ public function validateCSS($attribute, $stylesheet, $parameters) { $parser = new \Sabberworm\CSS\Parser($stylesheet); $style = $parser->parse(); foreach ($style->getAllRulesets() as $rulesets) { foreach ($rulesets->getRules() as $rules) { $rule = $rules->getRule(); if (!$this->isAllowedRule($rule)) { return false; } } } foreach ($style->getAllValues() as $value) { switch (true) { case $value instanceof \Sabberworm\CSS\Value\URL: $sValue = $this->getURLString($value); if (!$this->isValidDataUri($sValue) && !$this->isAllowedUrl($sValue)) { return false; } break; case $value instanceof \Sabberworm\CSS\Property\Import: $oValue = $value->getLocation(); $sValue = $this->getURLString($oValue); if (!$this->isValidDataUri($sValue) && !$this->isAllowedImportUrl($sValue)) { return false; } break; } } return true; }
/** * This utility script generates menu icons metadata based on the Dashicons icon font included in WordPress. */ if (!defined('ABSPATH')) { die('No direct script access'); } if (!constant('WP_DEBUG') || !current_user_can('edit_plugins')) { echo "Permission denied. You need the edit_plugins cap to run this script and WP_DEBUG must be enabled."; return; } require_once dirname(__FILE__) . '/PHP-CSS-Parser/autoloader.php'; $dashiconsStylesheet = ABSPATH . WPINC . '/css/dashicons.css'; $icons = array(); $ignoreIcons = array('dashboard', 'editor-bold', 'editor-italic'); $ignoreIcons = array_flip($ignoreIcons); $parser = new Sabberworm\CSS\Parser(file_get_contents($dashiconsStylesheet)); $cssDocument = $parser->parse(); $blocks = $cssDocument->getAllDeclarationBlocks(); foreach ($blocks as $block) { /** @var Sabberworm\CSS\RuleSet\DeclarationBlock $block */ //We want the ".dashicons-*:before" selectors. $selectors = $block->getSelectors(); foreach ($selectors as $selector) { /** @var Sabberworm\CSS\Property\Selector $selector */ if (preg_match('/\\.dashicons-(?P<name>[\\w\\-]+):before/', $selector->getSelector(), $matches)) { $name = $matches['name']; //We already have styles for icons that start with "admin-", and the arrow icons //aren't really suitable as menu icons. if (preg_match('/^(admin|arrow)-/', $name)) { break; }
public static function parse_css_template($dynamic_css, $css_id_preface) { $dynamic_css = str_replace('{{', '[[', $dynamic_css); $dynamic_css = str_replace('}}', ']]', $dynamic_css); /* End new parse */ $oParser = new Sabberworm\CSS\Parser($dynamic_css); $oCss = $oParser->parse(); foreach ($oCss->getAllDeclarationBlocks() as $oBlock) { foreach ($oBlock->getSelectors() as $oSelector) { //Loop over all selector parts (the comma-separated strings in a selector) and prepend the id $oSelector->setSelector($css_id_preface . ' ' . $oSelector->getSelector()); } } $dynamic_css = $oCss->__toString(); $dynamic_css = str_replace('[[', '{{', $dynamic_css); $dynamic_css = str_replace(']]', '}}', $dynamic_css); return $oCss->__toString(); }
/** * Sanitizes input. * * @return array */ public function sanitize() { $input = $this->all(); $parser = new \Sabberworm\CSS\Parser($input['boardCustomCSS']); $style = $parser->parse()->render(\Sabberworm\CSS\OutputFormat::createPretty()); $input['boardCustomCSS'] = $style; $this->replace($input); }
#!/usr/bin/env php <?php require_once dirname(__FILE__) . '/bootstrap.php'; $sSource = file_get_contents('php://stdin'); $oParser = new Sabberworm\CSS\Parser($sSource); $oDoc = $oParser->parse(); echo "\n" . '#### Input' . "\n\n```css\n"; print $sSource; echo "\n```\n\n" . '#### Structure (`var_dump()`)' . "\n\n```php\n"; var_dump($oDoc); echo "\n```\n\n" . '#### Output (`render()`)' . "\n\n```css\n"; print $oDoc->render(); echo "\n```\n";
require 'vendor/autoload.php'; function RGBToHex($r, $g, $b) { //String padding bug found and the solution put forth by Pete Williams (http://snipplr.com/users/PeteW) $hex = "#"; $hex .= str_pad(dechex($r), 2, "0", STR_PAD_LEFT); $hex .= str_pad(dechex($g), 2, "0", STR_PAD_LEFT); $hex .= str_pad(dechex($b), 2, "0", STR_PAD_LEFT); return $hex; } //$css_file = 'https://www.tricd.de/wp-content/themes/friedrich/style.css?ver=4.0'; $css_file = 'https://test12.sevenval-fit.com/admiralmobileapp/testing/;s;m=css;cdrid=cdrid_55528;extver=c866395bbd308031097815a8daab96bc;rp=css/css/styles.mobile.xml'; $project_name = 'admiral'; $color_file_name = $project_name . '_colors.css'; $unique_colors_file = $project_name . '_unique_colors.txt'; $oCssParser = new Sabberworm\CSS\Parser(file_get_contents($css_file)); $oCssDocument = $oCssParser->parse(); /* $all_values = $oCssDocument->getAllValues(); foreach($all_values as $value) { print_r($value); }*/ $color_hdl = fopen($color_file_name, 'w+'); $unique_colors = array(); $decls = $oCssDocument->getAllDeclarationBlocks(); foreach ($decls as $decl) { $decl->expandShorthands(); $selectors = $decl->getSelectors();
/** * Parse CSS and prepend the call to action / varition id */ public static function parse_css_template($dynamic_css, $css_id_preface) { $dynamic_css = str_replace('{{', '[[', $dynamic_css); $dynamic_css = str_replace('}}', ']]', $dynamic_css); $oParser = new Sabberworm\CSS\Parser($dynamic_css); $oCss = $oParser->parse(); foreach ($oCss->getAllDeclarationBlocks() as $oBlock) { foreach ($oBlock->getSelectors() as $oSelector) { $oSelector->setSelector($css_id_preface . ' ' . $oSelector->getSelector()); } } $dynamic_css = $oCss->__toString(); $dynamic_css = str_replace('[[', '{{', $dynamic_css); $dynamic_css = str_replace(']]', '}}', $dynamic_css); return $oCss->__toString(); }
/** * Executes the command * * @param InputInterface $input * @param OutputInterface $output */ protected function execute(InputInterface $input, OutputInterface $output) { $src = $input->getArgument('src'); $dst = $input->getArgument('dst'); $selector = $input->getArgument('selector'); $append = $input->getOption('append'); // Create CSS dest object $dstCss = new \Sabberworm\CSS\Parser($append && file_exists($dst) ? file_get_contents($dst) : null); $dstCssDoc = $dstCss->parse(); $finder = new Finder(); $resources = $finder->files()->depth(0)->in($src)->name($selector . '.css'); foreach ($resources as $res) { $output->writeln('CSS Found: ' . $res->getRealPath()); $css = new \Sabberworm\CSS\Parser(file_get_contents($res->getRealPath())); $cssDoc = $css->parse(); foreach ($cssDoc->getContents() as $block) { if ($block instanceof \Sabberworm\CSS\RuleSet\DeclarationBlock) { /* @var $ruleset \Sabberworm\CSS\RuleSet\DeclarationBlock */ // Keep only the root CSS (ignore media queries) $keepRules = array(); foreach ($block->getRules() as $rule) { /* @var $rule \Sabberworm\CSS\Rule\Rule */ $value = $rule->getValue(); if (is_object($value)) { // keep only object with size rem $keepValue = false; switch (get_class($value)) { case 'Sabberworm\\CSS\\Value\\Size': /* @var $value \Sabberworm\CSS\Value\Size */ if ($value->getUnit() == 'rem') { $value->setSize($value->getSize() * 10); $value->setUnit('px'); $keepValue = true; } break; case 'Sabberworm\\CSS\\Value\\RuleValueList': /* @var $value \Sabberworm\CSS\Value\RuleValueList */ foreach ($value->getListComponents() as $c) { if ($c instanceof \Sabberworm\CSS\Value\Size) { if ($c->getUnit() == 'rem') { $c->setSize($c->getSize() * 10); $c->setUnit('px'); $keepValue = true; } } } break; } if ($keepValue) { $keepRules[] = $rule; } } } if (count($keepRules)) { $oItem = new \Sabberworm\CSS\RuleSet\DeclarationBlock(); $oItem->setSelectors($block->getSelectors()); foreach ($keepRules as $rule) { $oItem->addRule($rule); } $dstCssDoc->append($oItem); } } } } $output->writeln('Write ' . $dst); file_put_contents($dst, $dstCssDoc->render(\Sabberworm\CSS\OutputFormat::createPretty())); }
public function adminGetContainers() { $oTemplate = $this->oPage->getTemplate(); foreach ($oTemplate->identifiersMatching('container', Template::$ANY_VALUE) as $oIdentifier) { $oInheritedFrom = null; $sContainerName = $oIdentifier->getValue(); if (BooleanParser::booleanForString($oIdentifier->getParameter('inherit'))) { $oInheritedFrom = $this->oPage; $iInheritedObjectCount = 0; while ($iInheritedObjectCount === 0 && ($oInheritedFrom = $oInheritedFrom->getParent()) !== null) { $iInheritedObjectCount = $oInheritedFrom->countObjectsForContainer($sContainerName); } } $sInheritedFrom = $oInheritedFrom ? $oInheritedFrom->getName() : ''; $aTagParams = array('class' => 'template-container template-container-' . $sContainerName, 'data-container-name' => $sContainerName, 'data-container-string' => TranslationPeer::getString('container_name.' . $sContainerName, null, $sContainerName), 'data-inherited-from' => $sInheritedFrom); $oContainerTag = TagWriter::quickTag('ol', $aTagParams); $mInnerTemplate = new Template(TemplateIdentifier::constructIdentifier('content'), null, true); //Replace container info //…name $mInnerTemplate->replaceIdentifierMultiple('content', TagWriter::quickTag('div', array('class' => 'template-container-description'), TranslationPeer::getString('wns.page.template_container', null, null, array('container' => TranslationPeer::getString('template_container.' . $sContainerName, null, $sContainerName)), true))); //…additional info $mInnerTemplate->replaceIdentifierMultiple('content', TagWriter::quickTag('div', array('class' => 'template-container-info'))); //…tag $mInnerTemplate->replaceIdentifierMultiple('content', $oContainerTag); //Replace actual container $oTemplate->replaceIdentifier($oIdentifier, $mInnerTemplate); } $bUseParsedCss = Settings::getSetting('admin', 'use_parsed_css_in_config', true); $oStyle = null; if ($bUseParsedCss) { $sTemplateName = $this->oPage->getTemplateNameUsed() . Template::$SUFFIX; $sCacheKey = 'parsed-css-' . $sTemplateName; $oCssCache = new Cache($sCacheKey, DIRNAME_PRELOAD); $sCssContents = ""; if (!$oCssCache->entryExists() || $oCssCache->isOutdated(ResourceFinder::create(array(DIRNAME_TEMPLATES, $sTemplateName)))) { $oIncluder = new ResourceIncluder(); foreach ($oTemplate->identifiersMatching('addResourceInclude', Template::$ANY_VALUE) as $oIdentifier) { $oIncluder->addResourceFromTemplateIdentifier($oIdentifier); } foreach ($oIncluder->getAllIncludedResources() as $sIdentifier => $aResource) { if ($aResource['resource_type'] === ResourceIncluder::RESOURCE_TYPE_CSS && !isset($aResource['ie_condition']) && !isset($aResource['frontend_specific'])) { if (isset($aResource['media'])) { $sCssContents .= "@media {$aResource['media']} {"; } if (isset($aResource['file_resource'])) { $sCssContents .= file_get_contents($aResource['file_resource']->getFullPath()); } else { // Absolute link, requires fopen wrappers $sCssContents .= file_get_contents($aResource['location']); } if (isset($aResource['media'])) { $sCssContents .= "}"; } } } $oParser = new Sabberworm\CSS\Parser($sCssContents, Sabberworm\CSS\Settings::create()->withDefaultCharset(Settings::getSetting("encoding", "browser", "utf-8"))); $oCss = $oParser->parse(); $this->cleanupCSS($oCss); $sCssContents = Template::htmlEncode($oCss->render(Sabberworm\CSS\OutputFormat::createCompact())); $oCssCache->setContents($sCssContents); } else { $sCssContents = $oCssCache->getContentsAsString(); } $oStyle = new HtmlTag('style'); $oStyle->addParameters(array('scoped' => 'scoped')); $oStyle->appendChild($sCssContents); } $sTemplate = $oTemplate->render(); $sTemplate = substr($sTemplate, strpos($sTemplate, '<body') + 5); $sTemplate = substr($sTemplate, strpos($sTemplate, '>') + 1); $sTemplate = substr($sTemplate, 0, strpos($sTemplate, '</body')); $oParser = new TagParser("<body>{$sTemplate}</body>"); $oTag = $oParser->getTag(); $this->cleanupContainerStructure($oTag); if ($bUseParsedCss) { $oTag->appendChild($oStyle); } $sResult = $oTag->__toString(); $sResult = substr($sResult, strpos($sResult, '<body>') + 6); $sResult = substr($sResult, 0, strrpos($sResult, '</body>')); return array('html' => $sResult, 'css_parsed' => $bUseParsedCss); }