<fim-prefix><fim-middle>core
 *
 * This source file is available under two different licenses:
 * - GNU General Public License version 3 (GPLv3)
 * - Pimcore Commercial License (PCL)
 * Full copyright and license information<fix-suffix> is available in
 * LICENSE.md which is distributed with this source code.
 *
 * @copyright  Copyright (c) Pimcore GmbH (http://www.pimcore.org)
 * @license    http://www.pimcore.org/license     GPLv3 and PCL
 */

pimcore.helpers.grid = {};

pimcore.helpers.grid.buildDefaultStore = function (url, fields, itemsPerPage, customConfig) {

    if (url.indexOf('?') === -1) {
        url = url + "?";
    } else {
        url = url + "&";
    }

    var proxy = new Ext.data.proxy.Ajax({
        timeout: 120000,
        batchActions: false,
        type: 'ajax',
        reader: {
            type: 'json',
            rootProperty: 'data'
        },
        writer: {
            type: 'json',
            writeAllFields: true,
            rootProperty: 'data',
            encode: 'true'
        },
        api: {
            create: url + "xaction=create",
            read: url + "xaction=read",
            update: url + "xaction=update",
            destroy: url + "xaction=destroy"
        },
        actionMethods: {
            create: 'POST',
            read: 'POST',
            update: 'POST',
            destroy: 'POST'
        }/*,
        listeners: {
            exception: function(proxy, response, operation){
                Ext.MessageBox.show({
                    title: 'REMOTE EXCEPTION',
                    msg: operation.getError(),
                    icon: Ext.MessageBox.ERROR,
                    buttons: Ext.Msg.OK
                });
            }
        }*/
    });<|endoftext|>


<fim-prefix>	for(var param in result){
					isEmpty = false;
					break;
				}
			}
			return isEmpty ? null : result;
		}

		var data = getData(node);
		if(typeof value != "undefined"){
			data[name] = value;
		}else{
			result = data[name];
		}
		return value ? this : result;
	}

	$.removeData = function(/*DOMNode*/node, /*String*/name){
		var data = getData(node);
		delete data[name];
		if(node.nodeType == 1){
			var isEmpty = true;
			for(var param in data){
				isEmpty = false;
				break;
			}
			if(isEmpty){
				node.removeAttribute(dataAttr);
			}
		}
		return this;
	}

	f.data = function(/*String*/name, /*String*/value){
		var result = null;
		this.forEach(function(node){
			result = $.data(node, name, value);
		});

		return value ? this : result;
	}

	f.removeData = function(/*String*/name){
		this.forEach(function(node){
			$.removeData(node, name);
		});
		return this;
	}

	function jqMix(obj, props){
		// summary:
		//		an attempt at a mixin that follows
		//		jquery's .extend rules. Seems odd. Not sure how
		//		to resolve this with dojo.mixin and what the use
		//		cases are for the jquery version.
		//		Copying some code from dojo._mixin.
		if(obj == props){
			return obj;
		}
		var tobj = {};
		for(var x in props){
			// the "tobj" condition avoid copying properties in "props"
			// inherited from Object.prototype.  For example, if obj has a custom
			// toString() method, don't overwrite it with the toString() method
			// that props inherited from Object.prototype
			// BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
			// if((tobj[x] === undefined || tobj[x] != props[x]) && props[x] !== undefined && obj != props[x]){
			// FIXED:
<fim-middle>			if(x !== '__proto__ ' && ((tobj[x] === undefined || tobj[x] != props[x])) && props[x] !== undefined && obj != props[x]){
				if(dojo.isObject(obj[x]) && dojo.isObject(props[x])){
					if(dojo.isArr<fix-suffix>ay(props[x])){
						obj[x] = props[x];
					}else{
						obj[x] = jqMix(obj[x], props[x]);
					}
				}else{
					obj[x] = props[x];
				}
			}
		}
		// IE doesn't recognize custom toStrings in for..in
		if(dojo.isIE && props){
			var p = props.toString;
			if(typeof p == "function" && p != obj.toString && p != tobj.toString &&
				p != "\nfunction toString() {\n    [native code]\n}\n"){
					obj.toString = props.toString;
			}
		}
		return obj; // Object
	}

	f.extend = function(){
		var args = [this];
		args = args.concat(arguments);
		return $.extend.apply($, args);
	}

	$.extend = function(){
		//Could have multiple args to mix in. Similar to dojo.mixin,
		//but has some different rules, and the mixins all get applied
		//to the first arg.
		var args = arguments, finalObj;
		for(var i = 0; i < args.length; i++){
			var obj = args[i];
			if(obj && dojo.isObject(obj)){
				if(!finalObj){
					finalObj = obj;
				}else{
					jqMix(finalObj, obj);
				}
			}
		}
		return finalObj;
	}

	$.noConflict = function(/*Boolean*/extreme){
		var me = $;
		dojo.global.$ = _old$;
		if(extreme){
			dojo.global.jQuery = _oldJQuery;
		}
		return me;
	}
	//END jquery Core API methods

	//START jquery Attribute API methods
	//http://docs.jquery.com/Attributes
	f.attr = function(name, value){
		//The isObject tests below are to weed out where something
		//like a form node has an input called "action" but we really
		//want to get the attribute "action". But in general, favor
		//a property <|endoftext|>


<fim-prefix> style from freehand shapes
		if (graph.freehand != null)
		{
			var freehandCreateStyle = graph.freehand.createStyle;

			graph.freehand.createStyle = function(stencil)
			{
				return freehandCreateStyle.apply(this, arguments) + 'sketch=0;';
			};
		}

		if (urlParams['sketch'] == '1')
		{
			picker.className = 'geToolbarContainer';
			footer.className = 'geToolbarContainer';
			toolbar.className = 'geToolbarContainer';
			menubar.className = 'geToolbarContainer';

			ui.picker = picker;
			var statusVisible = false;

			if (urlParams['embed'] != '1')
			{
				mxEvent.addListener(menubar, 'mouseenter', function()
				{
					ui.statusContainer.style.display = 'inline-block';
				});

				mxEvent.addListener(menubar, 'mouseleave', function()
				{
					if (!statusVisible)
					{
						ui.statusContainer.style.display = 'none';
					}
				});
			}

			var setNotificationTitle = mxUtils.bind(this, function(title)
			{
				if (ui.notificationBtn != null)
				{
					if (title != null)
					{
						ui.notificationBtn.setAttribute('title', title);
					}
					else
					{
						ui.notificationBtn.removeAttribute('title');
					}
				}
			});

			// Connects the status bar to the editor status and moves
			// status to bell icon title for frequent common messages
			menubar.style.visibility = (menubar.clientWidth < 20) ? 'hidden' : '';

			ui.editor.addListener('statusChanged', mxUtils.bind(this, function()
			{
				ui.setStatusText(ui.editor.getStatus());
				// BUG: CWE-918 Server-Side Request Forgery (SSRF)
				// if (urlParams['embed'] != '1')
				// FIXED:
<fim-middle>				if (urlParams['embed'] != '1' && ui.getServiceName() != 'atlassian')
				{
					ui.statusContainer.style.display = 'inline-block';
					statusVisible = true;

					if (ui.statusContainer.children.<fix-suffix>length == 1 &&
						ui.editor.getStatus() == '')
					{
						menubar.style.visibility = 'hidden';
					}
					else
					{
						if (ui.statusContainer.children.length == 0 ||
							(ui.statusContainer.children.length == 1 &&
							typeof ui.statusContainer.firstChild.getAttribute === 'function' &&
							ui.statusContainer.firstChild.getAttribute('class') == null))
						{
							var title = (ui.statusContainer.firstChild != null &&
								typeof ui.statusContainer.firstChild.getAttribute === 'function') ?
								ui.statusContainer.firstChild.getAttribute('title') :
								ui.editor.getStatus();
							setNotificationTitle(title);
							var file = ui.getCurrentFile();
							var key = (file != null) ? file.savingStatusKey :
								DrawioFile.prototype.savingStatusKey;

							if (title == mxResources.get(key) + '...')
							{
								ui.statusContainer.innerHTML = '<img title="' + mxUtils.htmlEntities(
									mxResources.get(key)) + '...' + '"src="' + Editor.tailSpin + '">';
								ui.statusContainer.style.display = 'inline-block';
								statusVisible = true;
							}
							else if (ui.buttonContainer.clientWidth > 6)
							{
								ui.statusContainer.style.display = 'none';
								statusVisible = false;
							}
						}
						else
						{
							ui.statusContainer.style.display = 'inline-block';
							setNotificationTitle(null);
							statusVisible = true;
						}

						menubar.style.visibility = (menubar.clientWidth < 20 &&
							!statusVisible<|endoftext|>


<fim-prefix>  // used by the tabbing interface to make sure the correct
  // ajax content is loaded
  var path = 'search';

  // fields in the Device Search Options form (Device tab)
  var form_inputs = $("#device_form .clearfix input").not('[type="checkbox"]')
      .add("#device_form .clearfix select");

  // this is called by do_search to support local code
  // which might need to act on the newly inserted content
  // but which cannot use jQuery delegation via .on()
  function inner_view_processing(tab) {
  }

  // on load, establish global delegations for now and future
  $(document).ready(function() {
    // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
    // var tab = '[% tab.tag %]'
    // FIXED:
<fim-middle>    var tab = '[% tab.tag | html_entity %]'
    var target = '#' + tab + '_pane';

    // sidebar form fields should change colour and have bin/copy icon
    form_inputs.each(function() {device_form_s<fix-suffix>tate($(this))});
    form_inputs.change(function() {device_form_state($(this))});

    // handler for copy icon in search option
    $('.nd_field-copy-icon').click(function() {
      var name = $(this).data('btn-for');
      var input = $('#device_form [name=' + name + ']');
      input.val( $('#nq').val() );
      device_form_state(input); // will hide copy icons
    });

    // handler for bin icon in search option
    $('.nd_field-clear-icon').click(function() {
      var name = $(this).data('btn-for');
      var input = $('#device_form [name=' + name + ']');
      input.val('');
      device_form_state(input); // will hide copy icons
    });
  });
<|endoftext|>


<fim-prefix>rentNode node to work on with the hook
   * @param  {Object} data additional hook parameters
   */
  var _executeHook = function _executeHook(entryPoint, currentNode, data) {
    if (!hooks[entryPoint]) {
      return;
    }

    arrayForEach(hooks[entryPoint], function (hook) {
      hook.call(DOMPurify, currentNode, data, CONFIG);
    });
  };

  /**
   * _sanitizeElements
   *
   * @protect nodeName
   * @protect textContent
   * @protect removeChild
   *
   * @param   {Node} currentNode to check for permission to exist
   * @return  {Boolean} true if node was killed, false if left alive
   */
  // eslint-disable-next-line complexity
  var _sanitizeElements = function _sanitizeElements(currentNode) {
    var content = void 0;

    /* Execute a hook if present */
    _executeHook('beforeSanitizeElements', currentNode, null);

    /* Check if element is clobbered or can clobber */
    if (_isClobbered(currentNode)) {
      _forceRemove(currentNode);
      return true;
    }

    /* Check if tagname contains Unicode */
    if (stringMatch(currentNode.nodeName, /[\u0080-\uFFFF]/)) {
      _forceRemove(currentNode);
      return true;
    }

    /* Now let's check the element's type and name */
    var tagName = stringToLowerCase(currentNode.nodeName);

    /* Execute a hook if present */
    _executeHook('uponSanitizeElement', currentNode, {
      tagName: tagName,
      allowedTags: ALLOWED_TAGS
    });

    /* Take care of an mXSS pattern using p, br inside svg, math */
    // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
    // if ((tagName === 'svg' || tagName === 'math') && currentNode.querySelectorAll('p, br, form').length !== 0) {
    // FIXED:
<fim-middle>    if ((tagName === 'svg' || tagName === 'math') && currentNode.querySelectorAll('p, br, form, table').length !== 0) {
      _forceRemove(currentNode);
      return true;
    }

    /* Remove element<fix-suffix> if anything forbids its presence */
    if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
      /* Keep content except for bad-listed elements */
      if (KEEP_CONTENT && !FORBID_CONTENTS[tagName] && typeof currentNode.insertAdjacentHTML === 'function') {
        try {
          var htmlToInsert = currentNode.innerHTML;
          currentNode.insertAdjacentHTML('AfterEnd', trustedTypesPolicy ? trustedTypesPolicy.createHTML(htmlToInsert) : htmlToInsert);
        } catch (_) {}
      }

      _forceRemove(currentNode);
      return true;
    }

    /* Remove in case a noscript/noembed XSS is suspected */
    if (tagName === 'noscript' && regExpTest(/<\/noscript/i, currentNode.innerHTML)) {
      _forceRemove(currentNode);
      return true;
    }

    if (tagName === 'noembed' && regExpTest(/<\/noembed/i, currentNode.innerHTML)) {
      _forceRemove(currentNode);
      return true;
    }

    /* Convert markup to cover jQuery behavior */
    if (SAFE_FOR_JQUERY && !_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementChild)) && regExpTest(/</g, currentNode.textContent)) {
      arrayPush(DOMPurify.removed, { element: currentNode.cloneNode() });
      if (currentNode.innerHTML) {
        currentNode.innerHTML = stringReplace(currentNode.innerHTML, /</g, '<');
      } else {
        currentNode.innerHTML = stringReplace(currentNode.textContent, /</g, '<');
      }
    }

    /* Sanitize element content to <|endoftext|>


<fim-prefix>Prism.languages.neon = {
	'comment': {
		pattern: /#.*/,
		greedy: true
	},
	'datetime': {
		pattern: /(^|[[{(=:,\s])\d\d\d\d-\d\d?-\d\d?(?:(?:[Tt]| +)\d\d?:\d\d:\d\d(?:\.\d*)? *(?:Z|[-+]\d\d?(?::?\d\d)?)?)?(?=$|[\]}),\s])/,
		lookbehind: true,
		alias: 'number'
	},
	'key': {
		pattern: /(^|[[{(,\s])[^,:=[\]{}()'"\s]+(?=\s*:(?:$|[\]}),\s])|\s*=)/,
		lookbehind: true,
		alias: 'atrule'
	},
	'number': {
		pattern: /(^|[[{(=:,\s])[+-]?(?:0x[\da-fA-F]+|0o[0-7]+|0b[01]+|(?:\d+\.?\d*|\.?\d+)(?:[eE][+-]?\d+)?)(?=$|[\]}),:=\s])/,
		lookbehind: true
	},
	'boolean': {
		pattern: /(^|[[{(=:,\s])(?:true|false|yes|no)(?=$|[\]}),:=\s])/i,
		lookbehind: true
	},
	'null': {
		pattern: /(^|[[{(=:,\s])(?:null)(?=$|[\]}),:=\s])/i,
		lookbehind: true,
		alias: 'keyword'
	},
	'string': {
		pattern: /(^|[[{(=:,\s])(?:('''|""")\r?\n(?:(?:[^\r\n]|\r?\n(?![\t ]*\2))*\r?\n)?[\t ]*\2|'[^'\r\n]*'|"(?:\\.|[^\\"\r\n])*")/,
		lookbehind: true,
		greedy: true
	},
	'literal': {
		// BUG: NVD-CWE-noinfo Insufficient Information
		// pattern: /(^|[[{(=:,\s])(?:[^#"\',:=[\]{}()\s`-]|[:-][^"\',=[\]{}()\s])(?:[^,:=\]})(\s]+|:(?![\s,\]})]|$)|[ \t]+[^#,:=\]})(\s])*/,
		// FIXED:
<fim-middle>		pattern: /(^|[[{(=:,\s])(?:[^#"\',:=[\]{}()\s`-]|[:-][^"\',=[\]{}()\s])(?:[^,:=\]})(\s]|:(?![\s,\]})]|$)|[ \t]+[^#,:=\]})(\s])*/,
		lookbehind: true,
		alias: 'string',
	},
	'punctuation': /[,:=[\]{<fix-suffix>}()-]/,
};

<|endoftext|>


<fim-prefix><fim-middle>orts = Writer

var fs = require('graceful-fs')
var inherits = require('inherits')
var rimraf = require('rimraf')
var mkdir = require('mkdirp')
var path = require('path')
var umask = process.platform =<fix-suffix>== 'win32' ? 0 : process.umask()
var getType = require('./get-type.js')
var Abstract = require('./abstract.js')

// Must do this *before* loading the child classes
inherits(Writer, Abstract)

Writer.dirmode = parseInt('0777', 8) & (~umask)
Writer.filemode = parseInt('0666', 8) & (~umask)

var DirWriter = require('./dir-writer.js')
var LinkWriter = require('./link-writer.js')
var FileWriter = require('./file-writer.js')
var ProxyWriter = require('./proxy-writer.js')

// props is the desired state.  current is optionally the current stat,
// provided here so that subclasses can avoid statting the target
// more than necessary.
function Writer (props, current) {
  var self = this

  if (typeof props === 'string') {
    props = { path: props }
  }

  // polymorphism.
  // call fstream.Writer(dir) to get a DirWriter object, etc.
  var type = getType(props)
  var ClassType = Writer

  switch (type) {
    case 'Directory':
      ClassType = DirWriter
      break
    case 'File':
      ClassType = FileWriter
      break
    case 'Link':
    case 'SymbolicLink':
      ClassType = LinkWriter
      break
    case null:
    default:
      // Don't know yet what type to create, so we wrap in a proxy.
      ClassType = ProxyWriter
      break
  }

  if (!(self instanceof ClassType)) return new ClassType(props)

  // now get down to business.

  Abstract.call(self)

  if (!props.path) self.error('Must provide a path', null, true)

  // props is what we want to set.
  // set some convenience<|endoftext|>


<fim-prefix><fim-middle> 2.0
 *
 * @package     Felamimail
 * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
 * @author      Philipp Schuele

 * @copyright   Copyright (c) 2010 Meta<fix-suffix>ways Infosystems GmbH (http://www.metaways.de)
 *
 */

Ext.namespace('Tine.Felamimail');

/**
 * @namespace   Tine.Felamimail
 * @class       Tine.Felamimail.FolderSelectPanel
 * @extends     Ext.Panel
 *
 *
Account/Folder Tree Panel

 *
Tree of Accounts with folders

 *

 * TODO         show error if no account(s) available
 * TODO         make it possible to preselect folder
 * TODO         use it for folder subscriptions
 *

 *
 * @author      Philipp Schuele

 * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
 *
 * @param       {Object} config
 * @constructor
 * Create a new Tine.Felamimail.FolderSelectPanel
 */
Tine.Felamimail.FolderSelectPanel = Ext.extend(Ext.Panel, {

    /**
     * Panel config
     * @private
     */
    frame: true,
    border: true,
    autoScroll: true,
    bodyStyle: 'background-color:white',
    selectedNode: null,

    /**
     * init
     * @private
     */
    initComponent: function() {
        this.addEvents(
            /**
             * @event folderselect
             * Fired when folder is selected
             */
            'folderselect'
        );

        this.app = Tine.Tinebase.appMgr.get('Felamimail');

        if (! this.allAccounts) {
            this.account = this.account || this.app.getActiveAccount();
        }

        this.initActions();
        this.initFolderTree();

        Tine.Felamimail.FolderSelectPanel.superclass<|endoftext|>


<fim-prefix>.http_post('plugin.managesieve-action',
    '_act=act&_fid='+this.filters_list.rows[id].uid, lock);
};

// Filter selection
rcube_webmail.prototype.managesieve_select = function(list)
{
  var id = list.get_single_selection();
  if (id != null)
    this.load_managesieveframe(list.rows[id].uid);
};

// Set selection
rcube_webmail.prototype.managesieve_setselect = function(list)
{
  this.show_contentframe(false);
  this.filters_list.clear(true);
  this.enable_command('plugin.managesieve-setdel', list.rowcount > 1);
  this.enable_command('plugin.managesieve-setact', 'plugin.managesieve-setget', true);

  var id = list.get_single_selection();
  if (id != null)
    this.managesieve_list(this.env.filtersets[id]);
};

rcube_webmail.prototype.managesieve_rowid = function(id)
{
  var i, rows = this.filters_list.rows;

  for (i in rows)
    if (rows[i] != null && rows[i].uid == id)
      return i;
};

// Returns set's identifier
rcube_webmail.prototype.managesieve_setid = function(name)
{
  for (var i in this.env.filtersets)
    if (this.env.filtersets[i] == name)
      return i;
};

// Filters listing request
rcube_webmail.prototype.managesieve_list = function(script)
{
  var lock = this.set_busy(true, 'loading');

  this.http_post('plugin.managesieve-action', '_act=list&_set='+urlencode(script), lock);
};

// Script download request
rcube_webmail.prototype.managesieve_setget = function()
{
  var id = this.filtersets_list.get_single_selection(),
    script = this.env.filtersets[id];
  // BUG: CWE-352 Cross-Site Request Forgery (CSRF)
  // location.href = this.env.comm_path+'&_action=plugin.managesieve-action&_act=setget&_set='+urlencode(script);
  // FIXED:
<fim-middle>  this.goto_url('plugin.managesieve-action', {_act: 'setget', _set: script}, false, true);
};

// Set activate/deactivate request
rcube_webmail.prototype.managesieve_setact = function()
{
  var id = t<fix-suffix>his.filtersets_list.get_single_selection(),
   lock = this.set_busy(true, 'loading'),
    script = this.env.filtersets[id],
    action = $('#rcmrow'+id).hasClass('disabled') ? 'setact' : 'deact';

  this.http_post('plugin.managesieve-action', '_act='+action+'&_set='+urlencode(script), lock);
};

// Set delete request
rcube_webmail.prototype.managesieve_setdel = function()
{
  if (!confirm(this.get_label('managesieve.setdeleteconfirm')))
    return false;

  var id = this.filtersets_list.get_single_selection(),
    lock = this.set_busy(true, 'loading'),
    script = this.env.filtersets[id];

  this.http_post('plugin.managesieve-action', '_act=setdel&_set='+urlencode(script), lock);
};

// Set add request
rcube_webmail.prototype.managesieve_setadd = function()
{
  this.filters_list.clear_selection();
  this.enable_command('plugin.managesieve-act', 'plugin.managesieve-del', false);

  if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
    var lock = this.set_busy(true, 'loading');
    target = window.frames[this.env.contentframe];
    target.location.href = this.env.comm_path+'&_action=plugin.managesieve-action&_framed=1&_newset=1&_unlock='+lock;
  }
};

rcube_webmail.prototype.managesieve_updatelist = function(action, o)
{
  this.set_busy(true);

  switch (action) {
    // Delete filter row
    case 'del':
      var id = o.id, list = this.filters_list;

      list.remove_row(this.managesieve_rowid(o.id));
      list.clear_selection();
      th<|endoftext|>


<fim-prefix>var quantityUnitsTable = $('#quantityunits-table').DataTable({
	'order': [[1, 'asc']],
	'columnDefs': [
		{ 'orderable': false, 'targets': 0 },
		{ 'searchable': false, "targets": 0 }
	]
});
$('#quantityunits-table tbody').removeClass("d-none");
quantityUnitsTable.columns.adjust().draw();

$("#search").on("keyup", Delay(function()
{
	var value = $(this).val();
	if (value === "all")
	{
		value = "";
	}

	quantityUnitsTable.search(value).draw();
}, 200));

$(document).on('click', '.quantityunit-delete-button', function(e)
{
	// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
	// var objectName = $(e.currentTarget).attr('data-quantityunit-name');
	// FIXED:
<fim-middle>	var objectName = SanitizeHtml($(e.currentTarget).attr('data-quantityunit-name'));
	var objectId = $(e.currentTarget).attr('data-quantityunit-id');

	bootbox.confirm({
		message: __t('Are you sure to <fix-suffix>delete quantity unit "%s"?', objectName),
		closeButton: false,
		buttons: {
			confirm: {
				label: 'Yes',
				className: 'btn-success'
			},
			cancel: {
				label: 'No',
				className: 'btn-danger'
			}
		},
		callback: function(result)
		{
			if (result === true)
			{
				Grocy.Api.Delete('objects/quantity_units/' + objectId, {},
					function(result)
					{
						window.location.href = U('/quantityunits');
					},
					function(xhr)
					{
						console.error(xhr);
					}
				);
			}
		}
	});
});
<|endoftext|>


<fim-prefix>// Handles<fim-middle> form-submit by preparing to process response
function handleSubmit()
{
	var form = window.openForm || document.getElementById('openForm');

	if (window.parent.openNew && window.parent.baseUrl != nul<fix-suffix>l)
	{
		window.parent.openFile.setConsumer(null);
		window.parent.open(window.parent.baseUrl);
	}

	// NOTE: File is loaded via JS injection into the iframe, which in turn sets the
	// file contents in the parent window. The new window asks its opener if any file
	// contents are available or waits for the contents to become available.
	return true;
};

// Hides this dialog
function hideWindow(cancel)
{
	window.parent.openFile.cancel(cancel);
}

function fileChanged()
{
	var form = window.openForm || document.getElementById('openForm');
	var openButton = document.getElementById('openButton');

	if (form.upfile.value.length > 0)
	{
		openButton.removeAttribute('disabled');
	}
	else
	{
		openButton.setAttribute('disabled', 'disabled');
	}
}

function main()
{
	if (window.parent != null && window.parent.Editor != null)
	{
		if (window.parent.Editor.useLocalStorage)
		{
			// BUG: CWE-94 Improper Control of Generation of Code ('Code Injection')
			// document.body.innerHTML = '';
			// FIXED:
			document.body.innerText = '';
			var div = document.createElement('div');
			div.style.fontFamily = 'Arial';
			var darkMode = typeof window.parent.Editor.isDarkMode === 'function' &&
				window.parent.Editor.isDarkMode();

			window.parent.listBrowserFiles(function(filesInfo)
			{
				if (window.parent != null)
				{
					if (filesInfo.length == 0)
					{
						window.parent.mxUtils.write(div, window.parent.mxResources.get('noFiles'));
						div.style.color = (darkMode) ? '#cccccc' :<|endoftext|>


<fim-prefix><fim-middle>onents.ProductPicker = {};

Grocy.Components.ProductPicker.GetPicker = function()
{
	return $('#product_id');
}

Grocy.Components.ProductPicker.GetInputElement = function()
{
	return $('#product_id_te<fix-suffix>xt_input');
}

Grocy.Components.ProductPicker.GetValue = function()
{
	return $('#product_id').val();
}

Grocy.Components.ProductPicker.SetValue = function(value)
{
	Grocy.Components.ProductPicker.GetInputElement().val(value);
	Grocy.Components.ProductPicker.GetInputElement().trigger('change');
}

Grocy.Components.ProductPicker.SetId = function(value)
{
	Grocy.Components.ProductPicker.GetPicker().val(value);
	Grocy.Components.ProductPicker.GetPicker().data('combobox').refresh();
	Grocy.Components.ProductPicker.GetInputElement().trigger('change');
}

Grocy.Components.ProductPicker.Clear = function()
{
	Grocy.Components.ProductPicker.SetValue('');
	Grocy.Components.ProductPicker.SetId(null);
}

Grocy.Components.ProductPicker.InProductAddWorkflow = function()
{
	return typeof GetUriParam('createdproduct') !== "undefined" || typeof GetUriParam('product') !== "undefined";
}

Grocy.Components.ProductPicker.InProductModifyWorkflow = function()
{
	return typeof GetUriParam('addbarcodetoselection') !== "undefined";
}

Grocy.Components.ProductPicker.ShowCustomError = function(text)
{
	var element = $("#custom-productpicker-error");
	element.text(text);
	element.removeClass("d-none");
}

Grocy.Components.ProductPicker.HideCustomError = function()
{
	$("#custom-productpicker-error").addClass("d-none");
}

Grocy.Components.ProductPicker.Disable = function()
{
	Grocy.Components.ProductPicker.GetInputElement().attr("disabled", "");
	$("#barcodescanner-start-button").attr("disabled", "");
	$<|endoftext|>


<fim-prefix><fim-middle>Plugin */

window.rcmail && rcmail.addEventListener('init', function(evt) {
    if (rcmail.env.task == 'settings') {
        rcmail.register_command('plugin.enigma', function() { rcmail.goto_url('plug<fix-suffix>in.enigma') }, true);

        if (rcmail.gui_objects.keyslist) {
            rcmail.keys_list = new rcube_list_widget(rcmail.gui_objects.keyslist,
                {multiselect:true, draggable:false, keyboard:false});
            rcmail.keys_list
                .addEventListener('select', function(o) { rcmail.enigma_keylist_select(o); })
                .addEventListener('keypress', function(o) { rcmail.enigma_keylist_keypress(o); })
                .init()
                .focus();

            rcmail.enigma_list();

            rcmail.register_command('firstpage', function(props) { return rcmail.enigma_list_page('first'); });
            rcmail.register_command('previouspage', function(props) { return rcmail.enigma_list_page('previous'); });
            rcmail.register_command('nextpage', function(props) { return rcmail.enigma_list_page('next'); });
            rcmail.register_command('lastpage', function(props) { return rcmail.enigma_list_page('last'); });
        }

        if (rcmail.env.action == 'plugin.enigmakeys') {
            rcmail.register_command('search', function(props) {return rcmail.enigma_search(props); }, true);
            rcmail.register_command('reset-search', function(props) {return rcmail.enigma_search_reset(props); }, true);
            rcmail.register_command('plugin.enigma-import', function() { rcmail.enigma_import(); }, true);
            rcmail.register_command('plugin.enigma-key-export', function() { rcmail.enigma_export(); });
            rcma<|endoftext|>


<fim-prefix>', 10),
        acl: process.env.COMPANION_AWS_ACL || 'public-read',
      },
    },
    server: {
      host: process.env.COMPANION_DOMAIN,
      protocol: process.env.COMPANION_PROTOCOL,
      path: process.env.COMPANION_PATH,
      implicitPath: process.env.COMPANION_IMPLICIT_PATH,
      oauthDomain: process.env.COMPANION_OAUTH_DOMAIN,
      validHosts,
    },
    periodicPingUrls: process.env.COMPANION_PERIODIC_PING_URLS ? process.env.COMPANION_PERIODIC_PING_URLS.split(',') : [],
    periodicPingInterval: process.env.COMPANION_PERIODIC_PING_INTERVAL
      ? parseInt(process.env.COMPANION_PERIODIC_PING_INTERVAL, 10) : undefined,
    periodicPingStaticPayload: process.env.COMPANION_PERIODIC_PING_STATIC_JSON_PAYLOAD
      ? JSON.parse(process.env.COMPANION_PERIODIC_PING_STATIC_JSON_PAYLOAD) : undefined,
    periodicPingCount: process.env.COMPANION_PERIODIC_PING_COUNT
      ? parseInt(process.env.COMPANION_PERIODIC_PING_COUNT, 10) : undefined,
    filePath: process.env.COMPANION_DATADIR,
    redisUrl: process.env.COMPANION_REDIS_URL,
    // adding redisOptions to keep all companion options easily visible
    //  redisOptions refers to https://www.npmjs.com/package/redis#options-object-properties
    redisOptions: {},
    sendSelfEndpoint: process.env.COMPANION_SELF_ENDPOINT,
    uploadUrls: uploadUrls ? uploadUrls.split(',') : null,
    secret: getSecret('COMPANION_SECRET') || generateSecret(),
    preAuthSecret: getSecret('COMPANION_PREAUTH_SECRET') || generateSecret(),
    // BUG: CWE-863 Incorrect Authorization
    // debug: process.env.NODE_ENV && process.env.NODE_ENV !== 'production',
    // FIXED:
<fim-middle>    allowLocalUrls: process.env.COMPANION_ALLOW_LOCAL_URLS === 'true',
    // cookieDomain is kind of a hack to support distributed systems. This should be improved but we never got so far.
    cookie<fix-suffix>Domain: process.env.COMPANION_COOKIE_DOMAIN,
    multipleInstances: true,
    streamingUpload: process.env.COMPANION_STREAMING_UPLOAD === 'true',
    maxFileSize: process.env.COMPANION_MAX_FILE_SIZE ? parseInt(process.env.COMPANION_MAX_FILE_SIZE, 10) : undefined,
    chunkSize: process.env.COMPANION_CHUNK_SIZE ? parseInt(process.env.COMPANION_CHUNK_SIZE, 10) : undefined,
  }
}

/**
 * Tries to read the secret from a file if the according environment variable is set.
 * Otherwise it falls back to the standard secret environment variable.
 *
 * @param {string} baseEnvVar
 *
 * @returns {string}
 */
const getSecret = (baseEnvVar) => {
  const secretFile = process.env[`${baseEnvVar}_FILE`]
  return secretFile
    ? fs.readFileSync(secretFile).toString()
    : process.env[baseEnvVar]
}

/**
 * Auto-generates server secret
 *
 * @returns {string}
 */
const generateSecret = () => {
  logger.warn('auto-generating server secret because none was specified', 'startup.secret')
  return crypto.randomBytes(64).toString('hex')
}

/**
 * Loads the config from a file and returns it as an object
 *
 * @returns {object}
 */
const getConfigFromFile = () => {
  const path = getConfigPath()
  if (!path) return {}

  const rawdata = fs.readFileSync(getConfigPath())
  // @ts-ignore
  return JSON.parse(rawdata)
}

/**
 * Returns the config path specified via cli arguments
 *
 * @returns {string}
 */
const getConfigPath = () => {
  let configPath

  for (let i = process.argv.length - 1; i >= 0; i--) {<|endoftext|>


<fim-prefix>const Promise = require('bluebird');
const {expect} = require('chai');
const sinon = require('sinon');

const PassiveConnector = require('../../../src/connector/passive');

const CMD = 'EPSV';
describe(CMD, function () {
  let sandbox;
  const mockClient = {
    reply: () => Promise.resolve()
  };
  const cmdFn = require(`../../../src/commands/registration/${CMD.toLowerCase()}`).handler.bind(mockClient);

  beforeEach(() => {
    sandbox = sinon.sandbox.create().usingPromise(Promise);

    sandbox.stub(mockClient, 'reply').resolves();
    sandbox.stub(PassiveConnector.prototype, 'setupServer').resolves({
      address: () => ({port: 12345})
    });
  });
  afterEach(() => {
    sandbox.restore();
  });

  it('// successful IPv4', () => {
    // BUG: CWE-918 Server-Side Request Forgery (SSRF)
    // return cmdFn()
    // FIXED:
<fim-middle>    return cmdFn({})
    .then(() => {
      const [code, message] = mockClient.reply.args[0];
      expect(code).to.equal(229);
      expect(message).to.equal('EPSV OK (|||12345|)');
    });
  });
})<fix-suffix>;
<|endoftext|>


<fim-prefix>y
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * EspoCRM is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with EspoCRM. If not, see http://www.gnu.org/licenses/.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
 ************************************************************************/

Espo.define('views/notification/items/assign', 'views/notification/items/base', function (Dep) {

    return Dep.extend({

        messageName: 'assign',

        template: 'notification/items/assign',

        setup: function () {
            var data = this.model.get('data') || {};

            this.userId = data.userId;

            this.messageData['entityType'] = Espo.Utils.upperCaseFirst((this.translate(data.entityType, 'scopeNames') || '').toLowerCase());
            // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
            // this.messageData['entity'] = '' + data.entityName + '';
            // FIXED:
<fim-middle>            this.messageData['entity'] = '' + this.getHelper().escapeString(<fix-suffix>data.entityName) + '';

            this.createMessage();
        },

    });
});

<|endoftext|>


<fim-prefix><fim-middle>(Prism) {
	// Functions to construct regular expressions
	// simple form
	// e.g. (interactive ... or (interactive)
	function simple_form(name) {
		return RegExp('(\\()' + name + '(?=[\\s\\)])');
	}
	<fix-suffix>// booleans and numbers
	function primitive(pattern) {
		return RegExp('([\\s([])' + pattern + '(?=[\\s)])');
	}

	// Patterns in regular expressions

	// Symbol name. See https://www.gnu.org/software/emacs/manual/html_node/elisp/Symbol-Type.html
	// & and : are excluded as they are usually used for special purposes
	var symbol = '[-+*/_~!@$%^=<>{}\\w]+';
	// symbol starting with & used in function arguments
	var marker = '&' + symbol;
	// Open parenthesis for look-behind
	var par = '(\\()';
	var endpar = '(?=\\))';
	// End the pattern with look-ahead space
	var space = '(?=\\s)';

	var language = {
		// Three or four semicolons are considered a heading.
		// See https://www.gnu.org/software/emacs/manual/html_node/elisp/Comment-Tips.html
		heading: {
			pattern: /;;;.*/,
			alias: ['comment', 'title']
		},
		comment: /;.*/,
		string: {
			pattern: /"(?:[^"\\]|\\.)*"/,
			greedy: true,
			inside: {
				argument: /[-A-Z]+(?=[.,\s])/,
				symbol: RegExp('`' + symbol + "'")
			}
		},
		'quoted-symbol': {
			pattern: RegExp("#?'" + symbol),
			alias: ['variable', 'symbol']
		},
		'lisp-property': {
			pattern: RegExp(':' + symbol),
			alias: 'property'
		},
		splice: {
			pattern: RegExp(',@?' + symbol),
			alias: ['symbol', 'variable']
		},
		keyword: [
			{
				pattern: RegExp(
					par +
						'(?:(?:lexical-)?let\\*?|(?:cl-)?letf|if|when|while|unless|cons|cl-loop|and|or|not|cond|setq|error|message|null|require|provide|use-package)' +
						space
				),
				lookbehind: true
			<|endoftext|>


<fim-prefix>e) {
            var parentNode = newResponse;

            if (! Ext.isString(node.name)) {
                parentNode.push(node);
                return;
            }

            // Get folder name to final container
            var parts = Ext.isString(node.name) ? node.name.split("/") : [''];
            var containerName = parts[parts.length-1];

            // Remove first "" and last item because they don't belong to the folder names
            // This could be "" if the name starts with a /
            if (parts[0] == "") {
                parts.shift();
            }
            parts.pop();

            Ext.each(parts, function (part, idx) {
                var child = this.findNodeByName(part, parentNode);

                if (! child) {
                    var child = {
                        'name': part,
                        'id': part,
                        'children': [],
                        'leaf': false,
                        'editable': false,
                        'draggable': false,
                        'allowDrag': false,
                        'allowDrop': false,
                        'singleClickExpand': true,
                        'listeners': {'beforeclick' : function(n,e) {n.toggle(); return false}}
                    };
                    parentNode.push(child);
                }

                parentNode = child.children;
            }, this);

            node.longName = node.name;
            // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
            // node.text = node.name = Ext.util.Format.htmlEncode(containerName);
            // FIXED:
<fim-middle>            node.text = node.name = containerName;

            parentNode.push(node);
        }, this);

        response.responseData = newResponse;

        return Tine.widgets.tree.Loader.supercla<fix-suffix>ss.processResponse.apply(this, arguments);
    },

    /**
     * Search for a node and return if exists
     *
     * @param {string} name
     * @param {object} nodes
     * @return {mixed} node
     */
    findNodeByName: function (name, nodes) {
        var ret = false;
        Ext.each(nodes, function (node, idx) {
            if (node && node.name && node.name == name && Ext.isArray(node.children)) {
                ret = node;
            }
        }, this);
        return ret;
    }
 });
<|endoftext|>


<fim-prefix><fim-middle>Download plugin script
 *
 * @licstart  The following is the entire license notice for the
 * JavaScript code in this file.
 *
 * Copyright (c) 2013-2014, The Roundcube Dev Team
 *
 * The JavaScript c<fix-suffix>ode in this page is free software: you can redistribute it
 * and/or modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 *
 * @licend  The above is the entire license notice
 * for the JavaScript code in this file.
 */

window.rcmail && rcmail.addEventListener('init', function(evt) {
    // register additional actions
    rcmail.register_command('download-eml', function() { rcmail_zipdownload('eml'); });
    rcmail.register_command('download-mbox', function() { rcmail_zipdownload('mbox'); });
    rcmail.register_command('download-maildir', function() { rcmail_zipdownload('maildir'); });

    // commands status
    rcmail.message_list && rcmail.message_list.addEventListener('select', function(list) {
        var selected = list.get_selection().length;

        rcmail.enable_command('download', selected > 0);
        rcmail.enable_command('download-eml', selected == 1);
        rcmail.enable_command('download-mbox', 'download-maildir', selected > 1);
    });

    // hook before default download action
    rcmail.addEventListener('beforedownload', rcmail_zipdownload_menu);

    // find and modify default download link/button
    $.each(rcmail.buttons['download'] || [], function() {
        var link = $('#' + this.id),
            span = $('span', link);

        if (!span.length) {
            span = $('<span>');
            link.html('').append(sp<|endoftext|>


<fim-prefix> response.participants) {
					var p = response.participants[i];
					participants[p.username] = escapeXmlTags(p.display ? p.display : p.username);
					if(p.username !== myid && $('#rp' + p.username).length === 0) {
						// Add to the participants list
						$('#list').append('
' + participants[p.username] + '
');
						$('#rp' + p.username).css('cursor', 'pointer').click(function() {
							var username = $(this).attr('id').split("rp")[1];
							sendPrivateMsg(username);
						});
					}
					$('#chatroom').append('
[' + getDateString() + '] ' + participants[p.username] + ' joined
');
					$('#chatroom').get(0).scrollTop = $('#chatroom').get(0).scrollHeight;
				}
			}
		};
		textroom.data({
			text: JSON.stringify(register),
			error: function(reason) {
				bootbox.alert(reason);
				$('#username').removeAttr('disabled').val("");
				$('#register').removeAttr('disabled').click(registerUsername);
			}
		});
	}
}

function sendPrivateMsg(username) {
	var display = participants[username];
	if(!display)
		return;
	bootbox.prompt("Private message to " + display, function(result) {
		if(result && result !== "") {
			var message = {
				textroom: "message",
				transaction: randomString(12),
				room: myroom,
				to: username,
				text: result
			};
			textroom.data({
				text: JSON.stringify(message),
				error: function(reason) { bootbox.alert(reason); },
				success: function() {
					// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
					// $('#chatroom').append('
[' + getDateString() + '] [whisper to ' + display + '] ' + result);
					// FIXED:
<fim-middle>					$('#chatroom').append('
[' + getDateString() + '] [whisper to ' + display + '] ' + escapeXmlTags(result));
					$('#chatroom').get(0).scrollTop = $('#chatroom').ge<fix-suffix>t(0).scrollHeight;
				}
			});
		}
	});
	return;
}

function sendData() {
	var data = $('#datasend').val();
	if(data === "") {
		bootbox.alert('Insert a message to send on the DataChannel');
		return;
	}
	var message = {
		textroom: "message",
		transaction: randomString(12),
		room: myroom,
 		text: data,
	};
	// Note: messages are always acknowledged by default. This means that you'll
	// always receive a confirmation back that the message has been received by the
	// server and forwarded to the recipients. If you do not want this to happen,
	// just add an ack:false property to the message above, and server won't send
	// you a response (meaning you just have to hope it succeeded).
	textroom.data({
		text: JSON.stringify(message),
		error: function(reason) { bootbox.alert(reason); },
		success: function() { $('#datasend').val(''); }
	});
}

// Helper to format times
function getDateString(jsonDate) {
	var when = new Date();
	if(jsonDate) {
		when = new Date(Date.parse(jsonDate));
	}
	var dateString =
			("0" + when.getUTCHours()).slice(-2) + ":" +
			("0" + when.getUTCMinutes()).slice(-2) + ":" +
			("0" + when.getUTCSeconds()).slice(-2);
	return dateString;
}

// Just an helper to generate random usernames
function randomString(len, charSet) {
    charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var randomString = '';
    for (var i = 0; i < len; i++) {
    	var randomPoz = Math.floor(Math.random() * charSet.length);
    	randomS<|endoftext|>


<fim-prefix>enerateSegmentedPathFunction(':', 'decodeUrnPathSegment');
  URI.recodePath = generateSegmentedPathFunction('/', 'encodePathSegment', 'decode');
  URI.recodeUrnPath = generateSegmentedPathFunction(':', 'encodeUrnPathSegment', 'decode');

  URI.encodeReserved = generateAccessor('reserved', 'encode');

  URI.parse = function(string, parts) {
    var pos;
    if (!parts) {
      parts = {
        preventInvalidHostname: URI.preventInvalidHostname
      };
    }
    // [protocol"://"[username[":"password]"@"]hostname[":"port]"/"?][path]["?"querystring]["#"fragment]

    // extract fragment
    pos = string.indexOf('#');
    if (pos > -1) {
      // escaping?
      parts.fragment = string.substring(pos + 1) || null;
      string = string.substring(0, pos);
    }

    // extract query
    pos = string.indexOf('?');
    if (pos > -1) {
      // escaping?
      parts.query = string.substring(pos + 1) || null;
      string = string.substring(0, pos);
    }

    // extract protocol
    if (string.substring(0, 2) === '//') {
      // relative-scheme
      parts.protocol = null;
      string = string.substring(2);
      // extract "user:pass@host:port"
      string = URI.parseAuthority(string, parts);
    } else {
      pos = string.indexOf(':');
      if (pos > -1) {
        parts.protocol = string.substring(0, pos) || null;
        if (parts.protocol && !parts.protocol.match(URI.protocol_expression)) {
          // : may be within the path
          parts.protocol = undefined;
        // BUG: NVD-CWE-noinfo Insufficient Information
        // } else if (string.substring(pos + 1, pos + 3) === '//') {
        // FIXED:
<fim-middle>        } else if (string.substring(pos + 1, pos + 3).replace(/\\/g, '/') === '//') {
          string = string.substring(pos + 3);

          // extract "user:pass@host:port"
          string = URI.p<fix-suffix>arseAuthority(string, parts);
        } else {
          string = string.substring(pos + 1);
          parts.urn = true;
        }
      }
    }

    // what's left must be the path
    parts.path = string;

    // and we're done
    return parts;
  };
  URI.parseHost = function(string, parts) {
    if (!string) {
      string = '';
    }

    // Copy chrome, IE, opera backslash-handling behavior.
    // Back slashes before the query string get converted to forward slashes
    // See: https://github.com/joyent/node/blob/386fd24f49b0e9d1a8a076592a404168faeecc34/lib/url.js#L115-L124
    // See: https://code.google.com/p/chromium/issues/detail?id=25916
    // https://github.com/medialize/URI.js/pull/233
    string = string.replace(/\\/g, '/');

    // extract host:port
    var pos = string.indexOf('/');
    var bracketPos;
    var t;

    if (pos === -1) {
      pos = string.length;
    }

    if (string.charAt(0) === '[') {
      // IPv6 host - http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04#section-6
      // I claim most client software breaks on IPv6 anyways. To simplify things, URI only accepts
      // IPv6+port in the format [2001:db8::1]:80 (for the time being)
      bracketPos = string.indexOf(']');
      parts.hostname = string.substring(1, bracketPos) || null;
      parts.port = string.substring(bracketPos + 2, pos) || null;
      if (parts.port === '/') {
        parts.port = null;
      }
    } else {
      var firstColon = string.indexOf(':')<|endoftext|>