Inspired by <http://code.seebz.net/p/minify-js/>
3685
public static function minify($input)
    {
        $output = '';
        $input = self::merge($input);

        $inQuotes        = array();
        $noSpacesAround  = '{}()[]<>|&!?:;,+-*/="\'';

        $input = preg_replace("`(\r\n|\r)`", "\n", $input);
        $inputs = str_split($input);
        $inputs_count = count($inputs);
        $prevChr = null;
        for ($i=0; $i<$inputs_count; $i++) {
            $chr = $inputs[$i];
            $nextChr = $i+1 < $inputs_count ? $inputs[$i+1] : null;

            switch ($chr) {
                case '/':
                    if (!count($inQuotes) && $nextChr == '*' && $inputs[$i+2] != '@') {
                        $i = 1 + strpos($input, '*/', $i);
                        continue 2;
                    } elseif (!count($inQuotes) && $nextChr == '/') {
                        if (strpos($input, "\n", $i)) {
                            $i = strpos($input, "\n", $i);
                        } else {
                            $i = strlen($input);
                        }
                        continue 2;
                    } elseif (!count($inQuotes)) {
                        $eolPos = strpos($input, "\n", $i);
                        if ($eolPos===false) {
                            $eolPos = $inputs_count;
                        }
                        $eol = substr($input, $i, $eolPos-$i);
                        if (!preg_match('`^(/.+(?<=\\\/)/(?!/)[gim]*)[^gim]`U', $eol, $m)) {
                            preg_match('`^(/.+(?<!/)/(?!/)[gim]*)[^gim]`U', $eol, $m);
                        }
                        // it's a RegExp
                        if (isset($m[1])) {
                            $output .= $m[1];
                            $i += strlen($m[1])-1;
                            continue 2;
                        }
                    }
                    break;

                case "'":
                case '"':
                    if ($prevChr != '\\' || ($prevChr == '\\' && $inputs[$i-2] == '\\')) {
                        if (end($inQuotes) == $chr) {
                            array_pop($inQuotes);
                        } elseif (!count($inQuotes)) {
                            $inQuotes[] = $chr;
                        }
                    }
                    break;

                case ' ':
                case "\t":
                case "\n":
                    if (!count($inQuotes)) {
                        if (strstr("{$noSpacesAround} \t\n", $nextChr)
                            || strstr("{$noSpacesAround} \t\n", $prevChr)
                        ) {
                            continue 2;
                        }
                        $chr = ' ';
                    }
                    break;

                default:
                    break;
            }

            $output .= $chr;
            $prevChr = $chr;
        }
        $output = trim($output);
        $output = str_replace(';}', '}', $output);

        return $output;
    }
415879
function() {
      var editor = $('<div></div>').addClass('kelmu-editor').css('z-order', '60000');
      editor.css('position', 'absolute').css('top', '10px').css('left', (container.children('div').last().outerWidth() + 100) + 'px');
      editor.css('border-radius', '5px').css('box-shadow', '3px 3px 5px #888888').css('background-color', '#FFFAE5');
      editor.css('padding', '10').css('cursor', 'move').draggable();
      editor.appendTo(container);

      editor.append($('<h3>Annotation editor</h3>').css('margin', '5px 0px'));

      // *********************************************************************************************************

      var statusView = $('<div></div>').text('Step 1, substep 1 of 1').addClass('kelmu-editor-status');
      statusView.appendTo(editor);

      // *********************************************************************************************************

      var generalButtons = $('<div></div>').addClass('kelmu-editor-general-buttons');
      generalButtons.appendTo(editor);

      $('<button></button>').text('Settings').addClass('btn').appendTo(generalButtons).click(function(e) {
        e.preventDefault();
        container.find('.kelmu-editor-pane').remove();
        editor.css('height', '');
        editor.css('width', '');
        window.kelmu.data[id].selectedElementNumber = -1;
        window.kelmu.data[id].previousSelectedElementNumber = -1;

        var settingsPanel = $('<div></div>').addClass('kelmu-editor-pane').appendTo(editor);

        addComponent('Length (ms)', settingsPanel, 'kelmu-editor-animation-length', window.kelmu.data[id].settings.animationLength, 'text');

        var helpShown = false;

        var pickerFunction = function() {

          if (!helpShown) {
            alert('Move the mouse cursor on top of the button and\nkeep moving the cursor until it gets a green border.');
            helpShown = true;
          }

          buttonPickerEnabled = true;
          element.find('a, button').css('border', '');
          if (!buttonPickerCreated) {
            createButtonPicker();
          }
        };

        addComponent('Begin button', settingsPanel, 'kelmu-editor-begin-button', window.kelmu.data[id].settings.begin, 'text');
        $('<br>').appendTo(settingsPanel);
        $('<button></button>').text('Point Begin button').appendTo(settingsPanel).click(function(e) {
          e.preventDefault();
          buttonToPick = 'begin';
          pickerFunction();
        });
        $('<br>').appendTo(settingsPanel);

        addComponent('Undo button', settingsPanel, 'kelmu-editor-undo-button', window.kelmu.data[id].settings.undo, 'text');
        $('<br>').appendTo(settingsPanel);
        $('<button></button>').text('Point Undo button').appendTo(settingsPanel).click(function(e) {
          e.preventDefault();
          buttonToPick = 'undo';
          pickerFunction();
        });
        $('<br>').appendTo(settingsPanel);

        addComponent('Step button', settingsPanel, 'kelmu-editor-step-button', window.kelmu.data[id].settings.step, 'text');
        $('<br>').appendTo(settingsPanel);
        $('<button></button>').text('Point Step button').appendTo(settingsPanel).click(function(e) {
          e.preventDefault();
          buttonToPick = 'step';
          pickerFunction();
        });
        $('<br>').appendTo(settingsPanel);

        addComponent('Redo button', settingsPanel, 'kelmu-editor-redo-button', window.kelmu.data[id].settings.redo, 'text');
        $('<br>').appendTo(settingsPanel);
        $('<button></button>').text('Point Redo button').appendTo(settingsPanel).click(function(e) {
          e.preventDefault();
          buttonToPick = 'redo';
          pickerFunction();
        });
        $('<br>').appendTo(settingsPanel);

        $('<button></button>').text('Save settings').appendTo($('<p></p>').appendTo(settingsPanel)).click(function(e) {
          e.preventDefault();

          window.kelmu.data[id].settings.animationLength = parseInt(settingsPanel.find('.kelmu-editor-animation-length').val(), 10);
          window.kelmu.data[id].settings.undo = settingsPanel.find('.kelmu-editor-undo-button').val();
          window.kelmu.data[id].settings.step = settingsPanel.find('.kelmu-editor-step-button').val();
          window.kelmu.data[id].settings.redo = settingsPanel.find('.kelmu-editor-redo-button').val();
          window.kelmu.data[id].settings.begin = settingsPanel.find('.kelmu-editor-begin-button').val();

          buttonPickerEnabled = false;

          window.kelmu.data[id].actions.update();
          updateView(true, true);
          window.kelmu.data[id].actions.initButtons();

          alert('Settings saved.');

        });

      });

      $('<button></button>').text('Import').addClass('btn').appendTo(generalButtons).click(function(e) {
        e.preventDefault();
        container.find('.kelmu-editor-pane').remove();
        editor.css('height', '');
        editor.css('width', '');
        window.kelmu.data[id].selectedElementNumber = -1;
        window.kelmu.data[id].previousSelectedElementNumber = -1;

        var importPanel = $('<div></div>').addClass('kelmu-editor-pane').appendTo(editor);
        var helpLabel = $('<p></p>').css('font-size', '11px').appendTo(importPanel);
        helpLabel.text('Copy and paste the definition below.');
        var textarea = $('<textarea></textarea>').appendTo(importPanel);
        textarea.css('font-size', '10px').css('min-height', '200px');
        $('<button></button>').text('Import').appendTo($('<p></p>').appendTo(importPanel)).click(function(e) {
          e.preventDefault();

          var text = textarea.val().trim();
          if (text.indexOf('kelmuCb(') >= 0) {
            text = text.substring(8, text.length - 1);
          }

          try {
            var parsed = JSON.parse(text);
            if (parsed[id] && parsed[id].settings && parsed[id].definitions) {
              window.kelmu.data[id].settings = parsed[id].settings;
              window.kelmu.data[id].definitions = parsed[id].definitions;
              alert('Definitions succesfully imported.');
              window.kelmu.data[id].actions.update();
              updateView(true, true);
              window.kelmu.data[id].actions.initButtons();
            } else {
              alert('Definition for ' + id + ' was not found or it is incomplete!');
            }
          } catch (error) {
            alert('Malformed definition!');
          }

        });
      });

      $('<button></button>').text('Export').addClass('btn').appendTo(generalButtons).click(function(e) {
        e.preventDefault();
        container.find('.kelmu-editor-pane').remove();
        editor.css('height', '');
        editor.css('width', '');
        window.kelmu.data[id].selectedElementNumber = -1;
        window.kelmu.data[id].previousSelectedElementNumber = -1;

        var exportedData = {};
        exportedData[id] = { definitions: window.kelmu.data[id].definitions, settings: window.kelmu.data[id].settings };

        var exportPanel = $('<div></div>').addClass('kelmu-editor-pane').appendTo(editor);
        var helpLabel = $('<p></p>').css('font-size', '11px').appendTo(exportPanel);
        helpLabel.text('Copy and paste the following definition in a file with extension .jsonp');
        var textarea = $('<textarea></textarea>').appendTo(exportPanel);
        textarea.css('font-size', '10px').css('min-height', '200px');
        textarea.val('kelmuCb(' + JSON.stringify(exportedData) + ')');
      });

      // *********************************************************************************************************

      var buttons = $('<div></div>').addClass('kelmu-editor-move-buttons');
      buttons.appendTo(editor);

      // Previous substep
      $('<button></button>').text('<').addClass('btn').appendTo(buttons).click(function(e) {
        e.preventDefault();
        if (window.kelmu.data[id].subStepNumber > 0) {
          window.kelmu.data[id].actions.setSubstep(window.kelmu.data[id].subStepNumber - 1);
        }
        window.kelmu.data[id].selectedElementNumber = -1;
        updateView(true, false);
      });

      // Next substep
      $('<button></button>').text('>').addClass('btn').appendTo(buttons).click(function(e) {
        e.preventDefault();
        if (window.kelmu.data[id].subStepNumber < (window.kelmu.data[id].definitions['step' + window.kelmu.data[id].stepNumber] || []).length - 1) {
          window.kelmu.data[id].actions.setSubstep(window.kelmu.data[id].subStepNumber + 1);
        }
        window.kelmu.data[id].selectedElementNumber = -1;
        updateView(true, false);
      });

      // New substep
      $('<button></button>').text('+Substep').addClass('btn').appendTo(buttons).click(function(e) {
        e.preventDefault();

        if (!window.kelmu.data[id].definitions['step' + window.kelmu.data[id].stepNumber]) {
          // Create new definition block for the substep
          window.kelmu.data[id].definitions['step' + window.kelmu.data[id].stepNumber] = [[]];
        }

        window.kelmu.data[id].definitions['step' + window.kelmu.data[id].stepNumber].splice(window.kelmu.data[id].subStepNumber + 1, 0, []);
        window.kelmu.data[id].actions.setSubstep(window.kelmu.data[id].subStepNumber + 1);
        window.kelmu.data[id].selectedElementNumber = -1;
        updateView(true, false);
        notifyModifications();
      });

      // Remove substep
      $('<button></button>').text('-Substep').addClass('btn').appendTo(buttons).click(function(e) {
        e.preventDefault();
        if ((window.kelmu.data[id].definitions['step' + window.kelmu.data[id].stepNumber] || []).length > 1) {
          if (confirm('Do you really want to remove this substep?')) {
            // Remove the definition block and make sure that the substep in the editor exists
            window.kelmu.data[id].definitions['step' + window.kelmu.data[id].stepNumber].splice(window.kelmu.data[id].subStepNumber, 1);
            window.kelmu.data[id].actions.setSubstep(Math.max(window.kelmu.data[id].subStepNumber - 1, 0));
          }

          window.kelmu.data[id].selectedElementNumber = -1;
          updateView(true, false);
          notifyModifications();
        } else {
          alert('You cannot remove the only substep!');
        }
      });

      // *********************************************************************************************************

      var newButtons = $('<div></div>').addClass('kelmu-editor-new-buttons');
      newButtons.appendTo(editor);

      var createNewButton = function(name, defaults, values) {
        return $('<button></button>').text(name).addClass('btn').appendTo(newButtons).click(function(e) {
          e.preventDefault();
          var data = window.kelmu.data[id];

          // Create new definition array for this step if it doesn't exist
          if (!data.definitions['step' + data.stepNumber]) {
            data.definitions['step' + data.stepNumber] = [[]];
          }

          data.definitions['step' + data.stepNumber][data.subStepNumber].push($.extend({}, values, defaults));
          data.selectedElementNumber = data.definitions['step' + data.stepNumber][data.subStepNumber].length - 1;
          data.actions.update();
          updateView(true, true);
          notifyModifications();
        });
      };

      // New text annotation
      createNewButton('+Text', window.kelmu.defaults.text, {
        text: 'New text',
        width: 400,
        height: 80,
        left: 10,
        top: 10
      }).appendTo(newButtons);

      // New arrow
      createNewButton('+Arrow', window.kelmu.defaults.arrow, {
        y1: 10,
        x1: 10,
        y2: 60,
        x2: 60
      }).appendTo(newButtons);

      // New line annotation
      createNewButton('+Line', window.kelmu.defaults.line, {
        y1: 10,
        x1: 10,
        y2: 60,
        x2: 60
      }).appendTo(newButtons);

      // New button
      createNewButton('+Button', window.kelmu.defaults.button, {}).appendTo(newButtons);

      // New action event
      createNewButton('+Action', window.kelmu.defaults.action, {}).appendTo(newButtons);

      // New sound
      createNewButton('+Sound', window.kelmu.defaults.sound, {}).click(function(e) {
        e.preventDefault();
        container.find('.kelmu-sound-control').show();
      }).appendTo(newButtons);

      // *********************************************************************************************************
      var componentPanel = $('<div></div>').addClass('kelmu-editor-components');
      componentPanel.appendTo(editor);

      // *********************************************************************************************************

      return editor;

    }
599856
function minify($files,$mime=NULL,$header=TRUE,$path=NULL) {
		$fw=Base::instance();
		if (is_string($files))
			$files=$fw->split($files);
		if (!$mime)
			$mime=$this->mime($files[0]);
		preg_match('/\w+$/',$files[0],$ext);
		$cache=Cache::instance();
		$dst='';
		if (!isset($path))
			$path=$fw->UI.';./';
		foreach ($fw->split($path,FALSE) as $dir)
			foreach ($files as $file)
				if (is_file($save=$fw->fixslashes($dir.$file)) &&
					is_bool(strpos($save,'../')) &&
					preg_match('/\.(css|js)$/i',$file)) {
					if ($fw->CACHE &&
						($cached=$cache->exists(
							$hash=$fw->hash($save).'.'.$ext[0],$data)) &&
						$cached[0]>filemtime($save))
						$dst.=$data;
					else {
						$data='';
						$src=$fw->read($save);
						for ($ptr=0,$len=strlen($src);$ptr<$len;) {
							if (preg_match('/^@import\h+url'.
								'\(\h*([\'"])((?!(?:https?:)?\/\/).+?)\1\h*\)[^;]*;/',
								substr($src,$ptr),$parts)) {
								$path=dirname($file);
								$data.=$this->minify(
									($path?($path.'/'):'').$parts[2],
									$mime,$header
								);
								$ptr+=strlen($parts[0]);
								continue;
							}
							if ($ext[0]=='css'&&preg_match('/^url\(([^\'"].*?[^\'"])\)/i',
									substr($src,$ptr),$parts)) {
								$data.=$parts[0];
								$ptr+=strlen($parts[0]);
								continue;
							}
							if ($src[$ptr]=='/') {
								if ($src[$ptr+1]=='*') {
									// Multiline comment
									$str=strstr(
										substr($src,$ptr+2),'*/',TRUE);
									$ptr+=strlen($str)+4;
								}
								elseif ($src[$ptr+1]=='/') {
									// Single-line comment
									$str=strstr(
										substr($src,$ptr+2),"\n",TRUE);
									$ptr+=(empty($str))?
										strlen(substr($src,$ptr)):strlen($str)+2;
								}
								else {
									// Presume it's a regex pattern
									$regex=TRUE;
									// Backtrack and validate
									for ($ofs=$ptr;$ofs;$ofs--) {
										// Pattern should be preceded by
										// open parenthesis, colon,
										// object property or operator
										if (preg_match(
											'/(return|[(:=!+\-*&|])$/',
											substr($src,0,$ofs))) {
											$data.='/';
											$ptr++;
											while ($ptr<$len) {
												$data.=$src[$ptr];
												$ptr++;
												if ($src[$ptr-1]=='\\') {
													$data.=$src[$ptr];
													$ptr++;
												}
												elseif ($src[$ptr-1]=='/')
													break;
											}
											break;
										}
										elseif (!ctype_space($src[$ofs-1])) {
											// Not a regex pattern
											$regex=FALSE;
											break;
										}
									}
									if (!$regex) {
										// Division operator
										$data.=$src[$ptr];
										$ptr++;
									}
								}
								continue;
							}
							if (in_array($src[$ptr],['\'','"'])) {
								$match=$src[$ptr];
								$data.=$match;
								$ptr++;
								// String literal
								while ($ptr<$len) {
									$data.=$src[$ptr];
									$ptr++;
									if ($src[$ptr-1]=='\\') {
										$data.=$src[$ptr];
										$ptr++;
									}
									elseif ($src[$ptr-1]==$match)
										break;
								}
								continue;
							}
							if (ctype_space($src[$ptr])) {
								if ($ptr+1<strlen($src) &&
									preg_match('/[\w'.($ext[0]=='css'?
										'#\.%+\-*()\[\]':'\$').']{2}|'.
										'[+\-]{2}/',
										substr($data,-1).$src[$ptr+1]) ||
									($ext[0]=='css' && $ptr+2<strlen($src) &&
									preg_match('/:\w/',substr($src,$ptr+1,2))))
									$data.=' ';
								$ptr++;
								continue;
							}
							$data.=$src[$ptr];
							$ptr++;
						}
						if ($ext[0]=='css')
							$data=str_replace(';}','}',$data);
						if ($fw->CACHE)
							$cache->set($hash,$data);
						$dst.=$data;
					}
				}
		if (PHP_SAPI!='cli' && $header)
			header('Content-Type: '.$mime.'; charset='.$fw->ENCODING);
		return $dst;
	}
769088
function rule(analyzer) {
	analyzer.setMetric('notMinified');

	/**
	 * A simple CSS minification detector
	 */
	function isMinified(css) {
		// analyze the first 1024 characters
		css = css.trim().substring(0, 1024);

		// there should be no newline in minified file
		return /\n/.test(css) === false;
	}

	analyzer.on('css', function(css) {
		analyzer.setMetric('notMinified', isMinified(css) ? 0 : 1);
	});
}
1101143
function (next) {

									minify(
										outputCommonsJsFile,
										_.extend({optimize: true},uglifyOptions),
										function(err){
											if ( err ){
												return next(err);
											}
											return next();
										}
									);

								}
777722
function automagic(parentNode, childNode, options, callback) {
    Embedo.log('info', 'automagic', parentNode, childNode, options);
    options = options || {};
    callback = callback || function () {};

    if (!Embedo.utils.validateElement(parentNode) || !Embedo.utils.validateElement(childNode)) {
      return callback(new Error('HTMLElement does not exist in DOM.'));
    }

    Embedo.utils.watcher(
      options.id || Embedo.utils.uuid(),
      function () {
        var parent = {
          width: options.width || Embedo.utils.compute(parentNode, 'width'),
          height: options.height || Embedo.utils.compute(parentNode, 'height')
        };
        var child = {
          width: Embedo.utils.compute(childNode, 'width'),
          height: Embedo.utils.compute(childNode, 'height')
        };

        if (options.strict) {
          return callback(null, {
            width: parent.width,
            height: parent.height
          });
        }

        // Odd case when requested height is beyond limit of third party
        // Only apply when fixed width and heights are provided
        if (options.width && options.height) {
          var isOverflowing = child.width > parent.width || child.height > parent.height;

          if (options.width) {
            childNode.style.width = options.width + 'px';
          }

          if (options.height) {
            childNode.style.height = options.height + 'px';
          }

          if (isOverflowing) {
            var scale = Math.min(parent.width / child.width, parent.height / child.height);
            Embedo.utils.transform(childNode, 'scale(' + scale + ')');
          }
        }

        callback(null, {
          width: parent.width,
          height: parent.height
        });
      },
      500
    );
  }
331018
public static function minifyJavaScript($script, &$error = '') {
		require_once(PATH_typo3 . 'contrib/jsmin/jsmin.php');
		try {
			$error = '';
			$script = trim(JSMin::minify(str_replace(CR, '', $script)));
		}
		catch (JSMinException $e) {
			$error = 'Error while minifying JavaScript: ' . $e->getMessage();
			self::devLog($error, 't3lib_div', 2,
				array('JavaScript' => $script, 'Stack trace' => $e->getTrace()));
		}
		return $script;
	}
605026
function ImageForm() {
		Requirements::javascript(THIRDPARTY_DIR . "/behaviour.js");
		Requirements::javascript(EXTERNALCONTENT . "/javascript/external_tiny_mce_improvements.js");
		Requirements::css('cms/css/TinyMCEImageEnhancement.css');
		Requirements::javascript('cms/javascript/TinyMCEImageEnhancement.js');
		Requirements::javascript(THIRDPARTY_DIR . '/SWFUpload/SWFUpload.js');
		Requirements::javascript(CMS_DIR . '/javascript/Upload.js');

		$form = new Form(
			$this->controller,
			"{$this->name}/ImageForm",
			new FieldSet(
				new LiteralField('Heading', '<h2><img src="cms/images/closeicon.gif" alt="' . _t('HtmlEditorField.CLOSE', 'close') . '" title="' . _t('HtmlEditorField.CLOSE', 'close') . '" />' . _t('HtmlEditorField.IMAGE', 'Image') . '</h2>'),
				new TreeDropdownField('FolderID', _t('HtmlEditorField.FOLDER', 'Folder'), 'Folder'),
				new LiteralField('AddFolderOrUpload',
					'<div style="clear:both;"></div><div id="AddFolderGroup" style="display: none">
						<a style="" href="#" id="AddFolder" class="link">' . _t('HtmlEditorField.CREATEFOLDER','Create Folder') . '</a>
						<input style="display: none; margin-left: 2px; width: 94px;" id="NewFolderName" class="addFolder" type="text">
						<a style="display: none;" href="#" id="FolderOk" class="link addFolder">' . _t('HtmlEditorField.OK','Ok') . '</a>
						<a style="display: none;" href="#" id="FolderCancel" class="link addFolder">' . _t('HtmlEditorField.FOLDERCANCEL','Cancel') . '</a>
					</div>
					<div id="PipeSeparator" style="display: none">|</div>
					<div id="UploadGroup" class="group" style="display: none; margin-top: 2px;">
						<a href="#" id="UploadFiles" class="link">' . _t('HtmlEditorField.UPLOAD','Upload') . '</a>
					</div>'
				),
				new TextField('getimagesSearch', _t('HtmlEditorField.SEARCHFILENAME', 'Search by file name')),
				new ThumbnailStripField('FolderImages', 'FolderID', 'getimages'),
				new TextField('AltText', _t('HtmlEditorField.IMAGEALTTEXT', 'Alternative text (alt) - shown if image cannot be displayed'), '', 80),
				new TextField('ImageTitle', _t('HtmlEditorField.IMAGETITLE', 'Title text (tooltip) - for additional information about the image')),
				new TextField('CaptionText', _t('HtmlEditorField.CAPTIONTEXT', 'Caption text')),
				new DropdownField(
					'CSSClass',
					_t('HtmlEditorField.CSSCLASS', 'Alignment / style'),
					array(
						'left' => _t('HtmlEditorField.CSSCLASSLEFT', 'On the left, with text wrapping around.'),
						'leftAlone' => _t('HtmlEditorField.CSSCLASSLEFTALONE', 'On the left, on its own.'),
						'right' => _t('HtmlEditorField.CSSCLASSRIGHT', 'On the right, with text wrapping around.'),
						'center' => _t('HtmlEditorField.CSSCLASSCENTER', 'Centered, on its own.'),
					)
				),
				new FieldGroup(_t('HtmlEditorField.IMAGEDIMENSIONS', 'Dimensions'),
					new TextField('Width', _t('HtmlEditorField.IMAGEWIDTHPX', 'Width'), 100),
					new TextField('Height', " x " . _t('HtmlEditorField.IMAGEHEIGHTPX', 'Height'), 100)
				)
			),
			new FieldSet(
				new FormAction('insertimage', _t('HtmlEditorField.BUTTONINSERTIMAGE', 'Insert image'))
			)
		);

		$form->disableSecurityToken();
		$form->loadDataFrom($this);

		return $form;
	}
1274764
function IncludeMiddleware(options) {
  var self = this;

  // Initialize with passed in configuration or empty arrays.
  self.globalStyles = (options && options.globalStyles) ? options.globalStyles : [];
  self.globalScripts = (options && options.globalScripts) ? options.globalScripts : [];
  self.sectionDefinition = (options && options.sectionDefinition) ? options.sectionDefinition : [];
  self.pageDefinition = (options && options.pageDefinition) ? options.pageDefinition : [];

  // Initialize minified files.
  self.minified = (options && options.minified) ? options.minified : false;
  self.dirName = (options && options.dirName) ? (options.dirName) : null;
  
  // Objects that hold cached css and js files both full and minified.
  self.scriptFiles = {};
  self.styleFiles = {};

  // This looks really ugly. But the point here is to read all the css files that
  // are defined anywhere into memory, minify them in order to get them ready to 
  // go for actual requests.
  if (self.minified && self.dirName) {

    // Get a listing of folders underneath the directory given.
    self.dirs = getFoldersRecursive(self.dirName);

    // Loop through defined global styles.
    self.globalStyles.forEach(function(element, index, array) {
      var source = minify.readAndMinifyCSS(self.dirName + '/' + self.globalStyles[index], self.dirs);
      self.styleFiles[self.globalStyles[index]] = source;
    });

    // Loop through defined global scripts.
    self.globalScripts.forEach(function(element, index, array) {
      var source = minify.readAndMinifyJS(self.dirName + '/' + self.globalScripts[index]);
      self.scriptFiles[self.globalScripts[index]] = source;
    });

    // Loop through defined section definitions.
    self.sectionDefinition.forEach(function(sectionElement, sectionIndex, sectionArray) {

      // styles
      self.sectionDefinition[sectionIndex].styles.forEach(function(el, i, arr) {
        var source = minify.readAndMinifyCSS(self.dirName + '/' + self.sectionDefinition[sectionIndex].styles[i], self.dirs);
        self.styleFiles[self.sectionDefinition[sectionIndex].styles[i]] = source;
      });

      // scripts
      self.sectionDefinition[sectionIndex].scripts.forEach(function(el, i, arr) {
        var source = minify.readAndMinifyJS(self.dirName + '/' + self.sectionDefinition[sectionIndex].scripts[i]);
        self.scriptFiles[self.sectionDefinition[sectionIndex].scripts[i]] = source;
      });

    });

    // Loop through defined page definitions.
    self.pageDefinition.forEach(function(pageElement, pageIndex, pageArray) {

      // styles
      self.pageDefinition[pageIndex].styles.forEach(function(el, i, arr) {
        var source = minify.readAndMinifyCSS(self.dirName + '/' + self.pageDefinition[pageIndex].styles[i], self.dirs);
        self.styleFiles[self.pageDefinition[pageIndex].styles[i]] = source;
      });

      // scripts
      self.pageDefinition[pageIndex].scripts.forEach(function(el, i, arr) {
        var source = minify.readAndMinifyJS(self.dirName + '/' + self.pageDefinition[pageIndex].scripts[i]);
        self.scriptFiles[self.pageDefinition[pageIndex].scripts[i]] = source;
      });

    });

  }

  /**
   * Express middleware function that gets imports for the current 
   * page and attaches them to `res.locals` object, then calls next(). 
   */
  self.mwFn = function(req, res, next) {
    var imports = self.getImports(url.parse(req.url).pathname);
    res.locals.scripts = imports.scripts;
    res.locals.styles = imports.styles;
    next();
  };

  /**
   * 
   */
  self.mwFnMinified = function(req, res, next) {
    var imports = self.getImports(url.parse(req.url).pathname);
    res.locals.scripts = imports.scripts;
    res.locals.styles = imports.styles;

    res.locals.cssSource = '';
    res.locals.cssSourceMin = '';
    res.locals.jsSource = '';
    res.locals.jsSourceMin = '';

    res.locals.styles.forEach(function(el, index, arr) {
      res.locals.cssSource += self.styleFiles[res.locals.styles[index]].full;
      res.locals.cssSourceMin += self.styleFiles[res.locals.styles[index]].min;
    });

    res.locals.scripts.forEach(function(el, index, arr) {
      res.locals.jsSource += self.scriptFiles[res.locals.scripts[index]].full;
      res.locals.jsSourceMin += self.scriptFiles[res.locals.scripts[index]].min;
    });

    next();
  };

  /**
   * Takes in a url and finds a section configuration from what was 
   * passed in earlier. At this time it can only return 1 section 
   * configuration, or null if none are found.
   * 
   * // TODO: ability to return multiple section configs? 
   */
  self.getSectionConfig = function(url) {
    if (!url) return null;

    for (var i = 0; i < self.sectionDefinition.length; i++) {
      if (url.indexOf(self.sectionDefinition[i].url) > -1) {
        return self.sectionDefinition[i];
      }
    }
    return null;
  };

  /**
   * Breaks down the url and each of the page definitions that were
   * passed in, and determines if there's a match. This function can 
   * currently only return one page config. 
   * 
   * TODO: ability to return multiple page configs?
   */
  self.getPageConfig = function(url) {
      if (!url) return null;
      var urlParts = url.split("/");

      for (var i = 0; i < self.pageDefinition.length; i++) {
          var itPageParts = self.pageDefinition[i].url.split("/");

          if (urlParts.length === itPageParts.length) {
              var match = true;

              for (var j = 0; j < itPageParts.length; j++) {
                  if (itPageParts[j] === ":") continue;
                  if (itPageParts[j] !== urlParts[j]) match = false;
              }

              if (match) {
                return self.pageDefinition[i];
              }
          }
      }
      return null;
  };

  /**
   * Top-level function that uses `getSectionConfig` and `getPageConfig`.
   * This function combines all of the imports that should go with the
   * page including each of the three layers (global, section and page). 
   */
  self.getImports = function(url) {
    var styles = self.globalStyles;
    var scripts = self.globalScripts;

    // Find section, append styles and scripts if section found.
    var sectionConfig = self.getSectionConfig(url);
    if (sectionConfig) {
      if (sectionConfig.styles && Array.isArray(sectionConfig.styles))
        styles = styles.concat(sectionConfig.styles);
      if (sectionConfig.scripts && Array.isArray(sectionConfig.scripts))
        scripts = scripts.concat(sectionConfig.scripts);
    }

    // Find page, append styles and scripts if page found.
    var pageConfig = self.getPageConfig(url);
    if (pageConfig) {
      if (pageConfig.styles && Array.isArray(pageConfig.styles))
        styles = styles.concat(pageConfig.styles);
      if (pageConfig.scripts && Array.isArray(pageConfig.scripts))
        scripts = scripts.concat(pageConfig.scripts);
    }

    // Return the entire list of styles, scripts and configs.
    return {
      styles: styles,
      scripts: scripts,
      pageConfig: pageConfig,
      sectionConfig: sectionConfig
    };
  };

  // Return myself.
  return self;
}
1043356
public function minifyHTML(){
        $buffer = $this->response->getContent();
        if(strpos($buffer,'<pre>') !== false)
        {
            $replace = array(
                '/<!--[^\[](.*?)[^\]]-->/s' => '',
                "/<\?php/"                  => '<?php ',
                "/\r/"                      => '',
                "/>\n</"                    => '><',
                "/>\s+\n</"    				=> '><',
                "/>\n\s+</"					=> '><',
            );
        }
        else
        {
            $replace = array(
                '/<!--[^\[](.*?)[^\]]-->/s' => '',
                "/<\?php/"                  => '<?php ',
                "/\n([\S])/"                => '$1',
                "/\r/"                      => '',
                "/\n/"                      => '',
                "/\t/"                      => '',
                "/ +/"                      => ' ',
                '#^\s*//.+$#m'              => '', // remove single comment in JS
            );
        }
        $buffer = preg_replace(array_keys($replace), array_values($replace), $buffer);
        $this->response->setContent($buffer);
    }
1110950
function minifyHtml($) {
  $('style:not([type]), style[type="text/css"]').each(function() {
    var el      = $(this);
    el.text( new cleancss({noAdvanced: true}).minify(el.text()) )
  });
  $('*').contents().filter(function(_, node) {
    if (node.type === 'comment'){
      return true;
    } else if (node.type === 'text') {
      // return true if the node is only whitespace
      return !((/\S/).test(node.data));
    }
  }).remove();
}
622405
function createHTML5Shims() {
  // localstorage dummy (does nothing)
  if (typeof window.localStorage == 'undefined') {
    window.localStorage = {
      getItem : function() {
        return null;
      },
      setItem : function() {
      },
      clear : function() {
      },
      removeItem : function() {
      },
      length : 0,
      key : function() {
        return null;
      }
    };
  }
}
1344667
private function minify($filename = false, $files, $yuicompressor, $baseDir, $width = null)
    {
        $content = '';
        if ($width === null) {
            $extra = '';
        } else {
            $extra = '--line-break '.intval($width);
        }

        foreach ($files as $file) {
            if (file_exists($baseDir.$file)) {
                $result = exec("java -jar $yuicompressor $extra $baseDir$file ");
                $content .= (defined('_MODE') && _MODE == 1 ? "/* $file */" : '')."$result\n";
                echo "\n    Add: $file";
            } else {
                echo "\n    Err: $file - not found.";
            }
        }
            //return minyfied data
        if ($filename === false) {
            return $content;
        }

            echo "\n Saving: $filename\n";
            file_put_contents($baseDir.$filename, $content);
            echo "\n Minified ..\n";
    }
1141934
function prettify ( fnBody ) {
  	var lines = fnBody
  		.replace( /^\t+/gm, function ( tabs ) { return tabs.split( '\t' ).join( '  ' ); } )
  		.split( '\n' );

  	var minIndent = lines.length < 2 ? 0 :
  		lines.slice( 1 ).reduce( function ( prev, line ) {
  			return Math.min( prev, /^\s*/.exec( line )[0].length );
  		}, Infinity );

  	return lines.map( function ( line, i ) {
  		return '    ' + ( i ? line.substring( minIndent ) : line );
  	}).join( '\n' );
  }
1002295
function extend(prototype, utils) {
  const { debug, strong, warn } = utils.cnsl;
  const { sourceMapCommentStrip } = utils.string;

  /**
   * Compress file contents
   * @param {Object} buildOptions
   *  - {Boolean} bootstrap
   *  - {Boolean} boilerplate
   *  - {Boolean} browser
   *  - {Boolean} bundle
   *  - {Boolean} compress
   *  - {Array} ignoredFiles
   *  - {Boolean} helpers
   *  - {Boolean} watchOnly
   * @param {Function} fn(err)
   */
  prototype.compress = function compress(buildOptions, fn) {
    const options = Object.assign(
      this.hasMaps
        ? {
            sourceMap: {
              content: this.map.toJSON(),
              url: this.mapUrl
            }
          }
        : {},
      DEFAULT_OPTIONS,
      this.options.pluginOptions.uglify || {}
    );
    const minified = minify(this.content, options);

    if ('error' in minified) {
      fn(minified.error);
      return;
    }

    debug(`compress: ${strong(this.relpath)}`, 4);
    this.setContent(sourceMapCommentStrip(minified.code));
    if (minified.map) {
      this.setMap(minified.map);
    }
    fn();
  };
}
899167
def minify(compiled):
    
    compiled = compiled.strip()
    if compiled:
        out = []
        for line in compiled.splitlines():
            line = line.split("#", 1)[0].rstrip()
            if line:
                ind = 0
                while line.startswith(" "):
                    line = line[1:]
                    ind += 1
                internal_assert(ind % tabideal == 0, "invalid indentation in", line)
                out.append(" " * (ind // tabideal) + line)
        compiled = "\n".join(out) + "\n"
    return compiled
146242
function minifyCodeEsprima(code,callback,description) {
    if ((typeof esprima == "undefined") ||
        (typeof esmangle == "undefined") ||
        (typeof escodegen == "undefined")) {
      console.warn("esprima/esmangle/escodegen not defined - not minifying")
      return callback(code);
    }

    var code, syntax, option, str, before, after;
    var options = {};
    options["mangle"] = Espruino.Config.MINIFICATION_Mangle;
    options["remove-unreachable-branch"] = Espruino.Config.MINIFICATION_Unreachable;
    options["remove-unused-vars"] = Espruino.Config.MINIFICATION_Unused;
    options["fold-constant"] = Espruino.Config.MINIFICATION_Literal;
    options["eliminate-dead-code"] = Espruino.Config.MINIFICATION_DeadCode;
    option = {format: {indent: {style: ''},quotes: 'auto',compact: true}};
    str = '';
    try {
        before = code.length;
        syntax = esprima.parse(code, { raw: true, loc: true });
        syntax = obfuscate(syntax,options);
        code = escodegen.generate(syntax, option);
        after = code.length;
        if (before > after) {
          Espruino.Core.Notifications.info('No errors'+description+'. Minified ' + before + ' bytes to ' + after + ' bytes.');
        } else {
          Espruino.Core.Notifications.info('Can not minify further'+description+', code is already optimized.');
        }
        callback(code);
    } catch (e) {
      Espruino.Core.Notifications.error(e.toString()+description);
      console.error(e.stack);
      callback(code);
    } finally { }
  }