CoreFiles by mySites.guru
plugin.js2,927 lines, 87,007 bytes, from Joomla_4.0.0-alpha2-Alpha-Full_Package.zip
Raw History Compare with 3.10.0-alpha9
md5
60a6d8edda31419388d798563448fdc2
sha1
bb2cf09a75561f76d830b87ee3c7d530079515ca
sha256
9a60eaf92f61612b1723453302d4a7760033a3fa57e562b9d3c466825a033f2d
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927
(function () {

var defs = {}; // id -> {dependencies, definition, instance (possibly undefined)}

// Used when there is no 'main' module.
// The name is probably (hopefully) unique so minification removes for releases.
var register_3795 = function (id) {
  var module = dem(id);
  var fragments = id.split('.');
  var target = Function('return this;')();
  for (var i = 0; i < fragments.length - 1; ++i) {
    if (target[fragments[i]] === undefined)
      target[fragments[i]] = {};
    target = target[fragments[i]];
  }
  target[fragments[fragments.length - 1]] = module;
};

var instantiate = function (id) {
  var actual = defs[id];
  var dependencies = actual.deps;
  var definition = actual.defn;
  var len = dependencies.length;
  var instances = new Array(len);
  for (var i = 0; i < len; ++i)
    instances[i] = dem(dependencies[i]);
  var defResult = definition.apply(null, instances);
  if (defResult === undefined)
     throw 'module [' + id + '] returned undefined';
  actual.instance = defResult;
};

var def = function (id, dependencies, definition) {
  if (typeof id !== 'string')
    throw 'module id must be a string';
  else if (dependencies === undefined)
    throw 'no dependencies for ' + id;
  else if (definition === undefined)
    throw 'no definition function for ' + id;
  defs[id] = {
    deps: dependencies,
    defn: definition,
    instance: undefined
  };
};

var dem = function (id) {
  var actual = defs[id];
  if (actual === undefined)
    throw 'module [' + id + '] was undefined';
  else if (actual.instance === undefined)
    instantiate(id);
  return actual.instance;
};

var req = function (ids, callback) {
  var len = ids.length;
  var instances = new Array(len);
  for (var i = 0; i < len; ++i)
    instances[i] = dem(ids[i]);
  callback.apply(null, instances);
};

var ephox = {};

ephox.bolt = {
  module: {
    api: {
      define: def,
      require: req,
      demand: dem
    }
  }
};

var define = def;
var require = req;
var demand = dem;
// this helps with minification when using a lot of global references
var defineGlobal = function (id, ref) {
  define(id, [], function () { return ref; });
};
/*jsc
["tinymce.plugins.paste.Plugin","ephox.katamari.api.Cell","tinymce.core.PluginManager","tinymce.plugins.paste.alien.DetectProPlugin","tinymce.plugins.paste.api.Api","tinymce.plugins.paste.api.Commands","tinymce.plugins.paste.core.Clipboard","tinymce.plugins.paste.core.CutCopy","tinymce.plugins.paste.core.DragDrop","tinymce.plugins.paste.core.PrePostProcess","tinymce.plugins.paste.core.Quirks","tinymce.plugins.paste.ui.Buttons","global!tinymce.util.Tools.resolve","global!window","tinymce.plugins.paste.core.Actions","global!Image","global!navigator","tinymce.core.Env","tinymce.core.util.Delay","tinymce.core.util.Tools","tinymce.core.util.VK","tinymce.plugins.paste.api.Events","tinymce.plugins.paste.api.Settings","tinymce.plugins.paste.core.InternalHtml","tinymce.plugins.paste.core.Newlines","tinymce.plugins.paste.core.PasteBin","tinymce.plugins.paste.core.ProcessFilters","tinymce.plugins.paste.core.SmartPaste","tinymce.plugins.paste.core.Utils","global!setTimeout","tinymce.core.api.dom.RangeUtils","tinymce.plugins.paste.core.WordFilter","ephox.katamari.api.Fun","tinymce.core.html.Entities","tinymce.core.html.DomParser","tinymce.core.html.Node","tinymce.core.html.Schema","tinymce.core.html.Serializer","global!Array","global!Error"]
jsc*/
define(
  'ephox.katamari.api.Cell',

  [
  ],

  function () {
    var Cell = function (initial) {
      var value = initial;

      var get = function () {
        return value;
      };

      var set = function (v) {
        value = v;
      };

      var clone = function () {
        return Cell(get());
      };

      return {
        get: get,
        set: set,
        clone: clone
      };
    };

    return Cell;
  }
);

defineGlobal("global!tinymce.util.Tools.resolve", tinymce.util.Tools.resolve);
/**
 * ResolveGlobal.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

define(
  'tinymce.core.PluginManager',
  [
    'global!tinymce.util.Tools.resolve'
  ],
  function (resolve) {
    return resolve('tinymce.PluginManager');
  }
);

defineGlobal("global!window", window);
/**
 * DetectProPlugin.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

define(
  'tinymce.plugins.paste.alien.DetectProPlugin',
  [
    'global!window',
    'tinymce.core.PluginManager'
  ],
  function (window, PluginManager) {
    var hasProPlugin = function (editor) {
      // draw back if power version is requested and registered
      if (/(^|[ ,])powerpaste([, ]|$)/.test(editor.settings.plugins) && PluginManager.get('powerpaste')) {
        /*eslint no-console:0 */
        if (typeof window.console !== "undefined" && window.console.log) {
          window.console.log("PowerPaste is incompatible with Paste plugin! Remove 'paste' from the 'plugins' option.");
        }
        return true;
      } else {
        return false;
      }
    };

    return {
      hasProPlugin: hasProPlugin
    };
  }
);

/**
 * Api.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

define(
  'tinymce.plugins.paste.api.Api',
  [
  ],
  function (Actions) {
    var get = function (clipboard, quirks) {
      return {
        clipboard: clipboard,
        quirks: quirks
      };
    };

    return {
      get: get
    };
  }
);

/**
 * Events.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

define(
  'tinymce.plugins.paste.api.Events',
  [
  ],
  function () {
    var firePastePreProcess = function (editor, html, internal, isWordHtml) {
      return editor.fire('PastePreProcess', { content: html, internal: internal, wordContent: isWordHtml });
    };

    var firePastePostProcess = function (editor, node, internal, isWordHtml) {
      return editor.fire('PastePostProcess', { node: node, internal: internal, wordContent: isWordHtml });
    };

    var firePastePlainTextToggle = function (editor, state) {
      return editor.fire('PastePlainTextToggle', { state: state });
    };

    var firePaste = function (editor, ieFake) {
      return editor.fire('paste', { ieFake: ieFake });
    };

    return {
      firePastePreProcess: firePastePreProcess,
      firePastePostProcess: firePastePostProcess,
      firePastePlainTextToggle: firePastePlainTextToggle,
      firePaste: firePaste
    };
  }
);

/**
 * Settings.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

define(
  'tinymce.plugins.paste.api.Settings',
  [
  ],
  function () {
    var shouldPlainTextInform = function (editor) {
      return editor.getParam('paste_plaintext_inform', true);
    };

    var shouldBlockDrop = function (editor) {
      return editor.getParam('paste_block_drop', false);
    };

    var shouldPasteDataImages = function (editor) {
      return editor.getParam('paste_data_images', false);
    };

    var shouldFilterDrop = function (editor) {
      return editor.getParam('paste_filter_drop', true);
    };

    var getPreProcess = function (editor) {
      return editor.getParam('paste_preprocess');
    };

    var getPostProcess = function (editor) {
      return editor.getParam('paste_postprocess');
    };

    var getWebkitStyles = function (editor) {
      return editor.getParam('paste_webkit_styles');
    };

    var shouldRemoveWebKitStyles = function (editor) {
      return editor.getParam('paste_remove_styles_if_webkit', true);
    };

    var shouldMergeFormats = function (editor) {
      return editor.getParam('paste_merge_formats', true);
    };

    var isSmartPasteEnabled = function (editor) {
      return editor.getParam('smart_paste', true);
    };

    var isPasteAsTextEnabled = function (editor) {
      return editor.getParam('paste_as_text', false);
    };

    var getRetainStyleProps = function (editor) {
      return editor.getParam('paste_retain_style_properties');
    };

    var getWordValidElements = function (editor) {
      var defaultValidElements = (
        '-strong/b,-em/i,-u,-span,-p,-ol,-ul,-li,-h1,-h2,-h3,-h4,-h5,-h6,' +
        '-p/div,-a[href|name],sub,sup,strike,br,del,table[width],tr,' +
        'td[colspan|rowspan|width],th[colspan|rowspan|width],thead,tfoot,tbody'
      );

      return editor.getParam('paste_word_valid_elements', defaultValidElements);
    };

    var shouldConvertWordFakeLists = function (editor) {
      return editor.getParam('paste_convert_word_fake_lists', true);
    };

    var shouldUseDefaultFilters = function (editor) {
      return editor.getParam('paste_enable_default_filters', true);
    };

    return {
      shouldPlainTextInform: shouldPlainTextInform,
      shouldBlockDrop: shouldBlockDrop,
      shouldPasteDataImages: shouldPasteDataImages,
      shouldFilterDrop: shouldFilterDrop,
      getPreProcess: getPreProcess,
      getPostProcess: getPostProcess,
      getWebkitStyles: getWebkitStyles,
      shouldRemoveWebKitStyles: shouldRemoveWebKitStyles,
      shouldMergeFormats: shouldMergeFormats,
      isSmartPasteEnabled: isSmartPasteEnabled,
      isPasteAsTextEnabled: isPasteAsTextEnabled,
      getRetainStyleProps: getRetainStyleProps,
      getWordValidElements: getWordValidElements,
      shouldConvertWordFakeLists: shouldConvertWordFakeLists,
      shouldUseDefaultFilters: shouldUseDefaultFilters
    };
  }
);

/**
 * Actions.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

define(
  'tinymce.plugins.paste.core.Actions',
  [
    'tinymce.plugins.paste.api.Events',
    'tinymce.plugins.paste.api.Settings'
  ],
  function (Events, Settings) {
    var shouldInformUserAboutPlainText = function (editor, userIsInformedState) {
      return userIsInformedState.get() === false && Settings.shouldPlainTextInform(editor);
    };

    var displayNotification = function (editor, message) {
      editor.notificationManager.open({
        text: editor.translate(message),
        type: 'info'
      });
    };

    var togglePlainTextPaste = function (editor, clipboard, userIsInformedState) {
      if (clipboard.pasteFormat === "text") {
        clipboard.pasteFormat = "html";
        Events.firePastePlainTextToggle(editor, false);
      } else {
        clipboard.pasteFormat = "text";
        Events.firePastePlainTextToggle(editor, true);

        if (shouldInformUserAboutPlainText(editor, userIsInformedState)) {
          displayNotification(editor, 'Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off.');
          userIsInformedState.set(true);
        }
      }

      editor.focus();
    };

    return {
      togglePlainTextPaste: togglePlainTextPaste
    };
  }
);
/**
 * Commands.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

define(
  'tinymce.plugins.paste.api.Commands',
  [
    'tinymce.plugins.paste.core.Actions'
  ],
  function (Actions) {
    var register = function (editor, clipboard, userIsInformedState) {
      editor.addCommand('mceTogglePlainTextPaste', function () {
        Actions.togglePlainTextPaste(editor, clipboard, userIsInformedState);
      });

      editor.addCommand('mceInsertClipboardContent', function (ui, value) {
        if (value.content) {
          clipboard.pasteHtml(value.content, value.internal);
        }

        if (value.text) {
          clipboard.pasteText(value.text);
        }
      });
    };

    return {
      register: register
    };
  }
);

defineGlobal("global!Image", Image);
defineGlobal("global!navigator", navigator);
/**
 * ResolveGlobal.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

define(
  'tinymce.core.Env',
  [
    'global!tinymce.util.Tools.resolve'
  ],
  function (resolve) {
    return resolve('tinymce.Env');
  }
);

/**
 * ResolveGlobal.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

define(
  'tinymce.core.util.Delay',
  [
    'global!tinymce.util.Tools.resolve'
  ],
  function (resolve) {
    return resolve('tinymce.util.Delay');
  }
);

/**
 * ResolveGlobal.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

define(
  'tinymce.core.util.Tools',
  [
    'global!tinymce.util.Tools.resolve'
  ],
  function (resolve) {
    return resolve('tinymce.util.Tools');
  }
);

/**
 * ResolveGlobal.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

define(
  'tinymce.core.util.VK',
  [
    'global!tinymce.util.Tools.resolve'
  ],
  function (resolve) {
    return resolve('tinymce.util.VK');
  }
);

/**
 * InternalHtml.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

define(
  'tinymce.plugins.paste.core.InternalHtml',
  [
  ],
  function () {
    var internalMimeType = 'x-tinymce/html';
    var internalMark = '<!-- ' + internalMimeType + ' -->';

    var mark = function (html) {
      return internalMark + html;
    };

    var unmark = function (html) {
      return html.replace(internalMark, '');
    };

    var isMarked = function (html) {
      return html.indexOf(internalMark) !== -1;
    };

    return {
      mark: mark,
      unmark: unmark,
      isMarked: isMarked,
      internalHtmlMime: function () {
        return internalMimeType;
      }
    };
  }
);
/**
 * ResolveGlobal.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

define(
  'tinymce.core.html.Entities',
  [
    'global!tinymce.util.Tools.resolve'
  ],
  function (resolve) {
    return resolve('tinymce.html.Entities');
  }
);

/**
 * Newlines.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * Newlines class contains utilities to convert newlines (\n or \r\n) tp BRs or to a combination of the specified block element and BRs
 *
 * @class tinymce.Newlines
 * @private
 */
define(
  'tinymce.plugins.paste.core.Newlines',
  [
    'tinymce.core.util.Tools',
    'tinymce.core.html.Entities'
  ],
  function (Tools, Entities) {

    var isPlainText = function (text) {
      // so basically any tag that is not one of the "p, div, span, br", or is one of them, but is followed
      // by some additional characters qualifies the text as not a plain text (having some HTML tags)
      // <span style="white-space:pre"> and <br /> are added as separate exceptions to the rule
      return !/<(?:\/?(?!(?:div|p|br|span)>)\w+|(?:(?!(?:span style="white-space:\s?pre;?">)|br\s?\/>))\w+\s[^>]+)>/i.test(text);
    };


    var toBRs = function (text) {
      return text.replace(/\r?\n/g, '<br>');
    };


    var openContainer = function (rootTag, rootAttrs) {
      var key, attrs = [];
      var tag = '<' + rootTag;

      if (typeof rootAttrs === 'object') {
        for (key in rootAttrs) {
          if (rootAttrs.hasOwnProperty(key)) {
            attrs.push(key + '="' + Entities.encodeAllRaw(rootAttrs[key]) + '"');
          }
        }

        if (attrs.length) {
          tag += ' ' + attrs.join(' ');
        }
      }
      return tag + '>';
    };


    var toBlockElements = function (text, rootTag, rootAttrs) {
      var blocks = text.split(/\n\n/);
      var tagOpen = openContainer(rootTag, rootAttrs);
      var tagClose = '</' + rootTag + '>';

      var paragraphs = Tools.map(blocks, function (p) {
        return p.split(/\n/).join('<br />');
      });

      var stitch = function (p) {
        return tagOpen + p + tagClose;
      };

      return paragraphs.length === 1 ? paragraphs[0] : Tools.map(paragraphs, stitch).join('');
    };


    var convert = function (text, rootTag, rootAttrs) {
      return rootTag ? toBlockElements(text, rootTag, rootAttrs) : toBRs(text);
    };


    return {
      isPlainText: isPlainText,
      convert: convert,
      toBRs: toBRs,
      toBlockElements: toBlockElements
    };
  }
);
/**
 * PasteBin.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * @class tinymce.pasteplugin.PasteBin
 * @private
 */
define(
  'tinymce.plugins.paste.core.PasteBin',
  [
    'tinymce.core.util.Tools',
    'tinymce.core.Env'
  ],
  function (Tools, Env) {
    return function (editor) {
      var lastRng;
      var pasteBinDefaultContent = '%MCEPASTEBIN%';

      /**
       * Creates a paste bin element as close as possible to the current caret location and places the focus inside that element
       * so that when the real paste event occurs the contents gets inserted into this element
       * instead of the current editor selection element.
       */
      var create = function () {
        var dom = editor.dom, body = editor.getBody();
        var viewport = editor.dom.getViewPort(editor.getWin()), scrollTop = viewport.y, top = 20;
        var pasteBinElm;
        var scrollContainer;

        lastRng = editor.selection.getRng();

        if (editor.inline) {
          scrollContainer = editor.selection.getScrollContainer();

          // Can't always rely on scrollTop returning a useful value.
          // It returns 0 if the browser doesn't support scrollTop for the element or is non-scrollable
          if (scrollContainer && scrollContainer.scrollTop > 0) {
            scrollTop = scrollContainer.scrollTop;
          }
        }

        /**
         * Returns the rect of the current caret if the caret is in an empty block before a
         * BR we insert a temporary invisible character that we get the rect this way we always get a proper rect.
         *
         * TODO: This might be useful in core.
         */
        function getCaretRect(rng) {
          var rects, textNode, node, container = rng.startContainer;

          rects = rng.getClientRects();
          if (rects.length) {
            return rects[0];
          }

          if (!rng.collapsed || container.nodeType !== 1) {
            return;
          }

          node = container.childNodes[lastRng.startOffset];

          // Skip empty whitespace nodes
          while (node && node.nodeType === 3 && !node.data.length) {
            node = node.nextSibling;
          }

          if (!node) {
            return;
          }

          // Check if the location is |<br>
          // TODO: Might need to expand this to say |<table>
          if (node.tagName === 'BR') {
            textNode = dom.doc.createTextNode('\uFEFF');
            node.parentNode.insertBefore(textNode, node);

            rng = dom.createRng();
            rng.setStartBefore(textNode);
            rng.setEndAfter(textNode);

            rects = rng.getClientRects();
            dom.remove(textNode);
          }

          if (rects.length) {
            return rects[0];
          }
        }

        // Calculate top cordinate this is needed to avoid scrolling to top of document
        // We want the paste bin to be as close to the caret as possible to avoid scrolling
        if (lastRng.getClientRects) {
          var rect = getCaretRect(lastRng);

          if (rect) {
            // Client rects gets us closes to the actual
            // caret location in for example a wrapped paragraph block
            top = scrollTop + (rect.top - dom.getPos(body).y);
          } else {
            top = scrollTop;

            // Check if we can find a closer location by checking the range element
            var container = lastRng.startContainer;
            if (container) {
              if (container.nodeType === 3 && container.parentNode !== body) {
                container = container.parentNode;
              }

              if (container.nodeType === 1) {
                top = dom.getPos(container, scrollContainer || body).y;
              }
            }
          }
        }

        // Create a pastebin
        pasteBinElm = editor.dom.add(editor.getBody(), 'div', {
          id: "mcepastebin",
          contentEditable: true,
          "data-mce-bogus": "all",
          style: 'position: absolute; top: ' + top + 'px; width: 10px; height: 10px; overflow: hidden; opacity: 0'
        }, pasteBinDefaultContent);

        // Move paste bin out of sight since the controlSelection rect gets displayed otherwise on IE and Gecko
        if (Env.ie || Env.gecko) {
          dom.setStyle(pasteBinElm, 'left', dom.getStyle(body, 'direction', true) === 'rtl' ? 0xFFFF : -0xFFFF);
        }

        // Prevent focus events from bubbeling fixed FocusManager issues
        dom.bind(pasteBinElm, 'beforedeactivate focusin focusout', function (e) {
          e.stopPropagation();
        });

        pasteBinElm.focus();
        editor.selection.select(pasteBinElm, true);
      };

      /**
       * Removes the paste bin if it exists.
       */
      var remove = function () {
        if (getEl()) {
          var pasteBinClone;

          // WebKit/Blink might clone the div so
          // lets make sure we remove all clones
          // TODO: Man o man is this ugly. WebKit is the new IE! Remove this if they ever fix it!
          while ((pasteBinClone = editor.dom.get('mcepastebin'))) {
            editor.dom.remove(pasteBinClone);
            editor.dom.unbind(pasteBinClone);
          }

          if (lastRng) {
            editor.selection.setRng(lastRng);
          }
        }

        lastRng = null;
      };


      var getEl = function () {
        return editor.dom.get('mcepastebin');
      };

      /**
       * Returns the contents of the paste bin as a HTML string.
       *
       * @return {String} Get the contents of the paste bin.
       */
      var getHtml = function () {
        var pasteBinElm, pasteBinClones, i, dirtyWrappers, cleanWrapper;

        // Since WebKit/Chrome might clone the paste bin when pasting
        // for example: <img style="float: right"> we need to check if any of them contains some useful html.
        // TODO: Man o man is this ugly. WebKit is the new IE! Remove this if they ever fix it!

        var copyAndRemove = function (toElm, fromElm) {
          toElm.appendChild(fromElm);
          editor.dom.remove(fromElm, true); // remove, but keep children
        };

        // find only top level elements (there might be more nested inside them as well, see TINY-1162)
        pasteBinClones = Tools.grep(editor.getBody().childNodes, function (elm) {
          return elm.id === 'mcepastebin';
        });
        pasteBinElm = pasteBinClones.shift();

        // if clones were found, move their content into the first bin
        Tools.each(pasteBinClones, function (pasteBinClone) {
          copyAndRemove(pasteBinElm, pasteBinClone);
        });

        // TINY-1162: when copying plain text (from notepad for example) WebKit clones
        // paste bin (with styles and attributes) and uses it as a default  wrapper for
        // the chunks of the content, here we cycle over the whole paste bin and replace
        // those wrappers with a basic div
        dirtyWrappers = editor.dom.select('div[id=mcepastebin]', pasteBinElm);
        for (i = dirtyWrappers.length - 1; i >= 0; i--) {
          cleanWrapper = editor.dom.create('div');
          pasteBinElm.insertBefore(cleanWrapper, dirtyWrappers[i]);
          copyAndRemove(cleanWrapper, dirtyWrappers[i]);
        }

        return pasteBinElm ? pasteBinElm.innerHTML : '';
      };


      var getLastRng = function () {
        return lastRng;
      };


      var isDefaultContent = function (content) {
        return content === pasteBinDefaultContent;
      };


      var isPasteBin = function (elm) {
        return elm && elm.id === 'mcepastebin';
      };


      var isDefault = function () {
        var pasteBinElm = getEl();
        return isPasteBin(pasteBinElm) && isDefaultContent(pasteBinElm.innerHTML);
      };

      return {
        create: create,
        remove: remove,
        getEl: getEl,
        getHtml: getHtml,
        getLastRng: getLastRng,
        isDefault: isDefault,
        isDefaultContent: isDefaultContent
      };
    };
  }
);

/**
 * ResolveGlobal.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

define(
  'tinymce.core.html.DomParser',
  [
    'global!tinymce.util.Tools.resolve'
  ],
  function (resolve) {
    return resolve('tinymce.html.DomParser');
  }
);

/**
 * ResolveGlobal.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

define(
  'tinymce.core.html.Node',
  [
    'global!tinymce.util.Tools.resolve'
  ],
  function (resolve) {
    return resolve('tinymce.html.Node');
  }
);

/**
 * ResolveGlobal.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

define(
  'tinymce.core.html.Schema',
  [
    'global!tinymce.util.Tools.resolve'
  ],
  function (resolve) {
    return resolve('tinymce.html.Schema');
  }
);

/**
 * ResolveGlobal.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

define(
  'tinymce.core.html.Serializer',
  [
    'global!tinymce.util.Tools.resolve'
  ],
  function (resolve) {
    return resolve('tinymce.html.Serializer');
  }
);

/**
 * Utils.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * This class contails various utility functions for the paste plugin.
 *
 * @class tinymce.pasteplugin.Utils
 */
define(
  'tinymce.plugins.paste.core.Utils',
  [
    'global!navigator',
    'tinymce.core.html.DomParser',
    'tinymce.core.html.Schema',
    'tinymce.core.util.Tools'
  ],
  function (navigator, DomParser, Schema, Tools) {
    function filter(content, items) {
      Tools.each(items, function (v) {
        if (v.constructor === RegExp) {
          content = content.replace(v, '');
        } else {
          content = content.replace(v[0], v[1]);
        }
      });

      return content;
    }

    /**
     * Gets the innerText of the specified element. It will handle edge cases
     * and works better than textContent on Gecko.
     *
     * @param {String} html HTML string to get text from.
     * @return {String} String of text with line feeds.
     */
    function innerText(html) {
      var schema = new Schema(), domParser = new DomParser({}, schema), text = '';
      var shortEndedElements = schema.getShortEndedElements();
      var ignoreElements = Tools.makeMap('script noscript style textarea video audio iframe object', ' ');
      var blockElements = schema.getBlockElements();

      function walk(node) {
        var name = node.name, currentNode = node;

        if (name === 'br') {
          text += '\n';
          return;
        }

        // img/input/hr
        if (shortEndedElements[name]) {
          text += ' ';
        }

        // Ingore script, video contents
        if (ignoreElements[name]) {
          text += ' ';
          return;
        }

        if (node.type === 3) {
          text += node.value;
        }

        // Walk all children
        if (!node.shortEnded) {
          if ((node = node.firstChild)) {
            do {
              walk(node);
            } while ((node = node.next));
          }
        }

        // Add \n or \n\n for blocks or P
        if (blockElements[name] && currentNode.next) {
          text += '\n';

          if (name === 'p') {
            text += '\n';
          }
        }
      }

      html = filter(html, [
        /<!\[[^\]]+\]>/g // Conditional comments
      ]);

      walk(domParser.parse(html));

      return text;
    }

    /**
     * Trims the specified HTML by removing all WebKit fragments, all elements wrapping the body trailing BR elements etc.
     *
     * @param {String} html Html string to trim contents on.
     * @return {String} Html contents that got trimmed.
     */
    function trimHtml(html) {
      function trimSpaces(all, s1, s2) {
        // WebKit &nbsp; meant to preserve multiple spaces but instead inserted around all inline tags,
        // including the spans with inline styles created on paste
        if (!s1 && !s2) {
          return ' ';
        }

        return '\u00a0';
      }

      html = filter(html, [
        /^[\s\S]*<body[^>]*>\s*|\s*<\/body[^>]*>[\s\S]*$/ig, // Remove anything but the contents within the BODY element
        /<!--StartFragment-->|<!--EndFragment-->/g, // Inner fragments (tables from excel on mac)
        [/( ?)<span class="Apple-converted-space">\u00a0<\/span>( ?)/g, trimSpaces],
        /<br class="Apple-interchange-newline">/g,
        /<br>$/i // Trailing BR elements
      ]);

      return html;
    }

    // TODO: Should be in some global class
    function createIdGenerator(prefix) {
      var count = 0;

      return function () {
        return prefix + (count++);
      };
    }

    var isMsEdge = function () {
      return navigator.userAgent.indexOf(' Edge/') !== -1;
    };

    return {
      filter: filter,
      innerText: innerText,
      trimHtml: trimHtml,
      createIdGenerator: createIdGenerator,
      isMsEdge: isMsEdge
    };
  }
);

/**
 * WordFilter.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * This class parses word HTML into proper TinyMCE markup.
 *
 * @class tinymce.pasteplugin.WordFilter
 * @private
 */
define(
  'tinymce.plugins.paste.core.WordFilter',
  [
    'tinymce.core.html.DomParser',
    'tinymce.core.html.Node',
    'tinymce.core.html.Schema',
    'tinymce.core.html.Serializer',
    'tinymce.core.util.Tools',
    'tinymce.plugins.paste.api.Settings',
    'tinymce.plugins.paste.core.Utils'
  ],
  function (DomParser, Node, Schema, Serializer, Tools, Settings, Utils) {
    /**
     * Checks if the specified content is from any of the following sources: MS Word/Office 365/Google docs.
     */
    function isWordContent(content) {
      return (
        (/<font face="Times New Roman"|class="?Mso|style="[^"]*\bmso-|style='[^'']*\bmso-|w:WordDocument/i).test(content) ||
        (/class="OutlineElement/).test(content) ||
        (/id="?docs\-internal\-guid\-/.test(content))
      );
    }

    /**
     * Checks if the specified text starts with "1. " or "a. " etc.
     */
    function isNumericList(text) {
      var found, patterns;

      patterns = [
        /^[IVXLMCD]{1,2}\.[ \u00a0]/,  // Roman upper case
        /^[ivxlmcd]{1,2}\.[ \u00a0]/,  // Roman lower case
        /^[a-z]{1,2}[\.\)][ \u00a0]/,  // Alphabetical a-z
        /^[A-Z]{1,2}[\.\)][ \u00a0]/,  // Alphabetical A-Z
        /^[0-9]+\.[ \u00a0]/,          // Numeric lists
        /^[\u3007\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d]+\.[ \u00a0]/, // Japanese
        /^[\u58f1\u5f10\u53c2\u56db\u4f0d\u516d\u4e03\u516b\u4e5d\u62fe]+\.[ \u00a0]/  // Chinese
      ];

      text = text.replace(/^[\u00a0 ]+/, '');

      Tools.each(patterns, function (pattern) {
        if (pattern.test(text)) {
          found = true;
          return false;
        }
      });

      return found;
    }

    function isBulletList(text) {
      return /^[\s\u00a0]*[\u2022\u00b7\u00a7\u25CF]\s*/.test(text);
    }

    /**
     * Converts fake bullet and numbered lists to real semantic OL/UL.
     *
     * @param {tinymce.html.Node} node Root node to convert children of.
     */
    function convertFakeListsToProperLists(node) {
      var currentListNode, prevListNode, lastLevel = 1;

      function getText(node) {
        var txt = '';

        if (node.type === 3) {
          return node.value;
        }

        if ((node = node.firstChild)) {
          do {
            txt += getText(node);
          } while ((node = node.next));
        }

        return txt;
      }

      function trimListStart(node, regExp) {
        if (node.type === 3) {
          if (regExp.test(node.value)) {
            node.value = node.value.replace(regExp, '');
            return false;
          }
        }

        if ((node = node.firstChild)) {
          do {
            if (!trimListStart(node, regExp)) {
              return false;
            }
          } while ((node = node.next));
        }

        return true;
      }

      function removeIgnoredNodes(node) {
        if (node._listIgnore) {
          node.remove();
          return;
        }

        if ((node = node.firstChild)) {
          do {
            removeIgnoredNodes(node);
          } while ((node = node.next));
        }
      }

      function convertParagraphToLi(paragraphNode, listName, start) {
        var level = paragraphNode._listLevel || lastLevel;

        // Handle list nesting
        if (level !== lastLevel) {
          if (level < lastLevel) {
            // Move to parent list
            if (currentListNode) {
              currentListNode = currentListNode.parent.parent;
            }
          } else {
            // Create new list
            prevListNode = currentListNode;
            currentListNode = null;
          }
        }

        if (!currentListNode || currentListNode.name !== listName) {
          prevListNode = prevListNode || currentListNode;
          currentListNode = new Node(listName, 1);

          if (start > 1) {
            currentListNode.attr('start', '' + start);
          }

          paragraphNode.wrap(currentListNode);
        } else {
          currentListNode.append(paragraphNode);
        }

        paragraphNode.name = 'li';

        // Append list to previous list if it exists
        if (level > lastLevel && prevListNode) {
          prevListNode.lastChild.append(currentListNode);
        }

        lastLevel = level;

        // Remove start of list item "1. " or "&middot; " etc
        removeIgnoredNodes(paragraphNode);
        trimListStart(paragraphNode, /^\u00a0+/);
        trimListStart(paragraphNode, /^\s*([\u2022\u00b7\u00a7\u25CF]|\w+\.)/);
        trimListStart(paragraphNode, /^\u00a0+/);
      }

      // Build a list of all root level elements before we start
      // altering them in the loop below.
      var elements = [], child = node.firstChild;
      while (typeof child !== 'undefined' && child !== null) {
        elements.push(child);

        child = child.walk();
        if (child !== null) {
          while (typeof child !== 'undefined' && child.parent !== node) {
            child = child.walk();
          }
        }
      }

      for (var i = 0; i < elements.length; i++) {
        node = elements[i];

        if (node.name === 'p' && node.firstChild) {
          // Find first text node in paragraph
          var nodeText = getText(node);

          // Detect unordered lists look for bullets
          if (isBulletList(nodeText)) {
            convertParagraphToLi(node, 'ul');
            continue;
          }

          // Detect ordered lists 1., a. or ixv.
          if (isNumericList(nodeText)) {
            // Parse OL start number
            var matches = /([0-9]+)\./.exec(nodeText);
            var start = 1;
            if (matches) {
              start = parseInt(matches[1], 10);
            }

            convertParagraphToLi(node, 'ol', start);
            continue;
          }

          // Convert paragraphs marked as lists but doesn't look like anything
          if (node._listLevel) {
            convertParagraphToLi(node, 'ul', 1);
            continue;
          }

          currentListNode = null;
        } else {
          // If the root level element isn't a p tag which can be
          // processed by convertParagraphToLi, it interrupts the
          // lists, causing a new list to start instead of having
          // elements from the next list inserted above this tag.
          prevListNode = currentListNode;
          currentListNode = null;
        }
      }
    }

    function filterStyles(editor, validStyles, node, styleValue) {
      var outputStyles = {}, matches, styles = editor.dom.parseStyle(styleValue);

      Tools.each(styles, function (value, name) {
        // Convert various MS styles to W3C styles
        switch (name) {
          case 'mso-list':
            // Parse out list indent level for lists
            matches = /\w+ \w+([0-9]+)/i.exec(styleValue);
            if (matches) {
              node._listLevel = parseInt(matches[1], 10);
            }

            // Remove these nodes <span style="mso-list:Ignore">o</span>
            // Since the span gets removed we mark the text node and the span
            if (/Ignore/i.test(value) && node.firstChild) {
              node._listIgnore = true;
              node.firstChild._listIgnore = true;
            }

            break;

          case "horiz-align":
            name = "text-align";
            break;

          case "vert-align":
            name = "vertical-align";
            break;

          case "font-color":
          case "mso-foreground":
            name = "color";
            break;

          case "mso-background":
          case "mso-highlight":
            name = "background";
            break;

          case "font-weight":
          case "font-style":
            if (value !== "normal") {
              outputStyles[name] = value;
            }
            return;

          case "mso-element":
            // Remove track changes code
            if (/^(comment|comment-list)$/i.test(value)) {
              node.remove();
              return;
            }

            break;
        }

        if (name.indexOf('mso-comment') === 0) {
          node.remove();
          return;
        }

        // Never allow mso- prefixed names
        if (name.indexOf('mso-') === 0) {
          return;
        }

        // Output only valid styles
        if (Settings.getRetainStyleProps(editor) === "all" || (validStyles && validStyles[name])) {
          outputStyles[name] = value;
        }
      });

      // Convert bold style to "b" element
      if (/(bold)/i.test(outputStyles["font-weight"])) {
        delete outputStyles["font-weight"];
        node.wrap(new Node("b", 1));
      }

      // Convert italic style to "i" element
      if (/(italic)/i.test(outputStyles["font-style"])) {
        delete outputStyles["font-style"];
        node.wrap(new Node("i", 1));
      }

      // Serialize the styles and see if there is something left to keep
      outputStyles = editor.dom.serializeStyle(outputStyles, node.name);
      if (outputStyles) {
        return outputStyles;
      }

      return null;
    }

    var filterWordContent = function (editor, content) {
      var retainStyleProperties, validStyles;

      retainStyleProperties = Settings.getRetainStyleProps(editor);
      if (retainStyleProperties) {
        validStyles = Tools.makeMap(retainStyleProperties.split(/[, ]/));
      }

      // Remove basic Word junk
      content = Utils.filter(content, [
        // Remove apple new line markers
        /<br class="?Apple-interchange-newline"?>/gi,

        // Remove google docs internal guid markers
        /<b[^>]+id="?docs-internal-[^>]*>/gi,

        // Word comments like conditional comments etc
        /<!--[\s\S]+?-->/gi,

        // Remove comments, scripts (e.g., msoShowComment), XML tag, VML content,
        // MS Office namespaced tags, and a few other tags
        /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,

        // Convert <s> into <strike> for line-though
        [/<(\/?)s>/gi, "<$1strike>"],

        // Replace nsbp entites to char since it's easier to handle
        [/&nbsp;/gi, "\u00a0"],

        // Convert <span style="mso-spacerun:yes">___</span> to string of alternating
        // breaking/non-breaking spaces of same length
        [/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi,
          function (str, spaces) {
            return (spaces.length > 0) ?
              spaces.replace(/./, " ").slice(Math.floor(spaces.length / 2)).split("").join("\u00a0") : "";
          }
        ]
      ]);

      var validElements = Settings.getWordValidElements(editor);

      // Setup strict schema
      var schema = new Schema({
        valid_elements: validElements,
        valid_children: '-li[p]'
      });

      // Add style/class attribute to all element rules since the user might have removed them from
      // paste_word_valid_elements config option and we need to check them for properties
      Tools.each(schema.elements, function (rule) {
        /*eslint dot-notation:0*/
        if (!rule.attributes["class"]) {
          rule.attributes["class"] = {};
          rule.attributesOrder.push("class");
        }

        if (!rule.attributes.style) {
          rule.attributes.style = {};
          rule.attributesOrder.push("style");
        }
      });

      // Parse HTML into DOM structure
      var domParser = new DomParser({}, schema);

      // Filter styles to remove "mso" specific styles and convert some of them
      domParser.addAttributeFilter('style', function (nodes) {
        var i = nodes.length, node;

        while (i--) {
          node = nodes[i];
          node.attr('style', filterStyles(editor, validStyles, node, node.attr('style')));

          // Remove pointess spans
          if (node.name === 'span' && node.parent && !node.attributes.length) {
            node.unwrap();
          }
        }
      });

      // Check the class attribute for comments or del items and remove those
      domParser.addAttributeFilter('class', function (nodes) {
        var i = nodes.length, node, className;

        while (i--) {
          node = nodes[i];

          className = node.attr('class');
          if (/^(MsoCommentReference|MsoCommentText|msoDel)$/i.test(className)) {
            node.remove();
          }

          node.attr('class', null);
        }
      });

      // Remove all del elements since we don't want the track changes code in the editor
      domParser.addNodeFilter('del', function (nodes) {
        var i = nodes.length;

        while (i--) {
          nodes[i].remove();
        }
      });

      // Keep some of the links and anchors
      domParser.addNodeFilter('a', function (nodes) {
        var i = nodes.length, node, href, name;

        while (i--) {
          node = nodes[i];
          href = node.attr('href');
          name = node.attr('name');

          if (href && href.indexOf('#_msocom_') !== -1) {
            node.remove();
            continue;
          }

          if (href && href.indexOf('file://') === 0) {
            href = href.split('#')[1];
            if (href) {
              href = '#' + href;
            }
          }

          if (!href && !name) {
            node.unwrap();
          } else {
            // Remove all named anchors that aren't specific to TOC, Footnotes or Endnotes
            if (name && !/^_?(?:toc|edn|ftn)/i.test(name)) {
              node.unwrap();
              continue;
            }

            node.attr({
              href: href,
              name: name
            });
          }
        }
      });

      // Parse into DOM structure
      var rootNode = domParser.parse(content);

      // Process DOM
      if (Settings.shouldConvertWordFakeLists(editor)) {
        convertFakeListsToProperLists(rootNode);
      }

      // Serialize DOM back to HTML
      content = new Serializer({
        validate: editor.settings.validate
      }, schema).serialize(rootNode);

      return content;
    };

    var preProcess = function (editor, content) {
      return Settings.shouldUseDefaultFilters(editor) ? filterWordContent(editor, content) : content;
    };

    return {
      preProcess: preProcess,
      isWordContent: isWordContent
    };
  }
);

/**
 * ProcessFilters.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

define(
  'tinymce.plugins.paste.core.ProcessFilters',
  [
    'tinymce.plugins.paste.api.Events',
    'tinymce.plugins.paste.core.WordFilter'
  ],
  function (Events, WordFilter) {
    var processResult = function (content, cancelled) {
      return { content: content, cancelled: cancelled };
    };

    var postProcessFilter = function (editor, html, internal, isWordHtml) {
      var tempBody = editor.dom.create('div', { style: 'display:none' }, html);
      var postProcessArgs = Events.firePastePostProcess(editor, tempBody, internal, isWordHtml);
      return processResult(postProcessArgs.node.innerHTML, postProcessArgs.isDefaultPrevented());
    };

    var filterContent = function (editor, content, internal, isWordHtml) {
      var preProcessArgs = Events.firePastePreProcess(editor, content, internal, isWordHtml);

      if (editor.hasEventListeners('PastePostProcess') && !preProcessArgs.isDefaultPrevented()) {
        return postProcessFilter(editor, preProcessArgs.content, internal, isWordHtml);
      } else {
        return processResult(preProcessArgs.content, preProcessArgs.isDefaultPrevented());
      }
    };

    var process = function (editor, html, internal) {
      var isWordHtml = WordFilter.isWordContent(html);
      var content = isWordHtml ? WordFilter.preProcess(editor, html) : html;

      return filterContent(editor, content, internal, isWordHtml);
    };

    return {
      process: process
    };
  }
);

/**
 * SmartPaste.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * Tries to be smart depending on what the user pastes if it looks like an url
 * it will make a link out of the current selection. If it's an image url that looks
 * like an image it will check if it's an image and insert it as an image.
 *
 * @class tinymce.pasteplugin.SmartPaste
 * @private
 */
define(
  'tinymce.plugins.paste.core.SmartPaste',
  [
    'tinymce.core.util.Tools',
    'tinymce.plugins.paste.api.Settings'
  ],
  function (Tools, Settings) {
    var isAbsoluteUrl = function (url) {
      return /^https?:\/\/[\w\?\-\/+=.&%@~#]+$/i.test(url);
    };

    var isImageUrl = function (url) {
      return isAbsoluteUrl(url) && /.(gif|jpe?g|png)$/.test(url);
    };

    var createImage = function (editor, url, pasteHtml) {
      editor.undoManager.extra(function () {
        pasteHtml(editor, url);
      }, function () {
        editor.insertContent('<img src="' + url + '">');
      });

      return true;
    };

    var createLink = function (editor, url, pasteHtml) {
      editor.undoManager.extra(function () {
        pasteHtml(editor, url);
      }, function () {
        editor.execCommand('mceInsertLink', false, url);
      });

      return true;
    };

    var linkSelection = function (editor, html, pasteHtml) {
      return editor.selection.isCollapsed() === false && isAbsoluteUrl(html) ? createLink(editor, html, pasteHtml) : false;
    };

    var insertImage = function (editor, html, pasteHtml) {
      return isImageUrl(html) ? createImage(editor, html, pasteHtml) : false;
    };

    var pasteHtml = function (editor, html) {
      editor.insertContent(html, {
        merge: Settings.shouldMergeFormats(editor),
        paste: true
      });

      return true;
    };

    var smartInsertContent = function (editor, html) {
      Tools.each([
        linkSelection,
        insertImage,
        pasteHtml
      ], function (action) {
        return action(editor, html, pasteHtml) !== true;
      });
    };

    var insertContent = function (editor, html) {
      if (Settings.isSmartPasteEnabled(editor) === false) {
        pasteHtml(editor, html);
      } else {
        smartInsertContent(editor, html);
      }
    };

    return {
      isImageUrl: isImageUrl,
      isAbsoluteUrl: isAbsoluteUrl,
      insertContent: insertContent
    };
  }
);

/**
 * Clipboard.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * This class contains logic for getting HTML contents out of the clipboard.
 *
 * We need to make a lot of ugly hacks to get the contents out of the clipboard since
 * the W3C Clipboard API is broken in all browsers that have it: Gecko/WebKit/Blink.
 * We might rewrite this the way those API:s stabilize. Browsers doesn't handle pasting
 * from applications like Word the same way as it does when pasting into a contentEditable area
 * so we need to do lots of extra work to try to get to this clipboard data.
 *
 * Current implementation steps:
 *  1. On keydown with paste keys Ctrl+V or Shift+Insert create
 *     a paste bin element and move focus to that element.
 *  2. Wait for the browser to fire a "paste" event and get the contents out of the paste bin.
 *  3. Check if the paste was successful if true, process the HTML.
 *  (4). If the paste was unsuccessful use IE execCommand, Clipboard API, document.dataTransfer old WebKit API etc.
 *
 * @class tinymce.pasteplugin.Clipboard
 * @private
 */
define(
  'tinymce.plugins.paste.core.Clipboard',
  [
    'global!Image',
    'global!navigator',
    'global!window',
    'tinymce.core.Env',
    'tinymce.core.util.Delay',
    'tinymce.core.util.Tools',
    'tinymce.core.util.VK',
    'tinymce.plugins.paste.api.Events',
    'tinymce.plugins.paste.api.Settings',
    'tinymce.plugins.paste.core.InternalHtml',
    'tinymce.plugins.paste.core.Newlines',
    'tinymce.plugins.paste.core.PasteBin',
    'tinymce.plugins.paste.core.ProcessFilters',
    'tinymce.plugins.paste.core.SmartPaste',
    'tinymce.plugins.paste.core.Utils'
  ],
  function (Image, navigator, window, Env, Delay, Tools, VK, Events, Settings, InternalHtml, Newlines, PasteBin, ProcessFilters, SmartPaste, Utils) {
    return function (editor) {
      var self = this, keyboardPasteTimeStamp = 0;
      var pasteBin = new PasteBin(editor);
      var keyboardPastePlainTextState;
      var mceInternalUrlPrefix = 'data:text/mce-internal,';
      var uniqueId = Utils.createIdGenerator("mceclip");

      self.pasteFormat = Settings.isPasteAsTextEnabled(editor) ? 'text' : 'html';

      /**
       * Pastes the specified HTML. This means that the HTML is filtered and then
       * inserted at the current selection in the editor. It will also fire paste events
       * for custom user filtering.
       *
       * @param {String} html HTML code to paste into the current selection.
       * @param {Boolean?} internalFlag Optional true/false flag if the contents is internal or external.
       */
      function pasteHtml(html, internalFlag) {
        var internal = internalFlag ? internalFlag : InternalHtml.isMarked(html);
        var args = ProcessFilters.process(editor, InternalHtml.unmark(html), internal);

        if (args.cancelled === false) {
          SmartPaste.insertContent(editor, args.content);
        }
      }

      /**
       * Pastes the specified text. This means that the plain text is processed
       * and converted into BR and P elements. It will fire paste events for custom filtering.
       *
       * @param {String} text Text to paste as the current selection location.
       */
      function pasteText(text) {
        text = editor.dom.encode(text).replace(/\r\n/g, '\n');
        text = Newlines.convert(text, editor.settings.forced_root_block, editor.settings.forced_root_block_attrs);

        pasteHtml(text, false);
      }


      /**
       * Gets various content types out of a datatransfer object.
       *
       * @param {DataTransfer} dataTransfer Event fired on paste.
       * @return {Object} Object with mime types and data for those mime types.
       */
      function getDataTransferItems(dataTransfer) {
        var items = {};

        if (dataTransfer) {
          // Use old WebKit/IE API
          if (dataTransfer.getData) {
            var legacyText = dataTransfer.getData('Text');
            if (legacyText && legacyText.length > 0) {
              if (legacyText.indexOf(mceInternalUrlPrefix) === -1) {
                items['text/plain'] = legacyText;
              }
            }
          }

          if (dataTransfer.types) {
            for (var i = 0; i < dataTransfer.types.length; i++) {
              var contentType = dataTransfer.types[i];
              try { // IE11 throws exception when contentType is Files (type is present but data cannot be retrieved via getData())
                items[contentType] = dataTransfer.getData(contentType);
              } catch (ex) {
                items[contentType] = ""; // useless in general, but for consistency across browsers
              }
            }
          }
        }

        return items;
      }

      /**
       * Gets various content types out of the Clipboard API. It will also get the
       * plain text using older IE and WebKit API:s.
       *
       * @param {ClipboardEvent} clipboardEvent Event fired on paste.
       * @return {Object} Object with mime types and data for those mime types.
       */
      function getClipboardContent(clipboardEvent) {
        var content = getDataTransferItems(clipboardEvent.clipboardData || editor.getDoc().dataTransfer);

        // Edge 15 has a broken HTML Clipboard API see https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/11877517/
        return Utils.isMsEdge() ? Tools.extend(content, { 'text/html': '' }) : content;
      }

      function hasHtmlOrText(content) {
        return hasContentType(content, 'text/html') || hasContentType(content, 'text/plain');
      }

      function getBase64FromUri(uri) {
        var idx;

        idx = uri.indexOf(',');
        if (idx !== -1) {
          return uri.substr(idx + 1);
        }

        return null;
      }

      function isValidDataUriImage(settings, imgElm) {
        return settings.images_dataimg_filter ? settings.images_dataimg_filter(imgElm) : true;
      }

      function extractFilename(str) {
        var m = str.match(/([\s\S]+?)\.(?:jpeg|jpg|png|gif)$/i);
        return m ? editor.dom.encode(m[1]) : null;
      }

      function pasteImage(rng, reader, blob) {
        if (rng) {
          editor.selection.setRng(rng);
          rng = null;
        }

        var dataUri = reader.result;
        var base64 = getBase64FromUri(dataUri);
        var id = uniqueId();
        var name = editor.settings.images_reuse_filename && blob.name ? extractFilename(blob.name) : id;
        var img = new Image();

        img.src = dataUri;

        // TODO: Move the bulk of the cache logic to EditorUpload
        if (isValidDataUriImage(editor.settings, img)) {
          var blobCache = editor.editorUpload.blobCache;
          var blobInfo, existingBlobInfo;

          existingBlobInfo = blobCache.findFirst(function (cachedBlobInfo) {
            return cachedBlobInfo.base64() === base64;
          });

          if (!existingBlobInfo) {
            blobInfo = blobCache.create(id, blob, base64, name);
            blobCache.add(blobInfo);
          } else {
            blobInfo = existingBlobInfo;
          }

          pasteHtml('<img src="' + blobInfo.blobUri() + '">', false);
        } else {
          pasteHtml('<img src="' + dataUri + '">', false);
        }
      }

      /**
       * Checks if the clipboard contains image data if it does it will take that data
       * and convert it into a data url image and paste that image at the caret location.
       *
       * @param  {ClipboardEvent} e Paste/drop event object.
       * @param  {DOMRange} rng Rng object to move selection to.
       * @return {Boolean} true/false if the image data was found or not.
       */
      function pasteImageData(e, rng) {
        var dataTransfer = e.clipboardData || e.dataTransfer;

        function processItems(items) {
          var i, item, reader, hadImage = false;

          if (items) {
            for (i = 0; i < items.length; i++) {
              item = items[i];

              if (/^image\/(jpeg|png|gif|bmp)$/.test(item.type)) {
                var blob = item.getAsFile ? item.getAsFile() : item;

                reader = new window.FileReader();
                reader.onload = pasteImage.bind(null, rng, reader, blob);
                reader.readAsDataURL(blob);

                e.preventDefault();
                hadImage = true;
              }
            }
          }

          return hadImage;
        }

        if (editor.settings.paste_data_images && dataTransfer) {
          return processItems(dataTransfer.items) || processItems(dataTransfer.files);
        }
      }

      /**
       * Chrome on Android doesn't support proper clipboard access so we have no choice but to allow the browser default behavior.
       *
       * @param {Event} e Paste event object to check if it contains any data.
       * @return {Boolean} true/false if the clipboard is empty or not.
       */
      function isBrokenAndroidClipboardEvent(e) {
        var clipboardData = e.clipboardData;

        return navigator.userAgent.indexOf('Android') !== -1 && clipboardData && clipboardData.items && clipboardData.items.length === 0;
      }

      function hasContentType(clipboardContent, mimeType) {
        return mimeType in clipboardContent && clipboardContent[mimeType].length > 0;
      }

      function isKeyboardPasteEvent(e) {
        return (VK.metaKeyPressed(e) && e.keyCode === 86) || (e.shiftKey && e.keyCode === 45);
      }

      function registerEventHandlers() {
        editor.on('keydown', function (e) {
          function removePasteBinOnKeyUp(e) {
            // Ctrl+V or Shift+Insert
            if (isKeyboardPasteEvent(e) && !e.isDefaultPrevented()) {
              pasteBin.remove();
            }
          }

          // Ctrl+V or Shift+Insert
          if (isKeyboardPasteEvent(e) && !e.isDefaultPrevented()) {
            keyboardPastePlainTextState = e.shiftKey && e.keyCode === 86;

            // Edge case on Safari on Mac where it doesn't handle Cmd+Shift+V correctly
            // it fires the keydown but no paste or keyup so we are left with a paste bin
            if (keyboardPastePlainTextState && Env.webkit && navigator.userAgent.indexOf('Version/') !== -1) {
              return;
            }

            // Prevent undoManager keydown handler from making an undo level with the pastebin in it
            e.stopImmediatePropagation();

            keyboardPasteTimeStamp = new Date().getTime();

            // IE doesn't support Ctrl+Shift+V and it doesn't even produce a paste event
            // so lets fake a paste event and let IE use the execCommand/dataTransfer methods
            if (Env.ie && keyboardPastePlainTextState) {
              e.preventDefault();
              Events.firePaste(editor, true);
              return;
            }

            pasteBin.remove();
            pasteBin.create();

            // Remove pastebin if we get a keyup and no paste event
            // For example pasting a file in IE 11 will not produce a paste event
            editor.once('keyup', removePasteBinOnKeyUp);
            editor.once('paste', function () {
              editor.off('keyup', removePasteBinOnKeyUp);
            });
          }
        });

        function insertClipboardContent(clipboardContent, isKeyBoardPaste, plainTextMode, internal) {
          var content, isPlainTextHtml;

          // Grab HTML from Clipboard API or paste bin as a fallback
          if (hasContentType(clipboardContent, 'text/html')) {
            content = clipboardContent['text/html'];
          } else {
            content = pasteBin.getHtml();
            internal = internal ? internal : InternalHtml.isMarked(content);

            // If paste bin is empty try using plain text mode
            // since that is better than nothing right
            if (pasteBin.isDefaultContent(content)) {
              plainTextMode = true;
            }
          }

          content = Utils.trimHtml(content);

          pasteBin.remove();

          isPlainTextHtml = (internal === false && Newlines.isPlainText(content));

          // If we got nothing from clipboard API and pastebin or the content is a plain text (with only
          // some BRs, Ps or DIVs as newlines) then we fallback to plain/text
          if (!content.length || isPlainTextHtml) {
            plainTextMode = true;
          }

          // Grab plain text from Clipboard API or convert existing HTML to plain text
          if (plainTextMode) {
            // Use plain text contents from Clipboard API unless the HTML contains paragraphs then
            // we should convert the HTML to plain text since works better when pasting HTML/Word contents as plain text
            if (hasContentType(clipboardContent, 'text/plain') && isPlainTextHtml) {
              content = clipboardContent['text/plain'];
            } else {
              content = Utils.innerText(content);
            }
          }

          // If the content is the paste bin default HTML then it was
          // impossible to get the cliboard data out.
          if (pasteBin.isDefaultContent(content)) {
            if (!isKeyBoardPaste) {
              editor.windowManager.alert('Please use Ctrl+V/Cmd+V keyboard shortcuts to paste contents.');
            }

            return;
          }

          if (plainTextMode) {
            pasteText(content);
          } else {
            pasteHtml(content, internal);
          }
        }

        var getLastRng = function () {
          return pasteBin.getLastRng() || editor.selection.getRng();
        };

        editor.on('paste', function (e) {
          // Getting content from the Clipboard can take some time
          var clipboardTimer = new Date().getTime();
          var clipboardContent = getClipboardContent(e);
          var clipboardDelay = new Date().getTime() - clipboardTimer;

          var isKeyBoardPaste = (new Date().getTime() - keyboardPasteTimeStamp - clipboardDelay) < 1000;
          var plainTextMode = self.pasteFormat === "text" || keyboardPastePlainTextState;
          var internal = hasContentType(clipboardContent, InternalHtml.internalHtmlMime());

          keyboardPastePlainTextState = false;

          if (e.isDefaultPrevented() || isBrokenAndroidClipboardEvent(e)) {
            pasteBin.remove();
            return;
          }

          if (!hasHtmlOrText(clipboardContent) && pasteImageData(e, getLastRng())) {
            pasteBin.remove();
            return;
          }

          // Not a keyboard paste prevent default paste and try to grab the clipboard contents using different APIs
          if (!isKeyBoardPaste) {
            e.preventDefault();
          }

          // Try IE only method if paste isn't a keyboard paste
          if (Env.ie && (!isKeyBoardPaste || e.ieFake) && !hasContentType(clipboardContent, 'text/html')) {
            pasteBin.create();

            editor.dom.bind(pasteBin.getEl(), 'paste', function (e) {
              e.stopPropagation();
            });

            editor.getDoc().execCommand('Paste', false, null);
            clipboardContent["text/html"] = pasteBin.getHtml();
          }

          // If clipboard API has HTML then use that directly
          if (hasContentType(clipboardContent, 'text/html')) {
            e.preventDefault();

            // if clipboard lacks internal mime type, inspect html for internal markings
            if (!internal) {
              internal = InternalHtml.isMarked(clipboardContent['text/html']);
            }

            insertClipboardContent(clipboardContent, isKeyBoardPaste, plainTextMode, internal);
          } else {
            Delay.setEditorTimeout(editor, function () {
              insertClipboardContent(clipboardContent, isKeyBoardPaste, plainTextMode, internal);
            }, 0);
          }
        });
      }

      self.pasteHtml = pasteHtml;
      self.pasteText = pasteText;
      self.pasteImageData = pasteImageData;
      self.getDataTransferItems = getDataTransferItems;
      self.hasHtmlOrText = hasHtmlOrText;
      self.hasContentType = hasContentType;

      editor.on('preInit', function () {
        registerEventHandlers();

        // Remove all data images from paste for example from Gecko
        // except internal images like video elements
        editor.parser.addNodeFilter('img', function (nodes, name, args) {
          function isPasteInsert(args) {
            return args.data && args.data.paste === true;
          }

          function remove(node) {
            if (!node.attr('data-mce-object') && src !== Env.transparentSrc) {
              node.remove();
            }
          }

          function isWebKitFakeUrl(src) {
            return src.indexOf("webkit-fake-url") === 0;
          }

          function isDataUri(src) {
            return src.indexOf("data:") === 0;
          }

          if (!editor.settings.paste_data_images && isPasteInsert(args)) {
            var i = nodes.length;

            while (i--) {
              var src = nodes[i].attributes.map.src;

              if (!src) {
                continue;
              }

              // Safari on Mac produces webkit-fake-url see: https://bugs.webkit.org/show_bug.cgi?id=49141
              if (isWebKitFakeUrl(src)) {
                remove(nodes[i]);
              } else if (!editor.settings.allow_html_data_urls && isDataUri(src)) {
                remove(nodes[i]);
              }
            }
          }
        });
      });
    };
  }
);

defineGlobal("global!setTimeout", setTimeout);
/**
 * CutCopy.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

define(
  'tinymce.plugins.paste.core.CutCopy',
  [
    'global!setTimeout',
    'tinymce.core.Env',
    'tinymce.plugins.paste.core.InternalHtml',
    'tinymce.plugins.paste.core.Utils'
  ],
  function (setTimeout, Env, InternalHtml, Utils) {
    var noop = function () {
    };

    var hasWorkingClipboardApi = function (clipboardData) {
      // iOS supports the clipboardData API but it doesn't do anything for cut operations
      // Edge 15 has a broken HTML Clipboard API see https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/11780845/
      return Env.iOS === false && clipboardData !== undefined && typeof clipboardData.setData === 'function' && Utils.isMsEdge() !== true;
    };

    var setHtml5Clipboard = function (clipboardData, html, text) {
      if (hasWorkingClipboardApi(clipboardData)) {
        try {
          clipboardData.clearData();
          clipboardData.setData('text/html', html);
          clipboardData.setData('text/plain', text);
          clipboardData.setData(InternalHtml.internalHtmlMime(), html);
          return true;
        } catch (e) {
          return false;
        }
      } else {
        return false;
      }
    };

    var setClipboardData = function (evt, data, fallback, done) {
      if (setHtml5Clipboard(evt.clipboardData, data.html, data.text)) {
        evt.preventDefault();
        done();
      } else {
        fallback(data.html, done);
      }
    };

    var fallback = function (editor) {
      return function (html, done) {
        var markedHtml = InternalHtml.mark(html);
        var outer = editor.dom.create('div', {
          contenteditable: "false",
          "data-mce-bogus": "all"
        });
        var inner = editor.dom.create('div', { contenteditable: "true" }, markedHtml);
        editor.dom.setStyles(outer, {
          position: 'fixed',
          left: '-3000px',
          width: '1000px',
          overflow: 'hidden'
        });
        outer.appendChild(inner);
        editor.dom.add(editor.getBody(), outer);

        var range = editor.selection.getRng();
        inner.focus();

        var offscreenRange = editor.dom.createRng();
        offscreenRange.selectNodeContents(inner);
        editor.selection.setRng(offscreenRange);

        setTimeout(function () {
          outer.parentNode.removeChild(outer);
          editor.selection.setRng(range);
          done();
        }, 0);
      };
    };

    var getData = function (editor) {
      return {
        html: editor.selection.getContent({ contextual: true }),
        text: editor.selection.getContent({ format: 'text' })
      };
    };

    var cut = function (editor) {
      return function (evt) {
        if (editor.selection.isCollapsed() === false) {
          setClipboardData(evt, getData(editor), fallback(editor), function () {
            // Chrome fails to execCommand from another execCommand with this message:
            // "We don't execute document.execCommand() this time, because it is called recursively.""
            setTimeout(function () { // detach
              editor.execCommand('Delete');
            }, 0);
          });
        }
      };
    };

    var copy = function (editor) {
      return function (evt) {
        if (editor.selection.isCollapsed() === false) {
          setClipboardData(evt, getData(editor), fallback(editor), noop);
        }
      };
    };

    var register = function (editor) {
      editor.on('cut', cut(editor));
      editor.on('copy', copy(editor));
    };

    return {
      register: register
    };
  }
);
/**
 * ResolveGlobal.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

define(
  'tinymce.core.api.dom.RangeUtils',
  [
    'global!tinymce.util.Tools.resolve'
  ],
  function (resolve) {
    return resolve('tinymce.dom.RangeUtils');
  }
);

/**
 * DragDrop.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

define(
  'tinymce.plugins.paste.core.DragDrop',
  [
    'tinymce.core.api.dom.RangeUtils',
    'tinymce.core.util.Delay',
    'tinymce.plugins.paste.api.Settings',
    'tinymce.plugins.paste.core.InternalHtml',
    'tinymce.plugins.paste.core.Utils'
  ],
  function (RangeUtils, Delay, Settings, InternalHtml, Utils) {
    var getCaretRangeFromEvent = function (editor, e) {
      return RangeUtils.getCaretRangeFromPoint(e.clientX, e.clientY, editor.getDoc());
    };

    var isPlainTextFileUrl = function (content) {
      var plainTextContent = content['text/plain'];
      return plainTextContent ? plainTextContent.indexOf('file://') === 0 : false;
    };

    var setFocusedRange = function (editor, rng) {
      editor.focus();
      editor.selection.setRng(rng);
    };

    var setup = function (editor, clipboard, draggingInternallyState) {
      // Block all drag/drop events
      if (Settings.shouldBlockDrop(editor)) {
        editor.on('dragend dragover draggesture dragdrop drop drag', function (e) {
          e.preventDefault();
          e.stopPropagation();
        });
      }

      // Prevent users from dropping data images on Gecko
      if (!Settings.shouldPasteDataImages(editor)) {
        editor.on('drop', function (e) {
          var dataTransfer = e.dataTransfer;

          if (dataTransfer && dataTransfer.files && dataTransfer.files.length > 0) {
            e.preventDefault();
          }
        });
      }

      editor.on('drop', function (e) {
        var dropContent, rng;

        rng = getCaretRangeFromEvent(editor, e);

        if (e.isDefaultPrevented() || draggingInternallyState.get()) {
          return;
        }

        dropContent = clipboard.getDataTransferItems(e.dataTransfer);
        var internal = clipboard.hasContentType(dropContent, InternalHtml.internalHtmlMime());

        if ((!clipboard.hasHtmlOrText(dropContent) || isPlainTextFileUrl(dropContent)) && clipboard.pasteImageData(e, rng)) {
          return;
        }

        if (rng && Settings.shouldFilterDrop(editor)) {
          var content = dropContent['mce-internal'] || dropContent['text/html'] || dropContent['text/plain'];

          if (content) {
            e.preventDefault();

            // FF 45 doesn't paint a caret when dragging in text in due to focus call by execCommand
            Delay.setEditorTimeout(editor, function () {
              editor.undoManager.transact(function () {
                if (dropContent['mce-internal']) {
                  editor.execCommand('Delete');
                }

                setFocusedRange(editor, rng);

                content = Utils.trimHtml(content);

                if (!dropContent['text/html']) {
                  clipboard.pasteText(content);
                } else {
                  clipboard.pasteHtml(content, internal);
                }
              });
            });
          }
        }
      });

      editor.on('dragstart', function (e) {
        draggingInternallyState.set(true);
      });

      editor.on('dragover dragend', function (e) {
        if (Settings.shouldPasteDataImages(editor) && draggingInternallyState.get() === false) {
          e.preventDefault();
          setFocusedRange(editor, getCaretRangeFromEvent(editor, e));
        }

        if (e.type === 'dragend') {
          draggingInternallyState.set(false);
        }
      });
    };

    return {
      setup: setup
    };
  }
);
/**
 * Plugin.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

define(
  'tinymce.plugins.paste.core.PrePostProcess',
  [
    'tinymce.plugins.paste.api.Settings'
  ],
  function (Settings) {
    var setup = function (editor) {
      var plugin = editor.plugins.paste;

      var preProcess = Settings.getPreProcess(editor);
      if (preProcess) {
        editor.on('PastePreProcess', function (e) {
          preProcess.call(plugin, plugin, e);
        });
      }

      var postProcess = Settings.getPostProcess(editor);
      if (postProcess) {
        editor.on('PastePostProcess', function (e) {
          postProcess.call(plugin, plugin, e);
        });
      }
    };

    return {
      setup: setup
    };
  }
);

/**
 * Quirks.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * This class contains various fixes for browsers. These issues can not be feature
 * detected since we have no direct control over the clipboard. However we might be able
 * to remove some of these fixes once the browsers gets updated/fixed.
 *
 * @class tinymce.pasteplugin.Quirks
 * @private
 */
define(
  'tinymce.plugins.paste.core.Quirks',
  [
    'tinymce.core.Env',
    'tinymce.core.util.Tools',
    'tinymce.plugins.paste.api.Settings',
    'tinymce.plugins.paste.core.Utils',
    'tinymce.plugins.paste.core.WordFilter'
  ],
  function (Env, Tools, Settings, Utils, WordFilter) {
    function addPreProcessFilter(editor, filterFunc) {
      editor.on('PastePreProcess', function (e) {
        e.content = filterFunc(editor, e.content, e.internal, e.wordContent);
      });
    }

    function addPostProcessFilter(editor, filterFunc) {
      editor.on('PastePostProcess', function (e) {
        filterFunc(editor, e.node);
      });
    }

    /**
     * Removes BR elements after block elements. IE9 has a nasty bug where it puts a BR element after each
     * block element when pasting from word. This removes those elements.
     *
     * This:
     *  <p>a</p><br><p>b</p>
     *
     * Becomes:
     *  <p>a</p><p>b</p>
     */
    function removeExplorerBrElementsAfterBlocks(editor, html) {
      // Only filter word specific content
      if (!WordFilter.isWordContent(html)) {
        return html;
      }

      // Produce block regexp based on the block elements in schema
      var blockElements = [];

      Tools.each(editor.schema.getBlockElements(), function (block, blockName) {
        blockElements.push(blockName);
      });

      var explorerBlocksRegExp = new RegExp(
        '(?:<br>&nbsp;[\\s\\r\\n]+|<br>)*(<\\/?(' + blockElements.join('|') + ')[^>]*>)(?:<br>&nbsp;[\\s\\r\\n]+|<br>)*',
        'g'
      );

      // Remove BR:s from: <BLOCK>X</BLOCK><BR>
      html = Utils.filter(html, [
        [explorerBlocksRegExp, '$1']
      ]);

      // IE9 also adds an extra BR element for each soft-linefeed and it also adds a BR for each word wrap break
      html = Utils.filter(html, [
        [/<br><br>/g, '<BR><BR>'], // Replace multiple BR elements with uppercase BR to keep them intact
        [/<br>/g, ' '],            // Replace single br elements with space since they are word wrap BR:s
        [/<BR><BR>/g, '<br>']      // Replace back the double brs but into a single BR
      ]);

      return html;
    }

    /**
     * WebKit has a nasty bug where the all computed styles gets added to style attributes when copy/pasting contents.
     * This fix solves that by simply removing the whole style attribute.
     *
     * The paste_webkit_styles option can be set to specify what to keep:
     *  paste_webkit_styles: "none" // Keep no styles
     *  paste_webkit_styles: "all", // Keep all of them
     *  paste_webkit_styles: "font-weight color" // Keep specific ones
     */
    function removeWebKitStyles(editor, content, internal, isWordHtml) {
      // WordFilter has already processed styles at this point and internal doesn't need any processing
      if (isWordHtml || internal) {
        return content;
      }

      // Filter away styles that isn't matching the target node
      var webKitStyles = Settings.getWebkitStyles(editor);

      if (Settings.shouldRemoveWebKitStyles(editor) === false || webKitStyles === "all") {
        return content;
      }

      if (webKitStyles) {
        webKitStyles = webKitStyles.split(/[, ]/);
      }

      // Keep specific styles that doesn't match the current node computed style
      if (webKitStyles) {
        var dom = editor.dom, node = editor.selection.getNode();

        content = content.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi, function (all, before, value, after) {
          var inputStyles = dom.parseStyle(dom.decode(value), 'span');
          var outputStyles = {};

          if (webKitStyles === "none") {
            return before + after;
          }

          for (var i = 0; i < webKitStyles.length; i++) {
            var inputValue = inputStyles[webKitStyles[i]], currentValue = dom.getStyle(node, webKitStyles[i], true);

            if (/color/.test(webKitStyles[i])) {
              inputValue = dom.toHex(inputValue);
              currentValue = dom.toHex(currentValue);
            }

            if (currentValue !== inputValue) {
              outputStyles[webKitStyles[i]] = inputValue;
            }
          }

          outputStyles = dom.serializeStyle(outputStyles, 'span');
          if (outputStyles) {
            return before + ' style="' + outputStyles + '"' + after;
          }

          return before + after;
        });
      } else {
        // Remove all external styles
        content = content.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi, '$1$3');
      }

      // Keep internal styles
      content = content.replace(/(<[^>]+) data-mce-style="([^"]+)"([^>]*>)/gi, function (all, before, value, after) {
        return before + ' style="' + value + '"' + after;
      });

      return content;
    }

    function removeUnderlineAndFontInAnchor(editor, root) {
      editor.$('a', root).find('font,u').each(function (i, node) {
        editor.dom.remove(node, true);
      });
    }

    var setup = function (editor) {
      if (Env.webkit) {
        addPreProcessFilter(editor, removeWebKitStyles);
      }

      if (Env.ie) {
        addPreProcessFilter(editor, removeExplorerBrElementsAfterBlocks);
        addPostProcessFilter(editor, removeUnderlineAndFontInAnchor);
      }
    };

    return {
      setup: setup
    };
  }
);
defineGlobal("global!Array", Array);
defineGlobal("global!Error", Error);
define(
  'ephox.katamari.api.Fun',

  [
    'global!Array',
    'global!Error'
  ],

  function (Array, Error) {

    var noop = function () { };

    var compose = function (fa, fb) {
      return function () {
        return fa(fb.apply(null, arguments));
      };
    };

    var constant = function (value) {
      return function () {
        return value;
      };
    };

    var identity = function (x) {
      return x;
    };

    var tripleEquals = function(a, b) {
      return a === b;
    };

    // Don't use array slice(arguments), makes the whole function unoptimisable on Chrome
    var curry = function (f) {
      // equivalent to arguments.slice(1)
      // starting at 1 because 0 is the f, makes things tricky.
      // Pay attention to what variable is where, and the -1 magic.
      // thankfully, we have tests for this.
      var args = new Array(arguments.length - 1);
      for (var i = 1; i < arguments.length; i++) args[i-1] = arguments[i];

      return function () {
        var newArgs = new Array(arguments.length);
        for (var j = 0; j < newArgs.length; j++) newArgs[j] = arguments[j];

        var all = args.concat(newArgs);
        return f.apply(null, all);
      };
    };

    var not = function (f) {
      return function () {
        return !f.apply(null, arguments);
      };
    };

    var die = function (msg) {
      return function () {
        throw new Error(msg);
      };
    };

    var apply = function (f) {
      return f();
    };

    var call = function(f) {
      f();
    };

    var never = constant(false);
    var always = constant(true);
    

    return {
      noop: noop,
      compose: compose,
      constant: constant,
      identity: identity,
      tripleEquals: tripleEquals,
      curry: curry,
      not: not,
      die: die,
      apply: apply,
      call: call,
      never: never,
      always: always
    };
  }
);

/**
 * Buttons.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

define(
  'tinymce.plugins.paste.ui.Buttons',
  [
    'ephox.katamari.api.Fun'
  ],
  function (Fun) {
    var stateChange = function (editor, clipboard, e) {
      var ctrl = e.control;

      ctrl.active(clipboard.pasteFormat === 'text');

      editor.on('PastePlainTextToggle', function (e) {
        ctrl.active(e.state);
      });
    };

    var register = function (editor, clipboard) {
      var postRender = Fun.curry(stateChange, editor, clipboard);

      editor.addButton('pastetext', {
        icon: 'pastetext',
        tooltip: 'Paste as text',
        cmd: 'mceTogglePlainTextPaste',
        onPostRender: postRender
      });

      editor.addMenuItem('pastetext', {
        text: 'Paste as text',
        selectable: true,
        active: clipboard.pasteFormat,
        cmd: 'mceTogglePlainTextPaste',
        onPostRender: postRender
      });
    };

    return {
      register: register
    };
  }
);
/**
 * Plugin.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

define(
  'tinymce.plugins.paste.Plugin',
  [
    'ephox.katamari.api.Cell',
    'tinymce.core.PluginManager',
    'tinymce.plugins.paste.alien.DetectProPlugin',
    'tinymce.plugins.paste.api.Api',
    'tinymce.plugins.paste.api.Commands',
    'tinymce.plugins.paste.core.Clipboard',
    'tinymce.plugins.paste.core.CutCopy',
    'tinymce.plugins.paste.core.DragDrop',
    'tinymce.plugins.paste.core.PrePostProcess',
    'tinymce.plugins.paste.core.Quirks',
    'tinymce.plugins.paste.ui.Buttons'
  ],
  function (Cell, PluginManager, DetectProPlugin, Api, Commands, Clipboard, CutCopy, DragDrop, PrePostProcess, Quirks, Buttons) {
    var userIsInformedState = Cell(false);

    PluginManager.add('paste', function (editor) {
      if (DetectProPlugin.hasProPlugin(editor) === false) {
        var clipboard = new Clipboard(editor);
        var quirks = Quirks.setup(editor);
        var draggingInternallyState = Cell(false);

        Buttons.register(editor, clipboard);
        Commands.register(editor, clipboard, userIsInformedState);
        PrePostProcess.setup(editor);
        CutCopy.register(editor);
        DragDrop.setup(editor, clipboard, draggingInternallyState);

        return Api.get(clipboard, quirks);
      }
    });

    return function () { };
  }
);
dem('tinymce.plugins.paste.Plugin')();
})();

No other release has this exact content. See every version of this file.