core-bundle/src/Resources/contao/classes/StyleSheets.php
public function importStyleSheet()
	{
		if (Input::get('key') != 'import')
		{
			return '';
		}

		/** @var FileUpload $objUploader */
		$objUploader = new FileUpload();

		// Import CSS
		if (Input::post('FORM_SUBMIT') == 'tl_style_sheet_import')
		{
			$arrUploaded = $objUploader->uploadTo('system/tmp');

			if (empty($arrUploaded))
			{
				Message::addError($GLOBALS['TL_LANG']['ERR']['all_fields']);
				$this->reload();
			}

			foreach ($arrUploaded as $strCssFile)
			{
				// Folders cannot be imported
				if (is_dir($this->strRootDir . '/' . $strCssFile))
				{
					Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['importFolder'], basename($strCssFile)));
					continue;
				}

				$objFile = new File($strCssFile);

				// Check the file extension
				if ($objFile->extension != 'css')
				{
					Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['filetype'], $objFile->extension));
					continue;
				}

				// Check the file name
				$strName = preg_replace('/\.css$/i', '', basename($strCssFile));
				$strName = $this->checkStyleSheetName($strName);

				// Create the new style sheet
				$objStyleSheet = $this->Database->prepare("INSERT INTO tl_style_sheet (pid, tstamp, name, media) VALUES (?, ?, ?, ?)")
												->execute(Input::get('id'), time(), $strName, array('all'));

				$insertId = $objStyleSheet->insertId;

				if (!is_numeric($insertId) || $insertId < 0)
				{
					throw new \Exception('Invalid insert ID');
				}

				// Read the file and remove carriage returns
				$strFile = $objFile->getContent();
				$strFile = str_replace("\r", '', $strFile);

				$arrTokens   = array();
				$strBuffer   = '';
				$intSorting  = 0;
				$strComment  = '';
				$strCategory = '';
				$intLength   = \strlen($strFile);

				// Tokenize
				for ($i=0; $i<$intLength; $i++)
				{
					$char = $strFile[$i];

					// Whitespace
					if ($char == '' || $char == "\n" || $char == "\t")
					{
						// Ignore
					}

					// Comment
					elseif ($char == '/')
					{
						if ($strFile[$i+1] == '*')
						{
							while ($i<$intLength)
							{
								$strBuffer .= $strFile[$i++];

								if ($strFile[$i] == '/' && $strFile[$i-1] == '*')
								{
									$arrTokens[] = array
									(
										'type'    => 'comment',
										'content' => $strBuffer . $strFile[$i]
									);

									$strBuffer = '';
									break;
								}
							}
						}
					}

					// At block
					elseif ($char == '@')
					{
						$intLevel = 0;
						$strSelector = '';

						while ($i<$intLength)
						{
							$strBuffer .= $strFile[$i++];

							if ($strFile[$i] == '{')
							{
								if (++$intLevel == 1)
								{
									++$i;
									$strSelector = $strBuffer;
									$strBuffer = '';
								}
							}
							elseif ($strFile[$i] == '}')
							{
								if (--$intLevel == 0)
								{
									$arrTokens[] = array
									(
										'type'     => 'atblock',
										'selector' => $strSelector,
										'content'  => $strBuffer
									);

									$strBuffer = '';
									break;
								}
							}
						}
					}

					// Regular block
					else
					{
						$strSelector = '';

						while ($i<$intLength)
						{
							$strBuffer .= $strFile[$i++];

							if ($strFile[$i] == '{')
							{
								++$i;
								$strSelector = $strBuffer;
								$strBuffer = '';
							}
							elseif ($strFile[$i] == '}')
							{
								$arrTokens[] = array
								(
									'type'     => 'block',
									'selector' => $strSelector,
									'content'  => $strBuffer
								);

								$strBuffer = '';
								break;
							}
						}
					}
				}

				foreach ($arrTokens as $arrToken)
				{
					// Comments
					if ($arrToken['type'] == 'comment')
					{
						// Category (comments start with /** and contain only one line)
						if (strncmp($arrToken['content'], '/**', 3) === 0 && substr_count($arrToken['content'], "\n") == 2)
						{
							$strCategory = trim(str_replace(array('/*', '*/', '*'), '', $arrToken['content']));
						}

						// Declaration comment
						elseif (strpos($arrToken['content'], "\n") === false)
						{
							$strComment = trim(str_replace(array('/*', '*/', '*'), '', $arrToken['content']));
						}
					}

					// At blocks like @media or @-webkit-keyframe
					elseif ($arrToken['type'] == 'atblock')
					{
						$arrSet = array
						(
							'pid'        => $insertId,
							'category'   => $strCategory,
							'comment'    => $strComment,
							'sorting'    => $intSorting += 128,
							'selector'   => trim($arrToken['selector']),
							'own'        => $arrToken['content']
						);

						$this->Database->prepare("INSERT INTO tl_style %s")->set($arrSet)->execute();
						$strComment = '';
					}

					// Regular blocks
					else
					{
						$arrDefinition = array
						(
							'pid'        => $insertId,
							'category'   => $strCategory,
							'comment'    => $strComment,
							'sorting'    => $intSorting += 128,
							'selector'   => trim($arrToken['selector']),
							'attributes' => $arrToken['content']
						);

						$this->createDefinition($arrDefinition);
						$strComment = '';
					}
				}

				// Write the style sheet
				$this->updateStyleSheet($insertId);

				// Notify the user
				if ($strName . '.css' != basename($strCssFile))
				{
					Message::addInfo(sprintf($GLOBALS['TL_LANG']['tl_style_sheet']['css_renamed'], basename($strCssFile), $strName . '.css'));
				}
				else
				{
					Message::addConfirmation(sprintf($GLOBALS['TL_LANG']['tl_style_sheet']['css_imported'], $strName . '.css'));
				}
			}

			// Redirect
			System::setCookie('BE_PAGE_OFFSET', 0, 0);
			$this->redirect(str_replace('&key=import', '', Environment::get('request')));
		}

		// Return form
		return Message::generate() . '
<div id="tl_buttons">
<a href="' .ampersand(str_replace('&key=import', '', Environment::get('request'))). '" class="header_back" title="' .StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['backBTTitle']). '" accesskey="b">' .$GLOBALS['TL_LANG']['MSC']['backBT']. '</a>
</div>
<form action="' .ampersand(Environment::get('request'), true). '" id="tl_style_sheet_import" class="tl_form tl_edit_form" method="post" enctype="multipart/form-data">
<div class="tl_formbody_edit">
<input type="hidden" name="FORM_SUBMIT" value="tl_style_sheet_import">
<input type="hidden" name="REQUEST_TOKEN" value="'.REQUEST_TOKEN.'">
<input type="hidden" name="MAX_FILE_SIZE" value="'.Config::get('maxFileSize').'">

<div class="tl_tbox">
  <div class="widget">
    <h3>'.$GLOBALS['TL_LANG']['tl_style_sheet']['source'][0].'</h3>'.$objUploader->generateMarkup().(isset($GLOBALS['TL_LANG']['tl_style_sheet']['source'][1]) ? '
    <p class="tl_help tl_tip">'.$GLOBALS['TL_LANG']['tl_style_sheet']['source'][1].'</p>' : '').'
  </div>
</div>

</div>

<div class="tl_formbody_submit">

<div class="tl_submit_container">
  <button type="submit" name="save" id="save" class="tl_submit" accesskey="s">'.$GLOBALS['TL_LANG']['tl_style_sheet']['import'][0].'</button>
</div>

</div>
</form>';
	}
public function importStyleSheet()
	{
		if (Input::get('key') != 'import')
		{
			return '';
		}

		/** @var FileUpload $objUploader */
		$objUploader = new FileUpload();

		// Import CSS
		if (Input::post('FORM_SUBMIT') == 'tl_style_sheet_import')
		{
			$arrUploaded = $objUploader->uploadTo('system/tmp');

			if (empty($arrUploaded))
			{
				Message::addError($GLOBALS['TL_LANG']['ERR']['all_fields']);
				$this->reload();
			}

			foreach ($arrUploaded as $strCssFile)
			{
				// Folders cannot be imported
				if (is_dir($this->strRootDir . '/' . $strCssFile))
				{
					Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['importFolder'], basename($strCssFile)));
					continue;
				}

				$objFile = new File($strCssFile);

				// Check the file extension
				if ($objFile->extension != 'css')
				{
					Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['filetype'], $objFile->extension));
					continue;
				}

				// Check the file name
				$strName = preg_replace('/\.css$/i', '', basename($strCssFile));
				$strName = $this->checkStyleSheetName($strName);

				// Create the new style sheet
				$objStyleSheet = $this->Database->prepare("INSERT INTO tl_style_sheet (pid, tstamp, name, media) VALUES (?, ?, ?, ?)")
												->execute(Input::get('id'), time(), $strName, array('all'));

				$insertId = $objStyleSheet->insertId;

				if (!is_numeric($insertId) || $insertId < 0)
				{
					throw new \Exception('Invalid insert ID');
				}

				// Read the file and remove carriage returns
				$strFile = $objFile->getContent();
				$strFile = str_replace("\r", '', $strFile);

				$arrTokens   = array();
				$strBuffer   = '';
				$intSorting  = 0;
				$strComment  = '';
				$strCategory = '';
				$intLength   = \strlen($strFile);

				// Tokenize
				for ($i=0; $i<$intLength; $i++)
				{
					$char = $strFile[$i];

					// Whitespace
					if ($char == '' || $char == "\n" || $char == "\t")
					{
						// Ignore
					}

					// Comment
					elseif ($char == '/')
					{
						if ($strFile[$i+1] == '*')
						{
							while ($i<$intLength)
							{
								$strBuffer .= $strFile[$i++];

								if ($strFile[$i] == '/' && $strFile[$i-1] == '*')
								{
									$arrTokens[] = array
									(
										'type'    => 'comment',
										'content' => $strBuffer . $strFile[$i]
									);

									$strBuffer = '';
									break;
								}
							}
						}
					}

					// At block
					elseif ($char == '@')
					{
						$intLevel = 0;
						$strSelector = '';

						while ($i<$intLength)
						{
							$strBuffer .= $strFile[$i++];

							if ($strFile[$i] == '{')
							{
								if (++$intLevel == 1)
								{
									++$i;
									$strSelector = $strBuffer;
									$strBuffer = '';
								}
							}
							elseif ($strFile[$i] == '}')
							{
								if (--$intLevel == 0)
								{
									$arrTokens[] = array
									(
										'type'     => 'atblock',
										'selector' => $strSelector,
										'content'  => $strBuffer
									);

									$strBuffer = '';
									break;
								}
							}
						}
					}

					// Regular block
					else
					{
						$strSelector = '';

						while ($i<$intLength)
						{
							$strBuffer .= $strFile[$i++];

							if ($strFile[$i] == '{')
							{
								++$i;
								$strSelector = $strBuffer;
								$strBuffer = '';
							}
							elseif ($strFile[$i] == '}')
							{
								$arrTokens[] = array
								(
									'type'     => 'block',
									'selector' => $strSelector,
									'content'  => $strBuffer
								);

								$strBuffer = '';
								break;
							}
						}
					}
				}

				foreach ($arrTokens as $arrToken)
				{
					// Comments
					if ($arrToken['type'] == 'comment')
					{
						// Category (comments start with /** and contain only one line)
						if (strncmp($arrToken['content'], '/**', 3) === 0 && substr_count($arrToken['content'], "\n") == 2)
						{
							$strCategory = trim(str_replace(array('/*', '*/', '*'), '', $arrToken['content']));
						}

						// Declaration comment
						elseif (strpos($arrToken['content'], "\n") === false)
						{
							$strComment = trim(str_replace(array('/*', '*/', '*'), '', $arrToken['content']));
						}
					}

					// At blocks like @media or @-webkit-keyframe
					elseif ($arrToken['type'] == 'atblock')
					{
						$arrSet = array
						(
							'pid'        => $insertId,
							'category'   => $strCategory,
							'comment'    => $strComment,
							'sorting'    => $intSorting += 128,
							'selector'   => trim($arrToken['selector']),
							'own'        => $arrToken['content']
						);

						$this->Database->prepare("INSERT INTO tl_style %s")->set($arrSet)->execute();
						$strComment = '';
					}

					// Regular blocks
					else
					{
						$arrDefinition = array
						(
							'pid'        => $insertId,
							'category'   => $strCategory,
							'comment'    => $strComment,
							'sorting'    => $intSorting += 128,
							'selector'   => trim($arrToken['selector']),
							'attributes' => $arrToken['content']
						);

						$this->createDefinition($arrDefinition);
						$strComment = '';
					}
				}

				// Write the style sheet
				$this->updateStyleSheet($insertId);

				// Notify the user
				if ($strName . '.css' != basename($strCssFile))
				{
					Message::addInfo(sprintf($GLOBALS['TL_LANG']['tl_style_sheet']['css_renamed'], basename($strCssFile), $strName . '.css'));
				}
				else
				{
					Message::addConfirmation(sprintf($GLOBALS['TL_LANG']['tl_style_sheet']['css_imported'], $strName . '.css'));
				}
			}

			// Redirect
			System::setCookie('BE_PAGE_OFFSET', 0, 0);
			$this->redirect(str_replace('&key=import', '', Environment::get('request')));
		}

		// Return form
		return Message::generate() . '
<div id="tl_buttons">
<a href="' .ampersand(str_replace('&key=import', '', Environment::get('request'))). '" class="header_back" title="' .StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['backBTTitle']). '" accesskey="b">' .$GLOBALS['TL_LANG']['MSC']['backBT']. '</a>
</div>
<form action="' .ampersand(Environment::get('request'), true). '" id="tl_style_sheet_import" class="tl_form tl_edit_form" method="post" enctype="multipart/form-data">
<div class="tl_formbody_edit">
<input type="hidden" name="FORM_SUBMIT" value="tl_style_sheet_import">
<input type="hidden" name="REQUEST_TOKEN" value="'.REQUEST_TOKEN.'">
<input type="hidden" name="MAX_FILE_SIZE" value="'.Config::get('maxFileSize').'">

<div class="tl_tbox">
  <div class="widget">
    <h3>'.$GLOBALS['TL_LANG']['tl_style_sheet']['source'][0].'</h3>'.$objUploader->generateMarkup().(isset($GLOBALS['TL_LANG']['tl_style_sheet']['source'][1]) ? '
    <p class="tl_help tl_tip">'.$GLOBALS['TL_LANG']['tl_style_sheet']['source'][1].'</p>' : '').'
  </div>
</div>

</div>

<div class="tl_formbody_submit">

<div class="tl_submit_container">
  <button type="submit" name="save" id="save" class="tl_submit" accesskey="s">'.$GLOBALS['TL_LANG']['tl_style_sheet']['import'][0].'</button>
</div>

</div>
</form>';
	}
Return a form to choose an existing style sheet and import it

@return string

@throws \Exception