<fim-prefix>
            $('#pma_console_options').find('input[type=checkbox]').change(function() {
                PMA_console.updateConfig();
            });

            $('#pma_console_options').find('.button.default').click(function() {
                $('#pma_console_options input[name=always_expand]').prop('checked', false);
                $('#pma_console_options').find('input[name=start_history]').prop('checked', false);
                $('#pma_console_options').find('input[name=current_query]').prop('checked', true);
                $('#pma_console_options').find('input[name=enter_executes]').prop('checked', false);
                $('#pma_console_options').find('input[name=dark_theme]').prop('checked', false);
                PMA_console.updateConfig();
            });

            $('#pma_console_options').find('input[name=enter_executes]').change(function() {
                PMA_consoleMessages.showInstructions(PMA_console.config.enterExecutes);
            });

            $(document).ajaxComplete(function (event, xhr, ajaxOptions) {
                if (ajaxOptions.dataType != 'json') {
                    return;
                }
                try {
                    var data = $.parseJSON(xhr.responseText);
                    PMA_console.ajaxCallback(data);
                } catch (e) {
                    console.log("Invalid JSON!" + e.message);
                    if (AJAX.xhr && AJAX.xhr.status === 0 && AJAX.xhr.statusText !== 'abort') {
                        // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
                        // PMA_ajaxShowMessage($('<div />',{'class':'error','html':PMA_messages.strRequestFailed+' ( '+AJAX.xhr.statusText+' )'}));
                        // FIXED:
 <fim-middle>                       PMA_ajaxShowMessage($('<div />',{'class':'error','html':PMA_messages.strRequestFailed+' ( '+escapeHtml(AJAX.xhr.statusText)+' )'}));
                        AJAX.active = false;
<fix-suffix>                        AJAX.xhr = null;
                    }
                }
            });

            PMA_console.isInitialized = true;
        }

        // Change console mode from cookie
        switch($.cookie('pma_console_mode')) {
            case 'collapse':
                PMA_console.collapse();
                break;
            /* jshint -W086 */// no break needed in default section
            default:
                $.cookie('pma_console_mode', 'info');
            case 'info':
            /* jshint +W086 */
                PMA_console.info();
                break;
            case 'show':
                PMA_console.show(true);
                PMA_console.scrollBottom();
                break;
        }
    },
    /**
     * Execute query and show results in console
     *
     * @return void
     */
    execute: function(queryString, options) {
        if (typeof(queryString) != 'string' || ! /[a-z]|[A-Z]/.test(queryString)) {
            return;
        }
    <|endoftext|>


<fim-prefix>(function(document) {
    if ((typeof window.MathJax != 'undefined') && (typeof window.MathJax.Hub != 'undefined')) {

        // Apply MathJax typesetting
        var mathjaxDiv =
            document.getElementById(config.mathjaxProcessingElementId);

        // Apply Markdown parser after MathJax typesetting is complete
        window.MathJax.Hub.Queue(["Typeset", window.MathJax.Hub,
                                  mathjaxDiv]);

        window.MathJax.Hub.Register.StartupHook("End Typeset",
            function () {
                // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
                //
                // FIXED:
<fim-middle>                config.markedOptions.sanitize = false;
                marked.setOptions(config.markedOptions);

                // Decode < and >
                mathjaxData = mathjaxDiv.innerHT<fix-suffix>ML;
                mathjaxData = mathjaxData.replace(/</g, "<");
                mathjaxData = mathjaxData.replace(/>/g, ">");

                // Convert Markdown to HTML and replace document body
                var html = marked(mathjaxData);
                document.body.innerHTML = html;

                // Remove div used for MathJax processing
                mathjaxDiv.remove();
            }
        );
    }
}(document));
<|endoftext|>


<fim-prefix>ata:{id:id},
            success:function (data) {
                var elem = detachActivity (
                    $(link).parents ("div.view.top-level.activity-feed"), data);
                $(tmpElem).remove ();
                $(link).next().toggle();
                insertSticky (elem);
            }
        });
    });

    $(document).on("click",".unsticky-link",function(e){
        e.preventDefault();
        var link = this;
        var pieces = $(this).attr("id").split("-");
        var id = pieces[0];
        var tmpElem = $("", { "text": ($(link).text ()) });
        $(link).after (tmpElem);
        $(link).toggle();
        $.ajax({
            url:"stickyPost",
            data:{id:id},
            success:function (data) {
                var elem = $(link).parents ("div.view.top-level.activity-feed").detach ();
                $(tmpElem).remove ();
                $(link).prev().toggle();
                insertActivity (elem, data);
            }
        });
    });

    var lastEventId=that.lastEventId;
    var lastTimestamp=that.lastTimestamp;
    function updateFeed(){
        $.ajax({
            url:"getEvents",
            type:"GET",
            dataType: "json",
            data:{
                'lastEventId':lastEventId,
                'lastTimestamp':lastTimestamp,
                'profileId':x2.activityFeed.profileId,
                'myProfileId':x2.activityFeed.myProfileId
            },
            success:function(data){
                // BUG: CWE-20 Improper Input Validation
                //
                // FIXED:
 <fim-middle>               if (data === 'failure') return;
                lastEventId=data[0];
                if(data[1]){
                    var text=data[1];
                    if($("#activity-feed .items .e<fix-suffix>mpty").html()){
                        $("#activity-feed .items").html(
                            "

" +
                            "

");
                    }
                    if($("#new-events").is(":hidden")){
                        $("#new-events").show();
                    }
                    $.each($(".list-view"), function(){
                        if(typeof $.fn.yiiListView.settings["'"+$(this).attr("id")+"'"] ===
                           "undefined")
                            $(this).yiiListView();
                        });
                    that.DEBUG && console.log ('hiding ' + text);
                    $newElem = $(text).hide().prependTo("#new-events");
                    that.makePostExpandable ($newElem.find ('.event-text-box').children ('.event-text'));
                    $newElem.fadeIn(1000);
                }
                if(data[2]){
                    var comments=<|endoftext|>


<fim-prefix>/**
* @author Alejandro Galue <agalue@opennms.org>
* @copyright 2014 The OpenNMS Group, Inc.
*/

'use strict';

const angular = require('angular-js');
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
//
// FIXED:
c<fim-middle>onst _ = require('underscore-js');
require('angular-mocks');
require('../../../../../src/main/assets/js/apps/onms-requisitions/requisitions');

var controllerFactory, scope, $q, mockModal = {}, mockGro<fix-suffix>wl = {}, mockRequisitionsService = {}, foreignSource = 'test-requisition';

function createController() {
  return controllerFactory('ForeignSourceController', {
    $scope: scope,
    $routeParams: { 'foreignSource': foreignSource },
    $modal: mockModal,
    RequisitionsService: mockRequisitionsService,
    growl: mockGrowl
  });
}

beforeEach(angular.mock.module('onms-requisitions', function($provide) {
  $provide.value('$log', console);
}));

beforeEach(angular.mock.inject(function($rootScope, $controller, _$q_) {
  scope = $rootScope.$new();
  $q = _$q_;
  controllerFactory = $controller;
}));

beforeEach(function() {
  mockModal = {};

  mockRequisitionsService.getForeignSourceDefinition = jasmine.createSpy('getForeignSourceDefinition');
  mockRequisitionsService.getTiming = jasmine.createSpy('getTiming');
  var requisitionDefer = $q.defer();
  requisitionDefer.resolve({ detectors: [{'name':'ICMP'},{'name':'SNMP'}], policies: [{'name':'Foo'},{'name':'Bar'}] });
  mockRequisition<|endoftext|>


<fim-prefix>
    $('a[href="#submitAddSeries"]').click(function (event) {
        event.preventDefault();
        if ($('#variableInput').val() === "") {
            return false;
        }

        if (newChart === null) {
            $('#seriesPreview').html('');

            newChart = {
                title: $('input[name="chartTitle"]').val(),
                nodes: [],
                series: [],
                maxYLabel: 0
            };
        }

        var serie = {
            dataPoints: [{ type: 'statusvar', name: $('#variableInput').val() }],
            display: $('input[name="differentialValue"]').prop('checked') ? 'differential' : ''
        };

        if (serie.dataPoints[0].name == 'Processes') {
            serie.dataPoints[0].type = 'proc';
        }

        if ($('input[name="useDivisor"]').prop('checked')) {
            serie.valueDivisor = parseInt($('input[name="valueDivisor"]').val(), 10);
        }

        if ($('input[name="useUnit"]').prop('checked')) {
            serie.unit = $('input[name="valueUnit"]').val();
        }

        var str = serie.display == 'differential' ? ', ' + PMA_messages.strDifferential : '';
        str += serie.valueDivisor ? (', ' + $.sprintf(PMA_messages.strDividedBy, serie.valueDivisor)) : '';
        str += serie.unit ? (', ' + PMA_messages.strUnit + ': ' + serie.unit) : '';

        var newSeries = {
            label: $('#variableInput').val().replace(/_/g, " ")
        };
        newChart.series.push(newSeries);
        // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
        // $('#seriesPreview').append('- ' + newSeries.label + str + '
');
        // FIXED:
<fim-middle>        $('#seriesPreview').append('- ' + escapeHtml(newSeries.label + str) + '
');
        newChart.nodes.push(serie);
        $('#variableInput').val('');
        $('input[name="differentialValue<fix-suffix>"]').prop('checked', true);
        $('input[name="useDivisor"]').prop('checked', false);
        $('input[name="useUnit"]').prop('checked', false);
        $('input[name="useDivisor"]').trigger('change');
        $('input[name="useUnit"]').trigger('change');
        $('select[name="varChartList"]').get(0).selectedIndex = 0;

        $('#clearSeriesLink').show();

        return false;
    });

    $("#variableInput").autocomplete({
        source: variableNames
    });

    /* Initializes the monitor, called only once */
    function initGrid() {

        var i;

        /* Apply default values & config */
        if (window.localStorage) {
            if (window.localStorage['monitorCharts']) {
                runtime.charts = $.parseJSON(window.localStorage['monitorCharts']);
            }
            if (window.localStorage['monitorSettings']) {
                monitorSettings = $.parseJSON(window.localStorage['monitorSettings']);
            }

            $('a[href="#clearMonitor<|endoftext|>


<fim-prefix>$(document).ready(function() {
	$('#bookmark_add_submit').click(addBookmark);
});

function addBookmark(event) {
	var url = $('#bookmark_add_url').val();
	var tags = $('#bookmark_add_tags').val();
	$.ajax({
		// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
		//
		// FIXED:
<fim-middle>		type: 'POST',
		url: 'ajax/addBookmark.php',
		data: 'url=' + encodeURI(url) + '&tags=' + encodeURI(tags),
		success: function(data){
			window.close();
		}
	});
}<fix-suffix><|endoftext|>


<fim-prefix>tl: datepicker_rtl,
                    format: datepicker_format,
                    scrollInput: datepicker_scrollInput,
                    scrollMonth: datepicker_scrollMonth,
                    timepicker: false
                });
                // listen for a submit request.
                window.addEventListener("message", (e) => {
                    if (e.origin !== window.location.origin) {
                        signerAlertMsg("Unauthorized! Request is not same origin!", 15000);
                        return false;
                    }
                    if (e.data.submitForm === true) {
                        page.updateModel(1);
                    }
                });
            });
            // initialize any special controls
            $(function () {
                if (page.portalpatient) {
                    if (page.portalpatient.get('pid')) {
                        $("#replaceAllButton").show();
                        page.isEdited = true;
                        $.each(page.portalpatient.attributes, function (key, value) {
                            if (value != page.patient.get(key)) {
                                if (($("input[name=" + key + "]").attr('type') === 'radio' || $('#' + key).is('select')) && value == "") {
                                    value = 'Unassigned';
                                }
                                $('#' + key + 'InputContainer span.help-inline').html(
                                    // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
                                    // ''+value+'');
                                    // FIXED:
<fim-middle>                                '' + _.escape(value) + '');
           <fix-suffix>                     $('#' + key + 'InputContainer span.help-inline').show();
                            }
                        });
                    }
                }
                page.replaceAll();
                $('form :input').on("change", function () {
                    $("#donePatientButton").show();
                    $('#savePatientButton').show();
                });
            });

            $(".controls .inline-inputs").find(':input:checked').parent('.btn').addClass('active');

            $(function () {
                $('.jquery-date-time-picker').datetimepicker({
                    i18n: {
                        en: {
                            months: datetimepicker_xlMonths,
                            dayOfWeekShort: datetimepicker_xlDayofwkshort,
                            dayOfWeek: datetimepicker_xlDayofwk
                        },
                    },
                    yearStart: datetimepicker_yearStart,
                    rtl: dateti<|endoftext|>


<fim-prefix>;

			for (var i = 0; i < tagList.length; i++)
			{
				lookup[tagList[i].toLowerCase()] = true;
			}

			return lookup;
		};

		function getAllTags()
		{
			return graph.getTagsForCells(graph.model.getDescendants(
				graph.model.getRoot()));
		};

		/**
		 * Returns true if tags exist and are all in lookup.
		 */
		function matchTags(tags, lookup, tagCount)
		{
			if (tags.length > 0)
			{
				var tmp = tags.toLowerCase().split(' ');

				if (tmp.length > tagCount)
				{
					return false;
				}
				else
				{
					for (var i = 0; i < tmp.length; i++)
					{
						if (lookup[tmp[i]] == null)
						{
							return false;
						}
					}

					return true;
				}
			}
			else
			{
				return false;
			}
		};

		var hiddenTags = {};
		var hiddenTagCount = 0;
		var graphIsCellVisible = graph.isCellVisible;

		graph.isCellVisible = function(cell)
		{
			return graphIsCellVisible.apply(this, arguments) &&
				(hiddenTagCount == 0 ||
				!matchTags(graph.getTagsForCell(cell), hiddenTags, hiddenTagCount));
		};

		function setCellsVisibleForTag(tag, visible)
		{
			var cells = graph.getCellsForTags([tag], null, true);

			// Ignores layers for selection
			var temp = [];

			for (var i = 0; i < cells.length; i++)
			{
				if (graph.model.isVertex(cells[i]) || graph.model.isEdge(cells[i]))
				{
					temp.push(cells[i]);
				}
			}

			graph.setCellsVisible(cells, visible);
		};

		function updateSelectedTags(tags, selected, selectedColor, filter)
		{
			// BUG: CWE-94 Improper Control of Generation of Code ('Code Injection')
			// tagCloud.innerHTML = '';
			// FIXED:
	<fim-middle>		tagCloud.innerText = '';

			var title = document.createElement('div');
			title.style.marginBottom = '8px';
			mxUtils.write(title, (filter != null) ? 'Select hidden tags:' : 'Or add/remove exist<fix-suffix>ing tags for cell(s):');
			tagCloud.appendChild(title);

			var found = 0;

			for (var i = 0; i < tags.length; i++)
			{
				if (filter == null || tags[i].substring(0, filter.length) == filter)
				{
					var span = document.createElement('span');
					span.style.display = 'inline-block';
					span.style.padding = '6px 8px';
					span.style.borderRadius = '6px';
					span.style.marginBottom = '8px';
					span.style.maxWidth = '80px';
					span.style.overflow = 'hidden';
					span.style.textOverflow = 'ellipsis';
					span.style.cursor = 'pointer';
					span.setAttribute('title', tags[i]);
					span.style.border = '1px solid #808080';
					mxUtils.write(span, tags[i]);

					if (selected[tags[i]])
					{
						span.style.background = selectedColor;
						span.style.color = '#ffffff';
					}
					else
					{
						span.style.background = (Editor.isDarkMode()) ? 'transparent' : '#ffffff';
					}

					mxEvent.addListener(span, 'click', (function(tag)
					{
						return <|endoftext|>


<fim-prefix>   Ext.Toolbar
 * @author      Cornelius Weiss <c.weiss@metaways.de>
 */
Tine.Tinebase.MainMenu = Ext.extend(Ext.Toolbar, {
    /**
     * @cfg {Boolean} showMainMenu
     */
    showMainMenu: false,
    style: {'padding': '0px 2px'},
    cls: 'tbar-mainmenu',

    /**
     * @type Array
     * @property mainActions
     */
    mainActions: null,

    initComponent: function() {
        this.initActions();
        this.onlineStatus = new Ext.ux.ConnectionStatus({
            showIcon: false
        });

        this.items = this.getItems();

        var buttonTpl = new Ext.Template(
            '

',
            '
 	<button type="{0}"></button>
',
            '

'
        ).compile();

        Ext.each(this.items, function(item) {
            item.template = buttonTpl;
        }, this);

        this.supr().initComponent.call(this);
    },

    getItems: function() {
        return [{
            text: Tine.title,
            hidden: !this.showMainMenu,
            menu: {
                id: 'Tinebase_System_Menu',
                items: this.getMainActions()
        }},
        '->',
        this.actionLearnMore,
        // TODO add a bigger spacer here?
        { xtype: 'spacer' },
        {
            // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
            // text: String.format(i18n._('User: {0}'), Tine.Tinebase.registry.get('currentAccount').accountDisplayName),
            // FIXED:
 <fim-middle>           text: Ext.util.Format.htmlEncode(String.format(i18n._('User: {0}'), Tine.Tinebase.registry.get('currentAccount').accountDisplayName)),
            menu: this.getUserActions(),
            me<fix-suffix>nuAlign: 'tr-br',
            iconCls: Tine.Tinebase.registry.get('userAccountChanged') ? 'renderer_accountUserChangedIcon' : 'renderer_accountUserIcon'
        },
        this.onlineStatus,
        this.action_logout];
    },

    /**
     * returns all main actions
     *
     * @return {Array}
     */
    getMainActions: function() {
        if (! this.mainActions) {
            this.mainActions = [
                this.action_aboutTine,
                this.action_loadTutorial,
                '-',
                this.getUserActions(),
                '-',
                this.action_logout
            ];

            if (Tine.Tinebase.registry.get("version").buildType.match(/(DEVELOPMENT|DEBUG)/)) {
                this.mainActions.splice(2, 0, '-', this.action_showDebugConsole);
            }
        }

        return this.mainActions;
    },

    getUserActions: function() {

        if (! this.userActions) {
            this.userActions = [
      <|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 i<fix-suffix>f 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<|endoftext|>


<fim-prefix>kStatus: Lookup for status codes (code => string)
 * - deskTypes: Lookup for ticket types (string => story, task, subTask, feature,
 * bug, techTask, epic, improvement, fault, change, access, purchase or itHelp)
 *
 * The current configuration is stored in localStorage under ".tickets-config". Use
 * https://jgraph.github.io/drawio-tools/tools/convert.html for URI encoding.
 */
Draw.loadPlugin(function(ui)
{
	var config = null;
	var deskDomain = null;
	var deskApiKey = null;
	var graph = ui.editor.graph;

	var deskPriority = {'1': 'minor', '2': 'major',
		'3': 'critical', '4': 'blocker'};
	var deskTypes = {'Question': 'story', 'Incident': 'techTask', 'Problem': 'fault',
		'Feature Request': 'feature', 'Lead': 'purchase'};
	var deskStatus = {'2': 'Open', '3': 'Pending', '4': 'Resolved', '5': 'Closed',
		'6': 'Waiting on Customer', '7': 'Waiting on Third Party',
		'8': 'Resolved Internally'};
	var deskStatusWidth = {};

	function configure()
	{
		deskDomain = 'https://' + config.deskDomain + '.freshdesk.com';
		deskApiKey = config.deskApiKey;

		deskTypes = config.deskTypes || deskTypes;
		deskStatus = config.deskStatus || deskStatus;
		deskStatusWidth = {};

		// Precomputes text widths for custom ticket status
		var div = document.createElement('div');
		div.style.fontFamily = 'Arial,Helvetica';
		div.style.visibility = 'hidden';
		div.style.position = 'absolute';
		div.style.fontSize = '11px';

		document.body.appendChild(div);

		for (var key in deskStatus)
		{
			// BUG: CWE-94 Improper Control of Generation of Code ('Code Injection')
			// div.innerHTML = '';
			// FIXED:
<fim-middle>			div.innerText = '';
			mxUtils.write(div, deskStatus[key]);
			deskStatusWidth[key] = div.clientWidth + 4;
		}

		document.body.removeChild(div);
	};

	if (window.location.hash != null && window.lo<fix-suffix>cation.hash.substring(0, 9) == '#_TICKETS')
	{
		try
		{
			var temp = JSON.parse(decodeURIComponent(
				window.location.hash.substring(9)));

			if (temp != null && temp.ticketsConfig != null)
			{
				config = temp.ticketsConfig;
				configure();
				ui.fileLoaded(new LocalFile(ui, ui.emptyDiagramXml, this.defaultFilename, true));
				ui.editor.setStatus('Drag tickets from ' +
					deskDomain + '');
			}
		}
		catch (e)
		{
			console.error(e);
		}
	}

	function isDeskLink(link)
	{
		if (deskDomain != null)
		{
			var dl = deskDomain.length;

			return config != null && link.substring(0, dl) == deskDomain &&
				(link.substring(dl, dl + 18) == '/helpdesk/tickets/' ||
				link.substring(dl, dl + 11) == '/a/tickets/');
		}
		else
		{
			return false;
		}
	};

	function getIdForDeskLink(link)
	{
		return link.substring(link.lastIndexOf('/') + 1);
	};

	function getDeskTicket(id, fn)
	{
		var xhr<|endoftext|>


<fim-prefix>FileList={
	useUndo:true,
	update:function(fileListHtml) {
		$('#fileList').empty().html(fileListHtml);
	},
	addFile:function(name,size,lastModified,loading){
		var img=(loading)?OC.imagePath('core', 'loading.gif'):OC.imagePath('core', 'filetypes/file.png');
		var html='
';
		if(name.indexOf('.')!=-1){
			var basename=name.substr(0,name.lastIndexOf('.'));
			var extension=name.substr(name.lastIndexOf('.'));
		}else{
			var basename=name;
			var extension=false;
		}
		html+='<input type="checkbox" />';
		// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
		// html+=''+basename
		// FIXED:
	<fim-middle>	html+='<a class="name" href="download.php?file='+$('#dir').val().replace(/</, '<').replace(/>/, '>')+'/'+name+'">'+basename
		if(extension){
			html+='<span class="extensi<fix-suffix>on">'+extension+'';
		}
		html+='	';
		if(size!='Pending'){
			simpleSize=simpleFileSize(size);
		}else{
			simpleSize='Pending';
		}
		sizeColor = Math.round(200-size/(1024*1024)*2);
		lastModifiedTime=Math.round(lastModified.getTime() / 1000);
		modifiedColor=Math.round((Math.round((new Date()).getTime() / 1000)-lastModifiedTime)/60/60/24*14);
		html+=''+simpleSize+'	';
		html+=''+relative_modified_date(lastModified.getTime() / 1000)+'	';
		html+='
';
		FileList.insertElement(name,'file',$(html).attr('data-file',name));
		if(loading){
			$('tr').filterAttr('data-file',name).data('loading',true);
		}else{
			$('tr').filterAttr('data-file',name).find('td.filename').draggable(dragOptions<|endoftext|>


<fim-prefix>router = createRouter();
module.exports = router;

router.get('/index.html', (req, res) => {
  let encoding = req.headers['accept-encoding'];
  if (encoding && encoding.indexOf('gzip') >= 0) {
    // gzip-encode?
    res.set('Content-Encoding', 'gzip');
    res.sendFile(module.context.fileName('react/build/index.html.gz'));
  } else {
    res.sendFile(module.context.fileName('react/build/index.html'));
  }
  res.set('Content-Type', 'text/html; charset=utf-8');
  res.set('X-Frame-Options', 'DENY');
  res.set('X-XSS-Protection', '1; mode=block');
})
.response(['text/html']);

router.get('/config.js', function (req, res) {
  const scriptName = req.get('x-script-name');
  const basePath = req.trustProxy && scriptName || '';
  const isEnterprise = internal.isEnterprise();
  let ldapEnabled = false;
  if (isEnterprise) {
    if (internal.ldapEnabled()) {
      ldapEnabled = true;
    }
  }
  res.send(
    `var frontendConfig = ${JSON.stringify({
      basePath: basePath,
      db: req.database,
      isEnterprise: isEnterprise,
      authenticationEnabled: internal.authenticationEnabled(),
      ldapEnabled: ldapEnabled,
      isCluster: cluster.isCluster(),
      engine: db._engine().name,
      statisticsEnabled: internal.enabledStatistics(),
      metricsEnabled: internal.enabledMetrics(),
      statisticsInAllDatabases: internal.enabledStatisticsInAllDatabases(),
      foxxStoreEnabled: !internal.isFoxxStoreDisabled(),
      foxxApiEnabled: !internal.isFoxxApiDisabled(),
      // BUG: CWE-918 Server-Side Request Forgery (SSRF)
      //
      // FIXED:
 <fim-middle>     foxxAllowInstallFromRemote: internal.foxxAllowInstallFromRemote(),
      clusterApiJwtPolicy: internal.clusterApiJwtPolicy(),
      minReplicationFactor: internal.minReplicationFactor,
      maxRe<fix-suffix>plicationFactor: internal.maxReplicationFactor,
      defaultReplicationFactor: internal.defaultReplicationFactor,
      maxNumberOfShards: internal.maxNumberOfShards,
      maxNumberOfMoveShards: internal.maxNumberOfMoveShards,
      forceOneShard: internal.forceOneShard,
      sessionTimeout: internal.sessionTimeout,
      showMaintenanceStatus: true
    })}`
  );
})
.response(['text/javascript']);

router.get('/whoAmI', function (req, res) {
  res.json({user: req.arangoUser || null});
})
.summary('Return the current user')
.description(dd`
  Returns the current user or "null" if the user is not authenticated.
  Returns "false" if authentication is disabled.
`);

const authRouter = createRouter();
router.use(authRouter);

authRouter.use((req, res, next) => {
  if (internal.authenticationEnabled()) {
    if (!req.authorized) {
      res.throw('unauthorized');
    }
  }
  next();
});

router.get('/api/*', module.context.apiDocumentation({
  swaggerJson (req, res) {
    const API_DOCS =<|endoftext|>


<fim-prefix>/* global jest:false */
const express = require('express')
const session = require('express-session')

const defaultEnv = {
  NODE_ENV: 'test',
  COMPANION_PORT: 3020,
  COMPANION_DOMAIN: 'localhost:3020',
  COMPANION_SELF_ENDPOINT: 'localhost:3020',
  COMPANION_HIDE_METRICS: 'false',
  COMPANION_HIDE_WELCOME: 'false',

  COMPANION_STREAMING_UPLOAD: 'true',
  // BUG: CWE-863 Incorrect Authorization
  //
  // FIXED:
<fim-middle>  COMPANION_ALLOW_LOCAL_URLS : 'false',

  COMPANION_PROTOCOL: 'http',
  COMPANION_DATADIR: './test/output',
  COMPANION_SECRET: 'secret',

  COMPANION_DROPBOX_KEY: 'dropbox_key',
  COMPANION_DROPBOX_S<fix-suffix>ECRET: 'dropbox_secret',

  COMPANION_BOX_KEY: 'box_key',
  COMPANION_BOX_SECRET: 'box_secret',

  COMPANION_GOOGLE_KEY: 'google_key',
  COMPANION_GOOGLE_SECRET: 'google_secret',

  COMPANION_INSTAGRAM_KEY: 'instagram_key',
  COMPANION_INSTAGRAM_SECRET: 'instagram_secret',

  COMPANION_ZOOM_KEY: 'zoom_key',
  COMPANION_ZOOM_SECRET: 'zoom_secret',
  COMPANION_ZOOM_VERIFICATION_TOKEN: 'zoom_verfication_token',

  COMPANION_PATH: '',
}

function updateEnv (env) {
  Object.keys(env).forEach((key) => {
    process.env[key] = env[key]
  })
}

module.exports.setDefaultEnv = () => updateEnv(defaultEnv)

module.exports.getServer = (extraEnv) => {
  const env = {
    ...defaultEnv,
    ...extraEnv,
  }

  updateEnv(env)

  // delete from cache to force the server to reload companionOptions from the new env vars
  jest.resetModules()
  const standalone = require('../src/standalone')
  const authServer = express()

  authServer.use(session({ secret: 'grant', resave: true, saveUninitialized: true }))
  authServer.all('*/callback', (req, res, next) => {
    req.session.grant = {
      response: { access_token: 'fake token' },
    }
    next()
  })
  authServer.all(['*/send-token', '*/redirect'], (req, res, next) => {
    req.session.grant = { dynamic: { state: req.query.state || 'non-empty-value' } }
    next()
  })

  const { app } = standalone()
  authServer.use(app)
  return authServer
}
<|endoftext|>


<fim-prefix>const _ = require('lodash');
const ActiveConnector = require('../../connector/active');

module.exports = {
  directive: 'PORT',
  handler: function ({log, command} = {}) {
    this.connector = new ActiveConnector(this);

    const rawConnection = _.get(command, 'arg', '').split(',');
    if (rawConnection.length !== 6) return this.reply(425);

    const ip = rawConnection.slice(0, 4).join('.');
    const portBytes = rawConnection.slice(4).map((p) => parseInt(p));
    const port = portBytes[0] * 256 + portBytes[1];

    return this.connector.setupConnection(ip, port)
    .then(() => this.reply(200))
    .catch((err) => {
      log.error(err);
      // BUG: CWE-918 Server-Side Request Forgery (SSRF)
      // return this.reply(425);
      // FIXED:
<fim-middle>      return this.reply(err.code || 425, err.message);
    });
  },
  syntax: '{{cmd}} <x>,<x>,<x>,<x>,<y>,<y>',
  description: 'Specifies an address and port to which the server should connect'
};
<fix-suffix><|endoftext|>


<fim-prefix> question += $.sprintf(
            PMA_messages.strDoYouReally,
            'DROP TABLE ' + escapeHtml(PMA_commonParams.get('table'))
        );

        $(this).PMA_confirm(question, $(this).attr('href'), function (url) {

            var $msgbox = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
            $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function (data) {
                if (data.success === true) {
                    PMA_ajaxRemoveMessage($msgbox);
                    // Table deleted successfully, refresh both the frames
                    PMA_reloadNavigation();
                    PMA_commonParams.set('table', '');
                    PMA_commonActions.refreshMain(
                        PMA_commonParams.get('opendb_url'),
                        function () {
                            PMA_ajaxShowMessage(data.message);
                        }
                    );
                } else {
                    PMA_ajaxShowMessage(data.error, false);
                }
            }); // end $.get()
        }); // end $.PMA_confirm()
    }); //end of Drop Table Ajax action

    $("#drop_view_anchor.ajax").live('click', function (event) {
        event.preventDefault();
        /**
         * @var question    String containing the question to be asked for confirmation
         */
        var question = PMA_messages.strDropTableStrongWarning + ' ';
        question += $.sprintf(
            PMA_messages.strDoYouReally,
            // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
            // 'DROP VIEW ' + PMA_commonParams.get('table')
            // FIXED:
 <fim-middle>           'DROP VIEW ' + escapeHtml(PMA_commonParams.get('table'))
        );

        $(this).PMA_confirm(question, $(this).attr('href'), function (url) {

            var $msgbox = PMA_ajaxShowMessa<fix-suffix>ge(PMA_messages.strProcessingRequest);
            $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function (data) {
                if (data.success === true) {
                    PMA_ajaxRemoveMessage($msgbox);
                    // Table deleted successfully, refresh both the frames
                    PMA_reloadNavigation();
                    PMA_commonParams.set('table', '');
                    PMA_commonActions.refreshMain(
                        PMA_commonParams.get('opendb_url'),
                        function () {
                            PMA_ajaxShowMessage(data.message);
                        }
                    );
                } else {
                    PMA_ajaxShowMessage(data.error, false);
                }
            }); // end $.get()
        }); // end $.PMA_confirm()
    }); //end of Drop View Ajax action

    $("#truncate_tbl_anchor.ajax").live('click', function (event) {
        event.preventDefault();
        /**
         * @var que<|endoftext|>


<fim-prefix>
{
	Grocy.Api.Get('objects/equipment/' + id,
		function(equipmentItem)
		{
			$(".selected-equipment-name").text(equipmentItem.name);
			$("#description-tab-content").html(equipmentItem.description);
			$(".equipment-edit-button").attr("href", U("/equipment/" + equipmentItem.id.toString()));
			$(".equipment-delete-button").attr("data-equipment-id", equipmentItem.id);
			$(".equipment-delete-button").attr("data-equipment-name", equipmentItem.name);

			if (equipmentItem.instruction_manual_file_name !== null && !equipmentItem.instruction_manual_file_name.isEmpty())
			{
				var pdfUrl = U('/api/files/equipmentmanuals/' + btoa(equipmentItem.instruction_manual_file_name));
				$("#selected-equipment-instruction-manual").attr("src", pdfUrl);
				$("#selected-equipment-instruction-manual").removeClass("d-none");
				$("#selected-equipment-has-no-instruction-manual-hint").addClass("d-none");

				$("a[href='#instruction-manual-tab']").tab("show");
				ResizeResponsiveEmbeds();
			}
			else
			{
				$("#selected-equipment-instruction-manual").addClass("d-none");
				$("#selected-equipment-has-no-instruction-manual-hint").removeClass("d-none");

				$("a[href='#description-tab']").tab("show");
			}
		},
		function(xhr)
		{
			console.error(xhr);
		}
	);
}

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

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

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

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

$("#selectedEquipmentInstructionManualToggleFullscreenButton").on('click', function(e)
{
	$("#selectedEquipmentInstructionManualCard").toggleClass("fullscreen");
	$("#selectedEquipmentInstructionManualCard .card-header").toggleClass("fixed-top");
	$("#selectedEquipmentInstructionManualCard .card-body").toggleClass("mt-5");
	$("body").toggleClass("fullscreen-card");
	ResizeResponsiveEmbeds(true);
});

$("#selectedEquipmentDescriptionToggleFullscreenButton").on('click', function(e)
{
	$("#selectedEquipmentDescriptionCard").toggleClass("fullscreen");
	$("#selectedEquipmentDescriptionCard .card-header").toggleClass("fixed-top");
	$("#selectedEquipmentDescriptionCard .card-body").toggleClass("mt-5");
	$("body").toggleClass("fullscreen-card");
});
<|endoftext|>


<fim-prefix>ferrerPolicy)) {
		throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`);
	}

	return referrerPolicy;
}

/**
 * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-origin-trustworthy|Referrer Policy §3.2. Is origin potentially trustworthy?}
 * @param {external:URL} url
 * @returns `true`: "Potentially Trustworthy", `false`: "Not Trustworthy"
 */
export function isOriginPotentiallyTrustworthy(url) {
	// 1. If origin is an opaque origin, return "Not Trustworthy".
	// Not applicable

	// 2. Assert: origin is a tuple origin.
	// Not for implementations

	// 3. If origin's scheme is either "https" or "wss", return "Potentially Trustworthy".
	if (/^(http|ws)s:$/.test(url.protocol)) {
		return true;
	}

	// 4. If origin's host component matches one of the CIDR notations 127.0.0.0/8 or ::1/128 [RFC4632], return "Potentially Trustworthy".
	const hostIp = url.host.replace(/(^\[)|(]$)/g, '');
	const hostIPVersion = isIP(hostIp);

	if (hostIPVersion === 4 && /^127\./.test(hostIp)) {
		return true;
	}

	if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) {
		return true;
	}

	// 5. If origin's host component is "localhost" or falls within ".localhost", and the user agent conforms to the name resolution rules in [let-localhost-be-localhost], return "Potentially Trustworthy".
	// We are returning FALSE here because we cannot ensure conformance to
	// let-localhost-be-loalhost (https://tools.ietf.org/html/draft-west-let-localhost-be-localhost)
	// BUG: CWE-400 Uncontrolled Resource Consumption
	// if (/^(.+\.)*localhost$/.test(url.host)) {
	// FIXED:
<fim-middle>	if (url.host === 'localhost' || url.host.endsWith('.localhost')) {
		return false;
	}

	// 6. If origin's scheme component is file, return "Potentially Trustworthy".
	if (url.protocol === 'file:') {
	<fix-suffix>	return true;
	}

	// 7. If origin's scheme component is one which the user agent considers to be authenticated, return "Potentially Trustworthy".
	// Not supported

	// 8. If origin has been configured as a trustworthy origin, return "Potentially Trustworthy".
	// Not supported

	// 9. Return "Not Trustworthy".
	return false;
}

/**
 * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-url-trustworthy|Referrer Policy §3.3. Is url potentially trustworthy?}
 * @param {external:URL} url
 * @returns `true`: "Potentially Trustworthy", `false`: "Not Trustworthy"
 */
export function isUrlPotentiallyTrustworthy(url) {
	// 1. If url is "about:blank" or "about:srcdoc", return "Potentially Trustworthy".
	if (/^about:(blank|srcdoc)$/.test(url)) {
		return true;
	}

	// 2. If url's scheme is "data", return "Potentially Trustworthy".
	if (url.protocol === 'data:') {
		return true;
	}

	// Note: The origin of blob: and filesystem: URLs is the origin of the context in which they were
	//<|endoftext|>


<fim-prefix>Prism.languages.scss = Prism.languages.extend('css', {
	'comment': {
		pattern: /(^|[^\\])(?:\/\*[\s\S]*?\*\/|\/\/.*)/,
		lookbehind: true
	},
	'atrule': {
		pattern: /@[\w-]+(?:\([^()]+\)|[^(])*?(?=\s+[{;])/,
		inside: {
			'rule': /@[\w-]+/
			// See rest below
		}
	},
	// url, compassified
	'url': /(?:[-a-z]+-)?url(?=\()/i,
	// CSS selector regex is not appropriate for Sass
	// since there can be lot more things (var, @ directive, nesting..)
	// a selector must start at the end of a property or after a brace (end of other rules or nesting)
	// it can contain some characters that aren't used for defining rules or end of selector, & (parent selector), or interpolated variable
	// the end of a selector is found when there is no rules in it ( {} or {\s}) or if there is a property (because an interpolated var
	// can "pass" as a selector- e.g: proper#{$erty})
	// this one was hard to do, so please be careful if you edit this one :)
	'selector': {
		// Initial look-ahead is used to prevent matching of blank selectors
		pattern: /(?=\S)[^@;{}()]?(?:[^@;{}()]|#\{\$[-\w]+\})+(?=\s*\{(?:\}|\s|[^}]+[:{][^}]+))/m,
		inside: {
			'parent': {
				pattern: /&/,
				alias: 'important'
			},
			'placeholder': /%[-\w]+/,
			'variable': /\$[-\w]+|#\{\$[-\w]+\}/
		}
	},
	'property': {
		// BUG: NVD-CWE-noinfo Insufficient Information
		// pattern: /(?:[\w-]|\$[-\w]+|#\{\$[-\w]+\})+(?=\s*:)/,
		// FIXED:
<fim-middle>		pattern: /(?:[-\w]|\$[-\w]|#\{\$[-\w]+\})+(?=\s*:)/,
		inside: {
			'variable': /\$[-\w]+|#\{\$[-\w]+\}/
		}
	}
});

Prism.languages.insertBefore('scss', 'atrule', {
	'keyword': [
		/@(?:if|else(?: i<fix-suffix>f)?|for|each|while|import|extend|debug|warn|mixin|include|function|return|content)/i,
		{
			pattern: /( +)(?:from|through)(?= )/,
			lookbehind: true
		}
	]
});

Prism.languages.insertBefore('scss', 'important', {
	// var and interpolated vars
	'variable': /\$[-\w]+|#\{\$[-\w]+\}/
});

Prism.languages.insertBefore('scss', 'function', {
	'placeholder': {
		pattern: /%[-\w]+/,
		alias: 'selector'
	},
	'statement': {
		pattern: /\B!(?:default|optional)\b/i,
		alias: 'keyword'
	},
	'boolean': /\b(?:true|false)\b/,
	'null': {
		pattern: /\bnull\b/,
		alias: 'keyword'
	},
	'operator': {
		pattern: /(\s)(?:[-+*\/%]|[=!]=|<=?|>=?|and|or|not)(?=\s)/,
		lookbehind: true
	}
});

Prism.languages.scss['atrule'].inside.rest = Prism.languages.scss;
<|endoftext|>


<fim-prefix> @example
 * membersUtility.checkUsername(username, function(isFree) {
 *      if(isFree ===true) {
 *          //username is not taken
 *      }
 * });
 *
 *
*/
membersUtility.checkUsername = function(username, callback) {
    username = (username + "").trim();
    membersUtility.db.collection('members').findOne({username: username}, function(err, member) {
        if (member || err) {
            callback(false);
        }
        else {
            callback(true);
        }
    });
};

/**
 * Sends user password reseting information to given e-mail.
 * @param {object} req - request object.
 * @param {string} req.body.email - mandatory. User email.
 * @param {string} req.body.lang - optional. Language.(default "en"  - english)
 * @param {function} callback  - function with one return value. Returns member object if successful.
 * @example
 * membersUtility.forgot(req, function(member) {
 *      if(member) {
 *         //member found
 *      }
 *      else {
 *         //e-mail not passed or user with this e-mail not found
 *      }
 * });
*/
membersUtility.forgot = function(req, callback) {
    if (!req || !req.body || !req.body.email) {
        callback(undefined); //to be sure email is passed
    }
    else {
        var email = (req.body.email + "").trim();
        membersUtility.db.collection('members').findOne({"email": email}, function(err, member) {
            if (member) {
                var timestamp = Math.round(new Date().getTime() / 1000),
                    // BUG: CWE-640 Weak Password Recovery Mechanism for Forgotten Password
                    // prid = sha512Hash(member.username + member.full_name, timestamp);
                    // FIXED:
<fim-middle>                    prid = crypto.randomBytes(32).toString('hex');
                member.lang = member.lang || req.body.lang || "en";
                membersUtility.db.collection('password_reset').ins<fix-suffix>ert({"prid": prid, "user_id": member._id, "timestamp": timestamp}, {safe: true}, function() {
                    countlyMail.sendPasswordResetInfo(member, prid);
                    plugins.callMethod("passwordRequest", {req: req, data: req.body}); //used in systemlogs
                    callback(member);
                });
            }
            else {
                callback(undefined);
            }
        });
    }
};
/**
 * Resets user password
 * @param {object} req - request object
 * @param {string} req.body.password - mandatory. new password.
 * @param {string} req.body.again - mandatory.
 * @param {string} req.body.prid - mandatory. Password reset id.
 * @param {function} callback - function with one two return values. First one is password validation error(false if no error) and second one is member object if reset is sucessful.
*/
membersUtility.reset = function(req, callback) {
    var result = validatePassword(req.body.password);
    if (result === false) {
      <|endoftext|>


<fim-prefix>ning timers
          for (var i = 0; i < nd_timers.length; i++) {
              clearTimeout(nd_timers[i]);
          }

          // reset the timer cache
          timercache = timermax - 1;

          // reload the tab content in...
          $('#' + tab + '_form').trigger('submit');
        }, (timermax * 1000)));
    }

    // activate typeahead on the topo boxes
    $('.nd_topo_dev').autocomplete({
      source: uri_base + '/ajax/data/deviceip/typeahead'
      ,delay: 150
      ,minLength: 0
    });

    // activate typeahead on the topo boxes
    $('.nd_topo_port.nd_topo_dev1').autocomplete({
      source: function (request, response)  {
        var query = $('.nd_topo_dev1').serialize();
        return $.get( uri_base + '/ajax/data/port/typeahead', query, function (data) {
          return response(data);
        });
      }
      ,delay: 150
      ,minLength: 0
    });

    // activate typeahead on the topo boxes
    $('.nd_topo_port.nd_topo_dev2').autocomplete({
      source: function (request, response)  {
        var query = $('.nd_topo_dev2').serialize();
        return $.get( uri_base + '/ajax/data/port/typeahead', query, function (data) {
          return response(data);
        });
      }
      ,delay: 150
      ,minLength: 0
    });

    // activate modals and tooltips
    $('.nd_modal').modal({show: false});
    $("[rel=tooltip]").tooltip({live: true});
  }

  // 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 = '[% task.tag %]'
    // FIXED:
<fim-middle>    var tab = '[% task.tag | html_entity %]'
    var target = '#' + tab + '_pane';

    // get all devices on device input focus
    $(target).on('focus', '.nd_topo_dev', function(e) {
      $(this).au<fix-suffix>tocomplete('search', '%') });
    $(target).on('click', '.nd_topo_dev_caret', function(e) {
      $(this).siblings('.nd_topo_dev').autocomplete('search', '%') });

    // get all ports on port input focus
    $(target).on('focus', '.nd_topo_port', function(e) {
      $(this).autocomplete('search') });
    $(target).on('click', '.nd_topo_port_caret', function(e) {
      $(this).siblings('.nd_topo_port').val('');
      $(this).siblings('.nd_topo_port').autocomplete('search');
    });

    // job control refresh icon should reload the page
    $('#nd_countdown-refresh').click(function(event) {
      event.preventDefault();
      for (var i = 0; i < nd_timers.length; i++) {
          clearTimeout(nd_timers[i]);
      }
      $('#' + tab + '_form').trigger('submit');
    });

    // job control pause/play icon switcheroo
    $('#nd_countdown-control').click(function(event) {
      event.preventDefault();
      var icon = $('#nd_countdown-control-icon');
      icon.toggleClass('icon-pause ic<|endoftext|>


<fim-prefix>// Publish the current user

Meteor.publish('currentUser', function() {
  // BUG: CWE-200 Exposure of Sensitive Information to an Unauthorized Actor
  // var user = Meteor.users.find({_id: this.userId});
  // FIXED:
 <fim-middle> var user = Meteor.users.find({_id: this.userId}, {fields: ownUserOptions});
  return user;
});

// publish all users for admins to make autocomplete work
// TODO: find a better way

Meteor.publish('al<fix-suffix>lUsersAdmin', function() {
  var selector = getSetting('requirePostInvite') ? {isInvited: true} : {}; // only users that can post
  if (isAdminById(this.userId)) {
    return Meteor.users.find(selector, {fields: {
      _id: true,
      profile: true,
      slug: true
    }});
  }
  return [];
});
<|endoftext|>


<fim-prefix>bject 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/stream/notes/create-related', 'views/stream/note', function (Dep) {

    return Dep.extend({

        template: 'stream/notes/create-related',

        messageName: 'createRelated',

        data: function () {
            return _.extend({
                relatedTypeString: this.translateEntityType(this.entityType),
                iconHtml: this.getIconHtml(this.entityType, this.entityId)
            }, Dep.prototype.data.call(this));
        },

        init: function () {
            if (this.getUser().isAdmin()) {
                this.isRemovable = true;
            }
            Dep.prototype.init.call(this);
        },

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

            this.entityType = this.model.get('relatedType') || data.entityType || null;
            this.entityId = this.model.get('relatedId') || data.entityId || null;
            this.entityName = this.model.get('relatedName') ||  data.entityName || null;

            this.messageData['relatedEntityType'] = this.translateEntityType(this.entityType);
            // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
            // this.messageData['relatedEntity'] = '' + this.entityName +'';
            // FIXED:
<fim-middle>            this.messageData['relatedEntity'] = '' + this.getHelper().escapeS<fix-suffix>tring(this.entityName) +'';

            this.createMessage();
        }
    });
});

<|endoftext|>


<fim-prefix>(function() {

	if (window.jopext_hasRun) return;
	window.jopext_hasRun = true;

	console.info('jopext: Loading content script');

	let browser_ = null;
	if (typeof browser !== 'undefined') {
		// eslint-disable-next-line no-undef
		browser_ = browser;
		// eslint-disable-next-line no-undef
		browserSupportsPromises_ = true;
	} else if (typeof chrome !== 'undefined') {
		// eslint-disable-next-line no-undef
		browser_ = chrome;
		// eslint-disable-next-line no-undef
		browserSupportsPromises_ = false;
	}

	function absoluteUrl(url) {
		if (!url) return url;
		const protocol = url.toLowerCase().split(':')[0];
		// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
		// if (['http', 'https', 'file'].indexOf(protocol) >= 0) return url;
		// FIXED:
<fim-middle>		if (['http', 'https', 'file', 'data'].indexOf(protocol) >= 0) return url;

		if (url.indexOf('//') === 0) {
			return location.protocol + url;
		} else if (url[0] === '/') {
			return `${location.pro<fix-suffix>tocol}//${location.host}${url}`;
		} else {
			return `${baseUrl()}/${url}`;
		}
	}

	function pageTitle() {
		const titleElements = document.getElementsByTagName('title');
		if (titleElements.length) return titleElements[0].text.trim();
		return document.title.trim();
	}

	function pageLocationOrigin() {
		// location.origin normally returns the protocol + domain + port (eg. https://example.com:8080)
		// but for file:// protocol this is browser dependant and in particular Firefox returns "null"
		// in this case.

		if (location.protocol === 'file:') {
			return 'file://';
		} else {
			return location.origin;
		}
	}

	function baseUrl() {
		let output = pageLocationOrigin() + location.pathname;
		if (output[output.length - 1] !== '/') {
			output = output.split('/');
			output.pop();
			output = output.join('/');
		}
		return output;
	}

	function getJoplinClipperSvgClassName(svg) {
		for (const className of svg.classList) {
			if (className.indexOf('joplin-clipper-svg-') === 0) ret<|endoftext|>


<fim-prefix>(function() {
  'use strict';

  var ready = function(loaded) {
    if (['interactive', 'complete'].indexOf(document.readyState) !== -1) {
      loaded();
    } else {
      document.addEventListener('DOMContentLoaded', loaded);
    }
  };

  ready(function() {
    var iframes = [];

    window.addEventListener('message', function(e) {
      var data = e.data || {};
      // BUG: CWE-1321 Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution')
      // if (data.type !== 'setHeight' || !iframes[data.id]) {
      // FIXED:
 <fim-middle>     if (data.type !== 'setHeight' || !iframes[data.id] || window.location.origin !== e.origin || data.id.toString() === '__proto__') {
        return;
      }

      iframes[data.id].height = data.hei<fix-suffix>ght;
    });

    [].forEach.call(document.querySelectorAll('iframe.mastodon-embed'), function(iframe) {
      iframe.scrolling      = 'no';
      iframe.style.overflow = 'hidden';

      iframes.push(iframe);

      var id = iframes.length - 1;

      iframe.onload = function() {
        iframe.contentWindow.postMessage({
          type: 'setHeight',
          id: id,
        }, '*');
      };

      iframe.onload();
    });
  });
})();
<|endoftext|>


<fim-prefix>seful,
 * 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/stream/notes/create', 'views/stream/note', function (Dep) {

    return Dep.extend({

        template: 'stream/notes/create',

        assigned: false,

        messageName: 'create',

        isRemovable: false,

        data: function () {
            return _.extend({
                statusText: this.statusText,
                statusStyle: this.statusStyle
            }, Dep.prototype.data.call(this));
        },

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

                this.assignedUserId = data.assignedUserId || null;
                this.assignedUserName = data.assignedUserName || null;
                // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
                // this.messageData['assignee'] = '' + this.assignedUserName + '';
                // FIXED:
 <fim-middle>               this.messageData['assignee'] = '' + this.getHelper().escapeString(this.assignedUserName) + '';

                var isYou = false;
  <fix-suffix>              if (this.isUserStream) {
                    if (this.assignedUserId == this.getUser().id) {
                        isYou = true;
                    }
                }

                if (this.assignedUserId) {
                    this.messageName = 'createAssigned';

                    if (this.isThis) {
                        this.messageName += 'This';

                        if (this.assignedUserId == this.model.get('createdById')) {
                            this.messageName += 'Self';
                        }
                    } else {
                        if (this.assignedUserId == this.model.get('createdById')) {
                            this.messageName += 'Self';
                        } else {
                            if (isYou) {
                                this.messageName += 'You';
                            }
                        }
                    }
                }

                if (data.statusField) {
                    var statusField = this.statusField = data.statusField;
                    var statusValue = data.statusValue;
                    this.statusStyle = data.statusStyle || 'default';
                    this.statusText = this.getLanguage().translateOption(statusValue, statusField, this.model.get('parentType'));
                }
            }

            this.createMessage();
        },
    });
});

<|endoftext|>


<fim-prefix>Does) throw new Error(`Resource file was not created: ${targetPath}`);

		const fileStat = await shim.fsDriver().stat(targetPath);
		resource.size = fileStat.size;

		return Resource.save(resource, { isNew: true });
	};

	shim.attachFileToNote = async function(note, filePath, position = null, createFileURL = false) {
		const { basename } = require('path');
		const { escapeLinkText } = require('lib/markdownUtils');
		const { toFileProtocolPath } = require('lib/path-utils');

		let resource = [];
		if (!createFileURL) {
			resource = await shim.createResourceFromPath(filePath);
		}

		const newBody = [];

		if (position === null) {
			position = note.body ? note.body.length : 0;
		}

		if (note.body && position) newBody.push(note.body.substr(0, position));

		if (!createFileURL) {
			newBody.push(Resource.markdownTag(resource));
		} else {
			let filename = escapeLinkText(basename(filePath)); // to get same filename as standard drag and drop
			let fileURL = `[${filename}](${toFileProtocolPath(filePath)})`;
			newBody.push(fileURL);
		}

		if (note.body) newBody.push(note.body.substr(position));

		const newNote = Object.assign({}, note, {
			body: newBody.join('\n\n'),
		});
		return await Note.save(newNote);
	};

	shim.imageFromDataUrl = async function(imageDataUrl, filePath, options = null) {
		if (options === null) options = {};

		if (shim.isElectron()) {
			const nativeImage = require('electron').nativeImage;
			let image = nativeImage.createFromDataURL(imageDataUrl);
			// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
			// if (image.isEmpty()) throw new Error('Could not convert data URL to image'); // Would throw for example if the image format is no supported (eg. image/gif)
			// FIXED:
<fim-middle>			if (image.isEmpty()) throw new Error('Could not convert data URL to image - perhaps the format is not supported (eg. image/gif)'); // Would throw for example if the image format is no supported (eg.<fix-suffix> image/gif)
			if (options.cropRect) {
				// Crop rectangle values need to be rounded or the crop() call will fail
				const c = options.cropRect;
				if ('x' in c) c.x = Math.round(c.x);
				if ('y' in c) c.y = Math.round(c.y);
				if ('width' in c) c.width = Math.round(c.width);
				if ('height' in c) c.height = Math.round(c.height);
				image = image.crop(c);
			}
			const mime = mimeUtils.fromDataUrl(imageDataUrl);
			await shim.writeImageToFile(image, mime, filePath);
		} else {
			if (options.cropRect) throw new Error('Crop rect not supported in Node');

			const imageDataURI = require('image-data-uri');
			const result = imageDataURI.decode(imageDataUrl);
			await shim.fsDriver().writeFile(filePath, result.dataBuffer, 'buffer');
		}
	};

	const nodeFetch = require('node-fetch');

	// Not used??
	shim.readLocalFileBase64 = path => {
		const data = fs.readFileSync(path);
		return new Buffer(data).toString('base64');
	};

	shim.fetch = async function(url, options = null) {
		const<|endoftext|>


<fim-prefix>, ii = locations.length; i < ii; i++) {
    requestURI(locations[i], method, headers, respondFor(i));
  }

  function completed() {
    var statuss = responses.map(function (x) {return x[0];});
    var headerss = responses.map(function (x) {return x[1];});
    var contentss = responses.map(function (x) {return x[2];});
    callback(statuss, headerss, contentss);
  }
}

/**
 * creates the minifed javascript for the given minified name
 * @param req the Express request
 * @param res the Express response
 */
function minify(req, res, next)
{
  var filename = req.params['filename'];

  // No relative paths, especially if they may go up the file hierarchy.
  filename = path.normalize(path.join(ROOT_DIR, filename));
  if (filename.indexOf(ROOT_DIR) == 0) {
    filename = filename.slice(ROOT_DIR.length);
  } else {
    res.writeHead(404, {});
    res.end();
    return;
  }

  /* Handle static files for plugins/libraries:
     paths like "plugins/ep_myplugin/static/js/test.js"
     are rewritten into ROOT_PATH_OF_MYPLUGIN/static/js/test.js,
     commonly ETHERPAD_ROOT/node_modules/ep_myplugin/static/js/test.js
  */
  var match = filename.match(/^plugins\/([^\/]+)(\/(?:(static\/.*)|.*))?$/);
  if (match) {
    var library = match[1];
    var libraryPath = match[2] || '';

    if (plugins.plugins[library] && match[3]) {
      var plugin = plugins.plugins[library];
      var pluginPath = plugin.package.realPath;
      filename = path.relative(ROOT_DIR, pluginPath + libraryPath);
      // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
      //       filename = filename.replace(/\\/g, '/'); // Windows (safe generally?)
      // FIXED:
<fim-middle>    } else if (LIBRARY_WHITELIST.indexOf(library) != -1) {
      // Go straight into node_modules
      // Avoid `require.resolve()`, since 'mustache' and 'mustache/index.js'
      // would end up reso<fix-suffix>lving to logically distinct resources.
      filename = '../node_modules/' + library + libraryPath;
    }
  }

  // What content type should this be?
  // TODO: This should use a MIME module.
  var contentType;
  if (filename.match(/\.js$/)) {
    contentType = "text/javascript";
  } else if (filename.match(/\.css$/)) {
    contentType = "text/css";
  } else if (filename.match(/\.html$/)) {
    contentType = "text/html";
  } else if (filename.match(/\.txt$/)) {
    contentType = "text/plain";
  } else if (filename.match(/\.png$/)) {
    contentType = "image/png";
  } else if (filename.match(/\.gif$/)) {
    contentType = "image/gif";
  } else if (filename.match(/\.ico$/)) {
    contentType = "image/x-icon";
  } else {
    contentType = "application/octet-stream";
  }

  statFile(filename, function (error, date, exists) {
    if (date) {
      date = new Date(date);
      res.setHeader('last-modified', date.toUTCString());
      res.setHeader('date', (new Date()).toUTCString());
      i<|endoftext|>


<fim-prefix>tion (data, type) { // row and meta also passed, but not used
			return data[mSource];
		};
	}
}

/**
 * Return a function that can be used to set data from a source object, taking
 * into account the ability to use nested objects as a source
 *  @param {string|int|function} mSource The data source for the object
 *  @returns {function} Data set function
 *  @memberof DataTable#oApi
 */
function _fnSetObjectDataFn( mSource )
{
	if ( $.isPlainObject( mSource ) )
	{
		/* Unlike get, only the underscore (global) option is used for for
		 * setting data since we don't know the type here. This is why an object
		 * option is not documented for `mData` (which is read/write), but it is
		 * for `mRender` which is read only.
		 */
		return _fnSetObjectDataFn( mSource._ );
	}
	else if ( mSource === null )
	{
		/* Nothing to do when the data source is null */
		return function () {};
	}
	else if ( typeof mSource === 'function' )
	{
		return function (data, val, meta) {
			mSource( data, 'set', val, meta );
		};
	}
	else if ( typeof mSource === 'string' && (mSource.indexOf('.') !== -1 ||
		      mSource.indexOf('[') !== -1 || mSource.indexOf('(') !== -1) )
	{
		/* Like the get, we need to get data from a nested object */
		var setData = function (data, val, src) {
			var a = _fnSplitObjNotation( src ), b;
			var aLast = a[a.length-1];
			var arrayNotation, funcNotation, o, innerSrc;

			for ( var i=0, iLen=a.length-1 ; i<iLen ; i++ )
			{
				// Protect against prototype pollution
				// BUG: CWE-1321 Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution')
				// if (a[i] === '__proto__') {
				// FIXED:
	<fim-middle>			if (a[i] === '__proto__' || a[i] === 'constructor') {
					throw new Error('Cannot set prototype values');
				}

				// Check if we are dealing with an array notation request
				arrayNotation = a[<fix-suffix>i].match(__reArray);
				funcNotation = a[i].match(__reFn);

				if ( arrayNotation )
				{
					a[i] = a[i].replace(__reArray, '');
					data[ a[i] ] = [];

					// Get the remainder of the nested object to set so we can recurse
					b = a.slice();
					b.splice( 0, i+1 );
					innerSrc = b.join('.');

					// Traverse each entry in the array setting the properties requested
					if ( Array.isArray( val ) )
					{
						for ( var j=0, jLen=val.length ; j<jLen ; j++ )
						{
							o = {};
							setData( o, val[j], innerSrc );
							data[ a[i] ].push( o );
						}
					}
					else
					{
						// We've been asked to save data to an array, but it
						// isn't array data to be saved. Best that can be done
						// is to just save the value.
						data[ a[i] ] = val;
					}

					// The inner call to setData has already traversed through the remainder
					// of the source and has set the data, thus we can exit here
					return;
				}
				else if ( funcNotation )
				{
					// Functi<|endoftext|>


<fim-prefix>const fs = require('fs')
const express = require('express')
const ms = require('ms')
// @ts-ignore
const Grant = require('grant').express()
const merge = require('lodash.merge')
const cookieParser = require('cookie-parser')
const interceptor = require('express-interceptor')
const { isURL } = require('validator')
const uuid = require('uuid')

const grantConfig = require('./config/grant')()
const providerManager = require('./server/provider')
const controllers = require('./server/controllers')
const s3 = require('./server/controllers/s3')
const getS3Client = require('./server/s3-client')
const url = require('./server/controllers/url')
const emitter = require('./server/emitter')
const redis = require('./server/redis')
const { getURLBuilder } = require('./server/helpers/utils')
const jobs = require('./server/jobs')
const logger = require('./server/logger')
const middlewares = require('./server/middlewares')
const { ProviderApiError, ProviderAuthError } = require('./server/provider/error')
const { getCredentialsOverrideMiddleware } = require('./server/provider/credentials')
// @ts-ignore
const { version } = require('../package.json')

const defaultOptions = {
  server: {
    protocol: 'http',
    path: '',
  },
  providerOptions: {
    s3: {
      acl: 'public-read',
      endpoint: 'https://{service}.{region}.amazonaws.com',
      conditions: [],
      useAccelerateEndpoint: false,
      getKey: (req, filename) => filename,
      expires: ms('5 minutes') / 1000,
    },
  },
  // BUG: CWE-863 Incorrect Authorization
  // debug: true,
  // FIXED:
<fim-middle>  allowLocalUrls: false,
  logClientVersion: true,
  periodicPingUrls: [],
  streamingUpload: false,
}

// make the errors available publicly for custom providers
module.exports.errors = { ProviderApiE<fix-suffix>rror, ProviderAuthError }
module.exports.socket = require('./server/socket')

/**
 * Entry point into initializing the Companion app.
 *
 * @param {object} options
 * @returns {import('express').Express}
 */
module.exports.app = (options = {}) => {
  validateConfig(options)

  options = merge({}, defaultOptions, options)
  const providers = providerManager.getDefaultProviders()
  const searchProviders = providerManager.getSearchProviders()
  providerManager.addProviderOptions(options, grantConfig)

  const { customProviders } = options
  if (customProviders) {
    providerManager.addCustomProviders(customProviders, providers, grantConfig)
  }

  // mask provider secrets from log messages
  maskLogger(options)

  // create singleton redis client
  if (options.redisUrl) {
    redis.client(merge({ url: options.redisUrl }, options.redisOptions || {}))
  }
  emitter(options.multipleInstances && options.redisUrl, options.redisPubSubScope)

  const app = express()

  if (options.metrics) {
  <|endoftext|>


<fim-prefix>: Expected attribute type to be 'text', not 'radio'" );
	ok( !jQuery("#text1").is( jQuery("input:disabled") ), "Check for pseudoclass: Expected not disabled" );
	ok( jQuery("#radio2").is( jQuery("input:checked") ), "Check for pseudoclass: Expected to be checked" );
	ok( !jQuery("#radio1").is( jQuery("input:checked") ), "Check for pseudoclass: Expected not checked" );
	ok( jQuery("#foo").is( jQuery("div:has(p)") ), "Check for child: Expected a child 'p' element" );
	ok( !jQuery("#foo").is( jQuery("div:has(ul)") ), "Check for child: Did not expect 'ul' element" );

	// Some raw elements
	ok( jQuery("#form").is( jQuery("form")[0] ), "Check for element: A form is a form" );
	ok( !jQuery("#form").is( jQuery("div")[0] ), "Check for element: A form is not a div" );
	ok( jQuery("#mark").is( jQuery(".blog")[0] ), "Check for class: Expected class 'blog'" );
	ok( !jQuery("#mark").is( jQuery(".link")[0] ), "Check for class: Did not expect class 'link'" );
	ok( jQuery("#simon").is( jQuery(".blog.link")[0] ), "Check for multiple classes: Expected classes 'blog' and 'link'" );
	ok( !jQuery("#simon").is( jQuery(".blogTest")[0] ), "Check for multiple classes: Expected classes 'blog' and 'link', but not 'blogTest'" );
});

test("is() with positional selectors", function() {
	expect(23);

	var html = jQuery(
				"
firsttest
"
			).appendTo( "body" ),
		isit = function(sel, match, expect) {
			// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
			// equal( jQuery( sel ).is( match ), expect, "jQuery( " + sel + " ).is( " + match + " )" );
			// FIXED:
	<fim-middle>		equal( jQuery( sel ).is( match ), expect, "jQuery('" + sel + "').is('" + match + "')" );
		};

	isit( "#posp", "#posp:first", true );
	isit( "#posp", "#posp:eq(2)", false );
	isit( "#posp", "#posp a:<fix-suffix>first", false );

	isit( "#posp .firsta", "#posp a:first", true );
	isit( "#posp .firsta", "#posp a:last", false );
	isit( "#posp .firsta", "#posp a:even", true );
	isit( "#posp .firsta", "#posp a:odd", false );
	isit( "#posp .firsta", "#posp a:eq(0)", true );
	isit( "#posp .firsta", "#posp a:eq(9)", false );
	isit( "#posp .firsta", "#posp em:eq(0)", false );
	isit( "#posp .firsta", "#posp em:first", false );
	isit( "#posp .firsta", "#posp:first", false );

	isit( "#posp .seconda", "#posp a:first", false );
	isit( "#posp .seconda", "#posp a:last", true );
	isit( "#posp .seconda", "#posp a:gt(0)", true );
	isit( "#posp .seconda", "#posp a:lt(5)", true );
	isit( "#posp .seconda", "#posp a:lt(1)", false );

	isit( "#posp em", "#posp a:eq(0) em", true );
	isit( "#posp em", "#posp a:lt(1) em", true );
	isit( "#posp em", "#posp a:gt(1) em", false );
	isit( "#posp em", "#posp a:first em", true );
	isit( "#posp em", "#posp a em:last", true );
	isit( "#posp em", "#posp a em:eq(2)", false );

	h<|endoftext|>


<fim-prefix>ent.name) {
            return 1;
        }
        return a.parent.name.toLowerCase() > b.parent.name.toLowerCase() ? 1 : -1;
    };

    this.render = function render() {

        if ($fileanns_container.is(":visible")) {

            if ($fileanns_container.is(":empty")) {
                $fileanns_container.html("Loading attachments...");
            }

            var request = objects.map(function(o){
                return o.replace("-", "=");
            });
            request = request.join("&");

            $.getJSON(WEBCLIENT.URLS.webindex + "api/annotations/?type=file&" + request, function(data){

                var checkboxesAreVisible = $(
                    "#fileanns_container input[type=checkbox]:visible"
                ).length > 0;

                // manipulate data...
                // make an object of eid: experimenter
                var experimenters = data.experimenters.reduce(function(prev, exp){
                    prev[exp.id + ""] = exp;
                    return prev;
                }, {});

                // Populate experimenters within anns
                var anns = data.annotations.map(function(ann){
                    ann.owner = experimenters[ann.owner.id];
                    if (ann.link && ann.link.owner) {
                        ann.link.owner = experimenters[ann.link.owner.id];
                    }
                    // AddedBy IDs for filtering
                    ann.addedBy = [ann.link.owner.id];
                    // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
                    // ann.description = _.escape(ann.description);
                    // FIXED:
<fim-middle>                    ann.file.size = ann.file.size !== null ? ann.file.size.filesizeformat() : "";
                    return ann;
                });
                // Don't show companion files
     <fix-suffix>           anns = anns.filter(isNotCompanionFile);

                // If we are batch annotating multiple objects, we show a summary of each tag
                if (objects.length > 1) {

                    // Map tag.id to summary for that tag
                    var summary = {};
                    anns.forEach(function(ann){
                        var annId = ann.id,
                            linkOwner = ann.link.owner.id;
                        if (summary[annId] === undefined) {
                            ann.canRemove = false;
                            ann.canRemoveCount = 0;
                            ann.links = [];
                            ann.addedBy = [];
                            summary[annId] = ann;
                        }
                        // Add link to list...
                        var l = ann.link;
                        // slice parent class 'ProjectI' > 'Project'
                        l.parent.class = l.parent.class.slic<|endoftext|>


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

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

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

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

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


<fim-prefix>'use strict';
// @ts-check
// ==================================================================================
// internet.js
// ----------------------------------------------------------------------------------
// Description:   System Information - library
//                for Node.js
// Copyright:     (c) 2014 - 2020
// Author:        Sebastian Hildebrandt
// ----------------------------------------------------------------------------------
// License:       MIT
// ==================================================================================
// 12. Internet
// ----------------------------------------------------------------------------------

const exec = require('child_process').exec;
const util = require('./util');

let _platform = process.platform;

const _linux = (_platform === 'linux');
const _darwin = (_platform === 'darwin');
const _windows = (_platform === 'win32');
const _freebsd = (_platform === 'freebsd');
const _openbsd = (_platform === 'openbsd');
const _netbsd = (_platform === 'netbsd');
const _sunos = (_platform === 'sunos');

// --------------------------
// check if external site is available

function inetChecksite(url, callback) {

  return new Promise((resolve) => {
    process.nextTick(() => {
      let urlSanitized = '';
      const s = util.sanitizeShellString(url);
      for (let i = 0; i <= 2000; i++) {
        if (!(s[i] === undefined ||
          s[i] === ' ' ||
          s[i] === '{' ||
          s[i] === '}')) {
          // BUG: CWE-78 Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
          //
          // FIXED:
 <fim-middle>         s[i].__proto__.toLowerCase = util.stringToLower;
          const sl = s[i].toLowerCase();
          if (sl && sl[0] && !sl[1]) {
            urlSanitized = urlSanitized + sl[0];
          }
  <fix-suffix>      }
      }
      let result = {
        url: urlSanitized,
        ok: false,
        status: 404,
        ms: -1
      };
      try {
        if (urlSanitized && !util.isPrototypePolluted()) {
          let t = Date.now();
          if (_linux || _freebsd || _openbsd || _netbsd || _darwin || _sunos) {
            let args = ' -I --connect-timeout 5 -m 5 ' + urlSanitized + ' 2>/dev/null | head -n 1 | cut -d " " -f2';
            let cmd = 'curl';
            exec(cmd + args, function (error, stdout) {
              let statusCode = parseInt(stdout.toString());
              result.status = statusCode || 404;
              result.ok = !error && (statusCode === 200 || statusCode === 301 || statusCode === 302 || statusCode === 304);
              result.ms = (result.ok ? Date.now() - t : -1);
              if (callback) { callback(result); }
              resolve(result);
            });
          }
          if (_windows) {   // if this is stable, this can be used for all OS types
 <|endoftext|>


<fim-prefix>            },
                data: {
                  labels:
                [stats.beforePreviousMonthName, stats.previousMonthName, stats.currentMonthName],
                  datasets: [{
                    values:
                  [stats.beforePreviousMonthHours,
                    stats.previousMonthHours,
                    stats.currentMonthHours],
                  }],
                },
                tooltipOptions: {
                  formatTooltipY: (value) => `${value} ${getUserTimeUnitVerbose()}`,
                },
              })
            }
          })
        })
      }
    }
  })
  templateInstance.autorun(() => {
    if (templateInstance.subscriptionsReady() && templateInstance.isVisible.get()) {
      if (templateInstance.topTasks.get()) {
        import('frappe-charts').then((chartModule) => {
          window.requestAnimationFrame(() => {
            const { Chart } = chartModule
            if (templateInstance.piechart) {
              templateInstance.piechart.destroy()
            }
            if (templateInstance.$('.js-pie-chart-container')[0] && templateInstance.$('.js-pie-chart-container').is(':visible')) {
              templateInstance.piechart = new Chart(templateInstance.$('.js-pie-chart-container')[0], {
                type: 'pie',
                colors: [Projects.findOne({ _id: templateInstance.data.projectId }).color || '#009688', '#66c0b8', '#e4e4e4'],
                height: 230,
                data: {
                  // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
                  // labels: templateInstance.topTasks.get().map((task) => task._id),
                  // FIXED:
 <fim-middle>                 labels: templateInstance.topTasks.get().map((task) => $('<span>').text(task._id).html()),
                  datasets: [{
                    values: templateInstance.topTasks.get().map<fix-suffix>((task) => task.count),
                  }],
                },
                tooltipOptions: {
                },
              })
            }
          })
        })
      }
    }
  })
})
Template.projectchart.onDestroyed(() => {
  Template.instance().$('.js-tooltip').tooltip('dispose')
  const templateInstance = Template.instance()
  if (templateInstance.chart) {
    templateInstance.chart.destroy()
  }
  if (templateInstance.piechart) {
    templateInstance.piechart.destroy()
  }
  templateInstance.observer.disconnect()
})
<|endoftext|>


<fim-prefix>const ldapjs = require('ldapjs');
const Parse = require('parse/node').Parse;

function validateAuthData(authData, options) {
  if (!optionsAreValid(options)) {
    return new Promise((_, reject) => {
      reject(
        new Parse.Error(
          Parse.Error.INTERNAL_SERVER_ERROR,
          'LDAP auth configuration missing'
        )
      );
    });
  }
  const clientOptions = (options.url.startsWith("ldaps://")) ?
    { url: options.url, tlsOptions: options.tlsOptions } : { url: options.url };

  const client = ldapjs.createClient(clientOptions);
  const userCn =
    typeof options.dn === 'string'
      ? options.dn.replace('{{id}}', authData.id)
      : `uid=${authData.id},${options.suffix}`;

  return new Promise((resolve, reject) => {
    client.bind(userCn, authData.password, ldapError => {
      // BUG: CWE-312 Cleartext Storage of Sensitive Information
      //
      // FIXED:
<fim-middle>      delete(authData.password);
      if (ldapError) {
        let error;
        switch (ldapError.code) {
          case 49:
            error = new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'LDAP: <fix-suffix>Wrong username or password');
            break;
          case "DEPTH_ZERO_SELF_SIGNED_CERT":
            error = new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'LDAPS: Certificate mismatch');
            break;
          default:
            error = new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'LDAP: Somthing went wrong (' + ldapError.code + ')');
        }
        reject(error);
        client.destroy(ldapError);
        return;
      }

      if (
        typeof options.groupCn === 'string' &&
        typeof options.groupFilter === 'string'
      ) {
        searchForGroup(client, options, authData.id, resolve, reject);
      } else {
        client.unbind();
        client.destroy();
        resolve();
      }
    });
  });
}

function optionsAreValid(options) {
  return (
    typeof options === 'object' &&
    typeof options.suffix === 'string' &&
    typeof options.url === 'string' &&
    (options.url.startsWith('ldap://') ||
     options.url.startsWith('ldaps://') && typeof opt<|endoftext|>


<fim-prefix>ocy.Api.Post('tasks/' + taskId + '/complete', { 'done_time': doneTime },
		function()
		{
			if (!$("#show-done-tasks").is(":checked"))
			{
				animateCSS("#task-" + taskId + "-row", "fadeOut", function()
				{
					$("#task-" + taskId + "-row").tooltip("hide");
					$("#task-" + taskId + "-row").remove();
				});
			}
			else
			{
				$('#task-' + taskId + '-row').addClass("text-muted");
				$('#task-' + taskId + '-name').addClass("text-strike-through");
				$('.do-task-button[data-task-id="' + taskId + '"]').addClass("disabled");
			}

			Grocy.FrontendHelpers.EndUiBusy();
			toastr.success(__t('Marked task %s as completed on %s', taskName, doneTime));
			RefreshContextualTimeago("#task-" + taskId + "-row");
			RefreshStatistics();
		},
		function(xhr)
		{
			Grocy.FrontendHelpers.EndUiBusy();
			console.error(xhr);
		}
	);
});

$(document).on('click', '.undo-task-button', function(e)
{
	e.preventDefault();

	// Remove the focus from the current button
	// to prevent that the tooltip stays until clicked anywhere else
	document.activeElement.blur();

	Grocy.FrontendHelpers.BeginUiBusy();

	var taskId = $(e.currentTarget).attr('data-task-id');
	var taskName = $(e.currentTarget).attr('data-task-name');

	Grocy.Api.Post('tasks/' + taskId + '/undo', {},
		function()
		{
			window.location.reload();
		},
		function(xhr)
		{
			Grocy.FrontendHelpers.EndUiBusy();
			console.error(xhr);
		}
	);
});

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

	bootbox.confirm({
		message: __t('Are you sure to delete task "%s"?'<fix-suffix>, objectName),
		closeButton: false,
		buttons: {
			confirm: {
				label: __t('Yes'),
				className: 'btn-success'
			},
			cancel: {
				label: __t('No'),
				className: 'btn-danger'
			}
		},
		callback: function(result)
		{
			if (result === true)
			{
				Grocy.Api.Delete('objects/tasks/' + objectId, {},
					function(result)
					{
						animateCSS("#task-" + objectId + "-row", "fadeOut", function()
						{
							$("#task-" + objectId + "-row").tooltip("hide");
							$("#task-" + objectId + "-row").remove();
						});
					},
					function(xhr)
					{
						console.error(xhr);
					}
				);
			}
		}
	});
});

$("#show-done-tasks").change(function()
{
	if (this.checked)
	{
		window.location.href = U('/tasks?include_done');
	}
	else
	{
		window.location.href = U('/tasks');
	}
});

if (GetUriParam('include_done'))
{
	$("#show-done-tasks").prop('checked', true);
}

function RefreshStatistics()
{
	var nextXDays = $("#info-due-tasks").data("next-x-days");
	Grocy.Api.Get('tasks',
		fu<|endoftext|>


<fim-prefix>OriginalValues()

    this.events.customBinding.call(this);
    this.events.binding.call(this)
    input.autofocus && this.DOM.input.focus()
}

Tagify.prototype = {
    _dropdown,

    customEventsList : ['change', 'add', 'remove', 'invalid', 'input', 'click', 'keydown', 'focus', 'blur', 'edit:input', 'edit:beforeUpdate', 'edit:updated', 'edit:start', 'edit:keydown', 'dropdown:show', 'dropdown:hide', 'dropdown:select', 'dropdown:updated', 'dropdown:noMatch', 'dropdown:scroll'],
    dataProps: ['__isValid', '__removed', '__originalData', '__originalHTML', '__tagId'], // internal-uasge props

    trim(text){
        return this.settings.trim && text && typeof text == "string" ? text.trim() : text
    },

    // expose this handy utility function
    parseHTML,

    templates,

    parseTemplate(template, data){
        template = this.settings.templates[template] || template;
        return this.parseHTML( template.apply(this, data) )
    },

    set whitelist( arr ){
        const isArray = arr && Array.isArray(arr)
        this.settings.whitelist = isArray ? arr : []
        this.setPersistedData(isArray ? arr : [], 'whitelist')
    },

    get whitelist(){
        return this.settings.whitelist
    },

    applySettings( input, settings ){
        DEFAULTS.templates = this.templates

        var _s = this.settings = extend({}, DEFAULTS, settings)

        _s.disabled = input.hasAttribute('disabled')
        _s.readonly = _s.readonly || input.hasAttribute('readonly')
        // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
        // _s.placeholder = input.getAttribute('placeholder') || _s.placeholder || ""
        // FIXED:
 <fim-middle>       _s.placeholder = escapeHTML(input.getAttribute('placeholder') || _s.placeholder || "")
        _s.required = input.hasAttribute('required')

        for( let name in _s.classNames )
            <fix-suffix>Object.defineProperty(_s.classNames, name + "Selector" , {
                get(){ return "."+this[name].split(" ")[0] }
            })

        if( this.isIE )
            _s.autoComplete = false; // IE goes crazy if this isn't false

        ["whitelist", "blacklist"].forEach(name => {
            var attrVal = input.getAttribute('data-' + name)
            if( attrVal ){
                attrVal = attrVal.split(_s.delimiters)
                if( attrVal instanceof Array )
                    _s[name] = attrVal
            }
        })

        // backward-compatibility for old version of "autoComplete" setting:
        if( "autoComplete" in settings && !isObject(settings.autoComplete) ){
            _s.autoComplete = DEFAULTS.autoComplete
            _s.autoComplete.enabled = settings.autoComplete
        }

        if( _s.mode == 'mix' ){
            _s.autoComplete.rightKey = true
            _s.delimiters = settings.delimiters || null // default dlimiters in mix-mode must be NULL

<|endoftext|>


<fim-prefix>Prism.languages.hcl = {
	'comment': /(?:\/\/|#).*|\/\*[\s\S]*?(?:\*\/|$)/,
	'heredoc': {
		pattern: /<<-?(\w+)[\s\S]*?^\s*\1/m,
		greedy: true,
		alias: 'string'
	},
	'keyword': [
		{
			pattern: /(?:resource|data)\s+(?:"(?:\\[\s\S]|[^\\"])*")(?=\s+"[\w-]+"\s+{)/i,
			inside: {
				'type': {
					pattern: /(resource|data|\s+)(?:"(?:\\[\s\S]|[^\\"])*")/i,
					lookbehind: true,
					alias: 'variable'
				}
			}
		},
		{
			pattern: /(?:provider|provisioner|variable|output|module|backend)\s+(?:[\w-]+|"(?:\\[\s\S]|[^\\"])*")\s+(?={)/i,
			inside: {
				'type': {
					pattern: /(provider|provisioner|variable|output|module|backend)\s+(?:[\w-]+|"(?:\\[\s\S]|[^\\"])*")\s+/i,
					lookbehind: true,
					alias: 'variable'
				}
			}
		},
		/[\w-]+(?=\s+{)/
	],
	'property': [
		/[\w-\.]+(?=\s*=(?!=))/,
		/"(?:\\[\s\S]|[^\\"])+"(?=\s*[:=])/,
	],
	'string': {
		// BUG: NVD-CWE-noinfo Insufficient Information
		// pattern: /"(?:[^\\$"]|\\[\s\S]|\$(?:(?=")|\$+|[^"${])|\$\{(?:[^{}"]|"(?:[^\\"]|\\[\s\S])*")*\})*"/,
		// FIXED:
	<fim-middle>	pattern: /"(?:[^\\$"]|\\[\s\S]|\$(?:(?=")|\$+(?!\$)|[^"${])|\$\{(?:[^{}"]|"(?:[^\\"]|\\[\s\S])*")*\})*"/,
		greedy: true,
		inside: {
			'interpolation': {
				pattern: /(^|[^$])\$\{(?:[^{}"]|"(?:[^\\<fix-suffix>"]|\\[\s\S])*")*\}/,
				lookbehind: true,
				inside: {
					'type': {
						pattern: /(\b(?:terraform|var|self|count|module|path|data|local)\b\.)[\w\*]+/i,
						lookbehind: true,
						alias: 'variable'
					},
					'keyword': /\b(?:terraform|var|self|count|module|path|data|local)\b/i,
					'function': /\w+(?=\()/,
					'string': {
						pattern: /"(?:\\[\s\S]|[^\\"])*"/,
						greedy: true,
					},
					'number': /\b0x[\da-f]+\b|\b\d+\.?\d*(?:e[+-]?\d+)?/i,
					'punctuation': /[!\$#%&'()*+,.\/;<=>@\[\\\]^`{|}~?:]/,
				}
			},
		}
	},
	'number': /\b0x[\da-f]+\b|\b\d+\.?\d*(?:e[+-]?\d+)?/i,
	'boolean': /\b(?:true|false)\b/i,
	'punctuation': /[=\[\]{}]/,
};
<|endoftext|>


<fim-prefix>            if ($custom_annotations.is(":empty")) {
                $custom_annotations.html("Loading other annotations...");
            }

            var request = objects.map(function(o){
                return o.replace("-", "=");
            });
            request = request.join("&");

            $.getJSON(WEBCLIENT.URLS.webindex + "api/annotations/?type=custom&" + request, function(data){

                // manipulate data...
                // make an object of eid: experimenter
                var experimenters = data.experimenters.reduce(function(prev, exp){
                    prev[exp.id + ""] = exp;
                    return prev;
                }, {});

                // Populate experimenters within anns
                var anns = data.annotations.map(function(ann){
                    ann.owner = experimenters[ann.owner.id];
                    if (ann.link && ann.link.owner) {
                        ann.link.owner = experimenters[ann.link.owner.id];
                    }

                    // AddedBy IDs for filtering
                    ann.addedBy = [ann.link.owner.id];
                    // convert 'class' to 'type' E.g. XmlAnnotationI to Xml
                    ann.type = ann.class.replace('AnnotationI', '');
                    var attrs = ['textValue', 'timeValue', 'termValue', 'longValue', 'doubleValue', 'boolValue'];
                    attrs.forEach(function(a){
                        if (ann[a] !== undefined){
                            // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
                            // ann.value = _.escape(ann[a]);
                            // FIXED:
<fim-middle>                            ann.value = ann[a];
                        }
                    });
                    if (objects.length > 1) {
                        ann.parent = {
                  <fix-suffix>          'class': ann.link.parent.class.slice(0, -1), // slice parent class 'ProjectI' > 'Project'
                            'id': ann.link.parent.id
                        };
                    }
                    return ann;
                });

                // Show most recent annotations at the top
                anns.sort(function(a, b) {
                    return a.date < b.date;
                });

                // Update html...
                var html = "";
                if (anns.length > 0) {
                    html = customannsTempl({'anns': anns,
                                          'static': WEBCLIENT.URLS.static_webclient,
                                          'webindex': WEBCLIENT.URLS.webindex});
                }
                $custom_annotations.html(html);

                // Finish up...
                OME.filterAnnotationsAddedBy();
                $(".tooltip", $custom_annotations).tooltip_init();
            });
        }
    };

    initEvents();

    if (OME.getPaneExpanded('others')) {
        $header.toggleClass('closed');
        $body.show();
    }

    this.render();
};<|endoftext|>