<commit_before>var db = require('mongoose');
var models = require(__dirname+'/../lib/databasemodels.js');
var clienttracking = require(__dirname+'/../lib/clienttracking.js');
var q = require('promised-io/promise');
var Deferred = q.Deferred;
var moment = require('moment');

db.connect('mongodb://127.0.0.1/adnoce', {});

var executeViewQuery = function (sessionID, requestHeaders, additionalData) {
  var deferred = new Deferred();
  clienttracking.pushTrackingData(sessionID, requestHeaders, additionalData, function(err, data) {
    if (err === null) deferred.resolve(data);
    else deferred.reject(err);
  });
  return deferred.promise;
}
var executeEventQuery = function(type, name, sessionId, additionalData, eventDate) {
  var deferred = new Deferred();
  clienttracking.addEvent(type, name, sessionId, additionalData, eventDate, function(err, data) {
    if (err === null) deferred.resolve(data);
    else deferred.reject(err);
  });
  return deferred.promise;
}

var requestHeaders = { 'referer': null, 'user-agent': 'user-agent for testing' }
var additionalData = { adnocetype: 100, timestamp: null }
var arrayOfPromises = [];
var acutalDate = new Date();

// generate 200 views (every 10 requests the path changes)
var pathstringID = 1;
for (var v = 0, vx = 200; v < vx; ++v) {
  if (v % 10 === 0) {
    ++pathstringID;
  }
  requestHeaders.referer = 'http://www.example.com/path'+pathstringID;
  var hour = Math.floor(Math.random() * (23 - 1 + 1)) + 1;
  var minute = Math.floor(Math.random() * (59 - 1 + 1)) + 1;
  var second = Math.floor(Math.random() * (59 - 1 + 1)) + 1;
  additionalData.timestamp = new Date(acutalDate.getFullYear(), acutalDate.getMonth(), acutalDate.getDate(), hour, minute, second);
  arrayOfPromises.push(executeViewQuery('testing', requestHeaders, additionalData));
}
// generate 400 events
for (var v = 0, vx = 400; v < vx; ++v) {
  if (v % 10 === 0) {
    ++pathstringID;
  }
  var hour = Math.floor(Math.random() * (23 - 1 + 1)) + 1;
  var minute = Math.floor(Math.random() * (59 - 1 + 1)) + 1;
  var second = Math.floor(Math.random() * (59 - 1 + 1)) + 1;
  var value = Math.floor(Math.random() * (1000 - 1 + 1)) + 1;
  var eventname = [];
  for (var e = 0, ex = 8; e < ex; ++e) eventname.push(String.fromCharCode(Math.floor(Math.random() * (90 - 65 + 1)) + 65));
  var data = { key: 'test', value: value };
  arrayOfPromises.push(executeEventQuery(200, eventname.join(''), 'testing', data, new Date(acutalDate.getFullYear(), acutalDate.getMonth(), acutalDate.getDate(), hour, minute, second)));
}
// generate 200 error events
for (var v = 0, vx = 200; v < vx; ++v) {
  if (v % 10 === 0) {
    ++pathstringID;
  }
  var hour = Math.floor(Math.random() * (23 - 1 + 1)) + 1;
  var minute = Math.floor(Math.random() * (59 - 1 + 1)) + 1;
  var second = Math.floor(Math.random() * (59 - 1 + 1)) + 1;
  var message = [];
  for (var e = 0, ex = (Math.floor(Math.random() * (40 - 1 + 1)) + 1); e < ex; ++e) message.push(String.fromCharCode(Math.floor(Math.random() * (90 - 65 + 1)) + 65));
  var data = { key: 'message', value: message.join('') };
  arrayOfPromises.push(executeEventQuery(100, 'error', 'testing', data, new Date(acutalDate.getFullYear(), acutalDate.getMonth(), acutalDate.getDate(), hour, minute, second)));
}

var group = q.all(arrayOfPromises);
var results = [];

group.then(function(resultArray){
  process.exit();
});
<commit_msg>reduce noise in generated data<commit_after>var db = require('mongoose');
var models = require(__dirname+'/../lib/databasemodels.js');
var clienttracking = require(__dirname+'/../lib/clienttracking.js');
var q = require('promised-io/promise');
var Deferred = q.Deferred;
var moment = require('moment');

db.connect('mongodb://127.0.0.1/adnoce', {});

var executeViewQuery = function (sessionID, requestHeaders, additionalData) {
  var deferred = new Deferred();
  clienttracking.pushTrackingData(sessionID, requestHeaders, additionalData, function(err, data) {
    if (err === null) deferred.resolve(data);
    else deferred.reject(err);
  });
  return deferred.promise;
}
var executeEventQuery = function(type, name, sessionId, additionalData, eventDate) {
  var deferred = new Deferred();
  clienttracking.addEvent(type, name, sessionId, additionalData, eventDate, function(err, data) {
    if (err === null) deferred.resolve(data);
    else deferred.reject(err);
  });
  return deferred.promise;
}

var requestHeaders = { 'referer': null, 'user-agent': 'user-agent for testing' }
var additionalData = { adnocetype: 100, timestamp: null }
var arrayOfPromises = [];
var acutalDate = new Date();

// generate 200 views
var pathstringID = 1;
for (var v = 0, vx = 200; v < vx; ++v) {
  if (v % 10 === 0) {
    pathstringID = 10;
  } else {
    pathstringID = Math.floor(Math.random() * (50 - 10 + 1)) + 10;
  }
  requestHeaders.referer = 'http://www.example.com/path'+pathstringID;
  var hour = Math.floor(Math.random() * (23 - 1 + 1)) + 1; // Math.floor(Math.random() * (max - min + 1)) + min;
  var minute = Math.floor(Math.random() * (59 - 1 + 1)) + 1;
  var second = Math.floor(Math.random() * (59 - 1 + 1)) + 1;
  additionalData.timestamp = new Date(acutalDate.getFullYear(), acutalDate.getMonth(), acutalDate.getDate(), hour, minute, second);
  arrayOfPromises.push(executeViewQuery('testing', requestHeaders, additionalData));
}
// generate 400 events
for (var v = 0, vx = 400; v < vx; ++v) {
  var hour = Math.floor(Math.random() * (23 - 1 + 1)) + 1;
  var minute = Math.floor(Math.random() * (59 - 1 + 1)) + 1;
  var second = Math.floor(Math.random() * (59 - 1 + 1)) + 1;
  var value = Math.floor(Math.random() * (1000 - 1 + 1)) + 1;
  var eventname = null;
  if (v % 10 === 0) {
    var eventnameA = [];
    for (var e = 0, ex = 8; e < ex; ++e) eventnameA.push(String.fromCharCode(Math.floor(Math.random() * (90 - 65 + 1)) + 65));
    eventname = eventnameA.join('');
  } else {
    switch (Math.floor(Math.random() * (5 - 1 + 1)) + 1) {
      case 5:
        eventname = 'login';
        break;
      case 4:
        eventname = 'login';
        break;
      case 3:
        eventname = 'search';
        break;
      case 2:
        eventname = 'register';
        break;
      case 1:
        eventname = 'order';
        break;
      default:
        eventname = 'generic';
    }
  }

  var data = { key: 'test', value: value };
  arrayOfPromises.push(executeEventQuery(200, eventname, 'testing', data, new Date(acutalDate.getFullYear(), acutalDate.getMonth(), acutalDate.getDate(), hour, minute, second)));
}
// generate 200 error events
for (var v = 0, vx = 200; v < vx; ++v) {
  if (v % 10 === 0) {
    ++pathstringID;
  }
  var hour = Math.floor(Math.random() * (23 - 1 + 1)) + 1;
  var minute = Math.floor(Math.random() * (59 - 1 + 1)) + 1;
  var second = Math.floor(Math.random() * (59 - 1 + 1)) + 1;
  var message = [];
  for (var e = 0, ex = (Math.floor(Math.random() * (40 - 1 + 1)) + 1); e < ex; ++e) message.push(String.fromCharCode(Math.floor(Math.random() * (90 - 65 + 1)) + 65));
  var data = { key: 'message', value: message.join('') };
  arrayOfPromises.push(executeEventQuery(100, 'error', 'testing', data, new Date(acutalDate.getFullYear(), acutalDate.getMonth(), acutalDate.getDate(), hour, minute, second)));
}

var group = q.all(arrayOfPromises);
var results = [];

group.then(function(resultArray){
  process.exit();
});
<|endoftext|>


<commit_before>// ==UserScript==
// @name        Bwin registration
// @namespace   Bwin registration
// @description Prefill registration form on for all bwin labels
// @include     *bwin.*/*/registration*
// @include     *gamebookers.com*/*/registration*
// @include     *giocodigitale.it*/*/registration*
// @version     0.4.5
// @require     https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.js
// @require     https://raw.githubusercontent.com/drizet/PortalUserScripts/master/src/core/common.js
// @require     https://raw.githubusercontent.com/drizet/PortalUserScripts/master/src/core/random.js
// @require     https://raw.githubusercontent.com/blueimp/JavaScript-MD5/master/js/md5.min.js
// ==/UserScript==

$(function () {
    // Portal labels
    var BAW = "bwin.com";
    var BE = "bwin.be";
    var ES = "bwin.es";
    var SHDE = "sh.bwin.de";
    var FR = "bwin.fr";
    var IT = "bwin.it";
    var GD = "giocodigitale.it";
    var GB = "gamebookers.com";
    var GR = "bwin.gr";

    if ($("#registration-form").length) {
        SetupPersonalData();
        SetupAccountData();

        if (LabelIs(BE)) {
            SetupIdentificationData();
        }

        if (LabelIs(ES)) {
            SetupNieNifData();
        }

        if(LabelIs(IT) || LabelIs(GD)){
            SetupDocumentData();
        }

        SetupConfirmationData();
    }

    function SetupPersonalData() {
        $("#Input_NameData_FirstName").val(Random.getText(10));
        $("#Input_NameData_LastName").val(Random.getText(10));

        if(LabelIs(ES)){
            $("#Input_AddressData_AddressCountryCode").selectOptionByValue("ES");
        }
        else if(LabelIs(BAW)){
            $("#Input_AddressData_AddressCountryCode").selectOptionByValue("GB");
        }
        else{
          $("#Input_AddressData_AddressCountryCode").selectOptionByIndex(1);
        }

        $("#Input_AddressData_AddressState").selectOptionByIndex(1);
        $("#Input_AddressData_AddressCity").val(Random.getText(6));
        $("#Input_AddressData_AddressZip").val("2" + Random.getNumbers(4));
        $("#Input_AddressData_AddressLine1").val("address");
        $("#Input_AddressData_AddressLine2").val("address2");
        $("#Input_CurrencyData_CurrencyCode").selectOptionByValue("EUR");
        $("#Input_BirthData_DateOfBirth").setDate(1, 1, 1992);
        $("#Input_ContactData_EmailAddress").val(Random.getEmail(8, "yopmail.com"));
        $("#Input_ContactData_MobileCountryCode").selectOptionByValue("380")
        $("#Input_ContactData_MobileNumber").val(Random.getNumbers(7));

        if (LabelIs(ES)) {
            $("#Input_NameData_SecondLastName").val(Random.getText(10));
        }

        if (LabelIs(SHDE)) {
            $("#Input_AddressData_Nationality").selectOptionByIndex(1);
            $("#Input_BirthData_PlaceOfBirth").val(Random.getText(7));
        }

        if (LabelIs(FR) || LabelIs(IT) || LabelIs(GD)) {
            $("#Input_BirthData_BirthState").selectOptionByIndex(2, true);
            $("#Input_BirthData_BirthCity").selectOptionByIndex(1, true);
        }

        if(LabelIs(IT) || LabelIs(GD)){
             $("#Input_BirthData_FiscalCodeConfirmed").checkWhenEntered("#Input_BirthData_FiscalCode");
        }
    }

    function SetupAccountData() {
        if (LabelIs(ES)) {
            SetPassword("123123Qq")
        }
        else {
            SetPassword("123123qq")
        }
        $("#Input_LoginData_Username").val(Random.getUserName(4));

        $("#Input_SecurityData_SecurityQuestion").selectOptionByIndex(1);
    }

    function SetPassword(password) {
        $("#Input_LoginData_Password, #Input_LoginData_PasswordConfirmation, #Input_SecurityData_SecurityAnswer").val(password);
    }

    function SetupConfirmationData() {
        $("#Input_TermsAndConditions_TacAcceptance, #Input_BonusData_BonusTacAccepted, #Input_PrivacyPolicy_PrivacyPolicyAccepted").check();

        if(LabelIs(IT) || LabelIs(GD)){
            $("#Input_NewslettersSubscription_NewslettersSubscriptionAccepted, #Input_OtherNoticeSubscription_OtherNoticeSubscriptionsAccepted").check()
        }

        $("#Captcha_Input_Answer").val("+++");
    }

    function SetupIdentificationData() {
        var nrnDate = "920101";
        var nrnSerialNumber = Random.getNumbers(3);
        var nrnChecksum = 97 - (parseInt(nrnDate + nrnSerialNumber) % 97);

        $("#Input_IdentificationData_NRNDate").val(nrnDate);
        $("#Input_IdentificationData_NRNSerialNumber").val(nrnSerialNumber);
        $("#Input_IdentificationData_NRNChecksum").val(pad(nrnChecksum, 2));
        $("#Input_IdentificationData_Profession").selectOptionByIndex(1);
        $("#Input_IdentificationData_CityOfBirth").val(Random.getText(6));
    }

    function SetupNieNifData() {
        $("#Input_NieNif_TaxProvince").selectOptionByIndex(1);

        var dni = Random.getNumbers(8);
        var characters = "TRWAGMYFPDXBNJZSQVHLCKE";
        dni = dni + characters[parseInt(dni) % 23];
        $("#Input_NieNif_IdDocumentNumber").val(dni);
    }

    function SetupDocumentData(){
        $("#Input_IdentificationData_DocumentType").selectOptionByIndex(1);
        $("#Input_IdentificationData_DocumentNumber").val(Random.getText(6));
        $("#Input_IdentificationData_DocumentReleaseDate").setDate(1, 1, 1992);
        $("#Input_IdentificationData_DocumentReleasedBy").selectOptionByIndex(1);
        $("#Input_IdentificationData_DocumentReleaseLocation").val(Random.getText(6));
    }

    function pad(n, width, z) {
        z = z || '0';
        n = n + '';
        return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
    }

    function LabelIs(host) {
        return document.location.href.indexOf(host) != -1;
    }
});<commit_msg>Updated include directives<commit_after>// ==UserScript==
// @name        Bwin registration
// @namespace   Bwin registration
// @description Prefill registration form on for all bwin labels
// @include     *bwin.com/*/registration*
// @include     *bwin.be/*/registration*
// @include     *bwin.es/*/registration*
// @include     *sh.bwin.de/*/registration*
// @include     *bwin.fr/*/registration*
// @include     *bwin.it/*/registration*
// @include     *bwin.gr/*/registration*
// @include     *gamebookers.com/*/registration*
// @include     *giocodigitale.it/*/registration*
// @version     0.4.6
// @require     https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.js
// @require     https://raw.githubusercontent.com/drizet/PortalUserScripts/master/src/core/common.js
// @require     https://raw.githubusercontent.com/drizet/PortalUserScripts/master/src/core/random.js
// @require     https://raw.githubusercontent.com/blueimp/JavaScript-MD5/master/js/md5.min.js
// ==/UserScript==

$(function () {
    // Portal labels
    var BAW = "bwin.com";
    var BE = "bwin.be";
    var ES = "bwin.es";
    var SHDE = "sh.bwin.de";
    var FR = "bwin.fr";
    var IT = "bwin.it";
    var GD = "giocodigitale.it";
    var GB = "gamebookers.com";
    var GR = "bwin.gr";

    if ($("#registration-form").length) {
        SetupPersonalData();
        SetupAccountData();

        if (LabelIs(BE)) {
            SetupIdentificationData();
        }

        if (LabelIs(ES)) {
            SetupNieNifData();
        }

        if(LabelIs(IT) || LabelIs(GD)){
            SetupDocumentData();
        }

        SetupConfirmationData();
    }

    function SetupPersonalData() {
        $("#Input_NameData_FirstName").val(Random.getText(10));
        $("#Input_NameData_LastName").val(Random.getText(10));

        if(LabelIs(ES)){
            $("#Input_AddressData_AddressCountryCode").selectOptionByValue("ES");
        }
        else if(LabelIs(BAW)){
            $("#Input_AddressData_AddressCountryCode").selectOptionByValue("GB");
        }
        else{
          $("#Input_AddressData_AddressCountryCode").selectOptionByIndex(1);
        }

        $("#Input_AddressData_AddressState").selectOptionByIndex(1);
        $("#Input_AddressData_AddressCity").val(Random.getText(6));
        $("#Input_AddressData_AddressZip").val("2" + Random.getNumbers(4));
        $("#Input_AddressData_AddressLine1").val("address");
        $("#Input_AddressData_AddressLine2").val("address2");
        $("#Input_CurrencyData_CurrencyCode").selectOptionByValue("EUR");
        $("#Input_BirthData_DateOfBirth").setDate(1, 1, 1992);
        $("#Input_ContactData_EmailAddress").val(Random.getEmail(8, "yopmail.com"));
        $("#Input_ContactData_MobileCountryCode").selectOptionByValue("380")
        $("#Input_ContactData_MobileNumber").val(Random.getNumbers(7));

        if (LabelIs(ES)) {
            $("#Input_NameData_SecondLastName").val(Random.getText(10));
        }

        if (LabelIs(SHDE)) {
            $("#Input_AddressData_Nationality").selectOptionByIndex(1);
            $("#Input_BirthData_PlaceOfBirth").val(Random.getText(7));
        }

        if (LabelIs(FR) || LabelIs(IT) || LabelIs(GD)) {
            $("#Input_BirthData_BirthState").selectOptionByIndex(2, true);
            $("#Input_BirthData_BirthCity").selectOptionByIndex(1, true);
        }

        if(LabelIs(IT) || LabelIs(GD)){
             $("#Input_BirthData_FiscalCodeConfirmed").checkWhenEntered("#Input_BirthData_FiscalCode");
        }
    }

    function SetupAccountData() {
        if (LabelIs(ES)) {
            SetPassword("123123Qq")
        }
        else {
            SetPassword("123123qq")
        }
        $("#Input_LoginData_Username").val(Random.getUserName(4));

        $("#Input_SecurityData_SecurityQuestion").selectOptionByIndex(1);
    }

    function SetPassword(password) {
        $("#Input_LoginData_Password, #Input_LoginData_PasswordConfirmation, #Input_SecurityData_SecurityAnswer").val(password);
    }

    function SetupConfirmationData() {
        $("#Input_TermsAndConditions_TacAcceptance, #Input_BonusData_BonusTacAccepted, #Input_PrivacyPolicy_PrivacyPolicyAccepted").check();

        if(LabelIs(IT) || LabelIs(GD)){
            $("#Input_NewslettersSubscription_NewslettersSubscriptionAccepted, #Input_OtherNoticeSubscription_OtherNoticeSubscriptionsAccepted").check()
        }

        $("#Captcha_Input_Answer").val("+++");
    }

    function SetupIdentificationData() {
        var nrnDate = "920101";
        var nrnSerialNumber = Random.getNumbers(3);
        var nrnChecksum = 97 - (parseInt(nrnDate + nrnSerialNumber) % 97);

        $("#Input_IdentificationData_NRNDate").val(nrnDate);
        $("#Input_IdentificationData_NRNSerialNumber").val(nrnSerialNumber);
        $("#Input_IdentificationData_NRNChecksum").val(pad(nrnChecksum, 2));
        $("#Input_IdentificationData_Profession").selectOptionByIndex(1);
        $("#Input_IdentificationData_CityOfBirth").val(Random.getText(6));
    }

    function SetupNieNifData() {
        $("#Input_NieNif_TaxProvince").selectOptionByIndex(1);

        var dni = Random.getNumbers(8);
        var characters = "TRWAGMYFPDXBNJZSQVHLCKE";
        dni = dni + characters[parseInt(dni) % 23];
        $("#Input_NieNif_IdDocumentNumber").val(dni);
    }

    function SetupDocumentData(){
        $("#Input_IdentificationData_DocumentType").selectOptionByIndex(1);
        $("#Input_IdentificationData_DocumentNumber").val(Random.getText(6));
        $("#Input_IdentificationData_DocumentReleaseDate").setDate(1, 1, 1992);
        $("#Input_IdentificationData_DocumentReleasedBy").selectOptionByIndex(1);
        $("#Input_IdentificationData_DocumentReleaseLocation").val(Random.getText(6));
    }

    function pad(n, width, z) {
        z = z || '0';
        n = n + '';
        return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
    }

    function LabelIs(host) {
        return document.location.href.indexOf(host) != -1;
    }
});<|endoftext|>


<commit_before>/**
 * Text Editor
 *
 * Created by Shadowgun on 13.02.2015.
 * Upgraded by Serhii Maksymchuk in 2016
 */
Imcms.Text = {};

Imcms.Text.API = function () {
};
Imcms.Text.API.prototype = {
    get: function (request, callback) {
        $.ajax({
            url: Imcms.Linker.get("text"),
            type: "GET",
            data: request,
            success: callback
        })
    },
    update: function (request, callback) {
        $.ajax({
            url: Imcms.Linker.get("text"),
            type: "POST",
            data: request,
            success: callback
        })
    },
    validate: function (request, callback) {
        $.ajax({
            url: Imcms.Linker.get("text.validate"),
            type: "POST",
            data: request,
            success: callback
        })
    }
};

Imcms.Text.Editor = function () {
    this.init();
};

Imcms.Text.Editor.prototype = {
    _api: new Imcms.Text.API(),
    _textFrame: {},
    init: function () {
        this._textFrame = new Imcms.FrameBuilder().title("Text Editor");

        CKEDITOR.on('instanceReady', this._onInstanceReady.bind(this));
        CKEDITOR.on('instanceCreated', this._onCreated.bind(this));
        CKEDITOR.on("confirmChangesEvent", this._onConfirm.bind(this));
        CKEDITOR.on("validateText", this._onValidateText.bind(this));
        CKEDITOR.on("getTextHistory", this._onGetTextHistory.bind(this));

        $("[contenteditable='true']").each(this.addEditor.bind(this));
    },
    addEditor: function (position, element) {
        element = $(element);
        CKEDITOR.inline(element[0]);
        element.parents("a").attr("onclick", "return false;");

        $("<div>").insertAfter(element)
            .append(element)
            .css({overflow: "hidden"});

        var loopTitle = "";
        if (element.data("loopentryref")) {
            loopTitle = (element.data("loopentryref")).split("_");
            loopTitle = "L" + loopTitle[0] + "-E" + loopTitle[1] + "-T";
        }

        var title = loopTitle + element.data("no") + " | " + element.data("label"),
            currentFrame = this._textFrame
                .click(function (e) {
                    currentFrame.hide();
                    element.focus();
                    element.trigger(e);
                    element.blur(function () {
                        currentFrame.show();
                    });
                })
                .build()
                .attr("title", title.replace(/<(?:.|\n)*?>/gim, ''))
                .insertBefore(element);

        if (element.data("showlabel")) {
            $("<div>").addClass("text-editor-label")
                .html(element.data("label"))
                .insertBefore(element);
        }
    },
    _onInstanceReady: function (event) {
        var editor = event.editor,
            selectedImageData = {};

        editor.addCommand('editInternalImageCmd', {
            exec: function (editor) {
                var imageInTextEditor = new Imcms.Image.ImageInTextEditor(editor);
                imageInTextEditor.onExistingImageEdit(selectedImageData);
            }
        });
        editor.contextMenu.addListener(function (element, selection) {
            if (element.hasClass("internalImageInTextEditor")) {
                var selectedElement = selection._.cache.selectedElement.$,
                    $selection = $(selectedElement);

                selectedImageData = {
                    no: $selection.attr("data-no"),
                    src: $selection.attr("src"),
                    selectedElement: selectedElement
                };
                // skipping CKEditor's "image" context menu item that is items[3]
                editor.contextMenu.items = editor.contextMenu.items.slice(0, 3);
                return {
                    editInternalImageCmd: CKEDITOR.TRISTATE_OFF
                };
            }
        });
        editor.addMenuItems({
            editInternalImageCmd: {
                label: 'Edit Image',
                command: 'editInternalImageCmd',
                group: 'image',
                order: 2
            }
        });
    },
    _onConfirm: function (event) {
        var editor = event.editor,
            data = $(editor.element.$).data(),
            isHtmlContent = (data.contenttype === "html"),
            callFunc = (isHtmlContent) ? "html" : "text",
            content = $(editor.element.$)[callFunc]();

        // save only when content is changed or mode is switched
        if ((data.content !== content) || CKEDITOR.switchFormat) {
            data.content = content;
            if (!data.meta) {
                data.meta = Imcms.document.meta;
            }

            var shouldRefreshPage = false;

            if (CKEDITOR.switchFormat) {
                data.contenttype = (isHtmlContent)
                    ? "from-html"
                    : "html";

                shouldRefreshPage = true;
                CKEDITOR.switchFormat = false;
            }

            this._api.update(data, event.data.callback || Imcms.BackgroundWorker.createTask({
                    showProcessWindow: true,
                    refreshPage: shouldRefreshPage
                })
            );

        } else if (event.data && event.data.callback && (typeof event.data.callback === "function")) {
            event.data.callback()
        }
    },
    _onCreated: function (event) {
        var editor = event.editor;

        // Customize editors.
        // These editors don't need features like smileys, templates, iframes etc.\
        // Customize the editor configurations on "configLoaded" event,
        // which is fired after the configuration file loading and
        // execution. This makes it possible to change the
        // configurations before the editor initialization takes place.
        editor.on('configLoaded', this._onEditorLoaded.bind(this));
    },
    _onGetTextHistory: function (event) {
        var data = jQuery(event.editor.element.$).data();

        data = { // sending only needed data, other can produce errors
            locale: data.locale,
            loopentryref: data.loopentryref,
            meta: Imcms.document.meta,
            no: data.no
        };

        this._api.get(data, event.data.callback);
    },
    _onValidateText: function (event) {
        this._api.validate({content: event.editor.getData()}, event.data.callback);
    },
    _onEditorLoaded: function (event) {
        var editor = event.editor;

        // commands definition
        editor.addCommand("switchFormat", CKEDITOR.newCommandWithExecution(function (editor) {
            CKEDITOR.switchFormat = true;
            editor.execCommand("confirmChangesBeforeSwitch");
        }));

        // Remove unnecessary plugins to make the editor simpler.
        editor.config.removePlugins = 'colorbutton,find,forms,newpage,removeformat,specialchar,stylescombo,templates';
        var customExtraPlugins = ",switchFormatToHTML,switchFormatToText,documentSaver,fileBrowser,link,textHistory,w3cValidator,maximize,toolbarswitch";

        if (editor.config.extraPlugins.indexOf(customExtraPlugins) == -1) {
            editor.config.extraPlugins = editor.config.extraPlugins + customExtraPlugins;
        }

        var fontPlugins = ['Bold', 'Italic', 'Underline', 'Strike'];
        var textParagraphPlugins = ['NumberedList', 'BulletedList', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'Outdent', 'Indent'];
        var linkPlugins = ['Link', 'Unlink', 'Anchor'];
        var imagesPlugins = ['Image', 'openBrowser'];
        var textPlugins = ['TextColor', 'BGColor'];
        var imcmsCustomPlugins = ['w3cValidate', 'textHistory', 'Toolbarswitch', 'saveData', 'confirm', 'cancel'];
        var switchFormatToTextPlugin = ['switchFormatToText'];
        var switchFormatToHtmlPlugin = ['switchFormatToHTML'];
        var plainTextPlugins = ['textHistory', 'Toolbarswitch', 'saveData', 'confirm', 'cancel'];
        var imageUtilsAndOtherDefaultPlugins = ['Image', 'openBrowser', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe'];
        var advancedFontPlugins = ['Styles', 'Format', 'Font', 'FontSize'];
        var sourcePlugin = ['Source'];
        var textEditingPlugins = ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Scayt'];
        var advancedActionsPlugins = ['Undo', 'Redo', '-', 'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat'];

        editor.config.toolbar_minPlainText = [
            plainTextPlugins
        ]; // Custom minimized toolbar config for tag with attribute "formats"="text"

        editor.config.toolbar_maxPlainText = [
            plainTextPlugins
        ]; // Custom maximized toolbar config for tag with attribute "formats"="text"

        editor.config.toolbar_minTextToolbar = [
            switchFormatToHtmlPlugin,
            linkPlugins,
            imagesPlugins,
            textPlugins,
            plainTextPlugins
        ]; // Custom minimized toolbar config for tag without attribute "formats" but was changed to "Text"

        editor.config.toolbar_minHtmlToolbar = [
            switchFormatToTextPlugin,
            fontPlugins,
            textParagraphPlugins,
            linkPlugins,
            imagesPlugins,
            textPlugins,
            sourcePlugin,
            imcmsCustomPlugins
        ]; // Custom minimized toolbar config for tag without attribute "formats" but was changed to "HTML"

        editor.config.toolbar_maxHtmlToolbar = [
            switchFormatToTextPlugin,
            fontPlugins,
            textParagraphPlugins,
            linkPlugins,
            imageUtilsAndOtherDefaultPlugins,
            advancedFontPlugins,
            textPlugins,
            textEditingPlugins,
            sourcePlugin,
            advancedActionsPlugins,
            imcmsCustomPlugins
        ]; // Custom maximized toolbar config for tag without attribute "formats" but was changed to "HTML"

        editor.config.toolbar_maxTextToolbar = [
            switchFormatToHtmlPlugin,
            linkPlugins,
            advancedActionsPlugins,
            plainTextPlugins
        ]; // Custom maximized toolbar config for tag without attribute "formats" but was changed to "HTML"

        editor.toolbarLocation = "top";
        editor.config.toolbar = CKEDITOR.defineToolbar(editor);
        editor.config.allowedContent = true;
    }
};
<commit_msg>IMCMS-179 - Image in texteditor: - Added icon for new context menu item.<commit_after>/**
 * Text Editor
 *
 * Created by Shadowgun on 13.02.2015.
 * Upgraded by Serhii Maksymchuk in 2016
 */
Imcms.Text = {};

Imcms.Text.API = function () {
};
Imcms.Text.API.prototype = {
    get: function (request, callback) {
        $.ajax({
            url: Imcms.Linker.get("text"),
            type: "GET",
            data: request,
            success: callback
        })
    },
    update: function (request, callback) {
        $.ajax({
            url: Imcms.Linker.get("text"),
            type: "POST",
            data: request,
            success: callback
        })
    },
    validate: function (request, callback) {
        $.ajax({
            url: Imcms.Linker.get("text.validate"),
            type: "POST",
            data: request,
            success: callback
        })
    }
};

Imcms.Text.Editor = function () {
    this.init();
};

Imcms.Text.Editor.prototype = {
    _api: new Imcms.Text.API(),
    _textFrame: {},
    init: function () {
        this._textFrame = new Imcms.FrameBuilder().title("Text Editor");

        CKEDITOR.on('instanceReady', this._onInstanceReady.bind(this));
        CKEDITOR.on('instanceCreated', this._onCreated.bind(this));
        CKEDITOR.on("confirmChangesEvent", this._onConfirm.bind(this));
        CKEDITOR.on("validateText", this._onValidateText.bind(this));
        CKEDITOR.on("getTextHistory", this._onGetTextHistory.bind(this));

        $("[contenteditable='true']").each(this.addEditor.bind(this));
    },
    addEditor: function (position, element) {
        element = $(element);
        CKEDITOR.inline(element[0]);
        element.parents("a").attr("onclick", "return false;");

        $("<div>").insertAfter(element)
            .append(element)
            .css({overflow: "hidden"});

        var loopTitle = "";
        if (element.data("loopentryref")) {
            loopTitle = (element.data("loopentryref")).split("_");
            loopTitle = "L" + loopTitle[0] + "-E" + loopTitle[1] + "-T";
        }

        var title = loopTitle + element.data("no") + " | " + element.data("label"),
            currentFrame = this._textFrame
                .click(function (e) {
                    currentFrame.hide();
                    element.focus();
                    element.trigger(e);
                    element.blur(function () {
                        currentFrame.show();
                    });
                })
                .build()
                .attr("title", title.replace(/<(?:.|\n)*?>/gim, ''))
                .insertBefore(element);

        if (element.data("showlabel")) {
            $("<div>").addClass("text-editor-label")
                .html(element.data("label"))
                .insertBefore(element);
        }
    },
    _onInstanceReady: function (event) {
        var editor = event.editor,
            selectedImageData = {};

        editor.addCommand('editInternalImageCmd', {
            exec: function (editor) {
                var imageInTextEditor = new Imcms.Image.ImageInTextEditor(editor);
                imageInTextEditor.onExistingImageEdit(selectedImageData);
            }
        });
        editor.contextMenu.addListener(function (element, selection) {
            if (element.hasClass("internalImageInTextEditor")) {
                var selectedElement = selection._.cache.selectedElement.$,
                    $selection = $(selectedElement);

                selectedImageData = {
                    no: $selection.attr("data-no"),
                    src: $selection.attr("src"),
                    selectedElement: selectedElement
                };
                // skipping CKEditor's "image" context menu item that is items[3]
                editor.contextMenu.items = editor.contextMenu.items.slice(0, 3);
                return {
                    editInternalImageCmd: CKEDITOR.TRISTATE_OFF
                };
            }
        });
        editor.addMenuItems({
            editInternalImageCmd: {
                label: 'Edit Image',
                command: 'editInternalImageCmd',
                group: 'image',
                icon: Imcms.Linker.getContextPath() + "/imcms/ckeditor/plugins/imcms_image/toolBarButton.png",
                order: 2
            }
        });
    },
    _onConfirm: function (event) {
        var editor = event.editor,
            data = $(editor.element.$).data(),
            isHtmlContent = (data.contenttype === "html"),
            callFunc = (isHtmlContent) ? "html" : "text",
            content = $(editor.element.$)[callFunc]();

        // save only when content is changed or mode is switched
        if ((data.content !== content) || CKEDITOR.switchFormat) {
            data.content = content;
            if (!data.meta) {
                data.meta = Imcms.document.meta;
            }

            var shouldRefreshPage = false;

            if (CKEDITOR.switchFormat) {
                data.contenttype = (isHtmlContent)
                    ? "from-html"
                    : "html";

                shouldRefreshPage = true;
                CKEDITOR.switchFormat = false;
            }

            this._api.update(data, event.data.callback || Imcms.BackgroundWorker.createTask({
                    showProcessWindow: true,
                    refreshPage: shouldRefreshPage
                })
            );

        } else if (event.data && event.data.callback && (typeof event.data.callback === "function")) {
            event.data.callback()
        }
    },
    _onCreated: function (event) {
        var editor = event.editor;

        // Customize editors.
        // These editors don't need features like smileys, templates, iframes etc.\
        // Customize the editor configurations on "configLoaded" event,
        // which is fired after the configuration file loading and
        // execution. This makes it possible to change the
        // configurations before the editor initialization takes place.
        editor.on('configLoaded', this._onEditorLoaded.bind(this));
    },
    _onGetTextHistory: function (event) {
        var data = jQuery(event.editor.element.$).data();

        data = { // sending only needed data, other can produce errors
            locale: data.locale,
            loopentryref: data.loopentryref,
            meta: Imcms.document.meta,
            no: data.no
        };

        this._api.get(data, event.data.callback);
    },
    _onValidateText: function (event) {
        this._api.validate({content: event.editor.getData()}, event.data.callback);
    },
    _onEditorLoaded: function (event) {
        var editor = event.editor;

        // commands definition
        editor.addCommand("switchFormat", CKEDITOR.newCommandWithExecution(function (editor) {
            CKEDITOR.switchFormat = true;
            editor.execCommand("confirmChangesBeforeSwitch");
        }));

        // Remove unnecessary plugins to make the editor simpler.
        editor.config.removePlugins = 'colorbutton,find,forms,newpage,removeformat,specialchar,stylescombo,templates';
        var customExtraPlugins = ",switchFormatToHTML,switchFormatToText,documentSaver,fileBrowser,link,textHistory,w3cValidator,maximize,toolbarswitch";

        if (editor.config.extraPlugins.indexOf(customExtraPlugins) == -1) {
            editor.config.extraPlugins = editor.config.extraPlugins + customExtraPlugins;
        }

        var fontPlugins = ['Bold', 'Italic', 'Underline', 'Strike'];
        var textParagraphPlugins = ['NumberedList', 'BulletedList', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'Outdent', 'Indent'];
        var linkPlugins = ['Link', 'Unlink', 'Anchor'];
        var imagesPlugins = ['Image', 'openBrowser'];
        var textPlugins = ['TextColor', 'BGColor'];
        var imcmsCustomPlugins = ['w3cValidate', 'textHistory', 'Toolbarswitch', 'saveData', 'confirm', 'cancel'];
        var switchFormatToTextPlugin = ['switchFormatToText'];
        var switchFormatToHtmlPlugin = ['switchFormatToHTML'];
        var plainTextPlugins = ['textHistory', 'Toolbarswitch', 'saveData', 'confirm', 'cancel'];
        var imageUtilsAndOtherDefaultPlugins = ['Image', 'openBrowser', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe'];
        var advancedFontPlugins = ['Styles', 'Format', 'Font', 'FontSize'];
        var sourcePlugin = ['Source'];
        var textEditingPlugins = ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Scayt'];
        var advancedActionsPlugins = ['Undo', 'Redo', '-', 'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat'];

        editor.config.toolbar_minPlainText = [
            plainTextPlugins
        ]; // Custom minimized toolbar config for tag with attribute "formats"="text"

        editor.config.toolbar_maxPlainText = [
            plainTextPlugins
        ]; // Custom maximized toolbar config for tag with attribute "formats"="text"

        editor.config.toolbar_minTextToolbar = [
            switchFormatToHtmlPlugin,
            linkPlugins,
            imagesPlugins,
            textPlugins,
            plainTextPlugins
        ]; // Custom minimized toolbar config for tag without attribute "formats" but was changed to "Text"

        editor.config.toolbar_minHtmlToolbar = [
            switchFormatToTextPlugin,
            fontPlugins,
            textParagraphPlugins,
            linkPlugins,
            imagesPlugins,
            textPlugins,
            sourcePlugin,
            imcmsCustomPlugins
        ]; // Custom minimized toolbar config for tag without attribute "formats" but was changed to "HTML"

        editor.config.toolbar_maxHtmlToolbar = [
            switchFormatToTextPlugin,
            fontPlugins,
            textParagraphPlugins,
            linkPlugins,
            imageUtilsAndOtherDefaultPlugins,
            advancedFontPlugins,
            textPlugins,
            textEditingPlugins,
            sourcePlugin,
            advancedActionsPlugins,
            imcmsCustomPlugins
        ]; // Custom maximized toolbar config for tag without attribute "formats" but was changed to "HTML"

        editor.config.toolbar_maxTextToolbar = [
            switchFormatToHtmlPlugin,
            linkPlugins,
            advancedActionsPlugins,
            plainTextPlugins
        ]; // Custom maximized toolbar config for tag without attribute "formats" but was changed to "HTML"

        editor.toolbarLocation = "top";
        editor.config.toolbar = CKEDITOR.defineToolbar(editor);
        editor.config.allowedContent = true;
    }
};
<|endoftext|>


<commit_before>(function($) {

    /**
     * Style manager widget
     */
    $.widget('mapbender.featureStyleEditor', {
        options: {
            asPopup:      true,
            data:         {
                'id':         null,
                'borderSize': 1
            },
            customColors: {
                '#777777': '#777777',
                '#337ab7': '#337ab7',
                '#5cb85c': '#5cb85c',
                '#5bc0de': '#5bc0de',
                '#f0ad4e': '#f0ad4e',
                '#d9534f': '#d9534f'
            },
            commonTab:    true
        },

        /**
         * Generate StyleManagerForm
         */
        _create: function() {
            var widget = this;
            var element = $(widget.element);
            var options = widget.options;
            var commonTab = {
                title:    "Allgemein",
                type:     "form",
                children: [{
                    type:      'input',
                    name:      'name',
                    title:     'Name',
                    infoText:  'Die Name erscheint in der Auswahlliste.',
                    mandatory: true
                }]
            };
            var customColors = options.customColors;
            var fillTab = {
                title:    "Füllung",
                type:     "form",
                children: [{
                    type:     'fieldSet',
                    children: [{
                        title:          "Farbe",
                        type:           "colorPicker",
                        name:           "fillColor",
                        value:          "#ff0000",
                        mandatory:      "/^#{1,1}[abcdefABCDEF0-9]{6,6}$/",
                        mandatoryText:  "Bitte Farbwähler nutzen",
                        colorSelectors: customColors,
                        css:            {width: "30%"}
                    }, {
                        title: "Deckkraft",
                        name:  "fillOpacity",
                        type:  "slider",
                        range: "max",
                        min:   0.1,
                        max:   1,
                        value: 1,
                        step:  0.1,
                        css:   {width: "35%"}

                    }, {
                        title:         "Punkt Radius",
                        name:          "pointRadius",
                        type:          "slider",
                        mandatory:     "/^\\d+$/",
                        mandatoryText: "Bitte nur Zahlen verwenden",
                        range:         "max",
                        min:           0,
                        max:           20,
                        value:         0,
                        css:   {width: "35%"}

                    },{
                        title:   "Aktivieren",
                        type:    "checkbox",
                        checked: true,
                        name:    "fill",
                        value:   '1'
                    }]
                }]
            };
            var backGroundTab = {
                title:    "Hintegrund",
                type:     "form",
                children: [{
                    type:     'fieldSet',
                    children: [{
                        title:         "Breite",
                        infoText:      "Die Breite der Hintergrund-Breite.  Wenn nicht angegeben, wird die graphicWidth verwendet.",
                        type:          "input",
                        name:          "backgroundWidth",
                        mandatoryText: "Bitte nur Zahlen verwenden",
                        css:           {width: '50%'}

                    }, {
                        title:         "Höhe",
                        infoText:      "Die Breite der Hintergrund-Höhe.  Wenn nicht angegeben, wird die graphicHeight verwendet.",
                        type:          "input",
                        name:          "backgroundHeight",
                        mandatoryText: "Bitte nur Zahlen verwenden",
                        css:           {width: '50%'}
                    }]
                }, {
                    type:     'fieldSet',
                    children: [{
                        title: "X-Offset", // infoText:  "The x offset (in pixels) for the background graphic.",
                        name:  "backgroundXOffset",
                        type:  "slider",
                        range: "max",
                        min:   0,
                        max:   100,
                        value: 0,
                        step:  1,
                        css:   {
                            width: '33%'
                        }
                    }, {
                        title: "Y-Offset",
                        type:  "slider",
                        name:  "backgroundYOffset",
                        range: "max",
                        min:   0,
                        max:   100,
                        value: 0,
                        step:  1,
                        css:   {
                            width: '33%'
                        }
                    }, {
                        title: "Z-Index",
                        type:  "slider",
                        name:  "backgroundGraphicZIndex", // infoText:  "The integer z-index value to use in rendering the background graphic.",
                        range: "max",
                        min:   0,
                        max:   100,
                        value: 0,
                        step:  1,
                        css:   {
                            width: '34%'
                        }
                    }]
                }, {
                    title:       "Bild URL",
                    infoText:    "Url to a graphic to be used as the background under an externalGraphic.",
                    type:        "input",
                    name:        "backgroundGraphic",
                    value:       "",
                    placeholder: "URL"
                }]
            };
            var strokeTab = {
                title:    "Rand",
                type:     "form",
                children: [{
                    type:     'fieldSet',
                    children: [{
                        title:         "Farbe",
                        type:          "colorPicker",
                        name:          "strokeColor",
                        value:         "#ffffff",
                        horizontal:    true,
                        mandatory:     "/^\#[A-F0-9]{6}$/i",
                        mandatoryText: "Bitte Farbwähler nutzen",
                        css:           {width: "30%"}

                    }, {
                        title: "Deckkraft",
                        name:  "strokeOpacity",
                        type:  "slider",
                        range: "max",
                        min:   0.1,
                        max:   1,
                        value: 1,
                        step:  0.1,
                        css:   {width: "35%"}

                    }, {
                        title: "Breite",
                        type:  "slider",
                        name:  "strokeWidth",
                        min:   0,
                        max:   10,
                        step:  1,
                        value: 1,
                        css:   {width: "35%"}
                    }]
                }, {
                    type:     'fieldSet',
                    children: [{
                        title:   "Glättung",
                        name:    "strokeLineCap",
                        type:    "select",
                        options: {
                            round:  "abgerundet",
                            square: "eckig",
                            butt:   "bünbdig"
                        },
                        value:   "round",
                        css:     {width: "50%"}
                    }, {
                        title:   "Style",
                        name:    "strokeDashStyle",
                        type:    "select",
                        options: {
                            Solid:           'Durchgezogen',
                            ShortDash:       'Kurze Striche',
                            ShortDot:        'Kleine Punkte',
                            ShortDashDot:    'Strichpunkt, kurz',
                            ShortDashDotDot: 'Strichpunktpunkt, kurz',
                            Dot:             'Punktiert',
                            Dash:            'Gestrichelt',
                            LongDash:        'Gestrichelt, lang',
                            DashDot:         'Strichpunkt',
                            LongDashDot:     'Strichpunktpunkt',
                            LongDashDotDot:  'Strichpunktpunkt, lang'
                        },
                        value:   "Solid",
                        css:     {width: "50%"}

                    }]
                }, {
                    title:   "Aktivieren",
                    type:    "checkbox",
                    checked: true,
                    name:    "stroke",
                    value:   '1'
                }]
            };
            var imageTab = {
                title:    "Bild",
                type:     "form",
                children: [{
                    title:    "Name",
                    type:     "input",
                    name:     "graphicName",
                    infoText: "Named graphic to use when rendering points.  Supported values include “circle” (default), “square”, “star”, “x”, “cross”, “triangle”."
                }, {
                    type:     'fieldSet',
                    children: [{
                        title:         "Breite",
                        type:          "input",
                        name:          "graphicWidth",
                        mandatoryText: "Bitte nur Zahlen verwenden",
                        css:           {width: '50%'}
                    }, {
                        title:         "Höhe",
                        type:          "input",
                        name:          "graphicHeight",
                        mandatoryText: "Bitte nur Zahlen verwenden",
                        css:           {width: '50%'}
                    }]
                }, {
                    type:     'fieldSet',
                    children: [{
                        title:         "X-Offset",
                        name:          "graphicXOffset",
                        type:          "slider",
                        mandatoryText: "Bitte nur Zahlen verwenden",
                        range:         "max",
                        min:           0,
                        max:           100,
                        value:         0,
                        step:          1,
                        css:           {
                            width: '33%'
                        }
                    }, {
                        title:         "Y-Offset",
                        type:          "slider",
                        name:          "graphicYOffset",
                        mandatoryText: "Bitte nur Zahlen verwenden",
                        range:         "max",
                        min:           0,
                        max:           100,
                        value:         0,
                        step:          1,
                        css:           {
                            width: '33%'
                        }
                    }, {
                        title: "Deckkraft",
                        name:  "graphicOpacity",
                        type:  "slider",
                        range: "max",
                        min:   0,
                        max:   1,
                        value: 1,
                        step:  0.01,
                        css:   {
                            width: '34%'
                        }
                    }]
                }, {
                    title:       "URL",
                    type:        "input",
                    name:        "graphicUrl",
                    value:       "",
                    placeholder: "URL"
                }]
            };
            var labelTab = {

                title:    'Beschriftung',
                type:     'form',
                children: [// labelAlign	{String} Label alignment.  This specifies the insertion point relative to the text.  It is a string composed of two characters.  The first character is for the horizontal alignment, the second for the vertical alignment.  Valid values for horizontal alignment: “l”=left, “c”=center, “r”=right.  Valid values for vertical alignment: “t”=top, “m”=middle, “b”=bottom.  Example values: “lt”, “cm”, “rb”.  Default is “cm”.
                    // labelXOffset	{Number} Pixel offset along the positive x axis for displacing the label.  Not supported by the canvas renderer.
                    // labelYOffset	{Number} Pixel offset along the positive y axis for displacing the label.  Not supported by the canvas renderer.
                    // labelOutlineColor	{String} The color of the label outline.  Default is ‘white’.  Only supported by the canvas & SVG renderers.
                    // labelOutlineWidth	{Number} The width of the label outline.  Default is 3, set to 0 or null to disable.  Only supported by the SVG renderers.
                    // labelOutlineOpacity	{Number} The opacity (0-1) of the label outline.  Default is fontOpacity.  Only supported by the canvas & SVG renderers.
                    {
                        type:     'textArea',
                        css:      {width: "100 %"},
                        name:     'label',
                        infoText: 'The text for an optional label.  For browsers that use the canvas renderer, this requires either fillText or mozDrawText to be available.'
                    }, {
                        type:     'fieldSet',
                        children: [{
                            title:    'Fontname',
                            type:     'select',
                            options:  {
                                "Open Sans":    "Open Sans",
                                "Calluna Sans": "Calluna Sans",
                                "Gill Sans MT": "Gill Sans MT",
                                'Calibri':      'Calibri',
                                "Trebuchet MS": "Trebuchet MS",
                                'sans-serif':   'sans-serif'
                            },
                            name:     'fontFamily',
                            infoText: 'The font family for the label, to be provided like in CSS.',
                            css:      {width: "50%"}

                        }, {
                            title:    'Grösse',
                            name:     'fontSize',
                            type:     'select',
                            options:  {
                                "9":  9,
                                "10": 10,
                                "11": 11,
                                "12": 12,
                                "13": 13,
                                "14": 14
                            },
                            css:      {width: "20%"},
                            infoText: 'The font size for the label, to be provided like in CSS'
                        }, //     {
                            //     title:    'Style',
                            //     type:     'input',
                            //     name:     'fontStyle',
                            //     infoText: 'The font style for the label, to be provided like in CSS'
                            // },

                            {
                                title:    'Art',
                                name:     'fontWeight',
                                type:     'select',
                                options:  {
                                    'regular': 'Normal',
                                    'bold':    'Fett',
                                    'italic':  'Kursive',
                                },
                                css:      {width: "30%"},
                                infoText: 'The font weight for the label, to be provided like in CSS.'
                            }, {
                                title:    'Farbe',
                                type:     'colorPicker',
                                name:     'fontColor',
                                // infoText: 'The font color for the label, to be provided like CSS.',
                                css:      {width: "50%"}
                            }, {
                                title: "Deckkraft",
                                name:  "fontOpacity",
                                type:  "slider",
                                range: "max",
                                min:   0,
                                max:   1,
                                value: 1,
                                step:  0.01,
                                css:   {
                                    width: '50%'
                                }
                            }, {
                                title:    "Selektierbar?",
                                type:     "checkbox",
                                checked:  false,
                                name:     "labelSelect",
                                infoText: 'If set to true, labels will be selectable using SelectFeature or similar controls.  Default is false.',
                                value:    'true',
                                css:      {
                                    width: '30%'
                                }
                            }]
                    }]

            };
            var miscTab = {
                title:    "Verschiedenes",
                type:     "form",
                children: [{
                    title:   "Zeigersymbol",
                    name:    "cursor",
                    type:    "select",
                    options: {
                        auto:        'Automatisch',
                        'default':   'Vorgabe',
                        crosshair:   'Kreuz',
                        pointer:     'Hand',
                        move:        'Verschieben',
                        // 'n-resize':  'n-resize',
                        // 'ne-resize': 'ne-resize',
                        // 'e-resize':  'e-resize',
                        // 'se-resize': 'se-resize',
                        // 's-resize':  's-resize',
                        // 'sw-resize': 'sw-resize',
                        // 'w-resize':  'w-resize',
                        // 'nw-resize': 'nw-resize',
                        text:        'Textauswahl',
                        wait:        'Warten',
                        help:        'Hilfe'
                    },
                    value:   "pointer"
                }, {
                    title:     "Rotation (°)",
                    name:      "rotation",
                    type:      "slider",
                    mandatory: "/^\\d+$/",
                    range:     "max",
                    min:       0,
                    max:       360,
                    value:     0,
                    step:      1
                }, {
                    title:   "Anzeige",
                    name:    "display",
                    type:    "select",
                    options: {
                        inline:         "inline",
                        "inline-block": "inline-block",
                        block:          "block",
                        none:           "none"
                    },
                    value:   "block"
                }]
            };

            var tabs = [];

            if(options.commonTab) {
                tabs.push(commonTab);
            }

            tabs.push(fillTab);
            tabs.push(strokeTab);
            tabs.push(labelTab);
            // tabs.push(imageTab);
            // tabs.push(backGroundTab);
            // tabs.push(miscTab);

            element.generateElements({
                type:     "tabs",
                children: tabs
            });

            window.setTimeout(function() {
                element.formData(options.data);
            }, 100);

            if(options.asPopup) {
                widget.popup();
            }

            return widget;
        },

        popup: function() {
            var widget = this;
            var element = $(widget.element);
            element.popupDialog({
                title:   "Stylemanager",
                modal:   true,
                width:   '500px',
                buttons: [{
                    text:  "Abbrechen",
                    click: function(e) {
                        widget.close();
                        return false;
                    }
                }, {
                    text:  "Speichern",
                    click: function(e) {
                        var form = $(e.currentTarget).closest(".ui-dialog");
                        widget._trigger('submit', null, {
                            form:   form,
                            widget: widget
                        });
                    }
                }]
            });
        },

        /**
         *
         * @private
         */
        close: function() {
            var widget = this;
            var element = $(widget.element);
            var options = widget.options;

            if(options.asPopup) {
                element.popupDialog("close");
            } else {
                widget.element.remove();
            }
        }
    });

})(jQuery);
<commit_msg>Add style name mandatory text<commit_after>(function($) {

    /**
     * Style manager widget
     */
    $.widget('mapbender.featureStyleEditor', {
        options: {
            asPopup:      true,
            data:         {
                'id':         null,
                'borderSize': 1
            },
            customColors: {
                '#777777': '#777777',
                '#337ab7': '#337ab7',
                '#5cb85c': '#5cb85c',
                '#5bc0de': '#5bc0de',
                '#f0ad4e': '#f0ad4e',
                '#d9534f': '#d9534f'
            },
            commonTab:    true
        },

        /**
         * Generate StyleManagerForm
         */
        _create: function() {
            var widget = this;
            var element = $(widget.element);
            var options = widget.options;
            var commonTab = {
                title:    "Allgemein",
                type:     "form",
                children: [{
                    type:      'input',
                    name:      'name',
                    title:     'Name',
                    mandatoryText: "Bitte einen Namen eintragen.",
                    infoText:  'Die Name erscheint in der Auswahlliste.',
                    mandatory: true
                }]
            };
            var customColors = options.customColors;
            var fillTab = {
                title:    "Füllung",
                type:     "form",
                children: [{
                    type:     'fieldSet',
                    children: [{
                        title:          "Farbe",
                        type:           "colorPicker",
                        name:           "fillColor",
                        value:          "#ff0000",
                        mandatory:      "/^#{1,1}[abcdefABCDEF0-9]{6,6}$/",
                        mandatoryText:  "Bitte Farbwähler nutzen",
                        colorSelectors: customColors,
                        css:            {width: "30%"}
                    }, {
                        title: "Deckkraft",
                        name:  "fillOpacity",
                        type:  "slider",
                        range: "max",
                        min:   0.1,
                        max:   1,
                        value: 1,
                        step:  0.1,
                        css:   {width: "35%"}

                    }, {
                        title:         "Punkt Radius",
                        name:          "pointRadius",
                        type:          "slider",
                        mandatory:     "/^\\d+$/",
                        mandatoryText: "Bitte nur Zahlen verwenden",
                        range:         "max",
                        min:           0,
                        max:           20,
                        value:         0,
                        css:   {width: "35%"}

                    },{
                        title:   "Aktivieren",
                        type:    "checkbox",
                        checked: true,
                        name:    "fill",
                        value:   '1'
                    }]
                }]
            };
            var backGroundTab = {
                title:    "Hintegrund",
                type:     "form",
                children: [{
                    type:     'fieldSet',
                    children: [{
                        title:         "Breite",
                        infoText:      "Die Breite der Hintergrund-Breite.  Wenn nicht angegeben, wird die graphicWidth verwendet.",
                        type:          "input",
                        name:          "backgroundWidth",
                        mandatoryText: "Bitte nur Zahlen verwenden",
                        css:           {width: '50%'}

                    }, {
                        title:         "Höhe",
                        infoText:      "Die Breite der Hintergrund-Höhe.  Wenn nicht angegeben, wird die graphicHeight verwendet.",
                        type:          "input",
                        name:          "backgroundHeight",
                        mandatoryText: "Bitte nur Zahlen verwenden",
                        css:           {width: '50%'}
                    }]
                }, {
                    type:     'fieldSet',
                    children: [{
                        title: "X-Offset", // infoText:  "The x offset (in pixels) for the background graphic.",
                        name:  "backgroundXOffset",
                        type:  "slider",
                        range: "max",
                        min:   0,
                        max:   100,
                        value: 0,
                        step:  1,
                        css:   {
                            width: '33%'
                        }
                    }, {
                        title: "Y-Offset",
                        type:  "slider",
                        name:  "backgroundYOffset",
                        range: "max",
                        min:   0,
                        max:   100,
                        value: 0,
                        step:  1,
                        css:   {
                            width: '33%'
                        }
                    }, {
                        title: "Z-Index",
                        type:  "slider",
                        name:  "backgroundGraphicZIndex", // infoText:  "The integer z-index value to use in rendering the background graphic.",
                        range: "max",
                        min:   0,
                        max:   100,
                        value: 0,
                        step:  1,
                        css:   {
                            width: '34%'
                        }
                    }]
                }, {
                    title:       "Bild URL",
                    infoText:    "Url to a graphic to be used as the background under an externalGraphic.",
                    type:        "input",
                    name:        "backgroundGraphic",
                    value:       "",
                    placeholder: "URL"
                }]
            };
            var strokeTab = {
                title:    "Rand",
                type:     "form",
                children: [{
                    type:     'fieldSet',
                    children: [{
                        title:         "Farbe",
                        type:          "colorPicker",
                        name:          "strokeColor",
                        value:         "#ffffff",
                        horizontal:    true,
                        mandatory:     "/^\#[A-F0-9]{6}$/i",
                        mandatoryText: "Bitte Farbwähler nutzen",
                        css:           {width: "30%"}

                    }, {
                        title: "Deckkraft",
                        name:  "strokeOpacity",
                        type:  "slider",
                        range: "max",
                        min:   0.1,
                        max:   1,
                        value: 1,
                        step:  0.1,
                        css:   {width: "35%"}

                    }, {
                        title: "Breite",
                        type:  "slider",
                        name:  "strokeWidth",
                        min:   0,
                        max:   10,
                        step:  1,
                        value: 1,
                        css:   {width: "35%"}
                    }]
                }, {
                    type:     'fieldSet',
                    children: [{
                        title:   "Glättung",
                        name:    "strokeLineCap",
                        type:    "select",
                        options: {
                            round:  "abgerundet",
                            square: "eckig",
                            butt:   "bünbdig"
                        },
                        value:   "round",
                        css:     {width: "50%"}
                    }, {
                        title:   "Style",
                        name:    "strokeDashStyle",
                        type:    "select",
                        options: {
                            Solid:           'Durchgezogen',
                            ShortDash:       'Kurze Striche',
                            ShortDot:        'Kleine Punkte',
                            ShortDashDot:    'Strichpunkt, kurz',
                            ShortDashDotDot: 'Strichpunktpunkt, kurz',
                            Dot:             'Punktiert',
                            Dash:            'Gestrichelt',
                            LongDash:        'Gestrichelt, lang',
                            DashDot:         'Strichpunkt',
                            LongDashDot:     'Strichpunktpunkt',
                            LongDashDotDot:  'Strichpunktpunkt, lang'
                        },
                        value:   "Solid",
                        css:     {width: "50%"}

                    }]
                }, {
                    title:   "Aktivieren",
                    type:    "checkbox",
                    checked: true,
                    name:    "stroke",
                    value:   '1'
                }]
            };
            var imageTab = {
                title:    "Bild",
                type:     "form",
                children: [{
                    title:    "Name",
                    type:     "input",
                    name:     "graphicName",
                    infoText: "Named graphic to use when rendering points.  Supported values include “circle” (default), “square”, “star”, “x”, “cross”, “triangle”."
                }, {
                    type:     'fieldSet',
                    children: [{
                        title:         "Breite",
                        type:          "input",
                        name:          "graphicWidth",
                        mandatoryText: "Bitte nur Zahlen verwenden",
                        css:           {width: '50%'}
                    }, {
                        title:         "Höhe",
                        type:          "input",
                        name:          "graphicHeight",
                        mandatoryText: "Bitte nur Zahlen verwenden",
                        css:           {width: '50%'}
                    }]
                }, {
                    type:     'fieldSet',
                    children: [{
                        title:         "X-Offset",
                        name:          "graphicXOffset",
                        type:          "slider",
                        mandatoryText: "Bitte nur Zahlen verwenden",
                        range:         "max",
                        min:           0,
                        max:           100,
                        value:         0,
                        step:          1,
                        css:           {
                            width: '33%'
                        }
                    }, {
                        title:         "Y-Offset",
                        type:          "slider",
                        name:          "graphicYOffset",
                        mandatoryText: "Bitte nur Zahlen verwenden",
                        range:         "max",
                        min:           0,
                        max:           100,
                        value:         0,
                        step:          1,
                        css:           {
                            width: '33%'
                        }
                    }, {
                        title: "Deckkraft",
                        name:  "graphicOpacity",
                        type:  "slider",
                        range: "max",
                        min:   0,
                        max:   1,
                        value: 1,
                        step:  0.01,
                        css:   {
                            width: '34%'
                        }
                    }]
                }, {
                    title:       "URL",
                    type:        "input",
                    name:        "graphicUrl",
                    value:       "",
                    placeholder: "URL"
                }]
            };
            var labelTab = {

                title:    'Beschriftung',
                type:     'form',
                children: [// labelAlign	{String} Label alignment.  This specifies the insertion point relative to the text.  It is a string composed of two characters.  The first character is for the horizontal alignment, the second for the vertical alignment.  Valid values for horizontal alignment: “l”=left, “c”=center, “r”=right.  Valid values for vertical alignment: “t”=top, “m”=middle, “b”=bottom.  Example values: “lt”, “cm”, “rb”.  Default is “cm”.
                    // labelXOffset	{Number} Pixel offset along the positive x axis for displacing the label.  Not supported by the canvas renderer.
                    // labelYOffset	{Number} Pixel offset along the positive y axis for displacing the label.  Not supported by the canvas renderer.
                    // labelOutlineColor	{String} The color of the label outline.  Default is ‘white’.  Only supported by the canvas & SVG renderers.
                    // labelOutlineWidth	{Number} The width of the label outline.  Default is 3, set to 0 or null to disable.  Only supported by the SVG renderers.
                    // labelOutlineOpacity	{Number} The opacity (0-1) of the label outline.  Default is fontOpacity.  Only supported by the canvas & SVG renderers.
                    {
                        type:     'textArea',
                        css:      {width: "100 %"},
                        name:     'label',
                        infoText: 'The text for an optional label.  For browsers that use the canvas renderer, this requires either fillText or mozDrawText to be available.'
                    }, {
                        type:     'fieldSet',
                        children: [{
                            title:    'Fontname',
                            type:     'select',
                            options:  {
                                "Open Sans":    "Open Sans",
                                "Calluna Sans": "Calluna Sans",
                                "Gill Sans MT": "Gill Sans MT",
                                'Calibri':      'Calibri',
                                "Trebuchet MS": "Trebuchet MS",
                                'sans-serif':   'sans-serif'
                            },
                            name:     'fontFamily',
                            infoText: 'The font family for the label, to be provided like in CSS.',
                            css:      {width: "50%"}

                        }, {
                            title:    'Grösse',
                            name:     'fontSize',
                            type:     'select',
                            options:  {
                                "9":  9,
                                "10": 10,
                                "11": 11,
                                "12": 12,
                                "13": 13,
                                "14": 14
                            },
                            css:      {width: "20%"},
                            infoText: 'The font size for the label, to be provided like in CSS'
                        }, //     {
                            //     title:    'Style',
                            //     type:     'input',
                            //     name:     'fontStyle',
                            //     infoText: 'The font style for the label, to be provided like in CSS'
                            // },

                            {
                                title:    'Art',
                                name:     'fontWeight',
                                type:     'select',
                                options:  {
                                    'regular': 'Normal',
                                    'bold':    'Fett',
                                    'italic':  'Kursive',
                                },
                                css:      {width: "30%"},
                                infoText: 'The font weight for the label, to be provided like in CSS.'
                            }, {
                                title:    'Farbe',
                                type:     'colorPicker',
                                name:     'fontColor',
                                // infoText: 'The font color for the label, to be provided like CSS.',
                                css:      {width: "50%"}
                            }, {
                                title: "Deckkraft",
                                name:  "fontOpacity",
                                type:  "slider",
                                range: "max",
                                min:   0,
                                max:   1,
                                value: 1,
                                step:  0.01,
                                css:   {
                                    width: '50%'
                                }
                            }, {
                                title:    "Selektierbar?",
                                type:     "checkbox",
                                checked:  false,
                                name:     "labelSelect",
                                infoText: 'If set to true, labels will be selectable using SelectFeature or similar controls.  Default is false.',
                                value:    'true',
                                css:      {
                                    width: '30%'
                                }
                            }]
                    }]

            };
            var miscTab = {
                title:    "Verschiedenes",
                type:     "form",
                children: [{
                    title:   "Zeigersymbol",
                    name:    "cursor",
                    type:    "select",
                    options: {
                        auto:        'Automatisch',
                        'default':   'Vorgabe',
                        crosshair:   'Kreuz',
                        pointer:     'Hand',
                        move:        'Verschieben',
                        // 'n-resize':  'n-resize',
                        // 'ne-resize': 'ne-resize',
                        // 'e-resize':  'e-resize',
                        // 'se-resize': 'se-resize',
                        // 's-resize':  's-resize',
                        // 'sw-resize': 'sw-resize',
                        // 'w-resize':  'w-resize',
                        // 'nw-resize': 'nw-resize',
                        text:        'Textauswahl',
                        wait:        'Warten',
                        help:        'Hilfe'
                    },
                    value:   "pointer"
                }, {
                    title:     "Rotation (°)",
                    name:      "rotation",
                    type:      "slider",
                    mandatory: "/^\\d+$/",
                    range:     "max",
                    min:       0,
                    max:       360,
                    value:     0,
                    step:      1
                }, {
                    title:   "Anzeige",
                    name:    "display",
                    type:    "select",
                    options: {
                        inline:         "inline",
                        "inline-block": "inline-block",
                        block:          "block",
                        none:           "none"
                    },
                    value:   "block"
                }]
            };

            var tabs = [];

            if(options.commonTab) {
                tabs.push(commonTab);
            }

            tabs.push(fillTab);
            tabs.push(strokeTab);
            tabs.push(labelTab);
            // tabs.push(imageTab);
            // tabs.push(backGroundTab);
            // tabs.push(miscTab);

            element.generateElements({
                type:     "tabs",
                children: tabs
            });

            window.setTimeout(function() {
                element.formData(options.data);
            }, 100);

            if(options.asPopup) {
                widget.popup();
            }

            return widget;
        },

        popup: function() {
            var widget = this;
            var element = $(widget.element);
            element.popupDialog({
                title:   "Stylemanager",
                modal:   true,
                width:   '500px',
                buttons: [{
                    text:  "Abbrechen",
                    click: function(e) {
                        widget.close();
                        return false;
                    }
                }, {
                    text:  "Speichern",
                    click: function(e) {
                        var form = $(e.currentTarget).closest(".ui-dialog");
                        widget._trigger('submit', null, {
                            form:   form,
                            widget: widget
                        });
                    }
                }]
            });
        },

        /**
         *
         * @private
         */
        close: function() {
            var widget = this;
            var element = $(widget.element);
            var options = widget.options;

            if(options.asPopup) {
                element.popupDialog("close");
            } else {
                widget.element.remove();
            }
        }
    });

})(jQuery);
<|endoftext|>


<commit_before>
import Meteor from 'react-native-meteor';

class ImageUtil {

  _slugify(desc, acfileame) {
    var text = desc;
    if (!text) {
      text = acfileame.split('.');
      text = text[0];
    }
    text = text.toString().toLowerCase()
      .replace(/\s+/g, '-')           // Replace spaces with -
      .replace(/[^\w\-]+/g, '')       // eslint-disable-line no-useless-escape
      .replace(/\-\-+/g, '-')         // eslint-disable-line no-useless-escape
      .replace(/^-+/, '')             // Trim - from start of text
      .replace(/-+$/, '');            // Trim - from end of text
    if (text.length < 1) {
      text = acfileame;
    }
    return text;
  }

  _getExtension(filename) {
    var i = filename.lastIndexOf('.');
    return (i < 0) ? '' : filename.substr(i).toLowerCase();
  }

  uploadImage(data, rid, isImage, desc, callBack) {
    let ezfilesize = 10050000;
    const _super = this;
    if (data.size) {
      ezfilesize = data.size;
    }
      // RNFS.stat(data.path).then((stats) => {
        // console.log("**** file stats ****");
        // console.log(stats);
        // ezfilesize = stats.size;
    _super._metUploadRequest(data, ezfilesize, rid, isImage, desc, callBack);
      // });
  }

  _metUploadRequest(data, filesize, roomid, isImage, desc, callBack) {
    var acfilename = data.path.replace(/^.*[\\\/]/, ''); // eslint-disable-line no-useless-escape
    const fileTemp = acfilename.split('?');// this is the key we got from meteor
    acfilename = fileTemp[0];
    console.log('Image Upload _metUploadRequest=', acfilename, '::', roomid);
    const _super = this;
        // upload request
    let ezType = 'video/mp4';
    if (isImage) { ezType = 'image/jpeg'; }
    const newFileName = this._slugify(desc, acfilename) + this._getExtension(acfilename);

    Meteor.call('slingshot/uploadRequest', 'rocketchat-uploads', { name: newFileName, size: filesize, type: ezType },
    { rid: roomid }, (err, res) => {
      console.log('_metUploadRequest errors:'); console.log(err);
      _super._parseMetUploadResponse(data, newFileName, filesize, res, ezType, desc, callBack);
    });
  }

  _parseMetUploadResponse(data, newfilename, filesize, res, ezType, desc, callBack) {
    let fileType = ezType;
    var uploadFilename = '';
    for (let i = 0; i < res.postData.length; i += 1) {
      const name = res.postData[i].name;
      const value = res.postData[i].value;
      if (name === 'key') {
        uploadFilename = value;
      } else if (name === 'Content-Type') {
        fileType = value;
      }
    }
    const file = {
      uri: data.path,
      name: newfilename,
      type: fileType,
    };

    const xhr = new XMLHttpRequest();
    const formData = new FormData();
    for (let i = 0; i < res.postData.length; i += 1) {
      const name = res.postData[i].name;
      const value = res.postData[i].value;
      formData.append(name, value);
    }

    formData.append('file', file);
    callBack(newfilename, 0, 'STARTED');
    xhr.upload.addEventListener('progress', (evt) => {
      if (evt.lengthComputable) {
        const percentComplete = evt.loaded / evt.total;
        if (percentComplete === 1) {
          callBack(newfilename, percentComplete, 'COMPLETE');
        } else {
          callBack(newfilename, percentComplete, 'INPROGRESS');
        }
      }
    }, false);
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status === 204) {
          const ezURI = decodeURIComponent(xhr.responseHeaders.Location); // .replace('%2F', '/');
          const temp = uploadFilename.split('/');// this is the key we got from meteor
          const ezid = temp[temp.length - 1];
          temp.pop();
//          const subFolder = temp[temp.length - 1];// unused
          temp.pop();
          const folder = temp[temp.length - 1];
          const fileObj = {
            type: fileType, size: filesize, name: newfilename, description: desc, _id: ezid, url: ezURI,
          };

          Meteor.call('sendFileMessage', folder, 's3', fileObj, (sferr, sfres) => {
            console.log(sferr);
            console.log(sfres);
          });
          callBack(newfilename, 1, 'SENT');
        } else {
          console.log('~~~~~~~~~~~~~~FAILED~~~~~~~~~~~~~~~~~~');
          console.log(xhr);
          callBack(newfilename, 1, 'FAILED');
        }
      }
    };
    xhr.open('POST', res.upload);
    xhr.setRequestHeader('Content-Length', formData.length);
    xhr.send(formData);
  }

}

export default ImageUtil;
<commit_msg> filesize set to max<commit_after>
import Meteor from 'react-native-meteor';
import Network from '../../../network';

class ImageUtil {

  _slugify(desc, acfileame) {
    var text = desc;
    if (!text) {
      text = acfileame.split('.');
      text = text[0];
    }
    text = text.toString().toLowerCase()
      .replace(/\s+/g, '-')           // Replace spaces with -
      .replace(/[^\w\-]+/g, '')       // eslint-disable-line no-useless-escape
      .replace(/\-\-+/g, '-')         // eslint-disable-line no-useless-escape
      .replace(/^-+/, '')             // Trim - from start of text
      .replace(/-+$/, '');            // Trim - from end of text
    if (text.length < 1) {
      text = acfileame;
    }
    return text;
  }

  _getExtension(filename) {
    var i = filename.lastIndexOf('.');
    return (i < 0) ? '' : filename.substr(i).toLowerCase();
  }

  uploadImage(data, rid, isImage, desc, callBack) {
    let ezfilesize = 10050000;
    const _net = new Network();
    const maxfileSize = _net.getServerSetting('FileUpload_MaxFileSize');
    if (maxfileSize && maxfileSize.value) {
      ezfilesize = maxfileSize.value;
    }
    const _super = this;
    if (data.size) {
      ezfilesize = data.size;
    }
      // RNFS.stat(data.path).then((stats) => {
        // console.log("**** file stats ****");
        // console.log(stats);
        // ezfilesize = stats.size;
    _super._metUploadRequest(data, ezfilesize, rid, isImage, desc, callBack);
      // });
  }

  _metUploadRequest(data, filesize, roomid, isImage, desc, callBack) {
    var acfilename = data.path.replace(/^.*[\\\/]/, ''); // eslint-disable-line no-useless-escape
    const fileTemp = acfilename.split('?');// this is the key we got from meteor
    acfilename = fileTemp[0];
    console.log('Image Upload _metUploadRequest=', acfilename, '::', roomid);
    const _super = this;
        // upload request
    let ezType = 'video/mp4';
    if (isImage) { ezType = 'image/jpeg'; }
    const newFileName = this._slugify(desc, acfilename) + this._getExtension(acfilename);

    Meteor.call('slingshot/uploadRequest', 'rocketchat-uploads', { name: newFileName, size: filesize, type: ezType },
    { rid: roomid }, (err, res) => {
      console.log('_metUploadRequest errors:'); console.log(err);
      _super._parseMetUploadResponse(data, newFileName, filesize, res, ezType, desc, callBack);
    });
  }

  _parseMetUploadResponse(data, newfilename, filesize, res, ezType, desc, callBack) {
    let fileType = ezType;
    var uploadFilename = '';
    for (let i = 0; i < res.postData.length; i += 1) {
      const name = res.postData[i].name;
      const value = res.postData[i].value;
      if (name === 'key') {
        uploadFilename = value;
      } else if (name === 'Content-Type') {
        fileType = value;
      }
    }
    const file = {
      uri: data.path,
      name: newfilename,
      type: fileType,
    };

    const xhr = new XMLHttpRequest();
    const formData = new FormData();
    for (let i = 0; i < res.postData.length; i += 1) {
      const name = res.postData[i].name;
      const value = res.postData[i].value;
      formData.append(name, value);
    }

    formData.append('file', file);
    callBack(newfilename, 0, 'STARTED');
    xhr.upload.addEventListener('progress', (evt) => {
      if (evt.lengthComputable) {
        const percentComplete = evt.loaded / evt.total;
        if (percentComplete === 1) {
          callBack(newfilename, percentComplete, 'COMPLETE');
        } else {
          callBack(newfilename, percentComplete, 'INPROGRESS');
        }
      }
    }, false);
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status === 204) {
          const ezURI = decodeURIComponent(xhr.responseHeaders.Location); // .replace('%2F', '/');
          const temp = uploadFilename.split('/');// this is the key we got from meteor
          const ezid = temp[temp.length - 1];
          temp.pop();
//          const subFolder = temp[temp.length - 1];// unused
          temp.pop();
          const folder = temp[temp.length - 1];
          const fileObj = {
            type: fileType, size: filesize, name: newfilename, description: desc, _id: ezid, url: ezURI,
          };

          Meteor.call('sendFileMessage', folder, 's3', fileObj, (sferr, sfres) => {
            console.log(sferr);
            console.log(sfres);
          });
          callBack(newfilename, 1, 'SENT');
        } else {
          console.log('~~~~~~~~~~~~~~FAILED~~~~~~~~~~~~~~~~~~');
          console.log(xhr);
          callBack(newfilename, 1, 'FAILED');
        }
      }
    };
    xhr.open('POST', res.upload);
    xhr.setRequestHeader('Content-Length', formData.length);
    xhr.send(formData);
  }

}

export default ImageUtil;
<|endoftext|>


<commit_before>import tape from 'tape'
import checkDisposable from './disposable'

const it = (desc, callback) => tape(`check-disposable ${desc}`, callback)

it('check-disposable detects disposable email', (t) => {
  t.plan(1)

  const email = 'pokemail@mailinator.com'

  checkDisposable(email, (err, isDisposable) => {
    t.is(isDisposable, true)
    t.end()
  })
})

it('check-disposable detects non-disposable email', (t) => {
  t.plan(1)

  const email = 'pokemail@gmail.com'

  checkDisposable(email, (err, isDisposable) => {
    t.is(isDisposable, false)
    t.end()
  })
})
<commit_msg>Fix duplication in test names<commit_after>import tape from 'tape'
import checkDisposable from './disposable'

const it = (desc, callback) => tape(`check-disposable ${desc}`, callback)

it('detects disposable email', (t) => {
  t.plan(1)

  const email = 'pokemail@mailinator.com'

  checkDisposable(email, (err, isDisposable) => {
    t.is(isDisposable, true)
    t.end()
  })
})

it('detects non-disposable email', (t) => {
  t.plan(1)

  const email = 'pokemail@gmail.com'

  checkDisposable(email, (err, isDisposable) => {
    t.is(isDisposable, false)
    t.end()
  })
})
<|endoftext|>