diff --git a/core/vendor/codemirror/mode/css.js b/core/vendor/codemirror/mode/css.js
new file mode 100644
index 00000000..05742c5c
--- /dev/null
+++ b/core/vendor/codemirror/mode/css.js
@@ -0,0 +1,831 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("../../lib/codemirror"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+"use strict";
+
+CodeMirror.defineMode("css", function(config, parserConfig) {
+ var inline = parserConfig.inline
+ if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css");
+
+ var indentUnit = config.indentUnit,
+ tokenHooks = parserConfig.tokenHooks,
+ documentTypes = parserConfig.documentTypes || {},
+ mediaTypes = parserConfig.mediaTypes || {},
+ mediaFeatures = parserConfig.mediaFeatures || {},
+ mediaValueKeywords = parserConfig.mediaValueKeywords || {},
+ propertyKeywords = parserConfig.propertyKeywords || {},
+ nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {},
+ fontProperties = parserConfig.fontProperties || {},
+ counterDescriptors = parserConfig.counterDescriptors || {},
+ colorKeywords = parserConfig.colorKeywords || {},
+ valueKeywords = parserConfig.valueKeywords || {},
+ allowNested = parserConfig.allowNested,
+ lineComment = parserConfig.lineComment,
+ supportsAtComponent = parserConfig.supportsAtComponent === true;
+
+ var type, override;
+ function ret(style, tp) { type = tp; return style; }
+
+ // Tokenizers
+
+ function tokenBase(stream, state) {
+ var ch = stream.next();
+ if (tokenHooks[ch]) {
+ var result = tokenHooks[ch](stream, state);
+ if (result !== false) return result;
+ }
+ if (ch == "@") {
+ stream.eatWhile(/[\w\\\-]/);
+ return ret("def", stream.current());
+ } else if (ch == "=" || (ch == "~" || ch == "|") && stream.eat("=")) {
+ return ret(null, "compare");
+ } else if (ch == "\"" || ch == "'") {
+ state.tokenize = tokenString(ch);
+ return state.tokenize(stream, state);
+ } else if (ch == "#") {
+ stream.eatWhile(/[\w\\\-]/);
+ return ret("atom", "hash");
+ } else if (ch == "!") {
+ stream.match(/^\s*\w*/);
+ return ret("keyword", "important");
+ } else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) {
+ stream.eatWhile(/[\w.%]/);
+ return ret("number", "unit");
+ } else if (ch === "-") {
+ if (/[\d.]/.test(stream.peek())) {
+ stream.eatWhile(/[\w.%]/);
+ return ret("number", "unit");
+ } else if (stream.match(/^-[\w\\\-]*/)) {
+ stream.eatWhile(/[\w\\\-]/);
+ if (stream.match(/^\s*:/, false))
+ return ret("variable-2", "variable-definition");
+ return ret("variable-2", "variable");
+ } else if (stream.match(/^\w+-/)) {
+ return ret("meta", "meta");
+ }
+ } else if (/[,+>*\/]/.test(ch)) {
+ return ret(null, "select-op");
+ } else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) {
+ return ret("qualifier", "qualifier");
+ } else if (/[:;{}\[\]\(\)]/.test(ch)) {
+ return ret(null, ch);
+ } else if (stream.match(/[\w-.]+(?=\()/)) {
+ if (/^(url(-prefix)?|domain|regexp)$/.test(stream.current().toLowerCase())) {
+ state.tokenize = tokenParenthesized;
+ }
+ return ret("variable callee", "variable");
+ } else if (/[\w\\\-]/.test(ch)) {
+ stream.eatWhile(/[\w\\\-]/);
+ return ret("property", "word");
+ } else {
+ return ret(null, null);
+ }
+ }
+
+ function tokenString(quote) {
+ return function(stream, state) {
+ var escaped = false, ch;
+ while ((ch = stream.next()) != null) {
+ if (ch == quote && !escaped) {
+ if (quote == ")") stream.backUp(1);
+ break;
+ }
+ escaped = !escaped && ch == "\\";
+ }
+ if (ch == quote || !escaped && quote != ")") state.tokenize = null;
+ return ret("string", "string");
+ };
+ }
+
+ function tokenParenthesized(stream, state) {
+ stream.next(); // Must be '('
+ if (!stream.match(/\s*[\"\')]/, false))
+ state.tokenize = tokenString(")");
+ else
+ state.tokenize = null;
+ return ret(null, "(");
+ }
+
+ // Context management
+
+ function Context(type, indent, prev) {
+ this.type = type;
+ this.indent = indent;
+ this.prev = prev;
+ }
+
+ function pushContext(state, stream, type, indent) {
+ state.context = new Context(type, stream.indentation() + (indent === false ? 0 : indentUnit), state.context);
+ return type;
+ }
+
+ function popContext(state) {
+ if (state.context.prev)
+ state.context = state.context.prev;
+ return state.context.type;
+ }
+
+ function pass(type, stream, state) {
+ return states[state.context.type](type, stream, state);
+ }
+ function popAndPass(type, stream, state, n) {
+ for (var i = n || 1; i > 0; i--)
+ state.context = state.context.prev;
+ return pass(type, stream, state);
+ }
+
+ // Parser
+
+ function wordAsValue(stream) {
+ var word = stream.current().toLowerCase();
+ if (valueKeywords.hasOwnProperty(word))
+ override = "atom";
+ else if (colorKeywords.hasOwnProperty(word))
+ override = "keyword";
+ else
+ override = "variable";
+ }
+
+ var states = {};
+
+ states.top = function(type, stream, state) {
+ if (type == "{") {
+ return pushContext(state, stream, "block");
+ } else if (type == "}" && state.context.prev) {
+ return popContext(state);
+ } else if (supportsAtComponent && /@component/i.test(type)) {
+ return pushContext(state, stream, "atComponentBlock");
+ } else if (/^@(-moz-)?document$/i.test(type)) {
+ return pushContext(state, stream, "documentTypes");
+ } else if (/^@(media|supports|(-moz-)?document|import)$/i.test(type)) {
+ return pushContext(state, stream, "atBlock");
+ } else if (/^@(font-face|counter-style)/i.test(type)) {
+ state.stateArg = type;
+ return "restricted_atBlock_before";
+ } else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/i.test(type)) {
+ return "keyframes";
+ } else if (type && type.charAt(0) == "@") {
+ return pushContext(state, stream, "at");
+ } else if (type == "hash") {
+ override = "builtin";
+ } else if (type == "word") {
+ override = "tag";
+ } else if (type == "variable-definition") {
+ return "maybeprop";
+ } else if (type == "interpolation") {
+ return pushContext(state, stream, "interpolation");
+ } else if (type == ":") {
+ return "pseudo";
+ } else if (allowNested && type == "(") {
+ return pushContext(state, stream, "parens");
+ }
+ return state.context.type;
+ };
+
+ states.block = function(type, stream, state) {
+ if (type == "word") {
+ var word = stream.current().toLowerCase();
+ if (propertyKeywords.hasOwnProperty(word)) {
+ override = "property";
+ return "maybeprop";
+ } else if (nonStandardPropertyKeywords.hasOwnProperty(word)) {
+ override = "string-2";
+ return "maybeprop";
+ } else if (allowNested) {
+ override = stream.match(/^\s*:(?:\s|$)/, false) ? "property" : "tag";
+ return "block";
+ } else {
+ override += " error";
+ return "maybeprop";
+ }
+ } else if (type == "meta") {
+ return "block";
+ } else if (!allowNested && (type == "hash" || type == "qualifier")) {
+ override = "error";
+ return "block";
+ } else {
+ return states.top(type, stream, state);
+ }
+ };
+
+ states.maybeprop = function(type, stream, state) {
+ if (type == ":") return pushContext(state, stream, "prop");
+ return pass(type, stream, state);
+ };
+
+ states.prop = function(type, stream, state) {
+ if (type == ";") return popContext(state);
+ if (type == "{" && allowNested) return pushContext(state, stream, "propBlock");
+ if (type == "}" || type == "{") return popAndPass(type, stream, state);
+ if (type == "(") return pushContext(state, stream, "parens");
+
+ if (type == "hash" && !/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())) {
+ override += " error";
+ } else if (type == "word") {
+ wordAsValue(stream);
+ } else if (type == "interpolation") {
+ return pushContext(state, stream, "interpolation");
+ }
+ return "prop";
+ };
+
+ states.propBlock = function(type, _stream, state) {
+ if (type == "}") return popContext(state);
+ if (type == "word") { override = "property"; return "maybeprop"; }
+ return state.context.type;
+ };
+
+ states.parens = function(type, stream, state) {
+ if (type == "{" || type == "}") return popAndPass(type, stream, state);
+ if (type == ")") return popContext(state);
+ if (type == "(") return pushContext(state, stream, "parens");
+ if (type == "interpolation") return pushContext(state, stream, "interpolation");
+ if (type == "word") wordAsValue(stream);
+ return "parens";
+ };
+
+ states.pseudo = function(type, stream, state) {
+ if (type == "meta") return "pseudo";
+
+ if (type == "word") {
+ override = "variable-3";
+ return state.context.type;
+ }
+ return pass(type, stream, state);
+ };
+
+ states.documentTypes = function(type, stream, state) {
+ if (type == "word" && documentTypes.hasOwnProperty(stream.current())) {
+ override = "tag";
+ return state.context.type;
+ } else {
+ return states.atBlock(type, stream, state);
+ }
+ };
+
+ states.atBlock = function(type, stream, state) {
+ if (type == "(") return pushContext(state, stream, "atBlock_parens");
+ if (type == "}" || type == ";") return popAndPass(type, stream, state);
+ if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top");
+
+ if (type == "interpolation") return pushContext(state, stream, "interpolation");
+
+ if (type == "word") {
+ var word = stream.current().toLowerCase();
+ if (word == "only" || word == "not" || word == "and" || word == "or")
+ override = "keyword";
+ else if (mediaTypes.hasOwnProperty(word))
+ override = "attribute";
+ else if (mediaFeatures.hasOwnProperty(word))
+ override = "property";
+ else if (mediaValueKeywords.hasOwnProperty(word))
+ override = "keyword";
+ else if (propertyKeywords.hasOwnProperty(word))
+ override = "property";
+ else if (nonStandardPropertyKeywords.hasOwnProperty(word))
+ override = "string-2";
+ else if (valueKeywords.hasOwnProperty(word))
+ override = "atom";
+ else if (colorKeywords.hasOwnProperty(word))
+ override = "keyword";
+ else
+ override = "error";
+ }
+ return state.context.type;
+ };
+
+ states.atComponentBlock = function(type, stream, state) {
+ if (type == "}")
+ return popAndPass(type, stream, state);
+ if (type == "{")
+ return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top", false);
+ if (type == "word")
+ override = "error";
+ return state.context.type;
+ };
+
+ states.atBlock_parens = function(type, stream, state) {
+ if (type == ")") return popContext(state);
+ if (type == "{" || type == "}") return popAndPass(type, stream, state, 2);
+ return states.atBlock(type, stream, state);
+ };
+
+ states.restricted_atBlock_before = function(type, stream, state) {
+ if (type == "{")
+ return pushContext(state, stream, "restricted_atBlock");
+ if (type == "word" && state.stateArg == "@counter-style") {
+ override = "variable";
+ return "restricted_atBlock_before";
+ }
+ return pass(type, stream, state);
+ };
+
+ states.restricted_atBlock = function(type, stream, state) {
+ if (type == "}") {
+ state.stateArg = null;
+ return popContext(state);
+ }
+ if (type == "word") {
+ if ((state.stateArg == "@font-face" && !fontProperties.hasOwnProperty(stream.current().toLowerCase())) ||
+ (state.stateArg == "@counter-style" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase())))
+ override = "error";
+ else
+ override = "property";
+ return "maybeprop";
+ }
+ return "restricted_atBlock";
+ };
+
+ states.keyframes = function(type, stream, state) {
+ if (type == "word") { override = "variable"; return "keyframes"; }
+ if (type == "{") return pushContext(state, stream, "top");
+ return pass(type, stream, state);
+ };
+
+ states.at = function(type, stream, state) {
+ if (type == ";") return popContext(state);
+ if (type == "{" || type == "}") return popAndPass(type, stream, state);
+ if (type == "word") override = "tag";
+ else if (type == "hash") override = "builtin";
+ return "at";
+ };
+
+ states.interpolation = function(type, stream, state) {
+ if (type == "}") return popContext(state);
+ if (type == "{" || type == ";") return popAndPass(type, stream, state);
+ if (type == "word") override = "variable";
+ else if (type != "variable" && type != "(" && type != ")") override = "error";
+ return "interpolation";
+ };
+
+ return {
+ startState: function(base) {
+ return {tokenize: null,
+ state: inline ? "block" : "top",
+ stateArg: null,
+ context: new Context(inline ? "block" : "top", base || 0, null)};
+ },
+
+ token: function(stream, state) {
+ if (!state.tokenize && stream.eatSpace()) return null;
+ var style = (state.tokenize || tokenBase)(stream, state);
+ if (style && typeof style == "object") {
+ type = style[1];
+ style = style[0];
+ }
+ override = style;
+ if (type != "comment")
+ state.state = states[state.state](type, stream, state);
+ return override;
+ },
+
+ indent: function(state, textAfter) {
+ var cx = state.context, ch = textAfter && textAfter.charAt(0);
+ var indent = cx.indent;
+ if (cx.type == "prop" && (ch == "}" || ch == ")")) cx = cx.prev;
+ if (cx.prev) {
+ if (ch == "}" && (cx.type == "block" || cx.type == "top" ||
+ cx.type == "interpolation" || cx.type == "restricted_atBlock")) {
+ // Resume indentation from parent context.
+ cx = cx.prev;
+ indent = cx.indent;
+ } else if (ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") ||
+ ch == "{" && (cx.type == "at" || cx.type == "atBlock")) {
+ // Dedent relative to current context.
+ indent = Math.max(0, cx.indent - indentUnit);
+ }
+ }
+ return indent;
+ },
+
+ electricChars: "}",
+ blockCommentStart: "/*",
+ blockCommentEnd: "*/",
+ blockCommentContinue: " * ",
+ lineComment: lineComment,
+ fold: "brace"
+ };
+});
+
+ function keySet(array) {
+ var keys = {};
+ for (var i = 0; i < array.length; ++i) {
+ keys[array[i].toLowerCase()] = true;
+ }
+ return keys;
+ }
+
+ var documentTypes_ = [
+ "domain", "regexp", "url", "url-prefix"
+ ], documentTypes = keySet(documentTypes_);
+
+ var mediaTypes_ = [
+ "all", "aural", "braille", "handheld", "print", "projection", "screen",
+ "tty", "tv", "embossed"
+ ], mediaTypes = keySet(mediaTypes_);
+
+ var mediaFeatures_ = [
+ "width", "min-width", "max-width", "height", "min-height", "max-height",
+ "device-width", "min-device-width", "max-device-width", "device-height",
+ "min-device-height", "max-device-height", "aspect-ratio",
+ "min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio",
+ "min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color",
+ "max-color", "color-index", "min-color-index", "max-color-index",
+ "monochrome", "min-monochrome", "max-monochrome", "resolution",
+ "min-resolution", "max-resolution", "scan", "grid", "orientation",
+ "device-pixel-ratio", "min-device-pixel-ratio", "max-device-pixel-ratio",
+ "pointer", "any-pointer", "hover", "any-hover"
+ ], mediaFeatures = keySet(mediaFeatures_);
+
+ var mediaValueKeywords_ = [
+ "landscape", "portrait", "none", "coarse", "fine", "on-demand", "hover",
+ "interlace", "progressive"
+ ], mediaValueKeywords = keySet(mediaValueKeywords_);
+
+ var propertyKeywords_ = [
+ "align-content", "align-items", "align-self", "alignment-adjust",
+ "alignment-baseline", "anchor-point", "animation", "animation-delay",
+ "animation-direction", "animation-duration", "animation-fill-mode",
+ "animation-iteration-count", "animation-name", "animation-play-state",
+ "animation-timing-function", "appearance", "azimuth", "backface-visibility",
+ "background", "background-attachment", "background-blend-mode", "background-clip",
+ "background-color", "background-image", "background-origin", "background-position",
+ "background-repeat", "background-size", "baseline-shift", "binding",
+ "bleed", "bookmark-label", "bookmark-level", "bookmark-state",
+ "bookmark-target", "border", "border-bottom", "border-bottom-color",
+ "border-bottom-left-radius", "border-bottom-right-radius",
+ "border-bottom-style", "border-bottom-width", "border-collapse",
+ "border-color", "border-image", "border-image-outset",
+ "border-image-repeat", "border-image-slice", "border-image-source",
+ "border-image-width", "border-left", "border-left-color",
+ "border-left-style", "border-left-width", "border-radius", "border-right",
+ "border-right-color", "border-right-style", "border-right-width",
+ "border-spacing", "border-style", "border-top", "border-top-color",
+ "border-top-left-radius", "border-top-right-radius", "border-top-style",
+ "border-top-width", "border-width", "bottom", "box-decoration-break",
+ "box-shadow", "box-sizing", "break-after", "break-before", "break-inside",
+ "caption-side", "caret-color", "clear", "clip", "color", "color-profile", "column-count",
+ "column-fill", "column-gap", "column-rule", "column-rule-color",
+ "column-rule-style", "column-rule-width", "column-span", "column-width",
+ "columns", "content", "counter-increment", "counter-reset", "crop", "cue",
+ "cue-after", "cue-before", "cursor", "direction", "display",
+ "dominant-baseline", "drop-initial-after-adjust",
+ "drop-initial-after-align", "drop-initial-before-adjust",
+ "drop-initial-before-align", "drop-initial-size", "drop-initial-value",
+ "elevation", "empty-cells", "fit", "fit-position", "flex", "flex-basis",
+ "flex-direction", "flex-flow", "flex-grow", "flex-shrink", "flex-wrap",
+ "float", "float-offset", "flow-from", "flow-into", "font", "font-feature-settings",
+ "font-family", "font-kerning", "font-language-override", "font-size", "font-size-adjust",
+ "font-stretch", "font-style", "font-synthesis", "font-variant",
+ "font-variant-alternates", "font-variant-caps", "font-variant-east-asian",
+ "font-variant-ligatures", "font-variant-numeric", "font-variant-position",
+ "font-weight", "grid", "grid-area", "grid-auto-columns", "grid-auto-flow",
+ "grid-auto-rows", "grid-column", "grid-column-end", "grid-column-gap",
+ "grid-column-start", "grid-gap", "grid-row", "grid-row-end", "grid-row-gap",
+ "grid-row-start", "grid-template", "grid-template-areas", "grid-template-columns",
+ "grid-template-rows", "hanging-punctuation", "height", "hyphens",
+ "icon", "image-orientation", "image-rendering", "image-resolution",
+ "inline-box-align", "justify-content", "justify-items", "justify-self", "left", "letter-spacing",
+ "line-break", "line-height", "line-stacking", "line-stacking-ruby",
+ "line-stacking-shift", "line-stacking-strategy", "list-style",
+ "list-style-image", "list-style-position", "list-style-type", "margin",
+ "margin-bottom", "margin-left", "margin-right", "margin-top",
+ "marks", "marquee-direction", "marquee-loop",
+ "marquee-play-count", "marquee-speed", "marquee-style", "max-height",
+ "max-width", "min-height", "min-width", "mix-blend-mode", "move-to", "nav-down", "nav-index",
+ "nav-left", "nav-right", "nav-up", "object-fit", "object-position",
+ "opacity", "order", "orphans", "outline",
+ "outline-color", "outline-offset", "outline-style", "outline-width",
+ "overflow", "overflow-style", "overflow-wrap", "overflow-x", "overflow-y",
+ "padding", "padding-bottom", "padding-left", "padding-right", "padding-top",
+ "page", "page-break-after", "page-break-before", "page-break-inside",
+ "page-policy", "pause", "pause-after", "pause-before", "perspective",
+ "perspective-origin", "pitch", "pitch-range", "place-content", "place-items", "place-self", "play-during", "position",
+ "presentation-level", "punctuation-trim", "quotes", "region-break-after",
+ "region-break-before", "region-break-inside", "region-fragment",
+ "rendering-intent", "resize", "rest", "rest-after", "rest-before", "richness",
+ "right", "rotation", "rotation-point", "ruby-align", "ruby-overhang",
+ "ruby-position", "ruby-span", "shape-image-threshold", "shape-inside", "shape-margin",
+ "shape-outside", "size", "speak", "speak-as", "speak-header",
+ "speak-numeral", "speak-punctuation", "speech-rate", "stress", "string-set",
+ "tab-size", "table-layout", "target", "target-name", "target-new",
+ "target-position", "text-align", "text-align-last", "text-decoration",
+ "text-decoration-color", "text-decoration-line", "text-decoration-skip",
+ "text-decoration-style", "text-emphasis", "text-emphasis-color",
+ "text-emphasis-position", "text-emphasis-style", "text-height",
+ "text-indent", "text-justify", "text-outline", "text-overflow", "text-shadow",
+ "text-size-adjust", "text-space-collapse", "text-transform", "text-underline-position",
+ "text-wrap", "top", "transform", "transform-origin", "transform-style",
+ "transition", "transition-delay", "transition-duration",
+ "transition-property", "transition-timing-function", "unicode-bidi",
+ "user-select", "vertical-align", "visibility", "voice-balance", "voice-duration",
+ "voice-family", "voice-pitch", "voice-range", "voice-rate", "voice-stress",
+ "voice-volume", "volume", "white-space", "widows", "width", "will-change", "word-break",
+ "word-spacing", "word-wrap", "z-index",
+ // SVG-specific
+ "clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color",
+ "flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events",
+ "color-interpolation", "color-interpolation-filters",
+ "color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering",
+ "marker", "marker-end", "marker-mid", "marker-start", "shape-rendering", "stroke",
+ "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin",
+ "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering",
+ "baseline-shift", "dominant-baseline", "glyph-orientation-horizontal",
+ "glyph-orientation-vertical", "text-anchor", "writing-mode"
+ ], propertyKeywords = keySet(propertyKeywords_);
+
+ var nonStandardPropertyKeywords_ = [
+ "scrollbar-arrow-color", "scrollbar-base-color", "scrollbar-dark-shadow-color",
+ "scrollbar-face-color", "scrollbar-highlight-color", "scrollbar-shadow-color",
+ "scrollbar-3d-light-color", "scrollbar-track-color", "shape-inside",
+ "searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button",
+ "searchfield-results-decoration", "zoom"
+ ], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_);
+
+ var fontProperties_ = [
+ "font-family", "src", "unicode-range", "font-variant", "font-feature-settings",
+ "font-stretch", "font-weight", "font-style"
+ ], fontProperties = keySet(fontProperties_);
+
+ var counterDescriptors_ = [
+ "additive-symbols", "fallback", "negative", "pad", "prefix", "range",
+ "speak-as", "suffix", "symbols", "system"
+ ], counterDescriptors = keySet(counterDescriptors_);
+
+ var colorKeywords_ = [
+ "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige",
+ "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown",
+ "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue",
+ "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod",
+ "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen",
+ "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen",
+ "darkslateblue", "darkslategray", "darkturquoise", "darkviolet",
+ "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick",
+ "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite",
+ "gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew",
+ "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender",
+ "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral",
+ "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightpink",
+ "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray",
+ "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta",
+ "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple",
+ "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise",
+ "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin",
+ "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered",
+ "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred",
+ "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue",
+ "purple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown",
+ "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue",
+ "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan",
+ "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white",
+ "whitesmoke", "yellow", "yellowgreen"
+ ], colorKeywords = keySet(colorKeywords_);
+
+ var valueKeywords_ = [
+ "above", "absolute", "activeborder", "additive", "activecaption", "afar",
+ "after-white-space", "ahead", "alias", "all", "all-scroll", "alphabetic", "alternate",
+ "always", "amharic", "amharic-abegede", "antialiased", "appworkspace",
+ "arabic-indic", "armenian", "asterisks", "attr", "auto", "auto-flow", "avoid", "avoid-column", "avoid-page",
+ "avoid-region", "background", "backwards", "baseline", "below", "bidi-override", "binary",
+ "bengali", "blink", "block", "block-axis", "bold", "bolder", "border", "border-box",
+ "both", "bottom", "break", "break-all", "break-word", "bullets", "button", "button-bevel",
+ "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "calc", "cambodian",
+ "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret",
+ "cell", "center", "checkbox", "circle", "cjk-decimal", "cjk-earthly-branch",
+ "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote",
+ "col-resize", "collapse", "color", "color-burn", "color-dodge", "column", "column-reverse",
+ "compact", "condensed", "contain", "content", "contents",
+ "content-box", "context-menu", "continuous", "copy", "counter", "counters", "cover", "crop",
+ "cross", "crosshair", "currentcolor", "cursive", "cyclic", "darken", "dashed", "decimal",
+ "decimal-leading-zero", "default", "default-button", "dense", "destination-atop",
+ "destination-in", "destination-out", "destination-over", "devanagari", "difference",
+ "disc", "discard", "disclosure-closed", "disclosure-open", "document",
+ "dot-dash", "dot-dot-dash",
+ "dotted", "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out",
+ "element", "ellipse", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede",
+ "ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er",
+ "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er",
+ "ethiopic-halehame-aa-et", "ethiopic-halehame-am-et",
+ "ethiopic-halehame-gez", "ethiopic-halehame-om-et",
+ "ethiopic-halehame-sid-et", "ethiopic-halehame-so-et",
+ "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", "ethiopic-halehame-tig",
+ "ethiopic-numeric", "ew-resize", "exclusion", "expanded", "extends", "extra-condensed",
+ "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "flex", "flex-end", "flex-start", "footnotes",
+ "forwards", "from", "geometricPrecision", "georgian", "graytext", "grid", "groove",
+ "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hard-light", "hebrew",
+ "help", "hidden", "hide", "higher", "highlight", "highlighttext",
+ "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "hue", "icon", "ignore",
+ "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite",
+ "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis",
+ "inline-block", "inline-flex", "inline-grid", "inline-table", "inset", "inside", "intrinsic", "invert",
+ "italic", "japanese-formal", "japanese-informal", "justify", "kannada",
+ "katakana", "katakana-iroha", "keep-all", "khmer",
+ "korean-hangul-formal", "korean-hanja-formal", "korean-hanja-informal",
+ "landscape", "lao", "large", "larger", "left", "level", "lighter", "lighten",
+ "line-through", "linear", "linear-gradient", "lines", "list-item", "listbox", "listitem",
+ "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian",
+ "lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian",
+ "lower-roman", "lowercase", "ltr", "luminosity", "malayalam", "match", "matrix", "matrix3d",
+ "media-controls-background", "media-current-time-display",
+ "media-fullscreen-button", "media-mute-button", "media-play-button",
+ "media-return-to-realtime-button", "media-rewind-button",
+ "media-seek-back-button", "media-seek-forward-button", "media-slider",
+ "media-sliderthumb", "media-time-remaining-display", "media-volume-slider",
+ "media-volume-slider-container", "media-volume-sliderthumb", "medium",
+ "menu", "menulist", "menulist-button", "menulist-text",
+ "menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic",
+ "mix", "mongolian", "monospace", "move", "multiple", "multiply", "myanmar", "n-resize",
+ "narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop",
+ "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap",
+ "ns-resize", "numbers", "numeric", "nw-resize", "nwse-resize", "oblique", "octal", "opacity", "open-quote",
+ "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset",
+ "outside", "outside-shape", "overlay", "overline", "padding", "padding-box",
+ "painted", "page", "paused", "persian", "perspective", "plus-darker", "plus-lighter",
+ "pointer", "polygon", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d",
+ "progress", "push-button", "radial-gradient", "radio", "read-only",
+ "read-write", "read-write-plaintext-only", "rectangle", "region",
+ "relative", "repeat", "repeating-linear-gradient",
+ "repeating-radial-gradient", "repeat-x", "repeat-y", "reset", "reverse",
+ "rgb", "rgba", "ridge", "right", "rotate", "rotate3d", "rotateX", "rotateY",
+ "rotateZ", "round", "row", "row-resize", "row-reverse", "rtl", "run-in", "running",
+ "s-resize", "sans-serif", "saturation", "scale", "scale3d", "scaleX", "scaleY", "scaleZ", "screen",
+ "scroll", "scrollbar", "scroll-position", "se-resize", "searchfield",
+ "searchfield-cancel-button", "searchfield-decoration",
+ "searchfield-results-button", "searchfield-results-decoration", "self-start", "self-end",
+ "semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama",
+ "simp-chinese-formal", "simp-chinese-informal", "single",
+ "skew", "skewX", "skewY", "skip-white-space", "slide", "slider-horizontal",
+ "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow",
+ "small", "small-caps", "small-caption", "smaller", "soft-light", "solid", "somali",
+ "source-atop", "source-in", "source-out", "source-over", "space", "space-around", "space-between", "space-evenly", "spell-out", "square",
+ "square-button", "start", "static", "status-bar", "stretch", "stroke", "sub",
+ "subpixel-antialiased", "super", "sw-resize", "symbolic", "symbols", "system-ui", "table",
+ "table-caption", "table-cell", "table-column", "table-column-group",
+ "table-footer-group", "table-header-group", "table-row", "table-row-group",
+ "tamil",
+ "telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai",
+ "thick", "thin", "threeddarkshadow", "threedface", "threedhighlight",
+ "threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er",
+ "tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top",
+ "trad-chinese-formal", "trad-chinese-informal", "transform",
+ "translate", "translate3d", "translateX", "translateY", "translateZ",
+ "transparent", "ultra-condensed", "ultra-expanded", "underline", "unset", "up",
+ "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal",
+ "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url",
+ "var", "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted",
+ "visibleStroke", "visual", "w-resize", "wait", "wave", "wider",
+ "window", "windowframe", "windowtext", "words", "wrap", "wrap-reverse", "x-large", "x-small", "xor",
+ "xx-large", "xx-small"
+ ], valueKeywords = keySet(valueKeywords_);
+
+ var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_)
+ .concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_)
+ .concat(valueKeywords_);
+ CodeMirror.registerHelper("hintWords", "css", allWords);
+
+ function tokenCComment(stream, state) {
+ var maybeEnd = false, ch;
+ while ((ch = stream.next()) != null) {
+ if (maybeEnd && ch == "/") {
+ state.tokenize = null;
+ break;
+ }
+ maybeEnd = (ch == "*");
+ }
+ return ["comment", "comment"];
+ }
+
+ CodeMirror.defineMIME("text/css", {
+ documentTypes: documentTypes,
+ mediaTypes: mediaTypes,
+ mediaFeatures: mediaFeatures,
+ mediaValueKeywords: mediaValueKeywords,
+ propertyKeywords: propertyKeywords,
+ nonStandardPropertyKeywords: nonStandardPropertyKeywords,
+ fontProperties: fontProperties,
+ counterDescriptors: counterDescriptors,
+ colorKeywords: colorKeywords,
+ valueKeywords: valueKeywords,
+ tokenHooks: {
+ "/": function(stream, state) {
+ if (!stream.eat("*")) return false;
+ state.tokenize = tokenCComment;
+ return tokenCComment(stream, state);
+ }
+ },
+ name: "css"
+ });
+
+ CodeMirror.defineMIME("text/x-scss", {
+ mediaTypes: mediaTypes,
+ mediaFeatures: mediaFeatures,
+ mediaValueKeywords: mediaValueKeywords,
+ propertyKeywords: propertyKeywords,
+ nonStandardPropertyKeywords: nonStandardPropertyKeywords,
+ colorKeywords: colorKeywords,
+ valueKeywords: valueKeywords,
+ fontProperties: fontProperties,
+ allowNested: true,
+ lineComment: "//",
+ tokenHooks: {
+ "/": function(stream, state) {
+ if (stream.eat("/")) {
+ stream.skipToEnd();
+ return ["comment", "comment"];
+ } else if (stream.eat("*")) {
+ state.tokenize = tokenCComment;
+ return tokenCComment(stream, state);
+ } else {
+ return ["operator", "operator"];
+ }
+ },
+ ":": function(stream) {
+ if (stream.match(/\s*\{/, false))
+ return [null, null]
+ return false;
+ },
+ "$": function(stream) {
+ stream.match(/^[\w-]+/);
+ if (stream.match(/^\s*:/, false))
+ return ["variable-2", "variable-definition"];
+ return ["variable-2", "variable"];
+ },
+ "#": function(stream) {
+ if (!stream.eat("{")) return false;
+ return [null, "interpolation"];
+ }
+ },
+ name: "css",
+ helperType: "scss"
+ });
+
+ CodeMirror.defineMIME("text/x-less", {
+ mediaTypes: mediaTypes,
+ mediaFeatures: mediaFeatures,
+ mediaValueKeywords: mediaValueKeywords,
+ propertyKeywords: propertyKeywords,
+ nonStandardPropertyKeywords: nonStandardPropertyKeywords,
+ colorKeywords: colorKeywords,
+ valueKeywords: valueKeywords,
+ fontProperties: fontProperties,
+ allowNested: true,
+ lineComment: "//",
+ tokenHooks: {
+ "/": function(stream, state) {
+ if (stream.eat("/")) {
+ stream.skipToEnd();
+ return ["comment", "comment"];
+ } else if (stream.eat("*")) {
+ state.tokenize = tokenCComment;
+ return tokenCComment(stream, state);
+ } else {
+ return ["operator", "operator"];
+ }
+ },
+ "@": function(stream) {
+ if (stream.eat("{")) return [null, "interpolation"];
+ if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/i, false)) return false;
+ stream.eatWhile(/[\w\\\-]/);
+ if (stream.match(/^\s*:/, false))
+ return ["variable-2", "variable-definition"];
+ return ["variable-2", "variable"];
+ },
+ "&": function() {
+ return ["atom", "atom"];
+ }
+ },
+ name: "css",
+ helperType: "less"
+ });
+
+ CodeMirror.defineMIME("text/x-gss", {
+ documentTypes: documentTypes,
+ mediaTypes: mediaTypes,
+ mediaFeatures: mediaFeatures,
+ propertyKeywords: propertyKeywords,
+ nonStandardPropertyKeywords: nonStandardPropertyKeywords,
+ fontProperties: fontProperties,
+ counterDescriptors: counterDescriptors,
+ colorKeywords: colorKeywords,
+ valueKeywords: valueKeywords,
+ supportsAtComponent: true,
+ tokenHooks: {
+ "/": function(stream, state) {
+ if (!stream.eat("*")) return false;
+ state.tokenize = tokenCComment;
+ return tokenCComment(stream, state);
+ }
+ },
+ name: "css",
+ helperType: "gss"
+ });
+
+});
diff --git a/core/vendor/codemirror/mode/javascript.js b/core/vendor/codemirror/mode/javascript.js
new file mode 100644
index 00000000..16943a9e
--- /dev/null
+++ b/core/vendor/codemirror/mode/javascript.js
@@ -0,0 +1,930 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("../../lib/codemirror"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+"use strict";
+
+CodeMirror.defineMode("javascript", function(config, parserConfig) {
+ var indentUnit = config.indentUnit;
+ var statementIndent = parserConfig.statementIndent;
+ var jsonldMode = parserConfig.jsonld;
+ var jsonMode = parserConfig.json || jsonldMode;
+ var isTS = parserConfig.typescript;
+ var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/;
+
+ // Tokenizer
+
+ var keywords = function(){
+ function kw(type) {return {type: type, style: "keyword"};}
+ var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"), D = kw("keyword d");
+ var operator = kw("operator"), atom = {type: "atom", style: "atom"};
+
+ return {
+ "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
+ "return": D, "break": D, "continue": D, "new": kw("new"), "delete": C, "void": C, "throw": C,
+ "debugger": kw("debugger"), "var": kw("var"), "const": kw("var"), "let": kw("var"),
+ "function": kw("function"), "catch": kw("catch"),
+ "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
+ "in": operator, "typeof": operator, "instanceof": operator,
+ "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom,
+ "this": kw("this"), "class": kw("class"), "super": kw("atom"),
+ "yield": C, "export": kw("export"), "import": kw("import"), "extends": C,
+ "await": C
+ };
+ }();
+
+ var isOperatorChar = /[+\-*&%=<>!?|~^@]/;
+ var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;
+
+ function readRegexp(stream) {
+ var escaped = false, next, inSet = false;
+ while ((next = stream.next()) != null) {
+ if (!escaped) {
+ if (next == "/" && !inSet) return;
+ if (next == "[") inSet = true;
+ else if (inSet && next == "]") inSet = false;
+ }
+ escaped = !escaped && next == "\\";
+ }
+ }
+
+ // Used as scratch variables to communicate multiple values without
+ // consing up tons of objects.
+ var type, content;
+ function ret(tp, style, cont) {
+ type = tp; content = cont;
+ return style;
+ }
+ function tokenBase(stream, state) {
+ var ch = stream.next();
+ if (ch == '"' || ch == "'") {
+ state.tokenize = tokenString(ch);
+ return state.tokenize(stream, state);
+ } else if (ch == "." && stream.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/)) {
+ return ret("number", "number");
+ } else if (ch == "." && stream.match("..")) {
+ return ret("spread", "meta");
+ } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
+ return ret(ch);
+ } else if (ch == "=" && stream.eat(">")) {
+ return ret("=>", "operator");
+ } else if (ch == "0" && stream.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/)) {
+ return ret("number", "number");
+ } else if (/\d/.test(ch)) {
+ stream.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/);
+ return ret("number", "number");
+ } else if (ch == "/") {
+ if (stream.eat("*")) {
+ state.tokenize = tokenComment;
+ return tokenComment(stream, state);
+ } else if (stream.eat("/")) {
+ stream.skipToEnd();
+ return ret("comment", "comment");
+ } else if (expressionAllowed(stream, state, 1)) {
+ readRegexp(stream);
+ stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/);
+ return ret("regexp", "string-2");
+ } else {
+ stream.eat("=");
+ return ret("operator", "operator", stream.current());
+ }
+ } else if (ch == "`") {
+ state.tokenize = tokenQuasi;
+ return tokenQuasi(stream, state);
+ } else if (ch == "#") {
+ stream.skipToEnd();
+ return ret("error", "error");
+ } else if (ch == "<" && stream.match("!--") || ch == "-" && stream.match("->")) {
+ stream.skipToEnd()
+ return ret("comment", "comment")
+ } else if (isOperatorChar.test(ch)) {
+ if (ch != ">" || !state.lexical || state.lexical.type != ">") {
+ if (stream.eat("=")) {
+ if (ch == "!" || ch == "=") stream.eat("=")
+ } else if (/[<>*+\-]/.test(ch)) {
+ stream.eat(ch)
+ if (ch == ">") stream.eat(ch)
+ }
+ }
+ return ret("operator", "operator", stream.current());
+ } else if (wordRE.test(ch)) {
+ stream.eatWhile(wordRE);
+ var word = stream.current()
+ if (state.lastType != ".") {
+ if (keywords.propertyIsEnumerable(word)) {
+ var kw = keywords[word]
+ return ret(kw.type, kw.style, word)
+ }
+ if (word == "async" && stream.match(/^(\s|\/\*.*?\*\/)*[\[\(\w]/, false))
+ return ret("async", "keyword", word)
+ }
+ return ret("variable", "variable", word)
+ }
+ }
+
+ function tokenString(quote) {
+ return function(stream, state) {
+ var escaped = false, next;
+ if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){
+ state.tokenize = tokenBase;
+ return ret("jsonld-keyword", "meta");
+ }
+ while ((next = stream.next()) != null) {
+ if (next == quote && !escaped) break;
+ escaped = !escaped && next == "\\";
+ }
+ if (!escaped) state.tokenize = tokenBase;
+ return ret("string", "string");
+ };
+ }
+
+ function tokenComment(stream, state) {
+ var maybeEnd = false, ch;
+ while (ch = stream.next()) {
+ if (ch == "/" && maybeEnd) {
+ state.tokenize = tokenBase;
+ break;
+ }
+ maybeEnd = (ch == "*");
+ }
+ return ret("comment", "comment");
+ }
+
+ function tokenQuasi(stream, state) {
+ var escaped = false, next;
+ while ((next = stream.next()) != null) {
+ if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) {
+ state.tokenize = tokenBase;
+ break;
+ }
+ escaped = !escaped && next == "\\";
+ }
+ return ret("quasi", "string-2", stream.current());
+ }
+
+ var brackets = "([{}])";
+ // This is a crude lookahead trick to try and notice that we're
+ // parsing the argument patterns for a fat-arrow function before we
+ // actually hit the arrow token. It only works if the arrow is on
+ // the same line as the arguments and there's no strange noise
+ // (comments) in between. Fallback is to only notice when we hit the
+ // arrow, and not declare the arguments as locals for the arrow
+ // body.
+ function findFatArrow(stream, state) {
+ if (state.fatArrowAt) state.fatArrowAt = null;
+ var arrow = stream.string.indexOf("=>", stream.start);
+ if (arrow < 0) return;
+
+ if (isTS) { // Try to skip TypeScript return type declarations after the arguments
+ var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow))
+ if (m) arrow = m.index
+ }
+
+ var depth = 0, sawSomething = false;
+ for (var pos = arrow - 1; pos >= 0; --pos) {
+ var ch = stream.string.charAt(pos);
+ var bracket = brackets.indexOf(ch);
+ if (bracket >= 0 && bracket < 3) {
+ if (!depth) { ++pos; break; }
+ if (--depth == 0) { if (ch == "(") sawSomething = true; break; }
+ } else if (bracket >= 3 && bracket < 6) {
+ ++depth;
+ } else if (wordRE.test(ch)) {
+ sawSomething = true;
+ } else if (/["'\/`]/.test(ch)) {
+ for (;; --pos) {
+ if (pos == 0) return
+ var next = stream.string.charAt(pos - 1)
+ if (next == ch && stream.string.charAt(pos - 2) != "\\") { pos--; break }
+ }
+ } else if (sawSomething && !depth) {
+ ++pos;
+ break;
+ }
+ }
+ if (sawSomething && !depth) state.fatArrowAt = pos;
+ }
+
+ // Parser
+
+ var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true};
+
+ function JSLexical(indented, column, type, align, prev, info) {
+ this.indented = indented;
+ this.column = column;
+ this.type = type;
+ this.prev = prev;
+ this.info = info;
+ if (align != null) this.align = align;
+ }
+
+ function inScope(state, varname) {
+ for (var v = state.localVars; v; v = v.next)
+ if (v.name == varname) return true;
+ for (var cx = state.context; cx; cx = cx.prev) {
+ for (var v = cx.vars; v; v = v.next)
+ if (v.name == varname) return true;
+ }
+ }
+
+ function parseJS(state, style, type, content, stream) {
+ var cc = state.cc;
+ // Communicate our context to the combinators.
+ // (Less wasteful than consing up a hundred closures on every call.)
+ cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style;
+
+ if (!state.lexical.hasOwnProperty("align"))
+ state.lexical.align = true;
+
+ while(true) {
+ var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
+ if (combinator(type, content)) {
+ while(cc.length && cc[cc.length - 1].lex)
+ cc.pop()();
+ if (cx.marked) return cx.marked;
+ if (type == "variable" && inScope(state, content)) return "variable-2";
+ return style;
+ }
+ }
+ }
+
+ // Combinator utils
+
+ var cx = {state: null, column: null, marked: null, cc: null};
+ function pass() {
+ for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
+ }
+ function cont() {
+ pass.apply(null, arguments);
+ return true;
+ }
+ function inList(name, list) {
+ for (var v = list; v; v = v.next) if (v.name == name) return true
+ return false;
+ }
+ function register(varname) {
+ var state = cx.state;
+ cx.marked = "def";
+ if (state.context) {
+ if (state.lexical.info == "var" && state.context && state.context.block) {
+ // FIXME function decls are also not block scoped
+ var newContext = registerVarScoped(varname, state.context)
+ if (newContext != null) {
+ state.context = newContext
+ return
+ }
+ } else if (!inList(varname, state.localVars)) {
+ state.localVars = new Var(varname, state.localVars)
+ return
+ }
+ }
+ // Fall through means this is global
+ if (parserConfig.globalVars && !inList(varname, state.globalVars))
+ state.globalVars = new Var(varname, state.globalVars)
+ }
+ function registerVarScoped(varname, context) {
+ if (!context) {
+ return null
+ } else if (context.block) {
+ var inner = registerVarScoped(varname, context.prev)
+ if (!inner) return null
+ if (inner == context.prev) return context
+ return new Context(inner, context.vars, true)
+ } else if (inList(varname, context.vars)) {
+ return context
+ } else {
+ return new Context(context.prev, new Var(varname, context.vars), false)
+ }
+ }
+
+ function isModifier(name) {
+ return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly"
+ }
+
+ // Combinators
+
+ function Context(prev, vars, block) { this.prev = prev; this.vars = vars; this.block = block }
+ function Var(name, next) { this.name = name; this.next = next }
+
+ var defaultVars = new Var("this", new Var("arguments", null))
+ function pushcontext() {
+ cx.state.context = new Context(cx.state.context, cx.state.localVars, false)
+ cx.state.localVars = defaultVars
+ }
+ function pushblockcontext() {
+ cx.state.context = new Context(cx.state.context, cx.state.localVars, true)
+ cx.state.localVars = null
+ }
+ function popcontext() {
+ cx.state.localVars = cx.state.context.vars
+ cx.state.context = cx.state.context.prev
+ }
+ popcontext.lex = true
+ function pushlex(type, info) {
+ var result = function() {
+ var state = cx.state, indent = state.indented;
+ if (state.lexical.type == "stat") indent = state.lexical.indented;
+ else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev)
+ indent = outer.indented;
+ state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
+ };
+ result.lex = true;
+ return result;
+ }
+ function poplex() {
+ var state = cx.state;
+ if (state.lexical.prev) {
+ if (state.lexical.type == ")")
+ state.indented = state.lexical.indented;
+ state.lexical = state.lexical.prev;
+ }
+ }
+ poplex.lex = true;
+
+ function expect(wanted) {
+ function exp(type) {
+ if (type == wanted) return cont();
+ else if (wanted == ";" || type == "}" || type == ")" || type == "]") return pass();
+ else return cont(exp);
+ };
+ return exp;
+ }
+
+ function statement(type, value) {
+ if (type == "var") return cont(pushlex("vardef", value), vardef, expect(";"), poplex);
+ if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex);
+ if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
+ if (type == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex);
+ if (type == "debugger") return cont(expect(";"));
+ if (type == "{") return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext);
+ if (type == ";") return cont();
+ if (type == "if") {
+ if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex)
+ cx.state.cc.pop()();
+ return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse);
+ }
+ if (type == "function") return cont(functiondef);
+ if (type == "for") return cont(pushlex("form"), forspec, statement, poplex);
+ if (type == "class" || (isTS && value == "interface")) {
+ cx.marked = "keyword"
+ return cont(pushlex("form", type == "class" ? type : value), className, poplex)
+ }
+ if (type == "variable") {
+ if (isTS && value == "declare") {
+ cx.marked = "keyword"
+ return cont(statement)
+ } else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) {
+ cx.marked = "keyword"
+ if (value == "enum") return cont(enumdef);
+ else if (value == "type") return cont(typename, expect("operator"), typeexpr, expect(";"));
+ else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex)
+ } else if (isTS && value == "namespace") {
+ cx.marked = "keyword"
+ return cont(pushlex("form"), expression, statement, poplex)
+ } else if (isTS && value == "abstract") {
+ cx.marked = "keyword"
+ return cont(statement)
+ } else {
+ return cont(pushlex("stat"), maybelabel);
+ }
+ }
+ if (type == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), pushblockcontext,
+ block, poplex, poplex, popcontext);
+ if (type == "case") return cont(expression, expect(":"));
+ if (type == "default") return cont(expect(":"));
+ if (type == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext);
+ if (type == "export") return cont(pushlex("stat"), afterExport, poplex);
+ if (type == "import") return cont(pushlex("stat"), afterImport, poplex);
+ if (type == "async") return cont(statement)
+ if (value == "@") return cont(expression, statement)
+ return pass(pushlex("stat"), expression, expect(";"), poplex);
+ }
+ function maybeCatchBinding(type) {
+ if (type == "(") return cont(funarg, expect(")"))
+ }
+ function expression(type, value) {
+ return expressionInner(type, value, false);
+ }
+ function expressionNoComma(type, value) {
+ return expressionInner(type, value, true);
+ }
+ function parenExpr(type) {
+ if (type != "(") return pass()
+ return cont(pushlex(")"), expression, expect(")"), poplex)
+ }
+ function expressionInner(type, value, noComma) {
+ if (cx.state.fatArrowAt == cx.stream.start) {
+ var body = noComma ? arrowBodyNoComma : arrowBody;
+ if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext);
+ else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext);
+ }
+
+ var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
+ if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
+ if (type == "function") return cont(functiondef, maybeop);
+ if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), classExpression, poplex); }
+ if (type == "keyword c" || type == "async") return cont(noComma ? expressionNoComma : expression);
+ if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop);
+ if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression);
+ if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop);
+ if (type == "{") return contCommasep(objprop, "}", null, maybeop);
+ if (type == "quasi") return pass(quasi, maybeop);
+ if (type == "new") return cont(maybeTarget(noComma));
+ if (type == "import") return cont(expression);
+ return cont();
+ }
+ function maybeexpression(type) {
+ if (type.match(/[;\}\)\],]/)) return pass();
+ return pass(expression);
+ }
+
+ function maybeoperatorComma(type, value) {
+ if (type == ",") return cont(expression);
+ return maybeoperatorNoComma(type, value, false);
+ }
+ function maybeoperatorNoComma(type, value, noComma) {
+ var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
+ var expr = noComma == false ? expression : expressionNoComma;
+ if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);
+ if (type == "operator") {
+ if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me);
+ if (isTS && value == "<" && cx.stream.match(/^([^>]|<.*?>)*>\s*\(/, false))
+ return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me);
+ if (value == "?") return cont(expression, expect(":"), expr);
+ return cont(expr);
+ }
+ if (type == "quasi") { return pass(quasi, me); }
+ if (type == ";") return;
+ if (type == "(") return contCommasep(expressionNoComma, ")", "call", me);
+ if (type == ".") return cont(property, me);
+ if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me);
+ if (isTS && value == "as") { cx.marked = "keyword"; return cont(typeexpr, me) }
+ if (type == "regexp") {
+ cx.state.lastType = cx.marked = "operator"
+ cx.stream.backUp(cx.stream.pos - cx.stream.start - 1)
+ return cont(expr)
+ }
+ }
+ function quasi(type, value) {
+ if (type != "quasi") return pass();
+ if (value.slice(value.length - 2) != "${") return cont(quasi);
+ return cont(expression, continueQuasi);
+ }
+ function continueQuasi(type) {
+ if (type == "}") {
+ cx.marked = "string-2";
+ cx.state.tokenize = tokenQuasi;
+ return cont(quasi);
+ }
+ }
+ function arrowBody(type) {
+ findFatArrow(cx.stream, cx.state);
+ return pass(type == "{" ? statement : expression);
+ }
+ function arrowBodyNoComma(type) {
+ findFatArrow(cx.stream, cx.state);
+ return pass(type == "{" ? statement : expressionNoComma);
+ }
+ function maybeTarget(noComma) {
+ return function(type) {
+ if (type == ".") return cont(noComma ? targetNoComma : target);
+ else if (type == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma)
+ else return pass(noComma ? expressionNoComma : expression);
+ };
+ }
+ function target(_, value) {
+ if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); }
+ }
+ function targetNoComma(_, value) {
+ if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); }
+ }
+ function maybelabel(type) {
+ if (type == ":") return cont(poplex, statement);
+ return pass(maybeoperatorComma, expect(";"), poplex);
+ }
+ function property(type) {
+ if (type == "variable") {cx.marked = "property"; return cont();}
+ }
+ function objprop(type, value) {
+ if (type == "async") {
+ cx.marked = "property";
+ return cont(objprop);
+ } else if (type == "variable" || cx.style == "keyword") {
+ cx.marked = "property";
+ if (value == "get" || value == "set") return cont(getterSetter);
+ var m // Work around fat-arrow-detection complication for detecting typescript typed arrow params
+ if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false)))
+ cx.state.fatArrowAt = cx.stream.pos + m[0].length
+ return cont(afterprop);
+ } else if (type == "number" || type == "string") {
+ cx.marked = jsonldMode ? "property" : (cx.style + " property");
+ return cont(afterprop);
+ } else if (type == "jsonld-keyword") {
+ return cont(afterprop);
+ } else if (isTS && isModifier(value)) {
+ cx.marked = "keyword"
+ return cont(objprop)
+ } else if (type == "[") {
+ return cont(expression, maybetype, expect("]"), afterprop);
+ } else if (type == "spread") {
+ return cont(expressionNoComma, afterprop);
+ } else if (value == "*") {
+ cx.marked = "keyword";
+ return cont(objprop);
+ } else if (type == ":") {
+ return pass(afterprop)
+ }
+ }
+ function getterSetter(type) {
+ if (type != "variable") return pass(afterprop);
+ cx.marked = "property";
+ return cont(functiondef);
+ }
+ function afterprop(type) {
+ if (type == ":") return cont(expressionNoComma);
+ if (type == "(") return pass(functiondef);
+ }
+ function commasep(what, end, sep) {
+ function proceed(type, value) {
+ if (sep ? sep.indexOf(type) > -1 : type == ",") {
+ var lex = cx.state.lexical;
+ if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
+ return cont(function(type, value) {
+ if (type == end || value == end) return pass()
+ return pass(what)
+ }, proceed);
+ }
+ if (type == end || value == end) return cont();
+ if (sep && sep.indexOf(";") > -1) return pass(what)
+ return cont(expect(end));
+ }
+ return function(type, value) {
+ if (type == end || value == end) return cont();
+ return pass(what, proceed);
+ };
+ }
+ function contCommasep(what, end, info) {
+ for (var i = 3; i < arguments.length; i++)
+ cx.cc.push(arguments[i]);
+ return cont(pushlex(end, info), commasep(what, end), poplex);
+ }
+ function block(type) {
+ if (type == "}") return cont();
+ return pass(statement, block);
+ }
+ function maybetype(type, value) {
+ if (isTS) {
+ if (type == ":") return cont(typeexpr);
+ if (value == "?") return cont(maybetype);
+ }
+ }
+ function maybetypeOrIn(type, value) {
+ if (isTS && (type == ":" || value == "in")) return cont(typeexpr)
+ }
+ function mayberettype(type) {
+ if (isTS && type == ":") {
+ if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr)
+ else return cont(typeexpr)
+ }
+ }
+ function isKW(_, value) {
+ if (value == "is") {
+ cx.marked = "keyword"
+ return cont()
+ }
+ }
+ function typeexpr(type, value) {
+ if (value == "keyof" || value == "typeof" || value == "infer") {
+ cx.marked = "keyword"
+ return cont(value == "typeof" ? expressionNoComma : typeexpr)
+ }
+ if (type == "variable" || value == "void") {
+ cx.marked = "type"
+ return cont(afterType)
+ }
+ if (value == "|" || value == "&") return cont(typeexpr)
+ if (type == "string" || type == "number" || type == "atom") return cont(afterType);
+ if (type == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType)
+ if (type == "{") return cont(pushlex("}"), commasep(typeprop, "}", ",;"), poplex, afterType)
+ if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType, afterType)
+ if (type == "<") return cont(commasep(typeexpr, ">"), typeexpr)
+ }
+ function maybeReturnType(type) {
+ if (type == "=>") return cont(typeexpr)
+ }
+ function typeprop(type, value) {
+ if (type == "variable" || cx.style == "keyword") {
+ cx.marked = "property"
+ return cont(typeprop)
+ } else if (value == "?" || type == "number" || type == "string") {
+ return cont(typeprop)
+ } else if (type == ":") {
+ return cont(typeexpr)
+ } else if (type == "[") {
+ return cont(expect("variable"), maybetypeOrIn, expect("]"), typeprop)
+ } else if (type == "(") {
+ return pass(functiondecl, typeprop)
+ }
+ }
+ function typearg(type, value) {
+ if (type == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg)
+ if (type == ":") return cont(typeexpr)
+ if (type == "spread") return cont(typearg)
+ return pass(typeexpr)
+ }
+ function afterType(type, value) {
+ if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType)
+ if (value == "|" || type == "." || value == "&") return cont(typeexpr)
+ if (type == "[") return cont(typeexpr, expect("]"), afterType)
+ if (value == "extends" || value == "implements") { cx.marked = "keyword"; return cont(typeexpr) }
+ if (value == "?") return cont(typeexpr, expect(":"), typeexpr)
+ }
+ function maybeTypeArgs(_, value) {
+ if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType)
+ }
+ function typeparam() {
+ return pass(typeexpr, maybeTypeDefault)
+ }
+ function maybeTypeDefault(_, value) {
+ if (value == "=") return cont(typeexpr)
+ }
+ function vardef(_, value) {
+ if (value == "enum") {cx.marked = "keyword"; return cont(enumdef)}
+ return pass(pattern, maybetype, maybeAssign, vardefCont);
+ }
+ function pattern(type, value) {
+ if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(pattern) }
+ if (type == "variable") { register(value); return cont(); }
+ if (type == "spread") return cont(pattern);
+ if (type == "[") return contCommasep(eltpattern, "]");
+ if (type == "{") return contCommasep(proppattern, "}");
+ }
+ function proppattern(type, value) {
+ if (type == "variable" && !cx.stream.match(/^\s*:/, false)) {
+ register(value);
+ return cont(maybeAssign);
+ }
+ if (type == "variable") cx.marked = "property";
+ if (type == "spread") return cont(pattern);
+ if (type == "}") return pass();
+ if (type == "[") return cont(expression, expect(']'), expect(':'), proppattern);
+ return cont(expect(":"), pattern, maybeAssign);
+ }
+ function eltpattern() {
+ return pass(pattern, maybeAssign)
+ }
+ function maybeAssign(_type, value) {
+ if (value == "=") return cont(expressionNoComma);
+ }
+ function vardefCont(type) {
+ if (type == ",") return cont(vardef);
+ }
+ function maybeelse(type, value) {
+ if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex);
+ }
+ function forspec(type, value) {
+ if (value == "await") return cont(forspec);
+ if (type == "(") return cont(pushlex(")"), forspec1, poplex);
+ }
+ function forspec1(type) {
+ if (type == "var") return cont(vardef, forspec2);
+ if (type == "variable") return cont(forspec2);
+ return pass(forspec2)
+ }
+ function forspec2(type, value) {
+ if (type == ")") return cont()
+ if (type == ";") return cont(forspec2)
+ if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression, forspec2) }
+ return pass(expression, forspec2)
+ }
+ function functiondef(type, value) {
+ if (value == "*") {cx.marked = "keyword"; return cont(functiondef);}
+ if (type == "variable") {register(value); return cont(functiondef);}
+ if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext);
+ if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef)
+ }
+ function functiondecl(type, value) {
+ if (value == "*") {cx.marked = "keyword"; return cont(functiondecl);}
+ if (type == "variable") {register(value); return cont(functiondecl);}
+ if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, popcontext);
+ if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondecl)
+ }
+ function typename(type, value) {
+ if (type == "keyword" || type == "variable") {
+ cx.marked = "type"
+ return cont(typename)
+ } else if (value == "<") {
+ return cont(pushlex(">"), commasep(typeparam, ">"), poplex)
+ }
+ }
+ function funarg(type, value) {
+ if (value == "@") cont(expression, funarg)
+ if (type == "spread") return cont(funarg);
+ if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(funarg); }
+ if (isTS && type == "this") return cont(maybetype, maybeAssign)
+ return pass(pattern, maybetype, maybeAssign);
+ }
+ function classExpression(type, value) {
+ // Class expressions may have an optional name.
+ if (type == "variable") return className(type, value);
+ return classNameAfter(type, value);
+ }
+ function className(type, value) {
+ if (type == "variable") {register(value); return cont(classNameAfter);}
+ }
+ function classNameAfter(type, value) {
+ if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter)
+ if (value == "extends" || value == "implements" || (isTS && type == ",")) {
+ if (value == "implements") cx.marked = "keyword";
+ return cont(isTS ? typeexpr : expression, classNameAfter);
+ }
+ if (type == "{") return cont(pushlex("}"), classBody, poplex);
+ }
+ function classBody(type, value) {
+ if (type == "async" ||
+ (type == "variable" &&
+ (value == "static" || value == "get" || value == "set" || (isTS && isModifier(value))) &&
+ cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false))) {
+ cx.marked = "keyword";
+ return cont(classBody);
+ }
+ if (type == "variable" || cx.style == "keyword") {
+ cx.marked = "property";
+ return cont(isTS ? classfield : functiondef, classBody);
+ }
+ if (type == "number" || type == "string") return cont(isTS ? classfield : functiondef, classBody);
+ if (type == "[")
+ return cont(expression, maybetype, expect("]"), isTS ? classfield : functiondef, classBody)
+ if (value == "*") {
+ cx.marked = "keyword";
+ return cont(classBody);
+ }
+ if (isTS && type == "(") return pass(functiondecl, classBody)
+ if (type == ";" || type == ",") return cont(classBody);
+ if (type == "}") return cont();
+ if (value == "@") return cont(expression, classBody)
+ }
+ function classfield(type, value) {
+ if (value == "?") return cont(classfield)
+ if (type == ":") return cont(typeexpr, maybeAssign)
+ if (value == "=") return cont(expressionNoComma)
+ var context = cx.state.lexical.prev, isInterface = context && context.info == "interface"
+ return pass(isInterface ? functiondecl : functiondef)
+ }
+ function afterExport(type, value) {
+ if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); }
+ if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); }
+ if (type == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";"));
+ return pass(statement);
+ }
+ function exportField(type, value) {
+ if (value == "as") { cx.marked = "keyword"; return cont(expect("variable")); }
+ if (type == "variable") return pass(expressionNoComma, exportField);
+ }
+ function afterImport(type) {
+ if (type == "string") return cont();
+ if (type == "(") return pass(expression);
+ return pass(importSpec, maybeMoreImports, maybeFrom);
+ }
+ function importSpec(type, value) {
+ if (type == "{") return contCommasep(importSpec, "}");
+ if (type == "variable") register(value);
+ if (value == "*") cx.marked = "keyword";
+ return cont(maybeAs);
+ }
+ function maybeMoreImports(type) {
+ if (type == ",") return cont(importSpec, maybeMoreImports)
+ }
+ function maybeAs(_type, value) {
+ if (value == "as") { cx.marked = "keyword"; return cont(importSpec); }
+ }
+ function maybeFrom(_type, value) {
+ if (value == "from") { cx.marked = "keyword"; return cont(expression); }
+ }
+ function arrayLiteral(type) {
+ if (type == "]") return cont();
+ return pass(commasep(expressionNoComma, "]"));
+ }
+ function enumdef() {
+ return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex)
+ }
+ function enummember() {
+ return pass(pattern, maybeAssign);
+ }
+
+ function isContinuedStatement(state, textAfter) {
+ return state.lastType == "operator" || state.lastType == "," ||
+ isOperatorChar.test(textAfter.charAt(0)) ||
+ /[,.]/.test(textAfter.charAt(0));
+ }
+
+ function expressionAllowed(stream, state, backUp) {
+ return state.tokenize == tokenBase &&
+ /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) ||
+ (state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))))
+ }
+
+ // Interface
+
+ return {
+ startState: function(basecolumn) {
+ var state = {
+ tokenize: tokenBase,
+ lastType: "sof",
+ cc: [],
+ lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
+ localVars: parserConfig.localVars,
+ context: parserConfig.localVars && new Context(null, null, false),
+ indented: basecolumn || 0
+ };
+ if (parserConfig.globalVars && typeof parserConfig.globalVars == "object")
+ state.globalVars = parserConfig.globalVars;
+ return state;
+ },
+
+ token: function(stream, state) {
+ if (stream.sol()) {
+ if (!state.lexical.hasOwnProperty("align"))
+ state.lexical.align = false;
+ state.indented = stream.indentation();
+ findFatArrow(stream, state);
+ }
+ if (state.tokenize != tokenComment && stream.eatSpace()) return null;
+ var style = state.tokenize(stream, state);
+ if (type == "comment") return style;
+ state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type;
+ return parseJS(state, style, type, content, stream);
+ },
+
+ indent: function(state, textAfter) {
+ if (state.tokenize == tokenComment) return CodeMirror.Pass;
+ if (state.tokenize != tokenBase) return 0;
+ var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top
+ // Kludge to prevent 'maybelse' from blocking lexical scope pops
+ if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {
+ var c = state.cc[i];
+ if (c == poplex) lexical = lexical.prev;
+ else if (c != maybeelse) break;
+ }
+ while ((lexical.type == "stat" || lexical.type == "form") &&
+ (firstChar == "}" || ((top = state.cc[state.cc.length - 1]) &&
+ (top == maybeoperatorComma || top == maybeoperatorNoComma) &&
+ !/^[,\.=+\-*:?[\(]/.test(textAfter))))
+ lexical = lexical.prev;
+ if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat")
+ lexical = lexical.prev;
+ var type = lexical.type, closing = firstChar == type;
+
+ if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0);
+ else if (type == "form" && firstChar == "{") return lexical.indented;
+ else if (type == "form") return lexical.indented + indentUnit;
+ else if (type == "stat")
+ return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);
+ else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false)
+ return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
+ else if (lexical.align) return lexical.column + (closing ? 0 : 1);
+ else return lexical.indented + (closing ? 0 : indentUnit);
+ },
+
+ electricInput: /^\s*(?:case .*?:|default:|\{|\})$/,
+ blockCommentStart: jsonMode ? null : "/*",
+ blockCommentEnd: jsonMode ? null : "*/",
+ blockCommentContinue: jsonMode ? null : " * ",
+ lineComment: jsonMode ? null : "//",
+ fold: "brace",
+ closeBrackets: "()[]{}''\"\"``",
+
+ helperType: jsonMode ? "json" : "javascript",
+ jsonldMode: jsonldMode,
+ jsonMode: jsonMode,
+
+ expressionAllowed: expressionAllowed,
+
+ skipExpression: function(state) {
+ var top = state.cc[state.cc.length - 1]
+ if (top == expression || top == expressionNoComma) state.cc.pop()
+ }
+ };
+});
+
+CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/);
+
+CodeMirror.defineMIME("text/javascript", "javascript");
+CodeMirror.defineMIME("text/ecmascript", "javascript");
+CodeMirror.defineMIME("application/javascript", "javascript");
+CodeMirror.defineMIME("application/x-javascript", "javascript");
+CodeMirror.defineMIME("application/ecmascript", "javascript");
+CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
+CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true});
+CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true});
+CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true });
+CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });
+
+});
diff --git a/core/vendor/codemirror/mode/xml.js b/core/vendor/codemirror/mode/xml.js
new file mode 100644
index 00000000..73c6e0e0
--- /dev/null
+++ b/core/vendor/codemirror/mode/xml.js
@@ -0,0 +1,413 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("../../lib/codemirror"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+"use strict";
+
+var htmlConfig = {
+ autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
+ 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
+ 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
+ 'track': true, 'wbr': true, 'menuitem': true},
+ implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
+ 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
+ 'th': true, 'tr': true},
+ contextGrabbers: {
+ 'dd': {'dd': true, 'dt': true},
+ 'dt': {'dd': true, 'dt': true},
+ 'li': {'li': true},
+ 'option': {'option': true, 'optgroup': true},
+ 'optgroup': {'optgroup': true},
+ 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
+ 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
+ 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
+ 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
+ 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
+ 'rp': {'rp': true, 'rt': true},
+ 'rt': {'rp': true, 'rt': true},
+ 'tbody': {'tbody': true, 'tfoot': true},
+ 'td': {'td': true, 'th': true},
+ 'tfoot': {'tbody': true},
+ 'th': {'td': true, 'th': true},
+ 'thead': {'tbody': true, 'tfoot': true},
+ 'tr': {'tr': true}
+ },
+ doNotIndent: {"pre": true},
+ allowUnquoted: true,
+ allowMissing: true,
+ caseFold: true
+}
+
+var xmlConfig = {
+ autoSelfClosers: {},
+ implicitlyClosed: {},
+ contextGrabbers: {},
+ doNotIndent: {},
+ allowUnquoted: false,
+ allowMissing: false,
+ allowMissingTagName: false,
+ caseFold: false
+}
+
+CodeMirror.defineMode("xml", function(editorConf, config_) {
+ var indentUnit = editorConf.indentUnit
+ var config = {}
+ var defaults = config_.htmlMode ? htmlConfig : xmlConfig
+ for (var prop in defaults) config[prop] = defaults[prop]
+ for (var prop in config_) config[prop] = config_[prop]
+
+ // Return variables for tokenizers
+ var type, setStyle;
+
+ function inText(stream, state) {
+ function chain(parser) {
+ state.tokenize = parser;
+ return parser(stream, state);
+ }
+
+ var ch = stream.next();
+ if (ch == "<") {
+ if (stream.eat("!")) {
+ if (stream.eat("[")) {
+ if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
+ else return null;
+ } else if (stream.match("--")) {
+ return chain(inBlock("comment", "-->"));
+ } else if (stream.match("DOCTYPE", true, true)) {
+ stream.eatWhile(/[\w\._\-]/);
+ return chain(doctype(1));
+ } else {
+ return null;
+ }
+ } else if (stream.eat("?")) {
+ stream.eatWhile(/[\w\._\-]/);
+ state.tokenize = inBlock("meta", "?>");
+ return "meta";
+ } else {
+ type = stream.eat("/") ? "closeTag" : "openTag";
+ state.tokenize = inTag;
+ return "tag bracket";
+ }
+ } else if (ch == "&") {
+ var ok;
+ if (stream.eat("#")) {
+ if (stream.eat("x")) {
+ ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
+ } else {
+ ok = stream.eatWhile(/[\d]/) && stream.eat(";");
+ }
+ } else {
+ ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
+ }
+ return ok ? "atom" : "error";
+ } else {
+ stream.eatWhile(/[^&<]/);
+ return null;
+ }
+ }
+ inText.isInText = true;
+
+ function inTag(stream, state) {
+ var ch = stream.next();
+ if (ch == ">" || (ch == "/" && stream.eat(">"))) {
+ state.tokenize = inText;
+ type = ch == ">" ? "endTag" : "selfcloseTag";
+ return "tag bracket";
+ } else if (ch == "=") {
+ type = "equals";
+ return null;
+ } else if (ch == "<") {
+ state.tokenize = inText;
+ state.state = baseState;
+ state.tagName = state.tagStart = null;
+ var next = state.tokenize(stream, state);
+ return next ? next + " tag error" : "tag error";
+ } else if (/[\'\"]/.test(ch)) {
+ state.tokenize = inAttribute(ch);
+ state.stringStartCol = stream.column();
+ return state.tokenize(stream, state);
+ } else {
+ stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
+ return "word";
+ }
+ }
+
+ function inAttribute(quote) {
+ var closure = function(stream, state) {
+ while (!stream.eol()) {
+ if (stream.next() == quote) {
+ state.tokenize = inTag;
+ break;
+ }
+ }
+ return "string";
+ };
+ closure.isInAttribute = true;
+ return closure;
+ }
+
+ function inBlock(style, terminator) {
+ return function(stream, state) {
+ while (!stream.eol()) {
+ if (stream.match(terminator)) {
+ state.tokenize = inText;
+ break;
+ }
+ stream.next();
+ }
+ return style;
+ }
+ }
+
+ function doctype(depth) {
+ return function(stream, state) {
+ var ch;
+ while ((ch = stream.next()) != null) {
+ if (ch == "<") {
+ state.tokenize = doctype(depth + 1);
+ return state.tokenize(stream, state);
+ } else if (ch == ">") {
+ if (depth == 1) {
+ state.tokenize = inText;
+ break;
+ } else {
+ state.tokenize = doctype(depth - 1);
+ return state.tokenize(stream, state);
+ }
+ }
+ }
+ return "meta";
+ };
+ }
+
+ function Context(state, tagName, startOfLine) {
+ this.prev = state.context;
+ this.tagName = tagName;
+ this.indent = state.indented;
+ this.startOfLine = startOfLine;
+ if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))
+ this.noIndent = true;
+ }
+ function popContext(state) {
+ if (state.context) state.context = state.context.prev;
+ }
+ function maybePopContext(state, nextTagName) {
+ var parentTagName;
+ while (true) {
+ if (!state.context) {
+ return;
+ }
+ parentTagName = state.context.tagName;
+ if (!config.contextGrabbers.hasOwnProperty(parentTagName) ||
+ !config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
+ return;
+ }
+ popContext(state);
+ }
+ }
+
+ function baseState(type, stream, state) {
+ if (type == "openTag") {
+ state.tagStart = stream.column();
+ return tagNameState;
+ } else if (type == "closeTag") {
+ return closeTagNameState;
+ } else {
+ return baseState;
+ }
+ }
+ function tagNameState(type, stream, state) {
+ if (type == "word") {
+ state.tagName = stream.current();
+ setStyle = "tag";
+ return attrState;
+ } else if (config.allowMissingTagName && type == "endTag") {
+ setStyle = "tag bracket";
+ return attrState(type, stream, state);
+ } else {
+ setStyle = "error";
+ return tagNameState;
+ }
+ }
+ function closeTagNameState(type, stream, state) {
+ if (type == "word") {
+ var tagName = stream.current();
+ if (state.context && state.context.tagName != tagName &&
+ config.implicitlyClosed.hasOwnProperty(state.context.tagName))
+ popContext(state);
+ if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) {
+ setStyle = "tag";
+ return closeState;
+ } else {
+ setStyle = "tag error";
+ return closeStateErr;
+ }
+ } else if (config.allowMissingTagName && type == "endTag") {
+ setStyle = "tag bracket";
+ return closeState(type, stream, state);
+ } else {
+ setStyle = "error";
+ return closeStateErr;
+ }
+ }
+
+ function closeState(type, _stream, state) {
+ if (type != "endTag") {
+ setStyle = "error";
+ return closeState;
+ }
+ popContext(state);
+ return baseState;
+ }
+ function closeStateErr(type, stream, state) {
+ setStyle = "error";
+ return closeState(type, stream, state);
+ }
+
+ function attrState(type, _stream, state) {
+ if (type == "word") {
+ setStyle = "attribute";
+ return attrEqState;
+ } else if (type == "endTag" || type == "selfcloseTag") {
+ var tagName = state.tagName, tagStart = state.tagStart;
+ state.tagName = state.tagStart = null;
+ if (type == "selfcloseTag" ||
+ config.autoSelfClosers.hasOwnProperty(tagName)) {
+ maybePopContext(state, tagName);
+ } else {
+ maybePopContext(state, tagName);
+ state.context = new Context(state, tagName, tagStart == state.indented);
+ }
+ return baseState;
+ }
+ setStyle = "error";
+ return attrState;
+ }
+ function attrEqState(type, stream, state) {
+ if (type == "equals") return attrValueState;
+ if (!config.allowMissing) setStyle = "error";
+ return attrState(type, stream, state);
+ }
+ function attrValueState(type, stream, state) {
+ if (type == "string") return attrContinuedState;
+ if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;}
+ setStyle = "error";
+ return attrState(type, stream, state);
+ }
+ function attrContinuedState(type, stream, state) {
+ if (type == "string") return attrContinuedState;
+ return attrState(type, stream, state);
+ }
+
+ return {
+ startState: function(baseIndent) {
+ var state = {tokenize: inText,
+ state: baseState,
+ indented: baseIndent || 0,
+ tagName: null, tagStart: null,
+ context: null}
+ if (baseIndent != null) state.baseIndent = baseIndent
+ return state
+ },
+
+ token: function(stream, state) {
+ if (!state.tagName && stream.sol())
+ state.indented = stream.indentation();
+
+ if (stream.eatSpace()) return null;
+ type = null;
+ var style = state.tokenize(stream, state);
+ if ((style || type) && style != "comment") {
+ setStyle = null;
+ state.state = state.state(type || style, stream, state);
+ if (setStyle)
+ style = setStyle == "error" ? style + " error" : setStyle;
+ }
+ return style;
+ },
+
+ indent: function(state, textAfter, fullLine) {
+ var context = state.context;
+ // Indent multi-line strings (e.g. css).
+ if (state.tokenize.isInAttribute) {
+ if (state.tagStart == state.indented)
+ return state.stringStartCol + 1;
+ else
+ return state.indented + indentUnit;
+ }
+ if (context && context.noIndent) return CodeMirror.Pass;
+ if (state.tokenize != inTag && state.tokenize != inText)
+ return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
+ // Indent the starts of attribute names.
+ if (state.tagName) {
+ if (config.multilineTagIndentPastTag !== false)
+ return state.tagStart + state.tagName.length + 2;
+ else
+ return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1);
+ }
+ if (config.alignCDATA && /$/,
+ blockCommentStart: "",
+
+ configuration: config.htmlMode ? "html" : "xml",
+ helperType: config.htmlMode ? "html" : "xml",
+
+ skipAttribute: function(state) {
+ if (state.state == attrValueState)
+ state.state = attrState
+ },
+
+ xmlCurrentTag: function(state) {
+ return state.tagName ? {name: state.tagName, close: state.type == "closeTag"} : null
+ },
+
+ xmlCurrentContext: function(state) {
+ var context = []
+ for (var cx = state.context; cx; cx = cx.prev)
+ if (cx.tagName) context.push(cx.tagName)
+ return context.reverse()
+ }
+ };
+});
+
+CodeMirror.defineMIME("text/xml", "xml");
+CodeMirror.defineMIME("application/xml", "xml");
+if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
+ CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
+
+});
diff --git a/core/vendor/filemanager/__UploadHandler.php b/core/vendor/filemanager/__UploadHandler.php
new file mode 100644
index 00000000..e3075448
--- /dev/null
+++ b/core/vendor/filemanager/__UploadHandler.php
@@ -0,0 +1,1595 @@
+ 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
+ 2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
+ 3 => 'The uploaded file was only partially uploaded',
+ 4 => 'No file was uploaded',
+ 6 => 'Missing a temporary folder',
+ 7 => 'Failed to write file to disk',
+ 8 => 'A PHP extension stopped the file upload',
+ 'post_max_size' => 'The uploaded file exceeds the post_max_size directive in php.ini',
+ 'max_file_size' => 'File is too big',
+ 'min_file_size' => 'File is too small',
+ 'accept_file_types' => 'Filetype not allowed',
+ 'max_number_of_files' => 'Maximum number of files exceeded',
+ 'max_width' => 'Image exceeds maximum width',
+ 'min_width' => 'Image requires a minimum width',
+ 'max_height' => 'Image exceeds maximum height',
+ 'min_height' => 'Image requires a minimum height',
+ 'abort' => 'File upload aborted',
+ 'image_resize' => 'Failed to resize image'
+ );
+
+ const IMAGETYPE_GIF = 1;
+ const IMAGETYPE_JPEG = 2;
+ const IMAGETYPE_PNG = 3;
+
+ protected $image_objects = array();
+
+ public function __construct($options = null, $initialize = true, $error_messages = null) {
+ $this->response = array();
+ $this->options = array(
+ 'script_url' => $this->get_full_url().'/'.$this->basename($this->get_server_var('SCRIPT_NAME')),
+ 'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'/files/',
+ 'upload_url' => $this->get_full_url().'/files/',
+ 'input_stream' => 'php://input',
+ 'user_dirs' => false,
+ 'mkdir_mode' => 0755,
+ 'param_name' => 'files',
+ // Set the following option to 'POST', if your server does not support
+ // DELETE requests. This is a parameter sent to the client:
+ 'delete_type' => 'DELETE',
+ 'access_control_allow_origin' => '*',
+ 'access_control_allow_credentials' => false,
+ 'access_control_allow_methods' => array(
+ 'OPTIONS',
+ 'HEAD',
+ 'GET',
+ 'POST',
+ 'PUT',
+ 'PATCH',
+ 'DELETE'
+ ),
+ 'access_control_allow_headers' => array(
+ 'Content-Type',
+ 'Content-Range',
+ 'Content-Disposition'
+ ),
+ // By default, allow redirects to the referer protocol+host:
+ 'redirect_allow_target' => '/^'.preg_quote(
+ parse_url($this->get_server_var('HTTP_REFERER'), PHP_URL_SCHEME)
+ .'://'
+ .parse_url($this->get_server_var('HTTP_REFERER'), PHP_URL_HOST)
+ .'/', // Trailing slash to not match subdomains by mistake
+ '/' // preg_quote delimiter param
+ ).'/',
+ // Enable to provide file downloads via GET requests to the PHP script:
+ // 1. Set to 1 to download files via readfile method through PHP
+ // 2. Set to 2 to send a X-Sendfile header for lighttpd/Apache
+ // 3. Set to 3 to send a X-Accel-Redirect header for nginx
+ // If set to 2 or 3, adjust the upload_url option to the base path of
+ // the redirect parameter, e.g. '/files/'.
+ 'download_via_php' => false,
+ // Read files in chunks to avoid memory limits when download_via_php
+ // is enabled, set to 0 to disable chunked reading of files:
+ 'readfile_chunk_size' => 10 * 1024 * 1024, // 10 MiB
+ // Defines which files can be displayed inline when downloaded:
+ 'inline_file_types' => '/\.(gif|jpe?g|png)$/i',
+ // Defines which files (based on their names) are accepted for upload.
+ // By default, only allows file uploads with image file extensions.
+ // Only change this setting after making sure that any allowed file
+ // types cannot be executed by the webserver in the files directory,
+ // e.g. PHP scripts, nor executed by the browser when downloaded,
+ // e.g. HTML files with embedded JavaScript code.
+ // Please also read the SECURITY.md document in this repository.
+ 'accept_file_types' => '/\.(gif|jpe?g|png)$/i',
+ // Replaces dots in filenames with the given string.
+ // Can be disabled by setting it to false or an empty string.
+ // Note that this is a security feature for servers that support
+ // multiple file extensions, e.g. the Apache AddHandler Directive:
+ // https://httpd.apache.org/docs/current/mod/mod_mime.html#addhandler
+ // Before disabling it, make sure that files uploaded with multiple
+ // extensions cannot be executed by the webserver, e.g.
+ // "example.php.png" with embedded PHP code, nor executed by the
+ // browser when downloaded, e.g. "example.html.gif" with embedded
+ // JavaScript code.
+ 'replace_dots_in_filenames' => '-',
+ // The php.ini settings upload_max_filesize and post_max_size
+ // take precedence over the following max_file_size setting:
+ 'max_file_size' => null,
+ 'min_file_size' => 1,
+ // The maximum number of files for the upload directory:
+ 'max_number_of_files' => null,
+ // Reads first file bytes to identify and correct file extensions:
+ 'correct_image_extensions' => false,
+ // Image resolution restrictions:
+ 'max_width' => null,
+ 'max_height' => null,
+ 'min_width' => 1,
+ 'min_height' => 1,
+ // Set the following option to false to enable resumable uploads:
+ 'discard_aborted_uploads' => true,
+ // Set to 0 to use the GD library to scale and orient images,
+ // set to 1 to use imagick (if installed, falls back to GD),
+ // set to 2 to use the ImageMagick convert binary directly:
+ 'image_library' => 1,
+ // Uncomment the following to define an array of resource limits
+ // for imagick:
+ /*
+ 'imagick_resource_limits' => array(
+ imagick::RESOURCETYPE_MAP => 32,
+ imagick::RESOURCETYPE_MEMORY => 32
+ ),
+ */
+ // Command or path for to the ImageMagick convert binary:
+ 'convert_bin' => 'convert',
+ // Uncomment the following to add parameters in front of each
+ // ImageMagick convert call (the limit constraints seem only
+ // to have an effect if put in front):
+ /*
+ 'convert_params' => '-limit memory 32MiB -limit map 32MiB',
+ */
+ // Command or path for to the ImageMagick identify binary:
+ 'identify_bin' => 'identify',
+ 'image_versions' => array(
+ // The empty image version key defines options for the original image.
+ // Keep in mind: these image manipulations are inherited by all other image versions from this point onwards.
+ // Also note that the property 'no_cache' is not inherited, since it's not a manipulation.
+ '' => array(
+ // Automatically rotate images based on EXIF meta data:
+ 'auto_orient' => true
+ ),
+ // You can add arrays to generate different versions.
+ // The name of the key is the name of the version (example: 'medium').
+ // the array contains the options to apply.
+ /*
+ 'medium' => array(
+ 'max_width' => 800,
+ 'max_height' => 600
+ ),
+ */
+ //'thumbnail' => array(
+ // Uncomment the following to use a defined directory for the thumbnails
+ // instead of a subdirectory based on the version identifier.
+ // Make sure that this directory doesn't allow execution of files if you
+ // don't pose any restrictions on the type of uploaded files, e.g. by
+ // copying the .htaccess file from the files directory for Apache:
+ //'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'/thumb/',
+ //'upload_url' => $this->get_full_url().'/thumb/',
+ // Uncomment the following to force the max
+ // dimensions and e.g. create square thumbnails:
+ // 'auto_orient' => true,
+ // 'crop' => true,
+ // 'jpeg_quality' => 70,
+ // 'no_cache' => true, (there's a caching option, but this remembers thumbnail sizes from a previous action!)
+ // 'strip' => true, (this strips EXIF tags, such as geolocation)
+ // 'max_width' => 80, // either specify width, or set to 0. Then width is automatically adjusted - keeping aspect ratio to a specified max_height.
+ // 'max_height' => 80 // either specify height, or set to 0. Then height is automatically adjusted - keeping aspect ratio to a specified max_width.
+ // )
+ ),
+ 'print_response' => true
+ );
+ if ($options) {
+ $this->options = $options + $this->options;
+ }
+ if ($error_messages) {
+ $this->error_messages = $error_messages + $this->error_messages;
+ }
+ if ($initialize) {
+ $this->initialize();
+ }
+ }
+
+ protected function initialize() {
+ switch ($this->get_server_var('REQUEST_METHOD')) {
+ case 'OPTIONS':
+ case 'HEAD':
+ $this->head();
+ break;
+ case 'GET':
+ $this->get($this->options['print_response']);
+ break;
+ case 'PATCH':
+ case 'PUT':
+ case 'POST':
+ $this->post($this->options['print_response']);
+ break;
+ case 'DELETE':
+ $this->delete($this->options['print_response']);
+ break;
+ default:
+ $this->header('HTTP/1.1 405 Method Not Allowed');
+ }
+ }
+
+ protected function get_full_url() {
+ $https = !empty($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'], 'on') === 0 ||
+ !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
+ strcasecmp($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') === 0;
+ return
+ ($https ? 'https://' : 'http://').
+ (!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
+ (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
+ ($https && $_SERVER['SERVER_PORT'] === 443 ||
+ $_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
+ substr($_SERVER['SCRIPT_NAME'],0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
+ }
+
+ protected function get_user_id() {
+ @session_start();
+ return session_id();
+ }
+
+ protected function get_user_path() {
+ if ($this->options['user_dirs']) {
+ return $this->get_user_id().'/';
+ }
+ return '';
+ }
+
+ protected function get_upload_path($file_name = null, $version = null) {
+ $file_name = $file_name ? $file_name : '';
+ if (empty($version)) {
+ $version_path = '';
+ } else {
+ $version_dir = @$this->options['image_versions'][$version]['upload_dir'];
+ if ($version_dir) {
+ return $version_dir.$this->get_user_path().$file_name;
+ }
+ $version_path = $version.'/';
+ }
+ return $this->options['upload_dir'].$this->get_user_path()
+ .$version_path.$file_name;
+ }
+
+ protected function get_query_separator($url) {
+ return strpos($url, '?') === false ? '?' : '&';
+ }
+
+ protected function get_download_url($file_name, $version = null, $direct = false) {
+ if (!$direct && $this->options['download_via_php']) {
+ $url = $this->options['script_url']
+ .$this->get_query_separator($this->options['script_url'])
+ .$this->get_singular_param_name()
+ .'='.rawurlencode($file_name);
+ if ($version) {
+ $url .= '&version='.rawurlencode($version);
+ }
+ return $url.'&download=1';
+ }
+ if (empty($version)) {
+ $version_path = '';
+ } else {
+ $version_url = @$this->options['image_versions'][$version]['upload_url'];
+ if ($version_url) {
+ return $version_url.$this->get_user_path().rawurlencode($file_name);
+ }
+ $version_path = rawurlencode($version).'/';
+ }
+ return $this->options['upload_url'].$this->get_user_path()
+ .$version_path.rawurlencode($file_name);
+ }
+
+ protected function set_additional_file_properties($file) {
+ $file->deleteUrl = $this->options['script_url']
+ .$this->get_query_separator($this->options['script_url'])
+ .$this->get_singular_param_name()
+ .'='.rawurlencode($file->name);
+ $file->deleteType = $this->options['delete_type'];
+ if ($file->deleteType !== 'DELETE') {
+ $file->deleteUrl .= '&_method=DELETE';
+ }
+ if ($this->options['access_control_allow_credentials']) {
+ $file->deleteWithCredentials = true;
+ }
+ }
+
+ // Fix for overflowing signed 32 bit integers,
+ // works for sizes up to 2^32-1 bytes (4 GiB - 1):
+ protected function fix_integer_overflow($size) {
+ if ($size < 0) {
+ $size += 2.0 * (PHP_INT_MAX + 1);
+ }
+ return $size;
+ }
+
+ protected function get_file_size($file_path, $clear_stat_cache = false) {
+ if ($clear_stat_cache) {
+ if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
+ clearstatcache(true, $file_path);
+ } else {
+ clearstatcache();
+ }
+ }
+ return $this->fix_integer_overflow(filesize($file_path));
+ }
+
+ protected function is_valid_file_object($file_name) {
+ $file_path = $this->get_upload_path($file_name);
+ if (is_file($file_path) && $file_name[0] !== '.') {
+ return true;
+ }
+ return false;
+ }
+
+ protected function get_file_object($file_name) {
+ if ($this->is_valid_file_object($file_name)) {
+ $file = new \stdClass();
+ $file->name = $file_name;
+ $file->size = $this->get_file_size(
+ $this->get_upload_path($file_name)
+ );
+ $file->url = $this->get_download_url($file->name);
+ foreach ($this->options['image_versions'] as $version => $options) {
+ if (!empty($version)) {
+ if (is_file($this->get_upload_path($file_name, $version))) {
+ $file->{$version.'Url'} = $this->get_download_url(
+ $file->name,
+ $version
+ );
+ }
+ }
+ }
+ $this->set_additional_file_properties($file);
+ return $file;
+ }
+ return null;
+ }
+
+ protected function get_file_objects($iteration_method = 'get_file_object') {
+ $upload_dir = $this->get_upload_path();
+ if (!is_dir($upload_dir)) {
+ return array();
+ }
+ return array_values(array_filter(array_map(
+ array($this, $iteration_method),
+ scandir($upload_dir)
+ )));
+ }
+
+ protected function count_file_objects() {
+ return count($this->get_file_objects('is_valid_file_object'));
+ }
+
+ protected function get_error_message($error) {
+ return isset($this->error_messages[$error]) ?
+ $this->error_messages[$error] : $error;
+ }
+
+ public function get_config_bytes($val) {
+ $val = trim($val);
+ $last = strtolower($val[strlen($val)-1]);
+ $val = (int)$val;
+ switch ($last) {
+ case 'g':
+ $val *= 1024;
+ case 'm':
+ $val *= 1024;
+ case 'k':
+ $val *= 1024;
+ }
+ return $this->fix_integer_overflow($val);
+ }
+
+ protected function validate($uploaded_file, $file, $error, $index) {
+ if ($error) {
+ $file->error = $this->get_error_message($error);
+ return false;
+ }
+ $content_length = $this->fix_integer_overflow(
+ (int)$this->get_server_var('CONTENT_LENGTH')
+ );
+ $post_max_size = $this->get_config_bytes(ini_get('post_max_size'));
+ if ($post_max_size && ($content_length > $post_max_size)) {
+ $file->error = $this->get_error_message('post_max_size');
+ return false;
+ }
+ if (!preg_match($this->options['accept_file_types'], $file->name)) {
+ $file->error = $this->get_error_message('accept_file_types');
+ return false;
+ }
+ if ($uploaded_file && is_uploaded_file($uploaded_file)) {
+ $file_size = $this->get_file_size($uploaded_file);
+ } else {
+ $file_size = $content_length;
+ }
+ if ($this->options['max_file_size'] && (
+ $file_size > $this->options['max_file_size'] ||
+ $file->size > $this->options['max_file_size'])
+ ) {
+ $file->error = $this->get_error_message('max_file_size');
+ return false;
+ }
+ if ($this->options['min_file_size'] &&
+ $file_size < $this->options['min_file_size']) {
+ $file->error = $this->get_error_message('min_file_size');
+ return false;
+ }
+ if (is_int($this->options['max_number_of_files']) &&
+ ($this->count_file_objects() >= $this->options['max_number_of_files']) &&
+ // Ignore additional chunks of existing files:
+ !is_file($this->get_upload_path($file->name))) {
+ $file->error = $this->get_error_message('max_number_of_files');
+ return false;
+ }
+ $max_width = @$this->options['max_width'];
+ $max_height = @$this->options['max_height'];
+ $min_width = @$this->options['min_width'];
+ $min_height = @$this->options['min_height'];
+ if (($max_width || $max_height || $min_width || $min_height)
+ && $this->is_valid_image_file($uploaded_file)) {
+ list($img_width, $img_height) = $this->get_image_size($uploaded_file);
+ // If we are auto rotating the image by default, do the checks on
+ // the correct orientation
+ if (
+ @$this->options['image_versions']['']['auto_orient'] &&
+ function_exists('exif_read_data') &&
+ ($exif = @exif_read_data($uploaded_file)) &&
+ (((int) @$exif['Orientation']) >= 5)
+ ) {
+ $tmp = $img_width;
+ $img_width = $img_height;
+ $img_height = $tmp;
+ unset($tmp);
+ }
+ }
+ if (!empty($img_width)) {
+ if ($max_width && $img_width > $max_width) {
+ $file->error = $this->get_error_message('max_width');
+ return false;
+ }
+ if ($max_height && $img_height > $max_height) {
+ $file->error = $this->get_error_message('max_height');
+ return false;
+ }
+ if ($min_width && $img_width < $min_width) {
+ $file->error = $this->get_error_message('min_width');
+ return false;
+ }
+ if ($min_height && $img_height < $min_height) {
+ $file->error = $this->get_error_message('min_height');
+ return false;
+ }
+ }
+ return true;
+ }
+
+ protected function upcount_name_callback($matches) {
+ $index = isset($matches[1]) ? ((int)$matches[1]) + 1 : 1;
+ $ext = isset($matches[2]) ? $matches[2] : '';
+ return ' ('.$index.')'.$ext;
+ }
+
+ protected function upcount_name($name) {
+ return preg_replace_callback(
+ '/(?:(?: \(([\d]+)\))?(\.[^.]+))?$/',
+ array($this, 'upcount_name_callback'),
+ $name,
+ 1
+ );
+ }
+
+ protected function get_unique_filename($file_path, $name, $size, $type, $error,
+ $index, $content_range) {
+ while(is_dir($this->get_upload_path($name))) {
+ $name = $this->upcount_name($name);
+ }
+ // Keep an existing filename if this is part of a chunked upload:
+ $uploaded_bytes = $this->fix_integer_overflow((int)$content_range[1]);
+ while (is_file($this->get_upload_path($name))) {
+ if ($uploaded_bytes === $this->get_file_size(
+ $this->get_upload_path($name))) {
+ break;
+ }
+ $name = $this->upcount_name($name);
+ }
+ return $name;
+ }
+
+ protected function fix_file_extension($file_path, $name, $size, $type, $error,
+ $index, $content_range) {
+ // Add missing file extension for known image types:
+ if (strpos($name, '.') === false &&
+ preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) {
+ $name .= '.'.$matches[1];
+ }
+ if ($this->options['correct_image_extensions']) {
+ switch ($this->imagetype($file_path)) {
+ case self::IMAGETYPE_JPEG:
+ $extensions = array('jpg', 'jpeg');
+ break;
+ case self::IMAGETYPE_PNG:
+ $extensions = array('png');
+ break;
+ case self::IMAGETYPE_GIF:
+ $extensions = array('gif');
+ break;
+ }
+ // Adjust incorrect image file extensions:
+ if (!empty($extensions)) {
+ $parts = explode('.', $name);
+ $extIndex = count($parts) - 1;
+ $ext = strtolower(@$parts[$extIndex]);
+ if (!in_array($ext, $extensions)) {
+ $parts[$extIndex] = $extensions[0];
+ $name = implode('.', $parts);
+ }
+ }
+ }
+ return $name;
+ }
+
+ protected function trim_file_name($file_path, $name, $size, $type, $error,
+ $index, $content_range) {
+ // Remove path information and dots around the filename, to prevent uploading
+ // into different directories or replacing hidden system files.
+ // Also remove control characters and spaces (\x00..\x20) around the filename:
+ $name = trim($this->basename(stripslashes($name)), ".\x00..\x20");
+ // Replace dots in filenames to avoid security issues with servers
+ // that interpret multiple file extensions, e.g. "example.php.png":
+ $replacement = $this->options['replace_dots_in_filenames'];
+ if (!empty($replacement)) {
+ $parts = explode('.', $name);
+ if (count($parts) > 2) {
+ $ext = array_pop($parts);
+ $name = implode($replacement, $parts).'.'.$ext;
+ }
+ }
+ // Use a timestamp for empty filenames:
+ if (!$name) {
+ $name = str_replace('.', '-', microtime(true));
+ }
+ return $name;
+ }
+
+ protected function get_file_name($file_path, $name, $size, $type, $error,
+ $index, $content_range) {
+ $name = $this->trim_file_name($file_path, $name, $size, $type, $error,
+ $index, $content_range);
+ return $this->get_unique_filename(
+ $file_path,
+ $this->fix_file_extension($file_path, $name, $size, $type, $error,
+ $index, $content_range),
+ $size,
+ $type,
+ $error,
+ $index,
+ $content_range
+ );
+ }
+
+ protected function get_scaled_image_file_paths($file_name, $version) {
+ $file_path = $this->get_upload_path($file_name);
+ if (!empty($version)) {
+ $version_dir = $this->get_upload_path(null, $version);
+ if (!is_dir($version_dir)) {
+ mkdir($version_dir, $this->options['mkdir_mode'], true);
+ }
+ $new_file_path = $version_dir.'/'.$file_name;
+ } else {
+ $new_file_path = $file_path;
+ }
+ return array($file_path, $new_file_path);
+ }
+
+ protected function gd_get_image_object($file_path, $func, $no_cache = false) {
+ if (empty($this->image_objects[$file_path]) || $no_cache) {
+ $this->gd_destroy_image_object($file_path);
+ $this->image_objects[$file_path] = $func($file_path);
+ }
+ return $this->image_objects[$file_path];
+ }
+
+ protected function gd_set_image_object($file_path, $image) {
+ $this->gd_destroy_image_object($file_path);
+ $this->image_objects[$file_path] = $image;
+ }
+
+ protected function gd_destroy_image_object($file_path) {
+ $image = (isset($this->image_objects[$file_path])) ? $this->image_objects[$file_path] : null ;
+ return $image && imagedestroy($image);
+ }
+
+ protected function gd_imageflip($image, $mode) {
+ if (function_exists('imageflip')) {
+ return imageflip($image, $mode);
+ }
+ $new_width = $src_width = imagesx($image);
+ $new_height = $src_height = imagesy($image);
+ $new_img = imagecreatetruecolor($new_width, $new_height);
+ $src_x = 0;
+ $src_y = 0;
+ switch ($mode) {
+ case '1': // flip on the horizontal axis
+ $src_y = $new_height - 1;
+ $src_height = -$new_height;
+ break;
+ case '2': // flip on the vertical axis
+ $src_x = $new_width - 1;
+ $src_width = -$new_width;
+ break;
+ case '3': // flip on both axes
+ $src_y = $new_height - 1;
+ $src_height = -$new_height;
+ $src_x = $new_width - 1;
+ $src_width = -$new_width;
+ break;
+ default:
+ return $image;
+ }
+ imagecopyresampled(
+ $new_img,
+ $image,
+ 0,
+ 0,
+ $src_x,
+ $src_y,
+ $new_width,
+ $new_height,
+ $src_width,
+ $src_height
+ );
+ return $new_img;
+ }
+
+ protected function gd_orient_image($file_path, $src_img) {
+ if (!function_exists('exif_read_data')) {
+ return false;
+ }
+ $exif = @exif_read_data($file_path);
+ if ($exif === false) {
+ return false;
+ }
+ $orientation = (int)@$exif['Orientation'];
+ if ($orientation < 2 || $orientation > 8) {
+ return false;
+ }
+ switch ($orientation) {
+ case 2:
+ $new_img = $this->gd_imageflip(
+ $src_img,
+ defined('IMG_FLIP_VERTICAL') ? IMG_FLIP_VERTICAL : 2
+ );
+ break;
+ case 3:
+ $new_img = imagerotate($src_img, 180, 0);
+ break;
+ case 4:
+ $new_img = $this->gd_imageflip(
+ $src_img,
+ defined('IMG_FLIP_HORIZONTAL') ? IMG_FLIP_HORIZONTAL : 1
+ );
+ break;
+ case 5:
+ $tmp_img = $this->gd_imageflip(
+ $src_img,
+ defined('IMG_FLIP_HORIZONTAL') ? IMG_FLIP_HORIZONTAL : 1
+ );
+ $new_img = imagerotate($tmp_img, 270, 0);
+ imagedestroy($tmp_img);
+ break;
+ case 6:
+ $new_img = imagerotate($src_img, 270, 0);
+ break;
+ case 7:
+ $tmp_img = $this->gd_imageflip(
+ $src_img,
+ defined('IMG_FLIP_VERTICAL') ? IMG_FLIP_VERTICAL : 2
+ );
+ $new_img = imagerotate($tmp_img, 270, 0);
+ imagedestroy($tmp_img);
+ break;
+ case 8:
+ $new_img = imagerotate($src_img, 90, 0);
+ break;
+ default:
+ return false;
+ }
+ $this->gd_set_image_object($file_path, $new_img);
+ return true;
+ }
+
+ protected function gd_create_scaled_image($file_name, $version, $options) {
+ if (!function_exists('imagecreatetruecolor')) {
+ error_log('Function not found: imagecreatetruecolor');
+ return false;
+ }
+ list($file_path, $new_file_path) =
+ $this->get_scaled_image_file_paths($file_name, $version);
+ $type = strtolower(substr(strrchr($file_name, '.'), 1));
+ switch ($type) {
+ case 'jpg':
+ case 'jpeg':
+ $src_func = 'imagecreatefromjpeg';
+ $write_func = 'imagejpeg';
+ $image_quality = isset($options['jpeg_quality']) ?
+ $options['jpeg_quality'] : 75;
+ break;
+ case 'gif':
+ $src_func = 'imagecreatefromgif';
+ $write_func = 'imagegif';
+ $image_quality = null;
+ break;
+ case 'png':
+ $src_func = 'imagecreatefrompng';
+ $write_func = 'imagepng';
+ $image_quality = isset($options['png_quality']) ?
+ $options['png_quality'] : 9;
+ break;
+ default:
+ return false;
+ }
+ $src_img = $this->gd_get_image_object(
+ $file_path,
+ $src_func,
+ !empty($options['no_cache'])
+ );
+ $image_oriented = false;
+ if (!empty($options['auto_orient']) && $this->gd_orient_image(
+ $file_path,
+ $src_img
+ )) {
+ $image_oriented = true;
+ $src_img = $this->gd_get_image_object(
+ $file_path,
+ $src_func
+ );
+ }
+ $max_width = $img_width = imagesx($src_img);
+ $max_height = $img_height = imagesy($src_img);
+ if (!empty($options['max_width'])) {
+ $max_width = $options['max_width'];
+ }
+ if (!empty($options['max_height'])) {
+ $max_height = $options['max_height'];
+ }
+ $scale = min(
+ $max_width / $img_width,
+ $max_height / $img_height
+ );
+ if ($scale >= 1) {
+ if ($image_oriented) {
+ return $write_func($src_img, $new_file_path, $image_quality);
+ }
+ if ($file_path !== $new_file_path) {
+ return copy($file_path, $new_file_path);
+ }
+ return true;
+ }
+ if (empty($options['crop'])) {
+ $new_width = $img_width * $scale;
+ $new_height = $img_height * $scale;
+ $dst_x = 0;
+ $dst_y = 0;
+ $new_img = imagecreatetruecolor($new_width, $new_height);
+ } else {
+ if (($img_width / $img_height) >= ($max_width / $max_height)) {
+ $new_width = $img_width / ($img_height / $max_height);
+ $new_height = $max_height;
+ } else {
+ $new_width = $max_width;
+ $new_height = $img_height / ($img_width / $max_width);
+ }
+ $dst_x = 0 - ($new_width - $max_width) / 2;
+ $dst_y = 0 - ($new_height - $max_height) / 2;
+ $new_img = imagecreatetruecolor($max_width, $max_height);
+ }
+ // Handle transparency in GIF and PNG images:
+ switch ($type) {
+ case 'gif':
+ case 'png':
+ imagecolortransparent($new_img, imagecolorallocate($new_img, 0, 0, 0));
+ case 'png':
+ imagealphablending($new_img, false);
+ imagesavealpha($new_img, true);
+ break;
+ }
+ $success = imagecopyresampled(
+ $new_img,
+ $src_img,
+ $dst_x,
+ $dst_y,
+ 0,
+ 0,
+ $new_width,
+ $new_height,
+ $img_width,
+ $img_height
+ ) && $write_func($new_img, $new_file_path, $image_quality);
+ $this->gd_set_image_object($file_path, $new_img);
+ return $success;
+ }
+
+ protected function imagick_get_image_object($file_path, $no_cache = false) {
+ if (empty($this->image_objects[$file_path]) || $no_cache) {
+ $this->imagick_destroy_image_object($file_path);
+ $image = new \Imagick();
+ if (!empty($this->options['imagick_resource_limits'])) {
+ foreach ($this->options['imagick_resource_limits'] as $type => $limit) {
+ $image->setResourceLimit($type, $limit);
+ }
+ }
+ $image->readImage($file_path);
+ $this->image_objects[$file_path] = $image;
+ }
+ return $this->image_objects[$file_path];
+ }
+
+ protected function imagick_set_image_object($file_path, $image) {
+ $this->imagick_destroy_image_object($file_path);
+ $this->image_objects[$file_path] = $image;
+ }
+
+ protected function imagick_destroy_image_object($file_path) {
+ $image = (isset($this->image_objects[$file_path])) ? $this->image_objects[$file_path] : null ;
+ return $image && $image->destroy();
+ }
+
+ protected function imagick_orient_image($image) {
+ $orientation = $image->getImageOrientation();
+ $background = new \ImagickPixel('none');
+ switch ($orientation) {
+ case \imagick::ORIENTATION_TOPRIGHT: // 2
+ $image->flopImage(); // horizontal flop around y-axis
+ break;
+ case \imagick::ORIENTATION_BOTTOMRIGHT: // 3
+ $image->rotateImage($background, 180);
+ break;
+ case \imagick::ORIENTATION_BOTTOMLEFT: // 4
+ $image->flipImage(); // vertical flip around x-axis
+ break;
+ case \imagick::ORIENTATION_LEFTTOP: // 5
+ $image->flopImage(); // horizontal flop around y-axis
+ $image->rotateImage($background, 270);
+ break;
+ case \imagick::ORIENTATION_RIGHTTOP: // 6
+ $image->rotateImage($background, 90);
+ break;
+ case \imagick::ORIENTATION_RIGHTBOTTOM: // 7
+ $image->flipImage(); // vertical flip around x-axis
+ $image->rotateImage($background, 270);
+ break;
+ case \imagick::ORIENTATION_LEFTBOTTOM: // 8
+ $image->rotateImage($background, 270);
+ break;
+ default:
+ return false;
+ }
+ $image->setImageOrientation(\imagick::ORIENTATION_TOPLEFT); // 1
+ return true;
+ }
+
+ protected function imagick_create_scaled_image($file_name, $version, $options) {
+ list($file_path, $new_file_path) =
+ $this->get_scaled_image_file_paths($file_name, $version);
+ $image = $this->imagick_get_image_object(
+ $file_path,
+ !empty($options['crop']) || !empty($options['no_cache'])
+ );
+ if ($image->getImageFormat() === 'GIF') {
+ // Handle animated GIFs:
+ $images = $image->coalesceImages();
+ foreach ($images as $frame) {
+ $image = $frame;
+ $this->imagick_set_image_object($file_name, $image);
+ break;
+ }
+ }
+ $image_oriented = false;
+ if (!empty($options['auto_orient'])) {
+ $image_oriented = $this->imagick_orient_image($image);
+ }
+
+ $image_resize = false;
+ $new_width = $max_width = $img_width = $image->getImageWidth();
+ $new_height = $max_height = $img_height = $image->getImageHeight();
+
+ // use isset(). User might be setting max_width = 0 (auto in regular resizing). Value 0 would be considered empty when you use empty()
+ if (isset($options['max_width'])) {
+ $image_resize = true;
+ $new_width = $max_width = $options['max_width'];
+ }
+ if (isset($options['max_height'])) {
+ $image_resize = true;
+ $new_height = $max_height = $options['max_height'];
+ }
+
+ $image_strip = (isset($options['strip']) ? $options['strip'] : false);
+
+ if ( !$image_oriented && ($max_width >= $img_width) && ($max_height >= $img_height) && !$image_strip && empty($options["jpeg_quality"]) ) {
+ if ($file_path !== $new_file_path) {
+ return copy($file_path, $new_file_path);
+ }
+ return true;
+ }
+ $crop = (isset($options['crop']) ? $options['crop'] : false);
+
+ if ($crop) {
+ $x = 0;
+ $y = 0;
+ if (($img_width / $img_height) >= ($max_width / $max_height)) {
+ $new_width = 0; // Enables proportional scaling based on max_height
+ $x = ($img_width / ($img_height / $max_height) - $max_width) / 2;
+ } else {
+ $new_height = 0; // Enables proportional scaling based on max_width
+ $y = ($img_height / ($img_width / $max_width) - $max_height) / 2;
+ }
+ }
+ $success = $image->resizeImage(
+ $new_width,
+ $new_height,
+ isset($options['filter']) ? $options['filter'] : \imagick::FILTER_LANCZOS,
+ isset($options['blur']) ? $options['blur'] : 1,
+ $new_width && $new_height // fit image into constraints if not to be cropped
+ );
+ if ($success && $crop) {
+ $success = $image->cropImage(
+ $max_width,
+ $max_height,
+ $x,
+ $y
+ );
+ if ($success) {
+ $success = $image->setImagePage($max_width, $max_height, 0, 0);
+ }
+ }
+ $type = strtolower(substr(strrchr($file_name, '.'), 1));
+ switch ($type) {
+ case 'jpg':
+ case 'jpeg':
+ if (!empty($options['jpeg_quality'])) {
+ $image->setImageCompression(\imagick::COMPRESSION_JPEG);
+ $image->setImageCompressionQuality($options['jpeg_quality']);
+ }
+ break;
+ }
+ if ( $image_strip ) {
+ $image->stripImage();
+ }
+ return $success && $image->writeImage($new_file_path);
+ }
+
+ protected function imagemagick_create_scaled_image($file_name, $version, $options) {
+ list($file_path, $new_file_path) =
+ $this->get_scaled_image_file_paths($file_name, $version);
+ $resize = @$options['max_width']
+ .(empty($options['max_height']) ? '' : 'X'.$options['max_height']);
+ if (!$resize && empty($options['auto_orient'])) {
+ if ($file_path !== $new_file_path) {
+ return copy($file_path, $new_file_path);
+ }
+ return true;
+ }
+ $cmd = $this->options['convert_bin'];
+ if (!empty($this->options['convert_params'])) {
+ $cmd .= ' '.$this->options['convert_params'];
+ }
+ $cmd .= ' '.escapeshellarg($file_path);
+ if (!empty($options['auto_orient'])) {
+ $cmd .= ' -auto-orient';
+ }
+ if ($resize) {
+ // Handle animated GIFs:
+ $cmd .= ' -coalesce';
+ if (empty($options['crop'])) {
+ $cmd .= ' -resize '.escapeshellarg($resize.'>');
+ } else {
+ $cmd .= ' -resize '.escapeshellarg($resize.'^');
+ $cmd .= ' -gravity center';
+ $cmd .= ' -crop '.escapeshellarg($resize.'+0+0');
+ }
+ // Make sure the page dimensions are correct (fixes offsets of animated GIFs):
+ $cmd .= ' +repage';
+ }
+ if (!empty($options['convert_params'])) {
+ $cmd .= ' '.$options['convert_params'];
+ }
+ $cmd .= ' '.escapeshellarg($new_file_path);
+ exec($cmd, $output, $error);
+ if ($error) {
+ error_log(implode('\n', $output));
+ return false;
+ }
+ return true;
+ }
+
+ protected function get_image_size($file_path) {
+ if ($this->options['image_library']) {
+ if (extension_loaded('imagick')) {
+ $image = new \Imagick();
+ try {
+ if (@$image->pingImage($file_path)) {
+ $dimensions = array($image->getImageWidth(), $image->getImageHeight());
+ $image->destroy();
+ return $dimensions;
+ }
+ return false;
+ } catch (\Exception $e) {
+ error_log($e->getMessage());
+ }
+ }
+ if ($this->options['image_library'] === 2) {
+ $cmd = $this->options['identify_bin'];
+ $cmd .= ' -ping '.escapeshellarg($file_path);
+ exec($cmd, $output, $error);
+ if (!$error && !empty($output)) {
+ // image.jpg JPEG 1920x1080 1920x1080+0+0 8-bit sRGB 465KB 0.000u 0:00.000
+ $infos = preg_split('/\s+/', substr($output[0], strlen($file_path)));
+ $dimensions = preg_split('/x/', $infos[2]);
+ return $dimensions;
+ }
+ return false;
+ }
+ }
+ if (!function_exists('getimagesize')) {
+ error_log('Function not found: getimagesize');
+ return false;
+ }
+ return @getimagesize($file_path);
+ }
+
+ protected function create_scaled_image($file_name, $version, $options) {
+ try {
+ if ($this->options['image_library'] === 2) {
+ return $this->imagemagick_create_scaled_image($file_name, $version, $options);
+ }
+ if ($this->options['image_library'] && extension_loaded('imagick')) {
+ return $this->imagick_create_scaled_image($file_name, $version, $options);
+ }
+ return $this->gd_create_scaled_image($file_name, $version, $options);
+ } catch (\Exception $e) {
+ error_log($e->getMessage());
+ return false;
+ }
+ }
+
+ protected function destroy_image_object($file_path) {
+ if ($this->options['image_library'] && extension_loaded('imagick')) {
+ return $this->imagick_destroy_image_object($file_path);
+ }
+ }
+
+ protected function imagetype($file_path) {
+ $fp = fopen($file_path, 'r');
+ $data = fread($fp, 4);
+ fclose($fp);
+ // GIF: 47 49 46 38
+ if ($data === 'GIF8') {
+ return self::IMAGETYPE_GIF;
+ }
+ // JPG: FF D8 FF
+ if (bin2hex(substr($data, 0, 3)) === 'ffd8ff') {
+ return self::IMAGETYPE_JPEG;
+ }
+ // PNG: 89 50 4E 47
+ if (bin2hex(@$data[0]).substr($data, 1, 4) === '89PNG') {
+ return self::IMAGETYPE_PNG;
+ }
+ return false;
+ }
+
+ protected function is_valid_image_file($file_path) {
+ if (!preg_match('/\.(gif|jpe?g|png)$/i', $file_path)) {
+ return false;
+ }
+ return !!$this->imagetype($file_path);
+ }
+
+ protected function handle_image_file($file_path, $file) {
+ $failed_versions = array();
+ foreach ($this->options['image_versions'] as $version => $options) {
+ if ($this->create_scaled_image($file->name, $version, $options)) {
+ if (!empty($version)) {
+ $file->{$version.'Url'} = $this->get_download_url(
+ $file->name,
+ $version
+ );
+ } else {
+ $file->size = $this->get_file_size($file_path, true);
+ }
+ } else {
+ $failed_versions[] = $version ? $version : 'original';
+ }
+ }
+ if (count($failed_versions)) {
+ $file->error = $this->get_error_message('image_resize')
+ .' ('.implode($failed_versions, ', ').')';
+ }
+ // Free memory:
+ $this->destroy_image_object($file_path);
+ }
+
+ protected function handle_file_upload($uploaded_file, $name, $size, $type, $error,
+ $index = null, $content_range = null) {
+ $file = new \stdClass();
+ $file->name = $this->get_file_name($uploaded_file, $name, $size, $type, $error,
+ $index, $content_range);
+ $file->size = $this->fix_integer_overflow((int)$size);
+ $file->type = $type;
+ if ($this->validate($uploaded_file, $file, $error, $index)) {
+ $this->handle_form_data($file, $index);
+ $upload_dir = $this->get_upload_path();
+ if (!is_dir($upload_dir)) {
+ mkdir($upload_dir, $this->options['mkdir_mode'], true);
+ }
+ $file_path = $this->get_upload_path($file->name);
+ $append_file = $content_range && is_file($file_path) &&
+ $file->size > $this->get_file_size($file_path);
+ if ($uploaded_file && is_uploaded_file($uploaded_file)) {
+ // multipart/formdata uploads (POST method uploads)
+ if ($append_file) {
+ file_put_contents(
+ $file_path,
+ fopen($uploaded_file, 'r'),
+ FILE_APPEND
+ );
+ } else {
+ move_uploaded_file($uploaded_file, $file_path);
+ }
+ } else {
+ // Non-multipart uploads (PUT method support)
+ file_put_contents(
+ $file_path,
+ fopen($this->options['input_stream'], 'r'),
+ $append_file ? FILE_APPEND : 0
+ );
+ }
+ $file_size = $this->get_file_size($file_path, $append_file);
+ if ($file_size === $file->size) {
+ $file->url = $this->get_download_url($file->name);
+ if ($this->is_valid_image_file($file_path)) {
+ $this->handle_image_file($file_path, $file);
+ }
+ } else {
+ $file->size = $file_size;
+ if (!$content_range && $this->options['discard_aborted_uploads']) {
+ unlink($file_path);
+ $file->error = $this->get_error_message('abort');
+ }
+ }
+ $this->set_additional_file_properties($file);
+ }
+ return $file;
+ }
+
+ protected function readfile($file_path) {
+ $file_size = $this->get_file_size($file_path);
+ $chunk_size = $this->options['readfile_chunk_size'];
+ if ($chunk_size && $file_size > $chunk_size) {
+ $handle = fopen($file_path, 'rb');
+ while (!feof($handle)) {
+ echo fread($handle, $chunk_size);
+ @ob_flush();
+ @flush();
+ }
+ fclose($handle);
+ return $file_size;
+ }
+ return readfile($file_path);
+ }
+
+ protected function body($str) {
+ echo $str;
+ }
+
+ protected function header($str) {
+ header($str);
+ }
+
+ protected function get_upload_data($id) {
+ return @$_FILES[$id];
+ }
+
+ protected function get_post_param($id) {
+ return @$_POST[$id];
+ }
+
+ protected function get_query_param($id) {
+ return @$_GET[$id];
+ }
+
+ protected function get_server_var($id) {
+ return @$_SERVER[$id];
+ }
+
+ protected function handle_form_data($file, $index) {
+ // Handle form data, e.g. $_POST['description'][$index]
+ }
+
+ protected function get_version_param() {
+ return $this->basename(stripslashes($this->get_query_param('version')));
+ }
+
+ protected function get_singular_param_name() {
+ return substr($this->options['param_name'], 0, -1);
+ }
+
+ protected function get_file_name_param() {
+ $name = $this->get_singular_param_name();
+ return $this->basename(stripslashes($this->get_query_param($name)));
+ }
+
+ protected function get_file_names_params() {
+ $params = $this->get_query_param($this->options['param_name']);
+ if (!$params) {
+ return null;
+ }
+ foreach ($params as $key => $value) {
+ $params[$key] = $this->basename(stripslashes($value));
+ }
+ return $params;
+ }
+
+ protected function get_file_type($file_path) {
+ switch (strtolower(pathinfo($file_path, PATHINFO_EXTENSION))) {
+ case 'jpeg':
+ case 'jpg':
+ return 'image/jpeg';
+ case 'png':
+ return 'image/png';
+ case 'gif':
+ return 'image/gif';
+ default:
+ return '';
+ }
+ }
+
+ protected function download() {
+ switch ($this->options['download_via_php']) {
+ case 1:
+ $redirect_header = null;
+ break;
+ case 2:
+ $redirect_header = 'X-Sendfile';
+ break;
+ case 3:
+ $redirect_header = 'X-Accel-Redirect';
+ break;
+ default:
+ return $this->header('HTTP/1.1 403 Forbidden');
+ }
+ $file_name = $this->get_file_name_param();
+ if (!$this->is_valid_file_object($file_name)) {
+ return $this->header('HTTP/1.1 404 Not Found');
+ }
+ if ($redirect_header) {
+ return $this->header(
+ $redirect_header.': '.$this->get_download_url(
+ $file_name,
+ $this->get_version_param(),
+ true
+ )
+ );
+ }
+ $file_path = $this->get_upload_path($file_name, $this->get_version_param());
+ // Prevent browsers from MIME-sniffing the content-type:
+ $this->header('X-Content-Type-Options: nosniff');
+ if (!preg_match($this->options['inline_file_types'], $file_name)) {
+ $this->header('Content-Type: application/octet-stream');
+ $this->header('Content-Disposition: attachment; filename="'.$file_name.'"');
+ } else {
+ $this->header('Content-Type: '.$this->get_file_type($file_path));
+ $this->header('Content-Disposition: inline; filename="'.$file_name.'"');
+ }
+ $this->header('Content-Length: '.$this->get_file_size($file_path));
+ $this->header('Last-Modified: '.gmdate('D, d M Y H:i:s T', filemtime($file_path)));
+ $this->readfile($file_path);
+ }
+
+ protected function send_content_type_header() {
+ $this->header('Vary: Accept');
+ if (strpos($this->get_server_var('HTTP_ACCEPT'), 'application/json') !== false) {
+ $this->header('Content-type: application/json');
+ } else {
+ $this->header('Content-type: text/plain');
+ }
+ }
+
+ protected function send_access_control_headers() {
+ $this->header('Access-Control-Allow-Origin: '.$this->options['access_control_allow_origin']);
+ $this->header('Access-Control-Allow-Credentials: '
+ .($this->options['access_control_allow_credentials'] ? 'true' : 'false'));
+ $this->header('Access-Control-Allow-Methods: '
+ .implode(', ', $this->options['access_control_allow_methods']));
+ $this->header('Access-Control-Allow-Headers: '
+ .implode(', ', $this->options['access_control_allow_headers']));
+ }
+
+ public function generate_response($content, $print_response = true) {
+ $this->response = $content;
+ if ($print_response) {
+ $json = json_encode($content);
+ $redirect = stripslashes($this->get_post_param('redirect'));
+ if ($redirect && preg_match($this->options['redirect_allow_target'], $redirect)) {
+ $this->header('Location: '.sprintf($redirect, rawurlencode($json)));
+ return;
+ }
+ $this->head();
+ if ($this->get_server_var('HTTP_CONTENT_RANGE')) {
+ $files = isset($content[$this->options['param_name']]) ?
+ $content[$this->options['param_name']] : null;
+ if ($files && is_array($files) && is_object($files[0]) && $files[0]->size) {
+ $this->header('Range: 0-'.(
+ $this->fix_integer_overflow((int)$files[0]->size) - 1
+ ));
+ }
+ }
+ $this->body($json);
+ }
+ return $content;
+ }
+
+ public function get_response () {
+ return $this->response;
+ }
+
+ public function head() {
+ $this->header('Pragma: no-cache');
+ $this->header('Cache-Control: no-store, no-cache, must-revalidate');
+ $this->header('Content-Disposition: inline; filename="files.json"');
+ // Prevent Internet Explorer from MIME-sniffing the content-type:
+ $this->header('X-Content-Type-Options: nosniff');
+ if ($this->options['access_control_allow_origin']) {
+ $this->send_access_control_headers();
+ }
+ $this->send_content_type_header();
+ }
+
+ public function get($print_response = true) {
+ if ($print_response && $this->get_query_param('download')) {
+ return $this->download();
+ }
+ $file_name = $this->get_file_name_param();
+ if ($file_name) {
+ $response = array(
+ $this->get_singular_param_name() => $this->get_file_object($file_name)
+ );
+ } else {
+ $response = array(
+ $this->options['param_name'] => $this->get_file_objects()
+ );
+ }
+ return $this->generate_response($response, $print_response);
+ }
+
+ public function post($print_response = true) {
+ if ($this->get_query_param('_method') === 'DELETE') {
+ return $this->delete($print_response);
+ }
+ $upload = $this->get_upload_data($this->options['param_name']);
+ // Parse the Content-Disposition header, if available:
+ $content_disposition_header = $this->get_server_var('HTTP_CONTENT_DISPOSITION');
+ $file_name = $content_disposition_header ?
+ rawurldecode(preg_replace(
+ '/(^[^"]+")|("$)/',
+ '',
+ $content_disposition_header
+ )) : null;
+ // Parse the Content-Range header, which has the following form:
+ // Content-Range: bytes 0-524287/2000000
+ $content_range_header = $this->get_server_var('HTTP_CONTENT_RANGE');
+ $content_range = $content_range_header ?
+ preg_split('/[^0-9]+/', $content_range_header) : null;
+ $size = $content_range ? $content_range[3] : null;
+ $files = array();
+ if ($upload) {
+ if (is_array($upload['tmp_name'])) {
+ // param_name is an array identifier like "files[]",
+ // $upload is a multi-dimensional array:
+ foreach ($upload['tmp_name'] as $index => $value) {
+ $files[] = $this->handle_file_upload(
+ $upload['tmp_name'][$index],
+ $file_name ? $file_name : $upload['name'][$index],
+ $size ? $size : $upload['size'][$index],
+ $upload['type'][$index],
+ isset($upload['error']) ? $upload['error'][$index] : null,
+ $index,
+ $content_range
+ );
+ }
+ } else {
+ // param_name is a single object identifier like "file",
+ // $upload is a one-dimensional array:
+ $files[] = $this->handle_file_upload(
+ isset($upload['tmp_name']) ? $upload['tmp_name'] : null,
+ $file_name ? $file_name : (isset($upload['name']) ?
+ $upload['name'] : null),
+ $size ? $size : (isset($upload['size']) ?
+ $upload['size'] : $this->get_server_var('CONTENT_LENGTH')),
+ isset($upload['type']) ?
+ $upload['type'] : $this->get_server_var('CONTENT_TYPE'),
+ isset($upload['error']) ? $upload['error'] : null,
+ null,
+ $content_range
+ );
+ }
+ }
+ $response = array($this->options['param_name'] => $files);
+ $name = $file_name ? $file_name : $upload['name'][0];
+ $res = $this->generate_response($response, $print_response);
+ if(is_file($this->get_upload_path($name))){
+ $uploaded_bytes = $this->fix_integer_overflow((int)$content_range[1]);
+ $totalSize = $this->get_file_size($this->get_upload_path($name));
+ if ($totalSize - $uploaded_bytes - $this->options['readfile_chunk_size'] < 0) {
+ $this->onUploadEnd($res);
+ }else{
+ $this->head();
+ $this->body(json_encode($res));
+ }
+ }else{
+ $this->head();
+ $this->body(json_encode($res));
+ }
+ return $res;
+ }
+
+ public function onUploadEnd ($res){
+ $targetPath = $this->options['storeFolder'];
+ $targetPathThumb = $this->options['storeFolderThumb'];
+
+ if(!$this->options['ftp']){
+ $targetFile = $targetPath. $res['files'][0]->name;
+ $targetFileThumb = $targetPathThumb. $res['files'][0]->name;
+ if (!is_dir($targetPathThumb)) {
+ mkdir($targetPathThumb, $this->options['mkdir_mode'], true);
+ }
+ if(is_file($targetFile)) {
+ chmod($targetFile, $this->options['config']['filePermission']);
+ }elseif(is_dir($targetFile)){
+ chmod($targetFile, $this->options['config']['folderPermission']);
+ }
+ }else{
+ $targetFile = $this->options['config']['ftp_temp_folder'].$res['files'][0]->name;
+ $targetFileThumb = $this->options['config']['ftp_temp_folder']."thumbs/". $res['files'][0]->name;
+ }
+
+ //check if image (and supported)
+ $is_img = FALSE;
+ if ($this->is_valid_image_file($targetFile)){
+ $is_img = TRUE;
+ }
+
+ if ($is_img)
+ {
+ if(isset($this->options['config']['image_watermark']) && $this->options['config']['image_watermark']){
+ require_once('include/php_image_magician.php');
+
+ $magicianObj = new imageLib($targetFile);
+ $magicianObj -> addWatermark($this->options['config']['image_watermark'], $this->options['config']['image_watermark_position'], $this->options['config']['image_watermark_padding']);
+
+ $magicianObj -> saveImage($targetFile);
+ }
+
+
+
+ $thumbResult = create_img($targetFile, $targetFileThumb, $this->options['config']['fixed_image_creation_width'], $this->options['config']['fixed_image_creation_height']);
+
+ if ( $thumbResult!==true)
+ {
+ if($thumbResult === false){
+ $res['files'][0]->error = trans("Not enough Memory");
+ }else{
+ $res['files'][0]->error = $thumbResult;
+ }
+ }
+ else
+ {
+ if( !$this->options['ftp'] && ! new_thumbnails_creation($targetPath,$targetFile,$_FILES['files']['name'][0],$this->options['config']['current_path'],$this->options['config']))
+ {
+ $res['files'][0]->error = trans("Not enough Memory");
+ }
+ else
+ {
+ $imginfo = getimagesize($targetFile);
+ $srcWidth = $imginfo[0];
+ $srcHeight = $imginfo[1];
+
+ // resize images if set
+ if ($this->options['config']['image_resizing'])
+ {
+ if ($this->options['config']['image_resizing_width'] == 0) // if width not set
+ {
+ if ($this->options['config']['image_resizing_height'] == 0)
+ {
+ $this->options['config']['image_resizing_width'] = $srcWidth;
+ $this->options['config']['image_resizing_height'] = $srcHeight;
+ }
+ else
+ {
+ $this->options['config']['image_resizing_width'] = $this->options['config']['image_resizing_height']*$srcWidth/$srcHeight;
+ }
+ }
+ elseif ($this->options['config']['image_resizing_height'] == 0) // if height not set
+ {
+ $this->options['config']['image_resizing_height'] = $this->options['config']['image_resizing_width']*$srcHeight/$srcWidth;
+ }
+
+ // new dims and create
+ $srcWidth = $this->options['config']['image_resizing_width'];
+ $srcHeight = $this->options['config']['image_resizing_height'];
+ create_img($targetFile, $targetFile, $this->options['config']['image_resizing_width'], $this->options['config']['image_resizing_height'], $this->options['config']['image_resizing_mode']);
+ }
+
+ //max resizing limit control
+ $resize = FALSE;
+ if ($this->options['config']['image_max_width'] != 0 && $srcWidth > $this->options['config']['image_max_width'] && $this->options['config']['image_resizing_override'] === FALSE)
+ {
+ $resize = TRUE;
+ $srcWidth = $this->options['config']['image_max_width'];
+
+ if ($this->options['config']['image_max_height'] == 0) $srcHeight = $this->options['config']['image_max_width']*$srcHeight/$srcWidth;
+ }
+
+ if ($this->options['config']['image_max_height'] != 0 && $srcHeight > $this->options['config']['image_max_height'] && $this->options['config']['image_resizing_override'] === FALSE){
+ $resize = TRUE;
+ $srcHeight = $this->options['config']['image_max_height'];
+
+ if ($this->options['config']['image_max_width'] == 0) $srcWidth = $this->options['config']['image_max_height']*$srcWidth/$srcHeight;
+ }
+
+ if ($resize){ create_img($targetFile, $targetFile, $srcWidth, $srcHeight, $this->options['config']['image_max_mode']); }
+ }
+ }
+ }
+
+ if($this->options['ftp']){
+
+ $this->options['ftp']->put($targetPath. $res['files'][0]->name, $targetFile, FTP_BINARY);
+ unlink($targetFile);
+ if ($is_img)
+ {
+ $this->options['ftp']->put($targetPathThumb. $res['files'][0]->name, $targetFileThumb, FTP_BINARY);
+ unlink($targetFileThumb);
+ }
+ }
+ $this->head();
+ $this->body(json_encode($res));
+ }
+
+ public function delete($print_response = true) {
+ $file_names = $this->get_file_names_params();
+ if (empty($file_names)) {
+ $file_names = array($this->get_file_name_param());
+ }
+ $response = array();
+ foreach ($file_names as $file_name) {
+ $file_path = $this->get_upload_path($file_name);
+ $success = is_file($file_path) && $file_name[0] !== '.' && unlink($file_path);
+ if ($success) {
+ foreach ($this->options['image_versions'] as $version => $options) {
+ if (!empty($version)) {
+ $file = $this->get_upload_path($file_name, $version);
+ if (is_file($file)) {
+ unlink($file);
+ }
+ }
+ }
+ }
+ $response[$file_name] = $success;
+ }
+ return $this->generate_response($response, $print_response);
+ }
+
+ protected function basename($filepath, $suffix = null) {
+ $splited = preg_split('/\//', rtrim ($filepath, '/ '));
+ return substr(basename('X'.$splited[count($splited)-1], $suffix), 1);
+ }
+}
diff --git a/core/vendor/simplelightbox/simple-lightbox.min.js b/core/vendor/simplelightbox/simple-lightbox.min.js
new file mode 100644
index 00000000..0e2c1dd5
--- /dev/null
+++ b/core/vendor/simplelightbox/simple-lightbox.min.js
@@ -0,0 +1,7 @@
+/*
+ By André Rinas, www.andrerinas.de
+ Documentation, www.simplelightbox.de
+ Available for use under the MIT License
+ 1.17.0
+*/
+!function(st,lt,rt,t){"use strict";st.fn.simpleLightbox=function(P){P=st.extend({sourceAttr:"href",overlay:!0,spinner:!0,nav:!0,navText:["‹","›"],captions:!0,captionDelay:0,captionSelector:"img",captionType:"attr",captionsData:"title",captionPosition:"bottom",captionClass:"",close:!0,closeText:"×",swipeClose:!0,showCounter:!0,fileExt:"png|jpg|jpeg|gif",animationSlide:!0,animationSpeed:250,preloading:!0,enableKeyboard:!0,loop:!0,rel:!1,docClose:!0,swipeTolerance:50,className:"simple-lightbox",widthRatio:.8,heightRatio:.9,scaleImageToRatio:!1,disableRightClick:!1,disableScroll:!0,alertError:!0,alertErrorMessage:"Image not found, next image will be loaded",additionalHtml:!1,history:!0,throttleInterval:0,doubleTapZoom:2,maxZoom:10,htmlClass:"has-lightbox"},P);var h,t,Z="ontouchstart"in lt,z=(lt.navigator.pointerEnabled||lt.navigator.msPointerEnabled,0),H=0,L=st(),i=function(){var t=rt.body||rt.documentElement;return""===(t=t.style).WebkitTransition?"-webkit-":""===t.MozTransition?"-moz-":""===t.OTransition?"-o-":""===t.transition&&""},N=!1,p=[],j=P.rel&&!1!==P.rel?(t=P.rel,st(this).filter(function(){return st(this).attr("rel")===t})):this,d=(i=i(),0),K=!1!==i,a="pushState"in history,u=!1,n=lt.location,$=function(){return n.hash.substring(1)},B=$(),f=function(){$();var t="pid="+(J+1),e=n.href.split("#")[0]+"#"+t;a?history[u?"replaceState":"pushState"]("",rt.title,e):u?n.replace(e):n.hash=t,u=!0},Q=function(e,a){var n;return function(){var t=arguments;n||(e.apply(this,t),n=!0,setTimeout(function(){return n=!1},a))}},U="simplelb",e=st("
").addClass("sl-overlay"),o=st("