Save custom CSS as file

@throws \common_exception_IsAjaxAction
766410
public function save() {
        if (!tao_helpers_Request::isAjax()) {
            throw new common_exception_IsAjaxAction(__METHOD__);
        }
        if (!$this->hasRequestParameter('uri')) {
            throw new common_exception_MissingParameter('uri', __METHOD__);
        }
        if (!$this->hasRequestParameter('stylesheetUri')) {
            throw new common_exception_MissingParameter('stylesheetUri', __METHOD__);
        }
        if (!$this->hasRequestParameter('lang')) {
            throw new common_exception_MissingParameter('lang', __METHOD__);
        }
        
        $item = new \core_kernel_classes_Resource($this->getRequestParameter('uri'));
        $lang = $this->getRequestParameter('lang');
        $styleSheet = $this->getRequestParameter('stylesheetUri');
        if (!\tao_helpers_File::securityCheck($styleSheet, true)) {
            throw new \common_exception_Error('invalid stylesheet path "'.$styleSheet.'"');
        }

        $css = $this->getCssArray();
        CssHelper::saveCssFile($item, $lang, $styleSheet, $css);
    }
534397
function (cb) {
    // check if we have a custom index file set
    if (settings.index) {
      // generate the real index file path
      var indexFile = process.cwd() + '/' + settings.index;

      // check if the file exists, throw an error otherwise
      if (!grunt.file.exists(indexFile)) {
        grunt.log.error('Index file: "' + indexFile + '" not found');
        cb('Index file: "' + indexFile + '" not found');
        return;
      }

      // load the file contents
      sourceFile = grunt.file.read(indexFile);
    }

    // modify the sourcefile css according to the settings
    var css = settings.css.map(function (file) {   
      if (settings.snapshot && file.search('http://') !== -1) {
        return '<link rel="stylesheet" type="text/css" href="' + path.basename(file) + '"/>';
      } else {
        return '<link rel="stylesheet" type="text/css" href="' + file + '"/>';
      }
    });
    sourceFile = sourceFile.replace('{{css}}', css.join(''));

    // spit out the default sourcefile
    cb(sourceFile);
  }
998826
function save() {
		$fw=Base::instance();
		if ($this->flag) {
			if (!is_dir($dir=$fw->get('TEMP')))
				mkdir($dir,Base::MODE,TRUE);
			$this->count++;
			$fw->write($dir.'/'.
				$fw->hash($fw->get('ROOT').$fw->get('BASE')).'.'.
				$fw->hash($this->file).'-'.$this->count.'.png',
				$this->dump());
		}
		return $this;
	}
282974
public function write( ADT_CSS_Sheet $sheet ){
		if( !$this->fileName )
			throw new RuntimeException( 'No CSS file set yet' );
		return self::save( $this->fileName, $sheet );
	}
382115
public function save()
    {
        $path = $this->paths['customPath'];

        $result = true;
        if (!empty($this->changedData)) {
            foreach ($this->changedData as $key1 => $keyData) {
                foreach ($keyData as $key2 => $data) {
                    if (!empty($data)) {
                        $result &= $this->getFileManager()->mergeContents(array($path, $key1, $key2.'.json'), $data, true);
                    }
                }
            }
        }

        if (!empty($this->deletedData)) {
            foreach ($this->deletedData as $key1 => $keyData) {
                foreach ($keyData as $key2 => $unsetData) {
                    if (!empty($unsetData)) {
                        $rowResult = $this->getFileManager()->unsetContents(array($path, $key1, $key2.'.json'), $unsetData, true);
                        if ($rowResult == false) {
                            $GLOBALS['log']->warning('Metadata items ['.$key1.'.'.$key2.'] can be deleted for custom code only.');
                        }
                        $result &= $rowResult;
                    }
                }
            }
        }

        if ($result == false) {
            throw new Error("Error saving metadata. See log file for details.");
        }

        $this->clearChanges();

        return (bool) $result;
    }
726575
private function _style() {
        // we need to compress?
        if($this->compress && $this->_config['compress']['css']) {
            // get cache
            $cache = $this->filename('css');
            if(!$cache)
                return false;

            // get paths
            $web_path = $this->_config['paths']['css'] . '/' . $cache;
            $system_path = $this->css['full'] . DS . $cache;

            // no cache file? write it
            if(!file_exists($system_path)) {
                // process compression
                $output = $this->process('css');

                // write to file
                file_put_contents($system_path, $output);
            }

            // output with the HTML helper
            return $this->Html->css($web_path);

        // no need to compress? output separately with the HTML helper
        } else return $this->Html->css($this->css['extern']);
    }
885939
function save() {
    // we must reset the colour cache or it will keep bad colours after clipping
    $this->currentColour = null;
    $this->currentStrokeColour = null;
    $this->objects[$this->currentContents]['c'].=  "\nq";
  }
1230121
def install_custom_css( destdir, cssfile, resource=PKGNAME ):
    
    ensure_dir_exists( destdir )
    custom = os.path.join( destdir, 'custom.css' )
    prefix = css_frame_prefix(resource)

    # Check if custom.css already includes it. If so, let's remove it first
    exists = False
    if os.path.exists( custom ):
        with io.open(custom) as f:
            for line in f:
                if line.find( prefix ) >= 0:
                    exists = True
                    break
    if exists:
        remove_custom_css( destdir, resource )

    # Fetch the CSS file
    cssfile += '.css'
    data = pkgutil.get_data( resource, os.path.join('resources',cssfile) )
    # get_data() delivers encoded data, str (Python2) or bytes (Python3)

    # Add the CSS at the beginning of custom.css
    # io.open uses unicode strings (unicode in Python2, str in Python3)
    with io.open(custom + '-new', 'wt', encoding='utf-8') as fout:
        fout.write( u'{}START ======================== */\n'.format(prefix))
        fout.write( data.decode('utf-8') )
        fout.write( u'{}END ======================== */\n'.format(prefix))
        if os.path.exists( custom ):
            with io.open( custom, 'rt', encoding='utf-8' ) as fin:
                for line in fin:
                    fout.write( unicode(line) )
    os.rename( custom+'-new',custom)
164690
public function customCssAction()
    {
        /* @var $siteInfo \Zork\Db\SiteInfo */
        /* @var $model \Grid\Customize\Model\Extra\Model */
        /* @var $structure \Grid\Customize\Model\Extra\Structure */
        $params     = $this->params();
        $request    = $this->getRequest();
        $id         = $params->fromRoute( 'id' );
        $rootId     = is_numeric( $id ) ? (int) $id : null;
        $schema     = $params->fromRoute( 'schema' );
        $locator    = $this->getServiceLocator();
        $siteInfo   = $locator->get( 'Zork\Db\SiteInfo' );

        if ( $schema != $siteInfo->getSchema() )
        {
            $this->getResponse()
                 ->setResultCode( 403 );

            return;
        }

        $model      = $locator->get( 'Grid\Customize\Model\Extra\Model' );
        $structure  = $model->findByRoot( $rootId );

        if ( empty( $structure ) )
        {
            $this->getResponse()
                 ->setResultCode( 404 );

            return;
        }

        $id         = $rootId ?: 'global';
        $url        = $this->url();
        $hash       = $structure->updated->toHash();
        $cssPath    = $url->fromRoute( 'Grid\Customize\Render\CustomCss', array(
            'schema' => $schema,
            'id'     => $id,
            'hash'   => $hash,
        ) );

        $cssFile = static::PUBLIC_DIR . $cssPath;

        if ( ! is_file( $cssFile ) )
        {
            $dir = dirname( $cssFile );

            if ( ! is_dir( $dir ) )
            {
                mkdir( $dir, 0777, true );
            }

            $iterator = new RegexIterator(
                new FileSystemIterator(
                    $dir,
                    FileSystemIterator::SKIP_DOTS |
                    FileSystemIterator::KEY_AS_FILENAME |
                    FileSystemIterator::CURRENT_AS_PATHNAME
                ),
                '#.*[/\\\\]custom\.([^\\.]+|'
                    . preg_quote( $id, '#' )
                    . '\.[^\\.]+)\.css$#'
            );

            foreach ( $iterator as $unlinkPath )
            {
                @ unlink( $unlinkPath );
            }

            $this->getServiceLocator()
                 ->get( 'Grid\Customize\Model\Sheet\Model' )
                 ->findByExtra( $structure )
                 ->render( $cssFile );
        }

        $requestPath = $request->getUri()
                               ->getPath();

        if ( ltrim( $requestPath, '/' ) != ltrim( $cssPath, '/' ) )
        {
            return $this->redirect()
                        ->toUrl( $cssPath );
        }

        $response = Readfile::fromFile( $cssFile, 'text/css' );

        $this->getEvent()
             ->setResponse( $response );

        return $response;
    }
829646
public function createCssLoader(): CssLoader
	{
		$compiler = Compiler::createCssCompiler($this->files[self::CSS][null], $this->wwwDir . '/' . $this->outputDir);
		foreach ($this->filters[self::CSS] as $filter) {
			$compiler->addFileFilter($filter);
		}
		return new CssLoader($compiler, $this->httpRequest->getUrl()->basePath . $this->outputDir);
	}
1212120
public function createTemplateFile()
	{		
		// css
		if (!is_dir($this->config['dir']['asset'] . '/css')) {
		  // dir doesn't exist, make it
		  mkdir($this->config['dir']['asset'] . '/css');
		}

		//js
		if (!is_dir($this->config['dir']['asset'] . '/js')) {
		  mkdir($this->config['dir']['asset'] . '/js');
		}

		// css file
		file_put_contents( $this->config['dir']['asset'] . '/css/bootstrap.min.css', file_get_contents(__DIR__ . '/tpl/css/bootstrap.min.css'));
		file_put_contents( $this->config['dir']['asset'] . '/css/bootstrap-theme.min.css', file_get_contents(__DIR__ . '/tpl/css/bootstrap-theme.min.css'));

		// js file
		file_put_contents( $this->config['dir']['asset'] . '/js/jquery.js', file_get_contents(__DIR__ . '/tpl/js/jquery.js'));
		file_put_contents( $this->config['dir']['asset'] . '/js/bootstrap.min.js', file_get_contents(__DIR__ . '/tpl/js/bootstrap.min.js'));

		// index html
		file_put_contents( $this->config['dir']['layout'] . '/index.html.tpl', file_get_contents(__DIR__ . '/tpl/index.html.tpl'));

		// post layout
		file_put_contents( $this->config['dir']['layout'] . '/post.html.tpl', file_get_contents(__DIR__ . '/tpl/post.html.tpl'));
		
		// page layout
		file_put_contents( $this->config['dir']['layout'] . '/page.html.tpl', file_get_contents(__DIR__ . '/tpl/page.html.tpl'));

		// category layout
		file_put_contents( $this->config['dir']['layout'] . '/category.html.tpl', file_get_contents(__DIR__ . '/tpl/category.html.tpl'));

		// author layout
		file_put_contents( $this->config['dir']['layout'] . '/author.html.tpl', file_get_contents(__DIR__ . '/tpl/author.html.tpl'));

		// sidebar layout
		file_put_contents( $this->config['dir']['layout'] . '/sidebar.html.tpl', file_get_contents(__DIR__ . '/tpl/sidebar.html.tpl'));

		// header layout
		file_put_contents( $this->config['dir']['layout'] . '/header.html.tpl', file_get_contents(__DIR__ . '/tpl/header.html.tpl'));

		// master layout
		file_put_contents( $this->config['dir']['layout'] . '/layout.html.tpl', file_get_contents(__DIR__ . '/tpl/layout.html.tpl'));
	}
762989
protected function cacheCssAssetFiles()
    {

        // Cache media asset files
        $this->cacheMediaAssetFiles();

        if ($this->getOptions()->isProduction()) {
            // Retrieve asset file filters manager
            $oAssetFileFiltersManager = $this->getAssetFileFiltersManager();

            // Retrieve Css file filter if available
            $oCssFileFilter = $oAssetFileFiltersManager->has(\AssetsBundle\AssetFile\AssetFile::ASSET_CSS) ? $oAssetFileFiltersManager->get(\AssetsBundle\AssetFile\AssetFile::ASSET_CSS) : null;

            // Create tmp asset file
            $oTmpAssetFile = $this->createTmpAssetFile(\AssetsBundle\AssetFile\AssetFile::ASSET_CSS);

            // Merge less asset files
            foreach ($this->cacheLessAssetFiles() as $oAssetFile) {
                $oTmpAssetFile->setAssetFileContents($this->rewriteAssetFileUrls(
                    // File content
                    $oCssFileFilter ? $oCssFileFilter->filterAssetFile($oAssetFile) : $oAssetFile->getAssetFileContents(),
                    // Current asset file
                    $oAssetFile
                ). PHP_EOL);

                // Remove temp less asset file
                \Zend\Stdlib\ErrorHandler::start();
                unlink($oAssetFile->getAssetFilePath());
                \Zend\Stdlib\ErrorHandler::stop(true);
            }

            // Merge css asset files
            foreach ($this->getAssetFilesConfiguration()->getAssetFiles(\AssetsBundle\AssetFile\AssetFile::ASSET_CSS) as $oAssetFile) {
                $oTmpAssetFile->setAssetFileContents($this->rewriteAssetFileUrls(
                    // File content
                    $oCssFileFilter ? $oCssFileFilter->filterAssetFile($oAssetFile) : $oAssetFile->getAssetFileContents(),
                    // Current asset file
                    $oAssetFile
                ) . PHP_EOL);
            }

             // Cache asset file if not empty
            if($oTmpAssetFile->getAssetFileSize()){
                return array($this->getAssetFilesCacheManager()->cacheAssetFile($oTmpAssetFile));
            }
            return array();
        }

        // Cache less asset files
        $aAssetFiles = $this->cacheLessAssetFiles();

        // Retrieve asset files cache manager
        $oAssetFilesCacheManager = $this->getAssetFilesCacheManager();
        foreach ($this->getAssetFilesConfiguration()->getAssetFiles(\AssetsBundle\AssetFile\AssetFile::ASSET_CSS) as $oAssetFile) {
            // Cache asset file if not empty
            if($oAssetFile->getAssetFileSize()){
                $aAssetFiles[] = $oAssetFilesCacheManager->cacheAssetFile($oAssetFile);
            }
        }
        return $aAssetFiles;
    }
924239
function writeCriticalFile(filePath, css) {
  _fs2.default.writeFile(filePath, css, { flag: append ? 'a' : 'w' }, function (err) {
    append = true;
    if (err) {
      console.error(err);
      process.exit(1);
    }
  });
}
839334
private function saveFile(): void
    {
        $sourceCode = Helpers::tabsToSpaces((string) $this->DTOFile);

        $fullPath = implode('/', [
            dirname(__DIR__, 7) . '/src',
            $this->inputData['namespace'],
            $this->inputData['module'] . 'Module',
            $this->inputData['type'],
            $this->inputData['class'] . $this->inputData['type'] . '.php'
        ]);

        $dirname = dirname($fullPath);

        if (!is_dir($dirname)) {
            mkdir($dirname, 0755, true);
        }

        $handle = fopen($fullPath, 'w');
        fwrite($handle, $sourceCode);
        fclose($handle);
    }
507682
private function processHtml()
    {
        $this->tree->build_tree();

        $this->css->load_css_file(Stylesheet::getDefaultStylesheet(), Stylesheet::ORIG_UA);

        $acceptedmedia = Stylesheet::$ACCEPTED_GENERIC_MEDIA_TYPES;
        $acceptedmedia[] = $this->options->getDefaultMediaType();

        // <base href="" />
        $base_nodes = $this->dom->getElementsByTagName("base");
        if ($base_nodes->length && ($href = $base_nodes->item(0)->getAttribute("href"))) {
            list($this->protocol, $this->baseHost, $this->basePath) = Helpers::explode_url($href);
        }

        // Set the base path of the Stylesheet to that of the file being processed
        $this->css->set_protocol($this->protocol);
        $this->css->set_host($this->baseHost);
        $this->css->set_base_path($this->basePath);

        // Get all the stylesheets so that they are processed in document order
        $xpath = new DOMXPath($this->dom);
        $stylesheets = $xpath->query("//*[name() = 'link' or name() = 'style']");

        /** @var \DOMElement $tag */
        foreach ($stylesheets as $tag) {
            switch (strtolower($tag->nodeName)) {
                // load <link rel="STYLESHEET" ... /> tags
                case "link":
                    if (mb_strtolower(stripos($tag->getAttribute("rel"), "stylesheet") !== false) || // may be "appendix stylesheet"
                        mb_strtolower($tag->getAttribute("type")) === "text/css"
                    ) {
                        //Check if the css file is for an accepted media type
                        //media not given then always valid
                        $formedialist = preg_split("/[\s\n,]/", $tag->getAttribute("media"), -1, PREG_SPLIT_NO_EMPTY);
                        if (count($formedialist) > 0) {
                            $accept = false;
                            foreach ($formedialist as $type) {
                                if (in_array(mb_strtolower(trim($type)), $acceptedmedia)) {
                                    $accept = true;
                                    break;
                                }
                            }

                            if (!$accept) {
                                //found at least one mediatype, but none of the accepted ones
                                //Skip this css file.
                                break;
                            }
                        }

                        $url = $tag->getAttribute("href");
                        $url = Helpers::build_url($this->protocol, $this->baseHost, $this->basePath, $url);

                        $this->css->load_css_file($url, Stylesheet::ORIG_AUTHOR);
                    }
                    break;

                // load <style> tags
                case "style":
                    // Accept all <style> tags by default (note this is contrary to W3C
                    // HTML 4.0 spec:
                    // http://www.w3.org/TR/REC-html40/present/styles.html#adef-media
                    // which states that the default media type is 'screen'
                    if ($tag->hasAttributes() &&
                        ($media = $tag->getAttribute("media")) &&
                        !in_array($media, $acceptedmedia)
                    ) {
                        break;
                    }

                    $css = "";
                    if ($tag->hasChildNodes()) {
                        $child = $tag->firstChild;
                        while ($child) {
                            $css .= $child->nodeValue; // Handle <style><!-- blah --></style>
                            $child = $child->nextSibling;
                        }
                    } else {
                        $css = $tag->nodeValue;
                    }

                    $this->css->load_css($css, Stylesheet::ORIG_AUTHOR);
                    break;
            }
        }
    }
466170
private function save()
    {
        $encodedContent = gzencode(json_encode($this->content));

        if (!file_exists($this->file)) {
            touch($this->file);
        }

        $fh = fopen($this->file, 'r+');

        if (flock($fh, LOCK_EX)) {
            ftruncate($fh, 0);
            fwrite($fh, $encodedContent);
            fflush($fh);
            flock($fh, LOCK_UN);
            fclose($fh);
        } else {
            throw new \Exception('Could not acquire exclusive file lock.');
        }
    }
412099
private function SaveContent()
    {
        $this->Content()->SetType($this->FrontendModule()->MyType());
        $this->Content()->SetCssClass($this->Value('CssClass'));
        $this->Content()->SetCssID($this->Value('CssID'));
        $this->Content()->SetTemplate($this->Value('Template'));
        $this->Content()->SetCacheLifetime((int) $this->Value('CacheLifetime'));
        $this->Content()->SetGuestsOnly((bool) $this->Value('GuestsOnly'));
        if ($this->AutoPublish())
        {
            $this->Content()->SetPublish(true);
        }
        else
        {
            $this->Content()->SetPublish((bool) $this->Value('Publish'));
        }
        $this->Content()->SetPublishFrom($this->PublishDate('PublishFrom'));
        $this->Content()->SetPublishTo($this->PublishDate('PublishTo'));

        $action = Action::Update();
        if (!$this->Content()->Exists()) {
            $action = Action::Create();
            $this->Content()->SetUser(self::Guard()->GetUser());
        }
        $this->Content()->Save();
        $logger = new Logger(self::Guard()->GetUser());
        $logger->ReportContentAction($this->Content(), $action);
        if ($this->CanAssignGroup()) {
            $this->SaveRights();
        }
        $this->SaveMemberGroups();
        $this->SaveWordings();
    }